GUIElements.py 48 KB

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