GUIElements.py 162 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699
  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):
  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. sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred)
  1668. self.setSizePolicy(sizePolicy)
  1669. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  1670. # pos = mouse right click click position
  1671. # self = is the combobox object itself
  1672. if callback:
  1673. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  1674. def eventFilter(self, obj, event):
  1675. if event.type() == QtCore.QEvent.MouseButtonRelease:
  1676. if event.button() == Qt.RightButton:
  1677. return True
  1678. return False
  1679. def wheelEvent(self, *args, **kwargs):
  1680. pass
  1681. def get_value(self):
  1682. return str(self.currentText())
  1683. def set_value(self, val):
  1684. idx = self.findText(str(val))
  1685. if idx == -1:
  1686. self.setCurrentIndex(0)
  1687. return
  1688. self.setCurrentIndex(idx)
  1689. @property
  1690. def is_last(self):
  1691. return self._set_last
  1692. @is_last.setter
  1693. def is_last(self, val):
  1694. self._set_last = val
  1695. if self._set_last is True:
  1696. self.model().rowsInserted.connect(self.on_model_changed)
  1697. self.setCurrentIndex(1)
  1698. @property
  1699. def obj_type(self):
  1700. return self._obj_type
  1701. @obj_type.setter
  1702. def obj_type(self, val):
  1703. self._obj_type = val
  1704. def on_model_changed(self, parent, first, last):
  1705. if self.model().data(parent, QtCore.Qt.DisplayRole) == self.obj_type:
  1706. self.setCurrentIndex(first)
  1707. class FCComboBox2(FCComboBox):
  1708. def __init__(self, parent=None, callback=None):
  1709. super(FCComboBox2, self).__init__(parent=parent, callback=callback)
  1710. def get_value(self):
  1711. return int(self.currentIndex())
  1712. def set_value(self, val):
  1713. self.setCurrentIndex(val)
  1714. class FCInputDialog(QtWidgets.QInputDialog):
  1715. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  1716. init_val=None):
  1717. super(FCInputDialog, self).__init__(parent)
  1718. self.allow_empty = ok
  1719. self.empty_val = val
  1720. self.val = 0.0
  1721. self.ok = ''
  1722. self.init_value = init_val if init_val else 0.0
  1723. if title is None:
  1724. self.title = 'title'
  1725. else:
  1726. self.title = title
  1727. if text is None:
  1728. self.text = 'text'
  1729. else:
  1730. self.text = text
  1731. if min is None:
  1732. self.min = 0
  1733. else:
  1734. self.min = min
  1735. if max is None:
  1736. self.max = 0
  1737. else:
  1738. self.max = max
  1739. if decimals is None:
  1740. self.decimals = 6
  1741. else:
  1742. self.decimals = decimals
  1743. def get_value(self):
  1744. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  1745. max=self.max, decimals=self.decimals, value=self.init_value)
  1746. return [self.val, self.ok]
  1747. # "Transform", "Enter the Angle value:"
  1748. def set_value(self, val):
  1749. pass
  1750. class FCInputDoubleSpinner(QtWidgets.QDialog):
  1751. def __init__(self, parent=None, title=None, text=None,
  1752. min=0.0, max=100.0000, step=1, decimals=4, init_val=None):
  1753. super(FCInputDoubleSpinner, self).__init__(parent)
  1754. self.val = 0.0
  1755. self.init_value = init_val if init_val else 0.0
  1756. self.setWindowTitle(title) if title else self.setWindowTitle('title')
  1757. self.text = text if text else 'text'
  1758. self.min = min
  1759. self.max = max
  1760. self.step = step
  1761. self.decimals = decimals
  1762. self.lbl = FCLabel(self.text)
  1763. if title is None:
  1764. self.title = 'title'
  1765. else:
  1766. self.title = title
  1767. if text is None:
  1768. self.text = 'text'
  1769. else:
  1770. self.text = text
  1771. self.wdg = FCDoubleSpinner()
  1772. self.wdg.set_value(self.init_value)
  1773. QBtn = QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
  1774. self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
  1775. self.buttonBox.accepted.connect(self.accept)
  1776. self.buttonBox.rejected.connect(self.reject)
  1777. self.layout = QtWidgets.QVBoxLayout()
  1778. self.layout.addWidget(self.lbl)
  1779. self.layout.addWidget(self.wdg)
  1780. self.layout.addWidget(self.buttonBox)
  1781. self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText(_("Ok"))
  1782. self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText(_("Cancel"))
  1783. self.setLayout(self.layout)
  1784. def set_title(self, txt):
  1785. self.setWindowTitle(txt)
  1786. def set_text(self, txt):
  1787. self.lbl.set_value(txt)
  1788. def set_icon(self, icon):
  1789. self.setWindowIcon(icon)
  1790. def set_min(self, val):
  1791. self.wdg.setMinimum(val)
  1792. def set_max(self, val):
  1793. self.wdg.setMaximum(val)
  1794. def set_range(self, min, max):
  1795. self.wdg.set_range(min, max)
  1796. def set_step(self, val):
  1797. self.wdg.set_step(val)
  1798. def set_value(self, val):
  1799. self.wdg.set_value(val)
  1800. def get_value(self):
  1801. if self.exec_() == QtWidgets.QDialog.Accepted:
  1802. return self.wdg.get_value(), True
  1803. else:
  1804. return None, False
  1805. class FCInputSpinner(QtWidgets.QDialog):
  1806. def __init__(self, parent=None, title=None, text=None, min=None, max=None, decimals=4, step=1, init_val=None):
  1807. super().__init__(parent)
  1808. self.val = 0.0
  1809. self.ok = ''
  1810. self.init_value = init_val if init_val else 0.0
  1811. self.setWindowTitle(title) if title else self.setWindowTitle('title')
  1812. self.text = text if text else 'text'
  1813. self.min = min if min else 0
  1814. self.max = max if max else 255
  1815. self.step = step if step else 1
  1816. self.lbl = FCLabel(self.text)
  1817. self.wdg = FCDoubleSpinner()
  1818. self.wdg.set_value(self.init_value)
  1819. self.wdg.set_range(self.min, self.max)
  1820. self.wdg.set_step(self.step)
  1821. self.wdg.set_precision(decimals)
  1822. sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
  1823. self.wdg.setSizePolicy(sizePolicy)
  1824. QBtn = QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
  1825. self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
  1826. self.buttonBox.accepted.connect(self.accept)
  1827. self.buttonBox.rejected.connect(self.reject)
  1828. self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText(_("Ok"))
  1829. self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText(_("Cancel"))
  1830. self.layout = QtWidgets.QVBoxLayout()
  1831. self.layout.addWidget(self.lbl)
  1832. self.layout.addWidget(self.wdg)
  1833. self.layout.addWidget(self.buttonBox)
  1834. self.setLayout(self.layout)
  1835. def set_title(self, txt):
  1836. self.setWindowTitle(txt)
  1837. def set_text(self, txt):
  1838. self.lbl.set_value(txt)
  1839. def set_min(self, val):
  1840. self.wdg.spinner.setMinimum(val)
  1841. def set_max(self, val):
  1842. self.wdg.spinner.setMaximum(val)
  1843. def set_range(self, min, max):
  1844. self.wdg.spinner.set_range(min, max)
  1845. def set_step(self, val):
  1846. self.wdg.spinner.set_step(val)
  1847. def get_value(self):
  1848. if self.exec_() == QtWidgets.QDialog.Accepted:
  1849. return [self.wdg.get_value(), True]
  1850. else:
  1851. return [None, False]
  1852. class FCInputDialogSlider(QtWidgets.QDialog):
  1853. def __init__(self, parent=None, title=None, text=None, min=None, max=None, step=1, init_val=None):
  1854. super().__init__(parent)
  1855. self.val = 0.0
  1856. self.init_value = init_val if init_val else 0.0
  1857. self.setWindowTitle(title) if title else self.setWindowTitle('title')
  1858. self.text = text if text else 'text'
  1859. self.min = min if min else 0
  1860. self.max = max if max else 255
  1861. self.step = step if step else 1
  1862. self.lbl = FCLabel(self.text)
  1863. self.wdg = FCSliderWithSpinner(min=self.min, max=self.max, step=self.step)
  1864. self.wdg.set_value(self.init_value)
  1865. QBtn = QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
  1866. self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
  1867. self.buttonBox.accepted.connect(self.accept)
  1868. self.buttonBox.rejected.connect(self.reject)
  1869. self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText(_("Ok"))
  1870. self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText(_("Cancel"))
  1871. self.layout = QtWidgets.QVBoxLayout()
  1872. self.layout.addWidget(self.lbl)
  1873. self.layout.addWidget(self.wdg)
  1874. self.layout.addWidget(self.buttonBox)
  1875. self.setLayout(self.layout)
  1876. def set_title(self, txt):
  1877. self.setWindowTitle(txt)
  1878. def set_text(self, txt):
  1879. self.lbl.set_value(txt)
  1880. def set_min(self, val):
  1881. self.wdg.spinner.setMinimum(val)
  1882. def set_max(self, val):
  1883. self.wdg.spinner.setMaximum(val)
  1884. def set_range(self, min, max):
  1885. self.wdg.spinner.set_range(min, max)
  1886. def set_step(self, val):
  1887. self.wdg.spinner.set_step(val)
  1888. def get_results(self):
  1889. if self.exec_() == QtWidgets.QDialog.Accepted:
  1890. return self.wdg.get_value(), True
  1891. else:
  1892. return None, False
  1893. class FCInputDialogSpinnerButton(QtWidgets.QDialog):
  1894. def __init__(self, parent=None, title=None, text=None, min=None, max=None, step=1, decimals=4, init_val=None,
  1895. button_text='', button_icon=None, callback=None):
  1896. super().__init__(parent)
  1897. self.val = 0.0
  1898. self.init_value = init_val if init_val else 0.0
  1899. self.setWindowTitle(title) if title else self.setWindowTitle('title')
  1900. self.text = text if text else 'text'
  1901. self.min = min if min else 0
  1902. self.max = max if max else 255
  1903. self.step = step if step else 1
  1904. self.decimals = decimals if decimals else 4
  1905. self.lbl = FCLabel(self.text)
  1906. self.wdg = FCButtonWithDoubleSpinner(min=self.min, max=self.max, step=self.step, decimals=decimals,
  1907. button_text=button_text, button_icon=button_icon, callback=callback)
  1908. self.wdg.set_value(self.init_value)
  1909. QBtn = QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
  1910. self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
  1911. self.buttonBox.accepted.connect(self.accept)
  1912. self.buttonBox.rejected.connect(self.reject)
  1913. self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText(_("Ok"))
  1914. self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText(_("Cancel"))
  1915. self.layout = QtWidgets.QVBoxLayout()
  1916. self.layout.addWidget(self.lbl)
  1917. self.layout.addWidget(self.wdg)
  1918. self.layout.addWidget(self.buttonBox)
  1919. self.setLayout(self.layout)
  1920. def set_title(self, txt):
  1921. self.setWindowTitle(txt)
  1922. def set_text(self, txt):
  1923. self.lbl.set_value(txt)
  1924. def set_icon(self, icon):
  1925. self.setWindowIcon(icon)
  1926. def set_min(self, val):
  1927. self.wdg.spinner.setMinimum(val)
  1928. def set_max(self, val):
  1929. self.wdg.spinner.setMaximum(val)
  1930. def set_range(self, min, max):
  1931. self.wdg.spinner.set_range(min, max)
  1932. def set_step(self, val):
  1933. self.wdg.spinner.set_step(val)
  1934. def set_value(self, val):
  1935. self.wdg.spinner.set_value(val)
  1936. def get_results(self):
  1937. if self.exec_() == QtWidgets.QDialog.Accepted:
  1938. return self.wdg.get_value(), True
  1939. else:
  1940. return None, False
  1941. class FCButton(QtWidgets.QPushButton):
  1942. def __init__(self, text=None, checkable=None, click_callback=None, parent=None):
  1943. super(FCButton, self).__init__(text, parent)
  1944. if checkable is not None:
  1945. self.setCheckable(checkable)
  1946. if not click_callback is None:
  1947. self.clicked.connect(click_callback)
  1948. def get_value(self):
  1949. return self.isChecked()
  1950. def set_value(self, val):
  1951. self.setText(str(val))
  1952. class FCLabel(QtWidgets.QLabel):
  1953. clicked = QtCore.pyqtSignal(bool)
  1954. right_clicked = QtCore.pyqtSignal(bool)
  1955. middle_clicked = QtCore.pyqtSignal(bool)
  1956. def __init__(self, parent=None):
  1957. super(FCLabel, self).__init__(parent)
  1958. # for the usage of this label as a clickable label, to know that current state
  1959. self.clicked_state = False
  1960. self.middle_clicked_state = False
  1961. self.right_clicked_state = False
  1962. def mousePressEvent(self, event):
  1963. if event.button() == Qt.LeftButton:
  1964. self.clicked_state = not self.clicked_state
  1965. self.clicked.emit(self.clicked_state)
  1966. elif event.button() == Qt.RightButton:
  1967. self.right_clicked_state = not self.right_clicked_state
  1968. self.right_clicked.emit(True)
  1969. elif event.button() == Qt.MiddleButton:
  1970. self.middle_clicked_state = not self.middle_clicked_state
  1971. self.middle_clicked.emit(True)
  1972. def get_value(self):
  1973. return self.text()
  1974. def set_value(self, val):
  1975. self.setText(str(val))
  1976. class FCMenu(QtWidgets.QMenu):
  1977. def __init__(self):
  1978. super().__init__()
  1979. self.mouse_is_panning = False
  1980. self.popup_active = False
  1981. def popup(self, pos, action=None):
  1982. super().popup(pos)
  1983. self.mouse_is_panning = False
  1984. self.popup_active = True
  1985. class FCTab(QtWidgets.QTabWidget):
  1986. def __init__(self, parent=None):
  1987. super(FCTab, self).__init__(parent)
  1988. self.setTabsClosable(True)
  1989. self.tabCloseRequested.connect(self.closeTab)
  1990. def deleteTab(self, currentIndex):
  1991. widget = self.widget(currentIndex)
  1992. if widget is not None:
  1993. widget.deleteLater()
  1994. self.removeTab(currentIndex)
  1995. def closeTab(self, currentIndex):
  1996. self.removeTab(currentIndex)
  1997. def protectTab(self, currentIndex):
  1998. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1999. # class FCTabBar(QtWidgets.QTabBar):
  2000. # def tabSizeHint(self, index):
  2001. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  2002. # w = int(self.width()/self.count())
  2003. # return QtCore.QSize(w, size.height())
  2004. class FCDetachableTab(QtWidgets.QTabWidget):
  2005. """
  2006. From here:
  2007. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  2008. """
  2009. tab_detached = QtCore.pyqtSignal(str)
  2010. tab_attached = QtCore.pyqtSignal(str)
  2011. def __init__(self, protect=None, protect_by_name=None, parent=None):
  2012. super().__init__(parent=parent)
  2013. self.tabBar = self.FCTabBar(self)
  2014. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  2015. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  2016. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  2017. self.set_detachable(val=True)
  2018. self.setTabBar(self.tabBar)
  2019. # Used to keep a reference to detached tabs since their QMainWindow
  2020. # does not have a parent
  2021. self.detachedTabs = {}
  2022. # a way to make sure that tabs can't be closed after they attach to the parent tab
  2023. self.protect_tab = True if protect is not None and protect is True else False
  2024. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  2025. # Close all detached tabs if the application is closed explicitly
  2026. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  2027. # used by the property self.useOldIndex(param)
  2028. self.use_old_index = None
  2029. self.old_index = None
  2030. self.setTabsClosable(True)
  2031. self.tabCloseRequested.connect(self.closeTab)
  2032. def set_rmb_callback(self, callback):
  2033. """
  2034. :param callback: Function to call on right mouse click on tab
  2035. :type callback: func
  2036. :return: None
  2037. """
  2038. self.tabBar.right_click.connect(callback)
  2039. def set_detachable(self, val=True):
  2040. try:
  2041. self.tabBar.onDetachTabSignal.disconnect()
  2042. except TypeError:
  2043. pass
  2044. if val is True:
  2045. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  2046. # the tab can be moved around
  2047. self.tabBar.can_be_dragged = True
  2048. else:
  2049. # the detached tab can't be moved
  2050. self.tabBar.can_be_dragged = False
  2051. return val
  2052. def setupContextMenu(self):
  2053. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  2054. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  2055. action_name = str(entry)
  2056. action = QtWidgets.QAction(self)
  2057. action.setCheckable(True)
  2058. action.setText(action_name)
  2059. if icon:
  2060. assert isinstance(icon, QtGui.QIcon), \
  2061. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  2062. action.setIcon(icon)
  2063. action.setChecked(initial_checked)
  2064. self.addAction(action)
  2065. action.triggered.connect(call_function)
  2066. def useOldIndex(self, param):
  2067. if param:
  2068. self.use_old_index = True
  2069. else:
  2070. self.use_old_index = False
  2071. def deleteTab(self, currentIndex):
  2072. widget = self.widget(currentIndex)
  2073. if widget is not None:
  2074. widget.deleteLater()
  2075. self.removeTab(currentIndex)
  2076. def closeTab(self, currentIndex):
  2077. """
  2078. Slot connected to the tabCloseRequested signal
  2079. :param currentIndex:
  2080. :return:
  2081. """
  2082. self.removeTab(currentIndex)
  2083. def on_closetab_middle_button(self, current_index):
  2084. """
  2085. :param current_index:
  2086. :return:
  2087. """
  2088. # if tab is protected don't delete it
  2089. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  2090. self.removeTab(current_index)
  2091. def protectTab(self, currentIndex):
  2092. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  2093. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  2094. def setMovable(self, movable):
  2095. """
  2096. The default movable functionality of QTabWidget must remain disabled
  2097. so as not to conflict with the added features
  2098. :param movable:
  2099. :return:
  2100. """
  2101. pass
  2102. @pyqtSlot(int, int)
  2103. def moveTab(self, fromIndex, toIndex):
  2104. """
  2105. Move a tab from one position (index) to another
  2106. :param fromIndex: the original index location of the tab
  2107. :param toIndex: the new index location of the tab
  2108. :return:
  2109. """
  2110. widget = self.widget(fromIndex)
  2111. icon = self.tabIcon(fromIndex)
  2112. text = self.tabText(fromIndex)
  2113. self.removeTab(fromIndex)
  2114. self.insertTab(toIndex, widget, icon, text)
  2115. self.setCurrentIndex(toIndex)
  2116. # @pyqtSlot(int, QtCore.QPoint)
  2117. def detachTab(self, index, point):
  2118. """
  2119. Detach the tab by removing it's contents and placing them in
  2120. a DetachedTab window
  2121. :param index: the index location of the tab to be detached
  2122. :param point: the screen position for creating the new DetachedTab window
  2123. :return:
  2124. """
  2125. self.old_index = index
  2126. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  2127. name = "FlatCAM " + self.tabText(index)
  2128. icon = self.tabIcon(index)
  2129. if icon.isNull():
  2130. icon = self.window().windowIcon()
  2131. contentWidget = self.widget(index)
  2132. try:
  2133. contentWidgetRect = contentWidget.frameGeometry()
  2134. except AttributeError:
  2135. return
  2136. # Create a new detached tab window
  2137. detachedTab = self.FCDetachedTab(name, contentWidget)
  2138. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  2139. detachedTab.setWindowIcon(icon)
  2140. detachedTab.setGeometry(contentWidgetRect)
  2141. detachedTab.onCloseSignal.connect(self.attachTab)
  2142. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  2143. detachedTab.move(point)
  2144. detachedTab.show()
  2145. # Create a reference to maintain access to the detached tab
  2146. self.detachedTabs[name] = detachedTab
  2147. self.tab_detached.emit(name)
  2148. def attachTab(self, contentWidget, name, icon, insertAt=None):
  2149. """
  2150. Re-attach the tab by removing the content from the DetachedTab window,
  2151. closing it, and placing the content back into the DetachableTabWidget
  2152. :param contentWidget: the content widget from the DetachedTab window
  2153. :param name: the name of the detached tab
  2154. :param icon: the window icon for the detached tab
  2155. :param insertAt: insert the re-attached tab at the given index
  2156. :return:
  2157. """
  2158. old_name = name
  2159. # Make the content widget a child of this widget
  2160. contentWidget.setParent(self)
  2161. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  2162. name = name.partition(' ')[2]
  2163. # helps in restoring the tab to the same index that it was before was detached
  2164. insert_index = self.old_index if self.use_old_index is True else insertAt
  2165. # Create an image from the given icon (for comparison)
  2166. if not icon.isNull():
  2167. try:
  2168. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  2169. tabIconImage = tabIconPixmap.toImage()
  2170. except IndexError:
  2171. tabIconImage = None
  2172. else:
  2173. tabIconImage = None
  2174. # Create an image of the main window icon (for comparison)
  2175. if not icon.isNull():
  2176. try:
  2177. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  2178. windowIconImage = windowIconPixmap.toImage()
  2179. except IndexError:
  2180. windowIconImage = None
  2181. else:
  2182. windowIconImage = None
  2183. # Determine if the given image and the main window icon are the same.
  2184. # If they are, then do not add the icon to the tab
  2185. if tabIconImage == windowIconImage:
  2186. if insert_index is None:
  2187. index = self.addTab(contentWidget, name)
  2188. else:
  2189. index = self.insertTab(insert_index, contentWidget, name)
  2190. else:
  2191. if insert_index is None:
  2192. index = self.addTab(contentWidget, icon, name)
  2193. else:
  2194. index = self.insertTab(insert_index, contentWidget, icon, name)
  2195. obj_name = contentWidget.objectName()
  2196. self.tab_attached.emit(obj_name)
  2197. # on reattaching the tab if protect is true then the closure button is not added
  2198. if self.protect_tab is True:
  2199. self.protectTab(index)
  2200. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  2201. if self.protect_by_name is not None:
  2202. for tab_name in self.protect_by_name:
  2203. for index in range(self.count()):
  2204. if str(tab_name) == str(self.tabText(index)):
  2205. self.protectTab(index)
  2206. # Make this tab the current tab
  2207. if index > -1:
  2208. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  2209. # Remove the reference
  2210. # Unix-like OS's crash with segmentation fault after this. FOr whatever reason, they loose reference
  2211. if sys.platform == 'win32':
  2212. try:
  2213. del self.detachedTabs[old_name]
  2214. except KeyError:
  2215. pass
  2216. def removeTabByName(self, name):
  2217. """
  2218. Remove the tab with the given name, even if it is detached
  2219. :param name: the name of the tab to be removed
  2220. :return:
  2221. """
  2222. # Remove the tab if it is attached
  2223. attached = False
  2224. for index in range(self.count()):
  2225. if str(name) == str(self.tabText(index)):
  2226. self.removeTab(index)
  2227. attached = True
  2228. break
  2229. # If the tab is not attached, close it's window and
  2230. # remove the reference to it
  2231. if not attached:
  2232. for key in self.detachedTabs:
  2233. if str(name) == str(key):
  2234. self.detachedTabs[key].onCloseSignal.disconnect()
  2235. self.detachedTabs[key].close()
  2236. del self.detachedTabs[key]
  2237. break
  2238. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  2239. def detachedTabDrop(self, name, index, dropPos):
  2240. """
  2241. Handle dropping of a detached tab inside the DetachableTabWidget
  2242. :param name: the name of the detached tab
  2243. :param index: the index of an existing tab (if the tab bar
  2244. # determined that the drop occurred on an
  2245. # existing tab)
  2246. :param dropPos: the mouse cursor position when the drop occurred
  2247. :return:
  2248. """
  2249. # If the drop occurred on an existing tab, insert the detached
  2250. # tab at the existing tab's location
  2251. if index > -1:
  2252. # Create references to the detached tab's content and icon
  2253. contentWidget = self.detachedTabs[name].contentWidget
  2254. icon = self.detachedTabs[name].windowIcon()
  2255. # Disconnect the detached tab's onCloseSignal so that it
  2256. # does not try to re-attach automatically
  2257. self.detachedTabs[name].onCloseSignal.disconnect()
  2258. # Close the detached
  2259. self.detachedTabs[name].close()
  2260. # Re-attach the tab at the given index
  2261. self.attachTab(contentWidget, name, icon, index)
  2262. # If the drop did not occur on an existing tab, determine if the drop
  2263. # occurred in the tab bar area (the area to the side of the QTabBar)
  2264. else:
  2265. # Find the drop position relative to the DetachableTabWidget
  2266. tabDropPos = self.mapFromGlobal(dropPos)
  2267. # If the drop position is inside the DetachableTabWidget...
  2268. if self.rect().contains(tabDropPos):
  2269. # If the drop position is inside the tab bar area (the
  2270. # area to the side of the QTabBar) or there are not tabs
  2271. # currently attached...
  2272. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  2273. # Close the detached tab and allow it to re-attach
  2274. # automatically
  2275. self.detachedTabs[name].close()
  2276. def closeDetachedTabs(self):
  2277. """
  2278. Close all tabs that are currently detached.
  2279. :return:
  2280. """
  2281. listOfDetachedTabs = []
  2282. for key in self.detachedTabs:
  2283. listOfDetachedTabs.append(self.detachedTabs[key])
  2284. for detachedTab in listOfDetachedTabs:
  2285. detachedTab.close()
  2286. class FCDetachedTab(QtWidgets.QMainWindow):
  2287. """
  2288. When a tab is detached, the contents are placed into this QMainWindow. The tab
  2289. can be re-attached by closing the dialog or by dragging the window into the tab bar
  2290. """
  2291. onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  2292. onDropSignal = QtCore.pyqtSignal(str, QtCore.QPoint)
  2293. def __init__(self, name, contentWidget):
  2294. QtWidgets.QMainWindow.__init__(self, None)
  2295. self.setObjectName(name)
  2296. self.setWindowTitle(name)
  2297. self.contentWidget = contentWidget
  2298. self.setCentralWidget(self.contentWidget)
  2299. self.contentWidget.show()
  2300. self.windowDropFilter = self.WindowDropFilter()
  2301. self.installEventFilter(self.windowDropFilter)
  2302. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  2303. @QtCore.pyqtSlot(QtCore.QPoint)
  2304. def windowDropSlot(self, dropPos):
  2305. """
  2306. Handle a window drop event
  2307. :param dropPos: the mouse cursor position of the drop
  2308. :return:
  2309. """
  2310. self.onDropSignal.emit(self.objectName(), dropPos)
  2311. def closeEvent(self, event):
  2312. """
  2313. If the window is closed, emit the onCloseSignal and give the
  2314. content widget back to the DetachableTabWidget
  2315. :param event: a close event
  2316. :return:
  2317. """
  2318. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  2319. class WindowDropFilter(QtCore.QObject):
  2320. """
  2321. An event filter class to detect a QMainWindow drop event
  2322. """
  2323. onDropSignal = QtCore.pyqtSignal(QtCore.QPoint)
  2324. def __init__(self):
  2325. QtCore.QObject.__init__(self)
  2326. self.lastEvent = None
  2327. def eventFilter(self, obj, event):
  2328. """
  2329. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  2330. event that immediately follows a Move event
  2331. :param obj: the object that generated the event
  2332. :param event: the current event
  2333. :return:
  2334. """
  2335. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  2336. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  2337. # Determine the position of the mouse cursor and emit it with the
  2338. # onDropSignal
  2339. mouseCursor = QtGui.QCursor()
  2340. dropPos = mouseCursor.pos()
  2341. self.onDropSignal.emit(dropPos)
  2342. self.lastEvent = event.type()
  2343. return True
  2344. else:
  2345. self.lastEvent = event.type()
  2346. return False
  2347. class FCTabBar(QtWidgets.QTabBar):
  2348. onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)
  2349. onMoveTabSignal = QtCore.pyqtSignal(int, int)
  2350. detachedTabDropSignal = QtCore.pyqtSignal(str, int, QtCore.QPoint)
  2351. onCloseTabSignal = QtCore.pyqtSignal(int)
  2352. right_click = QtCore.pyqtSignal(int)
  2353. def __init__(self, parent=None):
  2354. QtWidgets.QTabBar.__init__(self, parent)
  2355. self.setAcceptDrops(True)
  2356. self.setElideMode(QtCore.Qt.ElideRight)
  2357. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  2358. self.prev_index = -1
  2359. self.dragStartPos = QtCore.QPoint()
  2360. self.dragDropedPos = QtCore.QPoint()
  2361. self.mouseCursor = QtGui.QCursor()
  2362. self.dragInitiated = False
  2363. # set this to False and the tab will no longer be displayed as detached
  2364. self.can_be_dragged = True
  2365. def mouseDoubleClickEvent(self, event):
  2366. """
  2367. Send the onDetachTabSignal when a tab is double clicked
  2368. :param event: a mouse double click event
  2369. :return:
  2370. """
  2371. event.accept()
  2372. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  2373. def mousePressEvent(self, event):
  2374. """
  2375. Set the starting position for a drag event when the left mouse button is pressed.
  2376. Start detection of a right mouse click.
  2377. :param event: a mouse press event
  2378. :return:
  2379. """
  2380. if event.button() == QtCore.Qt.LeftButton:
  2381. self.dragStartPos = event.pos()
  2382. elif event.button() == QtCore.Qt.RightButton:
  2383. self.prev_index = self.tabAt(event.pos())
  2384. self.dragDropedPos.setX(0)
  2385. self.dragDropedPos.setY(0)
  2386. self.dragInitiated = False
  2387. QtWidgets.QTabBar.mousePressEvent(self, event)
  2388. def mouseReleaseEvent(self, event):
  2389. """
  2390. Finish the detection of the right mouse click on the tab
  2391. :param event: a mouse press event
  2392. :return:
  2393. """
  2394. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  2395. self.right_click.emit(self.prev_index)
  2396. if event.button() == QtCore.Qt.MiddleButton:
  2397. self.onCloseTabSignal.emit(int(self.tabAt(event.pos())))
  2398. self.prev_index = -1
  2399. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  2400. def mouseMoveEvent(self, event):
  2401. """
  2402. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  2403. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  2404. bar, emit an onDetachTabSignal.
  2405. :param event: a mouse move event
  2406. :return:
  2407. """
  2408. # Determine if the current movement is detected as a drag
  2409. if not self.dragStartPos.isNull() and \
  2410. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  2411. self.dragInitiated = True
  2412. # If the current movement is a drag initiated by the left button
  2413. if (event.buttons() & QtCore.Qt.LeftButton) and self.dragInitiated and self.can_be_dragged:
  2414. # Stop the move event
  2415. finishMoveEvent = QtGui.QMouseEvent(
  2416. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  2417. )
  2418. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  2419. # Convert the move event into a drag
  2420. drag = QtGui.QDrag(self)
  2421. mimeData = QtCore.QMimeData()
  2422. # mimeData.setData('action', 'application/tab-detach')
  2423. drag.setMimeData(mimeData)
  2424. # screen = QScreen(self.parentWidget().currentWidget().winId())
  2425. # Create the appearance of dragging the tab content
  2426. try:
  2427. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  2428. except Exception as e:
  2429. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  2430. return
  2431. targetPixmap = QtGui.QPixmap(pixmap.size())
  2432. targetPixmap.fill(QtCore.Qt.transparent)
  2433. painter = QtGui.QPainter(targetPixmap)
  2434. painter.setOpacity(0.85)
  2435. painter.drawPixmap(0, 0, pixmap)
  2436. painter.end()
  2437. drag.setPixmap(targetPixmap)
  2438. # Initiate the drag
  2439. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  2440. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  2441. # must be set manually
  2442. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  2443. dropAction = QtCore.Qt.MoveAction
  2444. # If the drag completed outside of the tab bar, detach the tab and move
  2445. # the content to the current cursor position
  2446. if dropAction == QtCore.Qt.IgnoreAction:
  2447. event.accept()
  2448. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  2449. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  2450. elif dropAction == QtCore.Qt.MoveAction:
  2451. if not self.dragDropedPos.isNull():
  2452. event.accept()
  2453. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  2454. else:
  2455. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  2456. def dragEnterEvent(self, event):
  2457. """
  2458. Determine if the drag has entered a tab position from another tab position
  2459. :param event: a drag enter event
  2460. :return:
  2461. """
  2462. mimeData = event.mimeData()
  2463. # formats = mcd imeData.formats()
  2464. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  2465. # event.acceptProposedAction()
  2466. QtWidgets.QTabBar.dragMoveEvent(self, event)
  2467. def dropEvent(self, event):
  2468. """
  2469. Get the position of the end of the drag
  2470. :param event: a drop event
  2471. :return:
  2472. """
  2473. self.dragDropedPos = event.pos()
  2474. QtWidgets.QTabBar.dropEvent(self, event)
  2475. def detachedTabDrop(self, name, dropPos):
  2476. """
  2477. Determine if the detached tab drop event occurred on an existing tab,
  2478. then send the event to the DetachableTabWidget
  2479. :param name:
  2480. :param dropPos:
  2481. :return:
  2482. """
  2483. tabDropPos = self.mapFromGlobal(dropPos)
  2484. index = self.tabAt(tabDropPos)
  2485. self.detachedTabDropSignal.emit(name, index, dropPos)
  2486. class FCDetachableTab2(FCDetachableTab):
  2487. tab_closed_signal = QtCore.pyqtSignal(object, int)
  2488. def __init__(self, protect=None, protect_by_name=None, parent=None):
  2489. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  2490. try:
  2491. self.tabBar.onCloseTabSignal.disconnect()
  2492. except TypeError:
  2493. pass
  2494. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  2495. def on_closetab_middle_button(self, current_index):
  2496. """
  2497. :param current_index:
  2498. :return:
  2499. """
  2500. # if tab is protected don't delete it
  2501. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  2502. self.closeTab(current_index)
  2503. def closeTab(self, currentIndex):
  2504. """
  2505. Slot connected to the tabCloseRequested signal
  2506. :param currentIndex:
  2507. :return:
  2508. """
  2509. # idx = self.currentIndex()
  2510. tab_name = self.widget(currentIndex).objectName()
  2511. self.tab_closed_signal.emit(tab_name, currentIndex)
  2512. self.removeTab(currentIndex)
  2513. class VerticalScrollArea(QtWidgets.QScrollArea):
  2514. """
  2515. This widget extends QtGui.QScrollArea to make a vertical-only
  2516. scroll area that also expands horizontally to accommodate
  2517. its contents.
  2518. """
  2519. def __init__(self, parent=None):
  2520. QtWidgets.QScrollArea.__init__(self, parent=parent)
  2521. self.setWidgetResizable(True)
  2522. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2523. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  2524. def eventFilter(self, source, event):
  2525. """
  2526. The event filter gets automatically installed when setWidget()
  2527. is called.
  2528. :param source:
  2529. :param event:
  2530. :return:
  2531. """
  2532. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  2533. # log.debug("VerticalScrollArea: Widget resized:")
  2534. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  2535. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  2536. self.setMinimumWidth(self.widget().sizeHint().width() +
  2537. self.verticalScrollBar().sizeHint().width())
  2538. # if self.verticalScrollBar().isVisible():
  2539. # log.debug(" Scroll bar visible")
  2540. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  2541. # self.verticalScrollBar().width())
  2542. # else:
  2543. # log.debug(" Scroll bar hidden")
  2544. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  2545. return QtWidgets.QWidget.eventFilter(self, source, event)
  2546. class OptionalInputSection:
  2547. def __init__(self, cb, optinputs, logic=True):
  2548. """
  2549. Associates the a checkbox with a set of inputs.
  2550. :param cb: Checkbox that enables the optional inputs.
  2551. :param optinputs: List of widgets that are optional.
  2552. :param logic: When True the logic is normal, when False the logic is in reverse
  2553. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  2554. for logic=False, when the checkbox is checked the widgets are Disabled
  2555. :return:
  2556. """
  2557. assert isinstance(cb, FCCheckBox), \
  2558. "Expected an FCCheckBox, got %s" % type(cb)
  2559. self.cb = cb
  2560. self.optinputs = optinputs
  2561. self.logic = logic
  2562. self.on_cb_change()
  2563. self.cb.stateChanged.connect(self.on_cb_change)
  2564. def on_cb_change(self):
  2565. if self.cb.checkState():
  2566. for widget in self.optinputs:
  2567. if self.logic is True:
  2568. widget.setEnabled(True)
  2569. else:
  2570. widget.setEnabled(False)
  2571. else:
  2572. for widget in self.optinputs:
  2573. if self.logic is True:
  2574. widget.setEnabled(False)
  2575. else:
  2576. widget.setEnabled(True)
  2577. class OptionalHideInputSection:
  2578. def __init__(self, cb, optinputs, logic=True):
  2579. """
  2580. Associates the a checkbox with a set of inputs.
  2581. :param cb: Checkbox that enables the optional inputs.
  2582. :type cb: QtWidgets.QCheckBox
  2583. :param optinputs: List of widgets that are optional.
  2584. :type optinputs: list
  2585. :param logic: When True the logic is normal, when False the logic is in reverse
  2586. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  2587. for logic=False, when the checkbox is checked the widgets are Disabled
  2588. :type logic: bool
  2589. :return:
  2590. """
  2591. assert isinstance(cb, FCCheckBox), \
  2592. "Expected an FCCheckBox, got %s" % type(cb)
  2593. self.cb = cb
  2594. self.optinputs = optinputs
  2595. self.logic = logic
  2596. self.on_cb_change()
  2597. self.cb.stateChanged.connect(self.on_cb_change)
  2598. def on_cb_change(self):
  2599. if self.cb.checkState():
  2600. for widget in self.optinputs:
  2601. if self.logic is True:
  2602. widget.show()
  2603. else:
  2604. widget.hide()
  2605. else:
  2606. for widget in self.optinputs:
  2607. if self.logic is True:
  2608. widget.hide()
  2609. else:
  2610. widget.show()
  2611. class FCTable(QtWidgets.QTableWidget):
  2612. drag_drop_sig = QtCore.pyqtSignal(object, int)
  2613. lost_focus = QtCore.pyqtSignal()
  2614. def __init__(self, drag_drop=False, protected_rows=None, parent=None):
  2615. super(FCTable, self).__init__(parent)
  2616. palette = QtGui.QPalette()
  2617. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight,
  2618. palette.color(QtGui.QPalette.Active, QtGui.QPalette.Highlight))
  2619. # make inactive rows text some color as active; may be useful in the future
  2620. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.HighlightedText,
  2621. palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
  2622. self.setPalette(palette)
  2623. if drag_drop:
  2624. self.setDragEnabled(True)
  2625. self.setAcceptDrops(True)
  2626. self.viewport().setAcceptDrops(True)
  2627. self.setDragDropOverwriteMode(False)
  2628. self.setDropIndicatorShown(True)
  2629. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2630. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2631. self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  2632. self.rows_not_for_drag_and_drop = []
  2633. if protected_rows:
  2634. try:
  2635. for r in protected_rows:
  2636. self.rows_not_for_drag_and_drop.append(r)
  2637. except TypeError:
  2638. self.rows_not_for_drag_and_drop = [protected_rows]
  2639. self.rows_to_move = []
  2640. self.rows_dragged = None
  2641. def sizeHint(self):
  2642. default_hint_size = super(FCTable, self).sizeHint()
  2643. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  2644. def getHeight(self):
  2645. height = self.horizontalHeader().height()
  2646. for i in range(self.rowCount()):
  2647. height += self.rowHeight(i)
  2648. return height
  2649. def getWidth(self):
  2650. width = self.verticalHeader().width()
  2651. for i in range(self.columnCount()):
  2652. width += self.columnWidth(i)
  2653. return width
  2654. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpha
  2655. def setColortoRow(self, rowIndex, color):
  2656. for j in range(self.columnCount()):
  2657. self.item(rowIndex, j).setBackground(color)
  2658. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  2659. def mousePressEvent(self, event):
  2660. clicked_item = self.itemAt(event.pos())
  2661. if not clicked_item:
  2662. self.clearSelection()
  2663. self.clearFocus()
  2664. else:
  2665. self.rows_dragged = [it.row() for it in self.selectedItems()]
  2666. QtWidgets.QTableWidget.mousePressEvent(self, event)
  2667. def focusOutEvent(self, event):
  2668. self.lost_focus.emit()
  2669. super().focusOutEvent(event)
  2670. def setupContextMenu(self):
  2671. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  2672. def addContextMenu(self, entry, call_function, icon=None):
  2673. action_name = str(entry)
  2674. action = QtWidgets.QAction(self)
  2675. action.setText(action_name)
  2676. if icon:
  2677. assert isinstance(icon, QtGui.QIcon), \
  2678. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  2679. action.setIcon(icon)
  2680. self.addAction(action)
  2681. action.triggered.connect(call_function)
  2682. # def dropEvent(self, event: QtGui.QDropEvent):
  2683. # if not event.isAccepted() and event.source() == self:
  2684. # drop_row = self.drop_on(event)
  2685. #
  2686. # rows = sorted(set(item.row() for item in self.selectedItems()))
  2687. # # rows_to_move = [
  2688. # # [QtWidgets.QTableWidgetItem(self.item(row_index, column_index))
  2689. # # for column_index in range(self.columnCount())] for row_index in rows
  2690. # # ]
  2691. # self.rows_to_move[:] = []
  2692. # for row_index in rows:
  2693. # row_items = []
  2694. # for column_index in range(self.columnCount()):
  2695. # r_item = self.item(row_index, column_index)
  2696. # w_item = self.cellWidget(row_index, column_index)
  2697. #
  2698. # if r_item is not None:
  2699. # row_items.append(QtWidgets.QTableWidgetItem(r_item))
  2700. # elif w_item is not None:
  2701. # row_items.append(w_item)
  2702. #
  2703. # self.rows_to_move.append(row_items)
  2704. #
  2705. # for row_index in reversed(rows):
  2706. # self.removeRow(row_index)
  2707. # if row_index < drop_row:
  2708. # drop_row -= 1
  2709. #
  2710. # for row_index, data in enumerate(self.rows_to_move):
  2711. # row_index += drop_row
  2712. # self.insertRow(row_index)
  2713. #
  2714. # for column_index, column_data in enumerate(data):
  2715. # if isinstance(column_data, QtWidgets.QTableWidgetItem):
  2716. # self.setItem(row_index, column_index, column_data)
  2717. # else:
  2718. # self.setCellWidget(row_index, column_index, column_data)
  2719. #
  2720. # event.accept()
  2721. # for row_index in range(len(self.rows_to_move)):
  2722. # self.item(drop_row + row_index, 0).setSelected(True)
  2723. # self.item(drop_row + row_index, 1).setSelected(True)
  2724. #
  2725. # super().dropEvent(event)
  2726. #
  2727. # def drop_on(self, event):
  2728. # ret_val = False
  2729. # index = self.indexAt(event.pos())
  2730. # if not index.isValid():
  2731. # return self.rowCount()
  2732. #
  2733. # ret_val = index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  2734. #
  2735. # return ret_val
  2736. #
  2737. # def is_below(self, pos, index):
  2738. # rect = self.visualRect(index)
  2739. # margin = 2
  2740. # if pos.y() - rect.top() < margin:
  2741. # return False
  2742. # elif rect.bottom() - pos.y() < margin:
  2743. # return True
  2744. # # noinspection PyTypeChecker
  2745. # return rect.contains(pos, True) and not (
  2746. # int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
  2747. def dragEnterEvent(self, e: QtGui.QDragEnterEvent) -> None:
  2748. if e.source() == self:
  2749. self.blockSignals(True)
  2750. e.accept()
  2751. else:
  2752. e.ignore()
  2753. # def dropEvent(self, event):
  2754. # """
  2755. # From here: https://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
  2756. # :param event:
  2757. # :return:
  2758. # """
  2759. # if event.source() == self:
  2760. # event.acceptProposedAction()
  2761. #
  2762. # # create a set of the selected rows that are dragged to another position
  2763. # rows = set([mi.row() for mi in self.selectedIndexes()])
  2764. # # if one of the selected rows for drag and drop is within the protected list, return
  2765. # for r in rows:
  2766. # if r in self.rows_not_for_drag_and_drop:
  2767. # return
  2768. #
  2769. # drop_index = self.indexAt(event.pos())
  2770. # # row where we drop the selected rows
  2771. # targetRow = drop_index.row()
  2772. #
  2773. # # drop_indicator = self.dropIndicatorPosition()
  2774. # # if targetRow != -1:
  2775. # # if drop_indicator == QtWidgets.QAbstractItemView.AboveItem:
  2776. # # print("above")
  2777. # # elif drop_indicator == QtWidgets.QAbstractItemView.BelowItem:
  2778. # # print("below")
  2779. # # elif drop_indicator == QtWidgets.QAbstractItemView.OnItem:
  2780. # # print("on")
  2781. # # elif drop_indicator == QtWidgets.QAbstractItemView.OnViewport:
  2782. # # print("on viewport")
  2783. #
  2784. # # if we drop on one row from the already dragged rows
  2785. # rows.discard(targetRow)
  2786. # rows = sorted(rows)
  2787. # if not rows:
  2788. # return
  2789. # if targetRow == -1:
  2790. # targetRow = self.rowCount()
  2791. #
  2792. # # insert empty rows at the index of the targetRow
  2793. # for _ in range(len(rows)):
  2794. # self.insertRow(targetRow)
  2795. #
  2796. # rowMapping = {} # Src row to target row.
  2797. # for idx, row in enumerate(rows):
  2798. # if row < targetRow:
  2799. # rowMapping[row] = targetRow + idx
  2800. # else:
  2801. # rowMapping[row + len(rows)] = targetRow + idx
  2802. #
  2803. # colCount = self.columnCount()
  2804. # for srcRow, tgtRow in sorted(rowMapping.items()):
  2805. # for col in range(0, colCount):
  2806. # new_item = self.item(srcRow, col)
  2807. # if new_item is None:
  2808. # new_item = self.cellWidget(srcRow, col)
  2809. #
  2810. # if isinstance(new_item, QtWidgets.QTableWidgetItem):
  2811. # new_item = self.takeItem(srcRow, col)
  2812. # self.setItem(tgtRow, col, new_item)
  2813. # else:
  2814. # self.setCellWidget(tgtRow, col, new_item)
  2815. #
  2816. # for row in reversed(sorted(rowMapping.keys())):
  2817. # self.removeRow(row)
  2818. #
  2819. # self.blockSignals(False)
  2820. # self.drag_drop_sig.emit(int(self.row_dragged), int(targetRow))
  2821. # else:
  2822. # event.ignore()
  2823. def dropEvent(self, event: QtGui.QDropEvent):
  2824. if not event.isAccepted() and event.source() == self:
  2825. drop_row = self.drop_on(event)
  2826. rows = sorted(set(item.row() for item in self.selectedItems()))
  2827. rows_to_move = []
  2828. for row_index in rows:
  2829. temp_lst = []
  2830. for column_index in range(self.columnCount()):
  2831. col_data = self.item(row_index, column_index)
  2832. if isinstance(col_data, QtWidgets.QTableWidgetItem):
  2833. table_item = QtWidgets.QTableWidgetItem(col_data)
  2834. else:
  2835. old_item = self.cellWidget(row_index, column_index)
  2836. if isinstance(old_item, QtWidgets.QComboBox):
  2837. table_item = FCComboBox()
  2838. items = [old_item.itemText(i) for i in range(old_item.count())]
  2839. table_item.addItems(items)
  2840. table_item.setCurrentIndex(old_item.currentIndex())
  2841. elif isinstance(old_item, QtWidgets.QCheckBox):
  2842. table_item = FCCheckBox()
  2843. table_item.setChecked(old_item.isChecked())
  2844. table_item.setText(old_item.text())
  2845. else:
  2846. table_item = None
  2847. temp_lst.append(table_item)
  2848. rows_to_move.append(temp_lst)
  2849. for row_index in reversed(rows):
  2850. self.removeRow(row_index)
  2851. if row_index < drop_row:
  2852. drop_row -= 1
  2853. for row_index, data in enumerate(rows_to_move):
  2854. row_index += drop_row
  2855. self.insertRow(row_index)
  2856. for column_index, column_data in enumerate(data):
  2857. if column_data is None:
  2858. continue
  2859. if isinstance(column_data, QtWidgets.QTableWidgetItem):
  2860. self.setItem(row_index, column_index, column_data)
  2861. else:
  2862. self.setCellWidget(row_index, column_index, column_data)
  2863. event.accept()
  2864. for row_index in range(len(rows_to_move)):
  2865. self.item(drop_row + row_index, 0).setSelected(True)
  2866. self.item(drop_row + row_index, 1).setSelected(True)
  2867. self.blockSignals(False)
  2868. self.drag_drop_sig.emit(self.rows_dragged, int(drop_row))
  2869. self.blockSignals(False)
  2870. self.resizeRowsToContents()
  2871. super().dropEvent(event)
  2872. def drop_on(self, event):
  2873. index = self.indexAt(event.pos())
  2874. if not index.isValid():
  2875. return self.rowCount()
  2876. return index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  2877. def is_below(self, pos, index):
  2878. rect = self.visualRect(index)
  2879. margin = 2
  2880. if pos.y() - rect.top() < margin:
  2881. return False
  2882. elif rect.bottom() - pos.y() < margin:
  2883. return True
  2884. # noinspection PyTypeChecker
  2885. return rect.contains(pos, True) and not (int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and \
  2886. pos.y() >= rect.center().y()
  2887. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  2888. def __init__(self, units):
  2889. super(SpinBoxDelegate, self).__init__()
  2890. self.units = units
  2891. self.current_value = None
  2892. def createEditor(self, parent, option, index):
  2893. editor = QtWidgets.QDoubleSpinBox(parent)
  2894. editor.setMinimum(-999.9999)
  2895. editor.setMaximum(999.9999)
  2896. if self.units == 'MM':
  2897. editor.setDecimals(2)
  2898. else:
  2899. editor.setDecimals(3)
  2900. return editor
  2901. def setEditorData(self, spinBox, index):
  2902. try:
  2903. value = float(index.model().data(index, Qt.EditRole))
  2904. except ValueError:
  2905. value = self.current_value
  2906. # return
  2907. spinBox.setValue(value)
  2908. def setModelData(self, spinBox, model, index):
  2909. spinBox.interpretText()
  2910. value = spinBox.value()
  2911. self.current_value = value
  2912. model.setData(index, value, Qt.EditRole)
  2913. def updateEditorGeometry(self, editor, option, index):
  2914. editor.setGeometry(option.rect)
  2915. @staticmethod
  2916. def setDecimals(spinbox, digits):
  2917. spinbox.setDecimals(digits)
  2918. class Dialog_box(QtWidgets.QWidget):
  2919. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  2920. """
  2921. :param title: string with the window title
  2922. :param label: string with the message inside the dialog box
  2923. """
  2924. super(Dialog_box, self).__init__()
  2925. if initial_text is None:
  2926. self.location = str((0, 0))
  2927. else:
  2928. self.location = initial_text
  2929. self.ok = False
  2930. self.dialog_box = QtWidgets.QInputDialog()
  2931. self.dialog_box.setMinimumWidth(290)
  2932. self.setWindowIcon(icon)
  2933. self.location, self.ok = self.dialog_box.getText(self, title, label,
  2934. text=str(self.location).replace('(', '').replace(')', ''))
  2935. self.readyToEdit = True
  2936. def mousePressEvent(self, e, parent=None):
  2937. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  2938. if self.readyToEdit:
  2939. self.lineEdit().selectAll()
  2940. self.readyToEdit = False
  2941. def focusOutEvent(self, e):
  2942. # don't focus out if the user requests an popup menu
  2943. if e.reason() != QtCore.Qt.PopupFocusReason:
  2944. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  2945. self.lineEdit().deselect()
  2946. self.readyToEdit = True
  2947. class DialogBoxRadio(QtWidgets.QDialog):
  2948. def __init__(self, title=None, label=None, icon=None, initial_text=None, reference='abs', parent=None):
  2949. """
  2950. :param title: string with the window title
  2951. :param label: string with the message inside the dialog box
  2952. """
  2953. super(DialogBoxRadio, self).__init__(parent=parent)
  2954. if initial_text is None:
  2955. self.location = str((0, 0))
  2956. else:
  2957. self.location = initial_text
  2958. self.ok = False
  2959. self.setWindowIcon(icon)
  2960. self.setWindowTitle(str(title))
  2961. self.form = QtWidgets.QFormLayout(self)
  2962. self.ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  2963. self.ref_label.setToolTip(
  2964. _("The reference can be:\n"
  2965. "- Absolute -> the reference point is point (0,0)\n"
  2966. "- Relative -> the reference point is the mouse position before Jump")
  2967. )
  2968. self.ref_radio = RadioSet([
  2969. {"label": _("Abs"), "value": "abs"},
  2970. {"label": _("Relative"), "value": "rel"}
  2971. ], orientation='horizontal', stretch=False)
  2972. self.ref_radio.set_value(reference)
  2973. self.form.addRow(self.ref_label, self.ref_radio)
  2974. self.form.addRow(QtWidgets.QLabel(''))
  2975. self.wdg_label = QtWidgets.QLabel('<b>%s</b>' % str(label))
  2976. self.form.addRow(self.wdg_label)
  2977. self.loc_label = QtWidgets.QLabel('%s:' % _("Location"))
  2978. self.loc_label.setToolTip(
  2979. _("The Location value is a tuple (x,y).\n"
  2980. "If the reference is Absolute then the Jump will be at the position (x,y).\n"
  2981. "If the reference is Relative then the Jump will be at the (x,y) distance\n"
  2982. "from the current mouse location point.")
  2983. )
  2984. self.lineEdit = EvalEntry(parent=self)
  2985. self.lineEdit.setText(str(self.location).replace('(', '').replace(')', ''))
  2986. self.lineEdit.selectAll()
  2987. self.lineEdit.setFocus()
  2988. self.form.addRow(self.loc_label, self.lineEdit)
  2989. self.button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  2990. orientation=Qt.Horizontal, parent=self)
  2991. self.form.addRow(self.button_box)
  2992. self.button_box.button(QtWidgets.QDialogButtonBox.Ok).setText(_("Ok"))
  2993. self.button_box.button(QtWidgets.QDialogButtonBox.Cancel).setText(_("Cancel"))
  2994. self.button_box.accepted.connect(self.accept)
  2995. self.button_box.rejected.connect(self.reject)
  2996. self.readyToEdit = True
  2997. if self.exec_() == QtWidgets.QDialog.Accepted:
  2998. self.ok = True
  2999. self.location = self.lineEdit.text()
  3000. self.reference = self.ref_radio.get_value()
  3001. else:
  3002. self.ok = False
  3003. class _BrowserTextEdit(QTextEdit):
  3004. def __init__(self, version, app=None):
  3005. QTextEdit.__init__(self)
  3006. self.menu = None
  3007. self.version = version
  3008. self.app = app
  3009. def contextMenuEvent(self, event):
  3010. # self.menu = self.createStandardContextMenu(event.pos())
  3011. self.menu = QtWidgets.QMenu()
  3012. tcursor = self.textCursor()
  3013. txt = tcursor.selectedText()
  3014. copy_action = QAction('%s\t%s' % (_("Copy"), _('Ctrl+C')), self)
  3015. self.menu.addAction(copy_action)
  3016. copy_action.triggered.connect(self.copy_text)
  3017. if txt == '':
  3018. copy_action.setDisabled(True)
  3019. self.menu.addSeparator()
  3020. sel_all_action = QAction('%s\t%s' % (_("Select All"), _('Ctrl+A')), self)
  3021. self.menu.addAction(sel_all_action)
  3022. sel_all_action.triggered.connect(self.selectAll)
  3023. if self.app:
  3024. save_action = QAction('%s\t%s' % (_("Save Log"), _('Ctrl+S')), self)
  3025. # save_action.setShortcut(QKeySequence(Qt.Key_S))
  3026. self.menu.addAction(save_action)
  3027. save_action.triggered.connect(lambda: self.save_log(app=self.app))
  3028. clear_action = QAction('%s\t%s' % (_("Clear All"), _('Del')), self)
  3029. # clear_action.setShortcut(QKeySequence(Qt.Key_Delete))
  3030. self.menu.addAction(clear_action)
  3031. clear_action.triggered.connect(self.clear)
  3032. # if self.app:
  3033. # close_action = QAction(_("Close"), self)
  3034. # self.menu.addAction(close_action)
  3035. # close_action.triggered.connect(lambda: self.app.ui.shell_dock.hide())
  3036. self.menu.exec_(event.globalPos())
  3037. def keyPressEvent(self, event) -> None:
  3038. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3039. key = event.key()
  3040. if modifiers == QtCore.Qt.ControlModifier:
  3041. # Select All
  3042. if key == QtCore.Qt.Key_A:
  3043. self.selectAll()
  3044. # Copy Text
  3045. elif key == QtCore.Qt.Key_C:
  3046. self.copy_text()
  3047. # Save Log
  3048. elif key == QtCore.Qt.Key_S:
  3049. if self.app:
  3050. self.save_log(app=self.app)
  3051. elif modifiers == QtCore.Qt.NoModifier:
  3052. # Clear all
  3053. if key == QtCore.Qt.Key_Delete:
  3054. self.clear()
  3055. # Shell toggle
  3056. if key == QtCore.Qt.Key_S:
  3057. self.app.ui.toggle_shell_ui()
  3058. def copy_text(self):
  3059. tcursor = self.textCursor()
  3060. clipboard = QtWidgets.QApplication.clipboard()
  3061. txt = tcursor.selectedText()
  3062. clipboard.clear()
  3063. clipboard.setText(txt)
  3064. def clear(self):
  3065. QTextEdit.clear(self)
  3066. text = "!FlatCAM %s? - %s" % (self.version, _("Type >help< to get started"))
  3067. text = html.escape(text)
  3068. # hack so I can make text bold because the escape method will replace the '<' and '>' signs with html code
  3069. text = text.replace('!', '<b>')
  3070. text = text.replace('?', '</b>')
  3071. text += '<br><br>'
  3072. self.moveCursor(QTextCursor.End)
  3073. self.insertHtml(text)
  3074. def save_log(self, app):
  3075. html_content = self.toHtml()
  3076. txt_content = self.toPlainText()
  3077. app.save_to_file(content_to_save=html_content, txt_content=txt_content)
  3078. class _ExpandableTextEdit(FCTextEdit):
  3079. """
  3080. Class implements edit line, which expands themselves automatically
  3081. """
  3082. historyNext = QtCore.pyqtSignal()
  3083. historyPrev = QtCore.pyqtSignal()
  3084. def __init__(self, termwidget, *args):
  3085. FCTextEdit.__init__(self, *args)
  3086. self.setStyleSheet("font: 9pt \"Courier\";")
  3087. self._fittedHeight = 1
  3088. self.textChanged.connect(self._fit_to_document)
  3089. self._fit_to_document()
  3090. self._termWidget = termwidget
  3091. self.completer = MyCompleter()
  3092. self.model = QtCore.QStringListModel()
  3093. self.completer.setModel(self.model)
  3094. self.set_model_data(keyword_list=[])
  3095. self.completer.insertText.connect(self.insertCompletion)
  3096. self.completer.popup().clicked.connect(self.insert_completion_click)
  3097. def set_model_data(self, keyword_list):
  3098. self.model.setStringList(keyword_list)
  3099. def insert_completion_click(self):
  3100. self.completer.insertText.emit(self.completer.getSelected())
  3101. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  3102. def insertCompletion(self, completion):
  3103. tc = self.textCursor()
  3104. extra = (len(completion) - len(self.completer.completionPrefix()))
  3105. # don't insert if the word is finished but add a space instead
  3106. if extra == 0:
  3107. tc.insertText(' ')
  3108. self.completer.popup().hide()
  3109. return
  3110. tc.movePosition(QTextCursor.Left)
  3111. tc.movePosition(QTextCursor.EndOfWord)
  3112. tc.insertText(completion[-extra:])
  3113. # add a space after inserting the word
  3114. tc.insertText(' ')
  3115. self.setTextCursor(tc)
  3116. self.completer.popup().hide()
  3117. def focusInEvent(self, event):
  3118. if self.completer:
  3119. self.completer.setWidget(self)
  3120. QTextEdit.focusInEvent(self, event)
  3121. def keyPressEvent(self, event):
  3122. """
  3123. Catch keyboard events. Process Enter, Up, Down
  3124. """
  3125. key = event.key()
  3126. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  3127. self.completer.insertText.emit(self.completer.getSelected())
  3128. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  3129. return
  3130. if event.matches(QKeySequence.InsertParagraphSeparator):
  3131. text = self.toPlainText()
  3132. if self._termWidget.is_command_complete(text):
  3133. self._termWidget.exec_current_command()
  3134. return
  3135. elif event.matches(QKeySequence.MoveToNextLine):
  3136. text = self.toPlainText()
  3137. cursor_pos = self.textCursor().position()
  3138. textBeforeEnd = text[cursor_pos:]
  3139. if len(textBeforeEnd.split('\n')) <= 1:
  3140. self.historyNext.emit()
  3141. return
  3142. elif event.matches(QKeySequence.MoveToPreviousLine):
  3143. text = self.toPlainText()
  3144. cursor_pos = self.textCursor().position()
  3145. text_before_start = text[:cursor_pos]
  3146. # lineCount = len(textBeforeStart.splitlines())
  3147. line_count = len(text_before_start.split('\n'))
  3148. if len(text_before_start) > 0 and \
  3149. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  3150. line_count += 1
  3151. if line_count <= 1:
  3152. self.historyPrev.emit()
  3153. return
  3154. elif event.matches(QKeySequence.MoveToNextPage) or event.matches(QKeySequence.MoveToPreviousPage):
  3155. return self._termWidget.browser().keyPressEvent(event)
  3156. tc = self.textCursor()
  3157. QTextEdit.keyPressEvent(self, event)
  3158. tc.select(QTextCursor.WordUnderCursor)
  3159. cr = self.cursorRect()
  3160. if len(tc.selectedText()) > 0:
  3161. self.completer.setCompletionPrefix(tc.selectedText())
  3162. popup = self.completer.popup()
  3163. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  3164. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  3165. + self.completer.popup().verticalScrollBar().sizeHint().width())
  3166. self.completer.complete(cr)
  3167. else:
  3168. self.completer.popup().hide()
  3169. def sizeHint(self):
  3170. """
  3171. QWidget sizeHint impelemtation
  3172. """
  3173. hint = QTextEdit.sizeHint(self)
  3174. hint.setHeight(self._fittedHeight)
  3175. return hint
  3176. def _fit_to_document(self):
  3177. """
  3178. Update widget height to fit all text
  3179. """
  3180. documentsize = self.document().size().toSize()
  3181. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  3182. self.setMaximumHeight(self._fittedHeight)
  3183. self.updateGeometry()
  3184. def insertFromMimeData(self, mime_data):
  3185. # Paste only plain text.
  3186. self.insertPlainText(mime_data.text())
  3187. class MyCompleter(QCompleter):
  3188. insertText = QtCore.pyqtSignal(str)
  3189. def __init__(self, parent=None):
  3190. QCompleter.__init__(self, parent=parent)
  3191. self.setCompletionMode(QCompleter.PopupCompletion)
  3192. self.highlighted.connect(self.setHighlighted)
  3193. self.lastSelected = ''
  3194. # self.popup().installEventFilter(self)
  3195. # def eventFilter(self, obj, event):
  3196. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  3197. # pass
  3198. # return False
  3199. def setHighlighted(self, text):
  3200. self.lastSelected = text
  3201. def getSelected(self):
  3202. return self.lastSelected
  3203. class FCTextAreaLineNumber(QtWidgets.QFrame):
  3204. textChanged = QtCore.pyqtSignal()
  3205. class NumberBar(QtWidgets.QWidget):
  3206. def __init__(self, edit):
  3207. QtWidgets.QWidget.__init__(self, edit)
  3208. self.edit = edit
  3209. self.adjustWidth(1)
  3210. def paintEvent(self, event):
  3211. self.edit.numberbarPaint(self, event)
  3212. QtWidgets.QWidget.paintEvent(self, event)
  3213. def adjustWidth(self, count):
  3214. # three spaces added to the width to make up for the space added in the line number
  3215. width = self.fontMetrics().width(str(count) + ' ')
  3216. if self.width() != width:
  3217. self.setFixedWidth(width)
  3218. def updateContents(self, rect, scroll):
  3219. if scroll:
  3220. self.scroll(0, scroll)
  3221. else:
  3222. # It would be nice to do
  3223. # self.update(0, rect.y(), self.width(), rect.height())
  3224. # But we can't because it will not remove the bold on the
  3225. # current line if word wrap is enabled and a new block is
  3226. # selected.
  3227. self.update()
  3228. class PlainTextEdit(FCPlainTextAreaExtended):
  3229. """
  3230. TextEdit with line numbers and highlight
  3231. From here: https://nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/
  3232. and from here: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
  3233. """
  3234. def __init__(self, *args):
  3235. FCPlainTextAreaExtended.__init__(self, *args)
  3236. # self.setFrameStyle(QFrame.NoFrame)
  3237. self.setFrameStyle(QtWidgets.QFrame.NoFrame)
  3238. self.highlight()
  3239. # self.setLineWrapMode(QPlainTextEdit.NoWrap)
  3240. self.cursorPositionChanged.connect(self.highlight)
  3241. def highlight(self):
  3242. hi_selection = QTextEdit.ExtraSelection()
  3243. hi_selection.format.setBackground(self.palette().alternateBase())
  3244. hi_selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
  3245. hi_selection.cursor = self.textCursor()
  3246. hi_selection.cursor.clearSelection()
  3247. self.setExtraSelections([hi_selection])
  3248. def numberbarPaint(self, number_bar, event):
  3249. font_metrics = self.fontMetrics()
  3250. current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
  3251. painter = QtGui.QPainter(number_bar)
  3252. painter.fillRect(event.rect(), QtCore.Qt.lightGray)
  3253. block = self.firstVisibleBlock()
  3254. line_count = int(block.blockNumber())
  3255. block_top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
  3256. block_bottom = block_top + int(self.blockBoundingRect(block).height())
  3257. # Iterate over all visible text blocks in the document.
  3258. while block.isValid() and block_top <= event.rect().bottom():
  3259. line_count += 1
  3260. # Check if the position of the block is out side of the visible
  3261. # area.
  3262. if block.isVisible() and block_bottom >= event.rect().top():
  3263. # We want the line number for the selected line to be bold.
  3264. if line_count == current_line:
  3265. font = painter.font()
  3266. font.setBold(True)
  3267. painter.setPen(QtCore.Qt.blue)
  3268. painter.setFont(font)
  3269. else:
  3270. font = painter.font()
  3271. font.setBold(False)
  3272. painter.setPen(self.palette().base().color())
  3273. painter.setFont(font)
  3274. # Draw the line number right justified at the position of the line.
  3275. paint_rect = QtCore.QRect(0, block_top, number_bar.width(), font_metrics.height())
  3276. # I add some spaces to the line_count to prettify; make sure to remember adjust the width in the
  3277. # NumberBar() class above
  3278. painter.drawText(paint_rect, Qt.AlignRight, ' ' + str(line_count) + ' ')
  3279. block = block.next()
  3280. block_top = block_bottom
  3281. block_bottom = block_top + self.blockBoundingRect(block).height()
  3282. painter.end()
  3283. def __init__(self, *args):
  3284. QtWidgets.QFrame.__init__(self, *args)
  3285. self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Sunken)
  3286. self.edit = self.PlainTextEdit()
  3287. self.number_bar = self.NumberBar(self.edit)
  3288. hbox = QtWidgets.QHBoxLayout(self)
  3289. hbox.setSpacing(0)
  3290. hbox.setContentsMargins(0, 0, 0, 0)
  3291. hbox.addWidget(self.number_bar)
  3292. hbox.addWidget(self.edit)
  3293. self.edit.blockCountChanged.connect(self.number_bar.adjustWidth)
  3294. self.edit.updateRequest.connect(self.number_bar.updateContents)
  3295. def getText(self):
  3296. return str(self.edit.toPlainText())
  3297. def setText(self, text):
  3298. self.edit.setPlainText(text)
  3299. def isModified(self):
  3300. return self.edit.document().isModified()
  3301. def setModified(self, modified):
  3302. self.edit.document().setModified(modified)
  3303. def setLineWrapMode(self, mode):
  3304. self.edit.setLineWrapMode(mode)
  3305. class FCFileSaveDialog(QtWidgets.QFileDialog):
  3306. def __init__(self, *args):
  3307. super(FCFileSaveDialog, self).__init__(*args)
  3308. @staticmethod
  3309. def get_saved_filename(parent=None, caption='', directory='', ext_filter='', initialFilter=''):
  3310. filename, _filter = QtWidgets.QFileDialog.getSaveFileName(parent=parent, caption=caption,
  3311. directory=directory, filter=ext_filter,
  3312. initialFilter=initialFilter)
  3313. filename = str(filename)
  3314. if filename == '':
  3315. return filename, _filter
  3316. extension = '.' + _filter.strip(')').rpartition('.')[2]
  3317. if filename.endswith(extension) or extension == '.*':
  3318. return filename, _filter
  3319. else:
  3320. filename += extension
  3321. return filename, _filter
  3322. class FCDock(QtWidgets.QDockWidget):
  3323. def __init__(self, *args, **kwargs):
  3324. super(FCDock, self).__init__(*args)
  3325. self.close_callback = kwargs["close_callback"] if "close_callback" in kwargs else None
  3326. def closeEvent(self, event: QtGui.QCloseEvent) -> None:
  3327. self.close_callback()
  3328. super().closeEvent(event)
  3329. def show(self) -> None:
  3330. if self.isFloating():
  3331. self.setFloating(False)
  3332. super().show()
  3333. class FCJog(QtWidgets.QFrame):
  3334. def __init__(self, app, *args, **kwargs):
  3335. super(FCJog, self).__init__(*args, **kwargs)
  3336. self.app = app
  3337. self.setFrameShape(QtWidgets.QFrame.Box)
  3338. self.setLineWidth(1)
  3339. # JOG axes
  3340. grbl_jog_grid = QtWidgets.QGridLayout()
  3341. grbl_jog_grid.setAlignment(QtCore.Qt.AlignCenter)
  3342. grbl_jog_grid.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
  3343. grbl_jog_grid.setContentsMargins(2, 4, 2, 4)
  3344. self.setLayout(grbl_jog_grid)
  3345. # JOG Y Up
  3346. self.jog_up_button = QtWidgets.QToolButton()
  3347. self.jog_up_button.setIcon(QtGui.QIcon(self.app.resource_location + '/up-arrow32.png'))
  3348. self.jog_up_button.setToolTip(
  3349. _("Jog the Y axis.")
  3350. )
  3351. grbl_jog_grid.addWidget(self.jog_up_button, 2, 1)
  3352. # Origin
  3353. self.jog_origin_button = QtWidgets.QToolButton()
  3354. self.jog_origin_button.setIcon(QtGui.QIcon(self.app.resource_location + '/origin2_32.png'))
  3355. self.jog_origin_button.setToolTip(
  3356. '%s' % _("Move to Origin")
  3357. )
  3358. grbl_jog_grid.addWidget(self.jog_origin_button, 3, 1)
  3359. # JOG Y Down
  3360. self.jog_down_button = QtWidgets.QToolButton()
  3361. self.jog_down_button.setIcon(QtGui.QIcon(self.app.resource_location + '/down-arrow32.png'))
  3362. self.jog_down_button.setToolTip(
  3363. _("Jog the Y axis.")
  3364. )
  3365. grbl_jog_grid.addWidget(self.jog_down_button, 4, 1)
  3366. # JOG X Left
  3367. self.jog_left_button = QtWidgets.QToolButton()
  3368. self.jog_left_button.setIcon(QtGui.QIcon(self.app.resource_location + '/left_arrow32.png'))
  3369. self.jog_left_button.setToolTip(
  3370. _("Jog the X axis.")
  3371. )
  3372. grbl_jog_grid.addWidget(self.jog_left_button, 3, 0)
  3373. # JOG X Right
  3374. self.jog_right_button = QtWidgets.QToolButton()
  3375. self.jog_right_button.setIcon(QtGui.QIcon(self.app.resource_location + '/right_arrow32.png'))
  3376. self.jog_right_button.setToolTip(
  3377. _("Jog the X axis.")
  3378. )
  3379. grbl_jog_grid.addWidget(self.jog_right_button, 3, 2)
  3380. # JOG Z Up
  3381. self.jog_z_up_button = QtWidgets.QToolButton()
  3382. self.jog_z_up_button.setIcon(QtGui.QIcon(self.app.resource_location + '/up-arrow32.png'))
  3383. self.jog_z_up_button.setText('Z')
  3384. self.jog_z_up_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
  3385. self.jog_z_up_button.setToolTip(
  3386. _("Jog the Z axis.")
  3387. )
  3388. grbl_jog_grid.addWidget(self.jog_z_up_button, 2, 3)
  3389. # JOG Z Down
  3390. self.jog_z_down_button = QtWidgets.QToolButton()
  3391. self.jog_z_down_button.setIcon(QtGui.QIcon(self.app.resource_location + '/down-arrow32.png'))
  3392. self.jog_z_down_button.setText('Z')
  3393. self.jog_z_down_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
  3394. self.jog_z_down_button.setToolTip(
  3395. _("Jog the Z axis.")
  3396. )
  3397. grbl_jog_grid.addWidget(self.jog_z_down_button, 4, 3)
  3398. class FCZeroAxes(QtWidgets.QFrame):
  3399. def __init__(self, app, *args, **kwargs):
  3400. super(FCZeroAxes, self).__init__(*args, **kwargs)
  3401. self.app = app
  3402. self.setFrameShape(QtWidgets.QFrame.Box)
  3403. self.setLineWidth(1)
  3404. # Zero the axes
  3405. grbl_zero_grid = QtWidgets.QGridLayout()
  3406. grbl_zero_grid.setContentsMargins(2, 4, 2, 4)
  3407. grbl_zero_grid.setColumnStretch(0, 0)
  3408. grbl_zero_grid.setColumnStretch(1, 0)
  3409. # grbl_zero_grid.setRowStretch(4, 1)
  3410. self.setLayout(grbl_zero_grid)
  3411. # Zero X axis
  3412. self.grbl_zerox_button = QtWidgets.QToolButton()
  3413. self.grbl_zerox_button.setText(_("X"))
  3414. self.grbl_zerox_button.setToolTip(
  3415. _("Zero the CNC X axes at current position.")
  3416. )
  3417. grbl_zero_grid.addWidget(self.grbl_zerox_button, 1, 0)
  3418. # Zero Y axis
  3419. self.grbl_zeroy_button = QtWidgets.QToolButton()
  3420. self.grbl_zeroy_button.setText(_("Y"))
  3421. self.grbl_zeroy_button.setToolTip(
  3422. _("Zero the CNC Y axes at current position.")
  3423. )
  3424. grbl_zero_grid.addWidget(self.grbl_zeroy_button, 2, 0)
  3425. # Zero Z axis
  3426. self.grbl_zeroz_button = QtWidgets.QToolButton()
  3427. self.grbl_zeroz_button.setText(_("Z"))
  3428. self.grbl_zeroz_button.setToolTip(
  3429. _("Zero the CNC Z axes at current position.")
  3430. )
  3431. grbl_zero_grid.addWidget(self.grbl_zeroz_button, 3, 0)
  3432. self.grbl_homing_button = QtWidgets.QToolButton()
  3433. self.grbl_homing_button.setText(_("Do Home"))
  3434. self.grbl_homing_button.setToolTip(
  3435. _("Perform a homing cycle on all axis."))
  3436. grbl_zero_grid.addWidget(self.grbl_homing_button, 4, 0, 1, 2)
  3437. # Zeroo all axes
  3438. self.grbl_zero_all_button = QtWidgets.QToolButton()
  3439. self.grbl_zero_all_button.setText(_("All"))
  3440. self.grbl_zero_all_button.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
  3441. self.grbl_zero_all_button.setToolTip(
  3442. _("Zero all CNC axes at current position.")
  3443. )
  3444. grbl_zero_grid.addWidget(self.grbl_zero_all_button, 1, 1, 3, 1)
  3445. class RotatedToolButton(QtWidgets.QToolButton):
  3446. def __init__(self, orientation="east", *args, **kwargs):
  3447. super(RotatedToolButton, self).__init__(*args, **kwargs)
  3448. self.orientation = orientation
  3449. def paintEvent(self, event):
  3450. painter = QtWidgets.QStylePainter(self)
  3451. if self.orientation == "east":
  3452. painter.rotate(270)
  3453. painter.translate(-1 * self.height(), 0)
  3454. if self.orientation == "west":
  3455. painter.rotate(90)
  3456. painter.translate(0, -1 * self.width())
  3457. painter.drawControl(QtWidgets.QStyle.CE_PushButton, self.getSyleOptions())
  3458. def minimumSizeHint(self):
  3459. size = super(RotatedToolButton, self).minimumSizeHint()
  3460. size.transpose()
  3461. return size
  3462. def sizeHint(self):
  3463. size = super(RotatedToolButton, self).sizeHint()
  3464. size.transpose()
  3465. return size
  3466. def getSyleOptions(self):
  3467. options = QtWidgets.QStyleOptionButton()
  3468. options.initFrom(self)
  3469. size = options.rect.size()
  3470. size.transpose()
  3471. options.rect.setSize(size)
  3472. options.features = QtWidgets.QStyleOptionButton.None_
  3473. # if self.isFlat():
  3474. # options.features |= QtWidgets.QStyleOptionButton.Flat
  3475. if self.menu():
  3476. options.features |= QtWidgets.QStyleOptionButton.HasMenu
  3477. # if self.autoDefault() or self.isDefault():
  3478. # options.features |= QtWidgets.QStyleOptionButton.AutoDefaultButton
  3479. # if self.isDefault():
  3480. # options.features |= QtWidgets.QStyleOptionButton.DefaultButton
  3481. if self.isDown() or (self.menu() and self.menu().isVisible()):
  3482. options.state |= QtWidgets.QStyle.State_Sunken
  3483. if self.isChecked():
  3484. options.state |= QtWidgets.QStyle.State_On
  3485. # if not self.isFlat() and not self.isDown():
  3486. # options.state |= QtWidgets.QStyle.State_Raised
  3487. options.text = self.text()
  3488. options.icon = self.icon()
  3489. options.iconSize = self.iconSize()
  3490. return options
  3491. class RotatedButton(QtWidgets.QPushButton):
  3492. def __init__(self, orientation="west", *args, **kwargs):
  3493. super(RotatedButton, self).__init__(*args, **kwargs)
  3494. self.orientation = orientation
  3495. def paintEvent(self, event):
  3496. painter = QtWidgets.QStylePainter(self)
  3497. if self.orientation == "east":
  3498. painter.rotate(270)
  3499. painter.translate(-1 * self.height(), 0)
  3500. if self.orientation == "west":
  3501. painter.rotate(90)
  3502. painter.translate(0, -1 * self.width())
  3503. painter.drawControl(QtWidgets.QStyle.CE_PushButton, self.getSyleOptions())
  3504. def minimumSizeHint(self):
  3505. size = super(RotatedButton, self).minimumSizeHint()
  3506. size.transpose()
  3507. return size
  3508. def sizeHint(self):
  3509. size = super(RotatedButton, self).sizeHint()
  3510. size.transpose()
  3511. return size
  3512. def getSyleOptions(self):
  3513. options = QtWidgets.QStyleOptionButton()
  3514. options.initFrom(self)
  3515. size = options.rect.size()
  3516. size.transpose()
  3517. options.rect.setSize(size)
  3518. options.features = QtWidgets.QStyleOptionButton.None_
  3519. if self.isFlat():
  3520. options.features |= QtWidgets.QStyleOptionButton.Flat
  3521. if self.menu():
  3522. options.features |= QtWidgets.QStyleOptionButton.HasMenu
  3523. if self.autoDefault() or self.isDefault():
  3524. options.features |= QtWidgets.QStyleOptionButton.AutoDefaultButton
  3525. if self.isDefault():
  3526. options.features |= QtWidgets.QStyleOptionButton.DefaultButton
  3527. if self.isDown() or (self.menu() and self.menu().isVisible()):
  3528. options.state |= QtWidgets.QStyle.State_Sunken
  3529. if self.isChecked():
  3530. options.state |= QtWidgets.QStyle.State_On
  3531. if not self.isFlat() and not self.isDown():
  3532. options.state |= QtWidgets.QStyle.State_Raised
  3533. options.text = self.text()
  3534. options.icon = self.icon()
  3535. options.iconSize = self.iconSize()
  3536. return options
  3537. class FlatCAMActivityView(QtWidgets.QWidget):
  3538. """
  3539. This class create and control the activity icon displayed in the App status bar
  3540. """
  3541. def __init__(self, app, parent=None):
  3542. super().__init__(parent=parent)
  3543. self.app = app
  3544. if self.app.defaults["global_activity_icon"] == "Ball green":
  3545. icon = self.app.resource_location + '/active_2_static.png'
  3546. movie = self.app.resource_location + "/active_2.gif"
  3547. elif self.app.defaults["global_activity_icon"] == "Ball black":
  3548. icon = self.app.resource_location + '/active_static.png'
  3549. movie = self.app.resource_location + "/active.gif"
  3550. elif self.app.defaults["global_activity_icon"] == "Arrow green":
  3551. icon = self.app.resource_location + '/active_3_static.png'
  3552. movie = self.app.resource_location + "/active_3.gif"
  3553. elif self.app.defaults["global_activity_icon"] == "Eclipse green":
  3554. icon = self.app.resource_location + '/active_4_static.png'
  3555. movie = self.app.resource_location + "/active_4.gif"
  3556. else:
  3557. icon = self.app.resource_location + '/active_static.png'
  3558. movie = self.app.resource_location + "/active.gif"
  3559. self.setMinimumWidth(200)
  3560. self.movie_path = movie
  3561. self.icon_path = icon
  3562. self.icon = FCLabel(self)
  3563. self.icon.setGeometry(0, 0, 16, 12)
  3564. self.movie = QtGui.QMovie(self.movie_path)
  3565. self.icon.setMovie(self.movie)
  3566. # self.movie.start()
  3567. layout = QtWidgets.QHBoxLayout()
  3568. layout.setContentsMargins(5, 0, 5, 0)
  3569. layout.setAlignment(QtCore.Qt.AlignLeft)
  3570. self.setLayout(layout)
  3571. layout.addWidget(self.icon)
  3572. self.text = QtWidgets.QLabel(self)
  3573. self.text.setText(_("Idle."))
  3574. self.icon.setPixmap(QtGui.QPixmap(self.icon_path))
  3575. layout.addWidget(self.text)
  3576. self.icon.clicked.connect(self.app.on_toolbar_replot)
  3577. def set_idle(self):
  3578. self.movie.stop()
  3579. self.text.setText(_("Idle."))
  3580. def set_busy(self, msg, no_movie=None):
  3581. if no_movie is not True:
  3582. self.icon.setMovie(self.movie)
  3583. self.movie.start()
  3584. self.text.setText(msg)
  3585. class FlatCAMInfoBar(QtWidgets.QWidget):
  3586. """
  3587. This class create a place to display the App messages in the Status Bar
  3588. """
  3589. def __init__(self, parent=None, app=None):
  3590. super(FlatCAMInfoBar, self).__init__(parent=parent)
  3591. self.app = app
  3592. self.icon = QtWidgets.QLabel(self)
  3593. self.icon.setGeometry(0, 0, 12, 12)
  3594. self.pmap = QtGui.QPixmap(self.app.resource_location + '/graylight12.png')
  3595. self.icon.setPixmap(self.pmap)
  3596. self.lock_pmaps = False
  3597. layout = QtWidgets.QHBoxLayout()
  3598. layout.setContentsMargins(5, 0, 5, 0)
  3599. self.setLayout(layout)
  3600. layout.addWidget(self.icon)
  3601. self.text = QtWidgets.QLabel(self)
  3602. self.text.setText(_("Application started ..."))
  3603. self.text.setToolTip(_("Hello!"))
  3604. layout.addWidget(self.text)
  3605. layout.addStretch()
  3606. def set_text_(self, text, color=None):
  3607. self.text.setText(text)
  3608. self.text.setToolTip(text)
  3609. if color:
  3610. self.text.setStyleSheet('color: %s' % str(color))
  3611. def set_status(self, text, level="info"):
  3612. level = str(level)
  3613. if self.lock_pmaps is not True:
  3614. self.pmap.fill()
  3615. if level == "ERROR" or level == "ERROR_NOTCL":
  3616. self.pmap = QtGui.QPixmap(self.app.resource_location + '/redlight12.png')
  3617. elif level.lower() == "success":
  3618. self.pmap = QtGui.QPixmap(self.app.resource_location + '/greenlight12.png')
  3619. elif level == "WARNING" or level == "WARNING_NOTCL":
  3620. self.pmap = QtGui.QPixmap(self.app.resource_location + '/yellowlight12.png')
  3621. elif level.lower() == "selected":
  3622. self.pmap = QtGui.QPixmap(self.app.resource_location + '/bluelight12.png')
  3623. else:
  3624. self.pmap = QtGui.QPixmap(self.app.resource_location + '/graylight12.png')
  3625. try:
  3626. self.set_text_(text)
  3627. self.icon.setPixmap(self.pmap)
  3628. except Exception as e:
  3629. log.debug("FlatCAMInfoBar.set_status() --> %s" % str(e))
  3630. class FlatCAMSystemTray(QtWidgets.QSystemTrayIcon):
  3631. """
  3632. This class create the Sys Tray icon for the app
  3633. """
  3634. def __init__(self, app, icon, headless=None, parent=None):
  3635. # QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
  3636. super().__init__(icon, parent=parent)
  3637. self.app = app
  3638. menu = QtWidgets.QMenu(parent)
  3639. menu_runscript = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/script14.png'),
  3640. '%s' % _('Run Script ...'), self)
  3641. menu_runscript.setToolTip(
  3642. _("Will run the opened Tcl Script thus\n"
  3643. "enabling the automation of certain\n"
  3644. "functions of FlatCAM.")
  3645. )
  3646. menu.addAction(menu_runscript)
  3647. menu.addSeparator()
  3648. if headless is None:
  3649. self.menu_open = menu.addMenu(QtGui.QIcon(self.app.resource_location + '/folder32_bis.png'), _('Open'))
  3650. # Open Project ...
  3651. menu_openproject = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/folder16.png'),
  3652. '%s ...' % _('Open Project'), self)
  3653. self.menu_open.addAction(menu_openproject)
  3654. self.menu_open.addSeparator()
  3655. # Open Gerber ...
  3656. menu_opengerber = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/flatcam_icon24.png'),
  3657. '%s ...\t%s' % (_('Open Gerber'), _('Ctrl+G')), self)
  3658. self.menu_open.addAction(menu_opengerber)
  3659. # Open Excellon ...
  3660. menu_openexcellon = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/open_excellon32.png'),
  3661. '%s ...\t%s' % (_('Open Excellon'), _('Ctrl+E')), self)
  3662. self.menu_open.addAction(menu_openexcellon)
  3663. # Open G-Code ...
  3664. menu_opengcode = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/code.png'),
  3665. '%s ...' % _('Open G-Code'), self)
  3666. self.menu_open.addAction(menu_opengcode)
  3667. self.menu_open.addSeparator()
  3668. menu_openproject.triggered.connect(self.app.f_handlers.on_file_openproject)
  3669. menu_opengerber.triggered.connect(self.app.f_handlers.on_fileopengerber)
  3670. menu_openexcellon.triggered.connect(self.app.f_handlers.on_fileopenexcellon)
  3671. menu_opengcode.triggered.connect(self.app.f_handlers.on_fileopengcode)
  3672. exitAction = menu.addAction(_("Exit"))
  3673. exitAction.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  3674. self.setContextMenu(menu)
  3675. menu_runscript.triggered.connect(lambda: self.app.on_filerunscript(
  3676. silent=True if self.app.cmd_line_headless == 1 else False))
  3677. exitAction.triggered.connect(self.app.final_save)
  3678. def message_dialog(title, message, kind="info", parent=None):
  3679. """
  3680. Builds and show a custom QMessageBox to be used in FlatCAM.
  3681. :param title: title of the QMessageBox
  3682. :param message: message to be displayed
  3683. :param kind: type of QMessageBox; will display a specific icon.
  3684. :param parent: parent
  3685. :return: None
  3686. """
  3687. icon = {"info": QtWidgets.QMessageBox.Information,
  3688. "warning": QtWidgets.QMessageBox.Warning,
  3689. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3690. dlg = QtWidgets.QMessageBox(icon, title, message, parent=parent)
  3691. dlg.setText(message)
  3692. dlg.exec_()
  3693. def rreplace(s, old, new, occurrence):
  3694. """
  3695. Credits go here:
  3696. https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
  3697. :param s: string to be processed
  3698. :param old: old char to be replaced
  3699. :param new: new char to replace the old one
  3700. :param occurrence: how many places from end to replace the old char
  3701. :return: modified string
  3702. """
  3703. li = s.rsplit(old, occurrence)
  3704. return new.join(li)