GUIElements.py 96 KB

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