GUIElements.py 116 KB

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