GUIElements.py 48 KB

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