GUIElements.py 112 KB

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