termwidget.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. cursorPos = self.textCursor().position()
  50. textBeforeEnd = text[cursorPos:]
  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. cursorPos = self.textCursor().position()
  58. textBeforeStart = text[:cursorPos]
  59. # lineCount = len(textBeforeStart.splitlines())
  60. lineCount = len(textBeforeStart.split('\n'))
  61. if len(textBeforeStart) > 0 and \
  62. (textBeforeStart[-1] == '\n' or textBeforeStart[-1] == '\r'):
  63. lineCount += 1
  64. if lineCount <= 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(self._browser.document().defaultStyleSheet() +
  83. "span {white-space:pre;}")
  84. self._edit = _ExpandableTextEdit(self, self)
  85. self._edit.historyNext.connect(self._on_history_next)
  86. self._edit.historyPrev.connect(self._on_history_prev)
  87. self.setFocusProxy(self._edit)
  88. layout = QVBoxLayout(self)
  89. layout.setSpacing(0)
  90. layout.setContentsMargins(0, 0, 0, 0)
  91. layout.addWidget(self._browser)
  92. layout.addWidget(self._edit)
  93. self._history = [''] # current empty line
  94. self._historyIndex = 0
  95. self._edit.setFocus()
  96. def _append_to_browser(self, style, text):
  97. """
  98. Convert text to HTML for inserting it to browser
  99. """
  100. assert style in ('in', 'out', 'err')
  101. text = cgi.escape(text)
  102. text = text.replace('\n', '<br/>')
  103. if style != 'out':
  104. def_bg = self._browser.palette().color(QPalette.Base)
  105. h, s, v, a = def_bg.getHsvF()
  106. if style == 'in':
  107. if v > 0.5: # white background
  108. v = v - (v / 8) # make darker
  109. else:
  110. v = v + ((1 - v) / 4) # make ligher
  111. else: # err
  112. if v < 0.5:
  113. v = v + ((1 - v) / 4) # make ligher
  114. if h == -1: # make red
  115. h = 0
  116. s = .4
  117. else:
  118. h = h + ((1 - h) * 0.5) # make more red
  119. bg = QColor.fromHsvF(h, s, v).name()
  120. text = '<span style="background-color: %s; font-weight: bold;">%s</span>' % (str(bg), text)
  121. else:
  122. text = '<span>%s</span>' % text # without span <br/> is ignored!!!
  123. scrollbar = self._browser.verticalScrollBar()
  124. old_value = scrollbar.value()
  125. scrollattheend = old_value == scrollbar.maximum()
  126. self._browser.moveCursor(QTextCursor.End)
  127. self._browser.insertHtml(text)
  128. """TODO When user enters second line to the input, and input is resized, scrollbar changes its positon
  129. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  130. To fix it correctly, srcoll to the bottom, if before intput has been resized,
  131. scrollbar was in the bottom, and remove next lien
  132. """
  133. scrollattheend = True
  134. if scrollattheend:
  135. scrollbar.setValue(scrollbar.maximum())
  136. else:
  137. scrollbar.setValue(old_value)
  138. def exec_current_command(self):
  139. """
  140. Save current command in the history. Append it to the log. Clear edit line
  141. Reimplement in the child classes to actually execute command
  142. """
  143. text = str(self._edit.toPlainText())
  144. self._append_to_browser('in', '> ' + text + '\n')
  145. if len(self._history) < 2 or\
  146. self._history[-2] != text: # don't insert duplicating items
  147. if text[-1] == '\n':
  148. self._history.insert(-1, text[:-1])
  149. else:
  150. self._history.insert(-1, text)
  151. self._historyIndex = len(self._history) - 1
  152. self._history[-1] = ''
  153. self._edit.clear()
  154. if not text[-1] == '\n':
  155. text += '\n'
  156. self.child_exec_command(text)
  157. def child_exec_command(self, text):
  158. """
  159. Reimplement in the child classes
  160. """
  161. pass
  162. def add_line_break_to_input(self):
  163. self._edit.textCursor().insertText('\n')
  164. def append_output(self, text):
  165. """Appent text to output widget
  166. """
  167. self._append_to_browser('out', text)
  168. def append_error(self, text):
  169. """Appent error text to output widget. Text is drawn with red background
  170. """
  171. self._append_to_browser('err', text)
  172. def is_command_complete(self, text):
  173. """
  174. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  175. """
  176. return True
  177. def browser(self):
  178. return self._browser
  179. def _on_history_next(self):
  180. """
  181. Down pressed, show next item from the history
  182. """
  183. if (self._historyIndex + 1) < len(self._history):
  184. self._historyIndex += 1
  185. self._edit.setPlainText(self._history[self._historyIndex])
  186. self._edit.moveCursor(QTextCursor.End)
  187. def _on_history_prev(self):
  188. """
  189. Up pressed, show previous item from the history
  190. """
  191. if self._historyIndex > 0:
  192. if self._historyIndex == (len(self._history) - 1):
  193. self._history[-1] = self._edit.toPlainText()
  194. self._historyIndex -= 1
  195. self._edit.setPlainText(self._history[self._historyIndex])
  196. self._edit.moveCursor(QTextCursor.End)