GUIElements.py 155 KB

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