GUIElements.py 135 KB

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