GUIElements.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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, pyqtSignal, pyqtSlot
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  16. from copy import copy
  17. import re
  18. import logging
  19. import html
  20. log = logging.getLogger('base')
  21. EDIT_SIZE_HINT = 70
  22. class RadioSet(QtWidgets.QWidget):
  23. activated_custom = QtCore.pyqtSignal(str)
  24. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  25. """
  26. The choices are specified as a list of dictionaries containing:
  27. * 'label': Shown in the UI
  28. * 'value': The value returned is selected
  29. :param choices: List of choices. See description.
  30. :param orientation: 'horizontal' (default) of 'vertical'.
  31. :param parent: Qt parent widget.
  32. :type choices: list
  33. """
  34. super(RadioSet, self).__init__(parent)
  35. self.choices = copy(choices)
  36. if orientation == 'horizontal':
  37. layout = QtWidgets.QHBoxLayout()
  38. else:
  39. layout = QtWidgets.QVBoxLayout()
  40. group = QtWidgets.QButtonGroup(self)
  41. for choice in self.choices:
  42. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  43. group.addButton(choice['radio'])
  44. layout.addWidget(choice['radio'], stretch=0)
  45. choice['radio'].toggled.connect(self.on_toggle)
  46. layout.setContentsMargins(0, 0, 0, 0)
  47. if stretch is False:
  48. pass
  49. else:
  50. layout.addStretch()
  51. self.setLayout(layout)
  52. self.group_toggle_fn = lambda: None
  53. def on_toggle(self):
  54. # log.debug("Radio toggled")
  55. radio = self.sender()
  56. if radio.isChecked():
  57. self.group_toggle_fn()
  58. ret_val = str(self.get_value())
  59. self.activated_custom.emit(ret_val)
  60. return
  61. def get_value(self):
  62. for choice in self.choices:
  63. if choice['radio'].isChecked():
  64. return choice['value']
  65. log.error("No button was toggled in RadioSet.")
  66. return None
  67. def set_value(self, val):
  68. for choice in self.choices:
  69. if choice['value'] == val:
  70. choice['radio'].setChecked(True)
  71. return
  72. log.error("Value given is not part of this RadioSet: %s" % str(val))
  73. # class RadioGroupChoice(QtWidgets.QWidget):
  74. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  75. # """
  76. # The choices are specified as a list of dictionaries containing:
  77. #
  78. # * 'label': Shown in the UI
  79. # * 'value': The value returned is selected
  80. #
  81. # :param choices: List of choices. See description.
  82. # :param orientation: 'horizontal' (default) of 'vertical'.
  83. # :param parent: Qt parent widget.
  84. # :type choices: list
  85. # """
  86. # super().__init__(parent)
  87. #
  88. # group = QtGui.QButtonGroup(self)
  89. #
  90. # self.lbl1 = label_1
  91. # self.lbl2 = label_2
  92. # self.hide_list = hide_list
  93. # self.show_list = show_list
  94. #
  95. # self.btn1 = QtGui.QRadioButton(str(label_1))
  96. # self.btn2 = QtGui.QRadioButton(str(label_2))
  97. # group.addButton(self.btn1)
  98. # group.addButton(self.btn2)
  99. #
  100. # if to_check == 1:
  101. # self.btn1.setChecked(True)
  102. # else:
  103. # self.btn2.setChecked(True)
  104. #
  105. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  106. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  107. #
  108. # def btn_state(self, btn):
  109. # if btn.text() == self.lbl1:
  110. # if btn.isChecked() is True:
  111. # self.show_widgets(self.show_list)
  112. # self.hide_widgets(self.hide_list)
  113. # else:
  114. # self.show_widgets(self.hide_list)
  115. # self.hide_widgets(self.show_list)
  116. #
  117. # def hide_widgets(self, lst):
  118. # for wgt in lst:
  119. # wgt.hide()
  120. #
  121. # def show_widgets(self, lst):
  122. # for wgt in lst:
  123. # wgt.show()
  124. class LengthEntry(QtWidgets.QLineEdit):
  125. def __init__(self, output_units='IN', parent=None):
  126. super(LengthEntry, self).__init__(parent)
  127. self.output_units = output_units
  128. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  129. # Unit conversion table OUTPUT-INPUT
  130. self.scales = {
  131. 'IN': {'IN': 1.0,
  132. 'MM': 1/25.4},
  133. 'MM': {'IN': 25.4,
  134. 'MM': 1.0}
  135. }
  136. self.readyToEdit = True
  137. def mousePressEvent(self, e, Parent=None):
  138. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  139. if self.readyToEdit:
  140. self.selectAll()
  141. self.readyToEdit = False
  142. def focusOutEvent(self, e):
  143. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  144. self.deselect()
  145. self.readyToEdit = True
  146. def returnPressed(self, *args, **kwargs):
  147. val = self.get_value()
  148. if val is not None:
  149. self.set_text(str(val))
  150. else:
  151. log.warning("Could not interpret entry: %s" % self.get_text())
  152. def get_value(self):
  153. raw = str(self.text()).strip(' ')
  154. # match = self.format_re.search(raw)
  155. try:
  156. units = raw[-2:]
  157. units = self.scales[self.output_units][units.upper()]
  158. value = raw[:-2]
  159. return float(eval(value))*units
  160. except IndexError:
  161. value = raw
  162. return float(eval(value))
  163. except KeyError:
  164. value = raw
  165. return float(eval(value))
  166. except:
  167. log.warning("Could not parse value in entry: %s" % str(raw))
  168. return None
  169. def set_value(self, val):
  170. self.setText(str('%.4f' % val))
  171. def sizeHint(self):
  172. default_hint_size = super(LengthEntry, self).sizeHint()
  173. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  174. class FloatEntry(QtWidgets.QLineEdit):
  175. def __init__(self, parent=None):
  176. super(FloatEntry, self).__init__(parent)
  177. self.readyToEdit = True
  178. def mousePressEvent(self, e, Parent=None):
  179. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  180. if self.readyToEdit:
  181. self.selectAll()
  182. self.readyToEdit = False
  183. def focusOutEvent(self, e):
  184. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  185. self.deselect()
  186. self.readyToEdit = True
  187. def returnPressed(self, *args, **kwargs):
  188. val = self.get_value()
  189. if val is not None:
  190. self.set_text(str(val))
  191. else:
  192. log.warning("Could not interpret entry: %s" % self.text())
  193. def get_value(self):
  194. raw = str(self.text()).strip(' ')
  195. evaled = 0.0
  196. try:
  197. evaled = eval(raw)
  198. except:
  199. if evaled is not None:
  200. log.error("Could not evaluate: %s" % str(raw))
  201. return None
  202. return float(evaled)
  203. def set_value(self, val):
  204. if val is not None:
  205. self.setText("%.4f" % val)
  206. else:
  207. self.setText("")
  208. def sizeHint(self):
  209. default_hint_size = super(FloatEntry, self).sizeHint()
  210. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  211. class FloatEntry2(QtWidgets.QLineEdit):
  212. def __init__(self, parent=None):
  213. super(FloatEntry2, self).__init__(parent)
  214. self.readyToEdit = True
  215. def mousePressEvent(self, e, Parent=None):
  216. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  217. if self.readyToEdit:
  218. self.selectAll()
  219. self.readyToEdit = False
  220. def focusOutEvent(self, e):
  221. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  222. self.deselect()
  223. self.readyToEdit = True
  224. def get_value(self):
  225. raw = str(self.text()).strip(' ')
  226. evaled = 0.0
  227. try:
  228. evaled = eval(raw)
  229. except:
  230. if evaled is not None:
  231. log.error("Could not evaluate: %s" % str(raw))
  232. return None
  233. return float(evaled)
  234. def set_value(self, val):
  235. self.setText("%.4f" % val)
  236. def sizeHint(self):
  237. default_hint_size = super(FloatEntry2, self).sizeHint()
  238. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  239. class IntEntry(QtWidgets.QLineEdit):
  240. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  241. super(IntEntry, self).__init__(parent)
  242. self.allow_empty = allow_empty
  243. self.empty_val = empty_val
  244. self.readyToEdit = True
  245. def mousePressEvent(self, e, Parent=None):
  246. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  247. if self.readyToEdit:
  248. self.selectAll()
  249. self.readyToEdit = False
  250. def focusOutEvent(self, e):
  251. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  252. self.deselect()
  253. self.readyToEdit = True
  254. def get_value(self):
  255. if self.allow_empty:
  256. if str(self.text()) == "":
  257. return self.empty_val
  258. # make the text() first a float and then int because if text is a float type,
  259. # the int() can't convert directly a "text float" into a int type.
  260. ret_val = float(self.text())
  261. ret_val = int(ret_val)
  262. return ret_val
  263. def set_value(self, val):
  264. if val == self.empty_val and self.allow_empty:
  265. self.setText("")
  266. return
  267. self.setText(str(val))
  268. def sizeHint(self):
  269. default_hint_size = super(IntEntry, self).sizeHint()
  270. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  271. class FCEntry(QtWidgets.QLineEdit):
  272. def __init__(self, parent=None):
  273. super(FCEntry, self).__init__(parent)
  274. self.readyToEdit = True
  275. def mousePressEvent(self, e, Parent=None):
  276. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  277. if self.readyToEdit:
  278. self.selectAll()
  279. self.readyToEdit = False
  280. def focusOutEvent(self, e):
  281. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  282. self.deselect()
  283. self.readyToEdit = True
  284. def get_value(self):
  285. return str(self.text())
  286. def set_value(self, val):
  287. if type(val) is float:
  288. self.setText('%.4f' % val)
  289. else:
  290. self.setText(str(val))
  291. def sizeHint(self):
  292. default_hint_size = super(FCEntry, self).sizeHint()
  293. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  294. class FCEntry2(FCEntry):
  295. def __init__(self, parent=None):
  296. super(FCEntry2, self).__init__(parent)
  297. self.readyToEdit = True
  298. def set_value(self, val):
  299. try:
  300. fval = float(val)
  301. except ValueError:
  302. return
  303. self.setText('%.4f' % fval)
  304. class EvalEntry(QtWidgets.QLineEdit):
  305. def __init__(self, parent=None):
  306. super(EvalEntry, self).__init__(parent)
  307. self.readyToEdit = True
  308. def mousePressEvent(self, e, Parent=None):
  309. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  310. if self.readyToEdit:
  311. self.selectAll()
  312. self.readyToEdit = False
  313. def focusOutEvent(self, e):
  314. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  315. self.deselect()
  316. self.readyToEdit = True
  317. def returnPressed(self, *args, **kwargs):
  318. val = self.get_value()
  319. if val is not None:
  320. self.setText(str(val))
  321. else:
  322. log.warning("Could not interpret entry: %s" % self.get_text())
  323. def get_value(self):
  324. raw = str(self.text()).strip(' ')
  325. evaled = 0.0
  326. try:
  327. evaled = eval(raw)
  328. except:
  329. if evaled is not None:
  330. log.error("Could not evaluate: %s" % str(raw))
  331. return None
  332. return evaled
  333. def set_value(self, val):
  334. self.setText(str(val))
  335. def sizeHint(self):
  336. default_hint_size = super(EvalEntry, self).sizeHint()
  337. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  338. class EvalEntry2(QtWidgets.QLineEdit):
  339. def __init__(self, parent=None):
  340. super(EvalEntry2, self).__init__(parent)
  341. self.readyToEdit = True
  342. def mousePressEvent(self, e, Parent=None):
  343. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  344. if self.readyToEdit:
  345. self.selectAll()
  346. self.readyToEdit = False
  347. def focusOutEvent(self, e):
  348. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  349. self.deselect()
  350. self.readyToEdit = True
  351. def get_value(self):
  352. raw = str(self.text()).strip(' ')
  353. evaled = 0.0
  354. try:
  355. evaled = eval(raw)
  356. except:
  357. if evaled is not None:
  358. log.error("Could not evaluate: %s" % str(raw))
  359. return None
  360. return evaled
  361. def set_value(self, val):
  362. self.setText(str(val))
  363. def sizeHint(self):
  364. default_hint_size = super(EvalEntry2, self).sizeHint()
  365. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  366. class FCCheckBox(QtWidgets.QCheckBox):
  367. def __init__(self, label='', parent=None):
  368. super(FCCheckBox, self).__init__(str(label), parent)
  369. def get_value(self):
  370. return self.isChecked()
  371. def set_value(self, val):
  372. self.setChecked(val)
  373. def toggle(self):
  374. self.set_value(not self.get_value())
  375. class FCTextArea(QtWidgets.QPlainTextEdit):
  376. def __init__(self, parent=None):
  377. super(FCTextArea, self).__init__(parent)
  378. def set_value(self, val):
  379. self.setPlainText(val)
  380. def get_value(self):
  381. return str(self.toPlainText())
  382. def sizeHint(self):
  383. default_hint_size = super(FCTextArea, self).sizeHint()
  384. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  385. class FCTextAreaRich(QtWidgets.QTextEdit):
  386. def __init__(self, parent=None):
  387. super(FCTextAreaRich, self).__init__(parent)
  388. def set_value(self, val):
  389. self.setText(val)
  390. def get_value(self):
  391. return str(self.toPlainText())
  392. def sizeHint(self):
  393. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  394. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  395. class FCTextAreaExtended(QtWidgets.QTextEdit):
  396. def __init__(self, parent=None):
  397. super(FCTextAreaExtended, self).__init__(parent)
  398. self.completer = MyCompleter()
  399. self.model = QtCore.QStringListModel()
  400. self.completer.setModel(self.model)
  401. self.set_model_data(keyword_list=[])
  402. self.completer.insertText.connect(self.insertCompletion)
  403. self.completer_enable = False
  404. def set_model_data(self, keyword_list):
  405. self.model.setStringList(keyword_list)
  406. def insertCompletion(self, completion):
  407. tc = self.textCursor()
  408. extra = (len(completion) - len(self.completer.completionPrefix()))
  409. # don't insert if the word is finished but add a space instead
  410. if extra == 0:
  411. tc.insertText(' ')
  412. self.completer.popup().hide()
  413. return
  414. tc.movePosition(QTextCursor.Left)
  415. tc.movePosition(QTextCursor.EndOfWord)
  416. tc.insertText(completion[-extra:])
  417. # add a space after inserting the word
  418. tc.insertText(' ')
  419. self.setTextCursor(tc)
  420. self.completer.popup().hide()
  421. def focusInEvent(self, event):
  422. if self.completer:
  423. self.completer.setWidget(self)
  424. QTextEdit.focusInEvent(self, event)
  425. def set_value(self, val):
  426. self.setText(val)
  427. def get_value(self):
  428. self.toPlainText()
  429. def insertFromMimeData(self, data):
  430. """
  431. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  432. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  433. :param data:
  434. :return:
  435. """
  436. modifier = QtWidgets.QApplication.keyboardModifiers()
  437. if modifier == Qt.ShiftModifier:
  438. text = data.text()
  439. text = text.replace('\\', '/')
  440. self.insertPlainText(text)
  441. else:
  442. self.insertPlainText(data.text())
  443. def keyPressEvent(self, event):
  444. """
  445. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  446. :param event:
  447. :return:
  448. """
  449. key = event.key()
  450. modifier = QtWidgets.QApplication.keyboardModifiers()
  451. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  452. if key == QtCore.Qt.Key_V:
  453. clipboard = QtWidgets.QApplication.clipboard()
  454. clip_text = clipboard.text()
  455. clip_text = clip_text.replace('\\', '/')
  456. self.insertPlainText(clip_text)
  457. tc = self.textCursor()
  458. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  459. self.completer.insertText.emit(self.completer.getSelected())
  460. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  461. return
  462. elif key == Qt.Key_BraceLeft:
  463. tc.insertText('{}')
  464. self.moveCursor(QtGui.QTextCursor.Left)
  465. elif key == Qt.Key_BracketLeft:
  466. tc.insertText('[]')
  467. self.moveCursor(QtGui.QTextCursor.Left)
  468. elif key == Qt.Key_ParenLeft:
  469. tc.insertText('()')
  470. self.moveCursor(QtGui.QTextCursor.Left)
  471. elif key == Qt.Key_BraceRight:
  472. tc.select(QtGui.QTextCursor.WordUnderCursor)
  473. if tc.selectedText() == '}':
  474. tc.movePosition(QTextCursor.Right)
  475. self.setTextCursor(tc)
  476. else:
  477. tc.clearSelection()
  478. self.textCursor().insertText('}')
  479. elif key == Qt.Key_BracketRight:
  480. tc.select(QtGui.QTextCursor.WordUnderCursor)
  481. if tc.selectedText() == ']':
  482. tc.movePosition(QTextCursor.Right)
  483. self.setTextCursor(tc)
  484. else:
  485. tc.clearSelection()
  486. self.textCursor().insertText(']')
  487. elif key == Qt.Key_ParenRight:
  488. tc.select(QtGui.QTextCursor.WordUnderCursor)
  489. if tc.selectedText() == ')':
  490. tc.movePosition(QTextCursor.Right)
  491. self.setTextCursor(tc)
  492. else:
  493. tc.clearSelection()
  494. self.textCursor().insertText(')')
  495. else:
  496. super(FCTextAreaExtended, self).keyPressEvent(event)
  497. if self.completer_enable:
  498. tc.select(QTextCursor.WordUnderCursor)
  499. cr = self.cursorRect()
  500. if len(tc.selectedText()) > 0:
  501. self.completer.setCompletionPrefix(tc.selectedText())
  502. popup = self.completer.popup()
  503. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  504. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  505. + self.completer.popup().verticalScrollBar().sizeHint().width())
  506. self.completer.complete(cr)
  507. else:
  508. self.completer.popup().hide()
  509. class FCComboBox(QtWidgets.QComboBox):
  510. def __init__(self, parent=None, callback=None):
  511. super(FCComboBox, self).__init__(parent)
  512. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  513. self.view = self.view()
  514. self.view.viewport().installEventFilter(self)
  515. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  516. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  517. # pos = mouse right click click position
  518. # self = is the combobox object itself
  519. if callback:
  520. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  521. def eventFilter(self, obj, event):
  522. if event.type() == QtCore.QEvent.MouseButtonRelease:
  523. if event.button() == Qt.RightButton:
  524. return True
  525. return False
  526. def wheelEvent(self, *args, **kwargs):
  527. pass
  528. def get_value(self):
  529. return str(self.currentText())
  530. def set_value(self, val):
  531. self.setCurrentIndex(self.findText(str(val)))
  532. class FCInputDialog(QtWidgets.QInputDialog):
  533. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  534. init_val=None):
  535. super(FCInputDialog, self).__init__(parent)
  536. self.allow_empty = ok
  537. self.empty_val = val
  538. self.val = 0.0
  539. self.ok = ''
  540. self.init_value = init_val if init_val else 0.0
  541. if title is None:
  542. self.title = 'title'
  543. else:
  544. self.title = title
  545. if text is None:
  546. self.text = 'text'
  547. else:
  548. self.text = text
  549. if min is None:
  550. self.min = 0
  551. else:
  552. self.min = min
  553. if max is None:
  554. self.max = 0
  555. else:
  556. self.max = max
  557. if decimals is None:
  558. self.decimals = 6
  559. else:
  560. self.decimals = decimals
  561. def get_value(self):
  562. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  563. max=self.max, decimals=self.decimals, value=self.init_value)
  564. return [self.val, self.ok]
  565. # "Transform", "Enter the Angle value:"
  566. def set_value(self, val):
  567. pass
  568. class FCButton(QtWidgets.QPushButton):
  569. def __init__(self, parent=None):
  570. super(FCButton, self).__init__(parent)
  571. def get_value(self):
  572. return self.isChecked()
  573. def set_value(self, val):
  574. self.setText(str(val))
  575. class FCMenu(QtWidgets.QMenu):
  576. def __init__(self):
  577. super().__init__()
  578. self.mouse_is_panning = False
  579. def popup(self, pos, action=None):
  580. self.mouse_is_panning = False
  581. super().popup(pos)
  582. class FCTab(QtWidgets.QTabWidget):
  583. def __init__(self, parent=None):
  584. super(FCTab, self).__init__(parent)
  585. self.setTabsClosable(True)
  586. self.tabCloseRequested.connect(self.closeTab)
  587. def deleteTab(self, currentIndex):
  588. widget = self.widget(currentIndex)
  589. if widget is not None:
  590. widget.deleteLater()
  591. self.removeTab(currentIndex)
  592. def closeTab(self, currentIndex):
  593. self.removeTab(currentIndex)
  594. def protectTab(self, currentIndex):
  595. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  596. class FCDetachableTab(QtWidgets.QTabWidget):
  597. """
  598. From here:
  599. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  600. """
  601. def __init__(self, protect=None, protect_by_name=None, parent=None):
  602. super().__init__()
  603. self.tabBar = self.FCTabBar(self)
  604. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  605. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  606. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  607. self.setTabBar(self.tabBar)
  608. # Used to keep a reference to detached tabs since their QMainWindow
  609. # does not have a parent
  610. self.detachedTabs = {}
  611. # a way to make sure that tabs can't be closed after they attach to the parent tab
  612. self.protect_tab = True if protect is not None and protect is True else False
  613. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  614. # Close all detached tabs if the application is closed explicitly
  615. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  616. # used by the property self.useOldIndex(param)
  617. self.use_old_index = None
  618. self.old_index = None
  619. self.setTabsClosable(True)
  620. self.tabCloseRequested.connect(self.closeTab)
  621. def useOldIndex(self, param):
  622. if param:
  623. self.use_old_index = True
  624. else:
  625. self.use_old_index = False
  626. def deleteTab(self, currentIndex):
  627. widget = self.widget(currentIndex)
  628. if widget is not None:
  629. widget.deleteLater()
  630. self.removeTab(currentIndex)
  631. def closeTab(self, currentIndex):
  632. """
  633. Slot connected to the tabCloseRequested signal
  634. :param currentIndex:
  635. :return:
  636. """
  637. self.removeTab(currentIndex)
  638. def protectTab(self, currentIndex):
  639. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  640. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  641. def setMovable(self, movable):
  642. """
  643. The default movable functionality of QTabWidget must remain disabled
  644. so as not to conflict with the added features
  645. :param movable:
  646. :return:
  647. """
  648. pass
  649. @pyqtSlot(int, int)
  650. def moveTab(self, fromIndex, toIndex):
  651. """
  652. Move a tab from one position (index) to another
  653. :param fromIndex: the original index location of the tab
  654. :param toIndex: the new index location of the tab
  655. :return:
  656. """
  657. widget = self.widget(fromIndex)
  658. icon = self.tabIcon(fromIndex)
  659. text = self.tabText(fromIndex)
  660. self.removeTab(fromIndex)
  661. self.insertTab(toIndex, widget, icon, text)
  662. self.setCurrentIndex(toIndex)
  663. @pyqtSlot(int, QtCore.QPoint)
  664. def detachTab(self, index, point):
  665. """
  666. Detach the tab by removing it's contents and placing them in
  667. a DetachedTab window
  668. :param index: the index location of the tab to be detached
  669. :param point: the screen position for creating the new DetachedTab window
  670. :return:
  671. """
  672. self.old_index = index
  673. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  674. name = "FlatCAM " + self.tabText(index)
  675. icon = self.tabIcon(index)
  676. if icon.isNull():
  677. icon = self.window().windowIcon()
  678. contentWidget = self.widget(index)
  679. try:
  680. contentWidgetRect = contentWidget.frameGeometry()
  681. except AttributeError:
  682. return
  683. # Create a new detached tab window
  684. detachedTab = self.FCDetachedTab(name, contentWidget)
  685. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  686. detachedTab.setWindowIcon(icon)
  687. detachedTab.setGeometry(contentWidgetRect)
  688. detachedTab.onCloseSignal.connect(self.attachTab)
  689. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  690. detachedTab.move(point)
  691. detachedTab.show()
  692. # Create a reference to maintain access to the detached tab
  693. self.detachedTabs[name] = detachedTab
  694. def attachTab(self, contentWidget, name, icon, insertAt=None):
  695. """
  696. Re-attach the tab by removing the content from the DetachedTab window,
  697. closing it, and placing the content back into the DetachableTabWidget
  698. :param contentWidget: the content widget from the DetachedTab window
  699. :param name: the name of the detached tab
  700. :param icon: the window icon for the detached tab
  701. :param insertAt: insert the re-attached tab at the given index
  702. :return:
  703. """
  704. # Make the content widget a child of this widget
  705. contentWidget.setParent(self)
  706. # Remove the reference
  707. del self.detachedTabs[name]
  708. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  709. name = name.partition(' ')[2]
  710. # helps in restoring the tab to the same index that it was before was detached
  711. insert_index = self.old_index if self.use_old_index is True else insertAt
  712. # Create an image from the given icon (for comparison)
  713. if not icon.isNull():
  714. try:
  715. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  716. tabIconImage = tabIconPixmap.toImage()
  717. except IndexError:
  718. tabIconImage = None
  719. else:
  720. tabIconImage = None
  721. # Create an image of the main window icon (for comparison)
  722. if not icon.isNull():
  723. try:
  724. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  725. windowIconImage = windowIconPixmap.toImage()
  726. except IndexError:
  727. windowIconImage = None
  728. else:
  729. windowIconImage = None
  730. # Determine if the given image and the main window icon are the same.
  731. # If they are, then do not add the icon to the tab
  732. if tabIconImage == windowIconImage:
  733. if insert_index is None:
  734. index = self.addTab(contentWidget, name)
  735. else:
  736. index = self.insertTab(insert_index, contentWidget, name)
  737. else:
  738. if insert_index is None:
  739. index = self.addTab(contentWidget, icon, name)
  740. else:
  741. index = self.insertTab(insert_index, contentWidget, icon, name)
  742. # on reattaching the tab if protect is true then the closure button is not added
  743. if self.protect_tab is True:
  744. self.protectTab(index)
  745. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  746. if self.protect_by_name is not None:
  747. for tab_name in self.protect_by_name:
  748. for index in range(self.count()):
  749. if str(tab_name) == str(self.tabText(index)):
  750. self.protectTab(index)
  751. # Make this tab the current tab
  752. if index > -1:
  753. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  754. def removeTabByName(self, name):
  755. """
  756. Remove the tab with the given name, even if it is detached
  757. :param name: the name of the tab to be removed
  758. :return:
  759. """
  760. # Remove the tab if it is attached
  761. attached = False
  762. for index in range(self.count()):
  763. if str(name) == str(self.tabText(index)):
  764. self.removeTab(index)
  765. attached = True
  766. break
  767. # If the tab is not attached, close it's window and
  768. # remove the reference to it
  769. if not attached:
  770. for key in self.detachedTabs:
  771. if str(name) == str(key):
  772. self.detachedTabs[key].onCloseSignal.disconnect()
  773. self.detachedTabs[key].close()
  774. del self.detachedTabs[key]
  775. break
  776. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  777. def detachedTabDrop(self, name, index, dropPos):
  778. """
  779. Handle dropping of a detached tab inside the DetachableTabWidget
  780. :param name: the name of the detached tab
  781. :param index: the index of an existing tab (if the tab bar
  782. # determined that the drop occurred on an
  783. # existing tab)
  784. :param dropPos: the mouse cursor position when the drop occurred
  785. :return:
  786. """
  787. # If the drop occurred on an existing tab, insert the detached
  788. # tab at the existing tab's location
  789. if index > -1:
  790. # Create references to the detached tab's content and icon
  791. contentWidget = self.detachedTabs[name].contentWidget
  792. icon = self.detachedTabs[name].windowIcon()
  793. # Disconnect the detached tab's onCloseSignal so that it
  794. # does not try to re-attach automatically
  795. self.detachedTabs[name].onCloseSignal.disconnect()
  796. # Close the detached
  797. self.detachedTabs[name].close()
  798. # Re-attach the tab at the given index
  799. self.attachTab(contentWidget, name, icon, index)
  800. # If the drop did not occur on an existing tab, determine if the drop
  801. # occurred in the tab bar area (the area to the side of the QTabBar)
  802. else:
  803. # Find the drop position relative to the DetachableTabWidget
  804. tabDropPos = self.mapFromGlobal(dropPos)
  805. # If the drop position is inside the DetachableTabWidget...
  806. if self.rect().contains(tabDropPos):
  807. # If the drop position is inside the tab bar area (the
  808. # area to the side of the QTabBar) or there are not tabs
  809. # currently attached...
  810. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  811. # Close the detached tab and allow it to re-attach
  812. # automatically
  813. self.detachedTabs[name].close()
  814. def closeDetachedTabs(self):
  815. """
  816. Close all tabs that are currently detached.
  817. :return:
  818. """
  819. listOfDetachedTabs = []
  820. for key in self.detachedTabs:
  821. listOfDetachedTabs.append(self.detachedTabs[key])
  822. for detachedTab in listOfDetachedTabs:
  823. detachedTab.close()
  824. class FCDetachedTab(QtWidgets.QMainWindow):
  825. """
  826. When a tab is detached, the contents are placed into this QMainWindow. The tab
  827. can be re-attached by closing the dialog or by dragging the window into the tab bar
  828. """
  829. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  830. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  831. def __init__(self, name, contentWidget):
  832. QtWidgets.QMainWindow.__init__(self, None)
  833. self.setObjectName(name)
  834. self.setWindowTitle(name)
  835. self.contentWidget = contentWidget
  836. self.setCentralWidget(self.contentWidget)
  837. self.contentWidget.show()
  838. self.windowDropFilter = self.WindowDropFilter()
  839. self.installEventFilter(self.windowDropFilter)
  840. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  841. @QtCore.pyqtSlot(QtCore.QPoint)
  842. def windowDropSlot(self, dropPos):
  843. """
  844. Handle a window drop event
  845. :param dropPos: the mouse cursor position of the drop
  846. :return:
  847. """
  848. self.onDropSignal.emit(self.objectName(), dropPos)
  849. def closeEvent(self, event):
  850. """
  851. If the window is closed, emit the onCloseSignal and give the
  852. content widget back to the DetachableTabWidget
  853. :param event: a close event
  854. :return:
  855. """
  856. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  857. class WindowDropFilter(QtCore.QObject):
  858. """
  859. An event filter class to detect a QMainWindow drop event
  860. """
  861. onDropSignal = pyqtSignal(QtCore.QPoint)
  862. def __init__(self):
  863. QtCore.QObject.__init__(self)
  864. self.lastEvent = None
  865. def eventFilter(self, obj, event):
  866. """
  867. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  868. event that immediately follows a Move event
  869. :param obj: the object that generated the event
  870. :param event: the current event
  871. :return:
  872. """
  873. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  874. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  875. # Determine the position of the mouse cursor and emit it with the
  876. # onDropSignal
  877. mouseCursor = QtGui.QCursor()
  878. dropPos = mouseCursor.pos()
  879. self.onDropSignal.emit(dropPos)
  880. self.lastEvent = event.type()
  881. return True
  882. else:
  883. self.lastEvent = event.type()
  884. return False
  885. class FCTabBar(QtWidgets.QTabBar):
  886. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  887. onMoveTabSignal = pyqtSignal(int, int)
  888. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  889. def __init__(self, parent=None):
  890. QtWidgets.QTabBar.__init__(self, parent)
  891. self.setAcceptDrops(True)
  892. self.setElideMode(QtCore.Qt.ElideRight)
  893. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  894. self.dragStartPos = QtCore.QPoint()
  895. self.dragDropedPos = QtCore.QPoint()
  896. self.mouseCursor = QtGui.QCursor()
  897. self.dragInitiated = False
  898. def mouseDoubleClickEvent(self, event):
  899. """
  900. Send the onDetachTabSignal when a tab is double clicked
  901. :param event: a mouse double click event
  902. :return:
  903. """
  904. event.accept()
  905. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  906. def mousePressEvent(self, event):
  907. """
  908. Set the starting position for a drag event when the mouse button is pressed
  909. :param event: a mouse press event
  910. :return:
  911. """
  912. if event.button() == QtCore.Qt.LeftButton:
  913. self.dragStartPos = event.pos()
  914. self.dragDropedPos.setX(0)
  915. self.dragDropedPos.setY(0)
  916. self.dragInitiated = False
  917. QtWidgets.QTabBar.mousePressEvent(self, event)
  918. def mouseMoveEvent(self, event):
  919. """
  920. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  921. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  922. bar, emit an onDetachTabSignal.
  923. :param event: a mouse move event
  924. :return:
  925. """
  926. # Determine if the current movement is detected as a drag
  927. if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  928. self.dragInitiated = True
  929. # If the current movement is a drag initiated by the left button
  930. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):
  931. # Stop the move event
  932. finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
  933. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  934. # Convert the move event into a drag
  935. drag = QtGui.QDrag(self)
  936. mimeData = QtCore.QMimeData()
  937. # mimeData.setData('action', 'application/tab-detach')
  938. drag.setMimeData(mimeData)
  939. # screen = QScreen(self.parentWidget().currentWidget().winId())
  940. # Create the appearance of dragging the tab content
  941. try:
  942. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  943. except Exception as e:
  944. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  945. return
  946. targetPixmap = QtGui.QPixmap(pixmap.size())
  947. targetPixmap.fill(QtCore.Qt.transparent)
  948. painter = QtGui.QPainter(targetPixmap)
  949. painter.setOpacity(0.85)
  950. painter.drawPixmap(0, 0, pixmap)
  951. painter.end()
  952. drag.setPixmap(targetPixmap)
  953. # Initiate the drag
  954. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  955. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  956. # must be set manually
  957. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  958. dropAction = QtCore.Qt.MoveAction
  959. # If the drag completed outside of the tab bar, detach the tab and move
  960. # the content to the current cursor position
  961. if dropAction == QtCore.Qt.IgnoreAction:
  962. event.accept()
  963. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  964. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  965. elif dropAction == QtCore.Qt.MoveAction:
  966. if not self.dragDropedPos.isNull():
  967. event.accept()
  968. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  969. else:
  970. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  971. def dragEnterEvent(self, event):
  972. """
  973. Determine if the drag has entered a tab position from another tab position
  974. :param event: a drag enter event
  975. :return:
  976. """
  977. mimeData = event.mimeData()
  978. # formats = mcd imeData.formats()
  979. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  980. # event.acceptProposedAction()
  981. QtWidgets.QTabBar.dragMoveEvent(self, event)
  982. def dropEvent(self, event):
  983. """
  984. Get the position of the end of the drag
  985. :param event: a drop event
  986. :return:
  987. """
  988. self.dragDropedPos = event.pos()
  989. QtWidgets.QTabBar.dropEvent(self, event)
  990. def detachedTabDrop(self, name, dropPos):
  991. """
  992. Determine if the detached tab drop event occurred on an existing tab,
  993. then send the event to the DetachableTabWidget
  994. :param name:
  995. :param dropPos:
  996. :return:
  997. """
  998. tabDropPos = self.mapFromGlobal(dropPos)
  999. index = self.tabAt(tabDropPos)
  1000. self.detachedTabDropSignal.emit(name, index, dropPos)
  1001. class VerticalScrollArea(QtWidgets.QScrollArea):
  1002. """
  1003. This widget extends QtGui.QScrollArea to make a vertical-only
  1004. scroll area that also expands horizontally to accomodate
  1005. its contents.
  1006. """
  1007. def __init__(self, parent=None):
  1008. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1009. self.setWidgetResizable(True)
  1010. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1011. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1012. def eventFilter(self, source, event):
  1013. """
  1014. The event filter gets automatically installed when setWidget()
  1015. is called.
  1016. :param source:
  1017. :param event:
  1018. :return:
  1019. """
  1020. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1021. # log.debug("VerticalScrollArea: Widget resized:")
  1022. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1023. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1024. self.setMinimumWidth(self.widget().sizeHint().width() +
  1025. self.verticalScrollBar().sizeHint().width())
  1026. # if self.verticalScrollBar().isVisible():
  1027. # log.debug(" Scroll bar visible")
  1028. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1029. # self.verticalScrollBar().width())
  1030. # else:
  1031. # log.debug(" Scroll bar hidden")
  1032. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1033. return QtWidgets.QWidget.eventFilter(self, source, event)
  1034. class OptionalInputSection:
  1035. def __init__(self, cb, optinputs, logic=True):
  1036. """
  1037. Associates the a checkbox with a set of inputs.
  1038. :param cb: Checkbox that enables the optional inputs.
  1039. :param optinputs: List of widgets that are optional.
  1040. :param logic: When True the logic is normal, when False the logic is in reverse
  1041. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1042. for logic=False, when the checkbox is checked the widgets are Disabled
  1043. :return:
  1044. """
  1045. assert isinstance(cb, FCCheckBox), \
  1046. "Expected an FCCheckBox, got %s" % type(cb)
  1047. self.cb = cb
  1048. self.optinputs = optinputs
  1049. self.logic = logic
  1050. self.on_cb_change()
  1051. self.cb.stateChanged.connect(self.on_cb_change)
  1052. def on_cb_change(self):
  1053. if self.cb.checkState():
  1054. for widget in self.optinputs:
  1055. if self.logic is True:
  1056. widget.setEnabled(True)
  1057. else:
  1058. widget.setEnabled(False)
  1059. else:
  1060. for widget in self.optinputs:
  1061. if self.logic is True:
  1062. widget.setEnabled(False)
  1063. else:
  1064. widget.setEnabled(True)
  1065. class FCTable(QtWidgets.QTableWidget):
  1066. def __init__(self, parent=None):
  1067. super(FCTable, self).__init__(parent)
  1068. def sizeHint(self):
  1069. default_hint_size = super(FCTable, self).sizeHint()
  1070. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1071. def getHeight(self):
  1072. height = self.horizontalHeader().height()
  1073. for i in range(self.rowCount()):
  1074. height += self.rowHeight(i)
  1075. return height
  1076. def getWidth(self):
  1077. width = self.verticalHeader().width()
  1078. for i in range(self.columnCount()):
  1079. width += self.columnWidth(i)
  1080. return width
  1081. # color is in format QtGui.Qcolor(r, g, b, alfa) with or without alfa
  1082. def setColortoRow(self, rowIndex, color):
  1083. for j in range(self.columnCount()):
  1084. self.item(rowIndex, j).setBackground(color)
  1085. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1086. def mousePressEvent(self, event):
  1087. if self.itemAt(event.pos()) is None:
  1088. self.clearSelection()
  1089. else:
  1090. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1091. def setupContextMenu(self):
  1092. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1093. def addContextMenu(self, entry, call_function, icon=None):
  1094. action_name = str(entry)
  1095. action = QtWidgets.QAction(self)
  1096. action.setText(action_name)
  1097. if icon:
  1098. assert isinstance(icon, QtGui.QIcon), \
  1099. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1100. action.setIcon(icon)
  1101. self.addAction(action)
  1102. action.triggered.connect(call_function)
  1103. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  1104. def __init__(self, units):
  1105. super(SpinBoxDelegate, self).__init__()
  1106. self.units = units
  1107. self.current_value = None
  1108. def createEditor(self, parent, option, index):
  1109. editor = QtWidgets.QDoubleSpinBox(parent)
  1110. editor.setMinimum(-999.9999)
  1111. editor.setMaximum(999.9999)
  1112. if self.units == 'MM':
  1113. editor.setDecimals(2)
  1114. else:
  1115. editor.setDecimals(3)
  1116. return editor
  1117. def setEditorData(self, spinBox, index):
  1118. try:
  1119. value = float(index.model().data(index, Qt.EditRole))
  1120. except ValueError:
  1121. value = self.current_value
  1122. # return
  1123. spinBox.setValue(value)
  1124. def setModelData(self, spinBox, model, index):
  1125. spinBox.interpretText()
  1126. value = spinBox.value()
  1127. self.current_value = value
  1128. model.setData(index, value, Qt.EditRole)
  1129. def updateEditorGeometry(self, editor, option, index):
  1130. editor.setGeometry(option.rect)
  1131. def setDecimals(self, spinbox, digits):
  1132. spinbox.setDecimals(digits)
  1133. class FCSpinner(QtWidgets.QSpinBox):
  1134. def __init__(self, parent=None):
  1135. super(FCSpinner, self).__init__(parent)
  1136. self.readyToEdit = True
  1137. def mousePressEvent(self, e, parent=None):
  1138. super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  1139. if self.readyToEdit:
  1140. self.lineEdit().selectAll()
  1141. self.readyToEdit = False
  1142. def focusOutEvent(self, e):
  1143. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  1144. self.lineEdit().deselect()
  1145. self.readyToEdit = True
  1146. def get_value(self):
  1147. return str(self.value())
  1148. def set_value(self, val):
  1149. try:
  1150. k = int(val)
  1151. except Exception as e:
  1152. log.debug(str(e))
  1153. return
  1154. self.setValue(k)
  1155. def set_range(self, min_val, max_val):
  1156. self.setRange(min_val, max_val)
  1157. # def sizeHint(self):
  1158. # default_hint_size = super(FCSpinner, self).sizeHint()
  1159. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1160. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  1161. def __init__(self, parent=None):
  1162. super(FCDoubleSpinner, self).__init__(parent)
  1163. self.readyToEdit = True
  1164. def mousePressEvent(self, e, parent=None):
  1165. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  1166. if self.readyToEdit:
  1167. self.lineEdit().selectAll()
  1168. self.readyToEdit = False
  1169. def focusOutEvent(self, e):
  1170. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  1171. self.lineEdit().deselect()
  1172. self.readyToEdit = True
  1173. def get_value(self):
  1174. return str(self.value())
  1175. def set_value(self, val):
  1176. try:
  1177. k = int(val)
  1178. except Exception as e:
  1179. log.debug(str(e))
  1180. return
  1181. self.setValue(k)
  1182. def set_precision(self, val):
  1183. self.setDecimals(val)
  1184. def set_range(self, min_val, max_val):
  1185. self.setRange(min_val, max_val)
  1186. class Dialog_box(QtWidgets.QWidget):
  1187. def __init__(self, title=None, label=None, icon=None):
  1188. """
  1189. :param title: string with the window title
  1190. :param label: string with the message inside the dialog box
  1191. """
  1192. super(Dialog_box, self).__init__()
  1193. self.location = (0, 0)
  1194. self.ok = False
  1195. dialog_box = QtWidgets.QInputDialog()
  1196. dialog_box.setFixedWidth(290)
  1197. self.setWindowIcon(icon)
  1198. self.location, self.ok = dialog_box.getText(self, title, label, text="0, 0")
  1199. self.readyToEdit = True
  1200. def mousePressEvent(self, e, parent=None):
  1201. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  1202. if self.readyToEdit:
  1203. self.lineEdit().selectAll()
  1204. self.readyToEdit = False
  1205. def focusOutEvent(self, e):
  1206. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  1207. self.lineEdit().deselect()
  1208. self.readyToEdit = True
  1209. class _BrowserTextEdit(QTextEdit):
  1210. def __init__(self, version):
  1211. QTextEdit.__init__(self)
  1212. self.menu = None
  1213. self.version = version
  1214. def contextMenuEvent(self, event):
  1215. self.menu = self.createStandardContextMenu(event.pos())
  1216. clear_action = QAction("Clear", self)
  1217. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  1218. self.menu.addAction(clear_action)
  1219. clear_action.triggered.connect(self.clear)
  1220. self.menu.exec_(event.globalPos())
  1221. def clear(self):
  1222. QTextEdit.clear(self)
  1223. text = "FlatCAM %s (c)2014-2019 Juan Pablo Caram (Type help to get started)\n\n" % self.version
  1224. text = html.escape(text)
  1225. text = text.replace('\n', '<br/>')
  1226. self.moveCursor(QTextCursor.End)
  1227. self.insertHtml(text)
  1228. class _ExpandableTextEdit(QTextEdit):
  1229. """
  1230. Class implements edit line, which expands themselves automatically
  1231. """
  1232. historyNext = pyqtSignal()
  1233. historyPrev = pyqtSignal()
  1234. def __init__(self, termwidget, *args):
  1235. QTextEdit.__init__(self, *args)
  1236. self.setStyleSheet("font: 9pt \"Courier\";")
  1237. self._fittedHeight = 1
  1238. self.textChanged.connect(self._fit_to_document)
  1239. self._fit_to_document()
  1240. self._termWidget = termwidget
  1241. self.completer = MyCompleter()
  1242. self.model = QtCore.QStringListModel()
  1243. self.completer.setModel(self.model)
  1244. self.set_model_data(keyword_list=[])
  1245. self.completer.insertText.connect(self.insertCompletion)
  1246. def set_model_data(self, keyword_list):
  1247. self.model.setStringList(keyword_list)
  1248. def insertCompletion(self, completion):
  1249. tc = self.textCursor()
  1250. extra = (len(completion) - len(self.completer.completionPrefix()))
  1251. # don't insert if the word is finished but add a space instead
  1252. if extra == 0:
  1253. tc.insertText(' ')
  1254. self.completer.popup().hide()
  1255. return
  1256. tc.movePosition(QTextCursor.Left)
  1257. tc.movePosition(QTextCursor.EndOfWord)
  1258. tc.insertText(completion[-extra:])
  1259. # add a space after inserting the word
  1260. tc.insertText(' ')
  1261. self.setTextCursor(tc)
  1262. self.completer.popup().hide()
  1263. def focusInEvent(self, event):
  1264. if self.completer:
  1265. self.completer.setWidget(self)
  1266. QTextEdit.focusInEvent(self, event)
  1267. def keyPressEvent(self, event):
  1268. """
  1269. Catch keyboard events. Process Enter, Up, Down
  1270. """
  1271. key = event.key()
  1272. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  1273. self.completer.insertText.emit(self.completer.getSelected())
  1274. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1275. return
  1276. if event.matches(QKeySequence.InsertParagraphSeparator):
  1277. text = self.toPlainText()
  1278. if self._termWidget.is_command_complete(text):
  1279. self._termWidget.exec_current_command()
  1280. return
  1281. elif event.matches(QKeySequence.MoveToNextLine):
  1282. text = self.toPlainText()
  1283. cursor_pos = self.textCursor().position()
  1284. textBeforeEnd = text[cursor_pos:]
  1285. if len(textBeforeEnd.split('\n')) <= 1:
  1286. self.historyNext.emit()
  1287. return
  1288. elif event.matches(QKeySequence.MoveToPreviousLine):
  1289. text = self.toPlainText()
  1290. cursor_pos = self.textCursor().position()
  1291. text_before_start = text[:cursor_pos]
  1292. # lineCount = len(textBeforeStart.splitlines())
  1293. line_count = len(text_before_start.split('\n'))
  1294. if len(text_before_start) > 0 and \
  1295. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1296. line_count += 1
  1297. if line_count <= 1:
  1298. self.historyPrev.emit()
  1299. return
  1300. elif event.matches(QKeySequence.MoveToNextPage) or \
  1301. event.matches(QKeySequence.MoveToPreviousPage):
  1302. return self._termWidget.browser().keyPressEvent(event)
  1303. tc = self.textCursor()
  1304. QTextEdit.keyPressEvent(self, event)
  1305. tc.select(QTextCursor.WordUnderCursor)
  1306. cr = self.cursorRect()
  1307. if len(tc.selectedText()) > 0:
  1308. self.completer.setCompletionPrefix(tc.selectedText())
  1309. popup = self.completer.popup()
  1310. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1311. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1312. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1313. self.completer.complete(cr)
  1314. else:
  1315. self.completer.popup().hide()
  1316. def sizeHint(self):
  1317. """
  1318. QWidget sizeHint impelemtation
  1319. """
  1320. hint = QTextEdit.sizeHint(self)
  1321. hint.setHeight(self._fittedHeight)
  1322. return hint
  1323. def _fit_to_document(self):
  1324. """
  1325. Update widget height to fit all text
  1326. """
  1327. documentsize = self.document().size().toSize()
  1328. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1329. self.setMaximumHeight(self._fittedHeight)
  1330. self.updateGeometry()
  1331. def insertFromMimeData(self, mime_data):
  1332. # Paste only plain text.
  1333. self.insertPlainText(mime_data.text())
  1334. class MyCompleter(QCompleter):
  1335. insertText = pyqtSignal(str)
  1336. def __init__(self, parent=None):
  1337. QCompleter.__init__(self)
  1338. self.setCompletionMode(QCompleter.PopupCompletion)
  1339. self.highlighted.connect(self.setHighlighted)
  1340. def setHighlighted(self, text):
  1341. self.lastSelected = text
  1342. def getSelected(self):
  1343. return self.lastSelected