GUIElements.py 103 KB

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