termwidget.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. 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 _append_to_browser(self, style, text):
  101. """
  102. Convert text to HTML for inserting it to browser
  103. """
  104. assert style in ('in', 'out', 'err')
  105. text = cgi.escape(text)
  106. text = text.replace('\n', '<br/>')
  107. if style == 'in':
  108. text = '<span style="font-weight: bold;">%s</span>' % text
  109. elif style == 'err':
  110. text = '<span style="font-weight: bold; color: red;">%s</span>' % text
  111. else:
  112. text = '<span>%s</span>' % text # without span <br/> is ignored!!!
  113. scrollbar = self._browser.verticalScrollBar()
  114. old_value = scrollbar.value()
  115. scrollattheend = old_value == scrollbar.maximum()
  116. self._browser.moveCursor(QTextCursor.End)
  117. self._browser.insertHtml(text)
  118. """TODO When user enters second line to the input, and input is resized, scrollbar changes its positon
  119. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  120. To fix it correctly, srcoll to the bottom, if before intput has been resized,
  121. scrollbar was in the bottom, and remove next lien
  122. """
  123. scrollattheend = True
  124. if scrollattheend:
  125. scrollbar.setValue(scrollbar.maximum())
  126. else:
  127. scrollbar.setValue(old_value)
  128. def exec_current_command(self):
  129. """
  130. Save current command in the history. Append it to the log. Clear edit line
  131. Reimplement in the child classes to actually execute command
  132. """
  133. text = str(self._edit.toPlainText())
  134. self._append_to_browser('in', '> ' + text + '\n')
  135. if len(self._history) < 2 or\
  136. self._history[-2] != text: # don't insert duplicating items
  137. if text[-1] == '\n':
  138. self._history.insert(-1, text[:-1])
  139. else:
  140. self._history.insert(-1, text)
  141. self._historyIndex = len(self._history) - 1
  142. self._history[-1] = ''
  143. self._edit.clear()
  144. if not text[-1] == '\n':
  145. text += '\n'
  146. self.child_exec_command(text)
  147. def child_exec_command(self, text):
  148. """
  149. Reimplement in the child classes
  150. """
  151. pass
  152. def add_line_break_to_input(self):
  153. self._edit.textCursor().insertText('\n')
  154. def append_output(self, text):
  155. """Appent text to output widget
  156. """
  157. self._append_to_browser('out', text)
  158. def append_error(self, text):
  159. """Appent error text to output widget. Text is drawn with red background
  160. """
  161. self._append_to_browser('err', text)
  162. def is_command_complete(self, text):
  163. """
  164. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  165. """
  166. return True
  167. def browser(self):
  168. return self._browser
  169. def _on_history_next(self):
  170. """
  171. Down pressed, show next item from the history
  172. """
  173. if (self._historyIndex + 1) < len(self._history):
  174. self._historyIndex += 1
  175. self._edit.setPlainText(self._history[self._historyIndex])
  176. self._edit.moveCursor(QTextCursor.End)
  177. def _on_history_prev(self):
  178. """
  179. Up pressed, show previous item from the history
  180. """
  181. if self._historyIndex > 0:
  182. if self._historyIndex == (len(self._history) - 1):
  183. self._history[-1] = self._edit.toPlainText()
  184. self._historyIndex -= 1
  185. self._edit.setPlainText(self._history[self._historyIndex])
  186. self._edit.moveCursor(QTextCursor.End)