GUIElements.py 159 KB

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