GUIElements.py 112 KB

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