GUIElements.py 73 KB

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