GUIElements.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File Modified (major mod): Marius Adrian Stanciu #
  10. # Date: 3/10/2019 #
  11. # ##########################################################
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, pyqtSlot, QSettings
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QKeySequence, QTextCursor
  16. from copy import copy
  17. import re
  18. import logging
  19. import html
  20. log = logging.getLogger('base')
  21. EDIT_SIZE_HINT = 70
  22. class RadioSet(QtWidgets.QWidget):
  23. activated_custom = QtCore.pyqtSignal(str)
  24. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  25. """
  26. The choices are specified as a list of dictionaries containing:
  27. * 'label': Shown in the UI
  28. * 'value': The value returned is selected
  29. :param choices: List of choices. See description.
  30. :param orientation: 'horizontal' (default) of 'vertical'.
  31. :param parent: Qt parent widget.
  32. :type choices: list
  33. """
  34. super(RadioSet, self).__init__(parent)
  35. self.choices = copy(choices)
  36. if orientation == 'horizontal':
  37. layout = QtWidgets.QHBoxLayout()
  38. else:
  39. layout = QtWidgets.QVBoxLayout()
  40. group = QtWidgets.QButtonGroup(self)
  41. for choice in self.choices:
  42. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  43. group.addButton(choice['radio'])
  44. layout.addWidget(choice['radio'], stretch=0)
  45. choice['radio'].toggled.connect(self.on_toggle)
  46. layout.setContentsMargins(0, 0, 0, 0)
  47. if stretch is False:
  48. pass
  49. else:
  50. layout.addStretch()
  51. self.setLayout(layout)
  52. self.group_toggle_fn = lambda: None
  53. def on_toggle(self):
  54. # log.debug("Radio toggled")
  55. radio = self.sender()
  56. if radio.isChecked():
  57. self.group_toggle_fn()
  58. ret_val = str(self.get_value())
  59. self.activated_custom.emit(ret_val)
  60. return
  61. def get_value(self):
  62. for choice in self.choices:
  63. if choice['radio'].isChecked():
  64. return choice['value']
  65. log.error("No button was toggled in RadioSet.")
  66. return None
  67. def set_value(self, val):
  68. for choice in self.choices:
  69. if choice['value'] == val:
  70. choice['radio'].setChecked(True)
  71. return
  72. log.error("Value given is not part of this RadioSet: %s" % str(val))
  73. # class RadioGroupChoice(QtWidgets.QWidget):
  74. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  75. # """
  76. # The choices are specified as a list of dictionaries containing:
  77. #
  78. # * 'label': Shown in the UI
  79. # * 'value': The value returned is selected
  80. #
  81. # :param choices: List of choices. See description.
  82. # :param orientation: 'horizontal' (default) of 'vertical'.
  83. # :param parent: Qt parent widget.
  84. # :type choices: list
  85. # """
  86. # super().__init__(parent)
  87. #
  88. # group = QtGui.QButtonGroup(self)
  89. #
  90. # self.lbl1 = label_1
  91. # self.lbl2 = label_2
  92. # self.hide_list = hide_list
  93. # self.show_list = show_list
  94. #
  95. # self.btn1 = QtGui.QRadioButton(str(label_1))
  96. # self.btn2 = QtGui.QRadioButton(str(label_2))
  97. # group.addButton(self.btn1)
  98. # group.addButton(self.btn2)
  99. #
  100. # if to_check == 1:
  101. # self.btn1.setChecked(True)
  102. # else:
  103. # self.btn2.setChecked(True)
  104. #
  105. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  106. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  107. #
  108. # def btn_state(self, btn):
  109. # if btn.text() == self.lbl1:
  110. # if btn.isChecked() is True:
  111. # self.show_widgets(self.show_list)
  112. # self.hide_widgets(self.hide_list)
  113. # else:
  114. # self.show_widgets(self.hide_list)
  115. # self.hide_widgets(self.show_list)
  116. #
  117. # def hide_widgets(self, lst):
  118. # for wgt in lst:
  119. # wgt.hide()
  120. #
  121. # def show_widgets(self, lst):
  122. # for wgt in lst:
  123. # wgt.show()
  124. class LengthEntry(QtWidgets.QLineEdit):
  125. def __init__(self, output_units='IN', parent=None):
  126. super(LengthEntry, self).__init__(parent)
  127. self.output_units = output_units
  128. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  129. # Unit conversion table OUTPUT-INPUT
  130. self.scales = {
  131. 'IN': {'IN': 1.0,
  132. 'MM': 1/25.4},
  133. 'MM': {'IN': 25.4,
  134. 'MM': 1.0}
  135. }
  136. self.readyToEdit = True
  137. self.editingFinished.connect(self.on_edit_finished)
  138. def on_edit_finished(self):
  139. self.clearFocus()
  140. def mousePressEvent(self, e, Parent=None):
  141. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  142. if self.readyToEdit:
  143. self.selectAll()
  144. self.readyToEdit = False
  145. def focusOutEvent(self, e):
  146. # don't focus out if the user requests an popup menu
  147. if e.reason() != QtCore.Qt.PopupFocusReason:
  148. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  149. self.deselect()
  150. self.readyToEdit = True
  151. def returnPressed(self, *args, **kwargs):
  152. val = self.get_value()
  153. if val is not None:
  154. self.set_text(str(val))
  155. else:
  156. log.warning("Could not interpret entry: %s" % self.get_text())
  157. def get_value(self):
  158. raw = str(self.text()).strip(' ')
  159. # match = self.format_re.search(raw)
  160. try:
  161. units = raw[-2:]
  162. units = self.scales[self.output_units][units.upper()]
  163. value = raw[:-2]
  164. return float(eval(value))* units
  165. except IndexError:
  166. value = raw
  167. return float(eval(value))
  168. except KeyError:
  169. value = raw
  170. return float(eval(value))
  171. except Exception:
  172. log.warning("Could not parse value in entry: %s" % str(raw))
  173. return None
  174. def set_value(self, val):
  175. self.setText(str('%.4f' % val))
  176. def sizeHint(self):
  177. default_hint_size = super(LengthEntry, self).sizeHint()
  178. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  179. class FloatEntry(QtWidgets.QLineEdit):
  180. def __init__(self, parent=None):
  181. super(FloatEntry, self).__init__(parent)
  182. self.readyToEdit = True
  183. self.editingFinished.connect(self.on_edit_finished)
  184. def on_edit_finished(self):
  185. self.clearFocus()
  186. def mousePressEvent(self, e, Parent=None):
  187. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  188. if self.readyToEdit == True:
  189. self.selectAll()
  190. self.readyToEdit = False
  191. def focusOutEvent(self, e):
  192. # don't focus out if the user requests an popup menu
  193. if e.reason() != QtCore.Qt.PopupFocusReason:
  194. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  195. self.deselect()
  196. self.readyToEdit = True
  197. def returnPressed(self, *args, **kwargs):
  198. val = self.get_value()
  199. if val is not None:
  200. self.set_text(str(val))
  201. else:
  202. log.warning("Could not interpret entry: %s" % self.text())
  203. def get_value(self):
  204. raw = str(self.text()).strip(' ')
  205. try:
  206. evaled = eval(raw)
  207. return float(evaled)
  208. except Exception as e:
  209. if raw is not '':
  210. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  211. return None
  212. def set_value(self, val):
  213. if val is not None:
  214. self.setText("%.4f" % float(val))
  215. else:
  216. self.setText("")
  217. def sizeHint(self):
  218. default_hint_size = super(FloatEntry, self).sizeHint()
  219. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  220. class FloatEntry2(QtWidgets.QLineEdit):
  221. def __init__(self, parent=None):
  222. super(FloatEntry2, self).__init__(parent)
  223. self.readyToEdit = True
  224. self.editingFinished.connect(self.on_edit_finished)
  225. def on_edit_finished(self):
  226. self.clearFocus()
  227. def mousePressEvent(self, e, Parent=None):
  228. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  229. if self.readyToEdit:
  230. self.selectAll()
  231. self.readyToEdit = False
  232. def focusOutEvent(self, e):
  233. # don't focus out if the user requests an popup menu
  234. if e.reason() != QtCore.Qt.PopupFocusReason:
  235. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  236. self.deselect()
  237. self.readyToEdit = True
  238. def get_value(self):
  239. raw = str(self.text()).strip(' ')
  240. try:
  241. evaled = eval(raw)
  242. return float(evaled)
  243. except Exception as e:
  244. if raw is not '':
  245. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  246. return None
  247. def set_value(self, val):
  248. self.setText("%.4f" % val)
  249. def sizeHint(self):
  250. default_hint_size = super(FloatEntry2, self).sizeHint()
  251. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  252. class IntEntry(QtWidgets.QLineEdit):
  253. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  254. super(IntEntry, self).__init__(parent)
  255. self.allow_empty = allow_empty
  256. self.empty_val = empty_val
  257. self.readyToEdit = True
  258. self.editingFinished.connect(self.on_edit_finished)
  259. def on_edit_finished(self):
  260. self.clearFocus()
  261. def mousePressEvent(self, e, Parent=None):
  262. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  263. if self.readyToEdit:
  264. self.selectAll()
  265. self.readyToEdit = False
  266. def focusOutEvent(self, e):
  267. # don't focus out if the user requests an popup menu
  268. if e.reason() != QtCore.Qt.PopupFocusReason:
  269. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  270. self.deselect()
  271. self.readyToEdit = True
  272. def get_value(self):
  273. if self.allow_empty:
  274. if str(self.text()) == "":
  275. return self.empty_val
  276. # make the text() first a float and then int because if text is a float type,
  277. # the int() can't convert directly a "text float" into a int type.
  278. ret_val = float(self.text())
  279. ret_val = int(ret_val)
  280. return ret_val
  281. def set_value(self, val):
  282. if val == self.empty_val and self.allow_empty:
  283. self.setText("")
  284. return
  285. self.setText(str(val))
  286. def sizeHint(self):
  287. default_hint_size = super(IntEntry, self).sizeHint()
  288. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  289. class FCEntry(QtWidgets.QLineEdit):
  290. def __init__(self, decimals=None, parent=None):
  291. super(FCEntry, self).__init__(parent)
  292. self.readyToEdit = True
  293. self.editingFinished.connect(self.on_edit_finished)
  294. self.decimals = decimals if decimals is not None else 4
  295. def on_edit_finished(self):
  296. self.clearFocus()
  297. def mousePressEvent(self, e, parent=None):
  298. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  299. if self.readyToEdit:
  300. self.selectAll()
  301. self.readyToEdit = False
  302. def focusOutEvent(self, e):
  303. if e.reason() != QtCore.Qt.PopupFocusReason:
  304. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  305. self.deselect()
  306. self.readyToEdit = True
  307. def get_value(self):
  308. return str(self.text())
  309. def set_value(self, val, decimals=None):
  310. decimal_digits = decimals if decimals is not None else self.decimals
  311. if type(val) is float:
  312. self.setText('%.*f' % (decimal_digits, val))
  313. else:
  314. self.setText(str(val))
  315. def sizeHint(self):
  316. default_hint_size = super(FCEntry, self).sizeHint()
  317. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  318. class FCEntry2(FCEntry):
  319. def __init__(self, parent=None):
  320. super(FCEntry2, self).__init__(parent)
  321. def set_value(self, val, decimals=4):
  322. try:
  323. fval = float(val)
  324. except ValueError:
  325. return
  326. self.setText('%.*f' % (decimals, fval))
  327. class FCEntry3(FCEntry):
  328. def __init__(self, parent=None):
  329. super(FCEntry3, self).__init__(parent)
  330. def set_value(self, val, decimals=4):
  331. try:
  332. fval = float(val)
  333. except ValueError:
  334. return
  335. self.setText('%.*f' % (decimals, fval))
  336. def get_value(self):
  337. value = str(self.text()).strip(' ')
  338. try:
  339. return float(eval(value))
  340. except Exception as e:
  341. log.warning("Could not parse value in entry: %s" % str(e))
  342. return None
  343. class EvalEntry(QtWidgets.QLineEdit):
  344. def __init__(self, parent=None):
  345. super(EvalEntry, self).__init__(parent)
  346. self.readyToEdit = True
  347. self.editingFinished.connect(self.on_edit_finished)
  348. def on_edit_finished(self):
  349. self.clearFocus()
  350. def mousePressEvent(self, e, parent=None):
  351. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  352. if self.readyToEdit:
  353. self.selectAll()
  354. self.readyToEdit = False
  355. def focusOutEvent(self, e):
  356. if e.reason() != QtCore.Qt.PopupFocusReason:
  357. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  358. self.deselect()
  359. self.readyToEdit = True
  360. def returnPressed(self, *args, **kwargs):
  361. val = self.get_value()
  362. if val is not None:
  363. self.setText(str(val))
  364. else:
  365. log.warning("Could not interpret entry: %s" % self.get_text())
  366. def get_value(self):
  367. raw = str(self.text()).strip(' ')
  368. evaled = 0.0
  369. try:
  370. evaled = eval(raw)
  371. except Exception as e:
  372. if raw is not '':
  373. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  374. return None
  375. return evaled
  376. def set_value(self, val):
  377. self.setText(str(val))
  378. def sizeHint(self):
  379. default_hint_size = super(EvalEntry, self).sizeHint()
  380. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  381. class EvalEntry2(QtWidgets.QLineEdit):
  382. def __init__(self, parent=None):
  383. super(EvalEntry2, self).__init__(parent)
  384. self.readyToEdit = True
  385. self.editingFinished.connect(self.on_edit_finished)
  386. def on_edit_finished(self):
  387. self.clearFocus()
  388. def mousePressEvent(self, e, parent=None):
  389. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  390. if self.readyToEdit:
  391. self.selectAll()
  392. self.readyToEdit = False
  393. def focusOutEvent(self, e):
  394. if e.reason() != QtCore.Qt.PopupFocusReason:
  395. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  396. self.deselect()
  397. self.readyToEdit = True
  398. def get_value(self):
  399. raw = str(self.text()).strip(' ')
  400. evaled = 0.0
  401. try:
  402. evaled = eval(raw)
  403. except Exception as e:
  404. if raw is not '':
  405. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  406. return None
  407. return evaled
  408. def set_value(self, val):
  409. self.setText(str(val))
  410. def sizeHint(self):
  411. default_hint_size = super(EvalEntry2, self).sizeHint()
  412. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  413. class FCSpinner(QtWidgets.QSpinBox):
  414. returnPressed = QtCore.pyqtSignal()
  415. def __init__(self, suffix=None, parent=None):
  416. super(FCSpinner, self).__init__(parent)
  417. self.readyToEdit = True
  418. self.editingFinished.connect(self.on_edit_finished)
  419. self.lineEdit().installEventFilter(self)
  420. if suffix:
  421. self.setSuffix(' %s' % str(suffix))
  422. self.prev_readyToEdit = True
  423. def eventFilter(self, object, event):
  424. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  425. self.prev_readyToEdit = False
  426. if self.isEnabled():
  427. if self.readyToEdit:
  428. self.lineEdit().selectAll()
  429. self.readyToEdit = False
  430. else:
  431. self.lineEdit().deselect()
  432. return True
  433. return False
  434. def keyPressEvent(self, event):
  435. if event.key() == Qt.Key_Enter:
  436. self.returnPressed.emit()
  437. self.clearFocus()
  438. else:
  439. super().keyPressEvent(event)
  440. def wheelEvent(self, *args, **kwargs):
  441. # should work only there is a focus in the lineedit of the SpinBox
  442. if self.readyToEdit is False:
  443. super().wheelEvent(*args, **kwargs)
  444. def on_edit_finished(self):
  445. self.clearFocus()
  446. self.returnPressed.emit()
  447. # def mousePressEvent(self, e, parent=None):
  448. # super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  449. # if self.readyToEdit:
  450. # self.lineEdit().selectAll()
  451. # self.readyToEdit = False
  452. def focusOutEvent(self, e):
  453. # don't focus out if the user requests an popup menu
  454. if e.reason() != QtCore.Qt.PopupFocusReason:
  455. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  456. self.lineEdit().deselect()
  457. self.readyToEdit = True
  458. def get_value(self):
  459. return int(self.value())
  460. def set_value(self, val):
  461. try:
  462. k = int(val)
  463. except Exception as e:
  464. log.debug(str(e))
  465. return
  466. self.setValue(k)
  467. def set_range(self, min_val, max_val):
  468. self.setRange(min_val, max_val)
  469. # def sizeHint(self):
  470. # default_hint_size = super(FCSpinner, self).sizeHint()
  471. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  472. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  473. returnPressed = QtCore.pyqtSignal()
  474. def __init__(self, suffix=None, parent=None):
  475. super(FCDoubleSpinner, self).__init__(parent)
  476. self.readyToEdit = True
  477. self.editingFinished.connect(self.on_edit_finished)
  478. self.lineEdit().installEventFilter(self)
  479. # by default don't allow the minus sign to be entered as the default for QDoubleSpinBox is the positive range
  480. # between 0.00 and 99.00 (2 decimals)
  481. self.lineEdit().setValidator(
  482. QtGui.QRegExpValidator(QtCore.QRegExp("[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  483. if suffix:
  484. self.setSuffix(' %s' % str(suffix))
  485. self.prev_readyToEdit = True
  486. def on_edit_finished(self):
  487. self.clearFocus()
  488. self.returnPressed.emit()
  489. def eventFilter(self, object, event):
  490. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  491. self.prev_readyToEdit = False
  492. if self.isEnabled():
  493. if self.readyToEdit:
  494. self.cursor_pos = self.lineEdit().cursorPosition()
  495. self.lineEdit().selectAll()
  496. self.readyToEdit = False
  497. else:
  498. self.lineEdit().deselect()
  499. return True
  500. return False
  501. def keyPressEvent(self, event):
  502. if event.key() == Qt.Key_Enter:
  503. self.returnPressed.emit()
  504. self.clearFocus()
  505. else:
  506. super().keyPressEvent(event)
  507. def wheelEvent(self, *args, **kwargs):
  508. # should work only there is a focus in the lineedit of the SpinBox
  509. if self.readyToEdit is False:
  510. super().wheelEvent(*args, **kwargs)
  511. def focusOutEvent(self, e):
  512. # don't focus out if the user requests an popup menu
  513. if e.reason() != QtCore.Qt.PopupFocusReason:
  514. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  515. self.lineEdit().deselect()
  516. self.readyToEdit = True
  517. self.prev_readyToEdit = True
  518. def valueFromText(self, p_str):
  519. text = p_str.replace(',', '.')
  520. try:
  521. ret_val = float(text)
  522. except ValueError:
  523. ret_val = 0.0
  524. return ret_val
  525. def validate(self, p_str, p_int):
  526. text = p_str.replace(',', '.')
  527. try:
  528. if float(text) < self.minimum() or float(text) > self.maximum():
  529. return QtGui.QValidator.Intermediate, text, p_int
  530. except ValueError:
  531. pass
  532. return QtGui.QValidator.Acceptable, p_str, p_int
  533. def get_value(self):
  534. return float(self.value())
  535. def set_value(self, val):
  536. try:
  537. k = float(val)
  538. except Exception as e:
  539. log.debug(str(e))
  540. return
  541. self.setValue(k)
  542. def set_precision(self, val):
  543. self.setDecimals(val)
  544. # make sure that the user can't type more decimals than the set precision
  545. if self.minimum() < 0 or self.maximum() < 0:
  546. self.lineEdit().setValidator(
  547. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  548. else:
  549. self.lineEdit().setValidator(
  550. QtGui.QRegExpValidator(QtCore.QRegExp("[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  551. def set_range(self, min_val, max_val):
  552. if min_val < 0 or max_val < 0:
  553. self.lineEdit().setValidator(
  554. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  555. self.setRange(min_val, max_val)
  556. class FCCheckBox(QtWidgets.QCheckBox):
  557. def __init__(self, label='', parent=None):
  558. super(FCCheckBox, self).__init__(str(label), parent)
  559. def get_value(self):
  560. return self.isChecked()
  561. def set_value(self, val):
  562. self.setChecked(val)
  563. def toggle(self):
  564. self.set_value(not self.get_value())
  565. class FCTextArea(QtWidgets.QPlainTextEdit):
  566. def __init__(self, parent=None):
  567. super(FCTextArea, self).__init__(parent)
  568. def set_value(self, val):
  569. self.setPlainText(val)
  570. def get_value(self):
  571. return str(self.toPlainText())
  572. def sizeHint(self, custom_sizehint=None):
  573. default_hint_size = super(FCTextArea, self).sizeHint()
  574. if custom_sizehint is None:
  575. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  576. else:
  577. return QtCore.QSize(custom_sizehint, default_hint_size.height())
  578. class FCTextAreaRich(QtWidgets.QTextEdit):
  579. def __init__(self, parent=None):
  580. super(FCTextAreaRich, self).__init__(parent)
  581. def set_value(self, val):
  582. self.setText(val)
  583. def get_value(self):
  584. return str(self.toPlainText())
  585. def sizeHint(self):
  586. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  587. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  588. class FCTextAreaExtended(QtWidgets.QTextEdit):
  589. def __init__(self, parent=None):
  590. super().__init__(parent)
  591. self.completer = MyCompleter()
  592. self.model = QtCore.QStringListModel()
  593. self.completer.setModel(self.model)
  594. self.set_model_data(keyword_list=[])
  595. self.completer.insertText.connect(self.insertCompletion)
  596. self.completer_enable = False
  597. def set_model_data(self, keyword_list):
  598. self.model.setStringList(keyword_list)
  599. def insertCompletion(self, completion):
  600. tc = self.textCursor()
  601. extra = (len(completion) - len(self.completer.completionPrefix()))
  602. # don't insert if the word is finished but add a space instead
  603. if extra == 0:
  604. tc.insertText(' ')
  605. self.completer.popup().hide()
  606. return
  607. tc.movePosition(QTextCursor.Left)
  608. tc.movePosition(QTextCursor.EndOfWord)
  609. tc.insertText(completion[-extra:])
  610. # add a space after inserting the word
  611. tc.insertText(' ')
  612. self.setTextCursor(tc)
  613. self.completer.popup().hide()
  614. def focusInEvent(self, event):
  615. if self.completer:
  616. self.completer.setWidget(self)
  617. QTextEdit.focusInEvent(self, event)
  618. def set_value(self, val):
  619. self.setText(val)
  620. def get_value(self):
  621. self.toPlainText()
  622. def insertFromMimeData(self, data):
  623. """
  624. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  625. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  626. :param data:
  627. :return:
  628. """
  629. modifier = QtWidgets.QApplication.keyboardModifiers()
  630. if modifier == Qt.ShiftModifier:
  631. text = data.text()
  632. text = text.replace('\\', '/')
  633. self.insertPlainText(text)
  634. else:
  635. self.insertPlainText(data.text())
  636. def keyPressEvent(self, event):
  637. """
  638. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  639. :param event:
  640. :return:
  641. """
  642. key = event.key()
  643. modifier = QtWidgets.QApplication.keyboardModifiers()
  644. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  645. if key == QtCore.Qt.Key_V:
  646. clipboard = QtWidgets.QApplication.clipboard()
  647. clip_text = clipboard.text()
  648. clip_text = clip_text.replace('\\', '/')
  649. self.insertPlainText(clip_text)
  650. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  651. self.comment()
  652. tc = self.textCursor()
  653. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  654. self.completer.insertText.emit(self.completer.getSelected())
  655. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  656. return
  657. elif key == Qt.Key_BraceLeft:
  658. tc.insertText('{}')
  659. self.moveCursor(QtGui.QTextCursor.Left)
  660. elif key == Qt.Key_BracketLeft:
  661. tc.insertText('[]')
  662. self.moveCursor(QtGui.QTextCursor.Left)
  663. elif key == Qt.Key_ParenLeft:
  664. tc.insertText('()')
  665. self.moveCursor(QtGui.QTextCursor.Left)
  666. elif key == Qt.Key_BraceRight:
  667. tc.select(QtGui.QTextCursor.WordUnderCursor)
  668. if tc.selectedText() == '}':
  669. tc.movePosition(QTextCursor.Right)
  670. self.setTextCursor(tc)
  671. else:
  672. tc.clearSelection()
  673. self.textCursor().insertText('}')
  674. elif key == Qt.Key_BracketRight:
  675. tc.select(QtGui.QTextCursor.WordUnderCursor)
  676. if tc.selectedText() == ']':
  677. tc.movePosition(QTextCursor.Right)
  678. self.setTextCursor(tc)
  679. else:
  680. tc.clearSelection()
  681. self.textCursor().insertText(']')
  682. elif key == Qt.Key_ParenRight:
  683. tc.select(QtGui.QTextCursor.WordUnderCursor)
  684. if tc.selectedText() == ')':
  685. tc.movePosition(QTextCursor.Right)
  686. self.setTextCursor(tc)
  687. else:
  688. tc.clearSelection()
  689. self.textCursor().insertText(')')
  690. else:
  691. super(FCTextAreaExtended, self).keyPressEvent(event)
  692. if self.completer_enable:
  693. tc.select(QTextCursor.WordUnderCursor)
  694. cr = self.cursorRect()
  695. if len(tc.selectedText()) > 0:
  696. self.completer.setCompletionPrefix(tc.selectedText())
  697. popup = self.completer.popup()
  698. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  699. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  700. + self.completer.popup().verticalScrollBar().sizeHint().width())
  701. self.completer.complete(cr)
  702. else:
  703. self.completer.popup().hide()
  704. def comment(self):
  705. """
  706. Got it from here:
  707. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  708. :return:
  709. """
  710. pos = self.textCursor().position()
  711. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  712. line_text = self.textCursor().block().text()
  713. if self.textCursor().block().text().startswith(" "):
  714. # skip the white space
  715. self.moveCursor(QtGui.QTextCursor.NextWord)
  716. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  717. character = self.textCursor().selectedText()
  718. if character == "#":
  719. # delete #
  720. self.textCursor().deletePreviousChar()
  721. # delete white space
  722. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  723. self.textCursor().removeSelectedText()
  724. else:
  725. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  726. self.textCursor().insertText("# ")
  727. cursor = QtGui.QTextCursor(self.textCursor())
  728. cursor.setPosition(pos)
  729. self.setTextCursor(cursor)
  730. class FCPlainTextAreaExtended(QtWidgets.QPlainTextEdit):
  731. def __init__(self, parent=None):
  732. super().__init__(parent)
  733. self.completer = MyCompleter()
  734. self.model = QtCore.QStringListModel()
  735. self.completer.setModel(self.model)
  736. self.set_model_data(keyword_list=[])
  737. self.completer.insertText.connect(self.insertCompletion)
  738. self.completer_enable = False
  739. def append(self, text):
  740. """
  741. Added this to make this subclass compatible with FCTextAreaExtended
  742. :param text: string
  743. :return:
  744. """
  745. self.appendPlainText(text)
  746. def set_model_data(self, keyword_list):
  747. self.model.setStringList(keyword_list)
  748. def insertCompletion(self, completion):
  749. tc = self.textCursor()
  750. extra = (len(completion) - len(self.completer.completionPrefix()))
  751. # don't insert if the word is finished but add a space instead
  752. if extra == 0:
  753. tc.insertText(' ')
  754. self.completer.popup().hide()
  755. return
  756. tc.movePosition(QTextCursor.Left)
  757. tc.movePosition(QTextCursor.EndOfWord)
  758. tc.insertText(completion[-extra:])
  759. # add a space after inserting the word
  760. tc.insertText(' ')
  761. self.setTextCursor(tc)
  762. self.completer.popup().hide()
  763. def focusInEvent(self, event):
  764. if self.completer:
  765. self.completer.setWidget(self)
  766. QtWidgets.QPlainTextEdit.focusInEvent(self, event)
  767. def set_value(self, val):
  768. self.setPlainText(val)
  769. def get_value(self):
  770. self.toPlainText()
  771. def insertFromMimeData(self, data):
  772. """
  773. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  774. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  775. :param data:
  776. :return:
  777. """
  778. modifier = QtWidgets.QApplication.keyboardModifiers()
  779. if modifier == Qt.ShiftModifier:
  780. text = data.text()
  781. text = text.replace('\\', '/')
  782. self.insertPlainText(text)
  783. else:
  784. self.insertPlainText(data.text())
  785. def keyPressEvent(self, event):
  786. """
  787. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  788. :param event:
  789. :return:
  790. """
  791. key = event.key()
  792. modifier = QtWidgets.QApplication.keyboardModifiers()
  793. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  794. if key == QtCore.Qt.Key_V:
  795. clipboard = QtWidgets.QApplication.clipboard()
  796. clip_text = clipboard.text()
  797. clip_text = clip_text.replace('\\', '/')
  798. self.insertPlainText(clip_text)
  799. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  800. self.comment()
  801. tc = self.textCursor()
  802. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  803. self.completer.insertText.emit(self.completer.getSelected())
  804. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  805. return
  806. elif key == Qt.Key_BraceLeft:
  807. tc.insertText('{}')
  808. self.moveCursor(QtGui.QTextCursor.Left)
  809. elif key == Qt.Key_BracketLeft:
  810. tc.insertText('[]')
  811. self.moveCursor(QtGui.QTextCursor.Left)
  812. elif key == Qt.Key_ParenLeft:
  813. tc.insertText('()')
  814. self.moveCursor(QtGui.QTextCursor.Left)
  815. elif key == Qt.Key_BraceRight:
  816. tc.select(QtGui.QTextCursor.WordUnderCursor)
  817. if tc.selectedText() == '}':
  818. tc.movePosition(QTextCursor.Right)
  819. self.setTextCursor(tc)
  820. else:
  821. tc.clearSelection()
  822. self.textCursor().insertText('}')
  823. elif key == Qt.Key_BracketRight:
  824. tc.select(QtGui.QTextCursor.WordUnderCursor)
  825. if tc.selectedText() == ']':
  826. tc.movePosition(QTextCursor.Right)
  827. self.setTextCursor(tc)
  828. else:
  829. tc.clearSelection()
  830. self.textCursor().insertText(']')
  831. elif key == Qt.Key_ParenRight:
  832. tc.select(QtGui.QTextCursor.WordUnderCursor)
  833. if tc.selectedText() == ')':
  834. tc.movePosition(QTextCursor.Right)
  835. self.setTextCursor(tc)
  836. else:
  837. tc.clearSelection()
  838. self.textCursor().insertText(')')
  839. else:
  840. super(FCPlainTextAreaExtended, self).keyPressEvent(event)
  841. if self.completer_enable:
  842. tc.select(QTextCursor.WordUnderCursor)
  843. cr = self.cursorRect()
  844. if len(tc.selectedText()) > 0:
  845. self.completer.setCompletionPrefix(tc.selectedText())
  846. popup = self.completer.popup()
  847. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  848. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  849. + self.completer.popup().verticalScrollBar().sizeHint().width())
  850. self.completer.complete(cr)
  851. else:
  852. self.completer.popup().hide()
  853. def comment(self):
  854. """
  855. Got it from here:
  856. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  857. :return:
  858. """
  859. pos = self.textCursor().position()
  860. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  861. line_text = self.textCursor().block().text()
  862. if self.textCursor().block().text().startswith(" "):
  863. # skip the white space
  864. self.moveCursor(QtGui.QTextCursor.NextWord)
  865. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  866. character = self.textCursor().selectedText()
  867. if character == "#":
  868. # delete #
  869. self.textCursor().deletePreviousChar()
  870. # delete white space
  871. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  872. self.textCursor().removeSelectedText()
  873. else:
  874. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  875. self.textCursor().insertText("# ")
  876. cursor = QtGui.QTextCursor(self.textCursor())
  877. cursor.setPosition(pos)
  878. self.setTextCursor(cursor)
  879. class FCComboBox(QtWidgets.QComboBox):
  880. def __init__(self, parent=None, callback=None):
  881. super(FCComboBox, self).__init__(parent)
  882. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  883. self.view = self.view()
  884. self.view.viewport().installEventFilter(self)
  885. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  886. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  887. # pos = mouse right click click position
  888. # self = is the combobox object itself
  889. if callback:
  890. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  891. def eventFilter(self, obj, event):
  892. if event.type() == QtCore.QEvent.MouseButtonRelease:
  893. if event.button() == Qt.RightButton:
  894. return True
  895. return False
  896. def wheelEvent(self, *args, **kwargs):
  897. pass
  898. def get_value(self):
  899. return str(self.currentText())
  900. def set_value(self, val):
  901. self.setCurrentIndex(self.findText(str(val)))
  902. class FCInputDialog(QtWidgets.QInputDialog):
  903. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  904. init_val=None):
  905. super(FCInputDialog, self).__init__(parent)
  906. self.allow_empty = ok
  907. self.empty_val = val
  908. self.val = 0.0
  909. self.ok = ''
  910. self.init_value = init_val if init_val else 0.0
  911. if title is None:
  912. self.title = 'title'
  913. else:
  914. self.title = title
  915. if text is None:
  916. self.text = 'text'
  917. else:
  918. self.text = text
  919. if min is None:
  920. self.min = 0
  921. else:
  922. self.min = min
  923. if max is None:
  924. self.max = 0
  925. else:
  926. self.max = max
  927. if decimals is None:
  928. self.decimals = 6
  929. else:
  930. self.decimals = decimals
  931. def get_value(self):
  932. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  933. max=self.max, decimals=self.decimals, value=self.init_value)
  934. return [self.val, self.ok]
  935. # "Transform", "Enter the Angle value:"
  936. def set_value(self, val):
  937. pass
  938. class FCButton(QtWidgets.QPushButton):
  939. def __init__(self, parent=None):
  940. super(FCButton, self).__init__(parent)
  941. def get_value(self):
  942. return self.isChecked()
  943. def set_value(self, val):
  944. self.setText(str(val))
  945. class FCMenu(QtWidgets.QMenu):
  946. def __init__(self):
  947. super().__init__()
  948. self.mouse_is_panning = False
  949. def popup(self, pos, action=None):
  950. self.mouse_is_panning = False
  951. super().popup(pos)
  952. class FCTab(QtWidgets.QTabWidget):
  953. def __init__(self, parent=None):
  954. super(FCTab, self).__init__(parent)
  955. self.setTabsClosable(True)
  956. self.tabCloseRequested.connect(self.closeTab)
  957. def deleteTab(self, currentIndex):
  958. widget = self.widget(currentIndex)
  959. if widget is not None:
  960. widget.deleteLater()
  961. self.removeTab(currentIndex)
  962. def closeTab(self, currentIndex):
  963. self.removeTab(currentIndex)
  964. def protectTab(self, currentIndex):
  965. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  966. # class FCTabBar(QtWidgets.QTabBar):
  967. # def tabSizeHint(self, index):
  968. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  969. # w = int(self.width()/self.count())
  970. # return QtCore.QSize(w, size.height())
  971. class FCDetachableTab(QtWidgets.QTabWidget):
  972. """
  973. From here:
  974. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  975. """
  976. def __init__(self, protect=None, protect_by_name=None, parent=None):
  977. super().__init__()
  978. self.tabBar = self.FCTabBar(self)
  979. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  980. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  981. self.set_detachable(val=True)
  982. self.setTabBar(self.tabBar)
  983. # Used to keep a reference to detached tabs since their QMainWindow
  984. # does not have a parent
  985. self.detachedTabs = {}
  986. # a way to make sure that tabs can't be closed after they attach to the parent tab
  987. self.protect_tab = True if protect is not None and protect is True else False
  988. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  989. # Close all detached tabs if the application is closed explicitly
  990. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  991. # used by the property self.useOldIndex(param)
  992. self.use_old_index = None
  993. self.old_index = None
  994. self.setTabsClosable(True)
  995. self.tabCloseRequested.connect(self.closeTab)
  996. def set_rmb_callback(self, callback):
  997. """
  998. :param callback: Function to call on right mouse click on tab
  999. :type callback: func
  1000. :return: None
  1001. """
  1002. self.tabBar.right_click.connect(callback)
  1003. def set_detachable(self, val=True):
  1004. try:
  1005. self.tabBar.onDetachTabSignal.disconnect()
  1006. except TypeError:
  1007. pass
  1008. if val is True:
  1009. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  1010. # the tab can be moved around
  1011. self.tabBar.can_be_dragged = True
  1012. else:
  1013. # the detached tab can't be moved
  1014. self.tabBar.can_be_dragged = False
  1015. return val
  1016. def setupContextMenu(self):
  1017. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1018. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  1019. action_name = str(entry)
  1020. action = QtWidgets.QAction(self)
  1021. action.setCheckable(True)
  1022. action.setText(action_name)
  1023. if icon:
  1024. assert isinstance(icon, QtGui.QIcon), \
  1025. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1026. action.setIcon(icon)
  1027. action.setChecked(initial_checked)
  1028. self.addAction(action)
  1029. action.triggered.connect(call_function)
  1030. def useOldIndex(self, param):
  1031. if param:
  1032. self.use_old_index = True
  1033. else:
  1034. self.use_old_index = False
  1035. def deleteTab(self, currentIndex):
  1036. widget = self.widget(currentIndex)
  1037. if widget is not None:
  1038. widget.deleteLater()
  1039. self.removeTab(currentIndex)
  1040. def closeTab(self, currentIndex):
  1041. """
  1042. Slot connected to the tabCloseRequested signal
  1043. :param currentIndex:
  1044. :return:
  1045. """
  1046. self.removeTab(currentIndex)
  1047. def protectTab(self, currentIndex):
  1048. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1049. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1050. def setMovable(self, movable):
  1051. """
  1052. The default movable functionality of QTabWidget must remain disabled
  1053. so as not to conflict with the added features
  1054. :param movable:
  1055. :return:
  1056. """
  1057. pass
  1058. @pyqtSlot(int, int)
  1059. def moveTab(self, fromIndex, toIndex):
  1060. """
  1061. Move a tab from one position (index) to another
  1062. :param fromIndex: the original index location of the tab
  1063. :param toIndex: the new index location of the tab
  1064. :return:
  1065. """
  1066. widget = self.widget(fromIndex)
  1067. icon = self.tabIcon(fromIndex)
  1068. text = self.tabText(fromIndex)
  1069. self.removeTab(fromIndex)
  1070. self.insertTab(toIndex, widget, icon, text)
  1071. self.setCurrentIndex(toIndex)
  1072. @pyqtSlot(int, QtCore.QPoint)
  1073. def detachTab(self, index, point):
  1074. """
  1075. Detach the tab by removing it's contents and placing them in
  1076. a DetachedTab window
  1077. :param index: the index location of the tab to be detached
  1078. :param point: the screen position for creating the new DetachedTab window
  1079. :return:
  1080. """
  1081. self.old_index = index
  1082. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  1083. name = "FlatCAM " + self.tabText(index)
  1084. icon = self.tabIcon(index)
  1085. if icon.isNull():
  1086. icon = self.window().windowIcon()
  1087. contentWidget = self.widget(index)
  1088. try:
  1089. contentWidgetRect = contentWidget.frameGeometry()
  1090. except AttributeError:
  1091. return
  1092. # Create a new detached tab window
  1093. detachedTab = self.FCDetachedTab(name, contentWidget)
  1094. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  1095. detachedTab.setWindowIcon(icon)
  1096. detachedTab.setGeometry(contentWidgetRect)
  1097. detachedTab.onCloseSignal.connect(self.attachTab)
  1098. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  1099. detachedTab.move(point)
  1100. detachedTab.show()
  1101. # Create a reference to maintain access to the detached tab
  1102. self.detachedTabs[name] = detachedTab
  1103. def attachTab(self, contentWidget, name, icon, insertAt=None):
  1104. """
  1105. Re-attach the tab by removing the content from the DetachedTab window,
  1106. closing it, and placing the content back into the DetachableTabWidget
  1107. :param contentWidget: the content widget from the DetachedTab window
  1108. :param name: the name of the detached tab
  1109. :param icon: the window icon for the detached tab
  1110. :param insertAt: insert the re-attached tab at the given index
  1111. :return:
  1112. """
  1113. # Make the content widget a child of this widget
  1114. contentWidget.setParent(self)
  1115. # Remove the reference
  1116. del self.detachedTabs[name]
  1117. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  1118. name = name.partition(' ')[2]
  1119. # helps in restoring the tab to the same index that it was before was detached
  1120. insert_index = self.old_index if self.use_old_index is True else insertAt
  1121. # Create an image from the given icon (for comparison)
  1122. if not icon.isNull():
  1123. try:
  1124. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  1125. tabIconImage = tabIconPixmap.toImage()
  1126. except IndexError:
  1127. tabIconImage = None
  1128. else:
  1129. tabIconImage = None
  1130. # Create an image of the main window icon (for comparison)
  1131. if not icon.isNull():
  1132. try:
  1133. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  1134. windowIconImage = windowIconPixmap.toImage()
  1135. except IndexError:
  1136. windowIconImage = None
  1137. else:
  1138. windowIconImage = None
  1139. # Determine if the given image and the main window icon are the same.
  1140. # If they are, then do not add the icon to the tab
  1141. if tabIconImage == windowIconImage:
  1142. if insert_index is None:
  1143. index = self.addTab(contentWidget, name)
  1144. else:
  1145. index = self.insertTab(insert_index, contentWidget, name)
  1146. else:
  1147. if insert_index is None:
  1148. index = self.addTab(contentWidget, icon, name)
  1149. else:
  1150. index = self.insertTab(insert_index, contentWidget, icon, name)
  1151. # on reattaching the tab if protect is true then the closure button is not added
  1152. if self.protect_tab is True:
  1153. self.protectTab(index)
  1154. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  1155. if self.protect_by_name is not None:
  1156. for tab_name in self.protect_by_name:
  1157. for index in range(self.count()):
  1158. if str(tab_name) == str(self.tabText(index)):
  1159. self.protectTab(index)
  1160. # Make this tab the current tab
  1161. if index > -1:
  1162. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  1163. def removeTabByName(self, name):
  1164. """
  1165. Remove the tab with the given name, even if it is detached
  1166. :param name: the name of the tab to be removed
  1167. :return:
  1168. """
  1169. # Remove the tab if it is attached
  1170. attached = False
  1171. for index in range(self.count()):
  1172. if str(name) == str(self.tabText(index)):
  1173. self.removeTab(index)
  1174. attached = True
  1175. break
  1176. # If the tab is not attached, close it's window and
  1177. # remove the reference to it
  1178. if not attached:
  1179. for key in self.detachedTabs:
  1180. if str(name) == str(key):
  1181. self.detachedTabs[key].onCloseSignal.disconnect()
  1182. self.detachedTabs[key].close()
  1183. del self.detachedTabs[key]
  1184. break
  1185. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  1186. def detachedTabDrop(self, name, index, dropPos):
  1187. """
  1188. Handle dropping of a detached tab inside the DetachableTabWidget
  1189. :param name: the name of the detached tab
  1190. :param index: the index of an existing tab (if the tab bar
  1191. # determined that the drop occurred on an
  1192. # existing tab)
  1193. :param dropPos: the mouse cursor position when the drop occurred
  1194. :return:
  1195. """
  1196. # If the drop occurred on an existing tab, insert the detached
  1197. # tab at the existing tab's location
  1198. if index > -1:
  1199. # Create references to the detached tab's content and icon
  1200. contentWidget = self.detachedTabs[name].contentWidget
  1201. icon = self.detachedTabs[name].windowIcon()
  1202. # Disconnect the detached tab's onCloseSignal so that it
  1203. # does not try to re-attach automatically
  1204. self.detachedTabs[name].onCloseSignal.disconnect()
  1205. # Close the detached
  1206. self.detachedTabs[name].close()
  1207. # Re-attach the tab at the given index
  1208. self.attachTab(contentWidget, name, icon, index)
  1209. # If the drop did not occur on an existing tab, determine if the drop
  1210. # occurred in the tab bar area (the area to the side of the QTabBar)
  1211. else:
  1212. # Find the drop position relative to the DetachableTabWidget
  1213. tabDropPos = self.mapFromGlobal(dropPos)
  1214. # If the drop position is inside the DetachableTabWidget...
  1215. if self.rect().contains(tabDropPos):
  1216. # If the drop position is inside the tab bar area (the
  1217. # area to the side of the QTabBar) or there are not tabs
  1218. # currently attached...
  1219. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1220. # Close the detached tab and allow it to re-attach
  1221. # automatically
  1222. self.detachedTabs[name].close()
  1223. def closeDetachedTabs(self):
  1224. """
  1225. Close all tabs that are currently detached.
  1226. :return:
  1227. """
  1228. listOfDetachedTabs = []
  1229. for key in self.detachedTabs:
  1230. listOfDetachedTabs.append(self.detachedTabs[key])
  1231. for detachedTab in listOfDetachedTabs:
  1232. detachedTab.close()
  1233. class FCDetachedTab(QtWidgets.QMainWindow):
  1234. """
  1235. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1236. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1237. """
  1238. onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1239. onDropSignal = QtCore.pyqtSignal(str, QtCore.QPoint)
  1240. def __init__(self, name, contentWidget):
  1241. QtWidgets.QMainWindow.__init__(self, None)
  1242. self.setObjectName(name)
  1243. self.setWindowTitle(name)
  1244. self.contentWidget = contentWidget
  1245. self.setCentralWidget(self.contentWidget)
  1246. self.contentWidget.show()
  1247. self.windowDropFilter = self.WindowDropFilter()
  1248. self.installEventFilter(self.windowDropFilter)
  1249. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1250. @QtCore.pyqtSlot(QtCore.QPoint)
  1251. def windowDropSlot(self, dropPos):
  1252. """
  1253. Handle a window drop event
  1254. :param dropPos: the mouse cursor position of the drop
  1255. :return:
  1256. """
  1257. self.onDropSignal.emit(self.objectName(), dropPos)
  1258. def closeEvent(self, event):
  1259. """
  1260. If the window is closed, emit the onCloseSignal and give the
  1261. content widget back to the DetachableTabWidget
  1262. :param event: a close event
  1263. :return:
  1264. """
  1265. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1266. class WindowDropFilter(QtCore.QObject):
  1267. """
  1268. An event filter class to detect a QMainWindow drop event
  1269. """
  1270. onDropSignal = QtCore.pyqtSignal(QtCore.QPoint)
  1271. def __init__(self):
  1272. QtCore.QObject.__init__(self)
  1273. self.lastEvent = None
  1274. def eventFilter(self, obj, event):
  1275. """
  1276. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1277. event that immediately follows a Move event
  1278. :param obj: the object that generated the event
  1279. :param event: the current event
  1280. :return:
  1281. """
  1282. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1283. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1284. # Determine the position of the mouse cursor and emit it with the
  1285. # onDropSignal
  1286. mouseCursor = QtGui.QCursor()
  1287. dropPos = mouseCursor.pos()
  1288. self.onDropSignal.emit(dropPos)
  1289. self.lastEvent = event.type()
  1290. return True
  1291. else:
  1292. self.lastEvent = event.type()
  1293. return False
  1294. class FCTabBar(QtWidgets.QTabBar):
  1295. onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)
  1296. onMoveTabSignal = QtCore.pyqtSignal(int, int)
  1297. detachedTabDropSignal = QtCore.pyqtSignal(str, int, QtCore.QPoint)
  1298. right_click = QtCore.pyqtSignal(int)
  1299. def __init__(self, parent=None):
  1300. QtWidgets.QTabBar.__init__(self, parent)
  1301. self.setAcceptDrops(True)
  1302. self.setElideMode(QtCore.Qt.ElideRight)
  1303. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1304. self.prev_index = -1
  1305. self.dragStartPos = QtCore.QPoint()
  1306. self.dragDropedPos = QtCore.QPoint()
  1307. self.mouseCursor = QtGui.QCursor()
  1308. self.dragInitiated = False
  1309. # set this to False and the tab will no longer be displayed as detached
  1310. self.can_be_dragged = True
  1311. def mouseDoubleClickEvent(self, event):
  1312. """
  1313. Send the onDetachTabSignal when a tab is double clicked
  1314. :param event: a mouse double click event
  1315. :return:
  1316. """
  1317. event.accept()
  1318. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1319. def mousePressEvent(self, event):
  1320. """
  1321. Set the starting position for a drag event when the left mouse button is pressed.
  1322. Start detection of a right mouse click.
  1323. :param event: a mouse press event
  1324. :return:
  1325. """
  1326. if event.button() == QtCore.Qt.LeftButton:
  1327. self.dragStartPos = event.pos()
  1328. elif event.button() == QtCore.Qt.RightButton:
  1329. self.prev_index = self.tabAt(event.pos())
  1330. self.dragDropedPos.setX(0)
  1331. self.dragDropedPos.setY(0)
  1332. self.dragInitiated = False
  1333. QtWidgets.QTabBar.mousePressEvent(self, event)
  1334. def mouseReleaseEvent(self, event):
  1335. """
  1336. Finish the detection of the right mouse click on the tab
  1337. :param event: a mouse press event
  1338. :return:
  1339. """
  1340. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1341. self.right_click.emit(self.prev_index)
  1342. self.prev_index = -1
  1343. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1344. def mouseMoveEvent(self, event):
  1345. """
  1346. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1347. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1348. bar, emit an onDetachTabSignal.
  1349. :param event: a mouse move event
  1350. :return:
  1351. """
  1352. # Determine if the current movement is detected as a drag
  1353. if not self.dragStartPos.isNull() and \
  1354. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1355. self.dragInitiated = True
  1356. # If the current movement is a drag initiated by the left button
  1357. if ((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated and self.can_be_dragged:
  1358. # Stop the move event
  1359. finishMoveEvent = QtGui.QMouseEvent(
  1360. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1361. )
  1362. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1363. # Convert the move event into a drag
  1364. drag = QtGui.QDrag(self)
  1365. mimeData = QtCore.QMimeData()
  1366. # mimeData.setData('action', 'application/tab-detach')
  1367. drag.setMimeData(mimeData)
  1368. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1369. # Create the appearance of dragging the tab content
  1370. try:
  1371. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1372. except Exception as e:
  1373. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1374. return
  1375. targetPixmap = QtGui.QPixmap(pixmap.size())
  1376. targetPixmap.fill(QtCore.Qt.transparent)
  1377. painter = QtGui.QPainter(targetPixmap)
  1378. painter.setOpacity(0.85)
  1379. painter.drawPixmap(0, 0, pixmap)
  1380. painter.end()
  1381. drag.setPixmap(targetPixmap)
  1382. # Initiate the drag
  1383. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1384. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1385. # must be set manually
  1386. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1387. dropAction = QtCore.Qt.MoveAction
  1388. # If the drag completed outside of the tab bar, detach the tab and move
  1389. # the content to the current cursor position
  1390. if dropAction == QtCore.Qt.IgnoreAction:
  1391. event.accept()
  1392. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1393. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1394. elif dropAction == QtCore.Qt.MoveAction:
  1395. if not self.dragDropedPos.isNull():
  1396. event.accept()
  1397. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1398. else:
  1399. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1400. def dragEnterEvent(self, event):
  1401. """
  1402. Determine if the drag has entered a tab position from another tab position
  1403. :param event: a drag enter event
  1404. :return:
  1405. """
  1406. mimeData = event.mimeData()
  1407. # formats = mcd imeData.formats()
  1408. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1409. # event.acceptProposedAction()
  1410. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1411. def dropEvent(self, event):
  1412. """
  1413. Get the position of the end of the drag
  1414. :param event: a drop event
  1415. :return:
  1416. """
  1417. self.dragDropedPos = event.pos()
  1418. QtWidgets.QTabBar.dropEvent(self, event)
  1419. def detachedTabDrop(self, name, dropPos):
  1420. """
  1421. Determine if the detached tab drop event occurred on an existing tab,
  1422. then send the event to the DetachableTabWidget
  1423. :param name:
  1424. :param dropPos:
  1425. :return:
  1426. """
  1427. tabDropPos = self.mapFromGlobal(dropPos)
  1428. index = self.tabAt(tabDropPos)
  1429. self.detachedTabDropSignal.emit(name, index, dropPos)
  1430. class FCDetachableTab2(FCDetachableTab):
  1431. tab_closed_signal = QtCore.pyqtSignal(object)
  1432. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1433. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1434. def closeTab(self, currentIndex):
  1435. """
  1436. Slot connected to the tabCloseRequested signal
  1437. :param currentIndex:
  1438. :return:
  1439. """
  1440. idx = self.currentIndex()
  1441. self.tab_closed_signal.emit(self.tabText(idx))
  1442. self.removeTab(currentIndex)
  1443. class VerticalScrollArea(QtWidgets.QScrollArea):
  1444. """
  1445. This widget extends QtGui.QScrollArea to make a vertical-only
  1446. scroll area that also expands horizontally to accomodate
  1447. its contents.
  1448. """
  1449. def __init__(self, parent=None):
  1450. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1451. self.setWidgetResizable(True)
  1452. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1453. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1454. def eventFilter(self, source, event):
  1455. """
  1456. The event filter gets automatically installed when setWidget()
  1457. is called.
  1458. :param source:
  1459. :param event:
  1460. :return:
  1461. """
  1462. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1463. # log.debug("VerticalScrollArea: Widget resized:")
  1464. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1465. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1466. self.setMinimumWidth(self.widget().sizeHint().width() +
  1467. self.verticalScrollBar().sizeHint().width())
  1468. # if self.verticalScrollBar().isVisible():
  1469. # log.debug(" Scroll bar visible")
  1470. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1471. # self.verticalScrollBar().width())
  1472. # else:
  1473. # log.debug(" Scroll bar hidden")
  1474. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1475. return QtWidgets.QWidget.eventFilter(self, source, event)
  1476. class OptionalInputSection:
  1477. def __init__(self, cb, optinputs, logic=True):
  1478. """
  1479. Associates the a checkbox with a set of inputs.
  1480. :param cb: Checkbox that enables the optional inputs.
  1481. :param optinputs: List of widgets that are optional.
  1482. :param logic: When True the logic is normal, when False the logic is in reverse
  1483. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1484. for logic=False, when the checkbox is checked the widgets are Disabled
  1485. :return:
  1486. """
  1487. assert isinstance(cb, FCCheckBox), \
  1488. "Expected an FCCheckBox, got %s" % type(cb)
  1489. self.cb = cb
  1490. self.optinputs = optinputs
  1491. self.logic = logic
  1492. self.on_cb_change()
  1493. self.cb.stateChanged.connect(self.on_cb_change)
  1494. def on_cb_change(self):
  1495. if self.cb.checkState():
  1496. for widget in self.optinputs:
  1497. if self.logic is True:
  1498. widget.setEnabled(True)
  1499. else:
  1500. widget.setEnabled(False)
  1501. else:
  1502. for widget in self.optinputs:
  1503. if self.logic is True:
  1504. widget.setEnabled(False)
  1505. else:
  1506. widget.setEnabled(True)
  1507. class OptionalHideInputSection:
  1508. def __init__(self, cb, optinputs, logic=True):
  1509. """
  1510. Associates the a checkbox with a set of inputs.
  1511. :param cb: Checkbox that enables the optional inputs.
  1512. :param optinputs: List of widgets that are optional.
  1513. :param logic: When True the logic is normal, when False the logic is in reverse
  1514. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1515. for logic=False, when the checkbox is checked the widgets are Disabled
  1516. :return:
  1517. """
  1518. assert isinstance(cb, FCCheckBox), \
  1519. "Expected an FCCheckBox, got %s" % type(cb)
  1520. self.cb = cb
  1521. self.optinputs = optinputs
  1522. self.logic = logic
  1523. self.on_cb_change()
  1524. self.cb.stateChanged.connect(self.on_cb_change)
  1525. def on_cb_change(self):
  1526. if self.cb.checkState():
  1527. for widget in self.optinputs:
  1528. if self.logic is True:
  1529. widget.show()
  1530. else:
  1531. widget.hide()
  1532. else:
  1533. for widget in self.optinputs:
  1534. if self.logic is True:
  1535. widget.hide()
  1536. else:
  1537. widget.show()
  1538. class FCTable(QtWidgets.QTableWidget):
  1539. drag_drop_sig = QtCore.pyqtSignal()
  1540. def __init__(self, drag_drop=False, protected_rows=None, parent=None):
  1541. super(FCTable, self).__init__(parent)
  1542. if drag_drop:
  1543. self.setDragEnabled(True)
  1544. self.setAcceptDrops(True)
  1545. self.viewport().setAcceptDrops(True)
  1546. self.setDragDropOverwriteMode(False)
  1547. self.setDropIndicatorShown(True)
  1548. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1549. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1550. self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  1551. self.rows_not_for_drag_and_drop = list()
  1552. if protected_rows:
  1553. try:
  1554. for r in protected_rows:
  1555. self.rows_not_for_drag_and_drop.append(r)
  1556. except TypeError:
  1557. self.rows_not_for_drag_and_drop = [protected_rows]
  1558. self.rows_to_move = list()
  1559. def sizeHint(self):
  1560. default_hint_size = super(FCTable, self).sizeHint()
  1561. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1562. def getHeight(self):
  1563. height = self.horizontalHeader().height()
  1564. for i in range(self.rowCount()):
  1565. height += self.rowHeight(i)
  1566. return height
  1567. def getWidth(self):
  1568. width = self.verticalHeader().width()
  1569. for i in range(self.columnCount()):
  1570. width += self.columnWidth(i)
  1571. return width
  1572. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpha
  1573. def setColortoRow(self, rowIndex, color):
  1574. for j in range(self.columnCount()):
  1575. self.item(rowIndex, j).setBackground(color)
  1576. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1577. def mousePressEvent(self, event):
  1578. if not self.itemAt(event.pos()):
  1579. self.clearSelection()
  1580. self.clearFocus()
  1581. else:
  1582. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1583. def setupContextMenu(self):
  1584. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1585. def addContextMenu(self, entry, call_function, icon=None):
  1586. action_name = str(entry)
  1587. action = QtWidgets.QAction(self)
  1588. action.setText(action_name)
  1589. if icon:
  1590. assert isinstance(icon, QtGui.QIcon), \
  1591. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1592. action.setIcon(icon)
  1593. self.addAction(action)
  1594. action.triggered.connect(call_function)
  1595. # def dropEvent(self, event: QtGui.QDropEvent):
  1596. # if not event.isAccepted() and event.source() == self:
  1597. # drop_row = self.drop_on(event)
  1598. #
  1599. # rows = sorted(set(item.row() for item in self.selectedItems()))
  1600. # # rows_to_move = [
  1601. # # [QtWidgets.QTableWidgetItem(self.item(row_index, column_index))
  1602. # # for column_index in range(self.columnCount())] for row_index in rows
  1603. # # ]
  1604. # self.rows_to_move[:] = []
  1605. # for row_index in rows:
  1606. # row_items = list()
  1607. # for column_index in range(self.columnCount()):
  1608. # r_item = self.item(row_index, column_index)
  1609. # w_item = self.cellWidget(row_index, column_index)
  1610. #
  1611. # if r_item is not None:
  1612. # row_items.append(QtWidgets.QTableWidgetItem(r_item))
  1613. # elif w_item is not None:
  1614. # row_items.append(w_item)
  1615. #
  1616. # self.rows_to_move.append(row_items)
  1617. #
  1618. # for row_index in reversed(rows):
  1619. # self.removeRow(row_index)
  1620. # if row_index < drop_row:
  1621. # drop_row -= 1
  1622. #
  1623. # for row_index, data in enumerate(self.rows_to_move):
  1624. # row_index += drop_row
  1625. # self.insertRow(row_index)
  1626. #
  1627. # for column_index, column_data in enumerate(data):
  1628. # if isinstance(column_data, QtWidgets.QTableWidgetItem):
  1629. # self.setItem(row_index, column_index, column_data)
  1630. # else:
  1631. # self.setCellWidget(row_index, column_index, column_data)
  1632. #
  1633. # event.accept()
  1634. # for row_index in range(len(self.rows_to_move)):
  1635. # self.item(drop_row + row_index, 0).setSelected(True)
  1636. # self.item(drop_row + row_index, 1).setSelected(True)
  1637. #
  1638. # super().dropEvent(event)
  1639. #
  1640. # def drop_on(self, event):
  1641. # ret_val = False
  1642. # index = self.indexAt(event.pos())
  1643. # if not index.isValid():
  1644. # return self.rowCount()
  1645. #
  1646. # ret_val = index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  1647. #
  1648. # return ret_val
  1649. #
  1650. # def is_below(self, pos, index):
  1651. # rect = self.visualRect(index)
  1652. # margin = 2
  1653. # if pos.y() - rect.top() < margin:
  1654. # return False
  1655. # elif rect.bottom() - pos.y() < margin:
  1656. # return True
  1657. # # noinspection PyTypeChecker
  1658. # return rect.contains(pos, True) and not (
  1659. # int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
  1660. def dropEvent(self, event):
  1661. """
  1662. From here: https://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
  1663. :param event:
  1664. :return:
  1665. """
  1666. if event.source() == self:
  1667. rows = set([mi.row() for mi in self.selectedIndexes()])
  1668. # if one of the selected rows for drag and drop is within the protected list, return
  1669. for r in rows:
  1670. if r in self.rows_not_for_drag_and_drop:
  1671. return
  1672. targetRow = self.indexAt(event.pos()).row()
  1673. rows.discard(targetRow)
  1674. rows = sorted(rows)
  1675. if not rows:
  1676. return
  1677. if targetRow == -1:
  1678. targetRow = self.rowCount()
  1679. for _ in range(len(rows)):
  1680. self.insertRow(targetRow)
  1681. rowMapping = dict() # Src row to target row.
  1682. for idx, row in enumerate(rows):
  1683. if row < targetRow:
  1684. rowMapping[row] = targetRow + idx
  1685. else:
  1686. rowMapping[row + len(rows)] = targetRow + idx
  1687. colCount = self.columnCount()
  1688. for srcRow, tgtRow in sorted(rowMapping.items()):
  1689. for col in range(0, colCount):
  1690. new_item = self.item(srcRow, col)
  1691. if new_item is None:
  1692. new_item = self.cellWidget(srcRow, col)
  1693. if isinstance(new_item, QtWidgets.QTableWidgetItem):
  1694. new_item = self.takeItem(srcRow, col)
  1695. self.setItem(tgtRow, col, new_item)
  1696. else:
  1697. self.setCellWidget(tgtRow, col, new_item)
  1698. for row in reversed(sorted(rowMapping.keys())):
  1699. self.removeRow(row)
  1700. event.accept()
  1701. self.drag_drop_sig.emit()
  1702. return
  1703. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  1704. def __init__(self, units):
  1705. super(SpinBoxDelegate, self).__init__()
  1706. self.units = units
  1707. self.current_value = None
  1708. def createEditor(self, parent, option, index):
  1709. editor = QtWidgets.QDoubleSpinBox(parent)
  1710. editor.setMinimum(-999.9999)
  1711. editor.setMaximum(999.9999)
  1712. if self.units == 'MM':
  1713. editor.setDecimals(2)
  1714. else:
  1715. editor.setDecimals(3)
  1716. return editor
  1717. def setEditorData(self, spinBox, index):
  1718. try:
  1719. value = float(index.model().data(index, Qt.EditRole))
  1720. except ValueError:
  1721. value = self.current_value
  1722. # return
  1723. spinBox.setValue(value)
  1724. def setModelData(self, spinBox, model, index):
  1725. spinBox.interpretText()
  1726. value = spinBox.value()
  1727. self.current_value = value
  1728. model.setData(index, value, Qt.EditRole)
  1729. def updateEditorGeometry(self, editor, option, index):
  1730. editor.setGeometry(option.rect)
  1731. def setDecimals(self, spinbox, digits):
  1732. spinbox.setDecimals(digits)
  1733. class Dialog_box(QtWidgets.QWidget):
  1734. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  1735. """
  1736. :param title: string with the window title
  1737. :param label: string with the message inside the dialog box
  1738. """
  1739. super(Dialog_box, self).__init__()
  1740. if initial_text is None:
  1741. self.location = str((0, 0))
  1742. else:
  1743. self.location = initial_text
  1744. self.ok = False
  1745. self.dialog_box = QtWidgets.QInputDialog()
  1746. self.dialog_box.setMinimumWidth(290)
  1747. self.setWindowIcon(icon)
  1748. self.location, self.ok = self.dialog_box.getText(self, title, label,
  1749. text=str(self.location).replace('(', '').replace(')', ''))
  1750. self.readyToEdit = True
  1751. def mousePressEvent(self, e, parent=None):
  1752. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  1753. if self.readyToEdit:
  1754. self.lineEdit().selectAll()
  1755. self.readyToEdit = False
  1756. def focusOutEvent(self, e):
  1757. # don't focus out if the user requests an popup menu
  1758. if e.reason() != QtCore.Qt.PopupFocusReason:
  1759. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  1760. self.lineEdit().deselect()
  1761. self.readyToEdit = True
  1762. class _BrowserTextEdit(QTextEdit):
  1763. def __init__(self, version):
  1764. QTextEdit.__init__(self)
  1765. self.menu = None
  1766. self.version = version
  1767. def contextMenuEvent(self, event):
  1768. self.menu = self.createStandardContextMenu(event.pos())
  1769. clear_action = QAction("Clear", self)
  1770. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  1771. self.menu.addAction(clear_action)
  1772. clear_action.triggered.connect(self.clear)
  1773. self.menu.exec_(event.globalPos())
  1774. def clear(self):
  1775. QTextEdit.clear(self)
  1776. text = "FlatCAM %s - Type >help< to get started\n\n" % self.version
  1777. text = html.escape(text)
  1778. text = text.replace('\n', '<br/>')
  1779. self.moveCursor(QTextCursor.End)
  1780. self.insertHtml(text)
  1781. class _ExpandableTextEdit(QTextEdit):
  1782. """
  1783. Class implements edit line, which expands themselves automatically
  1784. """
  1785. historyNext = QtCore.pyqtSignal()
  1786. historyPrev = QtCore.pyqtSignal()
  1787. def __init__(self, termwidget, *args):
  1788. QTextEdit.__init__(self, *args)
  1789. self.setStyleSheet("font: 9pt \"Courier\";")
  1790. self._fittedHeight = 1
  1791. self.textChanged.connect(self._fit_to_document)
  1792. self._fit_to_document()
  1793. self._termWidget = termwidget
  1794. self.completer = MyCompleter()
  1795. self.model = QtCore.QStringListModel()
  1796. self.completer.setModel(self.model)
  1797. self.set_model_data(keyword_list=[])
  1798. self.completer.insertText.connect(self.insertCompletion)
  1799. def set_model_data(self, keyword_list):
  1800. self.model.setStringList(keyword_list)
  1801. def insertCompletion(self, completion):
  1802. tc = self.textCursor()
  1803. extra = (len(completion) - len(self.completer.completionPrefix()))
  1804. # don't insert if the word is finished but add a space instead
  1805. if extra == 0:
  1806. tc.insertText(' ')
  1807. self.completer.popup().hide()
  1808. return
  1809. tc.movePosition(QTextCursor.Left)
  1810. tc.movePosition(QTextCursor.EndOfWord)
  1811. tc.insertText(completion[-extra:])
  1812. # add a space after inserting the word
  1813. tc.insertText(' ')
  1814. self.setTextCursor(tc)
  1815. self.completer.popup().hide()
  1816. def focusInEvent(self, event):
  1817. if self.completer:
  1818. self.completer.setWidget(self)
  1819. QTextEdit.focusInEvent(self, event)
  1820. def keyPressEvent(self, event):
  1821. """
  1822. Catch keyboard events. Process Enter, Up, Down
  1823. """
  1824. key = event.key()
  1825. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  1826. self.completer.insertText.emit(self.completer.getSelected())
  1827. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1828. return
  1829. if event.matches(QKeySequence.InsertParagraphSeparator):
  1830. text = self.toPlainText()
  1831. if self._termWidget.is_command_complete(text):
  1832. self._termWidget.exec_current_command()
  1833. return
  1834. elif event.matches(QKeySequence.MoveToNextLine):
  1835. text = self.toPlainText()
  1836. cursor_pos = self.textCursor().position()
  1837. textBeforeEnd = text[cursor_pos:]
  1838. if len(textBeforeEnd.split('\n')) <= 1:
  1839. self.historyNext.emit()
  1840. return
  1841. elif event.matches(QKeySequence.MoveToPreviousLine):
  1842. text = self.toPlainText()
  1843. cursor_pos = self.textCursor().position()
  1844. text_before_start = text[:cursor_pos]
  1845. # lineCount = len(textBeforeStart.splitlines())
  1846. line_count = len(text_before_start.split('\n'))
  1847. if len(text_before_start) > 0 and \
  1848. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1849. line_count += 1
  1850. if line_count <= 1:
  1851. self.historyPrev.emit()
  1852. return
  1853. elif event.matches(QKeySequence.MoveToNextPage) or \
  1854. event.matches(QKeySequence.MoveToPreviousPage):
  1855. return self._termWidget.browser().keyPressEvent(event)
  1856. tc = self.textCursor()
  1857. QTextEdit.keyPressEvent(self, event)
  1858. tc.select(QTextCursor.WordUnderCursor)
  1859. cr = self.cursorRect()
  1860. if len(tc.selectedText()) > 0:
  1861. self.completer.setCompletionPrefix(tc.selectedText())
  1862. popup = self.completer.popup()
  1863. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1864. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1865. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1866. self.completer.complete(cr)
  1867. else:
  1868. self.completer.popup().hide()
  1869. def sizeHint(self):
  1870. """
  1871. QWidget sizeHint impelemtation
  1872. """
  1873. hint = QTextEdit.sizeHint(self)
  1874. hint.setHeight(self._fittedHeight)
  1875. return hint
  1876. def _fit_to_document(self):
  1877. """
  1878. Update widget height to fit all text
  1879. """
  1880. documentsize = self.document().size().toSize()
  1881. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1882. self.setMaximumHeight(self._fittedHeight)
  1883. self.updateGeometry()
  1884. def insertFromMimeData(self, mime_data):
  1885. # Paste only plain text.
  1886. self.insertPlainText(mime_data.text())
  1887. class MyCompleter(QCompleter):
  1888. insertText = QtCore.pyqtSignal(str)
  1889. def __init__(self, parent=None):
  1890. QCompleter.__init__(self)
  1891. self.setCompletionMode(QCompleter.PopupCompletion)
  1892. self.highlighted.connect(self.setHighlighted)
  1893. # self.popup().installEventFilter(self)
  1894. # def eventFilter(self, obj, event):
  1895. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  1896. # pass
  1897. # return False
  1898. def setHighlighted(self, text):
  1899. self.lastSelected = text
  1900. def getSelected(self):
  1901. return self.lastSelected
  1902. class FCTextAreaLineNumber(QtWidgets.QFrame):
  1903. textChanged = QtCore.pyqtSignal()
  1904. class NumberBar(QtWidgets.QWidget):
  1905. def __init__(self, edit):
  1906. QtWidgets.QWidget.__init__(self, edit)
  1907. self.edit = edit
  1908. self.adjustWidth(1)
  1909. def paintEvent(self, event):
  1910. self.edit.numberbarPaint(self, event)
  1911. QtWidgets.QWidget.paintEvent(self, event)
  1912. def adjustWidth(self, count):
  1913. # three spaces added to the width to make up for the space added in the line number
  1914. width = self.fontMetrics().width(str(count) + ' ')
  1915. if self.width() != width:
  1916. self.setFixedWidth(width)
  1917. def updateContents(self, rect, scroll):
  1918. if scroll:
  1919. self.scroll(0, scroll)
  1920. else:
  1921. # It would be nice to do
  1922. # self.update(0, rect.y(), self.width(), rect.height())
  1923. # But we can't because it will not remove the bold on the
  1924. # current line if word wrap is enabled and a new block is
  1925. # selected.
  1926. self.update()
  1927. class PlainTextEdit(FCPlainTextAreaExtended):
  1928. """
  1929. TextEdit with line numbers and highlight
  1930. From here: https://nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/
  1931. and from here: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
  1932. """
  1933. def __init__(self, *args):
  1934. FCPlainTextAreaExtended.__init__(self, *args)
  1935. # self.setFrameStyle(QFrame.NoFrame)
  1936. self.setFrameStyle(QtWidgets.QFrame.NoFrame)
  1937. self.highlight()
  1938. # self.setLineWrapMode(QPlainTextEdit.NoWrap)
  1939. self.cursorPositionChanged.connect(self.highlight)
  1940. def highlight(self):
  1941. hi_selection = QTextEdit.ExtraSelection()
  1942. hi_selection.format.setBackground(self.palette().alternateBase())
  1943. hi_selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
  1944. hi_selection.cursor = self.textCursor()
  1945. hi_selection.cursor.clearSelection()
  1946. self.setExtraSelections([hi_selection])
  1947. def numberbarPaint(self, number_bar, event):
  1948. font_metrics = self.fontMetrics()
  1949. current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
  1950. painter = QtGui.QPainter(number_bar)
  1951. painter.fillRect(event.rect(), QtCore.Qt.lightGray)
  1952. block = self.firstVisibleBlock()
  1953. line_count = int(block.blockNumber())
  1954. block_top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
  1955. block_bottom = block_top + int(self.blockBoundingRect(block).height())
  1956. # Iterate over all visible text blocks in the document.
  1957. while block.isValid() and block_top <= event.rect().bottom():
  1958. line_count += 1
  1959. # Check if the position of the block is out side of the visible
  1960. # area.
  1961. if block.isVisible() and block_bottom >= event.rect().top():
  1962. # We want the line number for the selected line to be bold.
  1963. if line_count == current_line:
  1964. font = painter.font()
  1965. font.setBold(True)
  1966. painter.setPen(QtCore.Qt.blue)
  1967. painter.setFont(font)
  1968. else:
  1969. font = painter.font()
  1970. font.setBold(False)
  1971. painter.setPen(self.palette().base().color())
  1972. painter.setFont(font)
  1973. # Draw the line number right justified at the position of the line.
  1974. paint_rect = QtCore.QRect(0, block_top, number_bar.width(), font_metrics.height())
  1975. # I add some spaces to the line_count to prettify; make sure to remember adjust the width in the
  1976. # NumberBar() class above
  1977. painter.drawText(paint_rect, Qt.AlignRight, ' ' + str(line_count) + ' ')
  1978. block = block.next()
  1979. block_top = block_bottom
  1980. block_bottom = block_top + self.blockBoundingRect(block).height()
  1981. painter.end()
  1982. def __init__(self, *args):
  1983. QtWidgets.QFrame.__init__(self, *args)
  1984. self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Sunken)
  1985. self.edit = self.PlainTextEdit()
  1986. self.number_bar = self.NumberBar(self.edit)
  1987. hbox = QtWidgets.QHBoxLayout(self)
  1988. hbox.setSpacing(0)
  1989. hbox.setContentsMargins(0, 0, 0, 0)
  1990. hbox.addWidget(self.number_bar)
  1991. hbox.addWidget(self.edit)
  1992. self.edit.blockCountChanged.connect(self.number_bar.adjustWidth)
  1993. self.edit.updateRequest.connect(self.number_bar.updateContents)
  1994. def getText(self):
  1995. return str(self.edit.toPlainText())
  1996. def setText(self, text):
  1997. self.edit.setPlainText(text)
  1998. def isModified(self):
  1999. return self.edit.document().isModified()
  2000. def setModified(self, modified):
  2001. self.edit.document().setModified(modified)
  2002. def setLineWrapMode(self, mode):
  2003. self.edit.setLineWrapMode(mode)
  2004. def rreplace(s, old, new, occurrence):
  2005. """
  2006. Credits go here:
  2007. https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
  2008. :param s: string to be processed
  2009. :param old: old char to be replaced
  2010. :param new: new char to replace the old one
  2011. :param occurrence: how many places from end to replace the old char
  2012. :return: modified string
  2013. """
  2014. li = s.rsplit(old, occurrence)
  2015. return new.join(li)