GUIElements.py 116 KB

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