zettcode-tui 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. zettcode/tui/__init__.py +422 -0
  2. zettcode/tui/_compat.py +32 -0
  3. zettcode/tui/capabilities.py +107 -0
  4. zettcode/tui/clipboard.py +91 -0
  5. zettcode/tui/console.py +229 -0
  6. zettcode/tui/core/__init__.py +63 -0
  7. zettcode/tui/core/app.py +658 -0
  8. zettcode/tui/core/events.py +134 -0
  9. zettcode/tui/core/focus.py +85 -0
  10. zettcode/tui/core/geometry.py +212 -0
  11. zettcode/tui/core/host.py +66 -0
  12. zettcode/tui/core/keymap.py +218 -0
  13. zettcode/tui/core/scheduler.py +105 -0
  14. zettcode/tui/core/screen.py +80 -0
  15. zettcode/tui/core/theme.py +248 -0
  16. zettcode/tui/core/widget.py +204 -0
  17. zettcode/tui/gallery.py +588 -0
  18. zettcode/tui/glyphs.py +73 -0
  19. zettcode/tui/input/__init__.py +18 -0
  20. zettcode/tui/input/bridge.py +46 -0
  21. zettcode/tui/input/decoder.py +234 -0
  22. zettcode/tui/input/events.py +64 -0
  23. zettcode/tui/input/keys.py +289 -0
  24. zettcode/tui/input/reader.py +147 -0
  25. zettcode/tui/layout/__init__.py +24 -0
  26. zettcode/tui/layout/box.py +153 -0
  27. zettcode/tui/layout/overlay.py +164 -0
  28. zettcode/tui/layout/scroll.py +477 -0
  29. zettcode/tui/layout/solver.py +95 -0
  30. zettcode/tui/layout/spacing.py +137 -0
  31. zettcode/tui/py.typed +0 -0
  32. zettcode/tui/render/__init__.py +71 -0
  33. zettcode/tui/render/ansi.py +371 -0
  34. zettcode/tui/render/canvas.py +153 -0
  35. zettcode/tui/render/code.py +456 -0
  36. zettcode/tui/render/color.py +177 -0
  37. zettcode/tui/render/renderer.py +151 -0
  38. zettcode/tui/render/rich_text.py +80 -0
  39. zettcode/tui/render/style.py +121 -0
  40. zettcode/tui/render/sweep.py +87 -0
  41. zettcode/tui/render/text.py +319 -0
  42. zettcode/tui/runner.py +316 -0
  43. zettcode/tui/terminal.py +222 -0
  44. zettcode/tui/testing/__init__.py +6 -0
  45. zettcode/tui/testing/harness.py +220 -0
  46. zettcode/tui/testing/snapshot.py +64 -0
  47. zettcode/tui/theme_file.py +300 -0
  48. zettcode/tui/themes/ayu-mirage.toml +44 -0
  49. zettcode/tui/themes/catppuccin-latte.toml +44 -0
  50. zettcode/tui/themes/catppuccin-mocha.toml +44 -0
  51. zettcode/tui/themes/dracula.toml +44 -0
  52. zettcode/tui/themes/github-dimmed.toml +44 -0
  53. zettcode/tui/themes/github-light.toml +44 -0
  54. zettcode/tui/themes/gruvbox-dark.toml +44 -0
  55. zettcode/tui/themes/gruvbox-light.toml +44 -0
  56. zettcode/tui/themes/kanagawa.toml +44 -0
  57. zettcode/tui/themes/nord.toml +44 -0
  58. zettcode/tui/themes/one-dark.toml +44 -0
  59. zettcode/tui/themes/rose-pine-dawn.toml +44 -0
  60. zettcode/tui/themes/rose-pine.toml +44 -0
  61. zettcode/tui/themes/solarized-dark.toml +44 -0
  62. zettcode/tui/themes/solarized-light.toml +44 -0
  63. zettcode/tui/themes/tokyo-night.toml +44 -0
  64. zettcode/tui/widgets/__init__.py +121 -0
  65. zettcode/tui/widgets/collapsible.py +116 -0
  66. zettcode/tui/widgets/completion.py +211 -0
  67. zettcode/tui/widgets/console.py +442 -0
  68. zettcode/tui/widgets/dialog.py +165 -0
  69. zettcode/tui/widgets/diff.py +236 -0
  70. zettcode/tui/widgets/list.py +293 -0
  71. zettcode/tui/widgets/list_page.py +121 -0
  72. zettcode/tui/widgets/markdown.py +657 -0
  73. zettcode/tui/widgets/progress.py +166 -0
  74. zettcode/tui/widgets/rich_text.py +84 -0
  75. zettcode/tui/widgets/status.py +106 -0
  76. zettcode/tui/widgets/table.py +101 -0
  77. zettcode/tui/widgets/tasks.py +130 -0
  78. zettcode/tui/widgets/text.py +111 -0
  79. zettcode/tui/widgets/textarea.py +671 -0
  80. zettcode/tui/widgets/toast.py +137 -0
  81. zettcode_tui-0.4.0.dist-info/METADATA +20 -0
  82. zettcode_tui-0.4.0.dist-info/RECORD +83 -0
  83. zettcode_tui-0.4.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,137 @@
