GUIElements.py 98 KB

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