GUIElements.py 103 KB

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