GUIElements.py 153 KB

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