GUIElements.py 100 KB

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