GUIElements.py 52 KB

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