GUIElements.py 103 KB

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