GUIElements.py 99 KB

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