GUIElements.py 55 KB

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