termwidget.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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
  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. class TermWidget(QWidget):
  72. """
  73. Widget wich represents terminal. It only displays text and allows to enter text.
  74. All highlevel logic should be implemented by client classes
  75. User pressed Enter. Client class should decide, if command must be executed or user may continue edit it
  76. """
  77. def __init__(self, *args):
  78. QWidget.__init__(self, *args)
  79. self._browser = QTextEdit(self)
  80. self._browser.setStyleSheet("font: 9pt \"Courier\";")
  81. self._browser.setReadOnly(True)
  82. self._browser.document().setDefaultStyleSheet(
  83. self._browser.document().defaultStyleSheet() +
  84. "span {white-space:pre;}")
  85. self._edit = _ExpandableTextEdit(self, self)
  86. self._edit.historyNext.connect(self._on_history_next)
  87. self._edit.historyPrev.connect(self._on_history_prev)
  88. self.setFocusProxy(self._edit)
  89. layout = QVBoxLayout(self)
  90. layout.setSpacing(0)
  91. layout.setContentsMargins(0, 0, 0, 0)
  92. layout.addWidget(self._browser)
  93. layout.addWidget(self._edit)
  94. self._history = [''] # current empty line
  95. self._historyIndex = 0
  96. self._edit.setFocus()
  97. def _append_to_browser(self, style, text):
  98. """
  99. Convert text to HTML for inserting it to browser
  100. """
  101. assert style in ('in', 'out', 'err')
  102. text = cgi.escape(text)
  103. text = text.replace('\n', '<br/>')
  104. if style == 'in':
  105. text = '<span style="font-weight: bold;">%s</span>' % text
  106. elif style == 'err':
  107. text = '<span style="font-weight: bold; color: red;">%s</span>' % text
  108. else:
  109. text = '<span>%s</span>' % text # without span <br/> is ignored!!!
  110. scrollbar = self._browser.verticalScrollBar()
  111. old_value = scrollbar.value()
  112. scrollattheend = old_value == scrollbar.maximum()
  113. self._browser.moveCursor(QTextCursor.End)
  114. self._browser.insertHtml(text)
  115. """TODO When user enters second line to the input, and input is resized, scrollbar changes its positon
  116. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  117. To fix it correctly, srcoll to the bottom, if before intput has been resized,
  118. scrollbar was in the bottom, and remove next lien
  119. """
  120. scrollattheend = True
  121. if scrollattheend:
  122. scrollbar.setValue(scrollbar.maximum())
  123. else:
  124. scrollbar.setValue(old_value)
  125. def exec_current_command(self):
  126. """
  127. Save current command in the history. Append it to the log. Clear edit line
  128. Reimplement in the child classes to actually execute command
  129. """
  130. text = str(self._edit.toPlainText())
  131. self._append_to_browser('in', '> ' + text + '\n')
  132. if len(self._history) < 2 or\
  133. self._history[-2] != text: # don't insert duplicating items
  134. if text[-1] == '\n':
  135. self._history.insert(-1, text[:-1])
  136. else:
  137. self._history.insert(-1, text)
  138. self._historyIndex = len(self._history) - 1
  139. self._history[-1] = ''
  140. self._edit.clear()
  141. if not text[-1] == '\n':
  142. text += '\n'
  143. self.child_exec_command(text)
  144. def child_exec_command(self, text):
  145. """
  146. Reimplement in the child classes
  147. """
  148. pass
  149. def add_line_break_to_input(self):
  150. self._edit.textCursor().insertText('\n')
  151. def append_output(self, text):
  152. """Appent text to output widget
  153. """
  154. self._append_to_browser('out', text)
  155. def append_error(self, text):
  156. """Appent error text to output widget. Text is drawn with red background
  157. """
  158. self._append_to_browser('err', text)
  159. def is_command_complete(self, text):
  160. """
  161. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  162. """
  163. return True
  164. def browser(self):
  165. return self._browser
  166. def _on_history_next(self):
  167. """
  168. Down pressed, show next item from the history
  169. """
  170. if (self._historyIndex + 1) < len(self._history):
  171. self._historyIndex += 1
  172. self._edit.setPlainText(self._history[self._historyIndex])
  173. self._edit.moveCursor(QTextCursor.End)
  174. def _on_history_prev(self):
  175. """
  176. Up pressed, show previous item from the history
  177. """
  178. if self._historyIndex > 0:
  179. if self._historyIndex == (len(self._history) - 1):
  180. self._history[-1] = self._edit.toPlainText()
  181. self._historyIndex -= 1
  182. self._edit.setPlainText(self._history[self._historyIndex])
  183. self._edit.moveCursor(QTextCursor.End)