GUIElements.py 86 KB

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