GUIElements.py 71 KB

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