GUIElements.py 96 KB

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