insults.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. # -*- test-case-name: twisted.conch.test.test_insults -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. VT102 and VT220 terminal manipulation.
  6. @author: Jp Calderone
  7. """
  8. from zope.interface import implementer, Interface
  9. from twisted.internet import protocol, defer, interfaces as iinternet
  10. from twisted.python.compat import intToBytes, iterbytes, networkString
  11. class ITerminalProtocol(Interface):
  12. def makeConnection(transport):
  13. """
  14. Called with an L{ITerminalTransport} when a connection is established.
  15. """
  16. def keystrokeReceived(keyID, modifier):
  17. """
  18. A keystroke was received.
  19. Each keystroke corresponds to one invocation of this method.
  20. keyID is a string identifier for that key. Printable characters
  21. are represented by themselves. Control keys, such as arrows and
  22. function keys, are represented with symbolic constants on
  23. L{ServerProtocol}.
  24. """
  25. def terminalSize(width, height):
  26. """
  27. Called to indicate the size of the terminal.
  28. A terminal of 80x24 should be assumed if this method is not
  29. called. This method might not be called for real terminals.
  30. """
  31. def unhandledControlSequence(seq):
  32. """
  33. Called when an unsupported control sequence is received.
  34. @type seq: L{str}
  35. @param seq: The whole control sequence which could not be interpreted.
  36. """
  37. def connectionLost(reason):
  38. """
  39. Called when the connection has been lost.
  40. reason is a Failure describing why.
  41. """
  42. @implementer(ITerminalProtocol)
  43. class TerminalProtocol(object):
  44. def makeConnection(self, terminal):
  45. # assert ITerminalTransport.providedBy(transport), "TerminalProtocol.makeConnection must be passed an ITerminalTransport implementor"
  46. self.terminal = terminal
  47. self.connectionMade()
  48. def connectionMade(self):
  49. """
  50. Called after a connection has been established.
  51. """
  52. def keystrokeReceived(self, keyID, modifier):
  53. pass
  54. def terminalSize(self, width, height):
  55. pass
  56. def unhandledControlSequence(self, seq):
  57. pass
  58. def connectionLost(self, reason):
  59. pass
  60. class ITerminalTransport(iinternet.ITransport):
  61. def cursorUp(n=1):
  62. """
  63. Move the cursor up n lines.
  64. """
  65. def cursorDown(n=1):
  66. """
  67. Move the cursor down n lines.
  68. """
  69. def cursorForward(n=1):
  70. """
  71. Move the cursor right n columns.
  72. """
  73. def cursorBackward(n=1):
  74. """
  75. Move the cursor left n columns.
  76. """
  77. def cursorPosition(column, line):
  78. """
  79. Move the cursor to the given line and column.
  80. """
  81. def cursorHome():
  82. """
  83. Move the cursor home.
  84. """
  85. def index():
  86. """
  87. Move the cursor down one line, performing scrolling if necessary.
  88. """
  89. def reverseIndex():
  90. """
  91. Move the cursor up one line, performing scrolling if necessary.
  92. """
  93. def nextLine():
  94. """
  95. Move the cursor to the first position on the next line, performing scrolling if necessary.
  96. """
  97. def saveCursor():
  98. """
  99. Save the cursor position, character attribute, character set, and origin mode selection.
  100. """
  101. def restoreCursor():
  102. """
  103. Restore the previously saved cursor position, character attribute, character set, and origin mode selection.
  104. If no cursor state was previously saved, move the cursor to the home position.
  105. """
  106. def setModes(modes):
  107. """
  108. Set the given modes on the terminal.
  109. """
  110. def resetModes(mode):
  111. """
  112. Reset the given modes on the terminal.
  113. """
  114. def setPrivateModes(modes):
  115. """
  116. Set the given DEC private modes on the terminal.
  117. """
  118. def resetPrivateModes(modes):
  119. """
  120. Reset the given DEC private modes on the terminal.
  121. """
  122. def applicationKeypadMode():
  123. """
  124. Cause keypad to generate control functions.
  125. Cursor key mode selects the type of characters generated by cursor keys.
  126. """
  127. def numericKeypadMode():
  128. """
  129. Cause keypad to generate normal characters.
  130. """
  131. def selectCharacterSet(charSet, which):
  132. """
  133. Select a character set.
  134. charSet should be one of CS_US, CS_UK, CS_DRAWING, CS_ALTERNATE, or
  135. CS_ALTERNATE_SPECIAL.
  136. which should be one of G0 or G1.
  137. """
  138. def shiftIn():
  139. """
  140. Activate the G0 character set.
  141. """
  142. def shiftOut():
  143. """
  144. Activate the G1 character set.
  145. """
  146. def singleShift2():
  147. """
  148. Shift to the G2 character set for a single character.
  149. """
  150. def singleShift3():
  151. """
  152. Shift to the G3 character set for a single character.
  153. """
  154. def selectGraphicRendition(*attributes):
  155. """
  156. Enabled one or more character attributes.
  157. Arguments should be one or more of UNDERLINE, REVERSE_VIDEO, BLINK, or BOLD.
  158. NORMAL may also be specified to disable all character attributes.
  159. """
  160. def horizontalTabulationSet():
  161. """
  162. Set a tab stop at the current cursor position.
  163. """
  164. def tabulationClear():
  165. """
  166. Clear the tab stop at the current cursor position.
  167. """
  168. def tabulationClearAll():
  169. """
  170. Clear all tab stops.
  171. """
  172. def doubleHeightLine(top=True):
  173. """
  174. Make the current line the top or bottom half of a double-height, double-width line.
  175. If top is True, the current line is the top half. Otherwise, it is the bottom half.
  176. """
  177. def singleWidthLine():
  178. """
  179. Make the current line a single-width, single-height line.
  180. """
  181. def doubleWidthLine():
  182. """
  183. Make the current line a double-width line.
  184. """
  185. def eraseToLineEnd():
  186. """
  187. Erase from the cursor to the end of line, including cursor position.
  188. """
  189. def eraseToLineBeginning():
  190. """
  191. Erase from the cursor to the beginning of the line, including the cursor position.
  192. """
  193. def eraseLine():
  194. """
  195. Erase the entire cursor line.
  196. """
  197. def eraseToDisplayEnd():
  198. """
  199. Erase from the cursor to the end of the display, including the cursor position.
  200. """
  201. def eraseToDisplayBeginning():
  202. """
  203. Erase from the cursor to the beginning of the display, including the cursor position.
  204. """
  205. def eraseDisplay():
  206. """
  207. Erase the entire display.
  208. """
  209. def deleteCharacter(n=1):
  210. """
  211. Delete n characters starting at the cursor position.
  212. Characters to the right of deleted characters are shifted to the left.
  213. """
  214. def insertLine(n=1):
  215. """
  216. Insert n lines at the cursor position.
  217. Lines below the cursor are shifted down. Lines moved past the bottom margin are lost.
  218. This command is ignored when the cursor is outside the scroll region.
  219. """
  220. def deleteLine(n=1):
  221. """
  222. Delete n lines starting at the cursor position.
  223. Lines below the cursor are shifted up. This command is ignored when the cursor is outside
  224. the scroll region.
  225. """
  226. def reportCursorPosition():
  227. """
  228. Return a Deferred that fires with a two-tuple of (x, y) indicating the cursor position.
  229. """
  230. def reset():
  231. """
  232. Reset the terminal to its initial state.
  233. """
  234. def unhandledControlSequence(seq):
  235. """
  236. Called when an unsupported control sequence is received.
  237. @type seq: L{str}
  238. @param seq: The whole control sequence which could not be interpreted.
  239. """
  240. CSI = b'\x1b'
  241. CST = {b'~': b'tilde'}
  242. class modes:
  243. """
  244. ECMA 48 standardized modes
  245. """
  246. # BREAKS YOPUR KEYBOARD MOFO
  247. KEYBOARD_ACTION = KAM = 2
  248. # When set, enables character insertion. New display characters
  249. # move old display characters to the right. Characters moved past
  250. # the right margin are lost.
  251. # When reset, enables replacement mode (disables character
  252. # insertion). New display characters replace old display
  253. # characters at cursor position. The old character is erased.
  254. INSERTION_REPLACEMENT = IRM = 4
  255. # Set causes a received linefeed, form feed, or vertical tab to
  256. # move cursor to first column of next line. RETURN transmits both
  257. # a carriage return and linefeed. This selection is also called
  258. # new line option.
  259. # Reset causes a received linefeed, form feed, or vertical tab to
  260. # move cursor to next line in current column. RETURN transmits a
  261. # carriage return.
  262. LINEFEED_NEWLINE = LNM = 20
  263. class privateModes:
  264. """
  265. ANSI-Compatible Private Modes
  266. """
  267. ERROR = 0
  268. CURSOR_KEY = 1
  269. ANSI_VT52 = 2
  270. COLUMN = 3
  271. SCROLL = 4
  272. SCREEN = 5
  273. ORIGIN = 6
  274. AUTO_WRAP = 7
  275. AUTO_REPEAT = 8
  276. PRINTER_FORM_FEED = 18
  277. PRINTER_EXTENT = 19
  278. # Toggle cursor visibility (reset hides it)
  279. CURSOR_MODE = 25
  280. # Character sets
  281. CS_US = b'CS_US'
  282. CS_UK = b'CS_UK'
  283. CS_DRAWING = b'CS_DRAWING'
  284. CS_ALTERNATE = b'CS_ALTERNATE'
  285. CS_ALTERNATE_SPECIAL = b'CS_ALTERNATE_SPECIAL'
  286. # Groupings (or something?? These are like variables that can be bound to character sets)
  287. G0 = b'G0'
  288. G1 = b'G1'
  289. # G2 and G3 cannot be changed, but they can be shifted to.
  290. G2 = b'G2'
  291. G3 = b'G3'
  292. # Character attributes
  293. NORMAL = 0
  294. BOLD = 1
  295. UNDERLINE = 4
  296. BLINK = 5
  297. REVERSE_VIDEO = 7
  298. class Vector:
  299. def __init__(self, x, y):
  300. self.x = x
  301. self.y = y
  302. def log(s):
  303. with open('log', 'a') as f:
  304. f.write(str(s) + '\n')
  305. # XXX TODO - These attributes are really part of the
  306. # ITerminalTransport interface, I think.
  307. _KEY_NAMES = ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
  308. 'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', 'NUMPAD_MIDDLE',
  309. 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
  310. 'F10', 'F11', 'F12',
  311. 'ALT', 'SHIFT', 'CONTROL')
  312. class _const(object):
  313. """
  314. @ivar name: A string naming this constant
  315. """
  316. def __init__(self, name):
  317. self.name = name
  318. def __repr__(self):
  319. return '[' + self.name + ']'
  320. def __bytes__(self):
  321. return ('[' + self.name + ']').encode("ascii")
  322. FUNCTION_KEYS = [
  323. _const(_name).__bytes__() for _name in _KEY_NAMES]
  324. @implementer(ITerminalTransport)
  325. class ServerProtocol(protocol.Protocol):
  326. protocolFactory = None
  327. terminalProtocol = None
  328. TAB = b'\t'
  329. BACKSPACE = b'\x7f'
  330. ##
  331. lastWrite = b''
  332. state = b'data'
  333. termSize = Vector(80, 24)
  334. cursorPos = Vector(0, 0)
  335. scrollRegion = None
  336. # Factory who instantiated me
  337. factory = None
  338. def __init__(self, protocolFactory=None, *a, **kw):
  339. """
  340. @param protocolFactory: A callable which will be invoked with
  341. *a, **kw and should return an ITerminalProtocol implementor.
  342. This will be invoked when a connection to this ServerProtocol
  343. is established.
  344. @param a: Any positional arguments to pass to protocolFactory.
  345. @param kw: Any keyword arguments to pass to protocolFactory.
  346. """
  347. # assert protocolFactory is None or ITerminalProtocol.implementedBy(protocolFactory), "ServerProtocol.__init__ must be passed an ITerminalProtocol implementor"
  348. if protocolFactory is not None:
  349. self.protocolFactory = protocolFactory
  350. self.protocolArgs = a
  351. self.protocolKwArgs = kw
  352. self._cursorReports = []
  353. def connectionMade(self):
  354. if self.protocolFactory is not None:
  355. self.terminalProtocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
  356. try:
  357. factory = self.factory
  358. except AttributeError:
  359. pass
  360. else:
  361. self.terminalProtocol.factory = factory
  362. self.terminalProtocol.makeConnection(self)
  363. def dataReceived(self, data):
  364. for ch in iterbytes(data):
  365. if self.state == b'data':
  366. if ch == b'\x1b':
  367. self.state = b'escaped'
  368. else:
  369. self.terminalProtocol.keystrokeReceived(ch, None)
  370. elif self.state == b'escaped':
  371. if ch == b'[':
  372. self.state = b'bracket-escaped'
  373. self.escBuf = []
  374. elif ch == b'O':
  375. self.state = b'low-function-escaped'
  376. else:
  377. self.state = b'data'
  378. self._handleShortControlSequence(ch)
  379. elif self.state == b'bracket-escaped':
  380. if ch == b'O':
  381. self.state = b'low-function-escaped'
  382. elif ch.isalpha() or ch == b'~':
  383. self._handleControlSequence(b''.join(self.escBuf) + ch)
  384. del self.escBuf
  385. self.state = b'data'
  386. else:
  387. self.escBuf.append(ch)
  388. elif self.state == b'low-function-escaped':
  389. self._handleLowFunctionControlSequence(ch)
  390. self.state = b'data'
  391. else:
  392. raise ValueError("Illegal state")
  393. def _handleShortControlSequence(self, ch):
  394. self.terminalProtocol.keystrokeReceived(ch, self.ALT)
  395. def _handleControlSequence(self, buf):
  396. buf = b'\x1b[' + buf
  397. f = getattr(self.controlSequenceParser,
  398. CST.get(buf[-1:], buf[-1:]).decode("ascii"),
  399. None)
  400. if f is None:
  401. self.unhandledControlSequence(buf)
  402. else:
  403. f(self, self.terminalProtocol, buf[:-1])
  404. def unhandledControlSequence(self, buf):
  405. self.terminalProtocol.unhandledControlSequence(buf)
  406. def _handleLowFunctionControlSequence(self, ch):
  407. functionKeys = {b'P': self.F1, b'Q': self.F2,
  408. b'R': self.F3, b'S': self.F4}
  409. keyID = functionKeys.get(ch)
  410. if keyID is not None:
  411. self.terminalProtocol.keystrokeReceived(keyID, None)
  412. else:
  413. self.terminalProtocol.unhandledControlSequence(b'\x1b[O' + ch)
  414. class ControlSequenceParser:
  415. def A(self, proto, handler, buf):
  416. if buf == b'\x1b[':
  417. handler.keystrokeReceived(proto.UP_ARROW, None)
  418. else:
  419. handler.unhandledControlSequence(buf + b'A')
  420. def B(self, proto, handler, buf):
  421. if buf == b'\x1b[':
  422. handler.keystrokeReceived(proto.DOWN_ARROW, None)
  423. else:
  424. handler.unhandledControlSequence(buf + b'B')
  425. def C(self, proto, handler, buf):
  426. if buf == b'\x1b[':
  427. handler.keystrokeReceived(proto.RIGHT_ARROW, None)
  428. else:
  429. handler.unhandledControlSequence(buf + b'C')
  430. def D(self, proto, handler, buf):
  431. if buf == b'\x1b[':
  432. handler.keystrokeReceived(proto.LEFT_ARROW, None)
  433. else:
  434. handler.unhandledControlSequence(buf + b'D')
  435. def E(self, proto, handler, buf):
  436. if buf == b'\x1b[':
  437. handler.keystrokeReceived(proto.NUMPAD_MIDDLE, None)
  438. else:
  439. handler.unhandledControlSequence(buf + b'E')
  440. def F(self, proto, handler, buf):
  441. if buf == b'\x1b[':
  442. handler.keystrokeReceived(proto.END, None)
  443. else:
  444. handler.unhandledControlSequence(buf + b'F')
  445. def H(self, proto, handler, buf):
  446. if buf == b'\x1b[':
  447. handler.keystrokeReceived(proto.HOME, None)
  448. else:
  449. handler.unhandledControlSequence(buf + b'H')
  450. def R(self, proto, handler, buf):
  451. if not proto._cursorReports:
  452. handler.unhandledControlSequence(buf + b'R')
  453. elif buf.startswith(b'\x1b['):
  454. report = buf[2:]
  455. parts = report.split(b';')
  456. if len(parts) != 2:
  457. handler.unhandledControlSequence(buf + b'R')
  458. else:
  459. Pl, Pc = parts
  460. try:
  461. Pl, Pc = int(Pl), int(Pc)
  462. except ValueError:
  463. handler.unhandledControlSequence(buf + b'R')
  464. else:
  465. d = proto._cursorReports.pop(0)
  466. d.callback((Pc - 1, Pl - 1))
  467. else:
  468. handler.unhandledControlSequence(buf + b'R')
  469. def Z(self, proto, handler, buf):
  470. if buf == b'\x1b[':
  471. handler.keystrokeReceived(proto.TAB, proto.SHIFT)
  472. else:
  473. handler.unhandledControlSequence(buf + b'Z')
  474. def tilde(self, proto, handler, buf):
  475. map = {1: proto.HOME, 2: proto.INSERT, 3: proto.DELETE,
  476. 4: proto.END, 5: proto.PGUP, 6: proto.PGDN,
  477. 15: proto.F5, 17: proto.F6, 18: proto.F7,
  478. 19: proto.F8, 20: proto.F9, 21: proto.F10,
  479. 23: proto.F11, 24: proto.F12}
  480. if buf.startswith(b'\x1b['):
  481. ch = buf[2:]
  482. try:
  483. v = int(ch)
  484. except ValueError:
  485. handler.unhandledControlSequence(buf + b'~')
  486. else:
  487. symbolic = map.get(v)
  488. if symbolic is not None:
  489. handler.keystrokeReceived(map[v], None)
  490. else:
  491. handler.unhandledControlSequence(buf + b'~')
  492. else:
  493. handler.unhandledControlSequence(buf + b'~')
  494. controlSequenceParser = ControlSequenceParser()
  495. # ITerminalTransport
  496. def cursorUp(self, n=1):
  497. assert n >= 1
  498. self.cursorPos.y = max(self.cursorPos.y - n, 0)
  499. self.write(b'\x1b[' + intToBytes(n) + b'A')
  500. def cursorDown(self, n=1):
  501. assert n >= 1
  502. self.cursorPos.y = min(self.cursorPos.y + n, self.termSize.y - 1)
  503. self.write(b'\x1b[' + intToBytes(n) + b'B')
  504. def cursorForward(self, n=1):
  505. assert n >= 1
  506. self.cursorPos.x = min(self.cursorPos.x + n, self.termSize.x - 1)
  507. self.write(b'\x1b[' + intToBytes(n) + b'C')
  508. def cursorBackward(self, n=1):
  509. assert n >= 1
  510. self.cursorPos.x = max(self.cursorPos.x - n, 0)
  511. self.write(b'\x1b[' + intToBytes(n) + b'D')
  512. def cursorPosition(self, column, line):
  513. self.write(b'\x1b[' +
  514. intToBytes(line + 1) +
  515. b';' +
  516. intToBytes(column + 1) +
  517. b'H')
  518. def cursorHome(self):
  519. self.cursorPos.x = self.cursorPos.y = 0
  520. self.write(b'\x1b[H')
  521. def index(self):
  522. # ECMA48 5th Edition removes this
  523. self.cursorPos.y = min(self.cursorPos.y + 1, self.termSize.y - 1)
  524. self.write(b'\x1bD')
  525. def reverseIndex(self):
  526. self.cursorPos.y = max(self.cursorPos.y - 1, 0)
  527. self.write(b'\x1bM')
  528. def nextLine(self):
  529. self.cursorPos.x = 0
  530. self.cursorPos.y = min(self.cursorPos.y + 1, self.termSize.y - 1)
  531. self.write(b'\n')
  532. def saveCursor(self):
  533. self._savedCursorPos = Vector(self.cursorPos.x, self.cursorPos.y)
  534. self.write(b'\x1b7')
  535. def restoreCursor(self):
  536. self.cursorPos = self._savedCursorPos
  537. del self._savedCursorPos
  538. self.write(b'\x1b8')
  539. def setModes(self, modes):
  540. # XXX Support ANSI-Compatible private modes
  541. modesBytes = b';'.join([intToBytes(mode) for mode in modes])
  542. self.write(b'\x1b[' + modesBytes + b'h')
  543. def setPrivateModes(self, modes):
  544. modesBytes = b';'.join([intToBytes(mode) for mode in modes])
  545. self.write(b'\x1b[?' + modesBytes + b'h')
  546. def resetModes(self, modes):
  547. # XXX Support ANSI-Compatible private modes
  548. modesBytes = b';'.join([intToBytes(mode) for mode in modes])
  549. self.write(b'\x1b[' + modesBytes + b'l')
  550. def resetPrivateModes(self, modes):
  551. modesBytes = b';'.join([intToBytes(mode) for mode in modes])
  552. self.write(b'\x1b[?' + modesBytes + b'l')
  553. def applicationKeypadMode(self):
  554. self.write(b'\x1b=')
  555. def numericKeypadMode(self):
  556. self.write(b'\x1b>')
  557. def selectCharacterSet(self, charSet, which):
  558. # XXX Rewrite these as dict lookups
  559. if which == G0:
  560. which = b'('
  561. elif which == G1:
  562. which = b')'
  563. else:
  564. raise ValueError("`which' argument to selectCharacterSet must be G0 or G1")
  565. if charSet == CS_UK:
  566. charSet = b'A'
  567. elif charSet == CS_US:
  568. charSet = b'B'
  569. elif charSet == CS_DRAWING:
  570. charSet = b'0'
  571. elif charSet == CS_ALTERNATE:
  572. charSet = b'1'
  573. elif charSet == CS_ALTERNATE_SPECIAL:
  574. charSet = b'2'
  575. else:
  576. raise ValueError("Invalid `charSet' argument to selectCharacterSet")
  577. self.write(b'\x1b' + which + charSet)
  578. def shiftIn(self):
  579. self.write(b'\x15')
  580. def shiftOut(self):
  581. self.write(b'\x14')
  582. def singleShift2(self):
  583. self.write(b'\x1bN')
  584. def singleShift3(self):
  585. self.write(b'\x1bO')
  586. def selectGraphicRendition(self, *attributes):
  587. # each member of attributes must be a native string
  588. attrs = []
  589. for a in attributes:
  590. attrs.append(networkString(a))
  591. self.write(b'\x1b[' +
  592. b';'.join(attrs) +
  593. b'm')
  594. def horizontalTabulationSet(self):
  595. self.write(b'\x1bH')
  596. def tabulationClear(self):
  597. self.write(b'\x1b[q')
  598. def tabulationClearAll(self):
  599. self.write(b'\x1b[3q')
  600. def doubleHeightLine(self, top=True):
  601. if top:
  602. self.write(b'\x1b#3')
  603. else:
  604. self.write(b'\x1b#4')
  605. def singleWidthLine(self):
  606. self.write(b'\x1b#5')
  607. def doubleWidthLine(self):
  608. self.write(b'\x1b#6')
  609. def eraseToLineEnd(self):
  610. self.write(b'\x1b[K')
  611. def eraseToLineBeginning(self):
  612. self.write(b'\x1b[1K')
  613. def eraseLine(self):
  614. self.write(b'\x1b[2K')
  615. def eraseToDisplayEnd(self):
  616. self.write(b'\x1b[J')
  617. def eraseToDisplayBeginning(self):
  618. self.write(b'\x1b[1J')
  619. def eraseDisplay(self):
  620. self.write(b'\x1b[2J')
  621. def deleteCharacter(self, n=1):
  622. self.write(b'\x1b[' + intToBytes(n) + b'P')
  623. def insertLine(self, n=1):
  624. self.write(b'\x1b[' + intToBytes(n) + b'L')
  625. def deleteLine(self, n=1):
  626. self.write(b'\x1b[' + intToBytes(n) + b'M')
  627. def setScrollRegion(self, first=None, last=None):
  628. if first is not None:
  629. first = intToBytes(first)
  630. else:
  631. first = b''
  632. if last is not None:
  633. last = intToBytes(last)
  634. else:
  635. last = b''
  636. self.write(b'\x1b[' + first + b';' + last + b'r')
  637. def resetScrollRegion(self):
  638. self.setScrollRegion()
  639. def reportCursorPosition(self):
  640. d = defer.Deferred()
  641. self._cursorReports.append(d)
  642. self.write(b'\x1b[6n')
  643. return d
  644. def reset(self):
  645. self.cursorPos.x = self.cursorPos.y = 0
  646. try:
  647. del self._savedCursorPos
  648. except AttributeError:
  649. pass
  650. self.write(b'\x1bc')
  651. # ITransport
  652. def write(self, data):
  653. if data:
  654. if not isinstance(data, bytes):
  655. data = data.encode("utf-8")
  656. self.lastWrite = data
  657. self.transport.write(b'\r\n'.join(data.split(b'\n')))
  658. def writeSequence(self, data):
  659. self.write(b''.join(data))
  660. def loseConnection(self):
  661. self.reset()
  662. self.transport.loseConnection()
  663. def connectionLost(self, reason):
  664. if self.terminalProtocol is not None:
  665. try:
  666. self.terminalProtocol.connectionLost(reason)
  667. finally:
  668. self.terminalProtocol = None
  669. # Add symbolic names for function keys
  670. for name, const in zip(_KEY_NAMES, FUNCTION_KEYS):
  671. setattr(ServerProtocol, name, const)
  672. class ClientProtocol(protocol.Protocol):
  673. terminalFactory = None
  674. terminal = None
  675. state = b'data'
  676. _escBuf = None
  677. _shorts = {
  678. b'D': b'index',
  679. b'M': b'reverseIndex',
  680. b'E': b'nextLine',
  681. b'7': b'saveCursor',
  682. b'8': b'restoreCursor',
  683. b'=': b'applicationKeypadMode',
  684. b'>': b'numericKeypadMode',
  685. b'N': b'singleShift2',
  686. b'O': b'singleShift3',
  687. b'H': b'horizontalTabulationSet',
  688. b'c': b'reset'}
  689. _longs = {
  690. b'[': b'bracket-escape',
  691. b'(': b'select-g0',
  692. b')': b'select-g1',
  693. b'#': b'select-height-width'}
  694. _charsets = {
  695. b'A': CS_UK,
  696. b'B': CS_US,
  697. b'0': CS_DRAWING,
  698. b'1': CS_ALTERNATE,
  699. b'2': CS_ALTERNATE_SPECIAL}
  700. # Factory who instantiated me
  701. factory = None
  702. def __init__(self, terminalFactory=None, *a, **kw):
  703. """
  704. @param terminalFactory: A callable which will be invoked with
  705. *a, **kw and should return an ITerminalTransport provider.
  706. This will be invoked when this ClientProtocol establishes a
  707. connection.
  708. @param a: Any positional arguments to pass to terminalFactory.
  709. @param kw: Any keyword arguments to pass to terminalFactory.
  710. """
  711. # assert terminalFactory is None or ITerminalTransport.implementedBy(terminalFactory), "ClientProtocol.__init__ must be passed an ITerminalTransport implementor"
  712. if terminalFactory is not None:
  713. self.terminalFactory = terminalFactory
  714. self.terminalArgs = a
  715. self.terminalKwArgs = kw
  716. def connectionMade(self):
  717. if self.terminalFactory is not None:
  718. self.terminal = self.terminalFactory(*self.terminalArgs, **self.terminalKwArgs)
  719. self.terminal.factory = self.factory
  720. self.terminal.makeConnection(self)
  721. def connectionLost(self, reason):
  722. if self.terminal is not None:
  723. try:
  724. self.terminal.connectionLost(reason)
  725. finally:
  726. del self.terminal
  727. def dataReceived(self, data):
  728. """
  729. Parse the given data from a terminal server, dispatching to event
  730. handlers defined by C{self.terminal}.
  731. """
  732. toWrite = []
  733. for b in iterbytes(data):
  734. if self.state == b'data':
  735. if b == b'\x1b':
  736. if toWrite:
  737. self.terminal.write(b''.join(toWrite))
  738. del toWrite[:]
  739. self.state = b'escaped'
  740. elif b == b'\x14':
  741. if toWrite:
  742. self.terminal.write(b''.join(toWrite))
  743. del toWrite[:]
  744. self.terminal.shiftOut()
  745. elif b == b'\x15':
  746. if toWrite:
  747. self.terminal.write(b''.join(toWrite))
  748. del toWrite[:]
  749. self.terminal.shiftIn()
  750. elif b == b'\x08':
  751. if toWrite:
  752. self.terminal.write(b''.join(toWrite))
  753. del toWrite[:]
  754. self.terminal.cursorBackward()
  755. else:
  756. toWrite.append(b)
  757. elif self.state == b'escaped':
  758. fName = self._shorts.get(b)
  759. if fName is not None:
  760. self.state = b'data'
  761. getattr(self.terminal, fName.decode("ascii"))()
  762. else:
  763. state = self._longs.get(b)
  764. if state is not None:
  765. self.state = state
  766. else:
  767. self.terminal.unhandledControlSequence(b'\x1b' + b)
  768. self.state = b'data'
  769. elif self.state == b'bracket-escape':
  770. if self._escBuf is None:
  771. self._escBuf = []
  772. if b.isalpha() or b == b'~':
  773. self._handleControlSequence(b''.join(self._escBuf), b)
  774. del self._escBuf
  775. self.state = b'data'
  776. else:
  777. self._escBuf.append(b)
  778. elif self.state == b'select-g0':
  779. self.terminal.selectCharacterSet(self._charsets.get(b, b), G0)
  780. self.state = b'data'
  781. elif self.state == b'select-g1':
  782. self.terminal.selectCharacterSet(self._charsets.get(b, b), G1)
  783. self.state = b'data'
  784. elif self.state == b'select-height-width':
  785. self._handleHeightWidth(b)
  786. self.state = b'data'
  787. else:
  788. raise ValueError("Illegal state")
  789. if toWrite:
  790. self.terminal.write(b''.join(toWrite))
  791. def _handleControlSequence(self, buf, terminal):
  792. f = getattr(self.controlSequenceParser, CST.get(terminal, terminal).decode("ascii"), None)
  793. if f is None:
  794. self.terminal.unhandledControlSequence(b'\x1b[' + buf + terminal)
  795. else:
  796. f(self, self.terminal, buf)
  797. class ControlSequenceParser:
  798. def _makeSimple(ch, fName):
  799. n = 'cursor' + fName
  800. def simple(self, proto, handler, buf):
  801. if not buf:
  802. getattr(handler, n)(1)
  803. else:
  804. try:
  805. m = int(buf)
  806. except ValueError:
  807. handler.unhandledControlSequence(b'\x1b[' + buf + ch)
  808. else:
  809. getattr(handler, n)(m)
  810. return simple
  811. for (ch, fName) in (('A', 'Up'),
  812. ('B', 'Down'),
  813. ('C', 'Forward'),
  814. ('D', 'Backward')):
  815. exec(ch + " = _makeSimple(ch, fName)")
  816. del _makeSimple
  817. def h(self, proto, handler, buf):
  818. # XXX - Handle '?' to introduce ANSI-Compatible private modes.
  819. try:
  820. modes = [int(mode) for mode in buf.split(b';')]
  821. except ValueError:
  822. handler.unhandledControlSequence(b'\x1b[' + buf + b'h')
  823. else:
  824. handler.setModes(modes)
  825. def l(self, proto, handler, buf):
  826. # XXX - Handle '?' to introduce ANSI-Compatible private modes.
  827. try:
  828. modes = [int(mode) for mode in buf.split(b';')]
  829. except ValueError:
  830. handler.unhandledControlSequence(b'\x1b[' + buf + 'l')
  831. else:
  832. handler.resetModes(modes)
  833. def r(self, proto, handler, buf):
  834. parts = buf.split(b';')
  835. if len(parts) == 1:
  836. handler.setScrollRegion(None, None)
  837. elif len(parts) == 2:
  838. try:
  839. if parts[0]:
  840. pt = int(parts[0])
  841. else:
  842. pt = None
  843. if parts[1]:
  844. pb = int(parts[1])
  845. else:
  846. pb = None
  847. except ValueError:
  848. handler.unhandledControlSequence(b'\x1b[' + buf + b'r')
  849. else:
  850. handler.setScrollRegion(pt, pb)
  851. else:
  852. handler.unhandledControlSequence(b'\x1b[' + buf + b'r')
  853. def K(self, proto, handler, buf):
  854. if not buf:
  855. handler.eraseToLineEnd()
  856. elif buf == b'1':
  857. handler.eraseToLineBeginning()
  858. elif buf == b'2':
  859. handler.eraseLine()
  860. else:
  861. handler.unhandledControlSequence(b'\x1b[' + buf + b'K')
  862. def H(self, proto, handler, buf):
  863. handler.cursorHome()
  864. def J(self, proto, handler, buf):
  865. if not buf:
  866. handler.eraseToDisplayEnd()
  867. elif buf == b'1':
  868. handler.eraseToDisplayBeginning()
  869. elif buf == b'2':
  870. handler.eraseDisplay()
  871. else:
  872. handler.unhandledControlSequence(b'\x1b[' + buf + b'J')
  873. def P(self, proto, handler, buf):
  874. if not buf:
  875. handler.deleteCharacter(1)
  876. else:
  877. try:
  878. n = int(buf)
  879. except ValueError:
  880. handler.unhandledControlSequence(b'\x1b[' + buf + b'P')
  881. else:
  882. handler.deleteCharacter(n)
  883. def L(self, proto, handler, buf):
  884. if not buf:
  885. handler.insertLine(1)
  886. else:
  887. try:
  888. n = int(buf)
  889. except ValueError:
  890. handler.unhandledControlSequence(b'\x1b[' + buf + b'L')
  891. else:
  892. handler.insertLine(n)
  893. def M(self, proto, handler, buf):
  894. if not buf:
  895. handler.deleteLine(1)
  896. else:
  897. try:
  898. n = int(buf)
  899. except ValueError:
  900. handler.unhandledControlSequence(b'\x1b[' + buf + b'M')
  901. else:
  902. handler.deleteLine(n)
  903. def n(self, proto, handler, buf):
  904. if buf == b'6':
  905. x, y = handler.reportCursorPosition()
  906. proto.transport.write(b'\x1b['
  907. + intToBytes(x+1)
  908. + b';'
  909. + intToBytes(y+1)
  910. + b'R')
  911. else:
  912. handler.unhandledControlSequence(b'\x1b[' + buf + b'n')
  913. def m(self, proto, handler, buf):
  914. if not buf:
  915. handler.selectGraphicRendition(NORMAL)
  916. else:
  917. attrs = []
  918. for a in buf.split(b';'):
  919. try:
  920. a = int(a)
  921. except ValueError:
  922. pass
  923. attrs.append(a)
  924. handler.selectGraphicRendition(*attrs)
  925. controlSequenceParser = ControlSequenceParser()
  926. def _handleHeightWidth(self, b):
  927. if b == b'3':
  928. self.terminal.doubleHeightLine(True)
  929. elif b == b'4':
  930. self.terminal.doubleHeightLine(False)
  931. elif b == b'5':
  932. self.terminal.singleWidthLine()
  933. elif b == b'6':
  934. self.terminal.doubleWidthLine()
  935. else:
  936. self.terminal.unhandledControlSequence(b'\x1b#' + b)
  937. __all__ = [
  938. # Interfaces
  939. 'ITerminalProtocol', 'ITerminalTransport',
  940. # Symbolic constants
  941. 'modes', 'privateModes', 'FUNCTION_KEYS',
  942. 'CS_US', 'CS_UK', 'CS_DRAWING', 'CS_ALTERNATE', 'CS_ALTERNATE_SPECIAL',
  943. 'G0', 'G1', 'G2', 'G3',
  944. 'UNDERLINE', 'REVERSE_VIDEO', 'BLINK', 'BOLD', 'NORMAL',
  945. # Protocol classes
  946. 'ServerProtocol', 'ClientProtocol']