termwidget.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. """
  2. Terminal emulator widget.
  3. Shows intput and output text. Allows to enter commands. Supports history.
  4. """
  5. import cgi
  6. from PyQt4.QtCore import pyqtSignal, Qt
  7. from PyQt4.QtGui import QColor, QKeySequence, QLineEdit, QPalette, \
  8. QSizePolicy, QTextCursor, QTextEdit, \
  9. QVBoxLayout, QWidget
  10. class _ExpandableTextEdit(QTextEdit):
  11. """
  12. Class implements edit line, which expands themselves automatically
  13. """
  14. historyNext = pyqtSignal()
  15. historyPrev = pyqtSignal()
  16. def __init__(self, termwidget, *args):
  17. QTextEdit.__init__(self, *args)
  18. self.setStyleSheet("font: 9pt \"Courier\";")
  19. self._fittedHeight = 1
  20. self.textChanged.connect(self._fit_to_document)
  21. self._fit_to_document()
  22. self._termWidget = termwidget
  23. def sizeHint(self):
  24. """
  25. QWidget sizeHint impelemtation
  26. """
  27. hint = QTextEdit.sizeHint(self)
  28. hint.setHeight(self._fittedHeight)
  29. return hint
  30. def _fit_to_document(self):
  31. """
  32. Update widget height to fit all text
  33. """
  34. documentsize = self.document().size().toSize()
  35. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  36. self.setMaximumHeight(self._fittedHeight)
  37. self.updateGeometry()
  38. def keyPressEvent(self, event):
  39. """
  40. Catch keyboard events. Process Enter, Up, Down
  41. """
  42. if event.matches(QKeySequence.InsertParagraphSeparator):
  43. text = self.toPlainText()
  44. if self._termWidget.is_command_complete(text):
  45. self._termWidget.exec_current_command()
  46. return
  47. elif event.matches(QKeySequence.MoveToNextLine):
  48. text = self.toPlainText()
  49. cursor_pos = self.textCursor().position()
  50. textBeforeEnd = text[cursor_pos:]
  51. # if len(textBeforeEnd.splitlines()) <= 1:
  52. if len(textBeforeEnd.split('\n')) <= 1:
  53. self.historyNext.emit()
  54. return
  55. elif event.matches(QKeySequence.MoveToPreviousLine):
  56. text = self.toPlainText()
  57. cursor_pos = self.textCursor().position()
  58. text_before_start = text[:cursor_pos]
  59. # lineCount = len(textBeforeStart.splitlines())
  60. line_count = len(text_before_start.split('\n'))
  61. if len(text_before_start) > 0 and \
  62. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  63. line_count += 1
  64. if line_count <= 1:
  65. self.historyPrev.emit()
  66. return
  67. elif event.matches(QKeySequence.MoveToNextPage) or \
  68. event.matches(QKeySequence.MoveToPreviousPage):
  69. return self._termWidget.browser().keyPressEvent(event)
  70. QTextEdit.keyPressEvent(self, event)
  71. def insertFromMimeData(self, mime_data):
  72. # Paste only plain text.
  73. self.insertPlainText(mime_data.text())
  74. class TermWidget(QWidget):
  75. """
  76. Widget wich represents terminal. It only displays text and allows to enter text.
  77. All highlevel logic should be implemented by client classes
  78. User pressed Enter. Client class should decide, if command must be executed or user may continue edit it
  79. """
  80. def __init__(self, *args):
  81. QWidget.__init__(self, *args)
  82. self._browser = QTextEdit(self)
  83. self._browser.setStyleSheet("font: 9pt \"Courier\";")
  84. self._browser.setReadOnly(True)
  85. self._browser.document().setDefaultStyleSheet(
  86. self._browser.document().defaultStyleSheet() +
  87. "span {white-space:pre;}")
  88. self._edit = _ExpandableTextEdit(self, self)
  89. self._edit.historyNext.connect(self._on_history_next)
  90. self._edit.historyPrev.connect(self._on_history_prev)
  91. self.setFocusProxy(self._edit)
  92. layout = QVBoxLayout(self)
  93. layout.setSpacing(0)
  94. layout.setContentsMargins(0, 0, 0, 0)
  95. layout.addWidget(self._browser)
  96. layout.addWidget(self._edit)
  97. self._history = [''] # current empty line
  98. self._historyIndex = 0
  99. self._edit.setFocus()
  100. def open_proccessing(self, detail=None):
  101. """
  102. Open processing and disable using shell commands again until all commands are finished
  103. :param detail: text detail about what is currently called from TCL to python
  104. :return: None
  105. """
  106. self._edit.setTextColor(Qt.white)
  107. self._edit.setTextBackgroundColor(Qt.darkGreen)
  108. if detail is None:
  109. self._edit.setPlainText("...proccessing...")
  110. else:
  111. self._edit.setPlainText("...proccessing... [%s]" % detail)
  112. self._edit.setDisabled(True)
  113. def close_proccessing(self):
  114. """
  115. Close processing and enable using shell commands again
  116. :return:
  117. """
  118. self._edit.setTextColor(Qt.black)
  119. self._edit.setTextBackgroundColor(Qt.white)
  120. self._edit.setPlainText('')
  121. self._edit.setDisabled(False)
  122. self._edit.setFocus()
  123. def _append_to_browser(self, style, text):
  124. """
  125. Convert text to HTML for inserting it to browser
  126. """
  127. assert style in ('in', 'out', 'err')
  128. text = cgi.escape(text)
  129. text = text.replace('\n', '<br/>')
  130. if style == 'in':
  131. text = '<span style="font-weight: bold;">%s</span>' % text
  132. elif style == 'err':
  133. text = '<span style="font-weight: bold; color: red;">%s</span>' % text
  134. else:
  135. text = '<span>%s</span>' % text # without span <br/> is ignored!!!
  136. scrollbar = self._browser.verticalScrollBar()
  137. old_value = scrollbar.value()
  138. scrollattheend = old_value == scrollbar.maximum()
  139. self._browser.moveCursor(QTextCursor.End)
  140. self._browser.insertHtml(text)
  141. """TODO When user enters second line to the input, and input is resized, scrollbar changes its positon
  142. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  143. To fix it correctly, srcoll to the bottom, if before intput has been resized,
  144. scrollbar was in the bottom, and remove next lien
  145. """
  146. scrollattheend = True
  147. if scrollattheend:
  148. scrollbar.setValue(scrollbar.maximum())
  149. else:
  150. scrollbar.setValue(old_value)
  151. def exec_current_command(self):
  152. """
  153. Save current command in the history. Append it to the log. Clear edit line
  154. Reimplement in the child classes to actually execute command
  155. """
  156. text = str(self._edit.toPlainText())
  157. self._append_to_browser('in', '> ' + text + '\n')
  158. if len(self._history) < 2 or\
  159. self._history[-2] != text: # don't insert duplicating items
  160. if text[-1] == '\n':
  161. self._history.insert(-1, text[:-1])
  162. else:
  163. self._history.insert(-1, text)
  164. self._historyIndex = len(self._history) - 1
  165. self._history[-1] = ''
  166. self._edit.clear()
  167. if not text[-1] == '\n':
  168. text += '\n'
  169. self.child_exec_command(text)
  170. def child_exec_command(self, text):
  171. """
  172. Reimplement in the child classes
  173. """
  174. pass
  175. def add_line_break_to_input(self):
  176. self._edit.textCursor().insertText('\n')
  177. def append_output(self, text):
  178. """Appent text to output widget
  179. """
  180. self._append_to_browser('out', text)
  181. def append_error(self, text):
  182. """Appent error text to output widget. Text is drawn with red background
  183. """
  184. self._append_to_browser('err', text)
  185. def is_command_complete(self, text):
  186. """
  187. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  188. """
  189. return True
  190. def browser(self):
  191. return self._browser
  192. def _on_history_next(self):
  193. """
  194. Down pressed, show next item from the history
  195. """
  196. if (self._historyIndex + 1) < len(self._history):
  197. self._historyIndex += 1
  198. self._edit.setPlainText(self._history[self._historyIndex])
  199. self._edit.moveCursor(QTextCursor.End)
  200. def _on_history_prev(self):
  201. """
  202. Up pressed, show previous item from the history
  203. """
  204. if self._historyIndex > 0:
  205. if self._historyIndex == (len(self._history) - 1):
  206. self._history[-1] = self._edit.toPlainText()
  207. self._historyIndex -= 1
  208. self._edit.setPlainText(self._history[self._historyIndex])
  209. self._edit.moveCursor(QTextCursor.End)