_windows_renderer.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from typing import Iterable, Sequence, Tuple, cast
  2. from rich._win32_console import LegacyWindowsTerm, WindowsCoordinates
  3. from rich.segment import ControlCode, ControlType, Segment
  4. def legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None:
  5. """Makes appropriate Windows Console API calls based on the segments in the buffer.
  6. Args:
  7. buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls.
  8. term (LegacyWindowsTerm): Used to call the Windows Console API.
  9. """
  10. for text, style, control in buffer:
  11. if not control:
  12. if style:
  13. term.write_styled(text, style)
  14. else:
  15. term.write_text(text)
  16. else:
  17. control_codes: Sequence[ControlCode] = control
  18. for control_code in control_codes:
  19. control_type = control_code[0]
  20. if control_type == ControlType.CURSOR_MOVE_TO:
  21. _, x, y = cast(Tuple[ControlType, int, int], control_code)
  22. term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1))
  23. elif control_type == ControlType.CARRIAGE_RETURN:
  24. term.write_text("\r")
  25. elif control_type == ControlType.HOME:
  26. term.move_cursor_to(WindowsCoordinates(0, 0))
  27. elif control_type == ControlType.CURSOR_UP:
  28. term.move_cursor_up()
  29. elif control_type == ControlType.CURSOR_DOWN:
  30. term.move_cursor_down()
  31. elif control_type == ControlType.CURSOR_FORWARD:
  32. term.move_cursor_forward()
  33. elif control_type == ControlType.CURSOR_BACKWARD:
  34. term.move_cursor_backward()
  35. elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN:
  36. _, column = cast(Tuple[ControlType, int], control_code)
  37. term.move_cursor_to_column(column - 1)
  38. elif control_type == ControlType.HIDE_CURSOR:
  39. term.hide_cursor()
  40. elif control_type == ControlType.SHOW_CURSOR:
  41. term.show_cursor()
  42. elif control_type == ControlType.ERASE_IN_LINE:
  43. _, mode = cast(Tuple[ControlType, int], control_code)
  44. if mode == 0:
  45. term.erase_end_of_line()
  46. elif mode == 1:
  47. term.erase_start_of_line()
  48. elif mode == 2:
  49. term.erase_line()
  50. elif control_type == ControlType.SET_WINDOW_TITLE:
  51. _, title = cast(Tuple[ControlType, str], control_code)
  52. term.set_title(title)