GUIElements.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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, pyqtSignal, pyqtSlot
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  16. from copy import copy
  17. import re
  18. import logging
  19. import html
  20. log = logging.getLogger('base')
  21. EDIT_SIZE_HINT = 70
  22. class RadioSet(QtWidgets.QWidget):
  23. activated_custom = QtCore.pyqtSignal(str)
  24. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  25. """
  26. The choices are specified as a list of dictionaries containing:
  27. * 'label': Shown in the UI
  28. * 'value': The value returned is selected
  29. :param choices: List of choices. See description.
  30. :param orientation: 'horizontal' (default) of 'vertical'.
  31. :param parent: Qt parent widget.
  32. :type choices: list
  33. """
  34. super(RadioSet, self).__init__(parent)
  35. self.choices = copy(choices)
  36. if orientation == 'horizontal':
  37. layout = QtWidgets.QHBoxLayout()
  38. else:
  39. layout = QtWidgets.QVBoxLayout()
  40. group = QtWidgets.QButtonGroup(self)
  41. for choice in self.choices:
  42. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  43. group.addButton(choice['radio'])
  44. layout.addWidget(choice['radio'], stretch=0)
  45. choice['radio'].toggled.connect(self.on_toggle)
  46. layout.setContentsMargins(0, 0, 0, 0)
  47. if stretch is False:
  48. pass
  49. else:
  50. layout.addStretch()
  51. self.setLayout(layout)
  52. self.group_toggle_fn = lambda: None
  53. def on_toggle(self):
  54. # log.debug("Radio toggled")
  55. radio = self.sender()
  56. if radio.isChecked():
  57. self.group_toggle_fn()
  58. ret_val = str(self.get_value())
  59. self.activated_custom.emit(ret_val)
  60. return
  61. def get_value(self):
  62. for choice in self.choices:
  63. if choice['radio'].isChecked():
  64. return choice['value']
  65. log.error("No button was toggled in RadioSet.")
  66. return None
  67. def set_value(self, val):
  68. for choice in self.choices:
  69. if choice['value'] == val:
  70. choice['radio'].setChecked(True)
  71. return
  72. log.error("Value given is not part of this RadioSet: %s" % str(val))
  73. # class RadioGroupChoice(QtWidgets.QWidget):
  74. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  75. # """
  76. # The choices are specified as a list of dictionaries containing:
  77. #
  78. # * 'label': Shown in the UI
  79. # * 'value': The value returned is selected
  80. #
  81. # :param choices: List of choices. See description.
  82. # :param orientation: 'horizontal' (default) of 'vertical'.
  83. # :param parent: Qt parent widget.
  84. # :type choices: list
  85. # """
  86. # super().__init__(parent)
  87. #
  88. # group = QtGui.QButtonGroup(self)
  89. #
  90. # self.lbl1 = label_1
  91. # self.lbl2 = label_2
  92. # self.hide_list = hide_list
  93. # self.show_list = show_list
  94. #
  95. # self.btn1 = QtGui.QRadioButton(str(label_1))
  96. # self.btn2 = QtGui.QRadioButton(str(label_2))
  97. # group.addButton(self.btn1)
  98. # group.addButton(self.btn2)
  99. #
  100. # if to_check == 1:
  101. # self.btn1.setChecked(True)
  102. # else:
  103. # self.btn2.setChecked(True)
  104. #
  105. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  106. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  107. #
  108. # def btn_state(self, btn):
  109. # if btn.text() == self.lbl1:
  110. # if btn.isChecked() is True:
  111. # self.show_widgets(self.show_list)
  112. # self.hide_widgets(self.hide_list)
  113. # else:
  114. # self.show_widgets(self.hide_list)
  115. # self.hide_widgets(self.show_list)
  116. #
  117. # def hide_widgets(self, lst):
  118. # for wgt in lst:
  119. # wgt.hide()
  120. #
  121. # def show_widgets(self, lst):
  122. # for wgt in lst:
  123. # wgt.show()
  124. class LengthEntry(QtWidgets.QLineEdit):
  125. def __init__(self, output_units='IN', parent=None):
  126. super(LengthEntry, self).__init__(parent)
  127. self.output_units = output_units
  128. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  129. # Unit conversion table OUTPUT-INPUT
  130. self.scales = {
  131. 'IN': {'IN': 1.0,
  132. 'MM': 1/25.4},
  133. 'MM': {'IN': 25.4,
  134. 'MM': 1.0}
  135. }
  136. self.readyToEdit = True
  137. self.editingFinished.connect(self.on_edit_finished)
  138. def on_edit_finished(self):
  139. self.clearFocus()
  140. def mousePressEvent(self, e, Parent=None):
  141. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  142. if self.readyToEdit:
  143. self.selectAll()
  144. self.readyToEdit = False
  145. def focusOutEvent(self, e):
  146. # don't focus out if the user requests an popup menu
  147. if e.reason() != QtCore.Qt.PopupFocusReason:
  148. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  149. self.deselect()
  150. self.readyToEdit = True
  151. def returnPressed(self, *args, **kwargs):
  152. val = self.get_value()
  153. if val is not None:
  154. self.set_text(str(val))
  155. else:
  156. log.warning("Could not interpret entry: %s" % self.get_text())
  157. def get_value(self):
  158. raw = str(self.text()).strip(' ')
  159. # match = self.format_re.search(raw)
  160. try:
  161. units = raw[-2:]
  162. units = self.scales[self.output_units][units.upper()]
  163. value = raw[:-2]
  164. return float(eval(value))* units
  165. except IndexError:
  166. value = raw
  167. return float(eval(value))
  168. except KeyError:
  169. value = raw
  170. return float(eval(value))
  171. except:
  172. log.warning("Could not parse value in entry: %s" % str(raw))
  173. return None
  174. def set_value(self, val):
  175. self.setText(str('%.4f' % val))
  176. def sizeHint(self):
  177. default_hint_size = super(LengthEntry, self).sizeHint()
  178. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  179. class FloatEntry(QtWidgets.QLineEdit):
  180. def __init__(self, parent=None):
  181. super(FloatEntry, self).__init__(parent)
  182. self.readyToEdit = True
  183. self.editingFinished.connect(self.on_edit_finished)
  184. def on_edit_finished(self):
  185. self.clearFocus()
  186. def mousePressEvent(self, e, Parent=None):
  187. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  188. if self.readyToEdit == True:
  189. self.selectAll()
  190. self.readyToEdit = False
  191. def focusOutEvent(self, e):
  192. # don't focus out if the user requests an popup menu
  193. if e.reason() != QtCore.Qt.PopupFocusReason:
  194. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  195. self.deselect()
  196. self.readyToEdit = True
  197. def returnPressed(self, *args, **kwargs):
  198. val = self.get_value()
  199. if val is not None:
  200. self.set_text(str(val))
  201. else:
  202. log.warning("Could not interpret entry: %s" % self.text())
  203. def get_value(self):
  204. raw = str(self.text()).strip(' ')
  205. try:
  206. evaled = eval(raw)
  207. return float(evaled)
  208. except Exception as e:
  209. if raw is not '':
  210. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  211. return None
  212. def set_value(self, val):
  213. if val is not None:
  214. self.setText("%.4f" % float(val))
  215. else:
  216. self.setText("")
  217. def sizeHint(self):
  218. default_hint_size = super(FloatEntry, self).sizeHint()
  219. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  220. class FloatEntry2(QtWidgets.QLineEdit):
  221. def __init__(self, parent=None):
  222. super(FloatEntry2, self).__init__(parent)
  223. self.readyToEdit = True
  224. self.editingFinished.connect(self.on_edit_finished)
  225. def on_edit_finished(self):
  226. self.clearFocus()
  227. def mousePressEvent(self, e, Parent=None):
  228. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  229. if self.readyToEdit:
  230. self.selectAll()
  231. self.readyToEdit = False
  232. def focusOutEvent(self, e):
  233. # don't focus out if the user requests an popup menu
  234. if e.reason() != QtCore.Qt.PopupFocusReason:
  235. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  236. self.deselect()
  237. self.readyToEdit = True
  238. def get_value(self):
  239. raw = str(self.text()).strip(' ')
  240. try:
  241. evaled = eval(raw)
  242. return float(evaled)
  243. except Exception as e:
  244. if raw is not '':
  245. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  246. return None
  247. def set_value(self, val):
  248. self.setText("%.4f" % val)
  249. def sizeHint(self):
  250. default_hint_size = super(FloatEntry2, self).sizeHint()
  251. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  252. class IntEntry(QtWidgets.QLineEdit):
  253. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  254. super(IntEntry, self).__init__(parent)
  255. self.allow_empty = allow_empty
  256. self.empty_val = empty_val
  257. self.readyToEdit = True
  258. self.editingFinished.connect(self.on_edit_finished)
  259. def on_edit_finished(self):
  260. self.clearFocus()
  261. def mousePressEvent(self, e, Parent=None):
  262. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  263. if self.readyToEdit:
  264. self.selectAll()
  265. self.readyToEdit = False
  266. def focusOutEvent(self, e):
  267. # don't focus out if the user requests an popup menu
  268. if e.reason() != QtCore.Qt.PopupFocusReason:
  269. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  270. self.deselect()
  271. self.readyToEdit = True
  272. def get_value(self):
  273. if self.allow_empty:
  274. if str(self.text()) == "":
  275. return self.empty_val
  276. # make the text() first a float and then int because if text is a float type,
  277. # the int() can't convert directly a "text float" into a int type.
  278. ret_val = float(self.text())
  279. ret_val = int(ret_val)
  280. return ret_val
  281. def set_value(self, val):
  282. if val == self.empty_val and self.allow_empty:
  283. self.setText("")
  284. return
  285. self.setText(str(val))
  286. def sizeHint(self):
  287. default_hint_size = super(IntEntry, self).sizeHint()
  288. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  289. class FCEntry(QtWidgets.QLineEdit):
  290. def __init__(self, parent=None):
  291. super(FCEntry, self).__init__(parent)
  292. self.readyToEdit = True
  293. self.editingFinished.connect(self.on_edit_finished)
  294. def on_edit_finished(self):
  295. self.clearFocus()
  296. def mousePressEvent(self, e, parent=None):
  297. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  298. if self.readyToEdit:
  299. self.selectAll()
  300. self.readyToEdit = False
  301. def focusOutEvent(self, e):
  302. if e.reason() != QtCore.Qt.PopupFocusReason:
  303. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  304. self.deselect()
  305. self.readyToEdit = True
  306. def get_value(self):
  307. return str(self.text())
  308. def set_value(self, val):
  309. if type(val) is float:
  310. self.setText('%.4f' % val)
  311. else:
  312. self.setText(str(val))
  313. def sizeHint(self):
  314. default_hint_size = super(FCEntry, self).sizeHint()
  315. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  316. class FCEntry2(FCEntry):
  317. def __init__(self, parent=None):
  318. super(FCEntry2, self).__init__(parent)
  319. def set_value(self, val, decimals=4):
  320. try:
  321. fval = float(val)
  322. except ValueError:
  323. return
  324. self.setText('%.*f' % (decimals, fval))
  325. class FCEntry3(FCEntry):
  326. def __init__(self, parent=None):
  327. super(FCEntry3, self).__init__(parent)
  328. def set_value(self, val, decimals=4):
  329. try:
  330. fval = float(val)
  331. except ValueError:
  332. return
  333. self.setText('%.*f' % (decimals, fval))
  334. def get_value(self):
  335. value = str(self.text()).strip(' ')
  336. try:
  337. return float(eval(value))
  338. except Exception as e:
  339. log.warning("Could not parse value in entry: %s" % str(e))
  340. return None
  341. class EvalEntry(QtWidgets.QLineEdit):
  342. def __init__(self, parent=None):
  343. super(EvalEntry, self).__init__(parent)
  344. self.readyToEdit = True
  345. self.editingFinished.connect(self.on_edit_finished)
  346. def on_edit_finished(self):
  347. self.clearFocus()
  348. def mousePressEvent(self, e, parent=None):
  349. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  350. if self.readyToEdit:
  351. self.selectAll()
  352. self.readyToEdit = False
  353. def focusOutEvent(self, e):
  354. if e.reason() != QtCore.Qt.PopupFocusReason:
  355. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  356. self.deselect()
  357. self.readyToEdit = True
  358. def returnPressed(self, *args, **kwargs):
  359. val = self.get_value()
  360. if val is not None:
  361. self.setText(str(val))
  362. else:
  363. log.warning("Could not interpret entry: %s" % self.get_text())
  364. def get_value(self):
  365. raw = str(self.text()).strip(' ')
  366. evaled = 0.0
  367. try:
  368. evaled = eval(raw)
  369. except Exception as e:
  370. if raw is not '':
  371. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  372. return None
  373. return evaled
  374. def set_value(self, val):
  375. self.setText(str(val))
  376. def sizeHint(self):
  377. default_hint_size = super(EvalEntry, self).sizeHint()
  378. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  379. class EvalEntry2(QtWidgets.QLineEdit):
  380. def __init__(self, parent=None):
  381. super(EvalEntry2, self).__init__(parent)
  382. self.readyToEdit = True
  383. self.editingFinished.connect(self.on_edit_finished)
  384. def on_edit_finished(self):
  385. self.clearFocus()
  386. def mousePressEvent(self, e, parent=None):
  387. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  388. if self.readyToEdit:
  389. self.selectAll()
  390. self.readyToEdit = False
  391. def focusOutEvent(self, e):
  392. if e.reason() != QtCore.Qt.PopupFocusReason:
  393. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  394. self.deselect()
  395. self.readyToEdit = True
  396. def get_value(self):
  397. raw = str(self.text()).strip(' ')
  398. evaled = 0.0
  399. try:
  400. evaled = eval(raw)
  401. except Exception as e:
  402. if raw is not '':
  403. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  404. return None
  405. return evaled
  406. def set_value(self, val):
  407. self.setText(str(val))
  408. def sizeHint(self):
  409. default_hint_size = super(EvalEntry2, self).sizeHint()
  410. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  411. class FCCheckBox(QtWidgets.QCheckBox):
  412. def __init__(self, label='', parent=None):
  413. super(FCCheckBox, self).__init__(str(label), parent)
  414. def get_value(self):
  415. return self.isChecked()
  416. def set_value(self, val):
  417. self.setChecked(val)
  418. def toggle(self):
  419. self.set_value(not self.get_value())
  420. class FCTextArea(QtWidgets.QPlainTextEdit):
  421. def __init__(self, parent=None):
  422. super(FCTextArea, self).__init__(parent)
  423. def set_value(self, val):
  424. self.setPlainText(val)
  425. def get_value(self):
  426. return str(self.toPlainText())
  427. def sizeHint(self):
  428. default_hint_size = super(FCTextArea, self).sizeHint()
  429. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  430. class FCTextAreaRich(QtWidgets.QTextEdit):
  431. def __init__(self, parent=None):
  432. super(FCTextAreaRich, self).__init__(parent)
  433. def set_value(self, val):
  434. self.setText(val)
  435. def get_value(self):
  436. return str(self.toPlainText())
  437. def sizeHint(self):
  438. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  439. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  440. class FCTextAreaExtended(QtWidgets.QTextEdit):
  441. def __init__(self, parent=None):
  442. super(FCTextAreaExtended, self).__init__(parent)
  443. self.completer = MyCompleter()
  444. self.model = QtCore.QStringListModel()
  445. self.completer.setModel(self.model)
  446. self.set_model_data(keyword_list=[])
  447. self.completer.insertText.connect(self.insertCompletion)
  448. self.completer_enable = False
  449. def set_model_data(self, keyword_list):
  450. self.model.setStringList(keyword_list)
  451. def insertCompletion(self, completion):
  452. tc = self.textCursor()
  453. extra = (len(completion) - len(self.completer.completionPrefix()))
  454. # don't insert if the word is finished but add a space instead
  455. if extra == 0:
  456. tc.insertText(' ')
  457. self.completer.popup().hide()
  458. return
  459. tc.movePosition(QTextCursor.Left)
  460. tc.movePosition(QTextCursor.EndOfWord)
  461. tc.insertText(completion[-extra:])
  462. # add a space after inserting the word
  463. tc.insertText(' ')
  464. self.setTextCursor(tc)
  465. self.completer.popup().hide()
  466. def focusInEvent(self, event):
  467. if self.completer:
  468. self.completer.setWidget(self)
  469. QTextEdit.focusInEvent(self, event)
  470. def set_value(self, val):
  471. self.setText(val)
  472. def get_value(self):
  473. self.toPlainText()
  474. def insertFromMimeData(self, data):
  475. """
  476. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  477. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  478. :param data:
  479. :return:
  480. """
  481. modifier = QtWidgets.QApplication.keyboardModifiers()
  482. if modifier == Qt.ShiftModifier:
  483. text = data.text()
  484. text = text.replace('\\', '/')
  485. self.insertPlainText(text)
  486. else:
  487. self.insertPlainText(data.text())
  488. def keyPressEvent(self, event):
  489. """
  490. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  491. :param event:
  492. :return:
  493. """
  494. key = event.key()
  495. modifier = QtWidgets.QApplication.keyboardModifiers()
  496. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  497. if key == QtCore.Qt.Key_V:
  498. clipboard = QtWidgets.QApplication.clipboard()
  499. clip_text = clipboard.text()
  500. clip_text = clip_text.replace('\\', '/')
  501. self.insertPlainText(clip_text)
  502. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  503. self.comment()
  504. tc = self.textCursor()
  505. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  506. self.completer.insertText.emit(self.completer.getSelected())
  507. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  508. return
  509. elif key == Qt.Key_BraceLeft:
  510. tc.insertText('{}')
  511. self.moveCursor(QtGui.QTextCursor.Left)
  512. elif key == Qt.Key_BracketLeft:
  513. tc.insertText('[]')
  514. self.moveCursor(QtGui.QTextCursor.Left)
  515. elif key == Qt.Key_ParenLeft:
  516. tc.insertText('()')
  517. self.moveCursor(QtGui.QTextCursor.Left)
  518. elif key == Qt.Key_BraceRight:
  519. tc.select(QtGui.QTextCursor.WordUnderCursor)
  520. if tc.selectedText() == '}':
  521. tc.movePosition(QTextCursor.Right)
  522. self.setTextCursor(tc)
  523. else:
  524. tc.clearSelection()
  525. self.textCursor().insertText('}')
  526. elif key == Qt.Key_BracketRight:
  527. tc.select(QtGui.QTextCursor.WordUnderCursor)
  528. if tc.selectedText() == ']':
  529. tc.movePosition(QTextCursor.Right)
  530. self.setTextCursor(tc)
  531. else:
  532. tc.clearSelection()
  533. self.textCursor().insertText(']')
  534. elif key == Qt.Key_ParenRight:
  535. tc.select(QtGui.QTextCursor.WordUnderCursor)
  536. if tc.selectedText() == ')':
  537. tc.movePosition(QTextCursor.Right)
  538. self.setTextCursor(tc)
  539. else:
  540. tc.clearSelection()
  541. self.textCursor().insertText(')')
  542. else:
  543. super(FCTextAreaExtended, self).keyPressEvent(event)
  544. if self.completer_enable:
  545. tc.select(QTextCursor.WordUnderCursor)
  546. cr = self.cursorRect()
  547. if len(tc.selectedText()) > 0:
  548. self.completer.setCompletionPrefix(tc.selectedText())
  549. popup = self.completer.popup()
  550. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  551. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  552. + self.completer.popup().verticalScrollBar().sizeHint().width())
  553. self.completer.complete(cr)
  554. else:
  555. self.completer.popup().hide()
  556. def comment(self):
  557. """
  558. Got it from here:
  559. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  560. :return:
  561. """
  562. pos = self.textCursor().position()
  563. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  564. line_text = self.textCursor().block().text()
  565. if self.textCursor().block().text().startswith(" "):
  566. # skip the white space
  567. self.moveCursor(QtGui.QTextCursor.NextWord)
  568. self.moveCursor(QtGui.QTextCursor.NextCharacter,QtGui.QTextCursor.KeepAnchor)
  569. character = self.textCursor().selectedText()
  570. if character == "#":
  571. # delete #
  572. self.textCursor().deletePreviousChar()
  573. # delete white space
  574. self.moveCursor(QtGui.QTextCursor.NextWord,QtGui.QTextCursor.KeepAnchor)
  575. self.textCursor().removeSelectedText()
  576. else:
  577. self.moveCursor(QtGui.QTextCursor.PreviousCharacter,QtGui.QTextCursor.KeepAnchor)
  578. self.textCursor().insertText("# ")
  579. cursor = QtGui.QTextCursor(self.textCursor())
  580. cursor.setPosition(pos)
  581. self.setTextCursor(cursor)
  582. class FCComboBox(QtWidgets.QComboBox):
  583. def __init__(self, parent=None, callback=None):
  584. super(FCComboBox, self).__init__(parent)
  585. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  586. self.view = self.view()
  587. self.view.viewport().installEventFilter(self)
  588. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  589. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  590. # pos = mouse right click click position
  591. # self = is the combobox object itself
  592. if callback:
  593. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  594. def eventFilter(self, obj, event):
  595. if event.type() == QtCore.QEvent.MouseButtonRelease:
  596. if event.button() == Qt.RightButton:
  597. return True
  598. return False
  599. def wheelEvent(self, *args, **kwargs):
  600. pass
  601. def get_value(self):
  602. return str(self.currentText())
  603. def set_value(self, val):
  604. self.setCurrentIndex(self.findText(str(val)))
  605. class FCInputDialog(QtWidgets.QInputDialog):
  606. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  607. init_val=None):
  608. super(FCInputDialog, self).__init__(parent)
  609. self.allow_empty = ok
  610. self.empty_val = val
  611. self.val = 0.0
  612. self.ok = ''
  613. self.init_value = init_val if init_val else 0.0
  614. if title is None:
  615. self.title = 'title'
  616. else:
  617. self.title = title
  618. if text is None:
  619. self.text = 'text'
  620. else:
  621. self.text = text
  622. if min is None:
  623. self.min = 0
  624. else:
  625. self.min = min
  626. if max is None:
  627. self.max = 0
  628. else:
  629. self.max = max
  630. if decimals is None:
  631. self.decimals = 6
  632. else:
  633. self.decimals = decimals
  634. def get_value(self):
  635. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  636. max=self.max, decimals=self.decimals, value=self.init_value)
  637. return [self.val, self.ok]
  638. # "Transform", "Enter the Angle value:"
  639. def set_value(self, val):
  640. pass
  641. class FCButton(QtWidgets.QPushButton):
  642. def __init__(self, parent=None):
  643. super(FCButton, self).__init__(parent)
  644. def get_value(self):
  645. return self.isChecked()
  646. def set_value(self, val):
  647. self.setText(str(val))
  648. class FCMenu(QtWidgets.QMenu):
  649. def __init__(self):
  650. super().__init__()
  651. self.mouse_is_panning = False
  652. def popup(self, pos, action=None):
  653. self.mouse_is_panning = False
  654. super().popup(pos)
  655. class FCTab(QtWidgets.QTabWidget):
  656. def __init__(self, parent=None):
  657. super(FCTab, self).__init__(parent)
  658. self.setTabsClosable(True)
  659. self.tabCloseRequested.connect(self.closeTab)
  660. def deleteTab(self, currentIndex):
  661. widget = self.widget(currentIndex)
  662. if widget is not None:
  663. widget.deleteLater()
  664. self.removeTab(currentIndex)
  665. def closeTab(self, currentIndex):
  666. self.removeTab(currentIndex)
  667. def protectTab(self, currentIndex):
  668. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  669. # class FCTabBar(QtWidgets.QTabBar):
  670. # def tabSizeHint(self, index):
  671. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  672. # w = int(self.width()/self.count())
  673. # return QtCore.QSize(w, size.height())
  674. class FCDetachableTab(QtWidgets.QTabWidget):
  675. """
  676. From here:
  677. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  678. """
  679. def __init__(self, protect=None, protect_by_name=None, parent=None):
  680. super().__init__()
  681. self.tabBar = self.FCTabBar(self)
  682. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  683. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  684. self.set_detachable(val=True)
  685. self.setTabBar(self.tabBar)
  686. # Used to keep a reference to detached tabs since their QMainWindow
  687. # does not have a parent
  688. self.detachedTabs = {}
  689. # a way to make sure that tabs can't be closed after they attach to the parent tab
  690. self.protect_tab = True if protect is not None and protect is True else False
  691. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  692. # Close all detached tabs if the application is closed explicitly
  693. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  694. # used by the property self.useOldIndex(param)
  695. self.use_old_index = None
  696. self.old_index = None
  697. self.setTabsClosable(True)
  698. self.tabCloseRequested.connect(self.closeTab)
  699. def set_rmb_callback(self, callback):
  700. """
  701. :param callback: Function to call on right mouse click on tab
  702. :type callback: func
  703. :return: None
  704. """
  705. self.tabBar.right_click.connect(callback)
  706. def set_detachable(self, val=True):
  707. try:
  708. self.tabBar.onDetachTabSignal.disconnect()
  709. except TypeError:
  710. pass
  711. if val is True:
  712. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  713. # the tab can be moved around
  714. self.tabBar.can_be_dragged = True
  715. else:
  716. # the detached tab can't be moved
  717. self.tabBar.can_be_dragged = False
  718. return val
  719. def setupContextMenu(self):
  720. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  722. action_name = str(entry)
  723. action = QtWidgets.QAction(self)
  724. action.setCheckable(True)
  725. action.setText(action_name)
  726. if icon:
  727. assert isinstance(icon, QtGui.QIcon), \
  728. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  729. action.setIcon(icon)
  730. action.setChecked(initial_checked)
  731. self.addAction(action)
  732. action.triggered.connect(call_function)
  733. def useOldIndex(self, param):
  734. if param:
  735. self.use_old_index = True
  736. else:
  737. self.use_old_index = False
  738. def deleteTab(self, currentIndex):
  739. widget = self.widget(currentIndex)
  740. if widget is not None:
  741. widget.deleteLater()
  742. self.removeTab(currentIndex)
  743. def closeTab(self, currentIndex):
  744. """
  745. Slot connected to the tabCloseRequested signal
  746. :param currentIndex:
  747. :return:
  748. """
  749. self.removeTab(currentIndex)
  750. def protectTab(self, currentIndex):
  751. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  752. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  753. def setMovable(self, movable):
  754. """
  755. The default movable functionality of QTabWidget must remain disabled
  756. so as not to conflict with the added features
  757. :param movable:
  758. :return:
  759. """
  760. pass
  761. @pyqtSlot(int, int)
  762. def moveTab(self, fromIndex, toIndex):
  763. """
  764. Move a tab from one position (index) to another
  765. :param fromIndex: the original index location of the tab
  766. :param toIndex: the new index location of the tab
  767. :return:
  768. """
  769. widget = self.widget(fromIndex)
  770. icon = self.tabIcon(fromIndex)
  771. text = self.tabText(fromIndex)
  772. self.removeTab(fromIndex)
  773. self.insertTab(toIndex, widget, icon, text)
  774. self.setCurrentIndex(toIndex)
  775. @pyqtSlot(int, QtCore.QPoint)
  776. def detachTab(self, index, point):
  777. """
  778. Detach the tab by removing it's contents and placing them in
  779. a DetachedTab window
  780. :param index: the index location of the tab to be detached
  781. :param point: the screen position for creating the new DetachedTab window
  782. :return:
  783. """
  784. self.old_index = index
  785. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  786. name = "FlatCAM " + self.tabText(index)
  787. icon = self.tabIcon(index)
  788. if icon.isNull():
  789. icon = self.window().windowIcon()
  790. contentWidget = self.widget(index)
  791. try:
  792. contentWidgetRect = contentWidget.frameGeometry()
  793. except AttributeError:
  794. return
  795. # Create a new detached tab window
  796. detachedTab = self.FCDetachedTab(name, contentWidget)
  797. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  798. detachedTab.setWindowIcon(icon)
  799. detachedTab.setGeometry(contentWidgetRect)
  800. detachedTab.onCloseSignal.connect(self.attachTab)
  801. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  802. detachedTab.move(point)
  803. detachedTab.show()
  804. # Create a reference to maintain access to the detached tab
  805. self.detachedTabs[name] = detachedTab
  806. def attachTab(self, contentWidget, name, icon, insertAt=None):
  807. """
  808. Re-attach the tab by removing the content from the DetachedTab window,
  809. closing it, and placing the content back into the DetachableTabWidget
  810. :param contentWidget: the content widget from the DetachedTab window
  811. :param name: the name of the detached tab
  812. :param icon: the window icon for the detached tab
  813. :param insertAt: insert the re-attached tab at the given index
  814. :return:
  815. """
  816. # Make the content widget a child of this widget
  817. contentWidget.setParent(self)
  818. # Remove the reference
  819. del self.detachedTabs[name]
  820. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  821. name = name.partition(' ')[2]
  822. # helps in restoring the tab to the same index that it was before was detached
  823. insert_index = self.old_index if self.use_old_index is True else insertAt
  824. # Create an image from the given icon (for comparison)
  825. if not icon.isNull():
  826. try:
  827. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  828. tabIconImage = tabIconPixmap.toImage()
  829. except IndexError:
  830. tabIconImage = None
  831. else:
  832. tabIconImage = None
  833. # Create an image of the main window icon (for comparison)
  834. if not icon.isNull():
  835. try:
  836. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  837. windowIconImage = windowIconPixmap.toImage()
  838. except IndexError:
  839. windowIconImage = None
  840. else:
  841. windowIconImage = None
  842. # Determine if the given image and the main window icon are the same.
  843. # If they are, then do not add the icon to the tab
  844. if tabIconImage == windowIconImage:
  845. if insert_index is None:
  846. index = self.addTab(contentWidget, name)
  847. else:
  848. index = self.insertTab(insert_index, contentWidget, name)
  849. else:
  850. if insert_index is None:
  851. index = self.addTab(contentWidget, icon, name)
  852. else:
  853. index = self.insertTab(insert_index, contentWidget, icon, name)
  854. # on reattaching the tab if protect is true then the closure button is not added
  855. if self.protect_tab is True:
  856. self.protectTab(index)
  857. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  858. if self.protect_by_name is not None:
  859. for tab_name in self.protect_by_name:
  860. for index in range(self.count()):
  861. if str(tab_name) == str(self.tabText(index)):
  862. self.protectTab(index)
  863. # Make this tab the current tab
  864. if index > -1:
  865. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  866. def removeTabByName(self, name):
  867. """
  868. Remove the tab with the given name, even if it is detached
  869. :param name: the name of the tab to be removed
  870. :return:
  871. """
  872. # Remove the tab if it is attached
  873. attached = False
  874. for index in range(self.count()):
  875. if str(name) == str(self.tabText(index)):
  876. self.removeTab(index)
  877. attached = True
  878. break
  879. # If the tab is not attached, close it's window and
  880. # remove the reference to it
  881. if not attached:
  882. for key in self.detachedTabs:
  883. if str(name) == str(key):
  884. self.detachedTabs[key].onCloseSignal.disconnect()
  885. self.detachedTabs[key].close()
  886. del self.detachedTabs[key]
  887. break
  888. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  889. def detachedTabDrop(self, name, index, dropPos):
  890. """
  891. Handle dropping of a detached tab inside the DetachableTabWidget
  892. :param name: the name of the detached tab
  893. :param index: the index of an existing tab (if the tab bar
  894. # determined that the drop occurred on an
  895. # existing tab)
  896. :param dropPos: the mouse cursor position when the drop occurred
  897. :return:
  898. """
  899. # If the drop occurred on an existing tab, insert the detached
  900. # tab at the existing tab's location
  901. if index > -1:
  902. # Create references to the detached tab's content and icon
  903. contentWidget = self.detachedTabs[name].contentWidget
  904. icon = self.detachedTabs[name].windowIcon()
  905. # Disconnect the detached tab's onCloseSignal so that it
  906. # does not try to re-attach automatically
  907. self.detachedTabs[name].onCloseSignal.disconnect()
  908. # Close the detached
  909. self.detachedTabs[name].close()
  910. # Re-attach the tab at the given index
  911. self.attachTab(contentWidget, name, icon, index)
  912. # If the drop did not occur on an existing tab, determine if the drop
  913. # occurred in the tab bar area (the area to the side of the QTabBar)
  914. else:
  915. # Find the drop position relative to the DetachableTabWidget
  916. tabDropPos = self.mapFromGlobal(dropPos)
  917. # If the drop position is inside the DetachableTabWidget...
  918. if self.rect().contains(tabDropPos):
  919. # If the drop position is inside the tab bar area (the
  920. # area to the side of the QTabBar) or there are not tabs
  921. # currently attached...
  922. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  923. # Close the detached tab and allow it to re-attach
  924. # automatically
  925. self.detachedTabs[name].close()
  926. def closeDetachedTabs(self):
  927. """
  928. Close all tabs that are currently detached.
  929. :return:
  930. """
  931. listOfDetachedTabs = []
  932. for key in self.detachedTabs:
  933. listOfDetachedTabs.append(self.detachedTabs[key])
  934. for detachedTab in listOfDetachedTabs:
  935. detachedTab.close()
  936. class FCDetachedTab(QtWidgets.QMainWindow):
  937. """
  938. When a tab is detached, the contents are placed into this QMainWindow. The tab
  939. can be re-attached by closing the dialog or by dragging the window into the tab bar
  940. """
  941. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  942. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  943. def __init__(self, name, contentWidget):
  944. QtWidgets.QMainWindow.__init__(self, None)
  945. self.setObjectName(name)
  946. self.setWindowTitle(name)
  947. self.contentWidget = contentWidget
  948. self.setCentralWidget(self.contentWidget)
  949. self.contentWidget.show()
  950. self.windowDropFilter = self.WindowDropFilter()
  951. self.installEventFilter(self.windowDropFilter)
  952. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  953. @QtCore.pyqtSlot(QtCore.QPoint)
  954. def windowDropSlot(self, dropPos):
  955. """
  956. Handle a window drop event
  957. :param dropPos: the mouse cursor position of the drop
  958. :return:
  959. """
  960. self.onDropSignal.emit(self.objectName(), dropPos)
  961. def closeEvent(self, event):
  962. """
  963. If the window is closed, emit the onCloseSignal and give the
  964. content widget back to the DetachableTabWidget
  965. :param event: a close event
  966. :return:
  967. """
  968. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  969. class WindowDropFilter(QtCore.QObject):
  970. """
  971. An event filter class to detect a QMainWindow drop event
  972. """
  973. onDropSignal = pyqtSignal(QtCore.QPoint)
  974. def __init__(self):
  975. QtCore.QObject.__init__(self)
  976. self.lastEvent = None
  977. def eventFilter(self, obj, event):
  978. """
  979. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  980. event that immediately follows a Move event
  981. :param obj: the object that generated the event
  982. :param event: the current event
  983. :return:
  984. """
  985. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  986. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  987. # Determine the position of the mouse cursor and emit it with the
  988. # onDropSignal
  989. mouseCursor = QtGui.QCursor()
  990. dropPos = mouseCursor.pos()
  991. self.onDropSignal.emit(dropPos)
  992. self.lastEvent = event.type()
  993. return True
  994. else:
  995. self.lastEvent = event.type()
  996. return False
  997. class FCTabBar(QtWidgets.QTabBar):
  998. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  999. onMoveTabSignal = pyqtSignal(int, int)
  1000. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  1001. right_click = pyqtSignal(int)
  1002. def __init__(self, parent=None):
  1003. QtWidgets.QTabBar.__init__(self, parent)
  1004. self.setAcceptDrops(True)
  1005. self.setElideMode(QtCore.Qt.ElideRight)
  1006. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1007. self.prev_index = -1
  1008. self.dragStartPos = QtCore.QPoint()
  1009. self.dragDropedPos = QtCore.QPoint()
  1010. self.mouseCursor = QtGui.QCursor()
  1011. self.dragInitiated = False
  1012. # set this to False and the tab will no longer be displayed as detached
  1013. self.can_be_dragged = True
  1014. def mouseDoubleClickEvent(self, event):
  1015. """
  1016. Send the onDetachTabSignal when a tab is double clicked
  1017. :param event: a mouse double click event
  1018. :return:
  1019. """
  1020. event.accept()
  1021. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1022. def mousePressEvent(self, event):
  1023. """
  1024. Set the starting position for a drag event when the left mouse button is pressed.
  1025. Start detection of a right mouse click.
  1026. :param event: a mouse press event
  1027. :return:
  1028. """
  1029. if event.button() == QtCore.Qt.LeftButton:
  1030. self.dragStartPos = event.pos()
  1031. elif event.button() == QtCore.Qt.RightButton:
  1032. self.prev_index = self.tabAt(event.pos())
  1033. self.dragDropedPos.setX(0)
  1034. self.dragDropedPos.setY(0)
  1035. self.dragInitiated = False
  1036. QtWidgets.QTabBar.mousePressEvent(self, event)
  1037. def mouseReleaseEvent(self, event):
  1038. """
  1039. Finish the detection of the right mouse click on the tab
  1040. :param event: a mouse press event
  1041. :return:
  1042. """
  1043. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1044. self.right_click.emit(self.prev_index)
  1045. self.prev_index = -1
  1046. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1047. def mouseMoveEvent(self, event):
  1048. """
  1049. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1050. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1051. bar, emit an onDetachTabSignal.
  1052. :param event: a mouse move event
  1053. :return:
  1054. """
  1055. # Determine if the current movement is detected as a drag
  1056. if not self.dragStartPos.isNull() and \
  1057. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1058. self.dragInitiated = True
  1059. # If the current movement is a drag initiated by the left button
  1060. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated and self.can_be_dragged):
  1061. # Stop the move event
  1062. finishMoveEvent = QtGui.QMouseEvent(
  1063. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1064. )
  1065. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1066. # Convert the move event into a drag
  1067. drag = QtGui.QDrag(self)
  1068. mimeData = QtCore.QMimeData()
  1069. # mimeData.setData('action', 'application/tab-detach')
  1070. drag.setMimeData(mimeData)
  1071. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1072. # Create the appearance of dragging the tab content
  1073. try:
  1074. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1075. except Exception as e:
  1076. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1077. return
  1078. targetPixmap = QtGui.QPixmap(pixmap.size())
  1079. targetPixmap.fill(QtCore.Qt.transparent)
  1080. painter = QtGui.QPainter(targetPixmap)
  1081. painter.setOpacity(0.85)
  1082. painter.drawPixmap(0, 0, pixmap)
  1083. painter.end()
  1084. drag.setPixmap(targetPixmap)
  1085. # Initiate the drag
  1086. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1087. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1088. # must be set manually
  1089. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1090. dropAction = QtCore.Qt.MoveAction
  1091. # If the drag completed outside of the tab bar, detach the tab and move
  1092. # the content to the current cursor position
  1093. if dropAction == QtCore.Qt.IgnoreAction:
  1094. event.accept()
  1095. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1096. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1097. elif dropAction == QtCore.Qt.MoveAction:
  1098. if not self.dragDropedPos.isNull():
  1099. event.accept()
  1100. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1101. else:
  1102. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1103. def dragEnterEvent(self, event):
  1104. """
  1105. Determine if the drag has entered a tab position from another tab position
  1106. :param event: a drag enter event
  1107. :return:
  1108. """
  1109. mimeData = event.mimeData()
  1110. # formats = mcd imeData.formats()
  1111. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1112. # event.acceptProposedAction()
  1113. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1114. def dropEvent(self, event):
  1115. """
  1116. Get the position of the end of the drag
  1117. :param event: a drop event
  1118. :return:
  1119. """
  1120. self.dragDropedPos = event.pos()
  1121. QtWidgets.QTabBar.dropEvent(self, event)
  1122. def detachedTabDrop(self, name, dropPos):
  1123. """
  1124. Determine if the detached tab drop event occurred on an existing tab,
  1125. then send the event to the DetachableTabWidget
  1126. :param name:
  1127. :param dropPos:
  1128. :return:
  1129. """
  1130. tabDropPos = self.mapFromGlobal(dropPos)
  1131. index = self.tabAt(tabDropPos)
  1132. self.detachedTabDropSignal.emit(name, index, dropPos)
  1133. class FCDetachableTab2(FCDetachableTab):
  1134. tab_closed_signal = pyqtSignal()
  1135. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1136. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1137. def closeTab(self, currentIndex):
  1138. """
  1139. Slot connected to the tabCloseRequested signal
  1140. :param currentIndex:
  1141. :return:
  1142. """
  1143. idx = self.currentIndex()
  1144. # emit the signal only if the name is the one we want; the name should be a parameter somehow
  1145. if self.tabText(idx) == _("Preferences"):
  1146. self.tab_closed_signal.emit()
  1147. self.removeTab(currentIndex)
  1148. class VerticalScrollArea(QtWidgets.QScrollArea):
  1149. """
  1150. This widget extends QtGui.QScrollArea to make a vertical-only
  1151. scroll area that also expands horizontally to accomodate
  1152. its contents.
  1153. """
  1154. def __init__(self, parent=None):
  1155. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1156. self.setWidgetResizable(True)
  1157. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1158. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1159. def eventFilter(self, source, event):
  1160. """
  1161. The event filter gets automatically installed when setWidget()
  1162. is called.
  1163. :param source:
  1164. :param event:
  1165. :return:
  1166. """
  1167. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1168. # log.debug("VerticalScrollArea: Widget resized:")
  1169. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1170. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1171. self.setMinimumWidth(self.widget().sizeHint().width() +
  1172. self.verticalScrollBar().sizeHint().width())
  1173. # if self.verticalScrollBar().isVisible():
  1174. # log.debug(" Scroll bar visible")
  1175. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1176. # self.verticalScrollBar().width())
  1177. # else:
  1178. # log.debug(" Scroll bar hidden")
  1179. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1180. return QtWidgets.QWidget.eventFilter(self, source, event)
  1181. class OptionalInputSection:
  1182. def __init__(self, cb, optinputs, logic=True):
  1183. """
  1184. Associates the a checkbox with a set of inputs.
  1185. :param cb: Checkbox that enables the optional inputs.
  1186. :param optinputs: List of widgets that are optional.
  1187. :param logic: When True the logic is normal, when False the logic is in reverse
  1188. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1189. for logic=False, when the checkbox is checked the widgets are Disabled
  1190. :return:
  1191. """
  1192. assert isinstance(cb, FCCheckBox), \
  1193. "Expected an FCCheckBox, got %s" % type(cb)
  1194. self.cb = cb
  1195. self.optinputs = optinputs
  1196. self.logic = logic
  1197. self.on_cb_change()
  1198. self.cb.stateChanged.connect(self.on_cb_change)
  1199. def on_cb_change(self):
  1200. if self.cb.checkState():
  1201. for widget in self.optinputs:
  1202. if self.logic is True:
  1203. widget.setEnabled(True)
  1204. else:
  1205. widget.setEnabled(False)
  1206. else:
  1207. for widget in self.optinputs:
  1208. if self.logic is True:
  1209. widget.setEnabled(False)
  1210. else:
  1211. widget.setEnabled(True)
  1212. class FCTable(QtWidgets.QTableWidget):
  1213. def __init__(self, parent=None):
  1214. super(FCTable, self).__init__(parent)
  1215. def sizeHint(self):
  1216. default_hint_size = super(FCTable, self).sizeHint()
  1217. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1218. def getHeight(self):
  1219. height = self.horizontalHeader().height()
  1220. for i in range(self.rowCount()):
  1221. height += self.rowHeight(i)
  1222. return height
  1223. def getWidth(self):
  1224. width = self.verticalHeader().width()
  1225. for i in range(self.columnCount()):
  1226. width += self.columnWidth(i)
  1227. return width
  1228. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpfa
  1229. def setColortoRow(self, rowIndex, color):
  1230. for j in range(self.columnCount()):
  1231. self.item(rowIndex, j).setBackground(color)
  1232. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1233. def mousePressEvent(self, event):
  1234. if self.itemAt(event.pos()) is None:
  1235. self.clearSelection()
  1236. else:
  1237. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1238. def setupContextMenu(self):
  1239. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1240. def addContextMenu(self, entry, call_function, icon=None):
  1241. action_name = str(entry)
  1242. action = QtWidgets.QAction(self)
  1243. action.setText(action_name)
  1244. if icon:
  1245. assert isinstance(icon, QtGui.QIcon), \
  1246. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1247. action.setIcon(icon)
  1248. self.addAction(action)
  1249. action.triggered.connect(call_function)
  1250. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  1251. def __init__(self, units):
  1252. super(SpinBoxDelegate, self).__init__()
  1253. self.units = units
  1254. self.current_value = None
  1255. def createEditor(self, parent, option, index):
  1256. editor = QtWidgets.QDoubleSpinBox(parent)
  1257. editor.setMinimum(-999.9999)
  1258. editor.setMaximum(999.9999)
  1259. if self.units == 'MM':
  1260. editor.setDecimals(2)
  1261. else:
  1262. editor.setDecimals(3)
  1263. return editor
  1264. def setEditorData(self, spinBox, index):
  1265. try:
  1266. value = float(index.model().data(index, Qt.EditRole))
  1267. except ValueError:
  1268. value = self.current_value
  1269. # return
  1270. spinBox.setValue(value)
  1271. def setModelData(self, spinBox, model, index):
  1272. spinBox.interpretText()
  1273. value = spinBox.value()
  1274. self.current_value = value
  1275. model.setData(index, value, Qt.EditRole)
  1276. def updateEditorGeometry(self, editor, option, index):
  1277. editor.setGeometry(option.rect)
  1278. def setDecimals(self, spinbox, digits):
  1279. spinbox.setDecimals(digits)
  1280. class FCSpinner(QtWidgets.QSpinBox):
  1281. def __init__(self, parent=None):
  1282. super(FCSpinner, self).__init__(parent)
  1283. self.readyToEdit = True
  1284. self.editingFinished.connect(self.on_edit_finished)
  1285. def on_edit_finished(self):
  1286. self.clearFocus()
  1287. def mousePressEvent(self, e, parent=None):
  1288. super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  1289. if self.readyToEdit:
  1290. self.lineEdit().selectAll()
  1291. self.readyToEdit = False
  1292. def focusOutEvent(self, e):
  1293. # don't focus out if the user requests an popup menu
  1294. if e.reason() != QtCore.Qt.PopupFocusReason:
  1295. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  1296. self.lineEdit().deselect()
  1297. self.readyToEdit = True
  1298. def get_value(self):
  1299. return str(self.value())
  1300. def set_value(self, val):
  1301. try:
  1302. k = int(val)
  1303. except Exception as e:
  1304. log.debug(str(e))
  1305. return
  1306. self.setValue(k)
  1307. def set_range(self, min_val, max_val):
  1308. self.setRange(min_val, max_val)
  1309. # def sizeHint(self):
  1310. # default_hint_size = super(FCSpinner, self).sizeHint()
  1311. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1312. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  1313. def __init__(self, parent=None):
  1314. super(FCDoubleSpinner, self).__init__(parent)
  1315. self.readyToEdit = True
  1316. self.editingFinished.connect(self.on_edit_finished)
  1317. def on_edit_finished(self):
  1318. self.clearFocus()
  1319. def mousePressEvent(self, e, parent=None):
  1320. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  1321. if self.readyToEdit:
  1322. self.lineEdit().selectAll()
  1323. self.readyToEdit = False
  1324. def focusOutEvent(self, e):
  1325. # don't focus out if the user requests an popup menu
  1326. if e.reason() != QtCore.Qt.PopupFocusReason:
  1327. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  1328. self.lineEdit().deselect()
  1329. self.readyToEdit = True
  1330. def get_value(self):
  1331. return str(self.value())
  1332. def set_value(self, val):
  1333. try:
  1334. k = float(val)
  1335. except Exception as e:
  1336. log.debug(str(e))
  1337. return
  1338. self.setValue(k)
  1339. def set_precision(self, val):
  1340. self.setDecimals(val)
  1341. def set_range(self, min_val, max_val):
  1342. self.setRange(min_val, max_val)
  1343. class Dialog_box(QtWidgets.QWidget):
  1344. def __init__(self, title=None, label=None, icon=None):
  1345. """
  1346. :param title: string with the window title
  1347. :param label: string with the message inside the dialog box
  1348. """
  1349. super(Dialog_box, self).__init__()
  1350. self.location = (0, 0)
  1351. self.ok = False
  1352. dialog_box = QtWidgets.QInputDialog()
  1353. dialog_box.setMinimumWidth(290)
  1354. self.setWindowIcon(icon)
  1355. self.location, self.ok = dialog_box.getText(self, title, label, text="0, 0")
  1356. self.readyToEdit = True
  1357. def mousePressEvent(self, e, parent=None):
  1358. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  1359. if self.readyToEdit:
  1360. self.lineEdit().selectAll()
  1361. self.readyToEdit = False
  1362. def focusOutEvent(self, e):
  1363. # don't focus out if the user requests an popup menu
  1364. if e.reason() != QtCore.Qt.PopupFocusReason:
  1365. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  1366. self.lineEdit().deselect()
  1367. self.readyToEdit = True
  1368. class _BrowserTextEdit(QTextEdit):
  1369. def __init__(self, version):
  1370. QTextEdit.__init__(self)
  1371. self.menu = None
  1372. self.version = version
  1373. def contextMenuEvent(self, event):
  1374. self.menu = self.createStandardContextMenu(event.pos())
  1375. clear_action = QAction("Clear", self)
  1376. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  1377. self.menu.addAction(clear_action)
  1378. clear_action.triggered.connect(self.clear)
  1379. self.menu.exec_(event.globalPos())
  1380. def clear(self):
  1381. QTextEdit.clear(self)
  1382. text = "FlatCAM %s (c)2014-2019 Juan Pablo Caram (Type help to get started)\n\n" % self.version
  1383. text = html.escape(text)
  1384. text = text.replace('\n', '<br/>')
  1385. self.moveCursor(QTextCursor.End)
  1386. self.insertHtml(text)
  1387. class _ExpandableTextEdit(QTextEdit):
  1388. """
  1389. Class implements edit line, which expands themselves automatically
  1390. """
  1391. historyNext = pyqtSignal()
  1392. historyPrev = pyqtSignal()
  1393. def __init__(self, termwidget, *args):
  1394. QTextEdit.__init__(self, *args)
  1395. self.setStyleSheet("font: 9pt \"Courier\";")
  1396. self._fittedHeight = 1
  1397. self.textChanged.connect(self._fit_to_document)
  1398. self._fit_to_document()
  1399. self._termWidget = termwidget
  1400. self.completer = MyCompleter()
  1401. self.model = QtCore.QStringListModel()
  1402. self.completer.setModel(self.model)
  1403. self.set_model_data(keyword_list=[])
  1404. self.completer.insertText.connect(self.insertCompletion)
  1405. def set_model_data(self, keyword_list):
  1406. self.model.setStringList(keyword_list)
  1407. def insertCompletion(self, completion):
  1408. tc = self.textCursor()
  1409. extra = (len(completion) - len(self.completer.completionPrefix()))
  1410. # don't insert if the word is finished but add a space instead
  1411. if extra == 0:
  1412. tc.insertText(' ')
  1413. self.completer.popup().hide()
  1414. return
  1415. tc.movePosition(QTextCursor.Left)
  1416. tc.movePosition(QTextCursor.EndOfWord)
  1417. tc.insertText(completion[-extra:])
  1418. # add a space after inserting the word
  1419. tc.insertText(' ')
  1420. self.setTextCursor(tc)
  1421. self.completer.popup().hide()
  1422. def focusInEvent(self, event):
  1423. if self.completer:
  1424. self.completer.setWidget(self)
  1425. QTextEdit.focusInEvent(self, event)
  1426. def keyPressEvent(self, event):
  1427. """
  1428. Catch keyboard events. Process Enter, Up, Down
  1429. """
  1430. key = event.key()
  1431. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  1432. self.completer.insertText.emit(self.completer.getSelected())
  1433. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1434. return
  1435. if event.matches(QKeySequence.InsertParagraphSeparator):
  1436. text = self.toPlainText()
  1437. if self._termWidget.is_command_complete(text):
  1438. self._termWidget.exec_current_command()
  1439. return
  1440. elif event.matches(QKeySequence.MoveToNextLine):
  1441. text = self.toPlainText()
  1442. cursor_pos = self.textCursor().position()
  1443. textBeforeEnd = text[cursor_pos:]
  1444. if len(textBeforeEnd.split('\n')) <= 1:
  1445. self.historyNext.emit()
  1446. return
  1447. elif event.matches(QKeySequence.MoveToPreviousLine):
  1448. text = self.toPlainText()
  1449. cursor_pos = self.textCursor().position()
  1450. text_before_start = text[:cursor_pos]
  1451. # lineCount = len(textBeforeStart.splitlines())
  1452. line_count = len(text_before_start.split('\n'))
  1453. if len(text_before_start) > 0 and \
  1454. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1455. line_count += 1
  1456. if line_count <= 1:
  1457. self.historyPrev.emit()
  1458. return
  1459. elif event.matches(QKeySequence.MoveToNextPage) or \
  1460. event.matches(QKeySequence.MoveToPreviousPage):
  1461. return self._termWidget.browser().keyPressEvent(event)
  1462. tc = self.textCursor()
  1463. QTextEdit.keyPressEvent(self, event)
  1464. tc.select(QTextCursor.WordUnderCursor)
  1465. cr = self.cursorRect()
  1466. if len(tc.selectedText()) > 0:
  1467. self.completer.setCompletionPrefix(tc.selectedText())
  1468. popup = self.completer.popup()
  1469. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1470. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1471. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1472. self.completer.complete(cr)
  1473. else:
  1474. self.completer.popup().hide()
  1475. def sizeHint(self):
  1476. """
  1477. QWidget sizeHint impelemtation
  1478. """
  1479. hint = QTextEdit.sizeHint(self)
  1480. hint.setHeight(self._fittedHeight)
  1481. return hint
  1482. def _fit_to_document(self):
  1483. """
  1484. Update widget height to fit all text
  1485. """
  1486. documentsize = self.document().size().toSize()
  1487. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1488. self.setMaximumHeight(self._fittedHeight)
  1489. self.updateGeometry()
  1490. def insertFromMimeData(self, mime_data):
  1491. # Paste only plain text.
  1492. self.insertPlainText(mime_data.text())
  1493. class MyCompleter(QCompleter):
  1494. insertText = pyqtSignal(str)
  1495. def __init__(self, parent=None):
  1496. QCompleter.__init__(self)
  1497. self.setCompletionMode(QCompleter.PopupCompletion)
  1498. self.highlighted.connect(self.setHighlighted)
  1499. # self.popup().installEventFilter(self)
  1500. # def eventFilter(self, obj, event):
  1501. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  1502. # pass
  1503. # return False
  1504. def setHighlighted(self, text):
  1505. self.lastSelected = text
  1506. def getSelected(self):
  1507. return self.lastSelected