GUIElements.py 159 KB

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