GUIElements.py 61 KB

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