renderer.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. """
  2. Renders the command line on the console.
  3. (Redraws parts of the input line that were changed.)
  4. """
  5. from __future__ import annotations
  6. from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait
  7. from collections import deque
  8. from enum import Enum
  9. from typing import TYPE_CHECKING, Any, Callable, Dict, Hashable
  10. from prompt_toolkit.application.current import get_app
  11. from prompt_toolkit.cursor_shapes import CursorShape
  12. from prompt_toolkit.data_structures import Point, Size
  13. from prompt_toolkit.filters import FilterOrBool, to_filter
  14. from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text
  15. from prompt_toolkit.layout.mouse_handlers import MouseHandlers
  16. from prompt_toolkit.layout.screen import Char, Screen, WritePosition
  17. from prompt_toolkit.output import ColorDepth, Output
  18. from prompt_toolkit.styles import (
  19. Attrs,
  20. BaseStyle,
  21. DummyStyleTransformation,
  22. StyleTransformation,
  23. )
  24. if TYPE_CHECKING:
  25. from prompt_toolkit.application import Application
  26. from prompt_toolkit.layout.layout import Layout
  27. __all__ = [
  28. "Renderer",
  29. "print_formatted_text",
  30. ]
  31. def _output_screen_diff(
  32. app: Application[Any],
  33. output: Output,
  34. screen: Screen,
  35. current_pos: Point,
  36. color_depth: ColorDepth,
  37. previous_screen: Screen | None,
  38. last_style: str | None,
  39. is_done: bool, # XXX: drop is_done
  40. full_screen: bool,
  41. attrs_for_style_string: _StyleStringToAttrsCache,
  42. style_string_has_style: _StyleStringHasStyleCache,
  43. size: Size,
  44. previous_width: int,
  45. ) -> tuple[Point, str | None]:
  46. """
  47. Render the diff between this screen and the previous screen.
  48. This takes two `Screen` instances. The one that represents the output like
  49. it was during the last rendering and one that represents the current
  50. output raster. Looking at these two `Screen` instances, this function will
  51. render the difference by calling the appropriate methods of the `Output`
  52. object that only paint the changes to the terminal.
  53. This is some performance-critical code which is heavily optimized.
  54. Don't change things without profiling first.
  55. :param current_pos: Current cursor position.
  56. :param last_style: The style string, used for drawing the last drawn
  57. character. (Color/attributes.)
  58. :param attrs_for_style_string: :class:`._StyleStringToAttrsCache` instance.
  59. :param width: The width of the terminal.
  60. :param previous_width: The width of the terminal during the last rendering.
  61. """
  62. width, height = size.columns, size.rows
  63. #: Variable for capturing the output.
  64. write = output.write
  65. write_raw = output.write_raw
  66. # Create locals for the most used output methods.
  67. # (Save expensive attribute lookups.)
  68. _output_set_attributes = output.set_attributes
  69. _output_reset_attributes = output.reset_attributes
  70. _output_cursor_forward = output.cursor_forward
  71. _output_cursor_up = output.cursor_up
  72. _output_cursor_backward = output.cursor_backward
  73. # Hide cursor before rendering. (Avoid flickering.)
  74. output.hide_cursor()
  75. def reset_attributes() -> None:
  76. "Wrapper around Output.reset_attributes."
  77. nonlocal last_style
  78. _output_reset_attributes()
  79. last_style = None # Forget last char after resetting attributes.
  80. def move_cursor(new: Point) -> Point:
  81. "Move cursor to this `new` point. Returns the given Point."
  82. current_x, current_y = current_pos.x, current_pos.y
  83. if new.y > current_y:
  84. # Use newlines instead of CURSOR_DOWN, because this might add new lines.
  85. # CURSOR_DOWN will never create new lines at the bottom.
  86. # Also reset attributes, otherwise the newline could draw a
  87. # background color.
  88. reset_attributes()
  89. write("\r\n" * (new.y - current_y))
  90. current_x = 0
  91. _output_cursor_forward(new.x)
  92. return new
  93. elif new.y < current_y:
  94. _output_cursor_up(current_y - new.y)
  95. if current_x >= width - 1:
  96. write("\r")
  97. _output_cursor_forward(new.x)
  98. elif new.x < current_x or current_x >= width - 1:
  99. _output_cursor_backward(current_x - new.x)
  100. elif new.x > current_x:
  101. _output_cursor_forward(new.x - current_x)
  102. return new
  103. def output_char(char: Char) -> None:
  104. """
  105. Write the output of this character.
  106. """
  107. nonlocal last_style
  108. # If the last printed character has the same style, don't output the
  109. # style again.
  110. if last_style == char.style:
  111. write(char.char)
  112. else:
  113. # Look up `Attr` for this style string. Only set attributes if different.
  114. # (Two style strings can still have the same formatting.)
  115. # Note that an empty style string can have formatting that needs to
  116. # be applied, because of style transformations.
  117. new_attrs = attrs_for_style_string[char.style]
  118. if not last_style or new_attrs != attrs_for_style_string[last_style]:
  119. _output_set_attributes(new_attrs, color_depth)
  120. write(char.char)
  121. last_style = char.style
  122. def get_max_column_index(row: dict[int, Char]) -> int:
  123. """
  124. Return max used column index, ignoring whitespace (without style) at
  125. the end of the line. This is important for people that copy/paste
  126. terminal output.
  127. There are two reasons we are sometimes seeing whitespace at the end:
  128. - `BufferControl` adds a trailing space to each line, because it's a
  129. possible cursor position, so that the line wrapping won't change if
  130. the cursor position moves around.
  131. - The `Window` adds a style class to the current line for highlighting
  132. (cursor-line).
  133. """
  134. numbers = (
  135. index
  136. for index, cell in row.items()
  137. if cell.char != " " or style_string_has_style[cell.style]
  138. )
  139. return max(numbers, default=0)
  140. # Render for the first time: reset styling.
  141. if not previous_screen:
  142. reset_attributes()
  143. # Disable autowrap. (When entering a the alternate screen, or anytime when
  144. # we have a prompt. - In the case of a REPL, like IPython, people can have
  145. # background threads, and it's hard for debugging if their output is not
  146. # wrapped.)
  147. if not previous_screen or not full_screen:
  148. output.disable_autowrap()
  149. # When the previous screen has a different size, redraw everything anyway.
  150. # Also when we are done. (We might take up less rows, so clearing is important.)
  151. if (
  152. is_done or not previous_screen or previous_width != width
  153. ): # XXX: also consider height??
  154. current_pos = move_cursor(Point(x=0, y=0))
  155. reset_attributes()
  156. output.erase_down()
  157. previous_screen = Screen()
  158. # Get height of the screen.
  159. # (height changes as we loop over data_buffer, so remember the current value.)
  160. # (Also make sure to clip the height to the size of the output.)
  161. current_height = min(screen.height, height)
  162. # Loop over the rows.
  163. row_count = min(max(screen.height, previous_screen.height), height)
  164. for y in range(row_count):
  165. new_row = screen.data_buffer[y]
  166. previous_row = previous_screen.data_buffer[y]
  167. zero_width_escapes_row = screen.zero_width_escapes[y]
  168. new_max_line_len = min(width - 1, get_max_column_index(new_row))
  169. previous_max_line_len = min(width - 1, get_max_column_index(previous_row))
  170. # Loop over the columns.
  171. c = 0 # Column counter.
  172. while c <= new_max_line_len:
  173. new_char = new_row[c]
  174. old_char = previous_row[c]
  175. char_width = new_char.width or 1
  176. # When the old and new character at this position are different,
  177. # draw the output. (Because of the performance, we don't call
  178. # `Char.__ne__`, but inline the same expression.)
  179. if new_char.char != old_char.char or new_char.style != old_char.style:
  180. current_pos = move_cursor(Point(x=c, y=y))
  181. # Send injected escape sequences to output.
  182. if c in zero_width_escapes_row:
  183. write_raw(zero_width_escapes_row[c])
  184. output_char(new_char)
  185. current_pos = Point(x=current_pos.x + char_width, y=current_pos.y)
  186. c += char_width
  187. # If the new line is shorter, trim it.
  188. if previous_screen and new_max_line_len < previous_max_line_len:
  189. current_pos = move_cursor(Point(x=new_max_line_len + 1, y=y))
  190. reset_attributes()
  191. output.erase_end_of_line()
  192. # Correctly reserve vertical space as required by the layout.
  193. # When this is a new screen (drawn for the first time), or for some reason
  194. # higher than the previous one. Move the cursor once to the bottom of the
  195. # output. That way, we're sure that the terminal scrolls up, even when the
  196. # lower lines of the canvas just contain whitespace.
  197. # The most obvious reason that we actually want this behavior is the avoid
  198. # the artifact of the input scrolling when the completion menu is shown.
  199. # (If the scrolling is actually wanted, the layout can still be build in a
  200. # way to behave that way by setting a dynamic height.)
  201. if current_height > previous_screen.height:
  202. current_pos = move_cursor(Point(x=0, y=current_height - 1))
  203. # Move cursor:
  204. if is_done:
  205. current_pos = move_cursor(Point(x=0, y=current_height))
  206. output.erase_down()
  207. else:
  208. current_pos = move_cursor(screen.get_cursor_position(app.layout.current_window))
  209. if is_done or not full_screen:
  210. output.enable_autowrap()
  211. # Always reset the color attributes. This is important because a background
  212. # thread could print data to stdout and we want that to be displayed in the
  213. # default colors. (Also, if a background color has been set, many terminals
  214. # give weird artifacts on resize events.)
  215. reset_attributes()
  216. if screen.show_cursor or is_done:
  217. output.show_cursor()
  218. return current_pos, last_style
  219. class HeightIsUnknownError(Exception):
  220. "Information unavailable. Did not yet receive the CPR response."
  221. class _StyleStringToAttrsCache(Dict[str, Attrs]):
  222. """
  223. A cache structure that maps style strings to :class:`.Attr`.
  224. (This is an important speed up.)
  225. """
  226. def __init__(
  227. self,
  228. get_attrs_for_style_str: Callable[[str], Attrs],
  229. style_transformation: StyleTransformation,
  230. ) -> None:
  231. self.get_attrs_for_style_str = get_attrs_for_style_str
  232. self.style_transformation = style_transformation
  233. def __missing__(self, style_str: str) -> Attrs:
  234. attrs = self.get_attrs_for_style_str(style_str)
  235. attrs = self.style_transformation.transform_attrs(attrs)
  236. self[style_str] = attrs
  237. return attrs
  238. class _StyleStringHasStyleCache(Dict[str, bool]):
  239. """
  240. Cache for remember which style strings don't render the default output
  241. style (default fg/bg, no underline and no reverse and no blink). That way
  242. we know that we should render these cells, even when they're empty (when
  243. they contain a space).
  244. Note: we don't consider bold/italic/hidden because they don't change the
  245. output if there's no text in the cell.
  246. """
  247. def __init__(self, style_string_to_attrs: dict[str, Attrs]) -> None:
  248. self.style_string_to_attrs = style_string_to_attrs
  249. def __missing__(self, style_str: str) -> bool:
  250. attrs = self.style_string_to_attrs[style_str]
  251. is_default = bool(
  252. attrs.color
  253. or attrs.bgcolor
  254. or attrs.underline
  255. or attrs.strike
  256. or attrs.blink
  257. or attrs.reverse
  258. )
  259. self[style_str] = is_default
  260. return is_default
  261. class CPR_Support(Enum):
  262. "Enum: whether or not CPR is supported."
  263. SUPPORTED = "SUPPORTED"
  264. NOT_SUPPORTED = "NOT_SUPPORTED"
  265. UNKNOWN = "UNKNOWN"
  266. class Renderer:
  267. """
  268. Typical usage:
  269. ::
  270. output = Vt100_Output.from_pty(sys.stdout)
  271. r = Renderer(style, output)
  272. r.render(app, layout=...)
  273. """
  274. CPR_TIMEOUT = 2 # Time to wait until we consider CPR to be not supported.
  275. def __init__(
  276. self,
  277. style: BaseStyle,
  278. output: Output,
  279. full_screen: bool = False,
  280. mouse_support: FilterOrBool = False,
  281. cpr_not_supported_callback: Callable[[], None] | None = None,
  282. ) -> None:
  283. self.style = style
  284. self.output = output
  285. self.full_screen = full_screen
  286. self.mouse_support = to_filter(mouse_support)
  287. self.cpr_not_supported_callback = cpr_not_supported_callback
  288. self._in_alternate_screen = False
  289. self._mouse_support_enabled = False
  290. self._bracketed_paste_enabled = False
  291. self._cursor_key_mode_reset = False
  292. # Future set when we are waiting for a CPR flag.
  293. self._waiting_for_cpr_futures: deque[Future[None]] = deque()
  294. self.cpr_support = CPR_Support.UNKNOWN
  295. if not output.responds_to_cpr:
  296. self.cpr_support = CPR_Support.NOT_SUPPORTED
  297. # Cache for the style.
  298. self._attrs_for_style: _StyleStringToAttrsCache | None = None
  299. self._style_string_has_style: _StyleStringHasStyleCache | None = None
  300. self._last_style_hash: Hashable | None = None
  301. self._last_transformation_hash: Hashable | None = None
  302. self._last_color_depth: ColorDepth | None = None
  303. self.reset(_scroll=True)
  304. def reset(self, _scroll: bool = False, leave_alternate_screen: bool = True) -> None:
  305. # Reset position
  306. self._cursor_pos = Point(x=0, y=0)
  307. # Remember the last screen instance between renderers. This way,
  308. # we can create a `diff` between two screens and only output the
  309. # difference. It's also to remember the last height. (To show for
  310. # instance a toolbar at the bottom position.)
  311. self._last_screen: Screen | None = None
  312. self._last_size: Size | None = None
  313. self._last_style: str | None = None
  314. self._last_cursor_shape: CursorShape | None = None
  315. # Default MouseHandlers. (Just empty.)
  316. self.mouse_handlers = MouseHandlers()
  317. #: Space from the top of the layout, until the bottom of the terminal.
  318. #: We don't know this until a `report_absolute_cursor_row` call.
  319. self._min_available_height = 0
  320. # In case of Windows, also make sure to scroll to the current cursor
  321. # position. (Only when rendering the first time.)
  322. # It does nothing for vt100 terminals.
  323. if _scroll:
  324. self.output.scroll_buffer_to_prompt()
  325. # Quit alternate screen.
  326. if self._in_alternate_screen and leave_alternate_screen:
  327. self.output.quit_alternate_screen()
  328. self._in_alternate_screen = False
  329. # Disable mouse support.
  330. if self._mouse_support_enabled:
  331. self.output.disable_mouse_support()
  332. self._mouse_support_enabled = False
  333. # Disable bracketed paste.
  334. if self._bracketed_paste_enabled:
  335. self.output.disable_bracketed_paste()
  336. self._bracketed_paste_enabled = False
  337. self.output.reset_cursor_shape()
  338. # NOTE: No need to set/reset cursor key mode here.
  339. # Flush output. `disable_mouse_support` needs to write to stdout.
  340. self.output.flush()
  341. @property
  342. def last_rendered_screen(self) -> Screen | None:
  343. """
  344. The `Screen` class that was generated during the last rendering.
  345. This can be `None`.
  346. """
  347. return self._last_screen
  348. @property
  349. def height_is_known(self) -> bool:
  350. """
  351. True when the height from the cursor until the bottom of the terminal
  352. is known. (It's often nicer to draw bottom toolbars only if the height
  353. is known, in order to avoid flickering when the CPR response arrives.)
  354. """
  355. if self.full_screen or self._min_available_height > 0:
  356. return True
  357. try:
  358. self._min_available_height = self.output.get_rows_below_cursor_position()
  359. return True
  360. except NotImplementedError:
  361. return False
  362. @property
  363. def rows_above_layout(self) -> int:
  364. """
  365. Return the number of rows visible in the terminal above the layout.
  366. """
  367. if self._in_alternate_screen:
  368. return 0
  369. elif self._min_available_height > 0:
  370. total_rows = self.output.get_size().rows
  371. last_screen_height = self._last_screen.height if self._last_screen else 0
  372. return total_rows - max(self._min_available_height, last_screen_height)
  373. else:
  374. raise HeightIsUnknownError("Rows above layout is unknown.")
  375. def request_absolute_cursor_position(self) -> None:
  376. """
  377. Get current cursor position.
  378. We do this to calculate the minimum available height that we can
  379. consume for rendering the prompt. This is the available space below te
  380. cursor.
  381. For vt100: Do CPR request. (answer will arrive later.)
  382. For win32: Do API call. (Answer comes immediately.)
  383. """
  384. # Only do this request when the cursor is at the top row. (after a
  385. # clear or reset). We will rely on that in `report_absolute_cursor_row`.
  386. assert self._cursor_pos.y == 0
  387. # In full-screen mode, always use the total height as min-available-height.
  388. if self.full_screen:
  389. self._min_available_height = self.output.get_size().rows
  390. return
  391. # For Win32, we have an API call to get the number of rows below the
  392. # cursor.
  393. try:
  394. self._min_available_height = self.output.get_rows_below_cursor_position()
  395. return
  396. except NotImplementedError:
  397. pass
  398. # Use CPR.
  399. if self.cpr_support == CPR_Support.NOT_SUPPORTED:
  400. return
  401. def do_cpr() -> None:
  402. # Asks for a cursor position report (CPR).
  403. self._waiting_for_cpr_futures.append(Future())
  404. self.output.ask_for_cpr()
  405. if self.cpr_support == CPR_Support.SUPPORTED:
  406. do_cpr()
  407. return
  408. # If we don't know whether CPR is supported, only do a request if
  409. # none is pending, and test it, using a timer.
  410. if self.waiting_for_cpr:
  411. return
  412. do_cpr()
  413. async def timer() -> None:
  414. await sleep(self.CPR_TIMEOUT)
  415. # Not set in the meantime -> not supported.
  416. if self.cpr_support == CPR_Support.UNKNOWN:
  417. self.cpr_support = CPR_Support.NOT_SUPPORTED
  418. if self.cpr_not_supported_callback:
  419. # Make sure to call this callback in the main thread.
  420. self.cpr_not_supported_callback()
  421. get_app().create_background_task(timer())
  422. def report_absolute_cursor_row(self, row: int) -> None:
  423. """
  424. To be called when we know the absolute cursor position.
  425. (As an answer of a "Cursor Position Request" response.)
  426. """
  427. self.cpr_support = CPR_Support.SUPPORTED
  428. # Calculate the amount of rows from the cursor position until the
  429. # bottom of the terminal.
  430. total_rows = self.output.get_size().rows
  431. rows_below_cursor = total_rows - row + 1
  432. # Set the minimum available height.
  433. self._min_available_height = rows_below_cursor
  434. # Pop and set waiting for CPR future.
  435. try:
  436. f = self._waiting_for_cpr_futures.popleft()
  437. except IndexError:
  438. pass # Received CPR response without having a CPR.
  439. else:
  440. f.set_result(None)
  441. @property
  442. def waiting_for_cpr(self) -> bool:
  443. """
  444. Waiting for CPR flag. True when we send the request, but didn't got a
  445. response.
  446. """
  447. return bool(self._waiting_for_cpr_futures)
  448. async def wait_for_cpr_responses(self, timeout: int = 1) -> None:
  449. """
  450. Wait for a CPR response.
  451. """
  452. cpr_futures = list(self._waiting_for_cpr_futures) # Make copy.
  453. # When there are no CPRs in the queue. Don't do anything.
  454. if not cpr_futures or self.cpr_support == CPR_Support.NOT_SUPPORTED:
  455. return None
  456. async def wait_for_responses() -> None:
  457. for response_f in cpr_futures:
  458. await response_f
  459. async def wait_for_timeout() -> None:
  460. await sleep(timeout)
  461. # Got timeout, erase queue.
  462. for response_f in cpr_futures:
  463. response_f.cancel()
  464. self._waiting_for_cpr_futures = deque()
  465. tasks = {
  466. ensure_future(wait_for_responses()),
  467. ensure_future(wait_for_timeout()),
  468. }
  469. _, pending = await wait(tasks, return_when=FIRST_COMPLETED)
  470. for task in pending:
  471. task.cancel()
  472. def render(
  473. self, app: Application[Any], layout: Layout, is_done: bool = False
  474. ) -> None:
  475. """
  476. Render the current interface to the output.
  477. :param is_done: When True, put the cursor at the end of the interface. We
  478. won't print any changes to this part.
  479. """
  480. output = self.output
  481. # Enter alternate screen.
  482. if self.full_screen and not self._in_alternate_screen:
  483. self._in_alternate_screen = True
  484. output.enter_alternate_screen()
  485. # Enable bracketed paste.
  486. if not self._bracketed_paste_enabled:
  487. self.output.enable_bracketed_paste()
  488. self._bracketed_paste_enabled = True
  489. # Reset cursor key mode.
  490. if not self._cursor_key_mode_reset:
  491. self.output.reset_cursor_key_mode()
  492. self._cursor_key_mode_reset = True
  493. # Enable/disable mouse support.
  494. needs_mouse_support = self.mouse_support()
  495. if needs_mouse_support and not self._mouse_support_enabled:
  496. output.enable_mouse_support()
  497. self._mouse_support_enabled = True
  498. elif not needs_mouse_support and self._mouse_support_enabled:
  499. output.disable_mouse_support()
  500. self._mouse_support_enabled = False
  501. # Create screen and write layout to it.
  502. size = output.get_size()
  503. screen = Screen()
  504. screen.show_cursor = False # Hide cursor by default, unless one of the
  505. # containers decides to display it.
  506. mouse_handlers = MouseHandlers()
  507. # Calculate height.
  508. if self.full_screen:
  509. height = size.rows
  510. elif is_done:
  511. # When we are done, we don't necessary want to fill up until the bottom.
  512. height = layout.container.preferred_height(
  513. size.columns, size.rows
  514. ).preferred
  515. else:
  516. last_height = self._last_screen.height if self._last_screen else 0
  517. height = max(
  518. self._min_available_height,
  519. last_height,
  520. layout.container.preferred_height(size.columns, size.rows).preferred,
  521. )
  522. height = min(height, size.rows)
  523. # When the size changes, don't consider the previous screen.
  524. if self._last_size != size:
  525. self._last_screen = None
  526. # When we render using another style or another color depth, do a full
  527. # repaint. (Forget about the previous rendered screen.)
  528. # (But note that we still use _last_screen to calculate the height.)
  529. if (
  530. self.style.invalidation_hash() != self._last_style_hash
  531. or app.style_transformation.invalidation_hash()
  532. != self._last_transformation_hash
  533. or app.color_depth != self._last_color_depth
  534. ):
  535. self._last_screen = None
  536. self._attrs_for_style = None
  537. self._style_string_has_style = None
  538. if self._attrs_for_style is None:
  539. self._attrs_for_style = _StyleStringToAttrsCache(
  540. self.style.get_attrs_for_style_str, app.style_transformation
  541. )
  542. if self._style_string_has_style is None:
  543. self._style_string_has_style = _StyleStringHasStyleCache(
  544. self._attrs_for_style
  545. )
  546. self._last_style_hash = self.style.invalidation_hash()
  547. self._last_transformation_hash = app.style_transformation.invalidation_hash()
  548. self._last_color_depth = app.color_depth
  549. layout.container.write_to_screen(
  550. screen,
  551. mouse_handlers,
  552. WritePosition(xpos=0, ypos=0, width=size.columns, height=height),
  553. parent_style="",
  554. erase_bg=False,
  555. z_index=None,
  556. )
  557. screen.draw_all_floats()
  558. # When grayed. Replace all styles in the new screen.
  559. if app.exit_style:
  560. screen.append_style_to_content(app.exit_style)
  561. # Process diff and write to output.
  562. self._cursor_pos, self._last_style = _output_screen_diff(
  563. app,
  564. output,
  565. screen,
  566. self._cursor_pos,
  567. app.color_depth,
  568. self._last_screen,
  569. self._last_style,
  570. is_done,
  571. full_screen=self.full_screen,
  572. attrs_for_style_string=self._attrs_for_style,
  573. style_string_has_style=self._style_string_has_style,
  574. size=size,
  575. previous_width=(self._last_size.columns if self._last_size else 0),
  576. )
  577. self._last_screen = screen
  578. self._last_size = size
  579. self.mouse_handlers = mouse_handlers
  580. # Handle cursor shapes.
  581. new_cursor_shape = app.cursor.get_cursor_shape(app)
  582. if (
  583. self._last_cursor_shape is None
  584. or self._last_cursor_shape != new_cursor_shape
  585. ):
  586. output.set_cursor_shape(new_cursor_shape)
  587. self._last_cursor_shape = new_cursor_shape
  588. # Flush buffered output.
  589. output.flush()
  590. # Set visible windows in layout.
  591. app.layout.visible_windows = screen.visible_windows
  592. if is_done:
  593. self.reset()
  594. def erase(self, leave_alternate_screen: bool = True) -> None:
  595. """
  596. Hide all output and put the cursor back at the first line. This is for
  597. instance used for running a system command (while hiding the CLI) and
  598. later resuming the same CLI.)
  599. :param leave_alternate_screen: When True, and when inside an alternate
  600. screen buffer, quit the alternate screen.
  601. """
  602. output = self.output
  603. output.cursor_backward(self._cursor_pos.x)
  604. output.cursor_up(self._cursor_pos.y)
  605. output.erase_down()
  606. output.reset_attributes()
  607. output.enable_autowrap()
  608. output.flush()
  609. self.reset(leave_alternate_screen=leave_alternate_screen)
  610. def clear(self) -> None:
  611. """
  612. Clear screen and go to 0,0
  613. """
  614. # Erase current output first.
  615. self.erase()
  616. # Send "Erase Screen" command and go to (0, 0).
  617. output = self.output
  618. output.erase_screen()
  619. output.cursor_goto(0, 0)
  620. output.flush()
  621. self.request_absolute_cursor_position()
  622. def print_formatted_text(
  623. output: Output,
  624. formatted_text: AnyFormattedText,
  625. style: BaseStyle,
  626. style_transformation: StyleTransformation | None = None,
  627. color_depth: ColorDepth | None = None,
  628. ) -> None:
  629. """
  630. Print a list of (style_str, text) tuples in the given style to the output.
  631. """
  632. fragments = to_formatted_text(formatted_text)
  633. style_transformation = style_transformation or DummyStyleTransformation()
  634. color_depth = color_depth or output.get_default_color_depth()
  635. # Reset first.
  636. output.reset_attributes()
  637. output.enable_autowrap()
  638. last_attrs: Attrs | None = None
  639. # Print all (style_str, text) tuples.
  640. attrs_for_style_string = _StyleStringToAttrsCache(
  641. style.get_attrs_for_style_str, style_transformation
  642. )
  643. for style_str, text, *_ in fragments:
  644. attrs = attrs_for_style_string[style_str]
  645. # Set style attributes if something changed.
  646. if attrs != last_attrs:
  647. if attrs:
  648. output.set_attributes(attrs, color_depth)
  649. else:
  650. output.reset_attributes()
  651. last_attrs = attrs
  652. # Print escape sequences as raw output
  653. if "[ZeroWidthEscape]" in style_str:
  654. output.write_raw(text)
  655. else:
  656. # Eliminate carriage returns
  657. text = text.replace("\r", "")
  658. # Insert a carriage return before every newline (important when the
  659. # front-end is a telnet client).
  660. text = text.replace("\n", "\r\n")
  661. output.write(text)
  662. # Reset again.
  663. output.reset_attributes()
  664. output.flush()