GUIElements.py 106 KB

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