renderer.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. """
  2. Renders the command line on the console.
  3. (Redraws parts of the input line that were changed.)
  4. """
  5. from __future__ import unicode_literals
  6. from prompt_toolkit.filters import to_cli_filter
  7. from prompt_toolkit.layout.mouse_handlers import MouseHandlers
  8. from prompt_toolkit.layout.screen import Point, Screen, WritePosition
  9. from prompt_toolkit.output import Output
  10. from prompt_toolkit.styles import Style
  11. from prompt_toolkit.token import Token
  12. from prompt_toolkit.utils import is_windows
  13. from six.moves import range
  14. __all__ = (
  15. 'Renderer',
  16. 'print_tokens',
  17. )
  18. def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_token=None,
  19. is_done=False, use_alternate_screen=False, attrs_for_token=None, size=None,
  20. previous_width=0): # XXX: drop is_done
  21. """
  22. Render the diff between this screen and the previous screen.
  23. This takes two `Screen` instances. The one that represents the output like
  24. it was during the last rendering and one that represents the current
  25. output raster. Looking at these two `Screen` instances, this function will
  26. render the difference by calling the appropriate methods of the `Output`
  27. object that only paint the changes to the terminal.
  28. This is some performance-critical code which is heavily optimized.
  29. Don't change things without profiling first.
  30. :param current_pos: Current cursor position.
  31. :param last_token: `Token` instance that represents the output attributes of
  32. the last drawn character. (Color/attributes.)
  33. :param attrs_for_token: :class:`._TokenToAttrsCache` instance.
  34. :param width: The width of the terminal.
  35. :param prevous_width: The width of the terminal during the last rendering.
  36. """
  37. width, height = size.columns, size.rows
  38. #: Remember the last printed character.
  39. last_token = [last_token] # nonlocal
  40. #: Variable for capturing the output.
  41. write = output.write
  42. write_raw = output.write_raw
  43. # Create locals for the most used output methods.
  44. # (Save expensive attribute lookups.)
  45. _output_set_attributes = output.set_attributes
  46. _output_reset_attributes = output.reset_attributes
  47. _output_cursor_forward = output.cursor_forward
  48. _output_cursor_up = output.cursor_up
  49. _output_cursor_backward = output.cursor_backward
  50. # Hide cursor before rendering. (Avoid flickering.)
  51. output.hide_cursor()
  52. def reset_attributes():
  53. " Wrapper around Output.reset_attributes. "
  54. _output_reset_attributes()
  55. last_token[0] = None # Forget last char after resetting attributes.
  56. def move_cursor(new):
  57. " Move cursor to this `new` point. Returns the given Point. "
  58. current_x, current_y = current_pos.x, current_pos.y
  59. if new.y > current_y:
  60. # Use newlines instead of CURSOR_DOWN, because this meight add new lines.
  61. # CURSOR_DOWN will never create new lines at the bottom.
  62. # Also reset attributes, otherwise the newline could draw a
  63. # background color.
  64. reset_attributes()
  65. write('\r\n' * (new.y - current_y))
  66. current_x = 0
  67. _output_cursor_forward(new.x)
  68. return new
  69. elif new.y < current_y:
  70. _output_cursor_up(current_y - new.y)
  71. if current_x >= width - 1:
  72. write('\r')
  73. _output_cursor_forward(new.x)
  74. elif new.x < current_x or current_x >= width - 1:
  75. _output_cursor_backward(current_x - new.x)
  76. elif new.x > current_x:
  77. _output_cursor_forward(new.x - current_x)
  78. return new
  79. def output_char(char):
  80. """
  81. Write the output of this character.
  82. """
  83. # If the last printed character has the same token, it also has the
  84. # same style, so we don't output it.
  85. the_last_token = last_token[0]
  86. if the_last_token and the_last_token == char.token:
  87. write(char.char)
  88. else:
  89. _output_set_attributes(attrs_for_token[char.token])
  90. write(char.char)
  91. last_token[0] = char.token
  92. # Render for the first time: reset styling.
  93. if not previous_screen:
  94. reset_attributes()
  95. # Disable autowrap. (When entering a the alternate screen, or anytime when
  96. # we have a prompt. - In the case of a REPL, like IPython, people can have
  97. # background threads, and it's hard for debugging if their output is not
  98. # wrapped.)
  99. if not previous_screen or not use_alternate_screen:
  100. output.disable_autowrap()
  101. # When the previous screen has a different size, redraw everything anyway.
  102. # Also when we are done. (We meight take up less rows, so clearing is important.)
  103. if is_done or not previous_screen or previous_width != width: # XXX: also consider height??
  104. current_pos = move_cursor(Point(0, 0))
  105. reset_attributes()
  106. output.erase_down()
  107. previous_screen = Screen()
  108. # Get height of the screen.
  109. # (height changes as we loop over data_buffer, so remember the current value.)
  110. # (Also make sure to clip the height to the size of the output.)
  111. current_height = min(screen.height, height)
  112. # Loop over the rows.
  113. row_count = min(max(screen.height, previous_screen.height), height)
  114. c = 0 # Column counter.
  115. for y in range(row_count):
  116. new_row = screen.data_buffer[y]
  117. previous_row = previous_screen.data_buffer[y]
  118. zero_width_escapes_row = screen.zero_width_escapes[y]
  119. new_max_line_len = min(width - 1, max(new_row.keys()) if new_row else 0)
  120. previous_max_line_len = min(width - 1, max(previous_row.keys()) if previous_row else 0)
  121. # Loop over the columns.
  122. c = 0
  123. while c < new_max_line_len + 1:
  124. new_char = new_row[c]
  125. old_char = previous_row[c]
  126. char_width = (new_char.width or 1)
  127. # When the old and new character at this position are different,
  128. # draw the output. (Because of the performance, we don't call
  129. # `Char.__ne__`, but inline the same expression.)
  130. if new_char.char != old_char.char or new_char.token != old_char.token:
  131. current_pos = move_cursor(Point(y=y, x=c))
  132. # Send injected escape sequences to output.
  133. if c in zero_width_escapes_row:
  134. write_raw(zero_width_escapes_row[c])
  135. output_char(new_char)
  136. current_pos = current_pos._replace(x=current_pos.x + char_width)
  137. c += char_width
  138. # If the new line is shorter, trim it.
  139. if previous_screen and new_max_line_len < previous_max_line_len:
  140. current_pos = move_cursor(Point(y=y, x=new_max_line_len+1))
  141. reset_attributes()
  142. output.erase_end_of_line()
  143. # Correctly reserve vertical space as required by the layout.
  144. # When this is a new screen (drawn for the first time), or for some reason
  145. # higher than the previous one. Move the cursor once to the bottom of the
  146. # output. That way, we're sure that the terminal scrolls up, even when the
  147. # lower lines of the canvas just contain whitespace.
  148. # The most obvious reason that we actually want this behaviour is the avoid
  149. # the artifact of the input scrolling when the completion menu is shown.
  150. # (If the scrolling is actually wanted, the layout can still be build in a
  151. # way to behave that way by setting a dynamic height.)
  152. if current_height > previous_screen.height:
  153. current_pos = move_cursor(Point(y=current_height - 1, x=0))
  154. # Move cursor:
  155. if is_done:
  156. current_pos = move_cursor(Point(y=current_height, x=0))
  157. output.erase_down()
  158. else:
  159. current_pos = move_cursor(screen.cursor_position)
  160. if is_done or not use_alternate_screen:
  161. output.enable_autowrap()
  162. # Always reset the color attributes. This is important because a background
  163. # thread could print data to stdout and we want that to be displayed in the
  164. # default colors. (Also, if a background color has been set, many terminals
  165. # give weird artifacs on resize events.)
  166. reset_attributes()
  167. if screen.show_cursor or is_done:
  168. output.show_cursor()
  169. return current_pos, last_token[0]
  170. class HeightIsUnknownError(Exception):
  171. " Information unavailable. Did not yet receive the CPR response. "
  172. class _TokenToAttrsCache(dict):
  173. """
  174. A cache structure that maps Pygments Tokens to :class:`.Attr`.
  175. (This is an important speed up.)
  176. """
  177. def __init__(self, get_style_for_token):
  178. self.get_style_for_token = get_style_for_token
  179. def __missing__(self, token):
  180. try:
  181. result = self.get_style_for_token(token)
  182. except KeyError:
  183. result = None
  184. self[token] = result
  185. return result
  186. class Renderer(object):
  187. """
  188. Typical usage:
  189. ::
  190. output = Vt100_Output.from_pty(sys.stdout)
  191. r = Renderer(style, output)
  192. r.render(cli, layout=...)
  193. """
  194. def __init__(self, style, output, use_alternate_screen=False, mouse_support=False):
  195. assert isinstance(style, Style)
  196. assert isinstance(output, Output)
  197. self.style = style
  198. self.output = output
  199. self.use_alternate_screen = use_alternate_screen
  200. self.mouse_support = to_cli_filter(mouse_support)
  201. self._in_alternate_screen = False
  202. self._mouse_support_enabled = False
  203. self._bracketed_paste_enabled = False
  204. # Waiting for CPR flag. True when we send the request, but didn't got a
  205. # response.
  206. self.waiting_for_cpr = False
  207. self.reset(_scroll=True)
  208. def reset(self, _scroll=False, leave_alternate_screen=True):
  209. # Reset position
  210. self._cursor_pos = Point(x=0, y=0)
  211. # Remember the last screen instance between renderers. This way,
  212. # we can create a `diff` between two screens and only output the
  213. # difference. It's also to remember the last height. (To show for
  214. # instance a toolbar at the bottom position.)
  215. self._last_screen = None
  216. self._last_size = None
  217. self._last_token = None
  218. # When the style hash changes, we have to do a full redraw as well as
  219. # clear the `_attrs_for_token` dictionary.
  220. self._last_style_hash = None
  221. self._attrs_for_token = None
  222. # Default MouseHandlers. (Just empty.)
  223. self.mouse_handlers = MouseHandlers()
  224. # Remember the last title. Only set the title when it changes.
  225. self._last_title = None
  226. #: Space from the top of the layout, until the bottom of the terminal.
  227. #: We don't know this until a `report_absolute_cursor_row` call.
  228. self._min_available_height = 0
  229. # In case of Windown, also make sure to scroll to the current cursor
  230. # position. (Only when rendering the first time.)
  231. if is_windows() and _scroll:
  232. self.output.scroll_buffer_to_prompt()
  233. # Quit alternate screen.
  234. if self._in_alternate_screen and leave_alternate_screen:
  235. self.output.quit_alternate_screen()
  236. self._in_alternate_screen = False
  237. # Disable mouse support.
  238. if self._mouse_support_enabled:
  239. self.output.disable_mouse_support()
  240. self._mouse_support_enabled = False
  241. # Disable bracketed paste.
  242. if self._bracketed_paste_enabled:
  243. self.output.disable_bracketed_paste()
  244. self._bracketed_paste_enabled = False
  245. # Flush output. `disable_mouse_support` needs to write to stdout.
  246. self.output.flush()
  247. @property
  248. def height_is_known(self):
  249. """
  250. True when the height from the cursor until the bottom of the terminal
  251. is known. (It's often nicer to draw bottom toolbars only if the height
  252. is known, in order to avoid flickering when the CPR response arrives.)
  253. """
  254. return self.use_alternate_screen or self._min_available_height > 0 or \
  255. is_windows() # On Windows, we don't have to wait for a CPR.
  256. @property
  257. def rows_above_layout(self):
  258. """
  259. Return the number of rows visible in the terminal above the layout.
  260. """
  261. if self._in_alternate_screen:
  262. return 0
  263. elif self._min_available_height > 0:
  264. total_rows = self.output.get_size().rows
  265. last_screen_height = self._last_screen.height if self._last_screen else 0
  266. return total_rows - max(self._min_available_height, last_screen_height)
  267. else:
  268. raise HeightIsUnknownError('Rows above layout is unknown.')
  269. def request_absolute_cursor_position(self):
  270. """
  271. Get current cursor position.
  272. For vt100: Do CPR request. (answer will arrive later.)
  273. For win32: Do API call. (Answer comes immediately.)
  274. """
  275. # Only do this request when the cursor is at the top row. (after a
  276. # clear or reset). We will rely on that in `report_absolute_cursor_row`.
  277. assert self._cursor_pos.y == 0
  278. # For Win32, we have an API call to get the number of rows below the
  279. # cursor.
  280. if is_windows():
  281. self._min_available_height = self.output.get_rows_below_cursor_position()
  282. else:
  283. if self.use_alternate_screen:
  284. self._min_available_height = self.output.get_size().rows
  285. else:
  286. # Asks for a cursor position report (CPR).
  287. self.waiting_for_cpr = True
  288. self.output.ask_for_cpr()
  289. def report_absolute_cursor_row(self, row):
  290. """
  291. To be called when we know the absolute cursor position.
  292. (As an answer of a "Cursor Position Request" response.)
  293. """
  294. # Calculate the amount of rows from the cursor position until the
  295. # bottom of the terminal.
  296. total_rows = self.output.get_size().rows
  297. rows_below_cursor = total_rows - row + 1
  298. # Set the
  299. self._min_available_height = rows_below_cursor
  300. self.waiting_for_cpr = False
  301. def render(self, cli, layout, is_done=False):
  302. """
  303. Render the current interface to the output.
  304. :param is_done: When True, put the cursor at the end of the interface. We
  305. won't print any changes to this part.
  306. """
  307. output = self.output
  308. # Enter alternate screen.
  309. if self.use_alternate_screen and not self._in_alternate_screen:
  310. self._in_alternate_screen = True
  311. output.enter_alternate_screen()
  312. # Enable bracketed paste.
  313. if not self._bracketed_paste_enabled:
  314. self.output.enable_bracketed_paste()
  315. self._bracketed_paste_enabled = True
  316. # Enable/disable mouse support.
  317. needs_mouse_support = self.mouse_support(cli)
  318. if needs_mouse_support and not self._mouse_support_enabled:
  319. output.enable_mouse_support()
  320. self._mouse_support_enabled = True
  321. elif not needs_mouse_support and self._mouse_support_enabled:
  322. output.disable_mouse_support()
  323. self._mouse_support_enabled = False
  324. # Create screen and write layout to it.
  325. size = output.get_size()
  326. screen = Screen()
  327. screen.show_cursor = False # Hide cursor by default, unless one of the
  328. # containers decides to display it.
  329. mouse_handlers = MouseHandlers()
  330. if is_done:
  331. height = 0 # When we are done, we don't necessary want to fill up until the bottom.
  332. else:
  333. height = self._last_screen.height if self._last_screen else 0
  334. height = max(self._min_available_height, height)
  335. # When te size changes, don't consider the previous screen.
  336. if self._last_size != size:
  337. self._last_screen = None
  338. # When we render using another style, do a full repaint. (Forget about
  339. # the previous rendered screen.)
  340. # (But note that we still use _last_screen to calculate the height.)
  341. if self.style.invalidation_hash() != self._last_style_hash:
  342. self._last_screen = None
  343. self._attrs_for_token = None
  344. if self._attrs_for_token is None:
  345. self._attrs_for_token = _TokenToAttrsCache(self.style.get_attrs_for_token)
  346. self._last_style_hash = self.style.invalidation_hash()
  347. layout.write_to_screen(cli, screen, mouse_handlers, WritePosition(
  348. xpos=0,
  349. ypos=0,
  350. width=size.columns,
  351. height=(size.rows if self.use_alternate_screen else height),
  352. extended_height=size.rows,
  353. ))
  354. # When grayed. Replace all tokens in the new screen.
  355. if cli.is_aborting or cli.is_exiting:
  356. screen.replace_all_tokens(Token.Aborted)
  357. # Process diff and write to output.
  358. self._cursor_pos, self._last_token = _output_screen_diff(
  359. output, screen, self._cursor_pos,
  360. self._last_screen, self._last_token, is_done,
  361. use_alternate_screen=self.use_alternate_screen,
  362. attrs_for_token=self._attrs_for_token,
  363. size=size,
  364. previous_width=(self._last_size.columns if self._last_size else 0))
  365. self._last_screen = screen
  366. self._last_size = size
  367. self.mouse_handlers = mouse_handlers
  368. # Write title if it changed.
  369. new_title = cli.terminal_title
  370. if new_title != self._last_title:
  371. if new_title is None:
  372. self.output.clear_title()
  373. else:
  374. self.output.set_title(new_title)
  375. self._last_title = new_title
  376. output.flush()
  377. def erase(self, leave_alternate_screen=True, erase_title=True):
  378. """
  379. Hide all output and put the cursor back at the first line. This is for
  380. instance used for running a system command (while hiding the CLI) and
  381. later resuming the same CLI.)
  382. :param leave_alternate_screen: When True, and when inside an alternate
  383. screen buffer, quit the alternate screen.
  384. :param erase_title: When True, clear the title from the title bar.
  385. """
  386. output = self.output
  387. output.cursor_backward(self._cursor_pos.x)
  388. output.cursor_up(self._cursor_pos.y)
  389. output.erase_down()
  390. output.reset_attributes()
  391. output.enable_autowrap()
  392. output.flush()
  393. # Erase title.
  394. if self._last_title and erase_title:
  395. output.clear_title()
  396. self.reset(leave_alternate_screen=leave_alternate_screen)
  397. def clear(self):
  398. """
  399. Clear screen and go to 0,0
  400. """
  401. # Erase current output first.
  402. self.erase()
  403. # Send "Erase Screen" command and go to (0, 0).
  404. output = self.output
  405. output.erase_screen()
  406. output.cursor_goto(0, 0)
  407. output.flush()
  408. self.request_absolute_cursor_position()
  409. def print_tokens(output, tokens, style):
  410. """
  411. Print a list of (Token, text) tuples in the given style to the output.
  412. """
  413. assert isinstance(output, Output)
  414. assert isinstance(style, Style)
  415. # Reset first.
  416. output.reset_attributes()
  417. output.enable_autowrap()
  418. # Print all (token, text) tuples.
  419. attrs_for_token = _TokenToAttrsCache(style.get_attrs_for_token)
  420. for token, text in tokens:
  421. attrs = attrs_for_token[token]
  422. if attrs:
  423. output.set_attributes(attrs)
  424. else:
  425. output.reset_attributes()
  426. output.write(text)
  427. # Reset again.
  428. output.reset_attributes()
  429. output.flush()