GUIElements.py 135 KB

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