GUIElements.py 158 KB

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