GUIElements.py 95 KB

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