GUIElements.py 136 KB

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