GUIElements.py 97 KB

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