GUIElements.py 116 KB

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