GUIElements.py 101 KB

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