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.

431 lines
13 KiB

4 years ago
  1. '''This implements a virtual screen. This is used to support ANSI terminal
  2. emulation. The screen representation and state is implemented in this class.
  3. Most of the methods are inspired by ANSI screen control codes. The
  4. :class:`~pexpect.ANSI.ANSI` class extends this class to add parsing of ANSI
  5. escape codes.
  6. PEXPECT LICENSE
  7. This license is approved by the OSI and FSF as GPL-compatible.
  8. http://opensource.org/licenses/isc-license.txt
  9. Copyright (c) 2012, Noah Spurrier <noah@noah.org>
  10. PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
  11. PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
  12. COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
  13. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  14. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  15. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  16. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  17. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  18. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  19. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  20. '''
  21. import codecs
  22. import copy
  23. import sys
  24. import warnings
  25. warnings.warn(("pexpect.screen and pexpect.ANSI are deprecated. "
  26. "We recommend using pyte to emulate a terminal screen: "
  27. "https://pypi.python.org/pypi/pyte"),
  28. stacklevel=2)
  29. NUL = 0 # Fill character; ignored on input.
  30. ENQ = 5 # Transmit answerback message.
  31. BEL = 7 # Ring the bell.
  32. BS = 8 # Move cursor left.
  33. HT = 9 # Move cursor to next tab stop.
  34. LF = 10 # Line feed.
  35. VT = 11 # Same as LF.
  36. FF = 12 # Same as LF.
  37. CR = 13 # Move cursor to left margin or newline.
  38. SO = 14 # Invoke G1 character set.
  39. SI = 15 # Invoke G0 character set.
  40. XON = 17 # Resume transmission.
  41. XOFF = 19 # Halt transmission.
  42. CAN = 24 # Cancel escape sequence.
  43. SUB = 26 # Same as CAN.
  44. ESC = 27 # Introduce a control sequence.
  45. DEL = 127 # Fill character; ignored on input.
  46. SPACE = u' ' # Space or blank character.
  47. PY3 = (sys.version_info[0] >= 3)
  48. if PY3:
  49. unicode = str
  50. def constrain (n, min, max):
  51. '''This returns a number, n constrained to the min and max bounds. '''
  52. if n < min:
  53. return min
  54. if n > max:
  55. return max
  56. return n
  57. class screen:
  58. '''This object maintains the state of a virtual text screen as a
  59. rectangular array. This maintains a virtual cursor position and handles
  60. scrolling as characters are added. This supports most of the methods needed
  61. by an ANSI text screen. Row and column indexes are 1-based (not zero-based,
  62. like arrays).
  63. Characters are represented internally using unicode. Methods that accept
  64. input characters, when passed 'bytes' (which in Python 2 is equivalent to
  65. 'str'), convert them from the encoding specified in the 'encoding'
  66. parameter to the constructor. Methods that return screen contents return
  67. unicode strings, with the exception of __str__() under Python 2. Passing
  68. ``encoding=None`` limits the API to only accept unicode input, so passing
  69. bytes in will raise :exc:`TypeError`.
  70. '''
  71. def __init__(self, r=24, c=80, encoding='latin-1', encoding_errors='replace'):
  72. '''This initializes a blank screen of the given dimensions.'''
  73. self.rows = r
  74. self.cols = c
  75. self.encoding = encoding
  76. self.encoding_errors = encoding_errors
  77. if encoding is not None:
  78. self.decoder = codecs.getincrementaldecoder(encoding)(encoding_errors)
  79. else:
  80. self.decoder = None
  81. self.cur_r = 1
  82. self.cur_c = 1
  83. self.cur_saved_r = 1
  84. self.cur_saved_c = 1
  85. self.scroll_row_start = 1
  86. self.scroll_row_end = self.rows
  87. self.w = [ [SPACE] * self.cols for _ in range(self.rows)]
  88. def _decode(self, s):
  89. '''This converts from the external coding system (as passed to
  90. the constructor) to the internal one (unicode). '''
  91. if self.decoder is not None:
  92. return self.decoder.decode(s)
  93. else:
  94. raise TypeError("This screen was constructed with encoding=None, "
  95. "so it does not handle bytes.")
  96. def _unicode(self):
  97. '''This returns a printable representation of the screen as a unicode
  98. string (which, under Python 3.x, is the same as 'str'). The end of each
  99. screen line is terminated by a newline.'''
  100. return u'\n'.join ([ u''.join(c) for c in self.w ])
  101. if PY3:
  102. __str__ = _unicode
  103. else:
  104. __unicode__ = _unicode
  105. def __str__(self):
  106. '''This returns a printable representation of the screen. The end of
  107. each screen line is terminated by a newline. '''
  108. encoding = self.encoding or 'ascii'
  109. return self._unicode().encode(encoding, 'replace')
  110. def dump (self):
  111. '''This returns a copy of the screen as a unicode string. This is similar to
  112. __str__/__unicode__ except that lines are not terminated with line
  113. feeds.'''
  114. return u''.join ([ u''.join(c) for c in self.w ])
  115. def pretty (self):
  116. '''This returns a copy of the screen as a unicode string with an ASCII
  117. text box around the screen border. This is similar to
  118. __str__/__unicode__ except that it adds a box.'''
  119. top_bot = u'+' + u'-'*self.cols + u'+\n'
  120. return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
  121. def fill (self, ch=SPACE):
  122. if isinstance(ch, bytes):
  123. ch = self._decode(ch)
  124. self.fill_region (1,1,self.rows,self.cols, ch)
  125. def fill_region (self, rs,cs, re,ce, ch=SPACE):
  126. if isinstance(ch, bytes):
  127. ch = self._decode(ch)
  128. rs = constrain (rs, 1, self.rows)
  129. re = constrain (re, 1, self.rows)
  130. cs = constrain (cs, 1, self.cols)
  131. ce = constrain (ce, 1, self.cols)
  132. if rs > re:
  133. rs, re = re, rs
  134. if cs > ce:
  135. cs, ce = ce, cs
  136. for r in range (rs, re+1):
  137. for c in range (cs, ce + 1):
  138. self.put_abs (r,c,ch)
  139. def cr (self):
  140. '''This moves the cursor to the beginning (col 1) of the current row.
  141. '''
  142. self.cursor_home (self.cur_r, 1)
  143. def lf (self):
  144. '''This moves the cursor down with scrolling.
  145. '''
  146. old_r = self.cur_r
  147. self.cursor_down()
  148. if old_r == self.cur_r:
  149. self.scroll_up ()
  150. self.erase_line()
  151. def crlf (self):
  152. '''This advances the cursor with CRLF properties.
  153. The cursor will line wrap and the screen may scroll.
  154. '''
  155. self.cr ()
  156. self.lf ()
  157. def newline (self):
  158. '''This is an alias for crlf().
  159. '''
  160. self.crlf()
  161. def put_abs (self, r, c, ch):
  162. '''Screen array starts at 1 index.'''
  163. r = constrain (r, 1, self.rows)
  164. c = constrain (c, 1, self.cols)
  165. if isinstance(ch, bytes):
  166. ch = self._decode(ch)[0]
  167. else:
  168. ch = ch[0]
  169. self.w[r-1][c-1] = ch
  170. def put (self, ch):
  171. '''This puts a characters at the current cursor position.
  172. '''
  173. if isinstance(ch, bytes):
  174. ch = self._decode(ch)
  175. self.put_abs (self.cur_r, self.cur_c, ch)
  176. def insert_abs (self, r, c, ch):
  177. '''This inserts a character at (r,c). Everything under
  178. and to the right is shifted right one character.
  179. The last character of the line is lost.
  180. '''
  181. if isinstance(ch, bytes):
  182. ch = self._decode(ch)
  183. r = constrain (r, 1, self.rows)
  184. c = constrain (c, 1, self.cols)
  185. for ci in range (self.cols, c, -1):
  186. self.put_abs (r,ci, self.get_abs(r,ci-1))
  187. self.put_abs (r,c,ch)
  188. def insert (self, ch):
  189. if isinstance(ch, bytes):
  190. ch = self._decode(ch)
  191. self.insert_abs (self.cur_r, self.cur_c, ch)
  192. def get_abs (self, r, c):
  193. r = constrain (r, 1, self.rows)
  194. c = constrain (c, 1, self.cols)
  195. return self.w[r-1][c-1]
  196. def get (self):
  197. self.get_abs (self.cur_r, self.cur_c)
  198. def get_region (self, rs,cs, re,ce):
  199. '''This returns a list of lines representing the region.
  200. '''
  201. rs = constrain (rs, 1, self.rows)
  202. re = constrain (re, 1, self.rows)
  203. cs = constrain (cs, 1, self.cols)
  204. ce = constrain (ce, 1, self.cols)
  205. if rs > re:
  206. rs, re = re, rs
  207. if cs > ce:
  208. cs, ce = ce, cs
  209. sc = []
  210. for r in range (rs, re+1):
  211. line = u''
  212. for c in range (cs, ce + 1):
  213. ch = self.get_abs (r,c)
  214. line = line + ch
  215. sc.append (line)
  216. return sc
  217. def cursor_constrain (self):
  218. '''This keeps the cursor within the screen area.
  219. '''
  220. self.cur_r = constrain (self.cur_r, 1, self.rows)
  221. self.cur_c = constrain (self.cur_c, 1, self.cols)
  222. def cursor_home (self, r=1, c=1): # <ESC>[{ROW};{COLUMN}H
  223. self.cur_r = r
  224. self.cur_c = c
  225. self.cursor_constrain ()
  226. def cursor_back (self,count=1): # <ESC>[{COUNT}D (not confused with down)
  227. self.cur_c = self.cur_c - count
  228. self.cursor_constrain ()
  229. def cursor_down (self,count=1): # <ESC>[{COUNT}B (not confused with back)
  230. self.cur_r = self.cur_r + count
  231. self.cursor_constrain ()
  232. def cursor_forward (self,count=1): # <ESC>[{COUNT}C
  233. self.cur_c = self.cur_c + count
  234. self.cursor_constrain ()
  235. def cursor_up (self,count=1): # <ESC>[{COUNT}A
  236. self.cur_r = self.cur_r - count
  237. self.cursor_constrain ()
  238. def cursor_up_reverse (self): # <ESC> M (called RI -- Reverse Index)
  239. old_r = self.cur_r
  240. self.cursor_up()
  241. if old_r == self.cur_r:
  242. self.scroll_up()
  243. def cursor_force_position (self, r, c): # <ESC>[{ROW};{COLUMN}f
  244. '''Identical to Cursor Home.'''
  245. self.cursor_home (r, c)
  246. def cursor_save (self): # <ESC>[s
  247. '''Save current cursor position.'''
  248. self.cursor_save_attrs()
  249. def cursor_unsave (self): # <ESC>[u
  250. '''Restores cursor position after a Save Cursor.'''
  251. self.cursor_restore_attrs()
  252. def cursor_save_attrs (self): # <ESC>7
  253. '''Save current cursor position.'''
  254. self.cur_saved_r = self.cur_r
  255. self.cur_saved_c = self.cur_c
  256. def cursor_restore_attrs (self): # <ESC>8
  257. '''Restores cursor position after a Save Cursor.'''
  258. self.cursor_home (self.cur_saved_r, self.cur_saved_c)
  259. def scroll_constrain (self):
  260. '''This keeps the scroll region within the screen region.'''
  261. if self.scroll_row_start <= 0:
  262. self.scroll_row_start = 1
  263. if self.scroll_row_end > self.rows:
  264. self.scroll_row_end = self.rows
  265. def scroll_screen (self): # <ESC>[r
  266. '''Enable scrolling for entire display.'''
  267. self.scroll_row_start = 1
  268. self.scroll_row_end = self.rows
  269. def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r
  270. '''Enable scrolling from row {start} to row {end}.'''
  271. self.scroll_row_start = rs
  272. self.scroll_row_end = re
  273. self.scroll_constrain()
  274. def scroll_down (self): # <ESC>D
  275. '''Scroll display down one line.'''
  276. # Screen is indexed from 1, but arrays are indexed from 0.
  277. s = self.scroll_row_start - 1
  278. e = self.scroll_row_end - 1
  279. self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])
  280. def scroll_up (self): # <ESC>M
  281. '''Scroll display up one line.'''
  282. # Screen is indexed from 1, but arrays are indexed from 0.
  283. s = self.scroll_row_start - 1
  284. e = self.scroll_row_end - 1
  285. self.w[s:e] = copy.deepcopy(self.w[s+1:e+1])
  286. def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K
  287. '''Erases from the current cursor position to the end of the current
  288. line.'''
  289. self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols)
  290. def erase_start_of_line (self): # <ESC>[1K
  291. '''Erases from the current cursor position to the start of the current
  292. line.'''
  293. self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c)
  294. def erase_line (self): # <ESC>[2K
  295. '''Erases the entire current line.'''
  296. self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
  297. def erase_down (self): # <ESC>[0J -or- <ESC>[J
  298. '''Erases the screen from the current line down to the bottom of the
  299. screen.'''
  300. self.erase_end_of_line ()
  301. self.fill_region (self.cur_r + 1, 1, self.rows, self.cols)
  302. def erase_up (self): # <ESC>[1J
  303. '''Erases the screen from the current line up to the top of the
  304. screen.'''
  305. self.erase_start_of_line ()
  306. self.fill_region (self.cur_r-1, 1, 1, self.cols)
  307. def erase_screen (self): # <ESC>[2J
  308. '''Erases the screen with the background color.'''
  309. self.fill ()
  310. def set_tab (self): # <ESC>H
  311. '''Sets a tab at the current position.'''
  312. pass
  313. def clear_tab (self): # <ESC>[g
  314. '''Clears tab at the current position.'''
  315. pass
  316. def clear_all_tabs (self): # <ESC>[3g
  317. '''Clears all tabs.'''
  318. pass
  319. # Insert line Esc [ Pn L
  320. # Delete line Esc [ Pn M
  321. # Delete character Esc [ Pn P
  322. # Scrolling region Esc [ Pn(top);Pn(bot) r