GUIElements.py 162 KB

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