GUIElements.py 159 KB

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