termite-tui 0.3.0__py3-none-win_amd64.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.
- termite_tui/__init__.py +314 -0
- termite_tui/authoring.py +76 -0
- termite_tui/capture.py +138 -0
- termite_tui/termite_ffi.dll +0 -0
- termite_tui/testing.py +319 -0
- termite_tui-0.3.0.dist-info/METADATA +114 -0
- termite_tui-0.3.0.dist-info/RECORD +11 -0
- termite_tui-0.3.0.dist-info/WHEEL +5 -0
- termite_tui-0.3.0.dist-info/licenses/LICENSE-APACHE +202 -0
- termite_tui-0.3.0.dist-info/licenses/LICENSE-MIT +21 -0
- termite_tui-0.3.0.dist-info/top_level.txt +1 -0
termite_tui/__init__.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Python facade over Termite's versioned shared library."""
|
|
2
|
+
|
|
3
|
+
import ctypes as ct
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import IntEnum
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Sequence
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
CAP_DASHBOARD_DOCUMENT = 1 << 0
|
|
14
|
+
CAP_INTERACTION_DOCUMENT = 1 << 1
|
|
15
|
+
CAP_CONTENT_DOCUMENT = 1 << 2
|
|
16
|
+
CAP_TRANSPORT_OPTIONS = 1 << 3
|
|
17
|
+
CAP_POINTER_BOUNDARIES = 1 << 4
|
|
18
|
+
CAP_FOCUS_EVENTS = 1 << 5
|
|
19
|
+
CAP_SCREEN_MODES = 1 << 6
|
|
20
|
+
CAP_HELP_PANELS = 1 << 7
|
|
21
|
+
CAP_MESSAGE_ROUTING = 1 << 8
|
|
22
|
+
CAP_REACTIVE_STATE = 1 << 9
|
|
23
|
+
CAP_SCROLL_REGIONS = 1 << 10
|
|
24
|
+
CAP_SCROLLBARS = 1 << 11
|
|
25
|
+
CAP_SCROLLBAR_INTERACTION = 1 << 12
|
|
26
|
+
CAP_SCROLLBAR_STYLESHEET = 1 << 13
|
|
27
|
+
CAP_THEME_PALETTES = 1 << 14
|
|
28
|
+
CAP_BORDER_CAPTIONS = 1 << 15
|
|
29
|
+
CAP_POINTER_SHAPES = 1 << 16
|
|
30
|
+
CAP_FORCE_SCROLL = 1 << 17
|
|
31
|
+
CAP_SESSION_SUBTITLE = 1 << 18
|
|
32
|
+
CAP_TERMINAL_SUSPENSION = 1 << 19
|
|
33
|
+
CAP_OUTPUT_ROUTING = 1 << 20
|
|
34
|
+
CAP_TIMER_CONTROL = 1 << 21
|
|
35
|
+
CAP_WORKER_GROUPS = 1 << 22
|
|
36
|
+
CAP_WORKER_PROGRESS = 1 << 23
|
|
37
|
+
CAP_TABLE_LABELS = 1 << 24
|
|
38
|
+
CAP_STYLED_TABLE_CELLS = 1 << 25
|
|
39
|
+
CAP_TABLE_ROW_HEIGHTS = 1 << 26
|
|
40
|
+
CAP_TABLE_ROW_STYLES = 1 << 27
|
|
41
|
+
CAP_TABLE_SORT_AND_WIDTHS = 1 << 28
|
|
42
|
+
CAP_FIELD_VALIDATORS = 1 << 29
|
|
43
|
+
CAP_INPUT_TEMPLATES = 1 << 30
|
|
44
|
+
CAP_VALIDATION_EVENTS = 1 << 31
|
|
45
|
+
CAP_PATTERN_VALIDATORS = 1 << 32
|
|
46
|
+
CAP_HOST_VALIDATORS = 1 << 33
|
|
47
|
+
CAP_LOG_OPERATIONS = 1 << 34
|
|
48
|
+
CAP_LOG_WRAP = 1 << 35
|
|
49
|
+
CAP_LOG_LINE_LIMIT = 1 << 36
|
|
50
|
+
CAP_LOG_TEXT_FORMAT = 1 << 37
|
|
51
|
+
CAP_LOG_REPR_HIGHLIGHT = 1 << 38
|
|
52
|
+
CAP_LOG_HIGHLIGHT_RULES = 1 << 39
|
|
53
|
+
CAP_LOG_RENDERABLE = 1 << 40
|
|
54
|
+
CAP_LOG_WRITE_SCROLL = 1 << 41
|
|
55
|
+
CAP_LOG_WIDTH_OPTIONS = 1 << 42
|
|
56
|
+
CAP_LOG_DEFERRED_WRITES = 1 << 43
|
|
57
|
+
CAP_LOG_ANIMATED_SCROLL = 1 << 44
|
|
58
|
+
CAP_COMPONENT_QUERIES = 1 << 45
|
|
59
|
+
CAP_TIMER_MISSED_TICKS = 1 << 46
|
|
60
|
+
CAP_TIMER_DIAGNOSTICS = 1 << 47
|
|
61
|
+
CAP_WORKER_STATES = 1 << 48
|
|
62
|
+
CAP_REACTIVE_REFRESH = 1 << 49
|
|
63
|
+
CAP_TABLE_CELL_GEOMETRY = 1 << 50
|
|
64
|
+
CAP_TABLE_CURSOR_STYLE = 1 << 51
|
|
65
|
+
CAP_TABLE_CURSOR_MOVEMENT = 1 << 52
|
|
66
|
+
CAP_TABLE_CLICK_ACTIVATION = 1 << 53
|
|
67
|
+
CAP_TABLE_ANIMATED_REVEAL = 1 << 54
|
|
68
|
+
CAP_ATTRIBUTED_SNAPSHOT = 1 << 55
|
|
69
|
+
CAP_ATTRIBUTED_TEXT = 1 << 56
|
|
70
|
+
CAP_TAB_STRIP = 1 << 57
|
|
71
|
+
CAP_CALENDAR_EVENTS = 1 << 58
|
|
72
|
+
CAP_CALENDAR_PRESENTATION = 1 << 59
|
|
73
|
+
CAP_LINE_GAUGE = 1 << 60
|
|
74
|
+
CAP_SPARKLINE_PRESENTATION = 1 << 61
|
|
75
|
+
CAP_FOOTER_ACTIONS = 1 << 62
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Kind(IntEnum):
|
|
79
|
+
ROW = 1
|
|
80
|
+
COLUMN = 2
|
|
81
|
+
LABEL = 3
|
|
82
|
+
BUTTON = 4
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Input(IntEnum):
|
|
86
|
+
TAB = 1
|
|
87
|
+
BACK_TAB = 2
|
|
88
|
+
ENTER = 3
|
|
89
|
+
ESCAPE = 4
|
|
90
|
+
INTERRUPT = 5
|
|
91
|
+
RESIZE = 6
|
|
92
|
+
POINTER = 7
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class EventKind(IntEnum):
|
|
96
|
+
IDLE = 0
|
|
97
|
+
UPDATED = 1
|
|
98
|
+
RESIZED = 2
|
|
99
|
+
ACTION = 3
|
|
100
|
+
QUIT = 4
|
|
101
|
+
TARGETED = 5
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True)
|
|
105
|
+
class Style:
|
|
106
|
+
foreground: int = 0
|
|
107
|
+
background: int = 0
|
|
108
|
+
bold: bool = False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class Node:
|
|
113
|
+
key: int
|
|
114
|
+
kind: Kind
|
|
115
|
+
parent: int = 0xFFFFFFFF
|
|
116
|
+
text: str = ""
|
|
117
|
+
action: int = 0
|
|
118
|
+
disabled: bool = False
|
|
119
|
+
style: Style = None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class Event:
|
|
124
|
+
kind: EventKind
|
|
125
|
+
action: int
|
|
126
|
+
columns: int
|
|
127
|
+
rows: int
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class TermiteError(RuntimeError):
|
|
131
|
+
def __init__(self, status: int):
|
|
132
|
+
super().__init__(f"Termite error {status}")
|
|
133
|
+
self.status = status
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class _Style(ct.Structure):
|
|
137
|
+
_fields_ = [("foreground", ct.c_uint32), ("background", ct.c_uint32),
|
|
138
|
+
("bold", ct.c_uint32)]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class _Node(ct.Structure):
|
|
142
|
+
_fields_ = [("key", ct.c_uint64), ("action", ct.c_uint64),
|
|
143
|
+
("text", ct.c_char_p), ("length", ct.c_uint32),
|
|
144
|
+
("parent", ct.c_uint32), ("kind", ct.c_uint32),
|
|
145
|
+
("flags", ct.c_uint32), ("style", _Style)]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class _Event(ct.Structure):
|
|
149
|
+
_fields_ = [("action", ct.c_uint64), ("kind", ct.c_uint32),
|
|
150
|
+
("columns", ct.c_uint16), ("rows", ct.c_uint16)]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _load():
|
|
154
|
+
if sys.platform == "win32":
|
|
155
|
+
filename = "termite_ffi.dll"
|
|
156
|
+
elif sys.platform == "darwin":
|
|
157
|
+
filename = "libtermite_ffi.dylib"
|
|
158
|
+
else:
|
|
159
|
+
filename = "libtermite_ffi.so"
|
|
160
|
+
path = os.environ.get("TERMITE_LIBRARY") or str(Path(__file__).with_name(filename))
|
|
161
|
+
if sys.platform == "win32" and os.path.isfile(path):
|
|
162
|
+
# Windows resolves a relative DLL path against the search path, not
|
|
163
|
+
# the working directory.
|
|
164
|
+
path = os.path.abspath(path)
|
|
165
|
+
lib = ct.CDLL(path)
|
|
166
|
+
signatures = {
|
|
167
|
+
"abi_version": (ct.c_uint32, []),
|
|
168
|
+
"open": (ct.c_int32, [ct.c_uint32, ct.c_uint16, ct.c_uint16,
|
|
169
|
+
ct.POINTER(ct.c_uint64)]),
|
|
170
|
+
"close": (ct.c_int32, [ct.c_uint64]),
|
|
171
|
+
"submit": (ct.c_int32, [ct.c_uint64, ct.POINTER(_Node), ct.c_uint32]),
|
|
172
|
+
"inject": (ct.c_int32, [ct.c_uint64, ct.c_uint32, ct.c_uint16, ct.c_uint16]),
|
|
173
|
+
"poll": (ct.c_int32, [ct.c_uint64, ct.c_uint32, ct.POINTER(_Event)]),
|
|
174
|
+
"draw": (ct.c_int32, [ct.c_uint64]),
|
|
175
|
+
"snapshot": (ct.c_int32, [ct.c_uint64, ct.c_void_p, ct.c_size_t,
|
|
176
|
+
ct.POINTER(ct.c_size_t)]),
|
|
177
|
+
}
|
|
178
|
+
for name, (result, args) in signatures.items():
|
|
179
|
+
fn = getattr(lib, f"termite_{name}")
|
|
180
|
+
fn.restype, fn.argtypes = result, args
|
|
181
|
+
if lib.termite_abi_version() >> 16 != 1:
|
|
182
|
+
raise RuntimeError("Termite ABI major version must be 1")
|
|
183
|
+
if lib.termite_abi_version() & 0xFFFF >= 1:
|
|
184
|
+
lib.termite_capabilities.argtypes = []
|
|
185
|
+
lib.termite_capabilities.restype = ct.c_uint64
|
|
186
|
+
lib.termite_runtime.argtypes = [ct.c_uint64, ct.c_char_p, ct.c_size_t]
|
|
187
|
+
lib.termite_runtime.restype = ct.c_int32
|
|
188
|
+
lib.termite_runtime_reply.argtypes = [
|
|
189
|
+
ct.c_uint64, ct.c_void_p, ct.c_size_t, ct.POINTER(ct.c_size_t)]
|
|
190
|
+
lib.termite_runtime_reply.restype = ct.c_int32
|
|
191
|
+
if lib.termite_abi_version() & 0xFFFF >= 4:
|
|
192
|
+
lib.termite_open_with_options.argtypes = [
|
|
193
|
+
ct.c_char_p, ct.c_size_t, ct.POINTER(ct.c_uint64)]
|
|
194
|
+
lib.termite_open_with_options.restype = ct.c_int32
|
|
195
|
+
return lib
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _check(status):
|
|
199
|
+
if status:
|
|
200
|
+
raise TermiteError(status)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _unsigned(value, bits):
|
|
204
|
+
if not isinstance(value, int) or not 0 <= value < 2**bits:
|
|
205
|
+
raise ValueError(f"expected an unsigned {bits}-bit integer")
|
|
206
|
+
return value
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class Session:
|
|
210
|
+
"""Owner-thread terminal session with explicit or context-managed close."""
|
|
211
|
+
|
|
212
|
+
def __init__(self, *, headless=False, columns=0, rows=0, options=None):
|
|
213
|
+
self._lib = _load()
|
|
214
|
+
handle = ct.c_uint64()
|
|
215
|
+
if options is None:
|
|
216
|
+
_check(self._lib.termite_open(headless, _unsigned(columns, 16),
|
|
217
|
+
_unsigned(rows, 16), ct.byref(handle)))
|
|
218
|
+
else:
|
|
219
|
+
if headless or columns or rows:
|
|
220
|
+
raise ValueError("pass session options or the legacy arguments")
|
|
221
|
+
if not self.capabilities & CAP_TRANSPORT_OPTIONS:
|
|
222
|
+
raise RuntimeError("Termite library lacks transport options")
|
|
223
|
+
data = json.dumps({"version": 1, "options": options}).encode("utf-8")
|
|
224
|
+
_check(self._lib.termite_open_with_options(data, len(data), ct.byref(handle)))
|
|
225
|
+
self._handle = handle.value
|
|
226
|
+
|
|
227
|
+
def __enter__(self):
|
|
228
|
+
return self
|
|
229
|
+
|
|
230
|
+
def __exit__(self, *_):
|
|
231
|
+
self.close()
|
|
232
|
+
|
|
233
|
+
def close(self):
|
|
234
|
+
if self._handle:
|
|
235
|
+
status = self._lib.termite_close(self._handle)
|
|
236
|
+
if status != 3:
|
|
237
|
+
self._handle = 0
|
|
238
|
+
_check(status)
|
|
239
|
+
|
|
240
|
+
def submit(self, nodes: Sequence[Node]):
|
|
241
|
+
wire = (_Node * len(nodes))()
|
|
242
|
+
for index, node in enumerate(nodes):
|
|
243
|
+
text = node.text.encode()
|
|
244
|
+
style = node.style or Style()
|
|
245
|
+
flags = int(node.disabled) | (2 if node.style is not None else 0)
|
|
246
|
+
wire[index] = _Node(
|
|
247
|
+
_unsigned(node.key, 64), _unsigned(node.action, 64),
|
|
248
|
+
text, _unsigned(len(text), 32), _unsigned(node.parent, 32),
|
|
249
|
+
node.kind, flags, _Style(_unsigned(style.foreground, 32),
|
|
250
|
+
_unsigned(style.background, 32), style.bold))
|
|
251
|
+
_check(self._lib.termite_submit(self._handle, wire, _unsigned(len(wire), 32)))
|
|
252
|
+
|
|
253
|
+
def inject(self, kind: Input, columns=0, rows=0):
|
|
254
|
+
_check(self._lib.termite_inject(self._handle, kind,
|
|
255
|
+
_unsigned(columns, 16), _unsigned(rows, 16)))
|
|
256
|
+
|
|
257
|
+
def poll(self, timeout_ms=0) -> Event:
|
|
258
|
+
native = _Event()
|
|
259
|
+
_check(self._lib.termite_poll(self._handle, _unsigned(timeout_ms, 32),
|
|
260
|
+
ct.byref(native)))
|
|
261
|
+
return Event(EventKind(native.kind), native.action, native.columns, native.rows)
|
|
262
|
+
|
|
263
|
+
def draw(self):
|
|
264
|
+
_check(self._lib.termite_draw(self._handle))
|
|
265
|
+
|
|
266
|
+
def snapshot(self) -> bytes:
|
|
267
|
+
length = ct.c_size_t()
|
|
268
|
+
_check(self._lib.termite_snapshot(self._handle, None, 0, ct.byref(length)))
|
|
269
|
+
data = (ct.c_uint8 * length.value)()
|
|
270
|
+
_check(self._lib.termite_snapshot(self._handle, data, length, ct.byref(length)))
|
|
271
|
+
return bytes(data)
|
|
272
|
+
|
|
273
|
+
@property
|
|
274
|
+
def capabilities(self) -> int:
|
|
275
|
+
query = getattr(self._lib, "termite_capabilities", None)
|
|
276
|
+
return query() if query is not None else 0
|
|
277
|
+
|
|
278
|
+
@property
|
|
279
|
+
def abi_version(self) -> int:
|
|
280
|
+
"""Return the packed major and minor ABI version."""
|
|
281
|
+
return self._lib.termite_abi_version()
|
|
282
|
+
|
|
283
|
+
def runtime(self, request: str) -> str:
|
|
284
|
+
"""Execute one dashboard document and return its JSON reply."""
|
|
285
|
+
if not self.capabilities & CAP_DASHBOARD_DOCUMENT:
|
|
286
|
+
raise RuntimeError("Termite library lacks dashboard document support")
|
|
287
|
+
data = request.encode("utf-8")
|
|
288
|
+
_check(self._lib.termite_runtime(self._handle, data, len(data)))
|
|
289
|
+
length = ct.c_size_t()
|
|
290
|
+
_check(self._lib.termite_runtime_reply(self._handle, None, 0, ct.byref(length)))
|
|
291
|
+
reply = (ct.c_uint8 * length.value)()
|
|
292
|
+
_check(self._lib.termite_runtime_reply(self._handle, reply, length, ct.byref(length)))
|
|
293
|
+
return bytes(reply).decode("utf-8")
|
|
294
|
+
|
|
295
|
+
def register_syntax_grammar(self, name: str, language) -> None:
|
|
296
|
+
"""Register a trusted generated grammar entry point by name.
|
|
297
|
+
|
|
298
|
+
``language`` is the parser's C entry point, such as
|
|
299
|
+
``ctypes.CDLL(path).tree_sitter_json``, or its address. Keep the loaded
|
|
300
|
+
module alive until the grammar is removed or the session closes.
|
|
301
|
+
"""
|
|
302
|
+
register = getattr(self._lib, "termite_register_syntax_grammar", None)
|
|
303
|
+
if register is None:
|
|
304
|
+
raise RuntimeError("Termite library lacks syntax grammar registration")
|
|
305
|
+
register.argtypes = [ct.c_uint64, ct.c_char_p, ct.c_size_t, ct.c_void_p]
|
|
306
|
+
register.restype = ct.c_int32
|
|
307
|
+
address = language if isinstance(language, int) else ct.cast(language, ct.c_void_p).value
|
|
308
|
+
if not address:
|
|
309
|
+
raise ValueError("expected a grammar entry point")
|
|
310
|
+
data = name.encode("utf-8")
|
|
311
|
+
_check(register(self._handle, data, len(data), address))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
from .capture import OutputCapture, capture_output # noqa: E402
|
termite_tui/authoring.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Compose nodes for Termite's document protocol."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def label(key, text, style=None):
|
|
7
|
+
node = {"key": key, "kind": "label", "text": text}
|
|
8
|
+
if style is not None:
|
|
9
|
+
node["style"] = asdict(style)
|
|
10
|
+
return node
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def row(key, *children):
|
|
14
|
+
return {"key": key, "kind": "row", "children": list(children)}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def column(key, *children):
|
|
18
|
+
return {"key": key, "kind": "column", "children": list(children)}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def table_row(key, cells):
|
|
22
|
+
return {"key": key, "cells": {str(column_id): text for column_id, text in cells.items()}}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def bar_chart(key, rows, series, categories=(), **options):
|
|
26
|
+
"""A categorical bar chart (ABI 1.131).
|
|
27
|
+
|
|
28
|
+
``series`` holds dictionaries with ``values`` and optional ``name``,
|
|
29
|
+
``style`` and ``fill``. ``options`` passes ``layout`` (``grouped``,
|
|
30
|
+
``stacked`` or ``percent``), ``orientation``, ``range``, ``bar_width``,
|
|
31
|
+
``bar_gap``, ``group_gap``, ``axis`` and ``legend`` through unchanged.
|
|
32
|
+
"""
|
|
33
|
+
return {"key": key, "kind": "bar_chart", "rows": rows, "categories": list(categories),
|
|
34
|
+
"series": [dict(entry) for entry in series], **options}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def histogram(key, rows, samples, **options):
|
|
38
|
+
"""A histogram of raw samples (ABI 1.131).
|
|
39
|
+
|
|
40
|
+
``options`` passes ``bins`` or ``bin_width``, ``range``, ``cumulative``,
|
|
41
|
+
``orientation``, ``name``, ``style``, ``fill``, ``bar_width``, ``gap``
|
|
42
|
+
and ``axis`` through unchanged.
|
|
43
|
+
"""
|
|
44
|
+
return {"key": key, "kind": "histogram", "rows": rows, "samples": list(samples), **options}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def heatmap(key, values=None, *, calendar=None, **options):
|
|
48
|
+
"""A heatmap of rows of values, or a calendar of daily values (ABI 1.131).
|
|
49
|
+
|
|
50
|
+
Pass ``values`` as rows of numbers or ``None``, or ``calendar`` as
|
|
51
|
+
``{"first_weekday": 0, "days": [...]}``. ``options`` passes
|
|
52
|
+
``row_labels``, ``column_labels``, ``scale``, ``range``, ``cells``,
|
|
53
|
+
``cell_width``, ``show_values``, ``decimals``, ``legend``, ``shading``
|
|
54
|
+
and ``rows`` through unchanged.
|
|
55
|
+
"""
|
|
56
|
+
node = {"key": key, "kind": "heatmap", **options}
|
|
57
|
+
if calendar is not None:
|
|
58
|
+
node["calendar"] = calendar
|
|
59
|
+
else:
|
|
60
|
+
node["values"] = [list(row) for row in values]
|
|
61
|
+
return node
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def big_text(key, text, *, font=None, align=None):
|
|
65
|
+
"""Large block-character text: ``font`` is ``"block"`` or ``"half"``."""
|
|
66
|
+
node = {"key": key, "kind": "big_text", "text": text}
|
|
67
|
+
if font is not None:
|
|
68
|
+
node["font"] = font
|
|
69
|
+
if align is not None:
|
|
70
|
+
node["align"] = align
|
|
71
|
+
return node
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def chart_points(points):
|
|
75
|
+
"""Encode ``(x, y)`` pairs for ``append_chart_points`` and chart datasets."""
|
|
76
|
+
return [{"x": x, "y": y} for x, y in points]
|
termite_tui/capture.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Scoped capture of Python's standard streams into a Termite session."""
|
|
2
|
+
|
|
3
|
+
from collections import deque
|
|
4
|
+
import errno
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
|
|
10
|
+
_RECORD_BYTES = 16 * 1024
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _records(text):
|
|
14
|
+
"""Split text into UTF-8 records of at most 16 KiB on character boundaries."""
|
|
15
|
+
data = text.encode("utf-8")
|
|
16
|
+
while len(data) > _RECORD_BYTES:
|
|
17
|
+
end = _RECORD_BYTES
|
|
18
|
+
while data[end] & 0xC0 == 0x80:
|
|
19
|
+
end -= 1
|
|
20
|
+
yield data[:end].decode("utf-8")
|
|
21
|
+
data = data[end:]
|
|
22
|
+
if data:
|
|
23
|
+
yield data.decode("utf-8")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _CaptureStream(io.TextIOBase):
|
|
27
|
+
"""A text stream that submits each write as one `write_output` record.
|
|
28
|
+
|
|
29
|
+
Writes from the session owner thread are submitted at once. Writes from
|
|
30
|
+
other threads wait in order until the next owner-thread write, `flush`,
|
|
31
|
+
or the end of the capture scope.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, capture, name, original):
|
|
35
|
+
super().__init__()
|
|
36
|
+
self._capture = capture
|
|
37
|
+
self._name = name
|
|
38
|
+
self._original = original
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def encoding(self):
|
|
42
|
+
return "utf-8"
|
|
43
|
+
|
|
44
|
+
def writable(self):
|
|
45
|
+
return True
|
|
46
|
+
|
|
47
|
+
def isatty(self):
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
def fileno(self):
|
|
51
|
+
# Direct descriptor writes stay with the host stream.
|
|
52
|
+
raise io.UnsupportedOperation("captured Termite streams have no descriptor")
|
|
53
|
+
|
|
54
|
+
def write(self, text):
|
|
55
|
+
if not isinstance(text, str):
|
|
56
|
+
raise TypeError(f"write() argument must be str, not {type(text).__name__}")
|
|
57
|
+
self._capture._write(self._name, self._original, text)
|
|
58
|
+
return len(text)
|
|
59
|
+
|
|
60
|
+
def flush(self):
|
|
61
|
+
self._capture._drain()
|
|
62
|
+
if self._capture.tee:
|
|
63
|
+
self._original.flush()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class OutputCapture:
|
|
67
|
+
"""Redirect `sys.stdout` and `sys.stderr` to a session's output streams.
|
|
68
|
+
|
|
69
|
+
Each Python write becomes one record for the stream's route and its
|
|
70
|
+
subscribers. With `tee`, every write is also echoed to the replaced
|
|
71
|
+
stream, as a headless application might do. Leaving the scope, normally
|
|
72
|
+
or through an exception, restores the previous streams. Closing the
|
|
73
|
+
session invalidates the capture streams.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self, session, *, stdout=True, stderr=True, tee=False):
|
|
77
|
+
if not (stdout or stderr):
|
|
78
|
+
raise ValueError("capture at least one stream")
|
|
79
|
+
self.session = session
|
|
80
|
+
self.tee = tee
|
|
81
|
+
self._streams = [name for name, enabled in (("stdout", stdout), ("stderr", stderr))
|
|
82
|
+
if enabled]
|
|
83
|
+
self._owner = threading.get_ident()
|
|
84
|
+
self._pending = deque()
|
|
85
|
+
self._lock = threading.Lock()
|
|
86
|
+
self._saved = None
|
|
87
|
+
|
|
88
|
+
def __enter__(self):
|
|
89
|
+
if self._saved is not None:
|
|
90
|
+
raise RuntimeError("output capture is already active")
|
|
91
|
+
self._saved = {name: getattr(sys, name) for name in self._streams}
|
|
92
|
+
for name, original in self._saved.items():
|
|
93
|
+
setattr(sys, name, _CaptureStream(self, name, original))
|
|
94
|
+
return self
|
|
95
|
+
|
|
96
|
+
def __exit__(self, *_):
|
|
97
|
+
try:
|
|
98
|
+
if self.session._handle:
|
|
99
|
+
self._drain()
|
|
100
|
+
finally:
|
|
101
|
+
for name, original in self._saved.items():
|
|
102
|
+
setattr(sys, name, original)
|
|
103
|
+
self._saved = None
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
def _write(self, name, original, text):
|
|
107
|
+
if not text:
|
|
108
|
+
return
|
|
109
|
+
if self.tee:
|
|
110
|
+
original.write(text)
|
|
111
|
+
if threading.get_ident() != self._owner:
|
|
112
|
+
with self._lock:
|
|
113
|
+
self._pending.append((name, text))
|
|
114
|
+
return
|
|
115
|
+
self._drain()
|
|
116
|
+
self._submit(name, text)
|
|
117
|
+
|
|
118
|
+
def _drain(self):
|
|
119
|
+
if threading.get_ident() != self._owner:
|
|
120
|
+
return
|
|
121
|
+
while True:
|
|
122
|
+
with self._lock:
|
|
123
|
+
if not self._pending:
|
|
124
|
+
return
|
|
125
|
+
name, text = self._pending.popleft()
|
|
126
|
+
self._submit(name, text)
|
|
127
|
+
|
|
128
|
+
def _submit(self, name, text):
|
|
129
|
+
if not self.session._handle:
|
|
130
|
+
raise BrokenPipeError(errno.EPIPE, "the Termite session is closed")
|
|
131
|
+
for record in _records(text):
|
|
132
|
+
self.session.runtime(json.dumps({"op": "write_output", "stream": name,
|
|
133
|
+
"text": record}))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def capture_output(session, *, stdout=True, stderr=True, tee=False):
|
|
137
|
+
"""Return a context manager that captures the selected Python streams."""
|
|
138
|
+
return OutputCapture(session, stdout=stdout, stderr=stderr, tee=tee)
|
|
Binary file
|
termite_tui/testing.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Snapshot assertions and a scripted input driver for headless sessions.
|
|
2
|
+
|
|
3
|
+
Works with any test runner, including plain ``assert`` scripts and pytest,
|
|
4
|
+
and needs nothing beyond the standard library::
|
|
5
|
+
|
|
6
|
+
from termite_tui.testing import Pilot, assert_snapshot
|
|
7
|
+
|
|
8
|
+
def test_greeting():
|
|
9
|
+
with Pilot(columns=20, rows=3) as pilot:
|
|
10
|
+
pilot.call("submit", root={"kind": "label", "key": 1, "text": "Hello"})
|
|
11
|
+
assert_snapshot(pilot, "greeting")
|
|
12
|
+
|
|
13
|
+
The snapshot text comes from the shared runtime's ``snapshot_text`` request,
|
|
14
|
+
so a scene produces byte-identical snapshot files from Rust and from every
|
|
15
|
+
binding. Snapshots are stored as ``NAME.snap`` in a ``snapshots`` directory
|
|
16
|
+
next to the calling test file unless ``directory`` is given. On a mismatch,
|
|
17
|
+
the current frame is written to ``NAME.snap.new`` and a side-by-side HTML
|
|
18
|
+
report to ``NAME.diff.html``, and :class:`SnapshotMismatch` (an
|
|
19
|
+
``AssertionError``) carries the readable cell diff.
|
|
20
|
+
|
|
21
|
+
Set ``TERMITE_UPDATE_SNAPSHOTS=1`` to accept the current frames. ``new``
|
|
22
|
+
records only missing snapshots and ``0`` compares only. When the variable is
|
|
23
|
+
unset, missing snapshots are recorded unless ``CI`` is set.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import inspect
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from . import Session
|
|
33
|
+
|
|
34
|
+
UPDATE_ENV = "TERMITE_UPDATE_SNAPSHOTS"
|
|
35
|
+
|
|
36
|
+
NEVER = "never"
|
|
37
|
+
NEW = "new"
|
|
38
|
+
ALWAYS = "always"
|
|
39
|
+
|
|
40
|
+
_NAME = re.compile(r"[A-Za-z0-9_\-][A-Za-z0-9_.\-]*\Z")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class SnapshotMismatch(AssertionError):
|
|
44
|
+
"""A stored snapshot differs from the current frame."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, message, *, name, path, new_path, report_path=None,
|
|
47
|
+
differing_cells=0, diff=""):
|
|
48
|
+
super().__init__(message)
|
|
49
|
+
self.name = name
|
|
50
|
+
self.path = path
|
|
51
|
+
self.new_path = new_path
|
|
52
|
+
self.report_path = report_path
|
|
53
|
+
self.differing_cells = differing_cells
|
|
54
|
+
self.diff = diff
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SnapshotMissing(SnapshotMismatch):
|
|
58
|
+
"""No snapshot is stored and the update mode does not allow writing one."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def update_mode(update=None, ci=None):
|
|
62
|
+
"""Resolve the update mode from ``TERMITE_UPDATE_SNAPSHOTS`` and ``CI`` values.
|
|
63
|
+
|
|
64
|
+
Without arguments, both are read from the environment. Matches the Rust
|
|
65
|
+
``UpdateMode::from_values``.
|
|
66
|
+
"""
|
|
67
|
+
if update is None and ci is None:
|
|
68
|
+
update, ci = os.environ.get(UPDATE_ENV), os.environ.get("CI")
|
|
69
|
+
value = (update or "").strip().lower()
|
|
70
|
+
if value in ("1", "true", "yes", "always"):
|
|
71
|
+
return ALWAYS
|
|
72
|
+
if value == "new":
|
|
73
|
+
return NEW
|
|
74
|
+
if value in ("0", "false", "no", "never"):
|
|
75
|
+
return NEVER
|
|
76
|
+
if (ci or "").strip().lower() in ("", "0", "false"):
|
|
77
|
+
return NEW
|
|
78
|
+
return NEVER
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _runtime(source):
|
|
82
|
+
"""Return a function that sends one document request to the source's session."""
|
|
83
|
+
session = getattr(source, "session", source)
|
|
84
|
+
if not hasattr(session, "runtime"):
|
|
85
|
+
raise TypeError("expected a termite_tui Session or Pilot")
|
|
86
|
+
|
|
87
|
+
def call(op, **fields):
|
|
88
|
+
return json.loads(session.runtime(json.dumps({"op": op, **fields})))
|
|
89
|
+
|
|
90
|
+
return call
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def snapshot_text(source):
|
|
94
|
+
"""Return the current frame of a Session or Pilot as snapshot text."""
|
|
95
|
+
reply = _runtime(source)("snapshot_text")
|
|
96
|
+
if reply.get("version") != 1:
|
|
97
|
+
raise RuntimeError(f"unsupported snapshot version {reply.get('version')!r}")
|
|
98
|
+
return reply["text"]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def compare_snapshots(source, expected, actual, name="snapshot"):
|
|
102
|
+
"""Compare two snapshot texts with the shared runtime.
|
|
103
|
+
|
|
104
|
+
Returns a dict with ``equal``, ``differing_cells``, ``diff`` and the HTML
|
|
105
|
+
``report``.
|
|
106
|
+
"""
|
|
107
|
+
return _runtime(source)("snapshot_diff", expected=expected, actual=actual, name=name)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _caller_directory(depth):
|
|
111
|
+
frame = inspect.stack()[depth + 1]
|
|
112
|
+
return Path(frame.filename).resolve().parent / "snapshots"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _remove(path):
|
|
116
|
+
try:
|
|
117
|
+
path.unlink()
|
|
118
|
+
except FileNotFoundError:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _write(path, data):
|
|
123
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
124
|
+
path.write_bytes(data)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def check_snapshot(source, name, *, directory=None, svg=False, update=None, _depth=1):
|
|
128
|
+
"""Compare the current frame with the snapshot ``name``.
|
|
129
|
+
|
|
130
|
+
Returns ``"matched"``, ``"created"`` or ``"updated"``, or raises
|
|
131
|
+
:class:`SnapshotMismatch`. ``update`` is ``"never"``, ``"new"`` or
|
|
132
|
+
``"always"``; by default it comes from the environment.
|
|
133
|
+
"""
|
|
134
|
+
if not isinstance(name, str) or not _NAME.match(name):
|
|
135
|
+
raise ValueError(
|
|
136
|
+
f"snapshot name {name!r} must be non-empty ASCII letters, digits, '-', '_' or '.'")
|
|
137
|
+
directory = Path(directory) if directory is not None else _caller_directory(_depth)
|
|
138
|
+
mode = update or update_mode()
|
|
139
|
+
if mode not in (NEVER, NEW, ALWAYS):
|
|
140
|
+
raise ValueError(f"unknown update mode {mode!r}")
|
|
141
|
+
call = _runtime(source)
|
|
142
|
+
actual_text = snapshot_text(source)
|
|
143
|
+
artifacts = [(f"{name}.snap", actual_text)]
|
|
144
|
+
if svg:
|
|
145
|
+
artifacts.append((f"{name}.svg", call("snapshot_svg")["svg"]))
|
|
146
|
+
outcome = "matched"
|
|
147
|
+
failure = None
|
|
148
|
+
for file, actual in artifacts:
|
|
149
|
+
path, new_path = directory / file, directory / f"{file}.new"
|
|
150
|
+
data = actual.encode("utf-8")
|
|
151
|
+
stored = path.read_bytes() if path.exists() else None
|
|
152
|
+
if stored == data:
|
|
153
|
+
_remove(new_path)
|
|
154
|
+
elif stored is None and mode != NEVER:
|
|
155
|
+
_write(path, data)
|
|
156
|
+
_remove(new_path)
|
|
157
|
+
outcome = "created"
|
|
158
|
+
elif stored is not None and mode == ALWAYS:
|
|
159
|
+
_write(path, data)
|
|
160
|
+
_remove(new_path)
|
|
161
|
+
if outcome == "matched":
|
|
162
|
+
outcome = "updated"
|
|
163
|
+
elif stored is None:
|
|
164
|
+
_write(new_path, data)
|
|
165
|
+
if failure is None:
|
|
166
|
+
failure = SnapshotMissing(
|
|
167
|
+
f"snapshot `{name}` is missing: {path}\nactual frame: {new_path}\n"
|
|
168
|
+
f"run with {UPDATE_ENV}=1 to record it",
|
|
169
|
+
name=name, path=path, new_path=new_path)
|
|
170
|
+
else:
|
|
171
|
+
_write(new_path, data)
|
|
172
|
+
if file.endswith(".snap"):
|
|
173
|
+
comparison = call("snapshot_diff", expected=stored.decode("utf-8", "replace"),
|
|
174
|
+
actual=actual, name=name)
|
|
175
|
+
cells, diff = comparison["differing_cells"], comparison["diff"]
|
|
176
|
+
else:
|
|
177
|
+
cells, diff = 0, "the SVG rendering differs\n"
|
|
178
|
+
if failure is None or isinstance(failure, SnapshotMissing):
|
|
179
|
+
report = directory / f"{name}.diff.html"
|
|
180
|
+
failure = SnapshotMismatch(
|
|
181
|
+
f"snapshot `{name}` does not match {path}\n{diff}"
|
|
182
|
+
f"actual frame: {new_path}\nside-by-side report: {report}\n"
|
|
183
|
+
f"run with {UPDATE_ENV}=1 to accept the new frame",
|
|
184
|
+
name=name, path=path, new_path=new_path, report_path=report,
|
|
185
|
+
differing_cells=cells, diff=diff)
|
|
186
|
+
report = directory / f"{name}.diff.html"
|
|
187
|
+
if failure is None:
|
|
188
|
+
_remove(report)
|
|
189
|
+
return outcome
|
|
190
|
+
if failure.report_path is not None:
|
|
191
|
+
snap = directory / f"{name}.snap"
|
|
192
|
+
expected = snap.read_bytes().decode("utf-8", "replace") if snap.exists() else ""
|
|
193
|
+
reply = call("snapshot_diff", expected=expected, actual=actual_text, name=name)
|
|
194
|
+
_write(report, reply["report"].encode("utf-8"))
|
|
195
|
+
else:
|
|
196
|
+
_remove(report)
|
|
197
|
+
raise failure
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def assert_snapshot(source, name, *, directory=None, svg=False, update=None):
|
|
201
|
+
"""Assert that the current frame matches the stored snapshot ``name``.
|
|
202
|
+
|
|
203
|
+
``source`` is a :class:`termite_tui.Session` or a :class:`Pilot`.
|
|
204
|
+
"""
|
|
205
|
+
check_snapshot(source, name, directory=directory, svg=svg, update=update, _depth=2)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _key_symbol(key):
|
|
209
|
+
"""Map a key name or single character to the protocol's key symbol."""
|
|
210
|
+
if isinstance(key, str) and len(key) == 1:
|
|
211
|
+
return {"character": key}
|
|
212
|
+
if isinstance(key, str) and re.fullmatch(r"f([1-9][0-9]?)", key):
|
|
213
|
+
return {"function": int(key[1:])}
|
|
214
|
+
return key
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Pilot:
|
|
218
|
+
"""Drive a headless session the way a person at a terminal would.
|
|
219
|
+
|
|
220
|
+
Every input is injected and immediately routed with one
|
|
221
|
+
``poll_interaction``; the routed reply is returned so tests can feed
|
|
222
|
+
actions to their own update logic. ``call`` sends any other document
|
|
223
|
+
request.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
def __init__(self, *, columns=80, rows=24, session=None):
|
|
227
|
+
self._owned = session is None
|
|
228
|
+
self.session = session if session is not None else Session(
|
|
229
|
+
headless=True, columns=columns, rows=rows)
|
|
230
|
+
self._call = _runtime(self.session)
|
|
231
|
+
|
|
232
|
+
def __enter__(self):
|
|
233
|
+
return self
|
|
234
|
+
|
|
235
|
+
def __exit__(self, *_):
|
|
236
|
+
self.close()
|
|
237
|
+
|
|
238
|
+
def close(self):
|
|
239
|
+
if self._owned:
|
|
240
|
+
self.session.close()
|
|
241
|
+
|
|
242
|
+
def call(self, op, **fields):
|
|
243
|
+
"""Send one document request and decode its reply."""
|
|
244
|
+
return self._call(op, **fields)
|
|
245
|
+
|
|
246
|
+
def send(self, interaction):
|
|
247
|
+
"""Inject one normalized input and route it."""
|
|
248
|
+
if not self.call("inject_interaction", input=interaction)["accepted"]:
|
|
249
|
+
return None
|
|
250
|
+
return self.call("poll_interaction", timeout_ms=0)
|
|
251
|
+
|
|
252
|
+
def press(self, key, *, shift=False, control=False, alt=False):
|
|
253
|
+
"""Press one key: a name such as ``"enter"`` or ``"f2"``, or a character."""
|
|
254
|
+
modifiers = {name: True for name, on in
|
|
255
|
+
(("shift", shift), ("control", control), ("alt", alt)) if on}
|
|
256
|
+
return self.send({"kind": "key", "key": _key_symbol(key), "phase": "press",
|
|
257
|
+
"modifiers": modifiers})
|
|
258
|
+
|
|
259
|
+
def type(self, text):
|
|
260
|
+
"""Press each character of ``text`` as its own key."""
|
|
261
|
+
return [routed for routed in (self.press(ch) for ch in text) if routed is not None]
|
|
262
|
+
|
|
263
|
+
def paste(self, text):
|
|
264
|
+
return self.send({"kind": "paste", "text": text})
|
|
265
|
+
|
|
266
|
+
def click_at(self, column, row):
|
|
267
|
+
"""Press and release the left button on a cell."""
|
|
268
|
+
routed = []
|
|
269
|
+
for pointer in ({"down": "left"}, {"up": "left"}):
|
|
270
|
+
reply = self.send({"kind": "pointer", "column": column, "row": row,
|
|
271
|
+
"pointer": pointer})
|
|
272
|
+
if reply is not None:
|
|
273
|
+
routed.append(reply)
|
|
274
|
+
return routed
|
|
275
|
+
|
|
276
|
+
def click_point(self, key):
|
|
277
|
+
"""The middle of a node's visible area, as ``(column, row)``."""
|
|
278
|
+
inspected = self.call("inspect")
|
|
279
|
+
for entry in inspected["geometry"]:
|
|
280
|
+
if entry["key"] != key:
|
|
281
|
+
continue
|
|
282
|
+
bx, by, bw, bh = entry["bounds"]
|
|
283
|
+
cx, cy, cw, ch = entry["clip"]
|
|
284
|
+
left, top = max(bx, cx), max(by, cy)
|
|
285
|
+
right, bottom = min(bx + bw, cx + cw), min(by + bh, cy + ch)
|
|
286
|
+
if right > left and bottom > top:
|
|
287
|
+
column, row = left + (right - left - 1) // 2, top + (bottom - top - 1) // 2
|
|
288
|
+
if 0 <= column < inspected["columns"] and 0 <= row < inspected["rows"]:
|
|
289
|
+
return column, row
|
|
290
|
+
raise LookupError(f"node {key} is not visible")
|
|
291
|
+
|
|
292
|
+
def click_key(self, key):
|
|
293
|
+
return self.click_at(*self.click_point(key))
|
|
294
|
+
|
|
295
|
+
def click(self, selector):
|
|
296
|
+
"""Click the first node, in tree order, that matches a stylesheet selector."""
|
|
297
|
+
keys = self.call("query", selector=selector)["keys"]
|
|
298
|
+
if not keys:
|
|
299
|
+
raise LookupError(f"no node matches {selector!r}")
|
|
300
|
+
return self.click_key(keys[0])
|
|
301
|
+
|
|
302
|
+
def resize(self, columns, rows):
|
|
303
|
+
return self.send({"kind": "resize", "columns": columns, "rows": rows})
|
|
304
|
+
|
|
305
|
+
def advance(self, millis):
|
|
306
|
+
"""Advance the virtual clock by ``millis`` milliseconds."""
|
|
307
|
+
self.call("advance_clock", millis=millis)
|
|
308
|
+
|
|
309
|
+
def snapshot_text(self):
|
|
310
|
+
return snapshot_text(self)
|
|
311
|
+
|
|
312
|
+
def screen_text(self):
|
|
313
|
+
"""The current frame's symbols, one line per row, without styles."""
|
|
314
|
+
lines = snapshot_text(self).split("\n")
|
|
315
|
+
rows = int(lines[0].rsplit("x", 1)[1])
|
|
316
|
+
return "\n".join(line[1:-1] for line in lines[2:2 + rows])
|
|
317
|
+
|
|
318
|
+
def assert_snapshot(self, name, *, directory=None, svg=False, update=None):
|
|
319
|
+
check_snapshot(self, name, directory=directory, svg=svg, update=update, _depth=2)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: termite-tui
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python binding for Termite, a terminal UI runtime written in Rust
|
|
5
|
+
License-Expression: MIT OR Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/vanedaltro/termite
|
|
7
|
+
Project-URL: Documentation, https://github.com/vanedaltro/termite/blob/main/docs/install.md#python
|
|
8
|
+
Project-URL: Source, https://github.com/vanedaltro/termite
|
|
9
|
+
Project-URL: Changelog, https://github.com/vanedaltro/termite/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/vanedaltro/termite/issues
|
|
11
|
+
Keywords: terminal,tui,ui,console,widgets
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: MacOS
|
|
16
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
17
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Rust
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
22
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
23
|
+
Classifier: Topic :: Terminals
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE-MIT
|
|
27
|
+
License-File: LICENSE-APACHE
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# termite-tui
|
|
31
|
+
|
|
32
|
+
Python binding for [Termite](https://github.com/vanedaltro/termite), a terminal
|
|
33
|
+
UI runtime written in Rust. Build interactive dashboards, forms, editors and
|
|
34
|
+
data browsers from Python; layout, styling, input and rendering run in the
|
|
35
|
+
native runtime.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install termite-tui
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Wheels bundle the native library and are published for Linux x86_64
|
|
42
|
+
(manylinux) and macOS arm64. The package needs Python 3.9 or later and has no
|
|
43
|
+
Python dependencies.
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from termite_tui import EventKind, Kind, Node, Session
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def view(count):
|
|
52
|
+
return [
|
|
53
|
+
Node(1, Kind.COLUMN), Node(2, Kind.LABEL, 0, f"Count: {count}"),
|
|
54
|
+
Node(3, Kind.ROW, 0), Node(4, Kind.BUTTON, 2, "[-]", 1),
|
|
55
|
+
Node(5, Kind.BUTTON, 2, "[+]", 2),
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
with Session() as session:
|
|
60
|
+
count = 0
|
|
61
|
+
session.submit(view(count))
|
|
62
|
+
while True:
|
|
63
|
+
session.draw()
|
|
64
|
+
event = session.poll(250)
|
|
65
|
+
if event.kind == EventKind.QUIT:
|
|
66
|
+
break
|
|
67
|
+
if event.kind == EventKind.ACTION:
|
|
68
|
+
count += {1: -1, 2: 1}.get(event.action, 0)
|
|
69
|
+
session.submit(view(count))
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Tab moves focus, Enter presses a button, and Escape exits.
|
|
73
|
+
|
|
74
|
+
## Testing your app
|
|
75
|
+
|
|
76
|
+
`termite_tui.testing` drives a headless session and compares its frames with
|
|
77
|
+
stored snapshot files, under pytest or in a plain script:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from termite_tui.testing import Pilot, assert_snapshot
|
|
81
|
+
|
|
82
|
+
def test_greeting():
|
|
83
|
+
with Pilot(columns=20, rows=3) as pilot:
|
|
84
|
+
pilot.call("submit", root={"kind": "label", "key": 1, "text": "Hello"})
|
|
85
|
+
pilot.press("tab")
|
|
86
|
+
assert_snapshot(pilot, "greeting")
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The first run records `snapshots/greeting.snap` next to the test file. A
|
|
90
|
+
changed frame fails with a cell diff and writes a side-by-side HTML report;
|
|
91
|
+
set `TERMITE_UPDATE_SNAPSHOTS=1` to accept it. See the
|
|
92
|
+
[testing guide](https://github.com/vanedaltro/termite/blob/main/docs/testing.md).
|
|
93
|
+
|
|
94
|
+
## The native library
|
|
95
|
+
|
|
96
|
+
`termite_tui` loads the bundled library from its own package directory:
|
|
97
|
+
`libtermite_ffi.so` on Linux, `libtermite_ffi.dylib` on macOS and
|
|
98
|
+
`termite_ffi.dll` on Windows. Set
|
|
99
|
+
`TERMITE_LIBRARY` to the path of another build to use that one instead, for
|
|
100
|
+
example a debug build from a source checkout. A session's `abi_version`
|
|
101
|
+
property reports the packed C ABI version of the loaded library (major in
|
|
102
|
+
the high 16 bits, minor in the low 16 bits).
|
|
103
|
+
|
|
104
|
+
A session must be used from the OS thread that opened it.
|
|
105
|
+
|
|
106
|
+
## Links
|
|
107
|
+
|
|
108
|
+
- [Examples](https://github.com/vanedaltro/termite/tree/main/examples/python)
|
|
109
|
+
- [Installation guide](https://github.com/vanedaltro/termite/blob/main/docs/install.md#python)
|
|
110
|
+
- [Testing guide](https://github.com/vanedaltro/termite/blob/main/docs/testing.md)
|
|
111
|
+
- [Changelog](https://github.com/vanedaltro/termite/blob/main/CHANGELOG.md)
|
|
112
|
+
|
|
113
|
+
Termite is licensed under either the MIT license or the Apache License 2.0, at
|
|
114
|
+
your option.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
termite_tui/__init__.py,sha256=L9NDeUlFPgdDqPo_-F_rfC_Z2i8JtQrSBhbLd8LJsAk,10833
|
|
2
|
+
termite_tui/authoring.py,sha256=KUzxKWPfnDVGmycf7lNj4B52eYJV7TUNqk01KPyhnw8,2671
|
|
3
|
+
termite_tui/capture.py,sha256=XhISBi1bUd8kQgeUV_RhQej3TAqnSrPkXJqBvNmynD8,4492
|
|
4
|
+
termite_tui/termite_ffi.dll,sha256=-KU4chMYtECjMhvCy2sQMghcmQjizdaBeE9HP20ro5E,11491840
|
|
5
|
+
termite_tui/testing.py,sha256=xNQN1Lh8B56oNXI1hlDZlq2DUHBGEfeYZzRj4cdgQ1w,12154
|
|
6
|
+
termite_tui-0.3.0.dist-info/licenses/LICENSE-APACHE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
7
|
+
termite_tui-0.3.0.dist-info/licenses/LICENSE-MIT,sha256=hD4rKgl33RS6vXgLBetkqyGUEsQx6V-70Pem8_BQGFs,1081
|
|
8
|
+
termite_tui-0.3.0.dist-info/METADATA,sha256=08VUil7OoOKraZTm8QM-iyc1vdFyVywYCcPp1Dn7r0o,4254
|
|
9
|
+
termite_tui-0.3.0.dist-info/WHEEL,sha256=79BCzrXBJOa2YV6ugKrK59dqWifMGjAkgVd_6AQrqbU,98
|
|
10
|
+
termite_tui-0.3.0.dist-info/top_level.txt,sha256=0MoxnIHFRvlcrVatWMtwTGGxn5tXS7TK75DYHm7zHdU,12
|
|
11
|
+
termite_tui-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Termite contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
termite_tui
|