GUIElements.py 162 KB

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