GUIElements.py 137 KB

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