GUIElements.py 99 KB

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