GUIElements.py 85 KB

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