ToolShell.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import html
  9. from PyQt5.QtCore import pyqtSignal
  10. from PyQt5.QtCore import Qt, QStringListModel
  11. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  12. from PyQt5.QtWidgets import QLineEdit, QSizePolicy, QTextEdit, QVBoxLayout, QWidget, QCompleter, QAction
  13. class _BrowserTextEdit(QTextEdit):
  14. def __init__(self):
  15. QTextEdit.__init__(self)
  16. self.menu = None
  17. def contextMenuEvent(self, event):
  18. self.menu = self.createStandardContextMenu(event.pos())
  19. clear_action = QAction("Clear", self)
  20. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  21. self.menu.addAction(clear_action)
  22. clear_action.triggered.connect(self.clear)
  23. self.menu.exec_(event.globalPos())
  24. def clear(self):
  25. QTextEdit.clear(self)
  26. text = "FlatCAM 3000\n(c) 2014-2019 Juan Pablo Caram\n\nType help to get started.\n\n"
  27. text = html.escape(text)
  28. text = text.replace('\n', '<br/>')
  29. self.moveCursor(QTextCursor.End)
  30. self.insertHtml(text)
  31. class _ExpandableTextEdit(QTextEdit):
  32. """
  33. Class implements edit line, which expands themselves automatically
  34. """
  35. historyNext = pyqtSignal()
  36. historyPrev = pyqtSignal()
  37. def __init__(self, termwidget, *args):
  38. QTextEdit.__init__(self, *args)
  39. self.setStyleSheet("font: 9pt \"Courier\";")
  40. self._fittedHeight = 1
  41. self.textChanged.connect(self._fit_to_document)
  42. self._fit_to_document()
  43. self._termWidget = termwidget
  44. self.completer = MyCompleter()
  45. self.model = QStringListModel()
  46. self.completer.setModel(self.model)
  47. self.set_model_data(keyword_list=[])
  48. self.completer.insertText.connect(self.insertCompletion)
  49. def set_model_data(self, keyword_list):
  50. self.model.setStringList(keyword_list)
  51. def insertCompletion(self, completion):
  52. tc = self.textCursor()
  53. extra = (len(completion) - len(self.completer.completionPrefix()))
  54. tc.movePosition(QTextCursor.Left)
  55. tc.movePosition(QTextCursor.EndOfWord)
  56. tc.insertText(completion[-extra:])
  57. self.setTextCursor(tc)
  58. self.completer.popup().hide()
  59. def focusInEvent(self, event):
  60. if self.completer:
  61. self.completer.setWidget(self)
  62. QTextEdit.focusInEvent(self, event)
  63. def keyPressEvent(self, event):
  64. """
  65. Catch keyboard events. Process Enter, Up, Down
  66. """
  67. if event.matches(QKeySequence.InsertParagraphSeparator):
  68. text = self.toPlainText()
  69. if self._termWidget.is_command_complete(text):
  70. self._termWidget.exec_current_command()
  71. return
  72. elif event.matches(QKeySequence.MoveToNextLine):
  73. text = self.toPlainText()
  74. cursor_pos = self.textCursor().position()
  75. textBeforeEnd = text[cursor_pos:]
  76. if len(textBeforeEnd.split('\n')) <= 1:
  77. self.historyNext.emit()
  78. return
  79. elif event.matches(QKeySequence.MoveToPreviousLine):
  80. text = self.toPlainText()
  81. cursor_pos = self.textCursor().position()
  82. text_before_start = text[:cursor_pos]
  83. # lineCount = len(textBeforeStart.splitlines())
  84. line_count = len(text_before_start.split('\n'))
  85. if len(text_before_start) > 0 and \
  86. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  87. line_count += 1
  88. if line_count <= 1:
  89. self.historyPrev.emit()
  90. return
  91. elif event.matches(QKeySequence.MoveToNextPage) or \
  92. event.matches(QKeySequence.MoveToPreviousPage):
  93. return self._termWidget.browser().keyPressEvent(event)
  94. tc = self.textCursor()
  95. if event.key() == Qt.Key_Tab and self.completer.popup().isVisible():
  96. self.completer.insertText.emit(self.completer.getSelected())
  97. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  98. return
  99. QTextEdit.keyPressEvent(self, event)
  100. tc.select(QTextCursor.WordUnderCursor)
  101. cr = self.cursorRect()
  102. if len(tc.selectedText()) > 0:
  103. self.completer.setCompletionPrefix(tc.selectedText())
  104. popup = self.completer.popup()
  105. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  106. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  107. + self.completer.popup().verticalScrollBar().sizeHint().width())
  108. self.completer.complete(cr)
  109. else:
  110. self.completer.popup().hide()
  111. def sizeHint(self):
  112. """
  113. QWidget sizeHint impelemtation
  114. """
  115. hint = QTextEdit.sizeHint(self)
  116. hint.setHeight(self._fittedHeight)
  117. return hint
  118. def _fit_to_document(self):
  119. """
  120. Update widget height to fit all text
  121. """
  122. documentsize = self.document().size().toSize()
  123. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  124. self.setMaximumHeight(self._fittedHeight)
  125. self.updateGeometry()
  126. def insertFromMimeData(self, mime_data):
  127. # Paste only plain text.
  128. self.insertPlainText(mime_data.text())
  129. class MyCompleter(QCompleter):
  130. insertText = pyqtSignal(str)
  131. def __init__(self, parent=None):
  132. QCompleter.__init__(self)
  133. self.setCompletionMode(QCompleter.PopupCompletion)
  134. self.highlighted.connect(self.setHighlighted)
  135. def setHighlighted(self, text):
  136. self.lastSelected = text
  137. def getSelected(self):
  138. return self.lastSelected
  139. class TermWidget(QWidget):
  140. """
  141. Widget wich represents terminal. It only displays text and allows to enter text.
  142. All highlevel logic should be implemented by client classes
  143. User pressed Enter. Client class should decide, if command must be executed or user may continue edit it
  144. """
  145. def __init__(self, *args):
  146. QWidget.__init__(self, *args)
  147. self._browser = _BrowserTextEdit()
  148. self._browser.setStyleSheet("font: 9pt \"Courier\";")
  149. self._browser.setReadOnly(True)
  150. self._browser.document().setDefaultStyleSheet(
  151. self._browser.document().defaultStyleSheet() +
  152. "span {white-space:pre;}")
  153. self._edit = _ExpandableTextEdit(self, self)
  154. self._edit.historyNext.connect(self._on_history_next)
  155. self._edit.historyPrev.connect(self._on_history_prev)
  156. self._edit.setFocus()
  157. self.setFocusProxy(self._edit)
  158. layout = QVBoxLayout(self)
  159. layout.setSpacing(0)
  160. layout.setContentsMargins(0, 0, 0, 0)
  161. layout.addWidget(self._browser)
  162. layout.addWidget(self._edit)
  163. self._history = [''] # current empty line
  164. self._historyIndex = 0
  165. def open_proccessing(self, detail=None):
  166. """
  167. Open processing and disable using shell commands again until all commands are finished
  168. :param detail: text detail about what is currently called from TCL to python
  169. :return: None
  170. """
  171. self._edit.setTextColor(Qt.white)
  172. self._edit.setTextBackgroundColor(Qt.darkGreen)
  173. if detail is None:
  174. self._edit.setPlainText("...proccessing...")
  175. else:
  176. self._edit.setPlainText("...proccessing... [%s]" % detail)
  177. self._edit.setDisabled(True)
  178. self._edit.setFocus()
  179. def close_proccessing(self):
  180. """
  181. Close processing and enable using shell commands again
  182. :return:
  183. """
  184. self._edit.setTextColor(Qt.black)
  185. self._edit.setTextBackgroundColor(Qt.white)
  186. self._edit.setPlainText('')
  187. self._edit.setDisabled(False)
  188. self._edit.setFocus()
  189. def _append_to_browser(self, style, text):
  190. """
  191. Convert text to HTML for inserting it to browser
  192. """
  193. assert style in ('in', 'out', 'err')
  194. text = html.escape(text)
  195. text = text.replace('\n', '<br/>')
  196. if style == 'in':
  197. text = '<span style="font-weight: bold;">%s</span>' % text
  198. elif style == 'err':
  199. text = '<span style="font-weight: bold; color: red;">%s</span>' % text
  200. else:
  201. text = '<span>%s</span>' % text # without span <br/> is ignored!!!
  202. scrollbar = self._browser.verticalScrollBar()
  203. old_value = scrollbar.value()
  204. scrollattheend = old_value == scrollbar.maximum()
  205. self._browser.moveCursor(QTextCursor.End)
  206. self._browser.insertHtml(text)
  207. """TODO When user enters second line to the input, and input is resized, scrollbar changes its positon
  208. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  209. To fix it correctly, srcoll to the bottom, if before intput has been resized,
  210. scrollbar was in the bottom, and remove next lien
  211. """
  212. scrollattheend = True
  213. if scrollattheend:
  214. scrollbar.setValue(scrollbar.maximum())
  215. else:
  216. scrollbar.setValue(old_value)
  217. def exec_current_command(self):
  218. """
  219. Save current command in the history. Append it to the log. Clear edit line
  220. Reimplement in the child classes to actually execute command
  221. """
  222. text = str(self._edit.toPlainText())
  223. self._append_to_browser('in', '> ' + text + '\n')
  224. if len(self._history) < 2 or\
  225. self._history[-2] != text: # don't insert duplicating items
  226. if text[-1] == '\n':
  227. self._history.insert(-1, text[:-1])
  228. else:
  229. self._history.insert(-1, text)
  230. self._historyIndex = len(self._history) - 1
  231. self._history[-1] = ''
  232. self._edit.clear()
  233. if not text[-1] == '\n':
  234. text += '\n'
  235. self.child_exec_command(text)
  236. def child_exec_command(self, text):
  237. """
  238. Reimplement in the child classes
  239. """
  240. pass
  241. def add_line_break_to_input(self):
  242. self._edit.textCursor().insertText('\n')
  243. def append_output(self, text):
  244. """Appent text to output widget
  245. """
  246. self._append_to_browser('out', text)
  247. def append_error(self, text):
  248. """Appent error text to output widget. Text is drawn with red background
  249. """
  250. self._append_to_browser('err', text)
  251. def is_command_complete(self, text):
  252. """
  253. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  254. """
  255. return True
  256. def browser(self):
  257. return self._browser
  258. def _on_history_next(self):
  259. """
  260. Down pressed, show next item from the history
  261. """
  262. if (self._historyIndex + 1) < len(self._history):
  263. self._historyIndex += 1
  264. self._edit.setPlainText(self._history[self._historyIndex])
  265. self._edit.moveCursor(QTextCursor.End)
  266. def _on_history_prev(self):
  267. """
  268. Up pressed, show previous item from the history
  269. """
  270. if self._historyIndex > 0:
  271. if self._historyIndex == (len(self._history) - 1):
  272. self._history[-1] = self._edit.toPlainText()
  273. self._historyIndex -= 1
  274. self._edit.setPlainText(self._history[self._historyIndex])
  275. self._edit.moveCursor(QTextCursor.End)
  276. class FCShell(TermWidget):
  277. def __init__(self, sysShell, *args):
  278. TermWidget.__init__(self, *args)
  279. self._sysShell = sysShell
  280. def is_command_complete(self, text):
  281. def skipQuotes(text):
  282. quote = text[0]
  283. text = text[1:]
  284. endIndex = str(text).index(quote)
  285. return text[endIndex:]
  286. while text:
  287. if text[0] in ('"', "'"):
  288. try:
  289. text = skipQuotes(text)
  290. except ValueError:
  291. return False
  292. text = text[1:]
  293. return True
  294. def child_exec_command(self, text):
  295. self._sysShell.exec_command(text)