GUIElements.py 94 KB

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