GUIElements.py 47 KB

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