GUIElements.py 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613
  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, 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 LengthEntry(QtWidgets.QLineEdit):
  231. def __init__(self, output_units='IN', decimals=None, parent=None):
  232. super(LengthEntry, self).__init__(parent)
  233. self.output_units = output_units
  234. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  235. # Unit conversion table OUTPUT-INPUT
  236. self.scales = {
  237. 'IN': {'IN': 1.0,
  238. 'MM': 1/25.4},
  239. 'MM': {'IN': 25.4,
  240. 'MM': 1.0}
  241. }
  242. self.readyToEdit = True
  243. self.editingFinished.connect(self.on_edit_finished)
  244. self.decimals = decimals if decimals is not None else 4
  245. def on_edit_finished(self):
  246. self.clearFocus()
  247. def mousePressEvent(self, e, Parent=None):
  248. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  249. if self.readyToEdit:
  250. self.selectAll()
  251. self.readyToEdit = False
  252. def focusOutEvent(self, e):
  253. # don't focus out if the user requests an popup menu
  254. if e.reason() != QtCore.Qt.PopupFocusReason:
  255. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  256. self.deselect()
  257. self.readyToEdit = True
  258. def returnPressed(self, *args, **kwargs):
  259. val = self.get_value()
  260. if val is not None:
  261. self.set_text(str(val))
  262. else:
  263. log.warning("Could not interpret entry: %s" % self.get_text())
  264. def get_value(self):
  265. raw = str(self.text()).strip(' ')
  266. # match = self.format_re.search(raw)
  267. try:
  268. units = raw[-2:]
  269. units = self.scales[self.output_units][units.upper()]
  270. value = raw[:-2]
  271. return float(eval(value)) * units
  272. except IndexError:
  273. value = raw
  274. return float(eval(value))
  275. except KeyError:
  276. value = raw
  277. return float(eval(value))
  278. except Exception:
  279. log.warning("Could not parse value in entry: %s" % str(raw))
  280. return None
  281. def set_value(self, val, decimals=None):
  282. dec_digits = decimals if decimals is not None else self.decimals
  283. self.setText(str('%.*f' % (dec_digits, val)))
  284. def sizeHint(self):
  285. default_hint_size = super(LengthEntry, self).sizeHint()
  286. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  287. class FloatEntry(QtWidgets.QLineEdit):
  288. def __init__(self, decimals=None, parent=None):
  289. super(FloatEntry, self).__init__(parent)
  290. self.readyToEdit = True
  291. self.editingFinished.connect(self.on_edit_finished)
  292. self.decimals = decimals if decimals is not None else 4
  293. def on_edit_finished(self):
  294. self.clearFocus()
  295. def mousePressEvent(self, e, Parent=None):
  296. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  297. if self.readyToEdit is True:
  298. self.selectAll()
  299. self.readyToEdit = False
  300. def focusOutEvent(self, e):
  301. # don't focus out if the user requests an popup menu
  302. if e.reason() != QtCore.Qt.PopupFocusReason:
  303. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  304. self.deselect()
  305. self.readyToEdit = True
  306. def returnPressed(self, *args, **kwargs):
  307. val = self.get_value()
  308. if val is not None:
  309. self.set_text(str(val))
  310. else:
  311. log.warning("Could not interpret entry: %s" % self.text())
  312. def get_value(self):
  313. raw = str(self.text()).strip(' ')
  314. try:
  315. evaled = eval(raw)
  316. return float(evaled)
  317. except Exception as e:
  318. if raw != '':
  319. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  320. return None
  321. def set_value(self, val, decimals=None):
  322. dig_digits = decimals if decimals is not None else self.decimals
  323. if val is not None:
  324. self.setText("%.*f" % (dig_digits, float(val)))
  325. else:
  326. self.setText("")
  327. def sizeHint(self):
  328. default_hint_size = super(FloatEntry, self).sizeHint()
  329. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  330. class FloatEntry2(QtWidgets.QLineEdit):
  331. def __init__(self, decimals=None, parent=None):
  332. super(FloatEntry2, self).__init__(parent)
  333. self.readyToEdit = True
  334. self.editingFinished.connect(self.on_edit_finished)
  335. self.decimals = decimals if decimals is not None else 4
  336. def on_edit_finished(self):
  337. self.clearFocus()
  338. def mousePressEvent(self, e, Parent=None):
  339. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  340. if self.readyToEdit:
  341. self.selectAll()
  342. self.readyToEdit = False
  343. def focusOutEvent(self, e):
  344. # don't focus out if the user requests an popup menu
  345. if e.reason() != QtCore.Qt.PopupFocusReason:
  346. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  347. self.deselect()
  348. self.readyToEdit = True
  349. def get_value(self):
  350. raw = str(self.text()).strip(' ')
  351. try:
  352. evaled = eval(raw)
  353. return float(evaled)
  354. except Exception as e:
  355. if raw != '':
  356. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  357. return None
  358. def set_value(self, val, decimals=None):
  359. dig_digits = decimals if decimals is not None else self.decimals
  360. self.setText("%.*f" % (dig_digits, val))
  361. def sizeHint(self):
  362. default_hint_size = super(FloatEntry2, self).sizeHint()
  363. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  364. class IntEntry(QtWidgets.QLineEdit):
  365. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  366. super(IntEntry, self).__init__(parent)
  367. self.allow_empty = allow_empty
  368. self.empty_val = empty_val
  369. self.readyToEdit = True
  370. self.editingFinished.connect(self.on_edit_finished)
  371. def on_edit_finished(self):
  372. self.clearFocus()
  373. def mousePressEvent(self, e, Parent=None):
  374. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  375. if self.readyToEdit:
  376. self.selectAll()
  377. self.readyToEdit = False
  378. def focusOutEvent(self, e):
  379. # don't focus out if the user requests an popup menu
  380. if e.reason() != QtCore.Qt.PopupFocusReason:
  381. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  382. self.deselect()
  383. self.readyToEdit = True
  384. def get_value(self):
  385. if self.allow_empty:
  386. if str(self.text()) == "":
  387. return self.empty_val
  388. # make the text() first a float and then int because if text is a float type,
  389. # the int() can't convert directly a "text float" into a int type.
  390. ret_val = float(self.text())
  391. ret_val = int(ret_val)
  392. return ret_val
  393. def set_value(self, val):
  394. if val == self.empty_val and self.allow_empty:
  395. self.setText("")
  396. return
  397. self.setText(str(val))
  398. def sizeHint(self):
  399. default_hint_size = super(IntEntry, self).sizeHint()
  400. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  401. class FCEntry(QtWidgets.QLineEdit):
  402. def __init__(self, decimals=None, alignment=None, border_color=None, parent=None):
  403. super(FCEntry, self).__init__(parent)
  404. self.readyToEdit = True
  405. self.editingFinished.connect(self.on_edit_finished)
  406. self.decimals = decimals if decimals is not None else 4
  407. if border_color:
  408. self.setStyleSheet("QLineEdit {border: 1px solid %s;}" % border_color)
  409. if alignment:
  410. if alignment == 'center':
  411. align_val = QtCore.Qt.AlignHCenter
  412. elif alignment == 'right':
  413. align_val = QtCore.Qt.AlignRight
  414. else:
  415. align_val = QtCore.Qt.AlignLeft
  416. self.setAlignment(align_val)
  417. def on_edit_finished(self):
  418. self.clearFocus()
  419. def mousePressEvent(self, e, parent=None):
  420. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  421. if self.readyToEdit:
  422. self.selectAll()
  423. self.readyToEdit = False
  424. def focusOutEvent(self, e):
  425. if e.reason() != QtCore.Qt.PopupFocusReason:
  426. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  427. self.deselect()
  428. self.readyToEdit = True
  429. def get_value(self):
  430. return str(self.text())
  431. def set_value(self, val, decimals=None):
  432. decimal_digits = decimals if decimals is not None else self.decimals
  433. if type(val) is float:
  434. self.setText('%.*f' % (decimal_digits, val))
  435. elif val is None:
  436. self.setText('')
  437. else:
  438. self.setText(str(val))
  439. def sizeHint(self):
  440. default_hint_size = super(FCEntry, self).sizeHint()
  441. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  442. class FCEntry2(FCEntry):
  443. def __init__(self, parent=None):
  444. super(FCEntry2, self).__init__(parent)
  445. def set_value(self, val, decimals=4):
  446. try:
  447. fval = float(val)
  448. except ValueError:
  449. return
  450. self.setText('%.*f' % (decimals, fval))
  451. class FCEntry3(FCEntry):
  452. def __init__(self, parent=None):
  453. super(FCEntry3, self).__init__(parent)
  454. def set_value(self, val, decimals=4):
  455. try:
  456. fval = float(val)
  457. except ValueError:
  458. return
  459. self.setText('%.*f' % (decimals, fval))
  460. def get_value(self):
  461. value = str(self.text()).strip(' ')
  462. try:
  463. return float(eval(value))
  464. except Exception as e:
  465. log.warning("Could not parse value in entry: %s" % str(e))
  466. return None
  467. class EvalEntry(QtWidgets.QLineEdit):
  468. def __init__(self, border_color=None, parent=None):
  469. super(EvalEntry, self).__init__(parent)
  470. self.readyToEdit = True
  471. if border_color:
  472. self.setStyleSheet("QLineEdit {border: 1px solid %s;}" % border_color)
  473. self.editingFinished.connect(self.on_edit_finished)
  474. def on_edit_finished(self):
  475. self.clearFocus()
  476. def mousePressEvent(self, e, parent=None):
  477. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  478. if self.readyToEdit:
  479. self.selectAll()
  480. self.readyToEdit = False
  481. def focusOutEvent(self, e):
  482. if e.reason() != QtCore.Qt.PopupFocusReason:
  483. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  484. self.deselect()
  485. self.readyToEdit = True
  486. def returnPressed(self, *args, **kwargs):
  487. val = self.get_value()
  488. if val is not None:
  489. self.setText(str(val))
  490. else:
  491. log.warning("Could not interpret entry: %s" % self.get_text())
  492. def get_value(self):
  493. raw = str(self.text()).strip(' ')
  494. try:
  495. evaled = eval(raw)
  496. except Exception as e:
  497. if raw != '':
  498. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  499. return None
  500. return evaled
  501. def set_value(self, val):
  502. self.setText(str(val))
  503. def sizeHint(self):
  504. default_hint_size = super(EvalEntry, self).sizeHint()
  505. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  506. class EvalEntry2(QtWidgets.QLineEdit):
  507. def __init__(self, parent=None):
  508. super(EvalEntry2, self).__init__(parent)
  509. self.readyToEdit = True
  510. self.editingFinished.connect(self.on_edit_finished)
  511. def on_edit_finished(self):
  512. self.clearFocus()
  513. def mousePressEvent(self, e, parent=None):
  514. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  515. if self.readyToEdit:
  516. self.selectAll()
  517. self.readyToEdit = False
  518. def focusOutEvent(self, e):
  519. if e.reason() != QtCore.Qt.PopupFocusReason:
  520. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  521. self.deselect()
  522. self.readyToEdit = True
  523. def get_value(self):
  524. raw = str(self.text()).strip(' ')
  525. try:
  526. evaled = eval(raw)
  527. except Exception as e:
  528. if raw != '':
  529. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  530. return None
  531. return evaled
  532. def set_value(self, val):
  533. self.setText(str(val))
  534. def sizeHint(self):
  535. default_hint_size = super(EvalEntry2, self).sizeHint()
  536. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  537. class NumericalEvalEntry(FCEntry):
  538. """
  539. Will evaluate the input and return a value. Accepts only float numbers and formulas using the operators: /,*,+,-,%
  540. """
  541. def __init__(self, border_color=None):
  542. super().__init__(border_color=border_color)
  543. regex = QtCore.QRegExp("[0-9\/\*\+\-\%\.\,\s]*")
  544. validator = QtGui.QRegExpValidator(regex, self)
  545. self.setValidator(validator)
  546. def get_value(self):
  547. raw = str(self.text()).strip(' ')
  548. raw = raw.replace(',', '.')
  549. try:
  550. evaled = eval(raw)
  551. except Exception as e:
  552. if raw != '':
  553. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  554. return None
  555. return evaled
  556. class NumericalEvalTupleEntry(EvalEntry):
  557. """
  558. Will return a text value. Accepts only float numbers and formulas using the operators: /,*,+,-,%
  559. """
  560. def __init__(self, border_color=None):
  561. super().__init__(border_color=border_color)
  562. regex = QtCore.QRegExp("[0-9\/\*\+\-\%\.\s\,]*")
  563. validator = QtGui.QRegExpValidator(regex, self)
  564. self.setValidator(validator)
  565. class FCColorEntry(QtWidgets.QFrame):
  566. def __init__(self, **kwargs):
  567. super().__init__(**kwargs)
  568. self.entry = FCEntry()
  569. regex = QtCore.QRegExp("[#A-Fa-f0-9]*")
  570. validator = QtGui.QRegExpValidator(regex, self.entry)
  571. self.entry.setValidator(validator)
  572. self.button = QtWidgets.QPushButton()
  573. self.button.setFixedSize(15, 15)
  574. self.button.setStyleSheet("border-color: dimgray;")
  575. self.layout = QtWidgets.QHBoxLayout()
  576. self.layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  577. self.layout.setContentsMargins(0, 0, 0, 0)
  578. self.layout.addWidget(self.entry)
  579. self.layout.addWidget(self.button)
  580. self.setLayout(self.layout)
  581. self.entry.editingFinished.connect(self._sync_button_color)
  582. self.button.clicked.connect(self._on_button_clicked)
  583. self.editingFinished = self.entry.editingFinished
  584. def get_value(self) -> str:
  585. return self.entry.get_value()
  586. def set_value(self, value: str):
  587. self.entry.set_value(value)
  588. self._sync_button_color()
  589. def _sync_button_color(self):
  590. value = self.get_value()
  591. self.button.setStyleSheet("background-color:%s;" % self._extract_color(value))
  592. def _on_button_clicked(self):
  593. value = self.entry.get_value()
  594. current_color = QtGui.QColor(self._extract_color(value))
  595. color_dialog = QtWidgets.QColorDialog()
  596. selected_color = color_dialog.getColor(initial=current_color, options=QtWidgets.QColorDialog.ShowAlphaChannel)
  597. if selected_color.isValid() is False:
  598. return
  599. new_value = str(selected_color.name()) + self._extract_alpha(value)
  600. self.set_value(new_value)
  601. def _extract_color(self, value: str) -> str:
  602. return value[:7]
  603. def _extract_alpha(self, value: str) -> str:
  604. return value[7:9]
  605. class FCSliderWithSpinner(QtWidgets.QFrame):
  606. def __init__(self, min=0, max=100, step=1, **kwargs):
  607. super().__init__(**kwargs)
  608. self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
  609. self.slider.setMinimum(min)
  610. self.slider.setMaximum(max)
  611. self.slider.setSingleStep(step)
  612. self.spinner = FCSpinner()
  613. self.spinner.set_range(min, max)
  614. self.spinner.set_step(step)
  615. self.spinner.setMinimumWidth(70)
  616. sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
  617. self.spinner.setSizePolicy(sizePolicy)
  618. self.layout = QtWidgets.QHBoxLayout()
  619. self.layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  620. self.layout.setContentsMargins(0, 0, 0, 0)
  621. self.layout.addWidget(self.slider)
  622. self.layout.addWidget(self.spinner)
  623. self.setLayout(self.layout)
  624. self.slider.valueChanged.connect(self._on_slider)
  625. self.spinner.valueChanged.connect(self._on_spinner)
  626. self.valueChanged = self.spinner.valueChanged
  627. def get_value(self) -> int:
  628. return self.spinner.get_value()
  629. def set_value(self, value: int):
  630. self.spinner.set_value(value)
  631. def _on_spinner(self):
  632. spinner_value = self.spinner.value()
  633. self.slider.setValue(spinner_value)
  634. def _on_slider(self):
  635. slider_value = self.slider.value()
  636. self.spinner.set_value(slider_value)
  637. class FCSpinner(QtWidgets.QSpinBox):
  638. returnPressed = QtCore.pyqtSignal()
  639. confirmation_signal = QtCore.pyqtSignal(bool, float, float)
  640. def __init__(self, suffix=None, alignment=None, parent=None, callback=None):
  641. super(FCSpinner, self).__init__(parent)
  642. self.readyToEdit = True
  643. self.editingFinished.connect(self.on_edit_finished)
  644. if callback:
  645. self.confirmation_signal.connect(callback)
  646. self.lineEdit().installEventFilter(self)
  647. if suffix:
  648. self.setSuffix(' %s' % str(suffix))
  649. if alignment:
  650. if alignment == 'center':
  651. align_val = QtCore.Qt.AlignHCenter
  652. elif alignment == 'right':
  653. align_val = QtCore.Qt.AlignRight
  654. else:
  655. align_val = QtCore.Qt.AlignLeft
  656. self.setAlignment(align_val)
  657. self.prev_readyToEdit = True
  658. sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred)
  659. self.setSizePolicy(sizePolicy)
  660. def eventFilter(self, object, event):
  661. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  662. self.prev_readyToEdit = False
  663. if self.isEnabled():
  664. if self.readyToEdit:
  665. self.lineEdit().selectAll()
  666. self.readyToEdit = False
  667. else:
  668. self.lineEdit().deselect()
  669. return True
  670. return False
  671. def keyPressEvent(self, event):
  672. if event.key() == Qt.Key_Enter:
  673. self.returnPressed.emit()
  674. self.clearFocus()
  675. else:
  676. super().keyPressEvent(event)
  677. def wheelEvent(self, *args, **kwargs):
  678. # should work only there is a focus in the lineedit of the SpinBox
  679. if self.readyToEdit is False:
  680. super().wheelEvent(*args, **kwargs)
  681. def on_edit_finished(self):
  682. self.clearFocus()
  683. self.returnPressed.emit()
  684. # def mousePressEvent(self, e, parent=None):
  685. # super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  686. # if self.readyToEdit:
  687. # self.lineEdit().selectAll()
  688. # self.readyToEdit = False
  689. def focusOutEvent(self, e):
  690. # don't focus out if the user requests an popup menu
  691. if e.reason() != QtCore.Qt.PopupFocusReason:
  692. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  693. self.lineEdit().deselect()
  694. self.readyToEdit = True
  695. self.prev_readyToEdit = True
  696. def valueFromText(self, text):
  697. txt = text.strip('%%')
  698. try:
  699. ret_val = int(txt)
  700. except ValueError:
  701. ret_val = 0
  702. return ret_val
  703. def get_value(self):
  704. return int(self.value())
  705. def set_value(self, val):
  706. try:
  707. k = int(val)
  708. except Exception as e:
  709. log.debug(str(e))
  710. return
  711. self.setValue(k)
  712. def validate(self, p_str, p_int):
  713. text = p_str
  714. min_val = self.minimum()
  715. max_val = self.maximum()
  716. try:
  717. if int(text) < min_val or int(text) > max_val:
  718. self.confirmation_signal.emit(False, min_val, max_val)
  719. return QtGui.QValidator.Intermediate, text, p_int
  720. except ValueError:
  721. pass
  722. self.confirmation_signal.emit(True, min_val, max_val)
  723. return QtGui.QValidator.Acceptable, p_str, p_int
  724. def set_range(self, min_val, max_val):
  725. self.blockSignals(True)
  726. self.setRange(min_val, max_val)
  727. self.blockSignals(False)
  728. def set_step(self, p_int):
  729. self.blockSignals(True)
  730. self.setSingleStep(p_int)
  731. self.blockSignals(False)
  732. # def sizeHint(self):
  733. # default_hint_size = super(FCSpinner, self).sizeHint()
  734. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  735. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  736. returnPressed = QtCore.pyqtSignal()
  737. confirmation_signal = QtCore.pyqtSignal(bool, float, float)
  738. def __init__(self, suffix=None, alignment=None, parent=None, callback=None):
  739. """
  740. :param suffix: a char added to the end of the value in the LineEdit; like a '%' or '$' etc
  741. :param alignment: the value is aligned to left or right
  742. :param parent:
  743. :param callback: called when the entered value is outside limits; the min and max value will be passed to it
  744. """
  745. super(FCDoubleSpinner, self).__init__(parent)
  746. self.readyToEdit = True
  747. self.editingFinished.connect(self.on_edit_finished)
  748. if callback:
  749. self.confirmation_signal.connect(callback)
  750. self.lineEdit().installEventFilter(self)
  751. # by default don't allow the minus sign to be entered as the default for QDoubleSpinBox is the positive range
  752. # between 0.00 and 99.00 (2 decimals)
  753. self.lineEdit().setValidator(
  754. QtGui.QRegExpValidator(QtCore.QRegExp("\+?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  755. if suffix:
  756. self.setSuffix(' %s' % str(suffix))
  757. if alignment:
  758. if alignment == 'center':
  759. align_val = QtCore.Qt.AlignHCenter
  760. elif alignment == 'right':
  761. align_val = QtCore.Qt.AlignRight
  762. else:
  763. align_val = QtCore.Qt.AlignLeft
  764. self.setAlignment(align_val)
  765. self.prev_readyToEdit = True
  766. sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred)
  767. self.setSizePolicy(sizePolicy)
  768. def on_edit_finished(self):
  769. self.clearFocus()
  770. self.returnPressed.emit()
  771. def eventFilter(self, object, event):
  772. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  773. self.prev_readyToEdit = False
  774. if self.isEnabled():
  775. if self.readyToEdit:
  776. self.cursor_pos = self.lineEdit().cursorPosition()
  777. self.lineEdit().selectAll()
  778. self.readyToEdit = False
  779. else:
  780. self.lineEdit().deselect()
  781. return True
  782. return False
  783. def keyPressEvent(self, event):
  784. if event.key() == Qt.Key_Enter:
  785. self.returnPressed.emit()
  786. self.clearFocus()
  787. else:
  788. super().keyPressEvent(event)
  789. def wheelEvent(self, *args, **kwargs):
  790. # should work only there is a focus in the lineedit of the SpinBox
  791. if self.readyToEdit is False:
  792. super().wheelEvent(*args, **kwargs)
  793. def focusOutEvent(self, e):
  794. # don't focus out if the user requests an popup menu
  795. if e.reason() != QtCore.Qt.PopupFocusReason:
  796. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  797. self.lineEdit().deselect()
  798. self.readyToEdit = True
  799. self.prev_readyToEdit = True
  800. def valueFromText(self, p_str):
  801. text = p_str.replace(',', '.')
  802. text = text.strip('%%')
  803. try:
  804. ret_val = float(text)
  805. except ValueError:
  806. ret_val = 0.0
  807. return ret_val
  808. def validate(self, p_str, p_int):
  809. text = p_str.replace(',', '.')
  810. min_val = self.minimum()
  811. max_val = self.maximum()
  812. try:
  813. if float(text) < min_val or float(text) > max_val:
  814. self.confirmation_signal.emit(False, min_val, max_val)
  815. return QtGui.QValidator.Intermediate, text, p_int
  816. except ValueError:
  817. pass
  818. self.confirmation_signal.emit(True, min_val, max_val)
  819. return QtGui.QValidator.Acceptable, p_str, p_int
  820. def get_value(self):
  821. return float(self.value())
  822. def set_value(self, val):
  823. try:
  824. k = float(val)
  825. except Exception as e:
  826. log.debug(str(e))
  827. return
  828. self.setValue(k)
  829. def set_precision(self, val):
  830. self.setDecimals(val)
  831. # make sure that the user can't type more decimals than the set precision
  832. if self.minimum() < 0 or self.maximum() <= 0:
  833. self.lineEdit().setValidator(
  834. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  835. else:
  836. self.lineEdit().setValidator(
  837. QtGui.QRegExpValidator(QtCore.QRegExp("\+?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  838. def set_range(self, min_val, max_val):
  839. if min_val < 0 or max_val <= 0:
  840. self.lineEdit().setValidator(
  841. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  842. self.setRange(min_val, max_val)
  843. # def sizeHint(self):
  844. # default_hint_size = super(FCDoubleSpinner, self).sizeHint()
  845. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  846. class FCCheckBox(QtWidgets.QCheckBox):
  847. def __init__(self, label='', parent=None):
  848. super(FCCheckBox, self).__init__(str(label), parent)
  849. def get_value(self):
  850. return self.isChecked()
  851. def set_value(self, val):
  852. self.setChecked(val)
  853. def toggle(self):
  854. self.set_value(not self.get_value())
  855. class FCTextArea(QtWidgets.QPlainTextEdit):
  856. def __init__(self, parent=None):
  857. super(FCTextArea, self).__init__(parent)
  858. def set_value(self, val):
  859. self.setPlainText(val)
  860. def get_value(self):
  861. return str(self.toPlainText())
  862. def sizeHint(self, custom_sizehint=None):
  863. default_hint_size = super(FCTextArea, self).sizeHint()
  864. if custom_sizehint is None:
  865. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  866. else:
  867. return QtCore.QSize(custom_sizehint, default_hint_size.height())
  868. class FCTextAreaRich(QtWidgets.QTextEdit):
  869. def __init__(self, parent=None):
  870. super(FCTextAreaRich, self).__init__(parent)
  871. def set_value(self, val):
  872. self.setText(val)
  873. def get_value(self):
  874. return str(self.toPlainText())
  875. def sizeHint(self):
  876. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  877. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  878. class FCTextAreaExtended(QtWidgets.QTextEdit):
  879. def __init__(self, parent=None):
  880. super().__init__(parent)
  881. self.completer = MyCompleter()
  882. self.model = QtCore.QStringListModel()
  883. self.completer.setModel(self.model)
  884. self.set_model_data(keyword_list=[])
  885. self.completer.insertText.connect(self.insertCompletion)
  886. self.completer.popup().clicked.connect(self.insert_completion_click)
  887. self.completer_enable = False
  888. def set_model_data(self, keyword_list):
  889. self.model.setStringList(keyword_list)
  890. def insert_completion_click(self):
  891. self.completer.insertText.emit(self.completer.getSelected())
  892. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  893. def insertCompletion(self, completion):
  894. tc = self.textCursor()
  895. extra = (len(completion) - len(self.completer.completionPrefix()))
  896. # don't insert if the word is finished but add a space instead
  897. if extra == 0:
  898. tc.insertText(' ')
  899. self.completer.popup().hide()
  900. return
  901. tc.movePosition(QTextCursor.Left)
  902. tc.movePosition(QTextCursor.EndOfWord)
  903. tc.insertText(completion[-extra:])
  904. # add a space after inserting the word
  905. tc.insertText(' ')
  906. self.setTextCursor(tc)
  907. self.completer.popup().hide()
  908. def focusInEvent(self, event):
  909. if self.completer:
  910. self.completer.setWidget(self)
  911. QTextEdit.focusInEvent(self, event)
  912. def set_value(self, val):
  913. self.setText(val)
  914. def get_value(self):
  915. self.toPlainText()
  916. def insertFromMimeData(self, data):
  917. """
  918. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  919. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  920. :param data:
  921. :return:
  922. """
  923. modifier = QtWidgets.QApplication.keyboardModifiers()
  924. if modifier == Qt.ShiftModifier:
  925. text = data.text()
  926. text = text.replace('\\', '/')
  927. self.insertPlainText(text)
  928. else:
  929. self.insertPlainText(data.text())
  930. def keyPressEvent(self, event):
  931. """
  932. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  933. :param event:
  934. :return:
  935. """
  936. key = event.key()
  937. modifier = QtWidgets.QApplication.keyboardModifiers()
  938. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  939. if key == QtCore.Qt.Key_V:
  940. clipboard = QtWidgets.QApplication.clipboard()
  941. clip_text = clipboard.text()
  942. clip_text = clip_text.replace('\\', '/')
  943. self.insertPlainText(clip_text)
  944. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  945. self.comment()
  946. tc = self.textCursor()
  947. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  948. self.completer.insertText.emit(self.completer.getSelected())
  949. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  950. return
  951. elif key == Qt.Key_BraceLeft:
  952. tc.insertText('{}')
  953. self.moveCursor(QtGui.QTextCursor.Left)
  954. elif key == Qt.Key_BracketLeft:
  955. tc.insertText('[]')
  956. self.moveCursor(QtGui.QTextCursor.Left)
  957. elif key == Qt.Key_ParenLeft:
  958. tc.insertText('()')
  959. self.moveCursor(QtGui.QTextCursor.Left)
  960. elif key == Qt.Key_BraceRight:
  961. tc.select(QtGui.QTextCursor.WordUnderCursor)
  962. if tc.selectedText() == '}':
  963. tc.movePosition(QTextCursor.Right)
  964. self.setTextCursor(tc)
  965. else:
  966. tc.clearSelection()
  967. self.textCursor().insertText('}')
  968. elif key == Qt.Key_BracketRight:
  969. tc.select(QtGui.QTextCursor.WordUnderCursor)
  970. if tc.selectedText() == ']':
  971. tc.movePosition(QTextCursor.Right)
  972. self.setTextCursor(tc)
  973. else:
  974. tc.clearSelection()
  975. self.textCursor().insertText(']')
  976. elif key == Qt.Key_ParenRight:
  977. tc.select(QtGui.QTextCursor.WordUnderCursor)
  978. if tc.selectedText() == ')':
  979. tc.movePosition(QTextCursor.Right)
  980. self.setTextCursor(tc)
  981. else:
  982. tc.clearSelection()
  983. self.textCursor().insertText(')')
  984. else:
  985. super(FCTextAreaExtended, self).keyPressEvent(event)
  986. if self.completer_enable:
  987. tc.select(QTextCursor.WordUnderCursor)
  988. cr = self.cursorRect()
  989. if len(tc.selectedText()) > 0:
  990. self.completer.setCompletionPrefix(tc.selectedText())
  991. popup = self.completer.popup()
  992. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  993. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  994. + self.completer.popup().verticalScrollBar().sizeHint().width())
  995. self.completer.complete(cr)
  996. else:
  997. self.completer.popup().hide()
  998. def comment(self):
  999. """
  1000. Got it from here:
  1001. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  1002. :return:
  1003. """
  1004. pos = self.textCursor().position()
  1005. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  1006. line_text = self.textCursor().block().text()
  1007. if self.textCursor().block().text().startswith(" "):
  1008. # skip the white space
  1009. self.moveCursor(QtGui.QTextCursor.NextWord)
  1010. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  1011. character = self.textCursor().selectedText()
  1012. if character == "#":
  1013. # delete #
  1014. self.textCursor().deletePreviousChar()
  1015. # delete white space
  1016. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  1017. self.textCursor().removeSelectedText()
  1018. else:
  1019. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  1020. self.textCursor().insertText("# ")
  1021. cursor = QtGui.QTextCursor(self.textCursor())
  1022. cursor.setPosition(pos)
  1023. self.setTextCursor(cursor)
  1024. class FCPlainTextAreaExtended(QtWidgets.QPlainTextEdit):
  1025. def __init__(self, parent=None):
  1026. super().__init__(parent)
  1027. self.completer = MyCompleter()
  1028. self.model = QtCore.QStringListModel()
  1029. self.completer.setModel(self.model)
  1030. self.set_model_data(keyword_list=[])
  1031. self.completer.insertText.connect(self.insertCompletion)
  1032. self.completer.popup().clicked.connect(self.insert_completion_click)
  1033. self.completer_enable = False
  1034. def append(self, text):
  1035. """
  1036. Added this to make this subclass compatible with FCTextAreaExtended
  1037. :param text: string
  1038. :return:
  1039. """
  1040. self.appendPlainText(text)
  1041. def set_model_data(self, keyword_list):
  1042. self.model.setStringList(keyword_list)
  1043. def insert_completion_click(self):
  1044. self.completer.insertText.emit(self.completer.getSelected())
  1045. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1046. def insertCompletion(self, completion):
  1047. tc = self.textCursor()
  1048. extra = (len(completion) - len(self.completer.completionPrefix()))
  1049. # don't insert if the word is finished but add a space instead
  1050. if extra == 0:
  1051. tc.insertText(' ')
  1052. self.completer.popup().hide()
  1053. return
  1054. tc.movePosition(QTextCursor.Left)
  1055. tc.movePosition(QTextCursor.EndOfWord)
  1056. tc.insertText(completion[-extra:])
  1057. # add a space after inserting the word
  1058. tc.insertText(' ')
  1059. self.setTextCursor(tc)
  1060. self.completer.popup().hide()
  1061. def focusInEvent(self, event):
  1062. if self.completer:
  1063. self.completer.setWidget(self)
  1064. QtWidgets.QPlainTextEdit.focusInEvent(self, event)
  1065. def set_value(self, val):
  1066. self.setPlainText(val)
  1067. def get_value(self):
  1068. self.toPlainText()
  1069. def insertFromMimeData(self, data):
  1070. """
  1071. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  1072. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  1073. :param data:
  1074. :return:
  1075. """
  1076. modifier = QtWidgets.QApplication.keyboardModifiers()
  1077. if modifier == Qt.ShiftModifier:
  1078. text = data.text()
  1079. text = text.replace('\\', '/')
  1080. self.insertPlainText(text)
  1081. else:
  1082. self.insertPlainText(data.text())
  1083. def keyPressEvent(self, event):
  1084. """
  1085. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  1086. :param event:
  1087. :return:
  1088. """
  1089. key = event.key()
  1090. modifier = QtWidgets.QApplication.keyboardModifiers()
  1091. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  1092. if key == QtCore.Qt.Key_V:
  1093. clipboard = QtWidgets.QApplication.clipboard()
  1094. clip_text = clipboard.text()
  1095. clip_text = clip_text.replace('\\', '/')
  1096. self.insertPlainText(clip_text)
  1097. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  1098. self.comment()
  1099. tc = self.textCursor()
  1100. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  1101. self.completer.insertText.emit(self.completer.getSelected())
  1102. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1103. return
  1104. elif key == Qt.Key_BraceLeft:
  1105. tc.insertText('{}')
  1106. self.moveCursor(QtGui.QTextCursor.Left)
  1107. elif key == Qt.Key_BracketLeft:
  1108. tc.insertText('[]')
  1109. self.moveCursor(QtGui.QTextCursor.Left)
  1110. elif key == Qt.Key_ParenLeft:
  1111. tc.insertText('()')
  1112. self.moveCursor(QtGui.QTextCursor.Left)
  1113. elif key == Qt.Key_BraceRight:
  1114. tc.select(QtGui.QTextCursor.WordUnderCursor)
  1115. if tc.selectedText() == '}':
  1116. tc.movePosition(QTextCursor.Right)
  1117. self.setTextCursor(tc)
  1118. else:
  1119. tc.clearSelection()
  1120. self.textCursor().insertText('}')
  1121. elif key == Qt.Key_BracketRight:
  1122. tc.select(QtGui.QTextCursor.WordUnderCursor)
  1123. if tc.selectedText() == ']':
  1124. tc.movePosition(QTextCursor.Right)
  1125. self.setTextCursor(tc)
  1126. else:
  1127. tc.clearSelection()
  1128. self.textCursor().insertText(']')
  1129. elif key == Qt.Key_ParenRight:
  1130. tc.select(QtGui.QTextCursor.WordUnderCursor)
  1131. if tc.selectedText() == ')':
  1132. tc.movePosition(QTextCursor.Right)
  1133. self.setTextCursor(tc)
  1134. else:
  1135. tc.clearSelection()
  1136. self.textCursor().insertText(')')
  1137. else:
  1138. super(FCPlainTextAreaExtended, self).keyPressEvent(event)
  1139. if self.completer_enable:
  1140. tc.select(QTextCursor.WordUnderCursor)
  1141. cr = self.cursorRect()
  1142. if len(tc.selectedText()) > 0:
  1143. self.completer.setCompletionPrefix(tc.selectedText())
  1144. popup = self.completer.popup()
  1145. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1146. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1147. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1148. self.completer.complete(cr)
  1149. else:
  1150. self.completer.popup().hide()
  1151. def comment(self):
  1152. """
  1153. Got it from here:
  1154. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  1155. :return:
  1156. """
  1157. pos = self.textCursor().position()
  1158. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  1159. line_text = self.textCursor().block().text()
  1160. if self.textCursor().block().text().startswith(" "):
  1161. # skip the white space
  1162. self.moveCursor(QtGui.QTextCursor.NextWord)
  1163. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  1164. character = self.textCursor().selectedText()
  1165. if character == "#":
  1166. # delete #
  1167. self.textCursor().deletePreviousChar()
  1168. # delete white space
  1169. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  1170. self.textCursor().removeSelectedText()
  1171. else:
  1172. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  1173. self.textCursor().insertText("# ")
  1174. cursor = QtGui.QTextCursor(self.textCursor())
  1175. cursor.setPosition(pos)
  1176. self.setTextCursor(cursor)
  1177. class FCComboBox(QtWidgets.QComboBox):
  1178. def __init__(self, parent=None, callback=None):
  1179. super(FCComboBox, self).__init__(parent)
  1180. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  1181. self.view = self.view()
  1182. self.view.viewport().installEventFilter(self)
  1183. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  1184. self._set_last = False
  1185. self._obj_type = None
  1186. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  1187. # pos = mouse right click click position
  1188. # self = is the combobox object itself
  1189. if callback:
  1190. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  1191. def eventFilter(self, obj, event):
  1192. if event.type() == QtCore.QEvent.MouseButtonRelease:
  1193. if event.button() == Qt.RightButton:
  1194. return True
  1195. return False
  1196. def wheelEvent(self, *args, **kwargs):
  1197. pass
  1198. def get_value(self):
  1199. return str(self.currentText())
  1200. def set_value(self, val):
  1201. idx = self.findText(str(val))
  1202. self.setCurrentIndex(idx)
  1203. @property
  1204. def is_last(self):
  1205. return self._set_last
  1206. @is_last.setter
  1207. def is_last(self, val):
  1208. self._set_last = val
  1209. if self._set_last is True:
  1210. self.model().rowsInserted.connect(self.on_model_changed)
  1211. self.setCurrentIndex(1)
  1212. @property
  1213. def obj_type(self):
  1214. return self._obj_type
  1215. @obj_type.setter
  1216. def obj_type(self, val):
  1217. self._obj_type = val
  1218. def on_model_changed(self, parent, first, last):
  1219. if self.model().data(parent, QtCore.Qt.DisplayRole) == self.obj_type:
  1220. self.setCurrentIndex(first)
  1221. class FCInputDialog(QtWidgets.QInputDialog):
  1222. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  1223. init_val=None):
  1224. super(FCInputDialog, self).__init__(parent)
  1225. self.allow_empty = ok
  1226. self.empty_val = val
  1227. self.val = 0.0
  1228. self.ok = ''
  1229. self.init_value = init_val if init_val else 0.0
  1230. if title is None:
  1231. self.title = 'title'
  1232. else:
  1233. self.title = title
  1234. if text is None:
  1235. self.text = 'text'
  1236. else:
  1237. self.text = text
  1238. if min is None:
  1239. self.min = 0
  1240. else:
  1241. self.min = min
  1242. if max is None:
  1243. self.max = 0
  1244. else:
  1245. self.max = max
  1246. if decimals is None:
  1247. self.decimals = 6
  1248. else:
  1249. self.decimals = decimals
  1250. def get_value(self):
  1251. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  1252. max=self.max, decimals=self.decimals, value=self.init_value)
  1253. return [self.val, self.ok]
  1254. # "Transform", "Enter the Angle value:"
  1255. def set_value(self, val):
  1256. pass
  1257. class FCButton(QtWidgets.QPushButton):
  1258. def __init__(self, text=None, checkable=None, click_callback=None, parent=None):
  1259. super(FCButton, self).__init__(text, parent)
  1260. if not checkable is None:
  1261. self.setCheckable(checkable)
  1262. if not click_callback is None:
  1263. self.clicked.connect(click_callback)
  1264. def get_value(self):
  1265. return self.isChecked()
  1266. def set_value(self, val):
  1267. self.setText(str(val))
  1268. class FCLabel(QtWidgets.QLabel):
  1269. clicked = QtCore.pyqtSignal(bool)
  1270. right_clicked = QtCore.pyqtSignal(bool)
  1271. middle_clicked = QtCore.pyqtSignal(bool)
  1272. def __init__(self, parent=None):
  1273. super(FCLabel, self).__init__(parent)
  1274. # for the usage of this label as a clickable label, to know that current state
  1275. self.clicked_state = False
  1276. self.middle_clicked_state = False
  1277. self.right_clicked_state = False
  1278. def mousePressEvent(self, event):
  1279. if event.button() == Qt.LeftButton:
  1280. self.clicked_state = not self.clicked_state
  1281. self.clicked.emit(self.clicked_state)
  1282. elif event.button() == Qt.RightButton:
  1283. self.right_clicked_state = not self.right_clicked_state
  1284. self.right_clicked.emit(True)
  1285. elif event.button() == Qt.MiddleButton:
  1286. self.middle_clicked_state = not self.middle_clicked_state
  1287. self.middle_clicked.emit(True)
  1288. def get_value(self):
  1289. return self.text()
  1290. def set_value(self, val):
  1291. self.setText(str(val))
  1292. class FCMenu(QtWidgets.QMenu):
  1293. def __init__(self):
  1294. super().__init__()
  1295. self.mouse_is_panning = False
  1296. self.popup_active = False
  1297. def popup(self, pos, action=None):
  1298. super().popup(pos)
  1299. self.mouse_is_panning = False
  1300. self.popup_active = True
  1301. class FCTab(QtWidgets.QTabWidget):
  1302. def __init__(self, parent=None):
  1303. super(FCTab, self).__init__(parent)
  1304. self.setTabsClosable(True)
  1305. self.tabCloseRequested.connect(self.closeTab)
  1306. def deleteTab(self, currentIndex):
  1307. widget = self.widget(currentIndex)
  1308. if widget is not None:
  1309. widget.deleteLater()
  1310. self.removeTab(currentIndex)
  1311. def closeTab(self, currentIndex):
  1312. self.removeTab(currentIndex)
  1313. def protectTab(self, currentIndex):
  1314. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1315. # class FCTabBar(QtWidgets.QTabBar):
  1316. # def tabSizeHint(self, index):
  1317. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  1318. # w = int(self.width()/self.count())
  1319. # return QtCore.QSize(w, size.height())
  1320. class FCDetachableTab(QtWidgets.QTabWidget):
  1321. """
  1322. From here:
  1323. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  1324. """
  1325. tab_detached = QtCore.pyqtSignal(str)
  1326. tab_attached = QtCore.pyqtSignal(str)
  1327. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1328. super().__init__(parent=parent)
  1329. self.tabBar = self.FCTabBar(self)
  1330. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  1331. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  1332. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  1333. self.set_detachable(val=True)
  1334. self.setTabBar(self.tabBar)
  1335. # Used to keep a reference to detached tabs since their QMainWindow
  1336. # does not have a parent
  1337. self.detachedTabs = {}
  1338. # a way to make sure that tabs can't be closed after they attach to the parent tab
  1339. self.protect_tab = True if protect is not None and protect is True else False
  1340. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  1341. # Close all detached tabs if the application is closed explicitly
  1342. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  1343. # used by the property self.useOldIndex(param)
  1344. self.use_old_index = None
  1345. self.old_index = None
  1346. self.setTabsClosable(True)
  1347. self.tabCloseRequested.connect(self.closeTab)
  1348. def set_rmb_callback(self, callback):
  1349. """
  1350. :param callback: Function to call on right mouse click on tab
  1351. :type callback: func
  1352. :return: None
  1353. """
  1354. self.tabBar.right_click.connect(callback)
  1355. def set_detachable(self, val=True):
  1356. try:
  1357. self.tabBar.onDetachTabSignal.disconnect()
  1358. except TypeError:
  1359. pass
  1360. if val is True:
  1361. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  1362. # the tab can be moved around
  1363. self.tabBar.can_be_dragged = True
  1364. else:
  1365. # the detached tab can't be moved
  1366. self.tabBar.can_be_dragged = False
  1367. return val
  1368. def setupContextMenu(self):
  1369. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1370. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  1371. action_name = str(entry)
  1372. action = QtWidgets.QAction(self)
  1373. action.setCheckable(True)
  1374. action.setText(action_name)
  1375. if icon:
  1376. assert isinstance(icon, QtGui.QIcon), \
  1377. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1378. action.setIcon(icon)
  1379. action.setChecked(initial_checked)
  1380. self.addAction(action)
  1381. action.triggered.connect(call_function)
  1382. def useOldIndex(self, param):
  1383. if param:
  1384. self.use_old_index = True
  1385. else:
  1386. self.use_old_index = False
  1387. def deleteTab(self, currentIndex):
  1388. widget = self.widget(currentIndex)
  1389. if widget is not None:
  1390. widget.deleteLater()
  1391. self.removeTab(currentIndex)
  1392. def closeTab(self, currentIndex):
  1393. """
  1394. Slot connected to the tabCloseRequested signal
  1395. :param currentIndex:
  1396. :return:
  1397. """
  1398. self.removeTab(currentIndex)
  1399. def on_closetab_middle_button(self, current_index):
  1400. """
  1401. :param current_index:
  1402. :return:
  1403. """
  1404. # if tab is protected don't delete it
  1405. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  1406. self.removeTab(current_index)
  1407. def protectTab(self, currentIndex):
  1408. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1409. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1410. def setMovable(self, movable):
  1411. """
  1412. The default movable functionality of QTabWidget must remain disabled
  1413. so as not to conflict with the added features
  1414. :param movable:
  1415. :return:
  1416. """
  1417. pass
  1418. @pyqtSlot(int, int)
  1419. def moveTab(self, fromIndex, toIndex):
  1420. """
  1421. Move a tab from one position (index) to another
  1422. :param fromIndex: the original index location of the tab
  1423. :param toIndex: the new index location of the tab
  1424. :return:
  1425. """
  1426. widget = self.widget(fromIndex)
  1427. icon = self.tabIcon(fromIndex)
  1428. text = self.tabText(fromIndex)
  1429. self.removeTab(fromIndex)
  1430. self.insertTab(toIndex, widget, icon, text)
  1431. self.setCurrentIndex(toIndex)
  1432. # @pyqtSlot(int, QtCore.QPoint)
  1433. def detachTab(self, index, point):
  1434. """
  1435. Detach the tab by removing it's contents and placing them in
  1436. a DetachedTab window
  1437. :param index: the index location of the tab to be detached
  1438. :param point: the screen position for creating the new DetachedTab window
  1439. :return:
  1440. """
  1441. self.old_index = index
  1442. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  1443. name = "FlatCAM " + self.tabText(index)
  1444. icon = self.tabIcon(index)
  1445. if icon.isNull():
  1446. icon = self.window().windowIcon()
  1447. contentWidget = self.widget(index)
  1448. try:
  1449. contentWidgetRect = contentWidget.frameGeometry()
  1450. except AttributeError:
  1451. return
  1452. # Create a new detached tab window
  1453. detachedTab = self.FCDetachedTab(name, contentWidget)
  1454. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  1455. detachedTab.setWindowIcon(icon)
  1456. detachedTab.setGeometry(contentWidgetRect)
  1457. detachedTab.onCloseSignal.connect(self.attachTab)
  1458. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  1459. detachedTab.move(point)
  1460. detachedTab.show()
  1461. # Create a reference to maintain access to the detached tab
  1462. self.detachedTabs[name] = detachedTab
  1463. self.tab_detached.emit(name)
  1464. def attachTab(self, contentWidget, name, icon, insertAt=None):
  1465. """
  1466. Re-attach the tab by removing the content from the DetachedTab window,
  1467. closing it, and placing the content back into the DetachableTabWidget
  1468. :param contentWidget: the content widget from the DetachedTab window
  1469. :param name: the name of the detached tab
  1470. :param icon: the window icon for the detached tab
  1471. :param insertAt: insert the re-attached tab at the given index
  1472. :return:
  1473. """
  1474. old_name = name
  1475. # Make the content widget a child of this widget
  1476. contentWidget.setParent(self)
  1477. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  1478. name = name.partition(' ')[2]
  1479. # helps in restoring the tab to the same index that it was before was detached
  1480. insert_index = self.old_index if self.use_old_index is True else insertAt
  1481. # Create an image from the given icon (for comparison)
  1482. if not icon.isNull():
  1483. try:
  1484. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  1485. tabIconImage = tabIconPixmap.toImage()
  1486. except IndexError:
  1487. tabIconImage = None
  1488. else:
  1489. tabIconImage = None
  1490. # Create an image of the main window icon (for comparison)
  1491. if not icon.isNull():
  1492. try:
  1493. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  1494. windowIconImage = windowIconPixmap.toImage()
  1495. except IndexError:
  1496. windowIconImage = None
  1497. else:
  1498. windowIconImage = None
  1499. # Determine if the given image and the main window icon are the same.
  1500. # If they are, then do not add the icon to the tab
  1501. if tabIconImage == windowIconImage:
  1502. if insert_index is None:
  1503. index = self.addTab(contentWidget, name)
  1504. else:
  1505. index = self.insertTab(insert_index, contentWidget, name)
  1506. else:
  1507. if insert_index is None:
  1508. index = self.addTab(contentWidget, icon, name)
  1509. else:
  1510. index = self.insertTab(insert_index, contentWidget, icon, name)
  1511. obj_name = contentWidget.objectName()
  1512. self.tab_attached.emit(obj_name)
  1513. # on reattaching the tab if protect is true then the closure button is not added
  1514. if self.protect_tab is True:
  1515. self.protectTab(index)
  1516. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  1517. if self.protect_by_name is not None:
  1518. for tab_name in self.protect_by_name:
  1519. for index in range(self.count()):
  1520. if str(tab_name) == str(self.tabText(index)):
  1521. self.protectTab(index)
  1522. # Make this tab the current tab
  1523. if index > -1:
  1524. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  1525. # Remove the reference
  1526. # Unix-like OS's crash with segmentation fault after this. FOr whatever reason, they loose reference
  1527. if sys.platform == 'win32':
  1528. try:
  1529. del self.detachedTabs[old_name]
  1530. except KeyError:
  1531. pass
  1532. def removeTabByName(self, name):
  1533. """
  1534. Remove the tab with the given name, even if it is detached
  1535. :param name: the name of the tab to be removed
  1536. :return:
  1537. """
  1538. # Remove the tab if it is attached
  1539. attached = False
  1540. for index in range(self.count()):
  1541. if str(name) == str(self.tabText(index)):
  1542. self.removeTab(index)
  1543. attached = True
  1544. break
  1545. # If the tab is not attached, close it's window and
  1546. # remove the reference to it
  1547. if not attached:
  1548. for key in self.detachedTabs:
  1549. if str(name) == str(key):
  1550. self.detachedTabs[key].onCloseSignal.disconnect()
  1551. self.detachedTabs[key].close()
  1552. del self.detachedTabs[key]
  1553. break
  1554. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  1555. def detachedTabDrop(self, name, index, dropPos):
  1556. """
  1557. Handle dropping of a detached tab inside the DetachableTabWidget
  1558. :param name: the name of the detached tab
  1559. :param index: the index of an existing tab (if the tab bar
  1560. # determined that the drop occurred on an
  1561. # existing tab)
  1562. :param dropPos: the mouse cursor position when the drop occurred
  1563. :return:
  1564. """
  1565. # If the drop occurred on an existing tab, insert the detached
  1566. # tab at the existing tab's location
  1567. if index > -1:
  1568. # Create references to the detached tab's content and icon
  1569. contentWidget = self.detachedTabs[name].contentWidget
  1570. icon = self.detachedTabs[name].windowIcon()
  1571. # Disconnect the detached tab's onCloseSignal so that it
  1572. # does not try to re-attach automatically
  1573. self.detachedTabs[name].onCloseSignal.disconnect()
  1574. # Close the detached
  1575. self.detachedTabs[name].close()
  1576. # Re-attach the tab at the given index
  1577. self.attachTab(contentWidget, name, icon, index)
  1578. # If the drop did not occur on an existing tab, determine if the drop
  1579. # occurred in the tab bar area (the area to the side of the QTabBar)
  1580. else:
  1581. # Find the drop position relative to the DetachableTabWidget
  1582. tabDropPos = self.mapFromGlobal(dropPos)
  1583. # If the drop position is inside the DetachableTabWidget...
  1584. if self.rect().contains(tabDropPos):
  1585. # If the drop position is inside the tab bar area (the
  1586. # area to the side of the QTabBar) or there are not tabs
  1587. # currently attached...
  1588. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1589. # Close the detached tab and allow it to re-attach
  1590. # automatically
  1591. self.detachedTabs[name].close()
  1592. def closeDetachedTabs(self):
  1593. """
  1594. Close all tabs that are currently detached.
  1595. :return:
  1596. """
  1597. listOfDetachedTabs = []
  1598. for key in self.detachedTabs:
  1599. listOfDetachedTabs.append(self.detachedTabs[key])
  1600. for detachedTab in listOfDetachedTabs:
  1601. detachedTab.close()
  1602. class FCDetachedTab(QtWidgets.QMainWindow):
  1603. """
  1604. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1605. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1606. """
  1607. onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1608. onDropSignal = QtCore.pyqtSignal(str, QtCore.QPoint)
  1609. def __init__(self, name, contentWidget):
  1610. QtWidgets.QMainWindow.__init__(self, None)
  1611. self.setObjectName(name)
  1612. self.setWindowTitle(name)
  1613. self.contentWidget = contentWidget
  1614. self.setCentralWidget(self.contentWidget)
  1615. self.contentWidget.show()
  1616. self.windowDropFilter = self.WindowDropFilter()
  1617. self.installEventFilter(self.windowDropFilter)
  1618. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1619. @QtCore.pyqtSlot(QtCore.QPoint)
  1620. def windowDropSlot(self, dropPos):
  1621. """
  1622. Handle a window drop event
  1623. :param dropPos: the mouse cursor position of the drop
  1624. :return:
  1625. """
  1626. self.onDropSignal.emit(self.objectName(), dropPos)
  1627. def closeEvent(self, event):
  1628. """
  1629. If the window is closed, emit the onCloseSignal and give the
  1630. content widget back to the DetachableTabWidget
  1631. :param event: a close event
  1632. :return:
  1633. """
  1634. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1635. class WindowDropFilter(QtCore.QObject):
  1636. """
  1637. An event filter class to detect a QMainWindow drop event
  1638. """
  1639. onDropSignal = QtCore.pyqtSignal(QtCore.QPoint)
  1640. def __init__(self):
  1641. QtCore.QObject.__init__(self)
  1642. self.lastEvent = None
  1643. def eventFilter(self, obj, event):
  1644. """
  1645. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1646. event that immediately follows a Move event
  1647. :param obj: the object that generated the event
  1648. :param event: the current event
  1649. :return:
  1650. """
  1651. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1652. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1653. # Determine the position of the mouse cursor and emit it with the
  1654. # onDropSignal
  1655. mouseCursor = QtGui.QCursor()
  1656. dropPos = mouseCursor.pos()
  1657. self.onDropSignal.emit(dropPos)
  1658. self.lastEvent = event.type()
  1659. return True
  1660. else:
  1661. self.lastEvent = event.type()
  1662. return False
  1663. class FCTabBar(QtWidgets.QTabBar):
  1664. onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)
  1665. onMoveTabSignal = QtCore.pyqtSignal(int, int)
  1666. detachedTabDropSignal = QtCore.pyqtSignal(str, int, QtCore.QPoint)
  1667. onCloseTabSignal = QtCore.pyqtSignal(int)
  1668. right_click = QtCore.pyqtSignal(int)
  1669. def __init__(self, parent=None):
  1670. QtWidgets.QTabBar.__init__(self, parent)
  1671. self.setAcceptDrops(True)
  1672. self.setElideMode(QtCore.Qt.ElideRight)
  1673. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1674. self.prev_index = -1
  1675. self.dragStartPos = QtCore.QPoint()
  1676. self.dragDropedPos = QtCore.QPoint()
  1677. self.mouseCursor = QtGui.QCursor()
  1678. self.dragInitiated = False
  1679. # set this to False and the tab will no longer be displayed as detached
  1680. self.can_be_dragged = True
  1681. def mouseDoubleClickEvent(self, event):
  1682. """
  1683. Send the onDetachTabSignal when a tab is double clicked
  1684. :param event: a mouse double click event
  1685. :return:
  1686. """
  1687. event.accept()
  1688. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1689. def mousePressEvent(self, event):
  1690. """
  1691. Set the starting position for a drag event when the left mouse button is pressed.
  1692. Start detection of a right mouse click.
  1693. :param event: a mouse press event
  1694. :return:
  1695. """
  1696. if event.button() == QtCore.Qt.LeftButton:
  1697. self.dragStartPos = event.pos()
  1698. elif event.button() == QtCore.Qt.RightButton:
  1699. self.prev_index = self.tabAt(event.pos())
  1700. self.dragDropedPos.setX(0)
  1701. self.dragDropedPos.setY(0)
  1702. self.dragInitiated = False
  1703. QtWidgets.QTabBar.mousePressEvent(self, event)
  1704. def mouseReleaseEvent(self, event):
  1705. """
  1706. Finish the detection of the right mouse click on the tab
  1707. :param event: a mouse press event
  1708. :return:
  1709. """
  1710. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1711. self.right_click.emit(self.prev_index)
  1712. if event.button() == QtCore.Qt.MiddleButton:
  1713. self.onCloseTabSignal.emit(int(self.tabAt(event.pos())))
  1714. self.prev_index = -1
  1715. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1716. def mouseMoveEvent(self, event):
  1717. """
  1718. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1719. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1720. bar, emit an onDetachTabSignal.
  1721. :param event: a mouse move event
  1722. :return:
  1723. """
  1724. # Determine if the current movement is detected as a drag
  1725. if not self.dragStartPos.isNull() and \
  1726. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1727. self.dragInitiated = True
  1728. # If the current movement is a drag initiated by the left button
  1729. if (event.buttons() & QtCore.Qt.LeftButton) and self.dragInitiated and self.can_be_dragged:
  1730. # Stop the move event
  1731. finishMoveEvent = QtGui.QMouseEvent(
  1732. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1733. )
  1734. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1735. # Convert the move event into a drag
  1736. drag = QtGui.QDrag(self)
  1737. mimeData = QtCore.QMimeData()
  1738. # mimeData.setData('action', 'application/tab-detach')
  1739. drag.setMimeData(mimeData)
  1740. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1741. # Create the appearance of dragging the tab content
  1742. try:
  1743. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1744. except Exception as e:
  1745. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1746. return
  1747. targetPixmap = QtGui.QPixmap(pixmap.size())
  1748. targetPixmap.fill(QtCore.Qt.transparent)
  1749. painter = QtGui.QPainter(targetPixmap)
  1750. painter.setOpacity(0.85)
  1751. painter.drawPixmap(0, 0, pixmap)
  1752. painter.end()
  1753. drag.setPixmap(targetPixmap)
  1754. # Initiate the drag
  1755. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1756. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1757. # must be set manually
  1758. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1759. dropAction = QtCore.Qt.MoveAction
  1760. # If the drag completed outside of the tab bar, detach the tab and move
  1761. # the content to the current cursor position
  1762. if dropAction == QtCore.Qt.IgnoreAction:
  1763. event.accept()
  1764. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1765. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1766. elif dropAction == QtCore.Qt.MoveAction:
  1767. if not self.dragDropedPos.isNull():
  1768. event.accept()
  1769. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1770. else:
  1771. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1772. def dragEnterEvent(self, event):
  1773. """
  1774. Determine if the drag has entered a tab position from another tab position
  1775. :param event: a drag enter event
  1776. :return:
  1777. """
  1778. mimeData = event.mimeData()
  1779. # formats = mcd imeData.formats()
  1780. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1781. # event.acceptProposedAction()
  1782. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1783. def dropEvent(self, event):
  1784. """
  1785. Get the position of the end of the drag
  1786. :param event: a drop event
  1787. :return:
  1788. """
  1789. self.dragDropedPos = event.pos()
  1790. QtWidgets.QTabBar.dropEvent(self, event)
  1791. def detachedTabDrop(self, name, dropPos):
  1792. """
  1793. Determine if the detached tab drop event occurred on an existing tab,
  1794. then send the event to the DetachableTabWidget
  1795. :param name:
  1796. :param dropPos:
  1797. :return:
  1798. """
  1799. tabDropPos = self.mapFromGlobal(dropPos)
  1800. index = self.tabAt(tabDropPos)
  1801. self.detachedTabDropSignal.emit(name, index, dropPos)
  1802. class FCDetachableTab2(FCDetachableTab):
  1803. tab_closed_signal = QtCore.pyqtSignal(object, int)
  1804. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1805. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1806. try:
  1807. self.tabBar.onCloseTabSignal.disconnect()
  1808. except TypeError:
  1809. pass
  1810. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  1811. def on_closetab_middle_button(self, current_index):
  1812. """
  1813. :param current_index:
  1814. :return:
  1815. """
  1816. # if tab is protected don't delete it
  1817. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  1818. self.closeTab(current_index)
  1819. def closeTab(self, currentIndex):
  1820. """
  1821. Slot connected to the tabCloseRequested signal
  1822. :param currentIndex:
  1823. :return:
  1824. """
  1825. # idx = self.currentIndex()
  1826. tab_name = self.widget(currentIndex).objectName()
  1827. self.tab_closed_signal.emit(tab_name, currentIndex)
  1828. self.removeTab(currentIndex)
  1829. class VerticalScrollArea(QtWidgets.QScrollArea):
  1830. """
  1831. This widget extends QtGui.QScrollArea to make a vertical-only
  1832. scroll area that also expands horizontally to accommodate
  1833. its contents.
  1834. """
  1835. def __init__(self, parent=None):
  1836. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1837. self.setWidgetResizable(True)
  1838. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1839. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1840. def eventFilter(self, source, event):
  1841. """
  1842. The event filter gets automatically installed when setWidget()
  1843. is called.
  1844. :param source:
  1845. :param event:
  1846. :return:
  1847. """
  1848. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1849. # log.debug("VerticalScrollArea: Widget resized:")
  1850. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1851. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1852. self.setMinimumWidth(self.widget().sizeHint().width() +
  1853. self.verticalScrollBar().sizeHint().width())
  1854. # if self.verticalScrollBar().isVisible():
  1855. # log.debug(" Scroll bar visible")
  1856. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1857. # self.verticalScrollBar().width())
  1858. # else:
  1859. # log.debug(" Scroll bar hidden")
  1860. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1861. return QtWidgets.QWidget.eventFilter(self, source, event)
  1862. class OptionalInputSection:
  1863. def __init__(self, cb, optinputs, logic=True):
  1864. """
  1865. Associates the a checkbox with a set of inputs.
  1866. :param cb: Checkbox that enables the optional inputs.
  1867. :param optinputs: List of widgets that are optional.
  1868. :param logic: When True the logic is normal, when False the logic is in reverse
  1869. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1870. for logic=False, when the checkbox is checked the widgets are Disabled
  1871. :return:
  1872. """
  1873. assert isinstance(cb, FCCheckBox), \
  1874. "Expected an FCCheckBox, got %s" % type(cb)
  1875. self.cb = cb
  1876. self.optinputs = optinputs
  1877. self.logic = logic
  1878. self.on_cb_change()
  1879. self.cb.stateChanged.connect(self.on_cb_change)
  1880. def on_cb_change(self):
  1881. if self.cb.checkState():
  1882. for widget in self.optinputs:
  1883. if self.logic is True:
  1884. widget.setEnabled(True)
  1885. else:
  1886. widget.setEnabled(False)
  1887. else:
  1888. for widget in self.optinputs:
  1889. if self.logic is True:
  1890. widget.setEnabled(False)
  1891. else:
  1892. widget.setEnabled(True)
  1893. class OptionalHideInputSection:
  1894. def __init__(self, cb, optinputs, logic=True):
  1895. """
  1896. Associates the a checkbox with a set of inputs.
  1897. :param cb: Checkbox that enables the optional inputs.
  1898. :type cb: QtWidgets.QCheckBox
  1899. :param optinputs: List of widgets that are optional.
  1900. :type optinputs: list
  1901. :param logic: When True the logic is normal, when False the logic is in reverse
  1902. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1903. for logic=False, when the checkbox is checked the widgets are Disabled
  1904. :type logic: bool
  1905. :return:
  1906. """
  1907. assert isinstance(cb, FCCheckBox), \
  1908. "Expected an FCCheckBox, got %s" % type(cb)
  1909. self.cb = cb
  1910. self.optinputs = optinputs
  1911. self.logic = logic
  1912. self.on_cb_change()
  1913. self.cb.stateChanged.connect(self.on_cb_change)
  1914. def on_cb_change(self):
  1915. if self.cb.checkState():
  1916. for widget in self.optinputs:
  1917. if self.logic is True:
  1918. widget.show()
  1919. else:
  1920. widget.hide()
  1921. else:
  1922. for widget in self.optinputs:
  1923. if self.logic is True:
  1924. widget.hide()
  1925. else:
  1926. widget.show()
  1927. class FCTable(QtWidgets.QTableWidget):
  1928. drag_drop_sig = QtCore.pyqtSignal(object, int)
  1929. lost_focus = QtCore.pyqtSignal()
  1930. def __init__(self, drag_drop=False, protected_rows=None, parent=None):
  1931. super(FCTable, self).__init__(parent)
  1932. palette = QtGui.QPalette()
  1933. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight,
  1934. palette.color(QtGui.QPalette.Active, QtGui.QPalette.Highlight))
  1935. # make inactive rows text some color as active; may be useful in the future
  1936. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.HighlightedText,
  1937. palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
  1938. self.setPalette(palette)
  1939. if drag_drop:
  1940. self.setDragEnabled(True)
  1941. self.setAcceptDrops(True)
  1942. self.viewport().setAcceptDrops(True)
  1943. self.setDragDropOverwriteMode(False)
  1944. self.setDropIndicatorShown(True)
  1945. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1946. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1947. self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  1948. self.rows_not_for_drag_and_drop = []
  1949. if protected_rows:
  1950. try:
  1951. for r in protected_rows:
  1952. self.rows_not_for_drag_and_drop.append(r)
  1953. except TypeError:
  1954. self.rows_not_for_drag_and_drop = [protected_rows]
  1955. self.rows_to_move = []
  1956. self.rows_dragged = None
  1957. def sizeHint(self):
  1958. default_hint_size = super(FCTable, self).sizeHint()
  1959. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1960. def getHeight(self):
  1961. height = self.horizontalHeader().height()
  1962. for i in range(self.rowCount()):
  1963. height += self.rowHeight(i)
  1964. return height
  1965. def getWidth(self):
  1966. width = self.verticalHeader().width()
  1967. for i in range(self.columnCount()):
  1968. width += self.columnWidth(i)
  1969. return width
  1970. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpha
  1971. def setColortoRow(self, rowIndex, color):
  1972. for j in range(self.columnCount()):
  1973. self.item(rowIndex, j).setBackground(color)
  1974. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1975. def mousePressEvent(self, event):
  1976. clicked_item = self.itemAt(event.pos())
  1977. if not clicked_item:
  1978. self.clearSelection()
  1979. self.clearFocus()
  1980. else:
  1981. self.rows_dragged = [it.row() for it in self.selectedItems()]
  1982. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1983. def focusOutEvent(self, event):
  1984. self.lost_focus.emit()
  1985. super().focusOutEvent(event)
  1986. def setupContextMenu(self):
  1987. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1988. def addContextMenu(self, entry, call_function, icon=None):
  1989. action_name = str(entry)
  1990. action = QtWidgets.QAction(self)
  1991. action.setText(action_name)
  1992. if icon:
  1993. assert isinstance(icon, QtGui.QIcon), \
  1994. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1995. action.setIcon(icon)
  1996. self.addAction(action)
  1997. action.triggered.connect(call_function)
  1998. # def dropEvent(self, event: QtGui.QDropEvent):
  1999. # if not event.isAccepted() and event.source() == self:
  2000. # drop_row = self.drop_on(event)
  2001. #
  2002. # rows = sorted(set(item.row() for item in self.selectedItems()))
  2003. # # rows_to_move = [
  2004. # # [QtWidgets.QTableWidgetItem(self.item(row_index, column_index))
  2005. # # for column_index in range(self.columnCount())] for row_index in rows
  2006. # # ]
  2007. # self.rows_to_move[:] = []
  2008. # for row_index in rows:
  2009. # row_items = []
  2010. # for column_index in range(self.columnCount()):
  2011. # r_item = self.item(row_index, column_index)
  2012. # w_item = self.cellWidget(row_index, column_index)
  2013. #
  2014. # if r_item is not None:
  2015. # row_items.append(QtWidgets.QTableWidgetItem(r_item))
  2016. # elif w_item is not None:
  2017. # row_items.append(w_item)
  2018. #
  2019. # self.rows_to_move.append(row_items)
  2020. #
  2021. # for row_index in reversed(rows):
  2022. # self.removeRow(row_index)
  2023. # if row_index < drop_row:
  2024. # drop_row -= 1
  2025. #
  2026. # for row_index, data in enumerate(self.rows_to_move):
  2027. # row_index += drop_row
  2028. # self.insertRow(row_index)
  2029. #
  2030. # for column_index, column_data in enumerate(data):
  2031. # if isinstance(column_data, QtWidgets.QTableWidgetItem):
  2032. # self.setItem(row_index, column_index, column_data)
  2033. # else:
  2034. # self.setCellWidget(row_index, column_index, column_data)
  2035. #
  2036. # event.accept()
  2037. # for row_index in range(len(self.rows_to_move)):
  2038. # self.item(drop_row + row_index, 0).setSelected(True)
  2039. # self.item(drop_row + row_index, 1).setSelected(True)
  2040. #
  2041. # super().dropEvent(event)
  2042. #
  2043. # def drop_on(self, event):
  2044. # ret_val = False
  2045. # index = self.indexAt(event.pos())
  2046. # if not index.isValid():
  2047. # return self.rowCount()
  2048. #
  2049. # ret_val = index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  2050. #
  2051. # return ret_val
  2052. #
  2053. # def is_below(self, pos, index):
  2054. # rect = self.visualRect(index)
  2055. # margin = 2
  2056. # if pos.y() - rect.top() < margin:
  2057. # return False
  2058. # elif rect.bottom() - pos.y() < margin:
  2059. # return True
  2060. # # noinspection PyTypeChecker
  2061. # return rect.contains(pos, True) and not (
  2062. # int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
  2063. def dragEnterEvent(self, e: QtGui.QDragEnterEvent) -> None:
  2064. if e.source() == self:
  2065. self.blockSignals(True)
  2066. e.accept()
  2067. else:
  2068. e.ignore()
  2069. # def dropEvent(self, event):
  2070. # """
  2071. # From here: https://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
  2072. # :param event:
  2073. # :return:
  2074. # """
  2075. # if event.source() == self:
  2076. # event.acceptProposedAction()
  2077. #
  2078. # # create a set of the selected rows that are dragged to another position
  2079. # rows = set([mi.row() for mi in self.selectedIndexes()])
  2080. # # if one of the selected rows for drag and drop is within the protected list, return
  2081. # for r in rows:
  2082. # if r in self.rows_not_for_drag_and_drop:
  2083. # return
  2084. #
  2085. # drop_index = self.indexAt(event.pos())
  2086. # # row where we drop the selected rows
  2087. # targetRow = drop_index.row()
  2088. #
  2089. # # drop_indicator = self.dropIndicatorPosition()
  2090. # # if targetRow != -1:
  2091. # # if drop_indicator == QtWidgets.QAbstractItemView.AboveItem:
  2092. # # print("above")
  2093. # # elif drop_indicator == QtWidgets.QAbstractItemView.BelowItem:
  2094. # # print("below")
  2095. # # elif drop_indicator == QtWidgets.QAbstractItemView.OnItem:
  2096. # # print("on")
  2097. # # elif drop_indicator == QtWidgets.QAbstractItemView.OnViewport:
  2098. # # print("on viewport")
  2099. #
  2100. # # if we drop on one row from the already dragged rows
  2101. # rows.discard(targetRow)
  2102. # rows = sorted(rows)
  2103. # if not rows:
  2104. # return
  2105. # if targetRow == -1:
  2106. # targetRow = self.rowCount()
  2107. #
  2108. # # insert empty rows at the index of the targetRow
  2109. # for _ in range(len(rows)):
  2110. # self.insertRow(targetRow)
  2111. #
  2112. # rowMapping = {} # Src row to target row.
  2113. # for idx, row in enumerate(rows):
  2114. # if row < targetRow:
  2115. # rowMapping[row] = targetRow + idx
  2116. # else:
  2117. # rowMapping[row + len(rows)] = targetRow + idx
  2118. #
  2119. # colCount = self.columnCount()
  2120. # for srcRow, tgtRow in sorted(rowMapping.items()):
  2121. # for col in range(0, colCount):
  2122. # new_item = self.item(srcRow, col)
  2123. # if new_item is None:
  2124. # new_item = self.cellWidget(srcRow, col)
  2125. #
  2126. # if isinstance(new_item, QtWidgets.QTableWidgetItem):
  2127. # new_item = self.takeItem(srcRow, col)
  2128. # self.setItem(tgtRow, col, new_item)
  2129. # else:
  2130. # self.setCellWidget(tgtRow, col, new_item)
  2131. #
  2132. # for row in reversed(sorted(rowMapping.keys())):
  2133. # self.removeRow(row)
  2134. #
  2135. # self.blockSignals(False)
  2136. # self.drag_drop_sig.emit(int(self.row_dragged), int(targetRow))
  2137. # else:
  2138. # event.ignore()
  2139. def dropEvent(self, event: QtGui.QDropEvent):
  2140. if not event.isAccepted() and event.source() == self:
  2141. drop_row = self.drop_on(event)
  2142. rows = sorted(set(item.row() for item in self.selectedItems()))
  2143. rows_to_move = []
  2144. for row_index in rows:
  2145. temp_lst = []
  2146. for column_index in range(self.columnCount()):
  2147. col_data = self.item(row_index, column_index)
  2148. if isinstance(col_data, QtWidgets.QTableWidgetItem):
  2149. table_item = QtWidgets.QTableWidgetItem(col_data)
  2150. else:
  2151. old_item = self.cellWidget(row_index, column_index)
  2152. if isinstance(old_item, QtWidgets.QComboBox):
  2153. table_item = FCComboBox()
  2154. items = [old_item.itemText(i) for i in range(old_item.count())]
  2155. table_item.addItems(items)
  2156. table_item.setCurrentIndex(old_item.currentIndex())
  2157. elif isinstance(old_item, QtWidgets.QCheckBox):
  2158. table_item = FCCheckBox()
  2159. table_item.setChecked(old_item.isChecked())
  2160. table_item.setText(old_item.text())
  2161. else:
  2162. table_item = None
  2163. temp_lst.append(table_item)
  2164. rows_to_move.append(temp_lst)
  2165. for row_index in reversed(rows):
  2166. self.removeRow(row_index)
  2167. if row_index < drop_row:
  2168. drop_row -= 1
  2169. for row_index, data in enumerate(rows_to_move):
  2170. row_index += drop_row
  2171. self.insertRow(row_index)
  2172. for column_index, column_data in enumerate(data):
  2173. if column_data is None:
  2174. continue
  2175. if isinstance(column_data, QtWidgets.QTableWidgetItem):
  2176. self.setItem(row_index, column_index, column_data)
  2177. else:
  2178. self.setCellWidget(row_index, column_index, column_data)
  2179. event.accept()
  2180. for row_index in range(len(rows_to_move)):
  2181. self.item(drop_row + row_index, 0).setSelected(True)
  2182. self.item(drop_row + row_index, 1).setSelected(True)
  2183. self.blockSignals(False)
  2184. self.drag_drop_sig.emit(self.rows_dragged, int(drop_row))
  2185. self.blockSignals(False)
  2186. self.resizeRowsToContents()
  2187. super().dropEvent(event)
  2188. def drop_on(self, event):
  2189. index = self.indexAt(event.pos())
  2190. if not index.isValid():
  2191. return self.rowCount()
  2192. return index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  2193. def is_below(self, pos, index):
  2194. rect = self.visualRect(index)
  2195. margin = 2
  2196. if pos.y() - rect.top() < margin:
  2197. return False
  2198. elif rect.bottom() - pos.y() < margin:
  2199. return True
  2200. # noinspection PyTypeChecker
  2201. return rect.contains(pos, True) and not (int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and \
  2202. pos.y() >= rect.center().y()
  2203. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  2204. def __init__(self, units):
  2205. super(SpinBoxDelegate, self).__init__()
  2206. self.units = units
  2207. self.current_value = None
  2208. def createEditor(self, parent, option, index):
  2209. editor = QtWidgets.QDoubleSpinBox(parent)
  2210. editor.setMinimum(-999.9999)
  2211. editor.setMaximum(999.9999)
  2212. if self.units == 'MM':
  2213. editor.setDecimals(2)
  2214. else:
  2215. editor.setDecimals(3)
  2216. return editor
  2217. def setEditorData(self, spinBox, index):
  2218. try:
  2219. value = float(index.model().data(index, Qt.EditRole))
  2220. except ValueError:
  2221. value = self.current_value
  2222. # return
  2223. spinBox.setValue(value)
  2224. def setModelData(self, spinBox, model, index):
  2225. spinBox.interpretText()
  2226. value = spinBox.value()
  2227. self.current_value = value
  2228. model.setData(index, value, Qt.EditRole)
  2229. def updateEditorGeometry(self, editor, option, index):
  2230. editor.setGeometry(option.rect)
  2231. @staticmethod
  2232. def setDecimals(spinbox, digits):
  2233. spinbox.setDecimals(digits)
  2234. class Dialog_box(QtWidgets.QWidget):
  2235. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  2236. """
  2237. :param title: string with the window title
  2238. :param label: string with the message inside the dialog box
  2239. """
  2240. super(Dialog_box, self).__init__()
  2241. if initial_text is None:
  2242. self.location = str((0, 0))
  2243. else:
  2244. self.location = initial_text
  2245. self.ok = False
  2246. self.dialog_box = QtWidgets.QInputDialog()
  2247. self.dialog_box.setMinimumWidth(290)
  2248. self.setWindowIcon(icon)
  2249. self.location, self.ok = self.dialog_box.getText(self, title, label,
  2250. text=str(self.location).replace('(', '').replace(')', ''))
  2251. self.readyToEdit = True
  2252. def mousePressEvent(self, e, parent=None):
  2253. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  2254. if self.readyToEdit:
  2255. self.lineEdit().selectAll()
  2256. self.readyToEdit = False
  2257. def focusOutEvent(self, e):
  2258. # don't focus out if the user requests an popup menu
  2259. if e.reason() != QtCore.Qt.PopupFocusReason:
  2260. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  2261. self.lineEdit().deselect()
  2262. self.readyToEdit = True
  2263. class DialogBoxRadio(QtWidgets.QDialog):
  2264. def __init__(self, title=None, label=None, icon=None, initial_text=None, reference='abs', parent=None):
  2265. """
  2266. :param title: string with the window title
  2267. :param label: string with the message inside the dialog box
  2268. """
  2269. super(DialogBoxRadio, self).__init__(parent=parent)
  2270. if initial_text is None:
  2271. self.location = str((0, 0))
  2272. else:
  2273. self.location = initial_text
  2274. self.ok = False
  2275. self.setWindowIcon(icon)
  2276. self.setWindowTitle(str(title))
  2277. self.form = QtWidgets.QFormLayout(self)
  2278. self.ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  2279. self.ref_label.setToolTip(
  2280. _("The reference can be:\n"
  2281. "- Absolute -> the reference point is point (0,0)\n"
  2282. "- Relative -> the reference point is the mouse position before Jump")
  2283. )
  2284. self.ref_radio = RadioSet([
  2285. {"label": _("Abs"), "value": "abs"},
  2286. {"label": _("Relative"), "value": "rel"}
  2287. ], orientation='horizontal', stretch=False)
  2288. self.ref_radio.set_value(reference)
  2289. self.form.addRow(self.ref_label, self.ref_radio)
  2290. self.form.addRow(QtWidgets.QLabel(''))
  2291. self.wdg_label = QtWidgets.QLabel('<b>%s</b>' % str(label))
  2292. self.form.addRow(self.wdg_label)
  2293. self.loc_label = QtWidgets.QLabel('%s:' % _("Location"))
  2294. self.loc_label.setToolTip(
  2295. _("The Location value is a tuple (x,y).\n"
  2296. "If the reference is Absolute then the Jump will be at the position (x,y).\n"
  2297. "If the reference is Relative then the Jump will be at the (x,y) distance\n"
  2298. "from the current mouse location point.")
  2299. )
  2300. self.lineEdit = EvalEntry(parent=self)
  2301. self.lineEdit.setText(str(self.location).replace('(', '').replace(')', ''))
  2302. self.lineEdit.selectAll()
  2303. self.lineEdit.setFocus()
  2304. self.form.addRow(self.loc_label, self.lineEdit)
  2305. self.button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  2306. orientation=Qt.Horizontal, parent=self)
  2307. self.form.addRow(self.button_box)
  2308. self.button_box.accepted.connect(self.accept)
  2309. self.button_box.rejected.connect(self.reject)
  2310. self.readyToEdit = True
  2311. if self.exec_() == QtWidgets.QDialog.Accepted:
  2312. self.ok = True
  2313. self.location = self.lineEdit.text()
  2314. self.reference = self.ref_radio.get_value()
  2315. else:
  2316. self.ok = False
  2317. class _BrowserTextEdit(QTextEdit):
  2318. def __init__(self, version, app=None):
  2319. QTextEdit.__init__(self)
  2320. self.menu = None
  2321. self.version = version
  2322. self.app = app
  2323. def contextMenuEvent(self, event):
  2324. self.menu = self.createStandardContextMenu(event.pos())
  2325. if self.app:
  2326. save_action = QAction(_("Save Log"), self)
  2327. self.menu.addAction(save_action)
  2328. save_action.triggered.connect(lambda: self.save_log(app=self.app))
  2329. clear_action = QAction(_("Clear"), self)
  2330. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  2331. self.menu.addAction(clear_action)
  2332. clear_action.triggered.connect(self.clear)
  2333. if self.app:
  2334. close_action = QAction(_("Close"), self)
  2335. self.menu.addAction(close_action)
  2336. close_action.triggered.connect(lambda: self.app.ui.shell_dock.hide())
  2337. self.menu.exec_(event.globalPos())
  2338. def clear(self):
  2339. QTextEdit.clear(self)
  2340. text = "!FlatCAM %s? - %s" % (self.version, _("Type >help< to get started"))
  2341. text = html.escape(text)
  2342. # hack so I can make text bold because the escape method will replace the '<' and '>' signs with html code
  2343. text = text.replace('!', '<b>')
  2344. text = text.replace('?', '</b>')
  2345. text += '<br><br>'
  2346. self.moveCursor(QTextCursor.End)
  2347. self.insertHtml(text)
  2348. def save_log(self, app):
  2349. html_content = self.toHtml()
  2350. txt_content = self.toPlainText()
  2351. app.save_to_file(content_to_save=html_content, txt_content=txt_content)
  2352. class _ExpandableTextEdit(QTextEdit):
  2353. """
  2354. Class implements edit line, which expands themselves automatically
  2355. """
  2356. historyNext = QtCore.pyqtSignal()
  2357. historyPrev = QtCore.pyqtSignal()
  2358. def __init__(self, termwidget, *args):
  2359. QTextEdit.__init__(self, *args)
  2360. self.setStyleSheet("font: 9pt \"Courier\";")
  2361. self._fittedHeight = 1
  2362. self.textChanged.connect(self._fit_to_document)
  2363. self._fit_to_document()
  2364. self._termWidget = termwidget
  2365. self.completer = MyCompleter()
  2366. self.model = QtCore.QStringListModel()
  2367. self.completer.setModel(self.model)
  2368. self.set_model_data(keyword_list=[])
  2369. self.completer.insertText.connect(self.insertCompletion)
  2370. self.completer.popup().clicked.connect(self.insert_completion_click)
  2371. def set_model_data(self, keyword_list):
  2372. self.model.setStringList(keyword_list)
  2373. def insert_completion_click(self):
  2374. self.completer.insertText.emit(self.completer.getSelected())
  2375. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  2376. def insertCompletion(self, completion):
  2377. tc = self.textCursor()
  2378. extra = (len(completion) - len(self.completer.completionPrefix()))
  2379. # don't insert if the word is finished but add a space instead
  2380. if extra == 0:
  2381. tc.insertText(' ')
  2382. self.completer.popup().hide()
  2383. return
  2384. tc.movePosition(QTextCursor.Left)
  2385. tc.movePosition(QTextCursor.EndOfWord)
  2386. tc.insertText(completion[-extra:])
  2387. # add a space after inserting the word
  2388. tc.insertText(' ')
  2389. self.setTextCursor(tc)
  2390. self.completer.popup().hide()
  2391. def focusInEvent(self, event):
  2392. if self.completer:
  2393. self.completer.setWidget(self)
  2394. QTextEdit.focusInEvent(self, event)
  2395. def keyPressEvent(self, event):
  2396. """
  2397. Catch keyboard events. Process Enter, Up, Down
  2398. """
  2399. key = event.key()
  2400. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  2401. self.completer.insertText.emit(self.completer.getSelected())
  2402. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  2403. return
  2404. if event.matches(QKeySequence.InsertParagraphSeparator):
  2405. text = self.toPlainText()
  2406. if self._termWidget.is_command_complete(text):
  2407. self._termWidget.exec_current_command()
  2408. return
  2409. elif event.matches(QKeySequence.MoveToNextLine):
  2410. text = self.toPlainText()
  2411. cursor_pos = self.textCursor().position()
  2412. textBeforeEnd = text[cursor_pos:]
  2413. if len(textBeforeEnd.split('\n')) <= 1:
  2414. self.historyNext.emit()
  2415. return
  2416. elif event.matches(QKeySequence.MoveToPreviousLine):
  2417. text = self.toPlainText()
  2418. cursor_pos = self.textCursor().position()
  2419. text_before_start = text[:cursor_pos]
  2420. # lineCount = len(textBeforeStart.splitlines())
  2421. line_count = len(text_before_start.split('\n'))
  2422. if len(text_before_start) > 0 and \
  2423. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  2424. line_count += 1
  2425. if line_count <= 1:
  2426. self.historyPrev.emit()
  2427. return
  2428. elif event.matches(QKeySequence.MoveToNextPage) or event.matches(QKeySequence.MoveToPreviousPage):
  2429. return self._termWidget.browser().keyPressEvent(event)
  2430. tc = self.textCursor()
  2431. QTextEdit.keyPressEvent(self, event)
  2432. tc.select(QTextCursor.WordUnderCursor)
  2433. cr = self.cursorRect()
  2434. if len(tc.selectedText()) > 0:
  2435. self.completer.setCompletionPrefix(tc.selectedText())
  2436. popup = self.completer.popup()
  2437. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  2438. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  2439. + self.completer.popup().verticalScrollBar().sizeHint().width())
  2440. self.completer.complete(cr)
  2441. else:
  2442. self.completer.popup().hide()
  2443. def sizeHint(self):
  2444. """
  2445. QWidget sizeHint impelemtation
  2446. """
  2447. hint = QTextEdit.sizeHint(self)
  2448. hint.setHeight(self._fittedHeight)
  2449. return hint
  2450. def _fit_to_document(self):
  2451. """
  2452. Update widget height to fit all text
  2453. """
  2454. documentsize = self.document().size().toSize()
  2455. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  2456. self.setMaximumHeight(self._fittedHeight)
  2457. self.updateGeometry()
  2458. def insertFromMimeData(self, mime_data):
  2459. # Paste only plain text.
  2460. self.insertPlainText(mime_data.text())
  2461. class MyCompleter(QCompleter):
  2462. insertText = QtCore.pyqtSignal(str)
  2463. def __init__(self, parent=None):
  2464. QCompleter.__init__(self, parent=parent)
  2465. self.setCompletionMode(QCompleter.PopupCompletion)
  2466. self.highlighted.connect(self.setHighlighted)
  2467. self.lastSelected = ''
  2468. # self.popup().installEventFilter(self)
  2469. # def eventFilter(self, obj, event):
  2470. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  2471. # pass
  2472. # return False
  2473. def setHighlighted(self, text):
  2474. self.lastSelected = text
  2475. def getSelected(self):
  2476. return self.lastSelected
  2477. class FCTextAreaLineNumber(QtWidgets.QFrame):
  2478. textChanged = QtCore.pyqtSignal()
  2479. class NumberBar(QtWidgets.QWidget):
  2480. def __init__(self, edit):
  2481. QtWidgets.QWidget.__init__(self, edit)
  2482. self.edit = edit
  2483. self.adjustWidth(1)
  2484. def paintEvent(self, event):
  2485. self.edit.numberbarPaint(self, event)
  2486. QtWidgets.QWidget.paintEvent(self, event)
  2487. def adjustWidth(self, count):
  2488. # three spaces added to the width to make up for the space added in the line number
  2489. width = self.fontMetrics().width(str(count) + ' ')
  2490. if self.width() != width:
  2491. self.setFixedWidth(width)
  2492. def updateContents(self, rect, scroll):
  2493. if scroll:
  2494. self.scroll(0, scroll)
  2495. else:
  2496. # It would be nice to do
  2497. # self.update(0, rect.y(), self.width(), rect.height())
  2498. # But we can't because it will not remove the bold on the
  2499. # current line if word wrap is enabled and a new block is
  2500. # selected.
  2501. self.update()
  2502. class PlainTextEdit(FCPlainTextAreaExtended):
  2503. """
  2504. TextEdit with line numbers and highlight
  2505. From here: https://nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/
  2506. and from here: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
  2507. """
  2508. def __init__(self, *args):
  2509. FCPlainTextAreaExtended.__init__(self, *args)
  2510. # self.setFrameStyle(QFrame.NoFrame)
  2511. self.setFrameStyle(QtWidgets.QFrame.NoFrame)
  2512. self.highlight()
  2513. # self.setLineWrapMode(QPlainTextEdit.NoWrap)
  2514. self.cursorPositionChanged.connect(self.highlight)
  2515. def highlight(self):
  2516. hi_selection = QTextEdit.ExtraSelection()
  2517. hi_selection.format.setBackground(self.palette().alternateBase())
  2518. hi_selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
  2519. hi_selection.cursor = self.textCursor()
  2520. hi_selection.cursor.clearSelection()
  2521. self.setExtraSelections([hi_selection])
  2522. def numberbarPaint(self, number_bar, event):
  2523. font_metrics = self.fontMetrics()
  2524. current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
  2525. painter = QtGui.QPainter(number_bar)
  2526. painter.fillRect(event.rect(), QtCore.Qt.lightGray)
  2527. block = self.firstVisibleBlock()
  2528. line_count = int(block.blockNumber())
  2529. block_top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
  2530. block_bottom = block_top + int(self.blockBoundingRect(block).height())
  2531. # Iterate over all visible text blocks in the document.
  2532. while block.isValid() and block_top <= event.rect().bottom():
  2533. line_count += 1
  2534. # Check if the position of the block is out side of the visible
  2535. # area.
  2536. if block.isVisible() and block_bottom >= event.rect().top():
  2537. # We want the line number for the selected line to be bold.
  2538. if line_count == current_line:
  2539. font = painter.font()
  2540. font.setBold(True)
  2541. painter.setPen(QtCore.Qt.blue)
  2542. painter.setFont(font)
  2543. else:
  2544. font = painter.font()
  2545. font.setBold(False)
  2546. painter.setPen(self.palette().base().color())
  2547. painter.setFont(font)
  2548. # Draw the line number right justified at the position of the line.
  2549. paint_rect = QtCore.QRect(0, block_top, number_bar.width(), font_metrics.height())
  2550. # I add some spaces to the line_count to prettify; make sure to remember adjust the width in the
  2551. # NumberBar() class above
  2552. painter.drawText(paint_rect, Qt.AlignRight, ' ' + str(line_count) + ' ')
  2553. block = block.next()
  2554. block_top = block_bottom
  2555. block_bottom = block_top + self.blockBoundingRect(block).height()
  2556. painter.end()
  2557. def __init__(self, *args):
  2558. QtWidgets.QFrame.__init__(self, *args)
  2559. self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Sunken)
  2560. self.edit = self.PlainTextEdit()
  2561. self.number_bar = self.NumberBar(self.edit)
  2562. hbox = QtWidgets.QHBoxLayout(self)
  2563. hbox.setSpacing(0)
  2564. hbox.setContentsMargins(0, 0, 0, 0)
  2565. hbox.addWidget(self.number_bar)
  2566. hbox.addWidget(self.edit)
  2567. self.edit.blockCountChanged.connect(self.number_bar.adjustWidth)
  2568. self.edit.updateRequest.connect(self.number_bar.updateContents)
  2569. def getText(self):
  2570. return str(self.edit.toPlainText())
  2571. def setText(self, text):
  2572. self.edit.setPlainText(text)
  2573. def isModified(self):
  2574. return self.edit.document().isModified()
  2575. def setModified(self, modified):
  2576. self.edit.document().setModified(modified)
  2577. def setLineWrapMode(self, mode):
  2578. self.edit.setLineWrapMode(mode)
  2579. class FCFileSaveDialog(QtWidgets.QFileDialog):
  2580. def __init__(self, *args):
  2581. super(FCFileSaveDialog, self).__init__(*args)
  2582. @staticmethod
  2583. def get_saved_filename(parent=None, caption='', directory='', ext_filter='', initialFilter=''):
  2584. filename, _filter = QtWidgets.QFileDialog.getSaveFileName(parent=parent, caption=caption,
  2585. directory=directory, filter=ext_filter,
  2586. initialFilter=initialFilter)
  2587. filename = str(filename)
  2588. if filename == '':
  2589. return filename, _filter
  2590. extension = '.' + _filter.strip(')').rpartition('.')[2]
  2591. if filename.endswith(extension) or extension == '.*':
  2592. return filename, _filter
  2593. else:
  2594. filename += extension
  2595. return filename, _filter
  2596. class FCDock(QtWidgets.QDockWidget):
  2597. def __init__(self, *args, **kwargs):
  2598. super(FCDock, self).__init__(*args)
  2599. self.close_callback = kwargs["close_callback"] if "close_callback" in kwargs else None
  2600. def closeEvent(self, event: QtGui.QCloseEvent) -> None:
  2601. self.close_callback()
  2602. super().closeEvent(event)
  2603. def show(self) -> None:
  2604. if self.isFloating():
  2605. self.setFloating(False)
  2606. super().show()
  2607. class FCJog(QtWidgets.QFrame):
  2608. def __init__(self, title, app, *args, **kwargs):
  2609. super(FCJog, self).__init__(*args, **kwargs)
  2610. self.app = app
  2611. self.setFrameShape(QtWidgets.QFrame.Box)
  2612. self.setLineWidth(1)
  2613. # JOG axes
  2614. grbl_jog_grid = QtWidgets.QGridLayout()
  2615. grbl_jog_grid.setAlignment(QtCore.Qt.AlignCenter)
  2616. grbl_jog_grid.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
  2617. self.setLayout(grbl_jog_grid)
  2618. jog_title_label = FCLabel(title)
  2619. jog_title_label.setStyleSheet("""
  2620. FCLabel
  2621. {
  2622. font-weight: bold;
  2623. }
  2624. """)
  2625. grbl_jog_grid.addWidget(jog_title_label, 0, 0, 1, 4)
  2626. # JOG Y Up
  2627. self.jog_up_button = QtWidgets.QToolButton()
  2628. self.jog_up_button.setIcon(QtGui.QIcon(self.app.resource_location + '/up-arrow32.png'))
  2629. self.jog_up_button.setToolTip(
  2630. _("Jog the Y axis.")
  2631. )
  2632. grbl_jog_grid.addWidget(self.jog_up_button, 2, 1)
  2633. # Origin
  2634. self.jog_origin_button = QtWidgets.QToolButton()
  2635. self.jog_origin_button.setIcon(QtGui.QIcon(self.app.resource_location + '/origin2_32.png'))
  2636. self.jog_origin_button.setToolTip(
  2637. _("Move to Origin.")
  2638. )
  2639. grbl_jog_grid.addWidget(self.jog_origin_button, 3, 1)
  2640. # JOG Y Down
  2641. self.jog_down_button = QtWidgets.QToolButton()
  2642. self.jog_down_button.setIcon(QtGui.QIcon(self.app.resource_location + '/down-arrow32.png'))
  2643. self.jog_down_button.setToolTip(
  2644. _("Jog the Y axis.")
  2645. )
  2646. grbl_jog_grid.addWidget(self.jog_down_button, 4, 1)
  2647. # JOG X Left
  2648. self.jog_left_button = QtWidgets.QToolButton()
  2649. self.jog_left_button.setIcon(QtGui.QIcon(self.app.resource_location + '/left_arrow32.png'))
  2650. self.jog_left_button.setToolTip(
  2651. _("Jog the X axis.")
  2652. )
  2653. grbl_jog_grid.addWidget(self.jog_left_button, 3, 0)
  2654. # JOG X Right
  2655. self.jog_right_button = QtWidgets.QToolButton()
  2656. self.jog_right_button.setIcon(QtGui.QIcon(self.app.resource_location + '/right_arrow32.png'))
  2657. self.jog_right_button.setToolTip(
  2658. _("Jog the X axis.")
  2659. )
  2660. grbl_jog_grid.addWidget(self.jog_right_button, 3, 2)
  2661. # JOG Z Up
  2662. self.jog_z_up_button = QtWidgets.QToolButton()
  2663. self.jog_z_up_button.setIcon(QtGui.QIcon(self.app.resource_location + '/up-arrow32.png'))
  2664. self.jog_z_up_button.setText('Z')
  2665. self.jog_z_up_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
  2666. self.jog_z_up_button.setToolTip(
  2667. _("Jog the Z axis.")
  2668. )
  2669. grbl_jog_grid.addWidget(self.jog_z_up_button, 2, 3)
  2670. # JOG Z Down
  2671. self.jog_z_down_button = QtWidgets.QToolButton()
  2672. self.jog_z_down_button.setIcon(QtGui.QIcon(self.app.resource_location + '/down-arrow32.png'))
  2673. self.jog_z_down_button.setText('Z')
  2674. self.jog_z_down_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
  2675. self.jog_z_down_button.setToolTip(
  2676. _("Jog the Z axis.")
  2677. )
  2678. grbl_jog_grid.addWidget(self.jog_z_down_button, 4, 3)
  2679. class FCZeroAxes(QtWidgets.QFrame):
  2680. def __init__(self, title, app, *args, **kwargs):
  2681. super(FCZeroAxes, self).__init__(*args, **kwargs)
  2682. self.app = app
  2683. self.setFrameShape(QtWidgets.QFrame.Box)
  2684. self.setLineWidth(1)
  2685. # Zero the axes
  2686. grbl_zero_grid = QtWidgets.QGridLayout()
  2687. grbl_zero_grid.setColumnStretch(0, 0)
  2688. grbl_zero_grid.setColumnStretch(1, 0)
  2689. grbl_zero_grid.setRowStretch(4, 1)
  2690. self.setLayout(grbl_zero_grid)
  2691. zero_title_label = FCLabel(title)
  2692. zero_title_label.setStyleSheet("""
  2693. FCLabel
  2694. {
  2695. font-weight: bold;
  2696. }
  2697. """)
  2698. grbl_zero_grid.addWidget(zero_title_label, 0, 0, 1, 2)
  2699. # Zero X axis
  2700. self.grbl_zerox_button = QtWidgets.QToolButton()
  2701. self.grbl_zerox_button.setText(_("X"))
  2702. self.grbl_zerox_button.setToolTip(
  2703. _("Zero the CNC X axes at current position.")
  2704. )
  2705. grbl_zero_grid.addWidget(self.grbl_zerox_button, 1, 0)
  2706. # Zero Y axis
  2707. self.grbl_zeroy_button = QtWidgets.QToolButton()
  2708. self.grbl_zeroy_button.setText(_("Y"))
  2709. self.grbl_zeroy_button.setToolTip(
  2710. _("Zero the CNC Y axes at current position.")
  2711. )
  2712. grbl_zero_grid.addWidget(self.grbl_zeroy_button, 2, 0)
  2713. # Zero Z axis
  2714. self.grbl_zeroz_button = QtWidgets.QToolButton()
  2715. self.grbl_zeroz_button.setText(_("Z"))
  2716. self.grbl_zeroz_button.setToolTip(
  2717. _("Zero the CNC Z axes at current position.")
  2718. )
  2719. grbl_zero_grid.addWidget(self.grbl_zeroz_button, 3, 0)
  2720. # Zeroo all axes
  2721. self.grbl_zero_all_button = QtWidgets.QToolButton()
  2722. self.grbl_zero_all_button.setText(_("All"))
  2723. self.grbl_zero_all_button.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
  2724. self.grbl_zero_all_button.setToolTip(
  2725. _("Zero all CNC axes at current position.")
  2726. )
  2727. grbl_zero_grid.addWidget(self.grbl_zero_all_button, 1, 1, 3, 1)
  2728. class FlatCAMActivityView(QtWidgets.QWidget):
  2729. """
  2730. This class create and control the activity icon displayed in the App status bar
  2731. """
  2732. def __init__(self, app, parent=None):
  2733. super().__init__(parent=parent)
  2734. self.app = app
  2735. if self.app.defaults["global_activity_icon"] == "Ball green":
  2736. icon = self.app.resource_location + '/active_2_static.png'
  2737. movie = self.app.resource_location + "/active_2.gif"
  2738. elif self.app.defaults["global_activity_icon"] == "Ball black":
  2739. icon = self.app.resource_location + '/active_static.png'
  2740. movie = self.app.resource_location + "/active.gif"
  2741. elif self.app.defaults["global_activity_icon"] == "Arrow green":
  2742. icon = self.app.resource_location + '/active_3_static.png'
  2743. movie = self.app.resource_location + "/active_3.gif"
  2744. elif self.app.defaults["global_activity_icon"] == "Eclipse green":
  2745. icon = self.app.resource_location + '/active_4_static.png'
  2746. movie = self.app.resource_location + "/active_4.gif"
  2747. else:
  2748. icon = self.app.resource_location + '/active_static.png'
  2749. movie = self.app.resource_location + "/active.gif"
  2750. self.setMinimumWidth(200)
  2751. self.movie_path = movie
  2752. self.icon_path = icon
  2753. self.icon = FCLabel(self)
  2754. self.icon.setGeometry(0, 0, 16, 12)
  2755. self.movie = QtGui.QMovie(self.movie_path)
  2756. self.icon.setMovie(self.movie)
  2757. # self.movie.start()
  2758. layout = QtWidgets.QHBoxLayout()
  2759. layout.setContentsMargins(5, 0, 5, 0)
  2760. layout.setAlignment(QtCore.Qt.AlignLeft)
  2761. self.setLayout(layout)
  2762. layout.addWidget(self.icon)
  2763. self.text = QtWidgets.QLabel(self)
  2764. self.text.setText(_("Idle."))
  2765. self.icon.setPixmap(QtGui.QPixmap(self.icon_path))
  2766. layout.addWidget(self.text)
  2767. self.icon.clicked.connect(self.app.on_toolbar_replot)
  2768. def set_idle(self):
  2769. self.movie.stop()
  2770. self.text.setText(_("Idle."))
  2771. def set_busy(self, msg, no_movie=None):
  2772. if no_movie is not True:
  2773. self.icon.setMovie(self.movie)
  2774. self.movie.start()
  2775. self.text.setText(msg)
  2776. class FlatCAMInfoBar(QtWidgets.QWidget):
  2777. """
  2778. This class create a place to display the App messages in the Status Bar
  2779. """
  2780. def __init__(self, parent=None, app=None):
  2781. super(FlatCAMInfoBar, self).__init__(parent=parent)
  2782. self.app = app
  2783. self.icon = QtWidgets.QLabel(self)
  2784. self.icon.setGeometry(0, 0, 12, 12)
  2785. self.pmap = QtGui.QPixmap(self.app.resource_location + '/graylight12.png')
  2786. self.icon.setPixmap(self.pmap)
  2787. self.lock_pmaps = False
  2788. layout = QtWidgets.QHBoxLayout()
  2789. layout.setContentsMargins(5, 0, 5, 0)
  2790. self.setLayout(layout)
  2791. layout.addWidget(self.icon)
  2792. self.text = QtWidgets.QLabel(self)
  2793. self.text.setText(_("Application started ..."))
  2794. self.text.setToolTip(_("Hello!"))
  2795. layout.addWidget(self.text)
  2796. layout.addStretch()
  2797. def set_text_(self, text, color=None):
  2798. self.text.setText(text)
  2799. self.text.setToolTip(text)
  2800. if color:
  2801. self.text.setStyleSheet('color: %s' % str(color))
  2802. def set_status(self, text, level="info"):
  2803. level = str(level)
  2804. if self.lock_pmaps is not True:
  2805. self.pmap.fill()
  2806. if level == "ERROR" or level == "ERROR_NOTCL":
  2807. self.pmap = QtGui.QPixmap(self.app.resource_location + '/redlight12.png')
  2808. elif level.lower() == "success":
  2809. self.pmap = QtGui.QPixmap(self.app.resource_location + '/greenlight12.png')
  2810. elif level == "WARNING" or level == "WARNING_NOTCL":
  2811. self.pmap = QtGui.QPixmap(self.app.resource_location + '/yellowlight12.png')
  2812. elif level.lower() == "selected":
  2813. self.pmap = QtGui.QPixmap(self.app.resource_location + '/bluelight12.png')
  2814. else:
  2815. self.pmap = QtGui.QPixmap(self.app.resource_location + '/graylight12.png')
  2816. try:
  2817. self.set_text_(text)
  2818. self.icon.setPixmap(self.pmap)
  2819. except Exception as e:
  2820. log.debug("FlatCAMInfoBar.set_status() --> %s" % str(e))
  2821. class FlatCAMSystemTray(QtWidgets.QSystemTrayIcon):
  2822. """
  2823. This class create the Sys Tray icon for the app
  2824. """
  2825. def __init__(self, app, icon, headless=None, parent=None):
  2826. # QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
  2827. super().__init__(icon, parent=parent)
  2828. self.app = app
  2829. menu = QtWidgets.QMenu(parent)
  2830. menu_runscript = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/script14.png'),
  2831. '%s' % _('Run Script ...'), self)
  2832. menu_runscript.setToolTip(
  2833. _("Will run the opened Tcl Script thus\n"
  2834. "enabling the automation of certain\n"
  2835. "functions of FlatCAM.")
  2836. )
  2837. menu.addAction(menu_runscript)
  2838. menu.addSeparator()
  2839. if headless is None:
  2840. self.menu_open = menu.addMenu(QtGui.QIcon(self.app.resource_location + '/folder32_bis.png'), _('Open'))
  2841. # Open Project ...
  2842. menu_openproject = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/folder16.png'),
  2843. _('Open Project ...'), self)
  2844. self.menu_open.addAction(menu_openproject)
  2845. self.menu_open.addSeparator()
  2846. # Open Gerber ...
  2847. menu_opengerber = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/flatcam_icon24.png'),
  2848. _('Open &Gerber ...\tCtrl+G'), self)
  2849. self.menu_open.addAction(menu_opengerber)
  2850. # Open Excellon ...
  2851. menu_openexcellon = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/open_excellon32.png'),
  2852. _('Open &Excellon ...\tCtrl+E'), self)
  2853. self.menu_open.addAction(menu_openexcellon)
  2854. # Open G-Code ...
  2855. menu_opengcode = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/code.png'),
  2856. _('Open G-&Code ...'), self)
  2857. self.menu_open.addAction(menu_opengcode)
  2858. self.menu_open.addSeparator()
  2859. menu_openproject.triggered.connect(self.app.on_file_openproject)
  2860. menu_opengerber.triggered.connect(self.app.on_fileopengerber)
  2861. menu_openexcellon.triggered.connect(self.app.on_fileopenexcellon)
  2862. menu_opengcode.triggered.connect(self.app.on_fileopengcode)
  2863. exitAction = menu.addAction(_("Exit"))
  2864. exitAction.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  2865. self.setContextMenu(menu)
  2866. menu_runscript.triggered.connect(lambda: self.app.on_filerunscript(
  2867. silent=True if self.app.cmd_line_headless == 1 else False))
  2868. exitAction.triggered.connect(self.app.final_save)
  2869. def message_dialog(title, message, kind="info", parent=None):
  2870. """
  2871. Builds and show a custom QMessageBox to be used in FlatCAM.
  2872. :param title: title of the QMessageBox
  2873. :param message: message to be displayed
  2874. :param kind: type of QMessageBox; will display a specific icon.
  2875. :param parent: parent
  2876. :return: None
  2877. """
  2878. icon = {"info": QtWidgets.QMessageBox.Information,
  2879. "warning": QtWidgets.QMessageBox.Warning,
  2880. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2881. dlg = QtWidgets.QMessageBox(icon, title, message, parent=parent)
  2882. dlg.setText(message)
  2883. dlg.exec_()
  2884. def rreplace(s, old, new, occurrence):
  2885. """
  2886. Credits go here:
  2887. https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
  2888. :param s: string to be processed
  2889. :param old: old char to be replaced
  2890. :param new: new char to replace the old one
  2891. :param occurrence: how many places from end to replace the old char
  2892. :return: modified string
  2893. """
  2894. li = s.rsplit(old, occurrence)
  2895. return new.join(li)