GUIElements.py 51 KB

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