terminal_output.py

 1#!/usr/bin/env python
 2
 3"""Example: a chart drawn with terminal escape sequences, shown in a TerminalOutput widget.
 4
 5The chart is drawn again for the new size whenever the window is resized, and the chart drawn before scrolls into
 6the scrollback: Page Up and Page Down, or the mouse wheel, scroll through it, and q exits.
 7"""
 8
 9from __future__ import annotations
10
11import math
12
13import urwid
14
15# A cell filled from the bottom in eighths, from empty to full.
16EIGHTHS = " ▁▂▃▄▅▆▇█"
17
18
19def chart(columns: int, rows: int) -> str:
20    """Return the escape sequences and text that draw the chart on a screen of *columns* by *rows*."""
21    parts = [
22        # move the chart drawn before into the scrollback, then start again at the top-left corner
23        f"\x1b[{rows};1H" + "\n" * rows + "\x1b[H",
24        f"\x1b[1mTerminalOutput {columns}x{rows}\x1b[0m",
25        # a strip of the 216 colors of the 256-color cube
26        "\x1b[2;1H" + "".join(f"\x1b[48;5;{16 + column * 216 // columns}m " for column in range(columns)) + "\x1b[0m",
27    ]
28    height = rows - 2
29    for row in range(height):
30        level = (height - 1 - row) * 8
31        line = []
32        for column in range(columns):
33            value = (math.sin(4 * math.pi * column / columns) + 1) / 2 * height * 8
34            red, blue = 255 * column // columns, 255 - 255 * column // columns
35            line.append(f"\x1b[38;2;{red};96;{blue}m{EIGHTHS[min(8, max(0, round(value) - level))]}")
36        parts.append(f"\x1b[{row + 3};1H" + "".join(line) + "\x1b[0m")
37    return "".join(parts)
38
39
40def main() -> None:
41    """Show the chart, drawn again on each resize, with the key handling."""
42    # a size no window has, so the first render resizes and draws the chart for the real size
43    output = urwid.TerminalOutput(size=(1, 1))
44
45    def draw_for(widget: urwid.TerminalOutput, size: tuple[int, int]) -> None:
46        widget.write(chart(*size))
47
48    urwid.connect_signal(output, "resize", draw_for)
49
50    def unhandled(key: str | tuple[str, int, int, int]) -> None:
51        if key == "q":
52            raise urwid.ExitMainLoop
53
54    frame: urwid.Frame[urwid.TerminalOutput, None, urwid.Text] = urwid.Frame(
55        output,
56        footer=urwid.Text("Page Up/Page Down or the mouse wheel: scroll back  q: quit"),
57    )
58    urwid.MainLoop(frame, unhandled_input=unhandled).run()
59
60
61if __name__ == "__main__":
62    main()