recvline.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # -*- test-case-name: twisted.conch.test.test_recvline -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Basic line editing support.
  6. @author: Jp Calderone
  7. """
  8. import string
  9. from zope.interface import implementer
  10. from twisted.conch.insults import insults, helper
  11. from twisted.python import log, reflect
  12. from twisted.python.compat import iterbytes
  13. _counters = {}
  14. class Logging(object):
  15. """
  16. Wrapper which logs attribute lookups.
  17. This was useful in debugging something, I guess. I forget what.
  18. It can probably be deleted or moved somewhere more appropriate.
  19. Nothing special going on here, really.
  20. """
  21. def __init__(self, original):
  22. self.original = original
  23. key = reflect.qual(original.__class__)
  24. count = _counters.get(key, 0)
  25. _counters[key] = count + 1
  26. self._logFile = open(key + '-' + str(count), 'w')
  27. def __str__(self):
  28. return str(super(Logging, self).__getattribute__('original'))
  29. def __repr__(self):
  30. return repr(super(Logging, self).__getattribute__('original'))
  31. def __getattribute__(self, name):
  32. original = super(Logging, self).__getattribute__('original')
  33. logFile = super(Logging, self).__getattribute__('_logFile')
  34. logFile.write(name + '\n')
  35. return getattr(original, name)
  36. @implementer(insults.ITerminalTransport)
  37. class TransportSequence(object):
  38. """
  39. An L{ITerminalTransport} implementation which forwards calls to
  40. one or more other L{ITerminalTransport}s.
  41. This is a cheap way for servers to keep track of the state they
  42. expect the client to see, since all terminal manipulations can be
  43. send to the real client and to a terminal emulator that lives in
  44. the server process.
  45. """
  46. for keyID in (b'UP_ARROW', b'DOWN_ARROW', b'RIGHT_ARROW', b'LEFT_ARROW',
  47. b'HOME', b'INSERT', b'DELETE', b'END', b'PGUP', b'PGDN',
  48. b'F1', b'F2', b'F3', b'F4', b'F5', b'F6', b'F7', b'F8',
  49. b'F9', b'F10', b'F11', b'F12'):
  50. execBytes = keyID + b" = object()"
  51. execStr = execBytes.decode("ascii")
  52. exec(execStr)
  53. TAB = b'\t'
  54. BACKSPACE = b'\x7f'
  55. def __init__(self, *transports):
  56. assert transports, (
  57. "Cannot construct a TransportSequence with no transports")
  58. self.transports = transports
  59. for method in insults.ITerminalTransport:
  60. exec("""\
  61. def %s(self, *a, **kw):
  62. for tpt in self.transports:
  63. result = tpt.%s(*a, **kw)
  64. return result
  65. """ % (method, method))
  66. class LocalTerminalBufferMixin(object):
  67. """
  68. A mixin for RecvLine subclasses which records the state of the terminal.
  69. This is accomplished by performing all L{ITerminalTransport} operations on both
  70. the transport passed to makeConnection and an instance of helper.TerminalBuffer.
  71. @ivar terminalCopy: A L{helper.TerminalBuffer} instance which efforts
  72. will be made to keep up to date with the actual terminal
  73. associated with this protocol instance.
  74. """
  75. def makeConnection(self, transport):
  76. self.terminalCopy = helper.TerminalBuffer()
  77. self.terminalCopy.connectionMade()
  78. return super(LocalTerminalBufferMixin, self).makeConnection(
  79. TransportSequence(transport, self.terminalCopy))
  80. def __str__(self):
  81. return str(self.terminalCopy)
  82. class RecvLine(insults.TerminalProtocol):
  83. """
  84. L{TerminalProtocol} which adds line editing features.
  85. Clients will be prompted for lines of input with all the usual
  86. features: character echoing, left and right arrow support for
  87. moving the cursor to different areas of the line buffer, backspace
  88. and delete for removing characters, and insert for toggling
  89. between typeover and insert mode. Tabs will be expanded to enough
  90. spaces to move the cursor to the next tabstop (every four
  91. characters by default). Enter causes the line buffer to be
  92. cleared and the line to be passed to the lineReceived() method
  93. which, by default, does nothing. Subclasses are responsible for
  94. redrawing the input prompt (this will probably change).
  95. """
  96. width = 80
  97. height = 24
  98. TABSTOP = 4
  99. ps = (b'>>> ', b'... ')
  100. pn = 0
  101. _printableChars = string.printable.encode("ascii")
  102. def connectionMade(self):
  103. # A list containing the characters making up the current line
  104. self.lineBuffer = []
  105. # A zero-based (wtf else?) index into self.lineBuffer.
  106. # Indicates the current cursor position.
  107. self.lineBufferIndex = 0
  108. t = self.terminal
  109. # A map of keyIDs to bound instance methods.
  110. self.keyHandlers = {
  111. t.LEFT_ARROW: self.handle_LEFT,
  112. t.RIGHT_ARROW: self.handle_RIGHT,
  113. t.TAB: self.handle_TAB,
  114. # Both of these should not be necessary, but figuring out
  115. # which is necessary is a huge hassle.
  116. b'\r': self.handle_RETURN,
  117. b'\n': self.handle_RETURN,
  118. t.BACKSPACE: self.handle_BACKSPACE,
  119. t.DELETE: self.handle_DELETE,
  120. t.INSERT: self.handle_INSERT,
  121. t.HOME: self.handle_HOME,
  122. t.END: self.handle_END}
  123. self.initializeScreen()
  124. def initializeScreen(self):
  125. # Hmm, state sucks. Oh well.
  126. # For now we will just take over the whole terminal.
  127. self.terminal.reset()
  128. self.terminal.write(self.ps[self.pn])
  129. # XXX Note: I would prefer to default to starting in insert
  130. # mode, however this does not seem to actually work! I do not
  131. # know why. This is probably of interest to implementors
  132. # subclassing RecvLine.
  133. # XXX XXX Note: But the unit tests all expect the initial mode
  134. # to be insert right now. Fuck, there needs to be a way to
  135. # query the current mode or something.
  136. # self.setTypeoverMode()
  137. self.setInsertMode()
  138. def currentLineBuffer(self):
  139. s = b''.join(self.lineBuffer)
  140. return s[:self.lineBufferIndex], s[self.lineBufferIndex:]
  141. def setInsertMode(self):
  142. self.mode = 'insert'
  143. self.terminal.setModes([insults.modes.IRM])
  144. def setTypeoverMode(self):
  145. self.mode = 'typeover'
  146. self.terminal.resetModes([insults.modes.IRM])
  147. def drawInputLine(self):
  148. """
  149. Write a line containing the current input prompt and the current line
  150. buffer at the current cursor position.
  151. """
  152. self.terminal.write(self.ps[self.pn] + b''.join(self.lineBuffer))
  153. def terminalSize(self, width, height):
  154. # XXX - Clear the previous input line, redraw it at the new
  155. # cursor position
  156. self.terminal.eraseDisplay()
  157. self.terminal.cursorHome()
  158. self.width = width
  159. self.height = height
  160. self.drawInputLine()
  161. def unhandledControlSequence(self, seq):
  162. pass
  163. def keystrokeReceived(self, keyID, modifier):
  164. m = self.keyHandlers.get(keyID)
  165. if m is not None:
  166. m()
  167. elif keyID in self._printableChars:
  168. self.characterReceived(keyID, False)
  169. else:
  170. log.msg("Received unhandled keyID: %r" % (keyID,))
  171. def characterReceived(self, ch, moreCharactersComing):
  172. if self.mode == 'insert':
  173. self.lineBuffer.insert(self.lineBufferIndex, ch)
  174. else:
  175. self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch]
  176. self.lineBufferIndex += 1
  177. self.terminal.write(ch)
  178. def handle_TAB(self):
  179. n = self.TABSTOP - (len(self.lineBuffer) % self.TABSTOP)
  180. self.terminal.cursorForward(n)
  181. self.lineBufferIndex += n
  182. self.lineBuffer.extend(iterbytes(b' ' * n))
  183. def handle_LEFT(self):
  184. if self.lineBufferIndex > 0:
  185. self.lineBufferIndex -= 1
  186. self.terminal.cursorBackward()
  187. def handle_RIGHT(self):
  188. if self.lineBufferIndex < len(self.lineBuffer):
  189. self.lineBufferIndex += 1
  190. self.terminal.cursorForward()
  191. def handle_HOME(self):
  192. if self.lineBufferIndex:
  193. self.terminal.cursorBackward(self.lineBufferIndex)
  194. self.lineBufferIndex = 0
  195. def handle_END(self):
  196. offset = len(self.lineBuffer) - self.lineBufferIndex
  197. if offset:
  198. self.terminal.cursorForward(offset)
  199. self.lineBufferIndex = len(self.lineBuffer)
  200. def handle_BACKSPACE(self):
  201. if self.lineBufferIndex > 0:
  202. self.lineBufferIndex -= 1
  203. del self.lineBuffer[self.lineBufferIndex]
  204. self.terminal.cursorBackward()
  205. self.terminal.deleteCharacter()
  206. def handle_DELETE(self):
  207. if self.lineBufferIndex < len(self.lineBuffer):
  208. del self.lineBuffer[self.lineBufferIndex]
  209. self.terminal.deleteCharacter()
  210. def handle_RETURN(self):
  211. line = b''.join(self.lineBuffer)
  212. self.lineBuffer = []
  213. self.lineBufferIndex = 0
  214. self.terminal.nextLine()
  215. self.lineReceived(line)
  216. def handle_INSERT(self):
  217. assert self.mode in ('typeover', 'insert')
  218. if self.mode == 'typeover':
  219. self.setInsertMode()
  220. else:
  221. self.setTypeoverMode()
  222. def lineReceived(self, line):
  223. pass
  224. class HistoricRecvLine(RecvLine):
  225. """
  226. L{TerminalProtocol} which adds both basic line-editing features and input history.
  227. Everything supported by L{RecvLine} is also supported by this class. In addition, the
  228. up and down arrows traverse the input history. Each received line is automatically
  229. added to the end of the input history.
  230. """
  231. def connectionMade(self):
  232. RecvLine.connectionMade(self)
  233. self.historyLines = []
  234. self.historyPosition = 0
  235. t = self.terminal
  236. self.keyHandlers.update({t.UP_ARROW: self.handle_UP,
  237. t.DOWN_ARROW: self.handle_DOWN})
  238. def currentHistoryBuffer(self):
  239. b = tuple(self.historyLines)
  240. return b[:self.historyPosition], b[self.historyPosition:]
  241. def _deliverBuffer(self, buf):
  242. if buf:
  243. for ch in iterbytes(buf[:-1]):
  244. self.characterReceived(ch, True)
  245. self.characterReceived(buf[-1:], False)
  246. def handle_UP(self):
  247. if self.lineBuffer and self.historyPosition == len(self.historyLines):
  248. self.historyLines.append(b''.join(self.lineBuffer))
  249. if self.historyPosition > 0:
  250. self.handle_HOME()
  251. self.terminal.eraseToLineEnd()
  252. self.historyPosition -= 1
  253. self.lineBuffer = []
  254. self._deliverBuffer(self.historyLines[self.historyPosition])
  255. def handle_DOWN(self):
  256. if self.historyPosition < len(self.historyLines) - 1:
  257. self.handle_HOME()
  258. self.terminal.eraseToLineEnd()
  259. self.historyPosition += 1
  260. self.lineBuffer = []
  261. self._deliverBuffer(self.historyLines[self.historyPosition])
  262. else:
  263. self.handle_HOME()
  264. self.terminal.eraseToLineEnd()
  265. self.historyPosition = len(self.historyLines)
  266. self.lineBuffer = []
  267. self.lineBufferIndex = 0
  268. def handle_RETURN(self):
  269. if self.lineBuffer:
  270. self.historyLines.append(b''.join(self.lineBuffer))
  271. self.historyPosition = len(self.historyLines)
  272. return RecvLine.handle_RETURN(self)