You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

351 lines
12 KiB

4 years ago
  1. '''This implements an ANSI (VT100) terminal emulator as a subclass of screen.
  2. PEXPECT LICENSE
  3. This license is approved by the OSI and FSF as GPL-compatible.
  4. http://opensource.org/licenses/isc-license.txt
  5. Copyright (c) 2012, Noah Spurrier <noah@noah.org>
  6. PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
  7. PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
  8. COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
  9. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. '''
  17. # references:
  18. # http://en.wikipedia.org/wiki/ANSI_escape_code
  19. # http://www.retards.org/terminals/vt102.html
  20. # http://vt100.net/docs/vt102-ug/contents.html
  21. # http://vt100.net/docs/vt220-rm/
  22. # http://www.termsys.demon.co.uk/vtansi.htm
  23. from . import screen
  24. from . import FSM
  25. import string
  26. #
  27. # The 'Do.*' functions are helper functions for the ANSI class.
  28. #
  29. def DoEmit (fsm):
  30. screen = fsm.memory[0]
  31. screen.write_ch(fsm.input_symbol)
  32. def DoStartNumber (fsm):
  33. fsm.memory.append (fsm.input_symbol)
  34. def DoBuildNumber (fsm):
  35. ns = fsm.memory.pop()
  36. ns = ns + fsm.input_symbol
  37. fsm.memory.append (ns)
  38. def DoBackOne (fsm):
  39. screen = fsm.memory[0]
  40. screen.cursor_back ()
  41. def DoBack (fsm):
  42. count = int(fsm.memory.pop())
  43. screen = fsm.memory[0]
  44. screen.cursor_back (count)
  45. def DoDownOne (fsm):
  46. screen = fsm.memory[0]
  47. screen.cursor_down ()
  48. def DoDown (fsm):
  49. count = int(fsm.memory.pop())
  50. screen = fsm.memory[0]
  51. screen.cursor_down (count)
  52. def DoForwardOne (fsm):
  53. screen = fsm.memory[0]
  54. screen.cursor_forward ()
  55. def DoForward (fsm):
  56. count = int(fsm.memory.pop())
  57. screen = fsm.memory[0]
  58. screen.cursor_forward (count)
  59. def DoUpReverse (fsm):
  60. screen = fsm.memory[0]
  61. screen.cursor_up_reverse()
  62. def DoUpOne (fsm):
  63. screen = fsm.memory[0]
  64. screen.cursor_up ()
  65. def DoUp (fsm):
  66. count = int(fsm.memory.pop())
  67. screen = fsm.memory[0]
  68. screen.cursor_up (count)
  69. def DoHome (fsm):
  70. c = int(fsm.memory.pop())
  71. r = int(fsm.memory.pop())
  72. screen = fsm.memory[0]
  73. screen.cursor_home (r,c)
  74. def DoHomeOrigin (fsm):
  75. c = 1
  76. r = 1
  77. screen = fsm.memory[0]
  78. screen.cursor_home (r,c)
  79. def DoEraseDown (fsm):
  80. screen = fsm.memory[0]
  81. screen.erase_down()
  82. def DoErase (fsm):
  83. arg = int(fsm.memory.pop())
  84. screen = fsm.memory[0]
  85. if arg == 0:
  86. screen.erase_down()
  87. elif arg == 1:
  88. screen.erase_up()
  89. elif arg == 2:
  90. screen.erase_screen()
  91. def DoEraseEndOfLine (fsm):
  92. screen = fsm.memory[0]
  93. screen.erase_end_of_line()
  94. def DoEraseLine (fsm):
  95. arg = int(fsm.memory.pop())
  96. screen = fsm.memory[0]
  97. if arg == 0:
  98. screen.erase_end_of_line()
  99. elif arg == 1:
  100. screen.erase_start_of_line()
  101. elif arg == 2:
  102. screen.erase_line()
  103. def DoEnableScroll (fsm):
  104. screen = fsm.memory[0]
  105. screen.scroll_screen()
  106. def DoCursorSave (fsm):
  107. screen = fsm.memory[0]
  108. screen.cursor_save_attrs()
  109. def DoCursorRestore (fsm):
  110. screen = fsm.memory[0]
  111. screen.cursor_restore_attrs()
  112. def DoScrollRegion (fsm):
  113. screen = fsm.memory[0]
  114. r2 = int(fsm.memory.pop())
  115. r1 = int(fsm.memory.pop())
  116. screen.scroll_screen_rows (r1,r2)
  117. def DoMode (fsm):
  118. screen = fsm.memory[0]
  119. mode = fsm.memory.pop() # Should be 4
  120. # screen.setReplaceMode ()
  121. def DoLog (fsm):
  122. screen = fsm.memory[0]
  123. fsm.memory = [screen]
  124. fout = open ('log', 'a')
  125. fout.write (fsm.input_symbol + ',' + fsm.current_state + '\n')
  126. fout.close()
  127. class term (screen.screen):
  128. '''This class is an abstract, generic terminal.
  129. This does nothing. This is a placeholder that
  130. provides a common base class for other terminals
  131. such as an ANSI terminal. '''
  132. def __init__ (self, r=24, c=80, *args, **kwargs):
  133. screen.screen.__init__(self, r,c,*args,**kwargs)
  134. class ANSI (term):
  135. '''This class implements an ANSI (VT100) terminal.
  136. It is a stream filter that recognizes ANSI terminal
  137. escape sequences and maintains the state of a screen object. '''
  138. def __init__ (self, r=24,c=80,*args,**kwargs):
  139. term.__init__(self,r,c,*args,**kwargs)
  140. #self.screen = screen (24,80)
  141. self.state = FSM.FSM ('INIT',[self])
  142. self.state.set_default_transition (DoLog, 'INIT')
  143. self.state.add_transition_any ('INIT', DoEmit, 'INIT')
  144. self.state.add_transition ('\x1b', 'INIT', None, 'ESC')
  145. self.state.add_transition_any ('ESC', DoLog, 'INIT')
  146. self.state.add_transition ('(', 'ESC', None, 'G0SCS')
  147. self.state.add_transition (')', 'ESC', None, 'G1SCS')
  148. self.state.add_transition_list ('AB012', 'G0SCS', None, 'INIT')
  149. self.state.add_transition_list ('AB012', 'G1SCS', None, 'INIT')
  150. self.state.add_transition ('7', 'ESC', DoCursorSave, 'INIT')
  151. self.state.add_transition ('8', 'ESC', DoCursorRestore, 'INIT')
  152. self.state.add_transition ('M', 'ESC', DoUpReverse, 'INIT')
  153. self.state.add_transition ('>', 'ESC', DoUpReverse, 'INIT')
  154. self.state.add_transition ('<', 'ESC', DoUpReverse, 'INIT')
  155. self.state.add_transition ('=', 'ESC', None, 'INIT') # Selects application keypad.
  156. self.state.add_transition ('#', 'ESC', None, 'GRAPHICS_POUND')
  157. self.state.add_transition_any ('GRAPHICS_POUND', None, 'INIT')
  158. self.state.add_transition ('[', 'ESC', None, 'ELB')
  159. # ELB means Escape Left Bracket. That is ^[[
  160. self.state.add_transition ('H', 'ELB', DoHomeOrigin, 'INIT')
  161. self.state.add_transition ('D', 'ELB', DoBackOne, 'INIT')
  162. self.state.add_transition ('B', 'ELB', DoDownOne, 'INIT')
  163. self.state.add_transition ('C', 'ELB', DoForwardOne, 'INIT')
  164. self.state.add_transition ('A', 'ELB', DoUpOne, 'INIT')
  165. self.state.add_transition ('J', 'ELB', DoEraseDown, 'INIT')
  166. self.state.add_transition ('K', 'ELB', DoEraseEndOfLine, 'INIT')
  167. self.state.add_transition ('r', 'ELB', DoEnableScroll, 'INIT')
  168. self.state.add_transition ('m', 'ELB', self.do_sgr, 'INIT')
  169. self.state.add_transition ('?', 'ELB', None, 'MODECRAP')
  170. self.state.add_transition_list (string.digits, 'ELB', DoStartNumber, 'NUMBER_1')
  171. self.state.add_transition_list (string.digits, 'NUMBER_1', DoBuildNumber, 'NUMBER_1')
  172. self.state.add_transition ('D', 'NUMBER_1', DoBack, 'INIT')
  173. self.state.add_transition ('B', 'NUMBER_1', DoDown, 'INIT')
  174. self.state.add_transition ('C', 'NUMBER_1', DoForward, 'INIT')
  175. self.state.add_transition ('A', 'NUMBER_1', DoUp, 'INIT')
  176. self.state.add_transition ('J', 'NUMBER_1', DoErase, 'INIT')
  177. self.state.add_transition ('K', 'NUMBER_1', DoEraseLine, 'INIT')
  178. self.state.add_transition ('l', 'NUMBER_1', DoMode, 'INIT')
  179. ### It gets worse... the 'm' code can have infinite number of
  180. ### number;number;number before it. I've never seen more than two,
  181. ### but the specs say it's allowed. crap!
  182. self.state.add_transition ('m', 'NUMBER_1', self.do_sgr, 'INIT')
  183. ### LED control. Same implementation problem as 'm' code.
  184. self.state.add_transition ('q', 'NUMBER_1', self.do_decsca, 'INIT')
  185. # \E[?47h switch to alternate screen
  186. # \E[?47l restores to normal screen from alternate screen.
  187. self.state.add_transition_list (string.digits, 'MODECRAP', DoStartNumber, 'MODECRAP_NUM')
  188. self.state.add_transition_list (string.digits, 'MODECRAP_NUM', DoBuildNumber, 'MODECRAP_NUM')
  189. self.state.add_transition ('l', 'MODECRAP_NUM', self.do_modecrap, 'INIT')
  190. self.state.add_transition ('h', 'MODECRAP_NUM', self.do_modecrap, 'INIT')
  191. #RM Reset Mode Esc [ Ps l none
  192. self.state.add_transition (';', 'NUMBER_1', None, 'SEMICOLON')
  193. self.state.add_transition_any ('SEMICOLON', DoLog, 'INIT')
  194. self.state.add_transition_list (string.digits, 'SEMICOLON', DoStartNumber, 'NUMBER_2')
  195. self.state.add_transition_list (string.digits, 'NUMBER_2', DoBuildNumber, 'NUMBER_2')
  196. self.state.add_transition_any ('NUMBER_2', DoLog, 'INIT')
  197. self.state.add_transition ('H', 'NUMBER_2', DoHome, 'INIT')
  198. self.state.add_transition ('f', 'NUMBER_2', DoHome, 'INIT')
  199. self.state.add_transition ('r', 'NUMBER_2', DoScrollRegion, 'INIT')
  200. ### It gets worse... the 'm' code can have infinite number of
  201. ### number;number;number before it. I've never seen more than two,
  202. ### but the specs say it's allowed. crap!
  203. self.state.add_transition ('m', 'NUMBER_2', self.do_sgr, 'INIT')
  204. ### LED control. Same problem as 'm' code.
  205. self.state.add_transition ('q', 'NUMBER_2', self.do_decsca, 'INIT')
  206. self.state.add_transition (';', 'NUMBER_2', None, 'SEMICOLON_X')
  207. # Create a state for 'q' and 'm' which allows an infinite number of ignored numbers
  208. self.state.add_transition_any ('SEMICOLON_X', DoLog, 'INIT')
  209. self.state.add_transition_list (string.digits, 'SEMICOLON_X', DoStartNumber, 'NUMBER_X')
  210. self.state.add_transition_list (string.digits, 'NUMBER_X', DoBuildNumber, 'NUMBER_X')
  211. self.state.add_transition_any ('NUMBER_X', DoLog, 'INIT')
  212. self.state.add_transition ('m', 'NUMBER_X', self.do_sgr, 'INIT')
  213. self.state.add_transition ('q', 'NUMBER_X', self.do_decsca, 'INIT')
  214. self.state.add_transition (';', 'NUMBER_X', None, 'SEMICOLON_X')
  215. def process (self, c):
  216. """Process a single character. Called by :meth:`write`."""
  217. if isinstance(c, bytes):
  218. c = self._decode(c)
  219. self.state.process(c)
  220. def process_list (self, l):
  221. self.write(l)
  222. def write (self, s):
  223. """Process text, writing it to the virtual screen while handling
  224. ANSI escape codes.
  225. """
  226. if isinstance(s, bytes):
  227. s = self._decode(s)
  228. for c in s:
  229. self.process(c)
  230. def flush (self):
  231. pass
  232. def write_ch (self, ch):
  233. '''This puts a character at the current cursor position. The cursor
  234. position is moved forward with wrap-around, but no scrolling is done if
  235. the cursor hits the lower-right corner of the screen. '''
  236. if isinstance(ch, bytes):
  237. ch = self._decode(ch)
  238. #\r and \n both produce a call to cr() and lf(), respectively.
  239. ch = ch[0]
  240. if ch == u'\r':
  241. self.cr()
  242. return
  243. if ch == u'\n':
  244. self.crlf()
  245. return
  246. if ch == chr(screen.BS):
  247. self.cursor_back()
  248. return
  249. self.put_abs(self.cur_r, self.cur_c, ch)
  250. old_r = self.cur_r
  251. old_c = self.cur_c
  252. self.cursor_forward()
  253. if old_c == self.cur_c:
  254. self.cursor_down()
  255. if old_r != self.cur_r:
  256. self.cursor_home (self.cur_r, 1)
  257. else:
  258. self.scroll_up ()
  259. self.cursor_home (self.cur_r, 1)
  260. self.erase_line()
  261. def do_sgr (self, fsm):
  262. '''Select Graphic Rendition, e.g. color. '''
  263. screen = fsm.memory[0]
  264. fsm.memory = [screen]
  265. def do_decsca (self, fsm):
  266. '''Select character protection attribute. '''
  267. screen = fsm.memory[0]
  268. fsm.memory = [screen]
  269. def do_modecrap (self, fsm):
  270. '''Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone
  271. wanted to actually use these, they'd need to add more states to the
  272. FSM rather than just improve or override this method. '''
  273. screen = fsm.memory[0]
  274. fsm.memory = [screen]