GUIElements.py 55 KB

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