GUIElements.py 150 KB

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