GUIElements.py 102 KB

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