GUIElements.py 92 KB

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