GUIElements.py 52 KB

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