GUIElements.py 96 KB

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