GUIElements.py 87 KB

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