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.
- zettcode/tui/__init__.py +422 -0
- zettcode/tui/_compat.py +32 -0
- zettcode/tui/capabilities.py +107 -0
- zettcode/tui/clipboard.py +91 -0
- zettcode/tui/console.py +229 -0
- zettcode/tui/core/__init__.py +63 -0
- zettcode/tui/core/app.py +658 -0
- zettcode/tui/core/events.py +134 -0
- zettcode/tui/core/focus.py +85 -0
- zettcode/tui/core/geometry.py +212 -0
- zettcode/tui/core/host.py +66 -0
- zettcode/tui/core/keymap.py +218 -0
- zettcode/tui/core/scheduler.py +105 -0
- zettcode/tui/core/screen.py +80 -0
- zettcode/tui/core/theme.py +248 -0
- zettcode/tui/core/widget.py +204 -0
- zettcode/tui/gallery.py +588 -0
- zettcode/tui/glyphs.py +73 -0
- zettcode/tui/input/__init__.py +18 -0
- zettcode/tui/input/bridge.py +46 -0
- zettcode/tui/input/decoder.py +234 -0
- zettcode/tui/input/events.py +64 -0
- zettcode/tui/input/keys.py +289 -0
- zettcode/tui/input/reader.py +147 -0
- zettcode/tui/layout/__init__.py +24 -0
- zettcode/tui/layout/box.py +153 -0
- zettcode/tui/layout/overlay.py +164 -0
- zettcode/tui/layout/scroll.py +477 -0
- zettcode/tui/layout/solver.py +95 -0
- zettcode/tui/layout/spacing.py +137 -0
- zettcode/tui/py.typed +0 -0
- zettcode/tui/render/__init__.py +71 -0
- zettcode/tui/render/ansi.py +371 -0
- zettcode/tui/render/canvas.py +153 -0
- zettcode/tui/render/code.py +456 -0
- zettcode/tui/render/color.py +177 -0
- zettcode/tui/render/renderer.py +151 -0
- zettcode/tui/render/rich_text.py +80 -0
- zettcode/tui/render/style.py +121 -0
- zettcode/tui/render/sweep.py +87 -0
- zettcode/tui/render/text.py +319 -0
- zettcode/tui/runner.py +316 -0
- zettcode/tui/terminal.py +222 -0
- zettcode/tui/testing/__init__.py +6 -0
- zettcode/tui/testing/harness.py +220 -0
- zettcode/tui/testing/snapshot.py +64 -0
- zettcode/tui/theme_file.py +300 -0
- zettcode/tui/themes/ayu-mirage.toml +44 -0
- zettcode/tui/themes/catppuccin-latte.toml +44 -0
- zettcode/tui/themes/catppuccin-mocha.toml +44 -0
- zettcode/tui/themes/dracula.toml +44 -0
- zettcode/tui/themes/github-dimmed.toml +44 -0
- zettcode/tui/themes/github-light.toml +44 -0
- zettcode/tui/themes/gruvbox-dark.toml +44 -0
- zettcode/tui/themes/gruvbox-light.toml +44 -0
- zettcode/tui/themes/kanagawa.toml +44 -0
- zettcode/tui/themes/nord.toml +44 -0
- zettcode/tui/themes/one-dark.toml +44 -0
- zettcode/tui/themes/rose-pine-dawn.toml +44 -0
- zettcode/tui/themes/rose-pine.toml +44 -0
- zettcode/tui/themes/solarized-dark.toml +44 -0
- zettcode/tui/themes/solarized-light.toml +44 -0
- zettcode/tui/themes/tokyo-night.toml +44 -0
- zettcode/tui/widgets/__init__.py +121 -0
- zettcode/tui/widgets/collapsible.py +116 -0
- zettcode/tui/widgets/completion.py +211 -0
- zettcode/tui/widgets/console.py +442 -0
- zettcode/tui/widgets/dialog.py +165 -0
- zettcode/tui/widgets/diff.py +236 -0
- zettcode/tui/widgets/list.py +293 -0
- zettcode/tui/widgets/list_page.py +121 -0
- zettcode/tui/widgets/markdown.py +657 -0
- zettcode/tui/widgets/progress.py +166 -0
- zettcode/tui/widgets/rich_text.py +84 -0
- zettcode/tui/widgets/status.py +106 -0
- zettcode/tui/widgets/table.py +101 -0
- zettcode/tui/widgets/tasks.py +130 -0
- zettcode/tui/widgets/text.py +111 -0
- zettcode/tui/widgets/textarea.py +671 -0
- zettcode/tui/widgets/toast.py +137 -0
- zettcode_tui-0.4.0.dist-info/METADATA +20 -0
- zettcode_tui-0.4.0.dist-info/RECORD +83 -0
- zettcode_tui-0.4.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Unicode-aware text measurement, wrapping, and clamping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
|
|
8
|
+
from wcwidth import wcwidth
|
|
9
|
+
|
|
10
|
+
from .style import Span, Style
|
|
11
|
+
|
|
12
|
+
ELLIPSIS = "…"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cell_glyph(character: str) -> tuple[str, int]:
|
|
16
|
+
"""Return the paintable glyph and the columns it occupies.
|
|
17
|
+
|
|
18
|
+
Combining marks stay zero-width. Control characters cannot be painted
|
|
19
|
+
safely, so they are replaced by a single-column placeholder rather than
|
|
20
|
+
being allowed to reach the terminal as an escape.
|
|
21
|
+
"""
|
|
22
|
+
width = wcwidth(character)
|
|
23
|
+
if width < 0:
|
|
24
|
+
return "�", 1
|
|
25
|
+
return character, width
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@lru_cache(maxsize=1 << 16)
|
|
29
|
+
def character_width(character: str) -> int:
|
|
30
|
+
"""Return the columns one character occupies on screen.
|
|
31
|
+
|
|
32
|
+
Remembered, because the same few thousand characters make up almost all of the
|
|
33
|
+
text a terminal shows, and a cache hit is answered without running any Python:
|
|
34
|
+
measuring a screenful of Chinese is a hundred thousand of these.
|
|
35
|
+
"""
|
|
36
|
+
return cell_glyph(character)[1]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def display_width(text: str) -> int:
|
|
40
|
+
"""Return the columns a string occupies, counting wide glyphs as two."""
|
|
41
|
+
if text.isascii() and text.isprintable():
|
|
42
|
+
# Printable ASCII is one column a character, and it is nearly all of what a
|
|
43
|
+
# terminal shows; measuring it one character at a time is the cost this skips.
|
|
44
|
+
return len(text)
|
|
45
|
+
return sum(map(character_width, text))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def slice_columns(text: str, start: int, end: int) -> str:
|
|
49
|
+
"""Return the characters overlapping the half-open column range.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
text: Source string measured in display columns, not code points.
|
|
53
|
+
start: First column to include.
|
|
54
|
+
end: Column to stop before; a wide glyph is kept when it overlaps the
|
|
55
|
+
range at all, so the result can be one column wider than requested.
|
|
56
|
+
"""
|
|
57
|
+
output: list[str] = []
|
|
58
|
+
column = 0
|
|
59
|
+
for character in text:
|
|
60
|
+
width = character_width(character)
|
|
61
|
+
if column >= end:
|
|
62
|
+
break
|
|
63
|
+
if column + width > start:
|
|
64
|
+
output.append(character)
|
|
65
|
+
column += width
|
|
66
|
+
return "".join(output)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def truncate(text: str, width: int, *, ellipsis: str = ELLIPSIS) -> str:
|
|
70
|
+
"""Clamp text to a column budget, reserving room for the ellipsis.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
text: Source string.
|
|
74
|
+
width: Column budget; zero or less yields an empty string.
|
|
75
|
+
ellipsis: Suffix appended when text is cut; dropped when it would not
|
|
76
|
+
itself fit in ``width``.
|
|
77
|
+
"""
|
|
78
|
+
if width <= 0:
|
|
79
|
+
return ""
|
|
80
|
+
if display_width(text) <= width:
|
|
81
|
+
return text
|
|
82
|
+
suffix = ellipsis if display_width(ellipsis) <= width else ""
|
|
83
|
+
# A wide glyph that straddles the cut is left out rather than kept whole: the budget is the budget,
|
|
84
|
+
# and a result one column over it shifts every column after it on that line (which is what made a
|
|
85
|
+
# truncated CJK title push a table's columns out by one).
|
|
86
|
+
remaining = width - display_width(suffix)
|
|
87
|
+
kept: list[str] = []
|
|
88
|
+
used = 0
|
|
89
|
+
for character in text:
|
|
90
|
+
size = character_width(character)
|
|
91
|
+
if used + size > remaining:
|
|
92
|
+
break
|
|
93
|
+
kept.append(character)
|
|
94
|
+
used += size
|
|
95
|
+
return "".join(kept) + suffix
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def truncate_spans(spans: Sequence[Span], width: int) -> tuple[Span, ...]:
|
|
99
|
+
"""Clamp styled fragments to a column budget, marking overflow with an ellipsis.
|
|
100
|
+
|
|
101
|
+
The styles travel with the characters they were attached to, so a clipped
|
|
102
|
+
line keeps every colour it had up to the cut and the ellipsis wears the last
|
|
103
|
+
surviving style.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
spans: Fragments in paint order.
|
|
107
|
+
width: Column budget; the ellipsis is carved out of it.
|
|
108
|
+
"""
|
|
109
|
+
if width <= 0:
|
|
110
|
+
return ()
|
|
111
|
+
if sum(span.width for span in spans) <= width:
|
|
112
|
+
return tuple(spans)
|
|
113
|
+
remaining = max(0, width - 1)
|
|
114
|
+
clipped: list[Span] = []
|
|
115
|
+
for span in spans:
|
|
116
|
+
text = ""
|
|
117
|
+
for character in span.text:
|
|
118
|
+
size = character_width(character)
|
|
119
|
+
if size > remaining:
|
|
120
|
+
break
|
|
121
|
+
text += character
|
|
122
|
+
remaining -= size
|
|
123
|
+
if text:
|
|
124
|
+
clipped.append(Span(text, span.style))
|
|
125
|
+
if remaining == 0 or len(text) < len(span.text):
|
|
126
|
+
break
|
|
127
|
+
style = clipped[-1].style if clipped else spans[0].style if spans else Style()
|
|
128
|
+
clipped.append(Span(ELLIPSIS, style))
|
|
129
|
+
return tuple(clipped)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def wrap_words(text: str, width: int) -> list[str]:
|
|
133
|
+
"""Wrap one logical line of prose at a column budget, breaking between words where it can.
|
|
134
|
+
|
|
135
|
+
A word that fits a row is never split: it moves to the next row whole, and the space it was set
|
|
136
|
+
off by is dropped at the break rather than starting a row with a gap. A word wider than a row of
|
|
137
|
+
its own — a long path, an address, text with no spaces at all — is broken at the budget, never
|
|
138
|
+
mid-character, because there is nowhere kinder to break it. Leading space is kept on the first row,
|
|
139
|
+
and a run of spaces inside a line that has to wrap becomes one.
|
|
140
|
+
|
|
141
|
+
This is for sentences; code and command output keep :func:`wrap_columns`, where a column is a
|
|
142
|
+
column and a space is a character to preserve.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
text: Source line; embedded newlines are not treated specially.
|
|
146
|
+
width: Column budget per row, floored at 1.
|
|
147
|
+
"""
|
|
148
|
+
width = max(1, width)
|
|
149
|
+
if display_width(text) <= width:
|
|
150
|
+
return [text]
|
|
151
|
+
indent = text[: len(text) - len(text.lstrip(" "))]
|
|
152
|
+
rows: list[str] = []
|
|
153
|
+
current = indent if display_width(indent) < width else ""
|
|
154
|
+
used = display_width(current)
|
|
155
|
+
for word in text.lstrip(" ").split(" "):
|
|
156
|
+
if not word:
|
|
157
|
+
continue
|
|
158
|
+
size = display_width(word)
|
|
159
|
+
gap = 1 if current.strip() else 0
|
|
160
|
+
if used + gap + size <= width:
|
|
161
|
+
current += (" " if gap else "") + word
|
|
162
|
+
used += gap + size
|
|
163
|
+
continue
|
|
164
|
+
if current.strip():
|
|
165
|
+
rows.append(current)
|
|
166
|
+
current, used = "", 0
|
|
167
|
+
pieces = wrap_columns(word, width) # a word that fits a row comes back whole, so only a longer one is cut
|
|
168
|
+
rows.extend(pieces[:-1])
|
|
169
|
+
current = pieces[-1]
|
|
170
|
+
used = display_width(current)
|
|
171
|
+
rows.append(current)
|
|
172
|
+
return rows or [""]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def wrap_columns(text: str, width: int) -> list[str]:
|
|
176
|
+
"""Hard-wrap one logical line at a column budget, never mid-character.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
text: Source line; embedded newlines are not treated specially.
|
|
180
|
+
width: Column budget per row, floored at 1.
|
|
181
|
+
"""
|
|
182
|
+
width = max(1, width)
|
|
183
|
+
if text.isascii() and text.isprintable():
|
|
184
|
+
# One column a character, so a row is exactly ``width`` characters and the
|
|
185
|
+
# last is whatever is left. An empty line is still one (empty) row.
|
|
186
|
+
return [text[start : start + width] for start in range(0, len(text), width)] or [""]
|
|
187
|
+
lines: list[str] = []
|
|
188
|
+
current = ""
|
|
189
|
+
used = 0
|
|
190
|
+
for character in text:
|
|
191
|
+
char_width = character_width(character)
|
|
192
|
+
if current and used + char_width > width:
|
|
193
|
+
lines.append(current)
|
|
194
|
+
current, used = "", 0
|
|
195
|
+
current += character
|
|
196
|
+
used += char_width
|
|
197
|
+
lines.append(current)
|
|
198
|
+
return lines
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def count_wrapped_rows(text: str, width: int) -> int:
|
|
202
|
+
"""Return how many rows :func:`wrap_columns` would make of one line, without making them.
|
|
203
|
+
|
|
204
|
+
A caller that only needs to say how many rows lie beyond the ones it shows — a
|
|
205
|
+
tool result's "… 40 more rows" — should not build every one of them to count.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
text: Source line; embedded newlines are not treated specially.
|
|
209
|
+
width: Column budget per row, floored at 1.
|
|
210
|
+
"""
|
|
211
|
+
width = max(1, width)
|
|
212
|
+
if text.isascii() and text.isprintable():
|
|
213
|
+
return max(1, -(-len(text) // width))
|
|
214
|
+
return len(wrap_columns(text, width))
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def expand_tabs(text: str, *, tab_size: int = 4, start_column: int = 0) -> str:
|
|
218
|
+
"""Replace tabs with spaces aligned to fixed tab stops.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
text: Source string.
|
|
222
|
+
tab_size: Cells between tab stops.
|
|
223
|
+
start_column: Column the text begins at, so tab stops continue from the
|
|
224
|
+
caller's indentation rather than restarting at zero.
|
|
225
|
+
"""
|
|
226
|
+
expanded: list[str] = []
|
|
227
|
+
column = start_column
|
|
228
|
+
for character in text:
|
|
229
|
+
if character != "\t":
|
|
230
|
+
expanded.append(character)
|
|
231
|
+
column += character_width(character)
|
|
232
|
+
continue
|
|
233
|
+
spaces = tab_size - (column % tab_size)
|
|
234
|
+
expanded.append(" " * spaces)
|
|
235
|
+
column += spaces
|
|
236
|
+
return "".join(expanded)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def expand_span_tabs(spans: Sequence[Span], *, tab_size: int = 4, start_column: int = 0) -> tuple[Span, ...]:
|
|
240
|
+
"""Expand tabs across span boundaries while preserving their styles.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
spans: Fragments that may contain tabs.
|
|
244
|
+
tab_size: Cells between tab stops.
|
|
245
|
+
start_column: Column the first span begins at.
|
|
246
|
+
"""
|
|
247
|
+
expanded: list[Span] = []
|
|
248
|
+
column = start_column
|
|
249
|
+
for span in spans:
|
|
250
|
+
if "\t" not in span.text:
|
|
251
|
+
expanded.append(span)
|
|
252
|
+
column += display_width(span.text)
|
|
253
|
+
continue
|
|
254
|
+
chunk = ""
|
|
255
|
+
for character in span.text:
|
|
256
|
+
if character == "\t":
|
|
257
|
+
spaces = tab_size - (column % tab_size)
|
|
258
|
+
chunk += " " * spaces
|
|
259
|
+
column += spaces
|
|
260
|
+
else:
|
|
261
|
+
chunk += character
|
|
262
|
+
column += character_width(character)
|
|
263
|
+
if chunk:
|
|
264
|
+
expanded.append(Span(chunk, span.style))
|
|
265
|
+
return tuple(expanded)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def wrap_spans(spans: Sequence[Span], width: int) -> list[tuple[Span, ...]]:
|
|
269
|
+
"""Hard-wrap styled runs at a column budget, never mid-character.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
spans: Styled fragments forming one logical line.
|
|
273
|
+
width: Column budget per row, floored at 1.
|
|
274
|
+
|
|
275
|
+
Returns:
|
|
276
|
+
One span tuple per row; a fragment split across rows keeps its style.
|
|
277
|
+
"""
|
|
278
|
+
width = max(1, width)
|
|
279
|
+
rows: list[tuple[Span, ...]] = []
|
|
280
|
+
row: list[Span] = []
|
|
281
|
+
chunk = ""
|
|
282
|
+
chunk_style: Style = Style()
|
|
283
|
+
used = 0
|
|
284
|
+
for span in spans:
|
|
285
|
+
text = span.text
|
|
286
|
+
if not text:
|
|
287
|
+
continue
|
|
288
|
+
span_width = display_width(text)
|
|
289
|
+
if used + span_width <= width:
|
|
290
|
+
# The whole fragment fits on this row, so no character of it can wrap:
|
|
291
|
+
# it joins the run in progress when the style is the same and starts a
|
|
292
|
+
# new one when it is not, exactly as placing it character by character
|
|
293
|
+
# would, without visiting each character to say so.
|
|
294
|
+
if chunk and chunk_style != span.style:
|
|
295
|
+
row.append(Span(chunk, chunk_style))
|
|
296
|
+
chunk = ""
|
|
297
|
+
chunk_style = span.style
|
|
298
|
+
chunk += text
|
|
299
|
+
used += span_width
|
|
300
|
+
continue
|
|
301
|
+
for character in text:
|
|
302
|
+
char_width = character_width(character)
|
|
303
|
+
if used and used + char_width > width:
|
|
304
|
+
if chunk:
|
|
305
|
+
row.append(Span(chunk, chunk_style))
|
|
306
|
+
chunk = ""
|
|
307
|
+
rows.append(tuple(row))
|
|
308
|
+
row = []
|
|
309
|
+
used = 0
|
|
310
|
+
if chunk and chunk_style != span.style:
|
|
311
|
+
row.append(Span(chunk, chunk_style))
|
|
312
|
+
chunk = ""
|
|
313
|
+
chunk_style = span.style
|
|
314
|
+
chunk += character
|
|
315
|
+
used += char_width
|
|
316
|
+
if chunk:
|
|
317
|
+
row.append(Span(chunk, chunk_style))
|
|
318
|
+
rows.append(tuple(row))
|
|
319
|
+
return rows
|
zettcode/tui/runner.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Own a real terminal and drive a TuiApp until it exits.
|
|
2
|
+
|
|
3
|
+
The loop has one job: paint when a frame is due, and sleep otherwise without
|
|
4
|
+
missing a repaint that a background task asked for while it slept. Two sources
|
|
5
|
+
wake it — terminal input and the scheduler's wake-up callback — plus a timeout
|
|
6
|
+
that bounds animation.
|
|
7
|
+
|
|
8
|
+
Lifecycle and steady state:
|
|
9
|
+
|
|
10
|
+
streaming task TuiApp / Scheduler TerminalRunner AsyncInput TTY
|
|
11
|
+
| | | | |
|
|
12
|
+
-----+--------------------+---------------------+-------------------+-------------+----- startup
|
|
13
|
+
| | with terminal: raw mode, alternate screen,
|
|
14
|
+
| | bracketed paste, button-event mouse tracking
|
|
15
|
+
| |<-- resize(size) ----|------------------>| |
|
|
16
|
+
| |<-- set_copy_handler-| | |
|
|
17
|
+
| |<-- mount() ---------| attach + focus first Tab stop |
|
|
18
|
+
| |<-- on_request = wakeup.set | |
|
|
19
|
+
| | |-- start() ------->| add_reader |
|
|
20
|
+
| | | | (SIGWINCH; |
|
|
21
|
+
| | | | a thread on|
|
|
22
|
+
| | | | Windows) |
|
|
23
|
+
-----+--------------------+---------------------+-------------------+-------------+----- frame
|
|
24
|
+
| |<-- poll(now) -------| | |
|
|
25
|
+
| |--- due ------------>| | |
|
|
26
|
+
| |<-- tick(), render() | | |
|
|
27
|
+
| |--- Canvas --------->|-- ANSI diff ------------------->|
|
|
28
|
+
| |<-- delay() ---------| (None when idle) | |
|
|
29
|
+
| | | | |
|
|
30
|
+
-----+--------------------+---------------------+-------------------+-------------+----- idle
|
|
31
|
+
| | |== await wait {input, wakeup}, timeout
|
|
32
|
+
| | | | |
|
|
33
|
+
key press ----------------|---------------------|<-- InputEvent ----| |
|
|
34
|
+
| |<-- dispatch(event) -| (translated) | |
|
|
35
|
+
| | | | |
|
|
36
|
+
append + invalidate ----->|-- request_repaint()>| | |
|
|
37
|
+
| |--- wakeup.set() --->| wait returns | |
|
|
38
|
+
| |<-- poll(now) -------| back to frame | |
|
|
39
|
+
| | | | |
|
|
40
|
+
-----+--------------------+---------------------+-------------------+-------------+----- shutdown
|
|
41
|
+
| |<-- close() ---------| cancel input task, clear on_request,
|
|
42
|
+
| | | reader.close(), app.close(),
|
|
43
|
+
| | | terminal restored
|
|
44
|
+
|
|
45
|
+
Without the wake-up callback the loop would park on an empty input queue with an
|
|
46
|
+
infinite timeout and stay there until the user pressed a key, so a streamed
|
|
47
|
+
answer would never appear. ``TuiApp.invalidate`` is therefore wired to the same
|
|
48
|
+
event the loop is already waiting on.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import asyncio
|
|
54
|
+
import os
|
|
55
|
+
from collections.abc import Callable, Mapping
|
|
56
|
+
|
|
57
|
+
import pyperclip
|
|
58
|
+
|
|
59
|
+
from .clipboard import copy_route, osc52
|
|
60
|
+
from .core.app import TuiApp
|
|
61
|
+
from .core.events import ResizeEvent
|
|
62
|
+
from .core.theme import scheme_named, theme_named
|
|
63
|
+
from .input import AsyncInput, EventType, InputEvent, translate
|
|
64
|
+
from .render import DifferentialRenderer
|
|
65
|
+
from .terminal import Terminal, parse_background, title_sequence
|
|
66
|
+
|
|
67
|
+
#: Most queued events applied before the next frame is drawn. Large enough that a burst of wheel notches
|
|
68
|
+
#: or a held key is one frame, small enough that a flood of input still gets painted.
|
|
69
|
+
MAX_BATCH = 256
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class TerminalRunner:
|
|
73
|
+
"""Drive one TuiApp from a real terminal, owning every resource it needs."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, app: TuiApp, *, terminal: Terminal | None = None) -> None:
|
|
76
|
+
"""Bind the app to a terminal renderer, an input queue, and a wake-up event.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
app: The tree to drive; it is mounted inside ``run``.
|
|
80
|
+
terminal: Terminal to own; a default one wraps stdin and stdout.
|
|
81
|
+
"""
|
|
82
|
+
self.app = app
|
|
83
|
+
self.terminal = terminal or Terminal()
|
|
84
|
+
self.renderer = DifferentialRenderer(
|
|
85
|
+
self.terminal.output,
|
|
86
|
+
color_depth=self.terminal.capabilities.color_depth,
|
|
87
|
+
)
|
|
88
|
+
self.queue: asyncio.Queue[InputEvent] = asyncio.Queue()
|
|
89
|
+
self.wakeup = asyncio.Event()
|
|
90
|
+
self.reader: AsyncInput | None = None
|
|
91
|
+
self._input: asyncio.Task[InputEvent] | None = None
|
|
92
|
+
self._title = ""
|
|
93
|
+
self._after_paint: list[Callable[[], None]] = []
|
|
94
|
+
|
|
95
|
+
def after_next_paint(self, callback: Callable[[], None]) -> None:
|
|
96
|
+
"""Run ``callback`` once, right after the next frame has been written.
|
|
97
|
+
|
|
98
|
+
For work that must not compete with a frame the reader is waiting for. The
|
|
99
|
+
interpreter runs one thread's Python at a time, so a worker that starts
|
|
100
|
+
before the frame is drawn takes turns with the drawing, and the frame is
|
|
101
|
+
what pays: each time the loop wakes it queues behind the worker for the
|
|
102
|
+
lock. Starting the worker from here lets the frame finish first.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
callback: Called on the loop, after the terminal has the frame. An
|
|
106
|
+
exception it raises propagates out of the paint like any other.
|
|
107
|
+
"""
|
|
108
|
+
self._after_paint.append(callback)
|
|
109
|
+
|
|
110
|
+
async def run(self) -> None:
|
|
111
|
+
"""Enter raw mode and loop until the application exits."""
|
|
112
|
+
app = self.app
|
|
113
|
+
with self.terminal:
|
|
114
|
+
app.resize(*self.terminal.size)
|
|
115
|
+
app.set_copy_handler(clipboard_writer(self.terminal))
|
|
116
|
+
app.mount()
|
|
117
|
+
app.begin_painting()
|
|
118
|
+
app.scheduler.on_request = self.wakeup.set
|
|
119
|
+
# The interface goes up before the terminal is asked anything. A
|
|
120
|
+
# terminal that does not answer the background query — multiplexers
|
|
121
|
+
# and editors commonly do not — costs a full timeout, and that wait
|
|
122
|
+
# must not be the blank screen a reader stares at. Adopting a scheme
|
|
123
|
+
# afterwards repaints every cell, so the palette still lands.
|
|
124
|
+
self.paint()
|
|
125
|
+
# The query goes out now and its answer comes back as input, so a
|
|
126
|
+
# terminal that never answers delays nothing on screen.
|
|
127
|
+
self._ask_terminal_scheme()
|
|
128
|
+
self.reader = AsyncInput(self.terminal, self.queue.put_nowait)
|
|
129
|
+
self.reader.start()
|
|
130
|
+
# One long-lived reader task: cancelling a pending queue.get() can
|
|
131
|
+
# drop an item, so the loop keeps the same task and replaces it only
|
|
132
|
+
# after it delivers.
|
|
133
|
+
self._input = asyncio.ensure_future(self.queue.get())
|
|
134
|
+
try:
|
|
135
|
+
while app.running:
|
|
136
|
+
if app.scheduler.poll(now=app.clock()):
|
|
137
|
+
self.paint(animation_only=not app.scheduler.requested)
|
|
138
|
+
if not app.running:
|
|
139
|
+
break
|
|
140
|
+
await self.wait_for_work()
|
|
141
|
+
if self._input.done():
|
|
142
|
+
raw = self._input.result()
|
|
143
|
+
self._input = asyncio.ensure_future(self.queue.get())
|
|
144
|
+
self.deliver(raw)
|
|
145
|
+
self._deliver_pending()
|
|
146
|
+
finally:
|
|
147
|
+
await self._shutdown()
|
|
148
|
+
|
|
149
|
+
def _deliver_pending(self) -> None:
|
|
150
|
+
"""Hand over every event that is already waiting, so one frame answers all of them.
|
|
151
|
+
|
|
152
|
+
A wheel flick or a held key reaches the queue as a burst, and delivering one event per trip
|
|
153
|
+
round the loop paints between each: a hundred and twenty notches measured a hundred and twenty
|
|
154
|
+
full frames and three quarters of a second before the view stopped moving, the screen crawling
|
|
155
|
+
through positions the reader had already scrolled past. What is queued has all happened, so
|
|
156
|
+
it is applied together and drawn once. The batch is bounded, so a flood cannot starve the
|
|
157
|
+
frame it is waiting for, and it stops the moment the app is leaving.
|
|
158
|
+
"""
|
|
159
|
+
for _ in range(MAX_BATCH):
|
|
160
|
+
if not self.app.running:
|
|
161
|
+
return
|
|
162
|
+
try:
|
|
163
|
+
raw = self.queue.get_nowait()
|
|
164
|
+
except asyncio.QueueEmpty:
|
|
165
|
+
return
|
|
166
|
+
self.deliver(raw)
|
|
167
|
+
|
|
168
|
+
def paint(self, *, animation_only: bool = False) -> None:
|
|
169
|
+
"""Draw one frame into the terminal, unless it would only repeat the last one.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
animation_only: The frame is due because an animation's interval ran out and
|
|
173
|
+
nothing else asked for it. The widgets are still given the clock, because
|
|
174
|
+
that is how an animation moves; when none of them reports a change, nothing
|
|
175
|
+
else is pending and no one is waiting on the frame, it is skipped whole —
|
|
176
|
+
no canvas, no diff, no write. Most frames of a long wait are skipped this
|
|
177
|
+
way: the picture changes a few dozen times a second where the frames come a
|
|
178
|
+
hundred and twenty, and building every one cost a third of a core.
|
|
179
|
+
"""
|
|
180
|
+
refreshed = self.app.refreshed
|
|
181
|
+
if refreshed:
|
|
182
|
+
self.app.refreshed = False
|
|
183
|
+
self.renderer.reset()
|
|
184
|
+
changed = self.app.tick()
|
|
185
|
+
if (
|
|
186
|
+
animation_only
|
|
187
|
+
and not (refreshed or changed or self._after_paint)
|
|
188
|
+
and not (self.app.scheduler.pending or self.app.layout_pending or self.app.waiting_for_frame)
|
|
189
|
+
):
|
|
190
|
+
return
|
|
191
|
+
self._sync_title()
|
|
192
|
+
canvas = self.app.render()
|
|
193
|
+
cursor = self.app.cursor()
|
|
194
|
+
self.renderer.render(canvas, cursor=None if cursor is None else (cursor.x, cursor.y))
|
|
195
|
+
self.app.frame_painted()
|
|
196
|
+
callbacks, self._after_paint = self._after_paint, []
|
|
197
|
+
for callback in callbacks:
|
|
198
|
+
callback()
|
|
199
|
+
|
|
200
|
+
def _ask_terminal_scheme(self) -> None:
|
|
201
|
+
"""Ask the terminal which palette its background calls for, when allowed."""
|
|
202
|
+
if self.app.auto_theme:
|
|
203
|
+
self.terminal.query_background()
|
|
204
|
+
|
|
205
|
+
def _adopt_terminal_scheme(self, reply: str) -> None:
|
|
206
|
+
"""Take the palette the terminal's answer names, when it names one.
|
|
207
|
+
|
|
208
|
+
A terminal that answers something else, or nothing at all, leaves the
|
|
209
|
+
app on the palette it was built with: this is a preference, not a
|
|
210
|
+
requirement.
|
|
211
|
+
"""
|
|
212
|
+
scheme = scheme_named(parse_background(reply))
|
|
213
|
+
if scheme is not None:
|
|
214
|
+
self.app.theme = theme_named(scheme)
|
|
215
|
+
self.renderer.reset()
|
|
216
|
+
|
|
217
|
+
def _sync_title(self) -> None:
|
|
218
|
+
"""Name the terminal window after what the app is working on.
|
|
219
|
+
|
|
220
|
+
The name is written once per change and handed back on shutdown, so a
|
|
221
|
+
tabbed terminal shows the session instead of the command that started it.
|
|
222
|
+
"""
|
|
223
|
+
wanted = self.app.title() if callable(self.app.title) else self.app.title
|
|
224
|
+
if wanted == self._title:
|
|
225
|
+
return
|
|
226
|
+
self._title = wanted
|
|
227
|
+
self.terminal.write(title_sequence(wanted))
|
|
228
|
+
|
|
229
|
+
def deliver(self, raw: InputEvent) -> None:
|
|
230
|
+
"""Translate one decoded terminal event and hand it to the app."""
|
|
231
|
+
if raw.type is EventType.REPLY:
|
|
232
|
+
self._adopt_terminal_scheme(raw.text)
|
|
233
|
+
return
|
|
234
|
+
event = translate(raw)
|
|
235
|
+
if isinstance(event, ResizeEvent):
|
|
236
|
+
width, height = self.terminal.size
|
|
237
|
+
self.renderer.reset()
|
|
238
|
+
self.app.dispatch(ResizeEvent(width=width, height=height))
|
|
239
|
+
return
|
|
240
|
+
if event is not None:
|
|
241
|
+
self.app.dispatch(event)
|
|
242
|
+
|
|
243
|
+
async def wait_for_work(self) -> None:
|
|
244
|
+
"""Sleep until input arrives, a repaint is requested, or a frame is due."""
|
|
245
|
+
waker = asyncio.ensure_future(self.wakeup.wait())
|
|
246
|
+
self.wakeup.clear()
|
|
247
|
+
try:
|
|
248
|
+
pending = {waker} if self._input is None else {self._input, waker}
|
|
249
|
+
await asyncio.wait(
|
|
250
|
+
pending,
|
|
251
|
+
timeout=self.app.scheduler.delay(now=self.app.clock()),
|
|
252
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
253
|
+
)
|
|
254
|
+
finally:
|
|
255
|
+
waker.cancel()
|
|
256
|
+
await asyncio.gather(waker, return_exceptions=True)
|
|
257
|
+
|
|
258
|
+
async def _shutdown(self) -> None:
|
|
259
|
+
"""Cancel the reader task and release the terminal and the widget tree."""
|
|
260
|
+
self.app.end_painting()
|
|
261
|
+
if self._input is not None:
|
|
262
|
+
self._input.cancel()
|
|
263
|
+
await asyncio.gather(self._input, return_exceptions=True)
|
|
264
|
+
self._input = None
|
|
265
|
+
self.app.scheduler.on_request = None
|
|
266
|
+
if self.reader is not None:
|
|
267
|
+
self.reader.close()
|
|
268
|
+
self.reader = None
|
|
269
|
+
self._title = ""
|
|
270
|
+
self.terminal.write(title_sequence(""))
|
|
271
|
+
self.app.close()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
async def run_app(app: TuiApp, *, terminal: Terminal | None = None) -> None:
|
|
275
|
+
"""Convenience wrapper for the common case of running one app once.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
app: The tree to drive.
|
|
279
|
+
terminal: Terminal to own; a default one is built when omitted.
|
|
280
|
+
"""
|
|
281
|
+
await TerminalRunner(app, terminal=terminal).run()
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def clipboard_writer(
|
|
285
|
+
terminal: Terminal,
|
|
286
|
+
*,
|
|
287
|
+
environ: Mapping[str, str] | None = None,
|
|
288
|
+
system: Callable[[str], object] = pyperclip.copy,
|
|
289
|
+
) -> Callable[[str], None]:
|
|
290
|
+
"""Copy to the clipboard the reader will paste from.
|
|
291
|
+
|
|
292
|
+
Which one that is depends on where the program runs (see :mod:`zettcode.tui.clipboard`):
|
|
293
|
+
over ``ssh`` the terminal's, reached with OSC 52, because a tool on the server would put the
|
|
294
|
+
text where the reader cannot paste it; anywhere else the system clipboard, with OSC 52 as the
|
|
295
|
+
fallback for a headless session that has no tool to reach.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
terminal: Where an OSC 52 sequence is written.
|
|
299
|
+
environ: Environment to read; defaults to ``os.environ``, looked at on every copy.
|
|
300
|
+
system: Writes the system clipboard; injectable so a test needs no desktop.
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
def write(text: str) -> None:
|
|
304
|
+
"""Handle one copy request from the app."""
|
|
305
|
+
env = os.environ if environ is None else environ
|
|
306
|
+
if copy_route(env) == "terminal":
|
|
307
|
+
terminal.write(osc52(text, env))
|
|
308
|
+
return
|
|
309
|
+
try:
|
|
310
|
+
system(text)
|
|
311
|
+
except (pyperclip.PyperclipException, OSError):
|
|
312
|
+
# Either the machine has no clipboard tool, or the one it has could not be run.
|
|
313
|
+
# A copy must never take the session down, and the terminal is a way out.
|
|
314
|
+
terminal.write(osc52(text, env))
|
|
315
|
+
|
|
316
|
+
return write
|