GUIElements.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot
  3. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  4. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  5. from copy import copy
  6. import re
  7. import logging
  8. import html
  9. log = logging.getLogger('base')
  10. EDIT_SIZE_HINT = 70
  11. class RadioSet(QtWidgets.QWidget):
  12. activated_custom = QtCore.pyqtSignal()
  13. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  14. """
  15. The choices are specified as a list of dictionaries containing:
  16. * 'label': Shown in the UI
  17. * 'value': The value returned is selected
  18. :param choices: List of choices. See description.
  19. :param orientation: 'horizontal' (default) of 'vertical'.
  20. :param parent: Qt parent widget.
  21. :type choices: list
  22. """
  23. super(RadioSet, self).__init__(parent)
  24. self.choices = copy(choices)
  25. if orientation == 'horizontal':
  26. layout = QtWidgets.QHBoxLayout()
  27. else:
  28. layout = QtWidgets.QVBoxLayout()
  29. group = QtWidgets.QButtonGroup(self)
  30. for choice in self.choices:
  31. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  32. group.addButton(choice['radio'])
  33. layout.addWidget(choice['radio'], stretch=0)
  34. choice['radio'].toggled.connect(self.on_toggle)
  35. layout.setContentsMargins(0, 0, 0, 0)
  36. if stretch is False:
  37. pass
  38. else:
  39. layout.addStretch()
  40. self.setLayout(layout)
  41. self.group_toggle_fn = lambda: None
  42. def on_toggle(self):
  43. # log.debug("Radio toggled")
  44. radio = self.sender()
  45. if radio.isChecked():
  46. self.group_toggle_fn()
  47. self.activated_custom.emit()
  48. return
  49. def get_value(self):
  50. for choice in self.choices:
  51. if choice['radio'].isChecked():
  52. return choice['value']
  53. log.error("No button was toggled in RadioSet.")
  54. return None
  55. def set_value(self, val):
  56. for choice in self.choices:
  57. if choice['value'] == val:
  58. choice['radio'].setChecked(True)
  59. return
  60. log.error("Value given is not part of this RadioSet: %s" % str(val))
  61. # class RadioGroupChoice(QtWidgets.QWidget):
  62. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  63. # """
  64. # The choices are specified as a list of dictionaries containing:
  65. #
  66. # * 'label': Shown in the UI
  67. # * 'value': The value returned is selected
  68. #
  69. # :param choices: List of choices. See description.
  70. # :param orientation: 'horizontal' (default) of 'vertical'.
  71. # :param parent: Qt parent widget.
  72. # :type choices: list
  73. # """
  74. # super().__init__(parent)
  75. #
  76. # group = QtGui.QButtonGroup(self)
  77. #
  78. # self.lbl1 = label_1
  79. # self.lbl2 = label_2
  80. # self.hide_list = hide_list
  81. # self.show_list = show_list
  82. #
  83. # self.btn1 = QtGui.QRadioButton(str(label_1))
  84. # self.btn2 = QtGui.QRadioButton(str(label_2))
  85. # group.addButton(self.btn1)
  86. # group.addButton(self.btn2)
  87. #
  88. # if to_check == 1:
  89. # self.btn1.setChecked(True)
  90. # else:
  91. # self.btn2.setChecked(True)
  92. #
  93. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  94. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  95. #
  96. # def btn_state(self, btn):
  97. # if btn.text() == self.lbl1:
  98. # if btn.isChecked() is True:
  99. # self.show_widgets(self.show_list)
  100. # self.hide_widgets(self.hide_list)
  101. # else:
  102. # self.show_widgets(self.hide_list)
  103. # self.hide_widgets(self.show_list)
  104. #
  105. # def hide_widgets(self, lst):
  106. # for wgt in lst:
  107. # wgt.hide()
  108. #
  109. # def show_widgets(self, lst):
  110. # for wgt in lst:
  111. # wgt.show()
  112. class LengthEntry(QtWidgets.QLineEdit):
  113. def __init__(self, output_units='IN', parent=None):
  114. super(LengthEntry, self).__init__(parent)
  115. self.output_units = output_units
  116. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  117. # Unit conversion table OUTPUT-INPUT
  118. self.scales = {
  119. 'IN': {'IN': 1.0,
  120. 'MM': 1/25.4},
  121. 'MM': {'IN': 25.4,
  122. 'MM': 1.0}
  123. }
  124. self.readyToEdit = True
  125. def mousePressEvent(self, e, Parent=None):
  126. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  127. if self.readyToEdit:
  128. self.selectAll()
  129. self.readyToEdit = False
  130. def focusOutEvent(self, e):
  131. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  132. self.deselect()
  133. self.readyToEdit = True
  134. def returnPressed(self, *args, **kwargs):
  135. val = self.get_value()
  136. if val is not None:
  137. self.set_text(str(val))
  138. else:
  139. log.warning("Could not interpret entry: %s" % self.get_text())
  140. def get_value(self):
  141. raw = str(self.text()).strip(' ')
  142. # match = self.format_re.search(raw)
  143. try:
  144. units = raw[-2:]
  145. units = self.scales[self.output_units][units.upper()]
  146. value = raw[:-2]
  147. return float(eval(value))*units
  148. except IndexError:
  149. value = raw
  150. return float(eval(value))
  151. except KeyError:
  152. value = raw
  153. return float(eval(value))
  154. except:
  155. log.warning("Could not parse value in entry: %s" % str(raw))
  156. return None
  157. def set_value(self, val):
  158. self.setText(str('%.4f' % val))
  159. def sizeHint(self):
  160. default_hint_size = super(LengthEntry, self).sizeHint()
  161. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  162. class FloatEntry(QtWidgets.QLineEdit):
  163. def __init__(self, parent=None):
  164. super(FloatEntry, self).__init__(parent)
  165. self.readyToEdit = True
  166. def mousePressEvent(self, e, Parent=None):
  167. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  168. if self.readyToEdit:
  169. self.selectAll()
  170. self.readyToEdit = False
  171. def focusOutEvent(self, e):
  172. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  173. self.deselect()
  174. self.readyToEdit = True
  175. def returnPressed(self, *args, **kwargs):
  176. val = self.get_value()
  177. if val is not None:
  178. self.set_text(str(val))
  179. else:
  180. log.warning("Could not interpret entry: %s" % self.text())
  181. def get_value(self):
  182. raw = str(self.text()).strip(' ')
  183. evaled = 0.0
  184. try:
  185. evaled = eval(raw)
  186. except:
  187. if evaled is not None:
  188. log.error("Could not evaluate: %s" % str(raw))
  189. return None
  190. return float(evaled)
  191. def set_value(self, val):
  192. if val is not None:
  193. self.setText("%.6f" % val)
  194. else:
  195. self.setText("")
  196. def sizeHint(self):
  197. default_hint_size = super(FloatEntry, self).sizeHint()
  198. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  199. class FloatEntry2(QtWidgets.QLineEdit):
  200. def __init__(self, parent=None):
  201. super(FloatEntry2, self).__init__(parent)
  202. self.readyToEdit = True
  203. def mousePressEvent(self, e, Parent=None):
  204. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  205. if self.readyToEdit:
  206. self.selectAll()
  207. self.readyToEdit = False
  208. def focusOutEvent(self, e):
  209. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  210. self.deselect()
  211. self.readyToEdit = True
  212. def get_value(self):
  213. raw = str(self.text()).strip(' ')
  214. evaled = 0.0
  215. try:
  216. evaled = eval(raw)
  217. except:
  218. if evaled is not None:
  219. log.error("Could not evaluate: %s" % str(raw))
  220. return None
  221. return float(evaled)
  222. def set_value(self, val):
  223. self.setText("%.6f" % val)
  224. def sizeHint(self):
  225. default_hint_size = super(FloatEntry2, self).sizeHint()
  226. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  227. class IntEntry(QtWidgets.QLineEdit):
  228. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  229. super(IntEntry, self).__init__(parent)
  230. self.allow_empty = allow_empty
  231. self.empty_val = empty_val
  232. self.readyToEdit = True
  233. def mousePressEvent(self, e, Parent=None):
  234. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  235. if self.readyToEdit:
  236. self.selectAll()
  237. self.readyToEdit = False
  238. def focusOutEvent(self, e):
  239. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  240. self.deselect()
  241. self.readyToEdit = True
  242. def get_value(self):
  243. if self.allow_empty:
  244. if str(self.text()) == "":
  245. return self.empty_val
  246. # make the text() first a float and then int because if text is a float type,
  247. # the int() can't convert directly a "text float" into a int type.
  248. ret_val = float(self.text())
  249. ret_val = int(ret_val)
  250. return ret_val
  251. def set_value(self, val):
  252. if val == self.empty_val and self.allow_empty:
  253. self.setText("")
  254. return
  255. self.setText(str(val))
  256. def sizeHint(self):
  257. default_hint_size = super(IntEntry, self).sizeHint()
  258. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  259. class FCEntry(QtWidgets.QLineEdit):
  260. def __init__(self, parent=None):
  261. super(FCEntry, self).__init__(parent)
  262. self.readyToEdit = True
  263. def mousePressEvent(self, e, Parent=None):
  264. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  265. if self.readyToEdit:
  266. self.selectAll()
  267. self.readyToEdit = False
  268. def focusOutEvent(self, e):
  269. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  270. self.deselect()
  271. self.readyToEdit = True
  272. def get_value(self):
  273. return str(self.text())
  274. def set_value(self, val):
  275. self.setText(str(val))
  276. def sizeHint(self):
  277. default_hint_size = super(FCEntry, self).sizeHint()
  278. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  279. class FCEntry2(FCEntry):
  280. def __init__(self, parent=None):
  281. super(FCEntry2, self).__init__(parent)
  282. self.readyToEdit = True
  283. def set_value(self, val):
  284. self.setText('%.4f' % float(val))
  285. class EvalEntry(QtWidgets.QLineEdit):
  286. def __init__(self, parent=None):
  287. super(EvalEntry, self).__init__(parent)
  288. self.readyToEdit = True
  289. def mousePressEvent(self, e, Parent=None):
  290. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  291. if self.readyToEdit:
  292. self.selectAll()
  293. self.readyToEdit = False
  294. def focusOutEvent(self, e):
  295. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  296. self.deselect()
  297. self.readyToEdit = True
  298. def returnPressed(self, *args, **kwargs):
  299. val = self.get_value()
  300. if val is not None:
  301. self.setText(str(val))
  302. else:
  303. log.warning("Could not interpret entry: %s" % self.get_text())
  304. def get_value(self):
  305. raw = str(self.text()).strip(' ')
  306. evaled = 0.0
  307. try:
  308. evaled = eval(raw)
  309. except:
  310. if evaled is not None:
  311. log.error("Could not evaluate: %s" % str(raw))
  312. return None
  313. return evaled
  314. def set_value(self, val):
  315. self.setText(str(val))
  316. def sizeHint(self):
  317. default_hint_size = super(EvalEntry, self).sizeHint()
  318. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  319. class EvalEntry2(QtWidgets.QLineEdit):
  320. def __init__(self, parent=None):
  321. super(EvalEntry2, self).__init__(parent)
  322. self.readyToEdit = True
  323. def mousePressEvent(self, e, Parent=None):
  324. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  325. if self.readyToEdit:
  326. self.selectAll()
  327. self.readyToEdit = False
  328. def focusOutEvent(self, e):
  329. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  330. self.deselect()
  331. self.readyToEdit = True
  332. def get_value(self):
  333. raw = str(self.text()).strip(' ')
  334. evaled = 0.0
  335. try:
  336. evaled = eval(raw)
  337. except:
  338. if evaled is not None:
  339. log.error("Could not evaluate: %s" % str(raw))
  340. return None
  341. return evaled
  342. def set_value(self, val):
  343. self.setText(str(val))
  344. def sizeHint(self):
  345. default_hint_size = super(EvalEntry2, self).sizeHint()
  346. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  347. class FCCheckBox(QtWidgets.QCheckBox):
  348. def __init__(self, label='', parent=None):
  349. super(FCCheckBox, self).__init__(str(label), parent)
  350. def get_value(self):
  351. return self.isChecked()
  352. def set_value(self, val):
  353. self.setChecked(val)
  354. def toggle(self):
  355. self.set_value(not self.get_value())
  356. class FCTextArea(QtWidgets.QPlainTextEdit):
  357. def __init__(self, parent=None):
  358. super(FCTextArea, self).__init__(parent)
  359. def set_value(self, val):
  360. self.setPlainText(val)
  361. def get_value(self):
  362. return str(self.toPlainText())
  363. def sizeHint(self):
  364. default_hint_size = super(FCTextArea, self).sizeHint()
  365. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  366. class FCTextAreaRich(QtWidgets.QTextEdit):
  367. def __init__(self, parent=None):
  368. super(FCTextAreaRich, self).__init__(parent)
  369. def set_value(self, val):
  370. self.setText(val)
  371. def get_value(self):
  372. return str(self.toPlainText())
  373. def sizeHint(self):
  374. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  375. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  376. class FCComboBox(QtWidgets.QComboBox):
  377. def __init__(self, parent=None):
  378. super(FCComboBox, self).__init__(parent)
  379. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  380. def wheelEvent(self, *args, **kwargs):
  381. pass
  382. def get_value(self):
  383. return str(self.currentText())
  384. def set_value(self, val):
  385. self.setCurrentIndex(self.findText(str(val)))
  386. class FCInputDialog(QtWidgets.QInputDialog):
  387. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None):
  388. super(FCInputDialog, self).__init__(parent)
  389. self.allow_empty = ok
  390. self.empty_val = val
  391. self.val = 0.0
  392. self.ok = ''
  393. if title is None:
  394. self.title = 'title'
  395. else:
  396. self.title = title
  397. if text is None:
  398. self.text = 'text'
  399. else:
  400. self.text = text
  401. if min is None:
  402. self.min = 0
  403. else:
  404. self.min = min
  405. if max is None:
  406. self.max = 0
  407. else:
  408. self.max = max
  409. if decimals is None:
  410. self.decimals = 6
  411. else:
  412. self.decimals = decimals
  413. def get_value(self):
  414. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  415. max=self.max, decimals=self.decimals)
  416. return [self.val, self.ok]
  417. # "Transform", "Enter the Angle value:"
  418. def set_value(self, val):
  419. pass
  420. class FCButton(QtWidgets.QPushButton):
  421. def __init__(self, parent=None):
  422. super(FCButton, self).__init__(parent)
  423. def get_value(self):
  424. return self.isChecked()
  425. def set_value(self, val):
  426. self.setText(str(val))
  427. class FCTab(QtWidgets.QTabWidget):
  428. def __init__(self, parent=None):
  429. super(FCTab, self).__init__(parent)
  430. self.setTabsClosable(True)
  431. self.tabCloseRequested.connect(self.closeTab)
  432. def deleteTab(self, currentIndex):
  433. widget = self.widget(currentIndex)
  434. if widget is not None:
  435. widget.deleteLater()
  436. self.removeTab(currentIndex)
  437. def closeTab(self, currentIndex):
  438. self.removeTab(currentIndex)
  439. def protectTab(self, currentIndex):
  440. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  441. class FCDetachableTab(QtWidgets.QTabWidget):
  442. # From here: https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  443. def __init__(self, protect=None, protect_by_name=None, parent=None):
  444. super().__init__()
  445. self.tabBar = self.FCTabBar(self)
  446. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  447. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  448. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  449. self.setTabBar(self.tabBar)
  450. # Used to keep a reference to detached tabs since their QMainWindow
  451. # does not have a parent
  452. self.detachedTabs = {}
  453. # a way to make sure that tabs can't be closed after they attach to the parent tab
  454. self.protect_tab = True if protect is not None and protect is True else False
  455. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  456. # Close all detached tabs if the application is closed explicitly
  457. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  458. # used by the property self.useOldIndex(param)
  459. self.use_old_index = None
  460. self.old_index = None
  461. self.setTabsClosable(True)
  462. self.tabCloseRequested.connect(self.closeTab)
  463. def useOldIndex(self, param):
  464. if param:
  465. self.use_old_index = True
  466. else:
  467. self.use_old_index = False
  468. def deleteTab(self, currentIndex):
  469. widget = self.widget(currentIndex)
  470. if widget is not None:
  471. widget.deleteLater()
  472. self.removeTab(currentIndex)
  473. def closeTab(self, currentIndex):
  474. self.removeTab(currentIndex)
  475. def protectTab(self, currentIndex):
  476. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  477. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  478. ##
  479. # The default movable functionality of QTabWidget must remain disabled
  480. # so as not to conflict with the added features
  481. def setMovable(self, movable):
  482. pass
  483. ##
  484. # Move a tab from one position (index) to another
  485. #
  486. # @param fromIndex the original index location of the tab
  487. # @param toIndex the new index location of the tab
  488. @pyqtSlot(int, int)
  489. def moveTab(self, fromIndex, toIndex):
  490. widget = self.widget(fromIndex)
  491. icon = self.tabIcon(fromIndex)
  492. text = self.tabText(fromIndex)
  493. self.removeTab(fromIndex)
  494. self.insertTab(toIndex, widget, icon, text)
  495. self.setCurrentIndex(toIndex)
  496. ##
  497. # Detach the tab by removing it's contents and placing them in
  498. # a DetachedTab window
  499. #
  500. # @param index the index location of the tab to be detached
  501. # @param point the screen position for creating the new DetachedTab window
  502. @pyqtSlot(int, QtCore.QPoint)
  503. def detachTab(self, index, point):
  504. self.old_index = index
  505. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  506. name = "FlatCAM " + self.tabText(index)
  507. icon = self.tabIcon(index)
  508. if icon.isNull():
  509. icon = self.window().windowIcon()
  510. contentWidget = self.widget(index)
  511. try:
  512. contentWidgetRect = contentWidget.frameGeometry()
  513. except AttributeError:
  514. return
  515. # Create a new detached tab window
  516. detachedTab = self.FCDetachedTab(name, contentWidget)
  517. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  518. detachedTab.setWindowIcon(icon)
  519. detachedTab.setGeometry(contentWidgetRect)
  520. detachedTab.onCloseSignal.connect(self.attachTab)
  521. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  522. detachedTab.move(point)
  523. detachedTab.show()
  524. # Create a reference to maintain access to the detached tab
  525. self.detachedTabs[name] = detachedTab
  526. ##
  527. # Re-attach the tab by removing the content from the DetachedTab window,
  528. # closing it, and placing the content back into the DetachableTabWidget
  529. #
  530. # @param contentWidget the content widget from the DetachedTab window
  531. # @param name the name of the detached tab
  532. # @param icon the window icon for the detached tab
  533. # @param insertAt insert the re-attached tab at the given index
  534. def attachTab(self, contentWidget, name, icon, insertAt=None):
  535. # Make the content widget a child of this widget
  536. contentWidget.setParent(self)
  537. # Remove the reference
  538. del self.detachedTabs[name]
  539. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  540. name = name.partition(' ')[2]
  541. # helps in restoring the tab to the same index that it was before was detached
  542. insert_index = self.old_index if self.use_old_index is True else insertAt
  543. # Create an image from the given icon (for comparison)
  544. if not icon.isNull():
  545. try:
  546. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  547. tabIconImage = tabIconPixmap.toImage()
  548. except IndexError:
  549. tabIconImage = None
  550. else:
  551. tabIconImage = None
  552. # Create an image of the main window icon (for comparison)
  553. if not icon.isNull():
  554. try:
  555. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  556. windowIconImage = windowIconPixmap.toImage()
  557. except IndexError:
  558. windowIconImage = None
  559. else:
  560. windowIconImage = None
  561. # Determine if the given image and the main window icon are the same.
  562. # If they are, then do not add the icon to the tab
  563. if tabIconImage == windowIconImage:
  564. if insert_index is None:
  565. index = self.addTab(contentWidget, name)
  566. else:
  567. index = self.insertTab(insert_index, contentWidget, name)
  568. else:
  569. if insert_index is None:
  570. index = self.addTab(contentWidget, icon, name)
  571. else:
  572. index = self.insertTab(insert_index, contentWidget, icon, name)
  573. # on reattaching the tab if protect is true then the closure button is not added
  574. if self.protect_tab is True:
  575. self.protectTab(index)
  576. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  577. if self.protect_by_name is not None:
  578. for tab_name in self.protect_by_name:
  579. for index in range(self.count()):
  580. if str(tab_name) == str(self.tabText(index)):
  581. self.protectTab(index)
  582. # Make this tab the current tab
  583. if index > -1:
  584. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  585. ##
  586. # Remove the tab with the given name, even if it is detached
  587. #
  588. # @param name the name of the tab to be removed
  589. def removeTabByName(self, name):
  590. # Remove the tab if it is attached
  591. attached = False
  592. for index in range(self.count()):
  593. if str(name) == str(self.tabText(index)):
  594. self.removeTab(index)
  595. attached = True
  596. break
  597. # If the tab is not attached, close it's window and
  598. # remove the reference to it
  599. if not attached:
  600. for key in self.detachedTabs:
  601. if str(name) == str(key):
  602. self.detachedTabs[key].onCloseSignal.disconnect()
  603. self.detachedTabs[key].close()
  604. del self.detachedTabs[key]
  605. break
  606. ##
  607. # Handle dropping of a detached tab inside the DetachableTabWidget
  608. #
  609. # @param name the name of the detached tab
  610. # @param index the index of an existing tab (if the tab bar
  611. # determined that the drop occurred on an
  612. # existing tab)
  613. # @param dropPos the mouse cursor position when the drop occurred
  614. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  615. def detachedTabDrop(self, name, index, dropPos):
  616. # If the drop occurred on an existing tab, insert the detached
  617. # tab at the existing tab's location
  618. if index > -1:
  619. # Create references to the detached tab's content and icon
  620. contentWidget = self.detachedTabs[name].contentWidget
  621. icon = self.detachedTabs[name].windowIcon()
  622. # Disconnect the detached tab's onCloseSignal so that it
  623. # does not try to re-attach automatically
  624. self.detachedTabs[name].onCloseSignal.disconnect()
  625. # Close the detached
  626. self.detachedTabs[name].close()
  627. # Re-attach the tab at the given index
  628. self.attachTab(contentWidget, name, icon, index)
  629. # If the drop did not occur on an existing tab, determine if the drop
  630. # occurred in the tab bar area (the area to the side of the QTabBar)
  631. else:
  632. # Find the drop position relative to the DetachableTabWidget
  633. tabDropPos = self.mapFromGlobal(dropPos)
  634. # If the drop position is inside the DetachableTabWidget...
  635. if self.rect().contains(tabDropPos):
  636. # If the drop position is inside the tab bar area (the
  637. # area to the side of the QTabBar) or there are not tabs
  638. # currently attached...
  639. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  640. # Close the detached tab and allow it to re-attach
  641. # automatically
  642. self.detachedTabs[name].close()
  643. ##
  644. # Close all tabs that are currently detached.
  645. def closeDetachedTabs(self):
  646. listOfDetachedTabs = []
  647. for key in self.detachedTabs:
  648. listOfDetachedTabs.append(self.detachedTabs[key])
  649. for detachedTab in listOfDetachedTabs:
  650. detachedTab.close()
  651. ##
  652. # When a tab is detached, the contents are placed into this QMainWindow. The tab
  653. # can be re-attached by closing the dialog or by dragging the window into the tab bar
  654. class FCDetachedTab(QtWidgets.QMainWindow):
  655. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  656. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  657. def __init__(self, name, contentWidget):
  658. QtWidgets.QMainWindow.__init__(self, None)
  659. self.setObjectName(name)
  660. self.setWindowTitle(name)
  661. self.contentWidget = contentWidget
  662. self.setCentralWidget(self.contentWidget)
  663. self.contentWidget.show()
  664. self.windowDropFilter = self.WindowDropFilter()
  665. self.installEventFilter(self.windowDropFilter)
  666. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  667. ##
  668. # Handle a window drop event
  669. #
  670. # @param dropPos the mouse cursor position of the drop
  671. @QtCore.pyqtSlot(QtCore.QPoint)
  672. def windowDropSlot(self, dropPos):
  673. self.onDropSignal.emit(self.objectName(), dropPos)
  674. ##
  675. # If the window is closed, emit the onCloseSignal and give the
  676. # content widget back to the DetachableTabWidget
  677. #
  678. # @param event a close event
  679. def closeEvent(self, event):
  680. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  681. ##
  682. # An event filter class to detect a QMainWindow drop event
  683. class WindowDropFilter(QtCore.QObject):
  684. onDropSignal = pyqtSignal(QtCore.QPoint)
  685. def __init__(self):
  686. QtCore.QObject.__init__(self)
  687. self.lastEvent = None
  688. ##
  689. # Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  690. # event that immediately follows a Move event
  691. #
  692. # @param obj the object that generated the event
  693. # @param event the current event
  694. def eventFilter(self, obj, event):
  695. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  696. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  697. # Determine the position of the mouse cursor and emit it with the
  698. # onDropSignal
  699. mouseCursor = QtGui.QCursor()
  700. dropPos = mouseCursor.pos()
  701. self.onDropSignal.emit(dropPos)
  702. self.lastEvent = event.type()
  703. return True
  704. else:
  705. self.lastEvent = event.type()
  706. return False
  707. class FCTabBar(QtWidgets.QTabBar):
  708. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  709. onMoveTabSignal = pyqtSignal(int, int)
  710. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  711. def __init__(self, parent=None):
  712. QtWidgets.QTabBar.__init__(self, parent)
  713. self.setAcceptDrops(True)
  714. self.setElideMode(QtCore.Qt.ElideRight)
  715. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  716. self.dragStartPos = QtCore.QPoint()
  717. self.dragDropedPos = QtCore.QPoint()
  718. self.mouseCursor = QtGui.QCursor()
  719. self.dragInitiated = False
  720. # Send the onDetachTabSignal when a tab is double clicked
  721. #
  722. # @param event a mouse double click event
  723. def mouseDoubleClickEvent(self, event):
  724. event.accept()
  725. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  726. # Set the starting position for a drag event when the mouse button is pressed
  727. #
  728. # @param event a mouse press event
  729. def mousePressEvent(self, event):
  730. if event.button() == QtCore.Qt.LeftButton:
  731. self.dragStartPos = event.pos()
  732. self.dragDropedPos.setX(0)
  733. self.dragDropedPos.setY(0)
  734. self.dragInitiated = False
  735. QtWidgets.QTabBar.mousePressEvent(self, event)
  736. # Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  737. # drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  738. # bar, emit an onDetachTabSignal.
  739. #
  740. # @param event a mouse move event
  741. def mouseMoveEvent(self, event):
  742. # Determine if the current movement is detected as a drag
  743. if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  744. self.dragInitiated = True
  745. # If the current movement is a drag initiated by the left button
  746. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):
  747. # Stop the move event
  748. finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
  749. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  750. # Convert the move event into a drag
  751. drag = QtGui.QDrag(self)
  752. mimeData = QtCore.QMimeData()
  753. # mimeData.setData('action', 'application/tab-detach')
  754. drag.setMimeData(mimeData)
  755. # screen = QScreen(self.parentWidget().currentWidget().winId())
  756. # Create the appearance of dragging the tab content
  757. try:
  758. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  759. except Exception as e:
  760. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  761. return
  762. targetPixmap = QtGui.QPixmap(pixmap.size())
  763. targetPixmap.fill(QtCore.Qt.transparent)
  764. painter = QtGui.QPainter(targetPixmap)
  765. painter.setOpacity(0.85)
  766. painter.drawPixmap(0, 0, pixmap)
  767. painter.end()
  768. drag.setPixmap(targetPixmap)
  769. # Initiate the drag
  770. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  771. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  772. # must be set manually
  773. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  774. dropAction = QtCore.Qt.MoveAction
  775. # If the drag completed outside of the tab bar, detach the tab and move
  776. # the content to the current cursor position
  777. if dropAction == QtCore.Qt.IgnoreAction:
  778. event.accept()
  779. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  780. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  781. elif dropAction == QtCore.Qt.MoveAction:
  782. if not self.dragDropedPos.isNull():
  783. event.accept()
  784. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  785. else:
  786. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  787. # Determine if the drag has entered a tab position from another tab position
  788. #
  789. # @param event a drag enter event
  790. def dragEnterEvent(self, event):
  791. mimeData = event.mimeData()
  792. # formats = mcd imeData.formats()
  793. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  794. # event.acceptProposedAction()
  795. QtWidgets.QTabBar.dragMoveEvent(self, event)
  796. # Get the position of the end of the drag
  797. #
  798. # @param event a drop event
  799. def dropEvent(self, event):
  800. self.dragDropedPos = event.pos()
  801. QtWidgets.QTabBar.dropEvent(self, event)
  802. # Determine if the detached tab drop event occurred on an existing tab,
  803. # then send the event to the DetachableTabWidget
  804. def detachedTabDrop(self, name, dropPos):
  805. tabDropPos = self.mapFromGlobal(dropPos)
  806. index = self.tabAt(tabDropPos)
  807. self.detachedTabDropSignal.emit(name, index, dropPos)
  808. class VerticalScrollArea(QtWidgets.QScrollArea):
  809. """
  810. This widget extends QtGui.QScrollArea to make a vertical-only
  811. scroll area that also expands horizontally to accomodate
  812. its contents.
  813. """
  814. def __init__(self, parent=None):
  815. QtWidgets.QScrollArea.__init__(self, parent=parent)
  816. self.setWidgetResizable(True)
  817. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  818. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  819. def eventFilter(self, source, event):
  820. """
  821. The event filter gets automatically installed when setWidget()
  822. is called.
  823. :param source:
  824. :param event:
  825. :return:
  826. """
  827. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  828. # log.debug("VerticalScrollArea: Widget resized:")
  829. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  830. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  831. self.setMinimumWidth(self.widget().sizeHint().width() +
  832. self.verticalScrollBar().sizeHint().width())
  833. # if self.verticalScrollBar().isVisible():
  834. # log.debug(" Scroll bar visible")
  835. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  836. # self.verticalScrollBar().width())
  837. # else:
  838. # log.debug(" Scroll bar hidden")
  839. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  840. return QtWidgets.QWidget.eventFilter(self, source, event)
  841. class OptionalInputSection:
  842. def __init__(self, cb, optinputs, logic=True):
  843. """
  844. Associates the a checkbox with a set of inputs.
  845. :param cb: Checkbox that enables the optional inputs.
  846. :param optinputs: List of widgets that are optional.
  847. :param logic: When True the logic is normal, when False the logic is in reverse
  848. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  849. for logic=False, when the checkbox is checked the widgets are Disabled
  850. :return:
  851. """
  852. assert isinstance(cb, FCCheckBox), \
  853. "Expected an FCCheckBox, got %s" % type(cb)
  854. self.cb = cb
  855. self.optinputs = optinputs
  856. self.logic = logic
  857. self.on_cb_change()
  858. self.cb.stateChanged.connect(self.on_cb_change)
  859. def on_cb_change(self):
  860. if self.cb.checkState():
  861. for widget in self.optinputs:
  862. if self.logic is True:
  863. widget.setEnabled(True)
  864. else:
  865. widget.setEnabled(False)
  866. else:
  867. for widget in self.optinputs:
  868. if self.logic is True:
  869. widget.setEnabled(False)
  870. else:
  871. widget.setEnabled(True)
  872. class FCTable(QtWidgets.QTableWidget):
  873. def __init__(self, parent=None):
  874. super(FCTable, self).__init__(parent)
  875. def sizeHint(self):
  876. default_hint_size = super(FCTable, self).sizeHint()
  877. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  878. def getHeight(self):
  879. height = self.horizontalHeader().height()
  880. for i in range(self.rowCount()):
  881. height += self.rowHeight(i)
  882. return height
  883. def getWidth(self):
  884. width = self.verticalHeader().width()
  885. for i in range(self.columnCount()):
  886. width += self.columnWidth(i)
  887. return width
  888. # color is in format QtGui.Qcolor(r, g, b, alfa) with or without alfa
  889. def setColortoRow(self, rowIndex, color):
  890. for j in range(self.columnCount()):
  891. self.item(rowIndex, j).setBackground(color)
  892. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  893. def mousePressEvent(self, event):
  894. if self.itemAt(event.pos()) is None:
  895. self.clearSelection()
  896. else:
  897. QtWidgets.QTableWidget.mousePressEvent(self, event)
  898. def setupContextMenu(self):
  899. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  900. def addContextMenu(self, entry, call_function, icon=None):
  901. action_name = str(entry)
  902. action = QtWidgets.QAction(self)
  903. action.setText(action_name)
  904. if icon:
  905. assert isinstance(icon, QtGui.QIcon), \
  906. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  907. action.setIcon(icon)
  908. self.addAction(action)
  909. action.triggered.connect(call_function)
  910. class FCSpinner(QtWidgets.QSpinBox):
  911. def __init__(self, parent=None):
  912. super(FCSpinner, self).__init__(parent)
  913. def get_value(self):
  914. return str(self.value())
  915. def set_value(self, val):
  916. try:
  917. k = int(val)
  918. except Exception as e:
  919. log.debug(str(e))
  920. return
  921. self.setValue(k)
  922. # def sizeHint(self):
  923. # default_hint_size = super(FCSpinner, self).sizeHint()
  924. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  925. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  926. def __init__(self, parent=None):
  927. super(FCDoubleSpinner, self).__init__(parent)
  928. self.readyToEdit = True
  929. def mousePressEvent(self, e, parent=None):
  930. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  931. if self.readyToEdit:
  932. self.lineEdit().selectAll()
  933. self.readyToEdit = False
  934. def focusOutEvent(self, e):
  935. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  936. self.lineEdit().deselect()
  937. self.readyToEdit = True
  938. def get_value(self):
  939. return str(self.value())
  940. def set_value(self, val):
  941. try:
  942. k = int(val)
  943. except Exception as e:
  944. log.debug(str(e))
  945. return
  946. self.setValue(k)
  947. def set_precision(self, val):
  948. self.setDecimals(val)
  949. def set_range(self, min_val, max_val):
  950. self.setRange(self, min_val, max_val)
  951. class Dialog_box(QtWidgets.QWidget):
  952. def __init__(self, title=None, label=None, icon=None):
  953. """
  954. :param title: string with the window title
  955. :param label: string with the message inside the dialog box
  956. """
  957. super(Dialog_box, self).__init__()
  958. self.location = (0, 0)
  959. self.ok = False
  960. dialog_box = QtWidgets.QInputDialog()
  961. dialog_box.setFixedWidth(290)
  962. self.setWindowIcon(icon)
  963. self.location, self.ok = dialog_box.getText(self, title, label)
  964. class _BrowserTextEdit(QTextEdit):
  965. def __init__(self, version):
  966. QTextEdit.__init__(self)
  967. self.menu = None
  968. self.version = version
  969. def contextMenuEvent(self, event):
  970. self.menu = self.createStandardContextMenu(event.pos())
  971. clear_action = QAction("Clear", self)
  972. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  973. self.menu.addAction(clear_action)
  974. clear_action.triggered.connect(self.clear)
  975. self.menu.exec_(event.globalPos())
  976. def clear(self):
  977. QTextEdit.clear(self)
  978. text = "FlatCAM %s (c)2014-2019 Juan Pablo Caram (Type help to get started)\n\n" % self.version
  979. text = html.escape(text)
  980. text = text.replace('\n', '<br/>')
  981. self.moveCursor(QTextCursor.End)
  982. self.insertHtml(text)
  983. class _ExpandableTextEdit(QTextEdit):
  984. """
  985. Class implements edit line, which expands themselves automatically
  986. """
  987. historyNext = pyqtSignal()
  988. historyPrev = pyqtSignal()
  989. def __init__(self, termwidget, *args):
  990. QTextEdit.__init__(self, *args)
  991. self.setStyleSheet("font: 9pt \"Courier\";")
  992. self._fittedHeight = 1
  993. self.textChanged.connect(self._fit_to_document)
  994. self._fit_to_document()
  995. self._termWidget = termwidget
  996. self.completer = MyCompleter()
  997. self.model = QtCore.QStringListModel()
  998. self.completer.setModel(self.model)
  999. self.set_model_data(keyword_list=[])
  1000. self.completer.insertText.connect(self.insertCompletion)
  1001. def set_model_data(self, keyword_list):
  1002. self.model.setStringList(keyword_list)
  1003. def insertCompletion(self, completion):
  1004. tc = self.textCursor()
  1005. extra = (len(completion) - len(self.completer.completionPrefix()))
  1006. tc.movePosition(QTextCursor.Left)
  1007. tc.movePosition(QTextCursor.EndOfWord)
  1008. tc.insertText(completion[-extra:])
  1009. self.setTextCursor(tc)
  1010. self.completer.popup().hide()
  1011. def focusInEvent(self, event):
  1012. if self.completer:
  1013. self.completer.setWidget(self)
  1014. QTextEdit.focusInEvent(self, event)
  1015. def keyPressEvent(self, event):
  1016. """
  1017. Catch keyboard events. Process Enter, Up, Down
  1018. """
  1019. if event.matches(QKeySequence.InsertParagraphSeparator):
  1020. text = self.toPlainText()
  1021. if self._termWidget.is_command_complete(text):
  1022. self._termWidget.exec_current_command()
  1023. return
  1024. elif event.matches(QKeySequence.MoveToNextLine):
  1025. text = self.toPlainText()
  1026. cursor_pos = self.textCursor().position()
  1027. textBeforeEnd = text[cursor_pos:]
  1028. if len(textBeforeEnd.split('\n')) <= 1:
  1029. self.historyNext.emit()
  1030. return
  1031. elif event.matches(QKeySequence.MoveToPreviousLine):
  1032. text = self.toPlainText()
  1033. cursor_pos = self.textCursor().position()
  1034. text_before_start = text[:cursor_pos]
  1035. # lineCount = len(textBeforeStart.splitlines())
  1036. line_count = len(text_before_start.split('\n'))
  1037. if len(text_before_start) > 0 and \
  1038. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1039. line_count += 1
  1040. if line_count <= 1:
  1041. self.historyPrev.emit()
  1042. return
  1043. elif event.matches(QKeySequence.MoveToNextPage) or \
  1044. event.matches(QKeySequence.MoveToPreviousPage):
  1045. return self._termWidget.browser().keyPressEvent(event)
  1046. tc = self.textCursor()
  1047. if event.key() == Qt.Key_Tab and self.completer.popup().isVisible():
  1048. self.completer.insertText.emit(self.completer.getSelected())
  1049. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1050. return
  1051. QTextEdit.keyPressEvent(self, event)
  1052. tc.select(QTextCursor.WordUnderCursor)
  1053. cr = self.cursorRect()
  1054. if len(tc.selectedText()) > 0:
  1055. self.completer.setCompletionPrefix(tc.selectedText())
  1056. popup = self.completer.popup()
  1057. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1058. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1059. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1060. self.completer.complete(cr)
  1061. else:
  1062. self.completer.popup().hide()
  1063. def sizeHint(self):
  1064. """
  1065. QWidget sizeHint impelemtation
  1066. """
  1067. hint = QTextEdit.sizeHint(self)
  1068. hint.setHeight(self._fittedHeight)
  1069. return hint
  1070. def _fit_to_document(self):
  1071. """
  1072. Update widget height to fit all text
  1073. """
  1074. documentsize = self.document().size().toSize()
  1075. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1076. self.setMaximumHeight(self._fittedHeight)
  1077. self.updateGeometry()
  1078. def insertFromMimeData(self, mime_data):
  1079. # Paste only plain text.
  1080. self.insertPlainText(mime_data.text())
  1081. class MyCompleter(QCompleter):
  1082. insertText = pyqtSignal(str)
  1083. def __init__(self, parent=None):
  1084. QCompleter.__init__(self)
  1085. self.setCompletionMode(QCompleter.PopupCompletion)
  1086. self.highlighted.connect(self.setHighlighted)
  1087. def setHighlighted(self, text):
  1088. self.lastSelected = text
  1089. def getSelected(self):
  1090. return self.lastSelected