GUIElements.py 48 KB

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