GUIElements.py 101 KB

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