GUIElements.py 93 KB

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