1
+ """Containers that reserve space around a single child."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from zettcode.tui import RULE
6
+
7
+ from ..core.geometry import Constraints, EdgeInsets, Point, Rect, Size
8
+ from ..core.widget import Widget
9
+ from ..render import DEFAULT_STYLE, Canvas, Style
10
+
11
+
12
+ class Padding(Widget):
13
+ """Place one child inside an inset rectangle.
14
+
15
+ Shape::
16
+
17
+ +---------------------+ <- the widget's own rectangle (draws nothing)
18
+ | +---------------+ |
19
+ | | child | | <- child gets rect.inset(edges)
20
+ | +---------------+ |
21
+ +---------------------+
22
+
23
+ It contributes no glyphs of its own; it only deflates the constraints on
24
+ the way down and adds the edges back on the way up, so the parent's budget
25
+ stays exact.
26
+ """
27
+
28
+ def __init__(self, child: Widget, edges: EdgeInsets | int = 1) -> None:
29
+ """Accept a full EdgeInsets or one value applied to all four sides.
30
+
31
+ Args:
32
+ child: The single widget placed inside the inset rectangle.
33
+ edges: Spacing reserved on each side, in cells.
34
+ """
35
+ super().__init__()
36
+ self.child = child
37
+ self.edges = edges if isinstance(edges, EdgeInsets) else EdgeInsets.all(edges)
38
+
39
+ @property
40
+ def children(self) -> tuple[Widget, ...]:
41
+ """Expose the single child that receives the inset rectangle."""
42
+ return (self.child,)
43
+
44
+ def measure(self, constraints: Constraints) -> Size:
45
+ """Measure the child inside the deflated constraints, then add the edges back."""
46
+ inner = self.child.measure(constraints.deflate(self.edges))
47
+ wanted = Size(inner.width + self.edges.horizontal, inner.height + self.edges.vertical)
48
+ return constraints.constrain(wanted)
49
+
50
+ def layout(self, rect: Rect) -> None:
51
+ """Give the child the assigned rectangle minus the padding."""
52
+ super().layout(rect)
53
+ self.child.layout(rect.inset(self.edges))
54
+
55
+ def render(self, canvas: Canvas) -> None:
56
+ """Paint the child; padding itself draws nothing."""
57
+ self.child.render(canvas)
58
+
59
+ def cursor(self) -> Point | None:
60
+ """Forward the cursor request to the child."""
61
+ return self.child.cursor()
62
+
63
+
64
+ class Border(Widget):
65
+ """Draw a box around one child and inset it by the drawn frame.
66
+
67
+ Shape::
68
+
69
+ +-- title ---------+ <- title only when the frame is wider than 4 cells
70
+ |child | <- child gets rect.inset(1), one cell on every side
71
+ | |
72
+ +------------------+
73
+
74
+ The frame is box-drawing (U+250C, U+2500, U+2502, U+2514). It clears its own
75
+ rectangle before drawing, which is what lets a panel sit over another screen
76
+ without letting it show through; a border with no child still draws.
77
+ """
78
+
79
+ HORIZONTAL = RULE
80
+ VERTICAL = "\u2502"
81
+
82
+ def __init__(self, child: Widget | None = None, *, style: Style = DEFAULT_STYLE, title: str = "") -> None:
83
+ """Draw a frame around ``child``; a border without a child is still valid.
84
+
85
+ Args:
86
+ child: Content inset by one cell on each side; ``None`` draws the
87
+ frame alone.
88
+ style: Style of the frame glyphs, not of the child.
89
+ title: Text embedded in the top border; only drawn when the frame is
90
+ wider than four cells, otherwise it is dropped.
91
+ """
92
+ super().__init__()
93
+ self.child = child
94
+ self.style = style
95
+ self.title = title
96
+
97
+ @property
98
+ def children(self) -> tuple[Widget, ...]:
99
+ """Expose the child, if this border has one."""
100
+ return (self.child,) if self.child is not None else ()
101
+
102
+ def measure(self, constraints: Constraints) -> Size:
103
+ """Measure the child inside the frame and reserve two cells per axis."""
104
+ inner = self.child.measure(constraints.deflate(EdgeInsets.all(1))) if self.child else Size(0, 0)
105
+ wanted = Size(inner.width + 2, inner.height + 2)
106
+ return constraints.constrain(wanted)
107
+
108
+ def layout(self, rect: Rect) -> None:
109
+ """Reserve one cell on every side for the frame."""
110
+ super().layout(rect)
111
+ if self.child is not None:
112
+ self.child.layout(rect.inset(1))
113
+
114
+ def render(self, canvas: Canvas) -> None:
115
+ """Clear the panel, then draw the frame, the title, and the child."""
116
+ if self.rect.empty:
117
+ return
118
+ # A framed panel is a surface, not a frame drawn over someone else's
119
+ # text: clear its own rectangle so no earlier screen shows through.
120
+ canvas.fill(self.rect.x, self.rect.y, self.rect.width, self.rect.height, DEFAULT_STYLE, " ")
121
+ width = self.rect.width
122
+ rule = self.HORIZONTAL * max(0, width - 2)
123
+ canvas.draw_text(self.rect.x, self.rect.y, f"\u250c{rule}\u2510", self.style)
124
+ for row in range(1, max(1, self.rect.height - 1)):
125
+ y = self.rect.y + row
126
+ canvas.draw_text(self.rect.x, y, self.VERTICAL, self.style)
127
+ canvas.draw_text(self.rect.x + width - 1, y, self.VERTICAL, self.style)
128
+ if self.rect.height > 1:
129
+ canvas.draw_text(self.rect.x, self.rect.y + self.rect.height - 1, f"\u2514{rule}\u2518", self.style)
130
+ if self.title and width > 4:
131
+ canvas.draw_text(self.rect.x + 2, self.rect.y, f" {self.title} ", self.style, max_width=width - 4)
132
+ if self.child is not None:
133
+ self.child.render(canvas)
134
+
135
+ def cursor(self) -> Point | None:
136
+ """Forward the cursor request to the child, if there is one."""
137
+ return self.child.cursor() if self.child is not None else None
zettcode/tui/py.typed ADDED
File without changes
@@ -0,0 +1,71 @@
1
+ """Rendering primitives: styled text, capabilities-aware color, and canvases."""
2
+
3
+ from .ansi import ANSI_COLORS, AnsiBuffer, AnsiLine
4
+ from .canvas import Canvas
5
+ from .code import DEFAULT_CODE_THEME, GENERIC, LATEX, PYTHON, SHELL, CodeTheme, highlight, language_for, languages
6
+ from .color import ColorDepth, blend, encode_style, parse_hex, rgb_to_ansi16, rgb_to_ansi256
7
+ from .renderer import DifferentialRenderer
8
+ from .rich_text import Alignment, inset_line, layout_rich_lines
9
+ from .style import DEFAULT_STYLE, Cell, Span, Style, TextLine
10
+ from .sweep import SweepSpan, sweep_spans
11
+ from .text import (
12
+ ELLIPSIS,
13
+ cell_glyph,
14
+ character_width,
15
+ count_wrapped_rows,
16
+ display_width,
17
+ expand_span_tabs,
18
+ expand_tabs,
19
+ slice_columns,
20
+ truncate,
21
+ truncate_spans,
22
+ wrap_columns,
23
+ wrap_spans,
24
+ wrap_words,
25
+ )
26
+
27
+ __all__ = [
28
+ "ANSI_COLORS",
29
+ "AnsiBuffer",
30
+ "AnsiLine",
31
+ "DEFAULT_CODE_THEME",
32
+ "DEFAULT_STYLE",
33
+ "ELLIPSIS",
34
+ "GENERIC",
35
+ "LATEX",
36
+ "PYTHON",
37
+ "SHELL",
38
+ "Canvas",
39
+ "Alignment",
40
+ "Cell",
41
+ "ColorDepth",
42
+ "CodeTheme",
43
+ "DifferentialRenderer",
44
+ "Span",
45
+ "Style",
46
+ "SweepSpan",
47
+ "TextLine",
48
+ "blend",
49
+ "cell_glyph",
50
+ "character_width",
51
+ "count_wrapped_rows",
52
+ "display_width",
53
+ "encode_style",
54
+ "expand_span_tabs",
55
+ "expand_tabs",
56
+ "highlight",
57
+ "inset_line",
58
+ "layout_rich_lines",
59
+ "language_for",
60
+ "languages",
61
+ "parse_hex",
62
+ "rgb_to_ansi16",
63
+ "rgb_to_ansi256",
64
+ "slice_columns",
65
+ "sweep_spans",
66
+ "truncate",
67
+ "truncate_spans",
68
+ "wrap_columns",
69
+ "wrap_spans",
70
+ "wrap_words",
71
+ ]
@@ -0,0 +1,371 @@
1
+ """Turn the bytes a program prints into lines of styled cells: colours, carriage returns, and progress bars.
2
+
3
+ A command's output is not text, it is instructions to a terminal: ``\\x1b[31m`` turns the colour red,
4
+ ``\\r`` goes back to the start of the line so the next characters overwrite it (a progress bar), ``\\x1b[K``
5
+ erases the rest of the line. A widget that showed those bytes as they are would show ``^[[31m`` all over a build
6
+ log. :class:`AnsiBuffer` is the part of a terminal that understands them, without being one: it keeps a bounded
7
+ scrollback of lines, each a row of characters with the style they were written in, and it applies the
8
+ instructions that change *what is on the line being written*. Moving the cursor up or clearing the screen would
9
+ need a grid, which a scrolling log does not have; those are dropped, and what was meant to be shown on the
10
+ current line still is.
11
+
12
+ The buffer takes text in pieces of any size: a sequence cut in half by a read is held until the rest arrives.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Sequence
18
+ from dataclasses import replace
19
+
20
+ from .style import DEFAULT_STYLE, Span, Style
21
+ from .text import character_width
22
+
23
+ #: The sixteen colours, in the order the SGR codes 30-37 and 90-97 name them. Mid tones, chosen to stay legible on
24
+ #: both a dark and a light page: a program that prints "white" or "black" must not vanish into the background.
25
+ ANSI_COLORS: tuple[str, ...] = (
26
+ "#6b6f76",
27
+ "#d0504e",
28
+ "#5fa55a",
29
+ "#c9a227",
30
+ "#4f8fd6",
31
+ "#b266c4",
32
+ "#3fa7a7",
33
+ "#c0c4ca",
34
+ "#8a8f98",
35
+ "#f0716f",
36
+ "#7fcf7a",
37
+ "#e6c14d",
38
+ "#6fa8e8",
39
+ "#cf86dc",
40
+ "#5fcfcf",
41
+ "#f2f4f7",
42
+ )
43
+
44
+ #: Columns between tab stops.
45
+ TAB_WIDTH = 8
46
+
47
+ #: The longest escape sequence held back while waiting for its end; anything longer was never one.
48
+ MAX_PENDING = 4096
49
+
50
+ #: The levels of the colour cube's axes in the 256-colour palette.
51
+ _CUBE = (0, 95, 135, 175, 215, 255)
52
+
53
+
54
+ def xterm_color(index: int) -> str:
55
+ """Return the colour of entry ``index`` of the 256-colour palette as ``#rrggbb``."""
56
+ if index < 16:
57
+ return ANSI_COLORS[index]
58
+ if index < 232:
59
+ index -= 16
60
+ red, green, blue = _CUBE[index // 36], _CUBE[index // 6 % 6], _CUBE[index % 6]
61
+ else:
62
+ red = green = blue = 8 + (min(index, 255) - 232) * 10
63
+ return f"#{red:02x}{green:02x}{blue:02x}"
64
+
65
+
66
+ class AnsiLine:
67
+ """One line: its characters, and the style each was written in.
68
+
69
+ The two lists are parallel, one entry per character, so a character can be overwritten by position (the
70
+ carriage return) without re-slicing runs. A wide glyph is one entry; the width is worked out when a line is
71
+ drawn or wrapped.
72
+ """
73
+
74
+ __slots__ = ("chars", "styles", "_width")
75
+
76
+ def __init__(self) -> None:
77
+ self.chars: list[str] = []
78
+ self.styles: list[Style] = []
79
+ self._width: int | None = None
80
+
81
+ def __len__(self) -> int:
82
+ return len(self.chars)
83
+
84
+ @property
85
+ def text(self) -> str:
86
+ """Return the characters without their styles."""
87
+ return "".join(self.chars)
88
+
89
+ @property
90
+ def width(self) -> int:
91
+ """Return the columns the line takes up, counting wide glyphs as two."""
92
+ if self._width is None:
93
+ self._width = sum(map(character_width, self.chars))
94
+ return self._width
95
+
96
+ def put(self, column: int, character: str, style: Style) -> None:
97
+ """Write one character at ``column``: over what is there, or after it (padding a gap with spaces)."""
98
+ self._width = None
99
+ if column < len(self.chars):
100
+ self.chars[column] = character
101
+ self.styles[column] = style
102
+ return
103
+ if column > len(self.chars):
104
+ gap = column - len(self.chars)
105
+ self.chars.extend(" " * gap)
106
+ self.styles.extend([DEFAULT_STYLE] * gap)
107
+ self.chars.append(character)
108
+ self.styles.append(style)
109
+
110
+ def truncate(self, column: int) -> None:
111
+ """Erase from ``column`` to the end of the line."""
112
+ if column < len(self.chars):
113
+ del self.chars[column:]
114
+ del self.styles[column:]
115
+ self._width = None
116
+
117
+ def blank(self, column: int) -> None:
118
+ """Replace everything before ``column`` with spaces, keeping the line's length."""
119
+ for index in range(min(column, len(self.chars))):
120
+ self.chars[index] = " "
121
+ self.styles[index] = DEFAULT_STYLE
122
+ self._width = None
123
+
124
+ def spans(self, start: int = 0, end: int | None = None) -> tuple[Span, ...]:
125
+ """Return characters ``start`` to ``end`` as runs of one style."""
126
+ end = len(self.chars) if end is None else min(end, len(self.chars))
127
+ spans: list[Span] = []
128
+ run_start = start
129
+ for index in range(start + 1, end + 1):
130
+ if index == end or self.styles[index] != self.styles[run_start]:
131
+ if end > run_start:
132
+ spans.append(Span("".join(self.chars[run_start:index]), self.styles[run_start]))
133
+ run_start = index
134
+ return tuple(spans)
135
+
136
+ def rows(self, width: int) -> list[tuple[int, int]]:
137
+ """Return the character ranges ``(start, end)`` this line wraps into at ``width`` columns.
138
+
139
+ An empty line is one empty row. A glyph wider than the room goes on a row of its own rather than being
140
+ cut in half.
141
+ """
142
+ width = max(1, width)
143
+ if self.width <= width:
144
+ return [(0, len(self.chars))]
145
+ rows: list[tuple[int, int]] = []
146
+ start = used = 0
147
+ for index, character in enumerate(self.chars):
148
+ cells = character_width(character)
149
+ if used + cells > width and index > start:
150
+ rows.append((start, index))
151
+ start, used = index, 0
152
+ used += cells
153
+ rows.append((start, len(self.chars)))
154
+ return rows
155
+
156
+
157
+ class AnsiBuffer:
158
+ """A bounded scrollback that understands what programs print.
159
+
160
+ Args:
161
+ max_lines: Most lines kept; the oldest go first.
162
+ colors: The sixteen colours the SGR codes pick from.
163
+ """
164
+
165
+ def __init__(self, max_lines: int = 5000, colors: Sequence[str] = ANSI_COLORS) -> None:
166
+ self.max_lines = max(1, max_lines)
167
+ self.colors = tuple(colors)
168
+ self.lines: list[AnsiLine] = [AnsiLine()]
169
+ #: Lines dropped from the front since the buffer began, so a reader can tell the log was cut.
170
+ self.dropped = 0
171
+ self._column = 0
172
+ self._pen = DEFAULT_STYLE
173
+ self._pending = ""
174
+ self._started = 0
175
+
176
+ def __len__(self) -> int:
177
+ return len(self.lines)
178
+
179
+ @property
180
+ def text(self) -> str:
181
+ """Return the visible text, lines joined by newlines, without styles."""
182
+ return "\n".join(line.text for line in self.lines)
183
+
184
+ def clear(self) -> None:
185
+ """Forget every line and put the pen back to the default style."""
186
+ self.dropped += len(self.lines) - 1
187
+ self.lines = [AnsiLine()]
188
+ self._column = 0
189
+ self._pen = DEFAULT_STYLE
190
+ self._pending = ""
191
+
192
+ def write(self, text: str, style: Style | None = None) -> int:
193
+ """Append ``text`` and return how many lines it started.
194
+
195
+ Args:
196
+ text: What the program printed, escape sequences and all.
197
+ style: The style the text is written in until its own sequences change it; the default when omitted.
198
+ It is used only for this call, and the pen the program set is kept for the next one.
199
+ """
200
+ started = self._started
201
+ saved = self._pen
202
+ if style is not None:
203
+ self._pen = style
204
+ text = self._pending + text
205
+ self._pending = ""
206
+ index, size = 0, len(text)
207
+ while index < size:
208
+ character = text[index]
209
+ if character == "\x1b":
210
+ end = self._escape(text, index)
211
+ if end is None:
212
+ self._pending = text[index:] if size - index <= MAX_PENDING else ""
213
+ break
214
+ index = end
215
+ continue
216
+ index += 1
217
+ if character == "\n":
218
+ self._new_line()
219
+ elif character == "\r":
220
+ self._column = 0
221
+ elif character == "\b":
222
+ self._column = max(0, self._column - 1)
223
+ elif character == "\t":
224
+ for _ in range(TAB_WIDTH - self._column % TAB_WIDTH):
225
+ self._put(" ")
226
+ elif character >= " " and character != "\x7f":
227
+ self._put(character)
228
+ if style is not None:
229
+ self._pen = saved
230
+ return self._started - started
231
+
232
+ # -- one line at a time -------------------------------------------------
233
+ def _put(self, character: str) -> None:
234
+ self.lines[-1].put(self._column, character, self._pen)
235
+ self._column += 1
236
+
237
+ def _new_line(self) -> None:
238
+ self.lines.append(AnsiLine())
239
+ self._started += 1
240
+ self._column = 0
241
+ if len(self.lines) > self.max_lines:
242
+ del self.lines[0]
243
+ self.dropped += 1
244
+
245
+ # -- escape sequences ---------------------------------------------------
246
+ def _escape(self, text: str, start: int) -> int | None:
247
+ """Apply the sequence beginning at ``start``; return where the text goes on, or ``None`` if it is cut."""
248
+ if start + 1 >= len(text):
249
+ return None
250
+ kind = text[start + 1]
251
+ if kind == "[":
252
+ index = start + 2
253
+ while index < len(text) and text[index] in "0123456789;:?<=>! ":
254
+ index += 1
255
+ if index >= len(text):
256
+ return None
257
+ final = text[index]
258
+ if "@" <= final <= "~":
259
+ self._csi(text[start + 2 : index], final)
260
+ return index + 1
261
+ return index # not a sequence after all: drop the introducer and what was read
262
+ if kind == "]":
263
+ index = start + 2
264
+ while index < len(text):
265
+ if text[index] == "\x07":
266
+ return index + 1
267
+ if text[index] == "\x1b":
268
+ return index + 2 if index + 1 < len(text) else None
269
+ index += 1
270
+ return None
271
+ if kind in "()*+#%":
272
+ return start + 3 if start + 2 < len(text) else None
273
+ return start + 2
274
+
275
+ def _csi(self, parameters: str, final: str) -> None:
276
+ """Act on one control sequence: colours, and the few edits to the current line."""
277
+ numbers = self._numbers(parameters)
278
+ first = numbers[0] if numbers else 0
279
+ if final == "m":
280
+ self._sgr(numbers or [0])
281
+ elif final == "K":
282
+ line = self.lines[-1]
283
+ if first == 0:
284
+ line.truncate(self._column)
285
+ elif first == 1:
286
+ line.blank(self._column + 1)
287
+ else:
288
+ line.truncate(0)
289
+ elif final == "G":
290
+ self._column = max(0, (first or 1) - 1)
291
+ elif final == "C":
292
+ self._column += first or 1
293
+ elif final == "D":
294
+ self._column = max(0, self._column - (first or 1))
295
+ elif final == "J" and first in (2, 3):
296
+ self.clear()
297
+
298
+ @staticmethod
299
+ def _numbers(parameters: str) -> list[int]:
300
+ """Read the parameters of a sequence as numbers, an empty one being 0.
301
+
302
+ The colon form (``38:2::255:0:0``, ``4:3``) is turned into the semicolon form every program also understands: a
303
+ colour keeps its channels and loses the empty colour-space slot, and any other sub-parameter list keeps only
304
+ its first number, which is the attribute.
305
+ """
306
+ numbers: list[int] = []
307
+ for group in parameters.split(";"):
308
+ parts = [int(part) if part.isdigit() else 0 for part in group.split(":")]
309
+ if len(parts) > 1 and parts[0] in (38, 48):
310
+ if parts[1] == 2 and len(parts) >= 6:
311
+ parts = [parts[0], 2, *parts[-3:]]
312
+ numbers.extend(parts)
313
+ else:
314
+ numbers.append(parts[0])
315
+ return numbers
316
+
317
+ def _sgr(self, codes: list[int]) -> None:
318
+ """Change the pen: the "select graphic rendition" codes."""
319
+ pen = self._pen
320
+ index = 0
321
+ while index < len(codes):
322
+ code = codes[index]
323
+ index += 1
324
+ if code == 0:
325
+ pen = DEFAULT_STYLE
326
+ elif code == 1:
327
+ pen = replace(pen, bold=True)
328
+ elif code == 2:
329
+ pen = replace(pen, dim=True)
330
+ elif code == 3:
331
+ pen = replace(pen, italic=True)
332
+ elif code == 7:
333
+ pen = replace(pen, reverse=True)
334
+ elif code == 9:
335
+ pen = replace(pen, strike=True)
336
+ elif code == 22:
337
+ pen = replace(pen, bold=False, dim=False)
338
+ elif code == 23:
339
+ pen = replace(pen, italic=False)
340
+ elif code == 27:
341
+ pen = replace(pen, reverse=False)
342
+ elif code == 29:
343
+ pen = replace(pen, strike=False)
344
+ elif 30 <= code <= 37:
345
+ pen = replace(pen, foreground=self.colors[code - 30])
346
+ elif code == 39:
347
+ pen = replace(pen, foreground=None)
348
+ elif 40 <= code <= 47:
349
+ pen = replace(pen, background=self.colors[code - 40])
350
+ elif code == 49:
351
+ pen = replace(pen, background=None)
352
+ elif 90 <= code <= 97:
353
+ pen = replace(pen, foreground=self.colors[code - 90 + 8])
354
+ elif 100 <= code <= 107:
355
+ pen = replace(pen, background=self.colors[code - 100 + 8])
356
+ elif code in (38, 48):
357
+ colour, index = self._extended(codes, index)
358
+ if colour is not None:
359
+ pen = replace(pen, foreground=colour) if code == 38 else replace(pen, background=colour)
360
+ self._pen = pen
361
+
362
+ def _extended(self, codes: list[int], index: int) -> tuple[str | None, int]:
363
+ """Read the colour after a 38 or 48: ``5;n`` for the 256-colour palette or ``2;r;g;b`` for true colour."""
364
+ if index < len(codes) and codes[index] == 5 and index + 1 < len(codes):
365
+ return xterm_color(codes[index + 1]) if codes[index + 1] < 256 else None, index + 2
366
+ if index < len(codes) and codes[index] == 2:
367
+ channels = codes[index + 1 : index + 4]
368
+ if len(channels) == 3 and all(0 <= value < 256 for value in channels):
369
+ return "#{:02x}{:02x}{:02x}".format(*channels), index + 4
370
+ return None, len(codes)
371
+ return None, len(codes)