GUIElements.py 54 KB

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