From cf7f77cb0bd47d79a1c38723ae231078ce68b72a Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 08:09:32 -0600 Subject: [PATCH 1/4] core(refactor): Extract views, format, snapshot why: Break the screen-to-terminal import cycle and separate low-level buffer helpers, views, reflow, formatting, and snapshots into acyclic modules. what: - Extract _util.py with hardened _byte_view and ASCII integer parsers - Extract views.py with Cursor, ScrollRegion, RowView, and RegionView - Extract _reflow.py for primary-screen soft-wrap reflow - Extract format.py and snapshot.py, keeping terminal/screen re-exports - Make screen.py acyclic with lazy graphics initialization --- src/libvt/__init__.py | 10 +- src/libvt/_reflow.py | 360 +++++++ src/libvt/_util.py | 99 ++ src/libvt/aio.py | 3 +- src/libvt/contrib/tmux/capture.py | 3 +- src/libvt/contrib/tmux/control.py | 2 +- src/libvt/contrib/tmux/window.py | 2 +- src/libvt/format.py | 599 +++++++++++ src/libvt/graphics.py | 2 +- src/libvt/parser.py | 79 +- src/libvt/screen.py | 1487 +------------------------ src/libvt/snapshot.py | 1050 ++++++++++++++++++ src/libvt/status.py | 2 +- src/libvt/terminal.py | 1673 ++--------------------------- src/libvt/views.py | 1186 ++++++++++++++++++++ tests/test_libvt.py | 78 ++ tests/test_screen.py | 69 +- 17 files changed, 3612 insertions(+), 3092 deletions(-) create mode 100644 src/libvt/_reflow.py create mode 100644 src/libvt/_util.py create mode 100644 src/libvt/format.py create mode 100644 src/libvt/snapshot.py create mode 100644 src/libvt/views.py diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py index 7e06d904..53c1fb25 100644 --- a/src/libvt/__init__.py +++ b/src/libvt/__init__.py @@ -11,13 +11,15 @@ from libvt.config import Limits, Policy, Profile from libvt.events import Event from libvt.exc import LibVtError, ProtocolError - from libvt.screen import Cell, Screen + from libvt.screen import Screen + from libvt.snapshot import Snapshot from libvt.style import Appearance, Style - from libvt.terminal import Snapshot, Terminal, render, strip + from libvt.terminal import Terminal, render, strip + from libvt.views import Cell _LAZY_EXPORTS: dict[str, tuple[str, str]] = { "Appearance": ("libvt.style", "Appearance"), - "Cell": ("libvt.screen", "Cell"), + "Cell": ("libvt.views", "Cell"), "Event": ("libvt.events", "Event"), "LibVtError": ("libvt.exc", "LibVtError"), "Limits": ("libvt.config", "Limits"), @@ -25,7 +27,7 @@ "Profile": ("libvt.config", "Profile"), "ProtocolError": ("libvt.exc", "ProtocolError"), "Screen": ("libvt.screen", "Screen"), - "Snapshot": ("libvt.terminal", "Snapshot"), + "Snapshot": ("libvt.snapshot", "Snapshot"), "Style": ("libvt.style", "Style"), "Terminal": ("libvt.terminal", "Terminal"), "render": ("libvt.terminal", "render"), diff --git a/src/libvt/_reflow.py b/src/libvt/_reflow.py new file mode 100644 index 00000000..75ecb184 --- /dev/null +++ b/src/libvt/_reflow.py @@ -0,0 +1,360 @@ +"""Soft-wrap reflow engine for primary :class:`~libvt.screen.Screen` resizes.""" + +from __future__ import annotations + +import collections.abc +import typing as t + +from libvt._grid import ( + _PEN_BASE_MASK, + FrozenRow, + RowLike, + _CellExt, + _Row, + raw_width_bits, +) +from libvt._ucd import WidthRole + +if t.TYPE_CHECKING: + from libvt.screen import Screen + + +def reflow_primary_screen( + screen: Screen, + *, + rows: int, + cols: int, + extra_pins: collections.abc.Sequence[tuple[int, int]] = (), +) -> tuple[tuple[int, int], ...]: + """Reflow soft-wrapped lines across scrollback and viewport on *screen*.""" + hist_rows = list(screen._history.freeze()) + hist_len = len(hist_rows) + old_first_abs = screen._scrolled_total - hist_len + + last_active = screen._cur_row + for r_idx in range(len(screen._rows) - 1, screen._cur_row, -1): + if screen._rows[r_idx].used > 0 or screen._rows[r_idx].wrapped: + last_active = r_idx + break + + total = hist_len + last_active + 1 + cur_abs_idx = hist_len + screen._cur_row + eff_cur_col = screen._cur_col + (1 if screen._pending_wrap else 0) + + gfx_roots = screen._gfx.root_placement_pins() if screen._gfx is not None else [] + n_extra = len(extra_pins) + all_pins: list[tuple[int, int]] = list(extra_pins) + for _, g_abs, g_col in gfx_roots: + all_pins.append((g_abs, g_col)) + + mapped_out: list[tuple[int, int] | None] = [None] * len(all_pins) + pins_by_row: dict[int, list[tuple[int, int]]] = {} + for p_idx, (p_abs, p_col) in enumerate(all_pins): + rel_in = p_abs - old_first_abs + if 0 <= rel_in < total: + pins_by_row.setdefault(rel_in, []).append((p_idx, p_col)) + + new_all: list[RowLike] = [] + new_cur_abs = 0 + new_cur_col = 0 + new_pending_wrap = False + cursor_placed = False + viewport_start = 0 + + idx = 0 + while idx < total: + if idx < hist_len: + fr = hist_rows[idx] + if not fr.wrapped: + fr_t_cols = len(fr.cells) if fr.cells is not None else len(fr.text) + fr_used = ( + fr_t_cols + if (not fr.runs and not fr.exts) + else max( + fr_t_cols, + fr.runs[-1][0] if fr.runs else 0, + (fr.exts[-1][0] + 1) if fr.exts else 0, + ) + ) + if fr_used <= cols: + out_idx = len(new_all) + new_all.append(fr) + if pins_by_row: + row_ps = pins_by_row.get(idx) + if row_ps is not None: + for p_idx, p_col in row_ps: + mapped_out[p_idx] = ( + out_idx, + min(cols - 1, max(0, p_col)), + ) + idx += 1 + continue + + group_start = idx + if group_start == hist_len: + viewport_start = len(new_all) + while idx + 1 < total: + cur_src = hist_rows[idx] if idx < hist_len else screen._rows[idx - hist_len] + if not cur_src.wrapped: + break + idx += 1 + group_end = idx + idx += 1 + + if group_start <= cur_abs_idx < group_end: + cur_r_src = ( + hist_rows[cur_abs_idx] + if cur_abs_idx < hist_len + else screen._rows[cur_abs_idx - hist_len] + ) + cur_r_cols = cur_r_src.cols + if eff_cur_col >= cur_r_cols: + cur_abs_idx += 1 + eff_cur_col = 0 + + cells: list[tuple[str, int, int, _CellExt | None, int]] = [] + cell_pins: dict[int, list[tuple[int, int]]] = {} + carried_pins: list[int] = [] + after_group_pins: list[tuple[int, int]] = [] + cur_after_extra: int | None = None + carry_cur = False + + for r_i in range(group_start, group_end + 1): + src = hist_rows[r_i] if r_i < hist_len else screen._rows[r_i - hist_len] + is_last = r_i == group_end + src_cols = src.cols + src_t_used = ( + src.text_used + if isinstance(src, _Row) + else (len(src.cells) if src.cells is not None else len(src.text)) + ) + row_limit = src_cols if not is_last else src_t_used + if r_i == cur_abs_idx and eff_cur_col >= row_limit: + cur_after_extra = eff_cur_col - row_limit + + row_ps = pins_by_row.get(r_i) + col_pins_map: dict[int, list[int]] | None = None + if row_ps is not None: + col_pins_map = {} + for p_idx, p_col in row_ps: + eff_pc = max(0, p_col) + if eff_pc >= row_limit: + if is_last: + after_group_pins.append((p_idx, eff_pc - row_limit)) + else: + carried_pins.append(p_idx) + else: + col_pins_map.setdefault(eff_pc, []).append(p_idx) + + for c_i in range(row_limit): + word = src.attr_at(c_i) + rb = raw_width_bits(word) + is_cur = r_i == cur_abs_idx and c_i == eff_cur_col + here_pins = col_pins_map.get(c_i) if col_pins_map is not None else None + if rb == int(WidthRole.SPACER_HEAD): + if is_cur: + carry_cur = True + if here_pins: + carried_pins.extend(here_pins) + continue + if rb == int(WidthRole.SPACER_TAIL): + if is_cur and cells: + p_ch, p_w, p_cw, p_ext, _ = cells[-1] + cells[-1] = (p_ch, p_w, p_cw, p_ext, 1) + if here_pins: + if cells: + prev_k = len(cells) - 1 + tgt = cell_pins.setdefault(prev_k, []) + for p_idx in here_pins: + tgt.append((p_idx, 1)) + else: + carried_pins.extend(here_pins) + continue + cw = 2 if rb == int(WidthRole.WIDE) else 1 + base_word = word & _PEN_BASE_MASK + cur_off = 0 if (is_cur or carry_cur) else -1 + carry_cur = False + cell_k = len(cells) + if carried_pins or here_pins: + tgt = cell_pins.setdefault(cell_k, []) + for p_idx in carried_pins: + tgt.append((p_idx, 0)) + carried_pins.clear() + if here_pins: + for p_idx in here_pins: + tgt.append((p_idx, 0)) + ch_val = src.char_at(c_i) + cells.append( + ( + ch_val, + base_word, + cw, + src.ext_at(c_i), + cur_off, + ) + ) + + if not cells: + empty_row = _Row(cols, gen_counter=screen._gen_counter) + new_all.append(empty_row) + out_idx = len(new_all) - 1 + if group_start <= cur_abs_idx <= group_end and not cursor_placed: + extra = 0 if cur_after_extra is None else cur_after_extra + new_cur_abs = out_idx + new_cur_col = min(cols - 1, extra) + new_pending_wrap = False + cursor_placed = True + for p_idx in carried_pins: + mapped_out[p_idx] = (out_idx, 0) + for p_idx, p_extra in after_group_pins: + mapped_out[p_idx] = (out_idx, min(cols - 1, p_extra)) + continue + + cur_out = _Row(cols, gen_counter=screen._gen_counter) + new_all.append(cur_out) + out_col = 0 + for cell_k, (ch, base_w, cw, ce, cur_off) in enumerate(cells): + eff_cw = cw + eff_ch = ch + if eff_cw == 2 and cols == 1: + eff_ch = "\ufffd" + eff_cw = 1 + + if out_col + eff_cw > cols: + if out_col < cols: + cur_out.write_spacer_head(out_col, 0, None) + cur_out.wrapped = True + cur_out = _Row(cols, gen_counter=screen._gen_counter) + new_all.append(cur_out) + out_col = 0 + + out_idx = len(new_all) - 1 + if cur_off >= 0 and not cursor_placed: + new_cur_abs = out_idx + new_cur_col = min(cols - 1, out_col + cur_off) + new_pending_wrap = False + cursor_placed = True + + c_ps = cell_pins.get(cell_k) + if c_ps is not None: + for p_idx, p_off in c_ps: + mapped_out[p_idx] = ( + out_idx, + min(cols - 1, out_col + p_off), + ) + + if eff_cw == 2: + cur_out.write_wide(out_col, eff_ch, base_w, ce) + out_col += 2 + else: + cur_out.write_narrow(out_col, eff_ch, base_w, ce) + out_col += 1 + + last_out_idx = len(new_all) - 1 + for p_idx in carried_pins: + mapped_out[p_idx] = (last_out_idx, min(cols - 1, out_col)) + for p_idx, p_extra in after_group_pins: + mapped_out[p_idx] = ( + last_out_idx, + min(cols - 1, out_col + p_extra), + ) + + if (cur_after_extra is not None or carry_cur) and not cursor_placed: + extra = 0 if cur_after_extra is None else cur_after_extra + new_cur_abs = last_out_idx + if extra == 0 and out_col == cols: + new_cur_col = cols - 1 + new_pending_wrap = True + else: + new_cur_col = min(cols - 1, out_col + extra) + new_pending_wrap = False + cursor_placed = True + + if not new_all: + new_all.append(_Row(cols, gen_counter=screen._gen_counter)) + + last_in_abs = old_first_abs + total - 1 + last_out_base = len(new_all) - 1 + for p_idx, (p_abs, p_col) in enumerate(all_pins): + if p_abs > last_in_abs: + mapped_out[p_idx] = ( + last_out_base + (p_abs - last_in_abs), + min(cols - 1, max(0, p_col)), + ) + + hist_cut = max(0, len(new_all) - rows) + # Keep existing bottom padding from pulling hard history lines into view. + if hist_cut < viewport_start: + trailing_blanks = len(screen._rows) - last_active - 1 + hist_cut = min(viewport_start, hist_cut + trailing_blanks) + hist_cut = min(hist_cut, new_cur_abs) + + prev_scrolled = screen._scrolled_total + prev_evicted = screen._evicted_total + evicted_in_reflow = screen._history.replace_all(new_all[:hist_cut]) + new_hist_len = len(screen._history) + new_evicted = max( + prev_evicted + evicted_in_reflow, + prev_scrolled - new_hist_len, + ) + screen._evicted_total = new_evicted + screen._scrolled_total = new_evicted + new_hist_len + + viewport: list[_Row] = [ + ( + r_v.thaw(cols, gen_counter=screen._gen_counter) + if isinstance(r_v, FrozenRow) + else r_v + ) + for r_v in new_all[hist_cut : hist_cut + rows] + ] + while len(viewport) < rows: + viewport.append(_Row(cols, gen_counter=screen._gen_counter)) + for r_v in viewport: + r_v.bind_counter(screen._gen_counter) + screen._rows = viewport + screen._cols = cols + screen._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut)) + screen._cur_col = max(0, min(cols - 1, new_cur_col)) + screen._pending_wrap = new_pending_wrap + + if not all_pins: + if screen._gfx is not None: + screen._gfx.apply_reflow_pins( + (), + new_cols=cols, + min_retained_abs_row=screen._evicted_total, + max_abs=screen._scrolled_total + rows, + ) + return () + + final_pins: list[tuple[int, int]] = [] + new_first_abs = screen._scrolled_total - hist_cut + for p_idx, (old_abs, old_col) in enumerate(all_pins): + m_pair = mapped_out[p_idx] + if m_pair is None: + if old_abs < old_first_abs: + mapped_abs = new_first_abs + (old_abs - old_first_abs) + else: + mapped_abs = old_abs + final_pins.append((mapped_abs, min(cols - 1, max(0, old_col)))) + else: + out_r, new_c = m_pair + final_pins.append((new_first_abs + out_r, new_c)) + + if screen._gfx is not None: + remapped_gfx = [ + (gfx_idx, final_pins[n_extra + k][0], final_pins[n_extra + k][1]) + for k, (gfx_idx, _, _) in enumerate(gfx_roots) + ] + screen._gfx.apply_reflow_pins( + remapped_gfx, + new_cols=cols, + min_retained_abs_row=screen._evicted_total, + max_abs=screen._scrolled_total + rows, + ) + + return tuple(final_pins[:n_extra]) + + +__all__ = ["reflow_primary_screen"] diff --git a/src/libvt/_util.py b/src/libvt/_util.py new file mode 100644 index 00000000..73a23907 --- /dev/null +++ b/src/libvt/_util.py @@ -0,0 +1,99 @@ +"""Internal low-level buffer and ASCII integer parsing utilities.""" + +from __future__ import annotations + +import collections.abc + + +def _byte_view(data: collections.abc.Buffer) -> memoryview: + """Return a fresh flat unsigned-byte ``memoryview`` in logical order. + + Zero-copy for ``bytes``, ``bytearray``, and non-broadcast C-contiguous + buffers; copies non-contiguous, strided, or zero-stride broadcast views + into a contiguous ``bytes`` backing store. + + Examples + -------- + >>> from libvt._util import _byte_view + >>> with _byte_view(memoryview(b"hXeYlZlWo")[::2]) as mv: + ... bytes(mv) + b'hello' + """ + if isinstance(data, (bytes, bytearray)): + return memoryview(data) + view = memoryview(data) + if view.nbytes == 0: + view.release() + return memoryview(b"") + if view.c_contiguous: + if view.ndim == 1 and view.format == "B": + return view + strides = view.strides + if strides is None or 0 not in strides: + try: + return view.cast("B") + finally: + view.release() + try: + raw = view.tobytes() + finally: + view.release() + return memoryview(raw) + + +def _parse_ascii_uint(raw: str, *, max_val: int) -> int | None: + """Parse non-empty ASCII digits ``0..9`` up to *max_val*, else ``None``.""" + if not raw: + return None + acc = 0 + for ch in raw: + code = ord(ch) + if not (0x30 <= code <= 0x39): + return None + acc = acc * 10 + (code - 0x30) + if acc > max_val: + return None + return acc + + +def _parse_ascii_int(raw: str, *, min_val: int, max_val: int) -> int | None: + """Parse optional ``+``/``-`` plus ASCII digits within ``[min_val, max_val]``.""" + if not raw: + return None + neg = False + start = 0 + first = raw[0] + if first == "-": + neg = True + start = 1 + elif first == "+": + start = 1 + if start >= len(raw): + return None + acc = 0 + if neg: + limit = -min_val + for idx in range(start, len(raw)): + code = ord(raw[idx]) + if not (0x30 <= code <= 0x39): + return None + acc = acc * 10 + (code - 0x30) + if acc > limit: + return None + val = -acc + return val if val <= max_val else None + for idx in range(start, len(raw)): + code = ord(raw[idx]) + if not (0x30 <= code <= 0x39): + return None + acc = acc * 10 + (code - 0x30) + if acc > max_val: + return None + return acc if acc >= min_val else None + + +__all__ = [ + "_byte_view", + "_parse_ascii_int", + "_parse_ascii_uint", +] diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 74a1ebc1..337dcb6e 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -17,6 +17,7 @@ import time import typing as t +from libvt._util import _byte_view, _parse_ascii_uint from libvt.config import ( DEFAULT_LIMITS, DEFAULT_OSC7_HOSTS, @@ -34,7 +35,7 @@ MouseTracker, PasteEvent, ) -from libvt.parser import ParserEncoding, _byte_view, _parse_ascii_uint +from libvt.parser import ParserEncoding from libvt.terminal import FlightRecorder, Snapshot, StopOn, Terminal type TtyMode = t.Literal["cooked", "cbreak", "raw"] diff --git a/src/libvt/contrib/tmux/capture.py b/src/libvt/contrib/tmux/capture.py index 8e728ca1..f9377c0b 100644 --- a/src/libvt/contrib/tmux/capture.py +++ b/src/libvt/contrib/tmux/capture.py @@ -12,6 +12,7 @@ from libvt._grid import WidthRole, _Row, raw_width_bits from libvt._ucd import display_width +from libvt._util import _parse_ascii_int, _parse_ascii_uint from libvt.config import ( DEFAULT_LIMITS, Limits, @@ -26,7 +27,7 @@ ) from libvt.events import PromptKind, PromptZone from libvt.modes import DEC_PRIVATE_MASK, Mode -from libvt.parser import CsiParams, Parser, _parse_ascii_int, _parse_ascii_uint +from libvt.parser import CsiParams, Parser from libvt.screen import CursorShape, Screen, ScrollRegion from libvt.style import DEFAULT_STYLE from libvt.terminal import Snapshot, Terminal, strip diff --git a/src/libvt/contrib/tmux/control.py b/src/libvt/contrib/tmux/control.py index 217c83e4..0ac79c6b 100644 --- a/src/libvt/contrib/tmux/control.py +++ b/src/libvt/contrib/tmux/control.py @@ -11,8 +11,8 @@ import typing as t from dataclasses import dataclass +from libvt._util import _byte_view from libvt.exc import ProtocolError -from libvt.parser import _byte_view if t.TYPE_CHECKING: from libvt.config import Limits, Policy, Profile diff --git a/src/libvt/contrib/tmux/window.py b/src/libvt/contrib/tmux/window.py index ebc0d84c..06e9ad71 100644 --- a/src/libvt/contrib/tmux/window.py +++ b/src/libvt/contrib/tmux/window.py @@ -14,6 +14,7 @@ from dataclasses import dataclass, field from libvt._ucd import display_width +from libvt._util import _parse_ascii_uint from libvt.config import DEFAULT_LIMITS, Limits, Policy, Profile from libvt.contrib.tmux.capture import ( _TMUX_MAX_DIM, @@ -35,7 +36,6 @@ tmux_profile, ) from libvt.modes import Mode -from libvt.parser import _parse_ascii_uint from libvt.screen import Cursor, Screen from libvt.style import ( DEFAULT_STYLE, diff --git a/src/libvt/format.py b/src/libvt/format.py new file mode 100644 index 00000000..0056553e --- /dev/null +++ b/src/libvt/format.py @@ -0,0 +1,599 @@ +"""Plain-text, ANSI/DEC VT, and HTML formatters for terminal snapshots.""" + +from __future__ import annotations + +import collections.abc +import enum +import html +import itertools +import typing as t +from dataclasses import dataclass + +from libvt._grid import RowLike, _Row, raw_width_bits, unpack_style +from libvt._ucd import CLUSTER_NONE, WidthRole, char_width, step_cluster +from libvt.config import DEFAULT_POLICY, DEFAULT_PROFILE, Policy, Profile +from libvt.modes import ( + ALT_SCREEN_MODES, + DEC_PRIVATE_MASK, + TRANSIENT_SNAPSHOT_MODES, + Mode, +) +from libvt.style import ( + DEFAULT_APPEARANCE, + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + Style, + UnderlineStyle, +) +from libvt.views import CursorShape, RowView, _row_groups, _unwrapped_rows + +if t.TYPE_CHECKING: + from libvt.snapshot import Snapshot + +_SAFE_URI_PREFIXES = ("https://", "http://", "mailto:") + + +class OutputFormat(enum.StrEnum): + """Export target formats supported by :class:`Formatter`.""" + + #: Right-trimmed plain text without escape sequences. + PLAIN = "plain" + #: ANSI/DEC VT stream with the active viewport, pen, and modes. + VT = "vt" + #: Self-contained ``
`` HTML fragment with ```` SGR styling.
+    HTML = "html"
+
+
+@dataclass(frozen=True, slots=True)
+class _VtPen:
+    style: Style = DEFAULT_STYLE
+    hyperlink: Hyperlink | None = None
+    protected: bool = False
+
+
+_DEFAULT_VT_PEN = _VtPen()
+
+
+def _format_osc_rgb(rgb: tuple[int, int, int]) -> str:
+    r, g, b = rgb
+    return f"rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}"
+
+
+def _color_sgr_tokens(color: Color, *, fg: bool) -> list[str]:
+    if color is None:
+        return ["39" if fg else "49"]
+    if isinstance(color, AnsiColor):
+        idx = int(color)
+        if idx < 8:
+            return [str((30 if fg else 40) + idx)]
+        return [str((90 if fg else 100) + (idx - 8))]
+    prefix = "38" if fg else "48"
+    if isinstance(color, IndexedColor):
+        return [f"{prefix};5;{color.index}"]
+    return [f"{prefix};2;{color.r};{color.g};{color.b}"]
+
+
+def _style_to_sgr(style: Style) -> str:
+    if style == DEFAULT_STYLE:
+        return "\x1b[0m"
+    parts: list[str] = ["0"]
+    if style.bold:
+        parts.append("1")
+    if style.dim:
+        parts.append("2")
+    if style.italic:
+        parts.append("3")
+    if style.underline == UnderlineStyle.SINGLE:
+        parts.append("4")
+    elif style.underline != UnderlineStyle.NONE:
+        parts.append(f"4:{int(style.underline)}")
+    if style.blink:
+        parts.append("5")
+    if style.reverse:
+        parts.append("7")
+    if style.hidden:
+        parts.append("8")
+    if style.strikethrough:
+        parts.append("9")
+    if style.overline:
+        parts.append("53")
+    if style.fg is not None:
+        parts.extend(_color_sgr_tokens(style.fg, fg=True))
+    if style.bg is not None:
+        parts.extend(_color_sgr_tokens(style.bg, fg=False))
+    if style.underline_color is not None:
+        ul = style.underline_color
+        if isinstance(ul, AnsiColor):
+            parts.append(f"58:5:{int(ul)}")
+        elif isinstance(ul, IndexedColor):
+            parts.append(f"58:5:{ul.index}")
+        else:
+            parts.append(f"58:2::{ul.r}:{ul.g}:{ul.b}")
+    return f"\x1b[{';'.join(parts)}m"
+
+
+def _is_safe_uri(uri: str) -> bool:
+    low = uri.lstrip().lower()
+    return low.startswith(_SAFE_URI_PREFIXES)
+
+
+def _vt_cell_pen(row: _Row, col: int) -> _VtPen:
+    ext = row.ext_at(col)
+    return _VtPen(
+        style=unpack_style(row.attr_at(col), ext),
+        hyperlink=ext.hyperlink if ext is not None else None,
+        protected=ext is not None and ext.protected,
+    )
+
+
+def _vt_glyph_state(
+    text: str,
+    width: int,
+    state: int,
+    *,
+    mode_2027: bool,
+    profile: Profile,
+) -> int | None:
+    """Return the cluster state if printing *text* adds one glyph of *width*."""
+    if not text:
+        return None
+    unicode = profile.unicode
+    actual_width = char_width(text[0], ambiguous_width=unicode.ambiguous_width)
+    for idx, ch in enumerate(text):
+        extends, state, override = step_cluster(
+            state,
+            ord(ch),
+            mode_2027=mode_2027,
+            vs15_narrows=unicode.vs15_narrows_wide_emoji,
+            vs16_always_wide=unicode.vs16_always_wide,
+            ambiguous_width=unicode.ambiguous_width,
+        )
+        if extends != (idx > 0):
+            return None
+        if override >= 0:
+            actual_width = override
+    return state if actual_width == width else None
+
+
+def _vt_wrap_position(
+    snapshot: Snapshot, *, left: int, right: int
+) -> tuple[int, int, int] | None:
+    """Find the write position and captured glyph column for pending wrap."""
+    cur = snapshot.cursor
+    if not cur.pending_wrap or Mode.DECAWM not in snapshot.modes:
+        return None
+    edge = right if cur.col <= right else snapshot.cols - 1
+    if cur.col != edge or edge < 0 or not 0 <= cur.row < snapshot.rows:
+        return None
+    row = snapshot._rows[cur.row]
+    if edge >= row.text_used:
+        return None
+    role = raw_width_bits(row.attr_at(edge))
+    if role == WidthRole.SPACER_HEAD:
+        return None
+    col = edge - 1 if role == WidthRole.SPACER_TAIL else edge
+    if col < 0:
+        return None
+    last_col = snapshot.cols - 1
+    if (
+        col <= 1
+        and cur.row > 0
+        and raw_width_bits(snapshot._rows[cur.row - 1].attr_at(last_col))
+        == WidthRole.SPACER_HEAD
+    ):
+        # Printing from the spacer head keeps the wide glyph paired across rows.
+        margins = snapshot._scroll_region
+        if (
+            col == 0
+            and role == WidthRole.SPACER_TAIL
+            and (left, right) == (0, last_col)
+            and cur.row - 1 != margins.bottom
+            and (Mode.DECOM not in snapshot.modes or margins.top < cur.row)
+        ):
+            return cur.row - 1, last_col, col
+        return None
+    return cur.row, col, col
+
+
+def _unwrapped_style_runs(
+    rows: collections.abc.Sequence[RowLike],
+) -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]:
+    def runs() -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]:
+        for row, padding in _unwrapped_rows(rows, include_styles=True):
+            yield from (
+                (run.text, run.style, run.hyperlink)
+                for run in RowView(row).runs
+                if run.text
+            )
+            if padding:
+                yield " " * padding, DEFAULT_STYLE, None
+
+    for (style, link), group in itertools.groupby(
+        runs(), key=lambda item: (item[1], item[2])
+    ):
+        yield "".join(text for text, _, _ in group), style, link
+
+
+class Formatter:
+    r"""Serialize a :class:`~libvt.terminal.Snapshot` to plain text, VT, or HTML.
+
+    Replay VT output into a fresh :class:`~libvt.terminal.Terminal` of the same
+    size and profile.
+    See :meth:`~libvt.terminal.Snapshot.format` for the VT export contract.
+
+    Attributes
+    ----------
+    output_format : OutputFormat
+        Target export format (``PLAIN``, ``VT``, or ``HTML``).
+    policy : Policy
+        URI and sequence policy applied during export.
+    profile : Profile
+        Terminal profile governing width and appearance rules.
+    unwrap : bool
+        When ``True``, join soft-wrapped continuation rows onto a single line
+        in ``PLAIN`` and ``HTML`` output.
+
+    Examples
+    --------
+    >>> from libvt.terminal import Formatter, OutputFormat, Terminal
+    >>> term = Terminal(rows=2, cols=8)
+    >>> term.feed(b"\x1b[31mhello world\x1b[0m")
+    >>> Formatter(OutputFormat.PLAIN, unwrap=True).format_snapshot(term.committed)
+    'hello world'
+    """
+
+    __slots__ = ("output_format", "policy", "profile", "unwrap")
+
+    def __init__(
+        self,
+        output_format: OutputFormat = OutputFormat.PLAIN,
+        *,
+        policy: Policy = DEFAULT_POLICY,
+        profile: Profile = DEFAULT_PROFILE,
+        unwrap: bool = False,
+    ) -> None:
+        self.output_format = output_format
+        self.policy = policy
+        self.profile = profile
+        self.unwrap = unwrap
+
+    def format_snapshot(self, snapshot: Snapshot) -> str:
+        """Render *snapshot* in :attr:`output_format`."""
+        if self.output_format == OutputFormat.PLAIN:
+            return snapshot.unwrapped_text if self.unwrap else snapshot.text
+        if self.output_format == OutputFormat.VT:
+            return self._render_vt(snapshot)
+        return self._render_html(snapshot)
+
+    def _render_vt(self, snapshot: Snapshot) -> str:
+        out: list[str] = []
+        export_modes = snapshot.modes - TRANSIENT_SNAPSHOT_MODES
+        if Mode.DECCOLM in export_modes:
+            if Mode.ALLOW_80_132 in export_modes:
+                out.append("\x1b[?40h\x1b[?3h")
+            else:
+                out.append("\x1b[?40h\x1b[?3h\x1b[?40l")
+        if not snapshot.active_is_alt:
+            export_modes = export_modes - ALT_SCREEN_MODES
+        else:
+            for alt_mode in sorted(export_modes & ALT_SCREEN_MODES, key=int):
+                code = int(alt_mode) & ~DEC_PRIVATE_MASK
+                out.append(f"\x1b[?{code}h")
+        mode_2027 = Mode.GRAPHEME_CLUSTERING in export_modes
+        if not mode_2027:
+            out.append("\x1b[?2027l")
+        app = snapshot.appearance
+        for ov_idx, ov_rgb in app.palette_overrides:
+            out.append(f"\x1b]4;{ov_idx};{_format_osc_rgb(ov_rgb)}\x1b\\")
+        if app.fg_rgb != self.profile.queries.fg_rgb:
+            out.append(f"\x1b]10;{_format_osc_rgb(app.fg_rgb)}\x1b\\")
+        if app.bg_rgb != self.profile.queries.bg_rgb:
+            out.append(f"\x1b]11;{_format_osc_rgb(app.bg_rgb)}\x1b\\")
+        if app.cursor_rgb != self.profile.queries.cursor_rgb:
+            out.append(f"\x1b]12;{_format_osc_rgb(app.cursor_rgb)}\x1b\\")
+        cur_pen = _DEFAULT_VT_PEN
+        cluster_state = CLUSTER_NONE
+        cols = snapshot.cols
+        n_rows = len(snapshot._rows)
+
+        def set_pen(pen: _VtPen) -> None:
+            nonlocal cur_pen
+            if pen.hyperlink != cur_pen.hyperlink:
+                link = pen.hyperlink
+                if link is None:
+                    out.append("\x1b]8;;\x1b\\")
+                else:
+                    param = f"id={link.id}" if link.id else ""
+                    out.append(f"\x1b]8;{param};{link.uri}\x1b\\")
+            if pen.style != cur_pen.style:
+                out.append(_style_to_sgr(pen.style))
+            if pen.protected != cur_pen.protected:
+                out.append('\x1b[1"q' if pen.protected else '\x1b[0"q')
+            cur_pen = pen
+
+        def set_grapheme_mode(enabled: bool) -> None:
+            nonlocal mode_2027
+            if enabled != mode_2027:
+                out.append("\x1b[?2027h" if enabled else "\x1b[?2027l")
+                mode_2027 = enabled
+
+        def move_cursor(r: int, c: int) -> None:
+            nonlocal cluster_state
+            out.append(f"\x1b[{r + 1};{c + 1}H")
+            cluster_state = CLUSTER_NONE
+
+        def glyph_mode(text: str, width: int, anchor: int) -> tuple[bool, int] | None:
+            for mode in (mode_2027, not mode_2027):
+                state = _vt_glyph_state(
+                    text, width, anchor, mode_2027=mode, profile=snapshot._profile
+                )
+                if state is not None:
+                    return mode, state
+            return None
+
+        def write_glyph(r: int, c: int) -> None:
+            nonlocal cluster_state
+            row = snapshot._rows[r]
+            text = row.char_at(c)
+            width = 2 if raw_width_bits(row.attr_at(c)) == WidthRole.WIDE else 1
+            variant = glyph_mode(text, width, cluster_state)
+            if variant is None and cluster_state != CLUSTER_NONE:
+                variant = glyph_mode(text, width, CLUSTER_NONE)
+                if variant is not None:
+                    if r > 0 and c == 0 and snapshot._rows[r - 1].wrapped:
+                        prev = snapshot._rows[r - 1]
+                        if (
+                            raw_width_bits(prev.attr_at(cols - 1))
+                            == WidthRole.SPACER_HEAD
+                        ):
+                            move_cursor(r - 1, cols - 1)
+                        else:
+                            # Consume pending wrap before addressing the row.
+                            out.append(" ")
+                            move_cursor(r, c)
+                    else:
+                        move_cursor(r, c)
+            if variant is not None:
+                mode, cluster_state = variant
+                set_grapheme_mode(mode)
+            out.append(text)
+
+        for r_idx, row in enumerate(snapshot._rows):
+            eff_wrapped = row.wrapped and r_idx + 1 < n_rows
+            if r_idx > 0:
+                prev_wrapped = snapshot._rows[r_idx - 1].wrapped
+                if not prev_wrapped:
+                    out.append("\r\n")
+                    cluster_state = CLUSTER_NONE
+                elif not eff_wrapped and row.text_used == 0 and cols > 0:
+                    set_pen(_DEFAULT_VT_PEN)
+                    out.append(f" \x1b[{r_idx + 1};1H\x1b[X")
+                    cluster_state = CLUSTER_NONE
+            if eff_wrapped:
+                has_spacer_head = (
+                    cols > 0
+                    and raw_width_bits(row.attr_at(cols - 1))
+                    == int(WidthRole.SPACER_HEAD)
+                    and raw_width_bits(snapshot._rows[r_idx + 1].attr_at(0))
+                    == int(WidthRole.WIDE)
+                )
+                limit = max(0, cols - 1) if has_spacer_head else cols
+            else:
+                limit = min(cols, row.text_used)
+            for c in range(limit):
+                rb = raw_width_bits(row.attr_at(c))
+                if rb in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)):
+                    continue
+                set_pen(_vt_cell_pen(row, c))
+                write_glyph(r_idx, c)
+            if not eff_wrapped and row.used > limit:
+                cur_col_pos = limit
+                span_c = limit
+                row_used = min(cols, row.used)
+                while span_c < row_used:
+                    pen = _vt_cell_pen(row, span_c)
+                    end_c = span_c + 1
+                    while end_c < row_used and _vt_cell_pen(row, end_c) == pen:
+                        end_c += 1
+                    if pen != _DEFAULT_VT_PEN:
+                        if cur_col_pos != span_c:
+                            move_cursor(r_idx, span_c)
+                            cur_col_pos = span_c
+                        set_pen(pen)
+                        if pen.protected or pen.hyperlink is not None:
+                            out.append(" " * (end_c - span_c))
+                            cur_col_pos = end_c
+                        elif end_c == cols:
+                            out.append("\x1b[K")
+                        else:
+                            out.append(f"\x1b[{end_c - span_c}X")
+                    span_c = end_c
+        margins = snapshot._scroll_region
+        if (margins.top, margins.bottom) != (0, n_rows - 1):
+            out.append(f"\x1b[{margins.top + 1};{margins.bottom + 1}r")
+        left, right = 0, cols - 1
+        if Mode.DECLRMM in export_modes:
+            out.append("\x1b[?69h")
+            left, right = margins.left, margins.right
+            if (left, right) != (0, cols - 1):
+                out.append(f"\x1b[{left + 1};{right + 1}s")
+        positioned_modes = ALT_SCREEN_MODES | {Mode.DECLRMM, Mode.IRM}
+        for mode in sorted(export_modes - positioned_modes, key=int):
+            raw = int(mode)
+            if raw & DEC_PRIVATE_MASK:
+                code = raw & ~DEC_PRIVATE_MASK
+                if mode not in (
+                    Mode.DECCOLM,
+                    Mode.DECAWM,
+                    Mode.AUTO_REPEAT,
+                    Mode.DECTCEM,
+                    Mode.ALTERNATE_SCROLL,
+                    Mode.GRAPHEME_CLUSTERING,
+                ) and not (mode == Mode.ALLOW_80_132 and Mode.DECCOLM in export_modes):
+                    out.append(f"\x1b[?{code}h")
+            else:
+                out.append(f"\x1b[{raw}h")
+        if Mode.DECAWM not in export_modes:
+            out.append("\x1b[?7l")
+        if Mode.AUTO_REPEAT not in export_modes:
+            out.append("\x1b[?8l")
+        if Mode.DECTCEM not in export_modes:
+            out.append("\x1b[?25l")
+        if Mode.ALTERNATE_SCROLL not in export_modes:
+            out.append("\x1b[?1007l")
+        cur = snapshot.cursor
+        if (cur.shape, cur.blinking) != (CursorShape.BLOCK, True):
+            decscusr_map: dict[tuple[CursorShape, bool], int] = {
+                (CursorShape.BLOCK, False): 2,
+                (CursorShape.UNDERLINE, True): 3,
+                (CursorShape.UNDERLINE, False): 4,
+                (CursorShape.BAR, True): 5,
+                (CursorShape.BAR, False): 6,
+            }
+            ps = decscusr_map.get((cur.shape, cur.blinking), 1)
+            out.append(f"\x1b[{ps} q")
+        origin = Mode.DECOM in export_modes
+        row_offset, col_offset = (margins.top, left) if origin else (0, 0)
+        wrap = _vt_wrap_position(snapshot, left=left, right=right)
+        r, c, glyph_col = wrap if wrap is not None else (cur.row, cur.col, None)
+        move_cursor(r - row_offset, c - col_offset)
+        if glyph_col is not None:
+            row = snapshot._rows[cur.row]
+            set_pen(_vt_cell_pen(row, glyph_col))
+            write_glyph(cur.row, glyph_col)
+        set_grapheme_mode(Mode.GRAPHEME_CLUSTERING in export_modes)
+        if Mode.IRM in export_modes:
+            out.append("\x1b[4h")
+        set_pen(snapshot._vt_pen)
+        return "".join(out)
+
+    def _render_html(self, snapshot: Snapshot) -> str:
+        r"""Render *snapshot* as an HTML ``
`` block.
+
+        References
+        ----------
+        - `VT510 Video Terminal Programmer Information — DECSCNM
+          `__
+
+        Examples
+        --------
+        >>> from libvt.terminal import OutputFormat, Terminal
+        >>> term = Terminal(rows=1, cols=4)
+        >>> term.feed(b"\x1b[?5h\x1b[31mR")
+        >>> "color:rgb(205,0,0)" in term.snapshot().format(OutputFormat.HTML)
+        True
+        """
+        app = snapshot.appearance
+        scr_fg, scr_bg = (
+            (app.bg_rgb, app.fg_rgb) if app.reverse_video else (app.fg_rgb, app.bg_rgb)
+        )
+        if app.reverse_video or (scr_fg, scr_bg) != (
+            DEFAULT_APPEARANCE.fg_rgb,
+            DEFAULT_APPEARANCE.bg_rgb,
+        ):
+            pre_tag = (
+                '
'
+            )
+        else:
+            pre_tag = '
'
+        lines: list[str] = [pre_tag]
+        allow_unsafe = self.policy.allow_unsafe_uris
+        ul_styles = {
+            UnderlineStyle.DOUBLE: "double",
+            UnderlineStyle.CURLY: "wavy",
+            UnderlineStyle.DOTTED: "dotted",
+            UnderlineStyle.DASHED: "dashed",
+        }
+        for rows in _row_groups(snapshot._rows, unwrap=self.unwrap):
+            runs = (
+                _unwrapped_style_runs(rows)
+                if self.unwrap
+                else (
+                    (run.text, run.style, run.hyperlink)
+                    for run in RowView(rows[0]).runs
+                )
+            )
+            chunks: list[str] = []
+            for run_text, style, hyperlink in runs:
+                escaped = html.escape(run_text)
+                css: list[str] = []
+                background: str | None = None
+                if style.bold:
+                    css.append("font-weight:bold")
+                if style.dim:
+                    css.append("opacity:0.65")
+                if style.italic:
+                    css.append("font-style:italic")
+                if style.reverse:
+                    fg_r, fg_g, fg_b = app.resolve_rgb(
+                        style.bg,
+                        default_rgb=scr_bg,
+                    )
+                    bg_r, bg_g, bg_b = app.resolve_rgb(
+                        style.fg,
+                        default_rgb=scr_fg,
+                    )
+                    css.append(f"color:rgb({fg_r},{fg_g},{fg_b})")
+                    background = f"background-color:rgb({bg_r},{bg_g},{bg_b})"
+                else:
+                    if style.fg is not None:
+                        fg_r, fg_g, fg_b = app.resolve_rgb(
+                            style.fg,
+                            default_rgb=scr_fg,
+                        )
+                        css.append(f"color:rgb({fg_r},{fg_g},{fg_b})")
+                    if style.bg is not None:
+                        bg_r, bg_g, bg_b = app.resolve_rgb(
+                            style.bg,
+                            default_rgb=scr_bg,
+                        )
+                        background = f"background-color:rgb({bg_r},{bg_g},{bg_b})"
+                if background is not None and not style.hidden:
+                    css.append(background)
+                dec_lines: list[str] = []
+                if style.underline != UnderlineStyle.NONE:
+                    dec_lines.append("underline")
+                if style.overline:
+                    dec_lines.append("overline")
+                if style.strikethrough:
+                    dec_lines.append("line-through")
+                if dec_lines:
+                    css.append(f"text-decoration-line:{' '.join(dec_lines)}")
+                ul_css = ul_styles.get(style.underline)
+                if ul_css is not None:
+                    css.append(f"text-decoration-style:{ul_css}")
+                if style.underline_color is not None:
+                    ur, ug, ub = app.resolve_rgb(
+                        style.underline_color,
+                        default_rgb=scr_fg,
+                    )
+                    css.append(f"text-decoration-color:rgb({ur},{ug},{ub})")
+                span = (
+                    f'{escaped}'
+                    if css
+                    else escaped
+                )
+                if hyperlink is not None and (
+                    allow_unsafe or _is_safe_uri(hyperlink.uri)
+                ):
+                    href = html.escape(hyperlink.uri, quote=True)
+                    span = f'{span}'
+                if style.hidden:
+                    span = f'{span}'
+                    if background is not None:
+                        span = f'{span}'
+                chunks.append(span)
+            lines.append("".join(chunks))
+        lines.append("
") + return "\n".join(lines) + + +__all__ = [ + "Formatter", + "OutputFormat", +] diff --git a/src/libvt/graphics.py b/src/libvt/graphics.py index 71d77297..a8b34575 100644 --- a/src/libvt/graphics.py +++ b/src/libvt/graphics.py @@ -12,7 +12,7 @@ import zlib from dataclasses import dataclass -from libvt.parser import _parse_ascii_uint +from libvt._util import _parse_ascii_uint if t.TYPE_CHECKING: from libvt.config import SixelErasePolicy diff --git a/src/libvt/parser.py b/src/libvt/parser.py index 8563ba37..2747e722 100644 --- a/src/libvt/parser.py +++ b/src/libvt/parser.py @@ -15,6 +15,7 @@ import typing as t from dataclasses import dataclass +from libvt._util import _byte_view from libvt.config import DEFAULT_LIMITS, Limits from libvt.style import ( DEFAULT_STYLE, @@ -918,7 +919,10 @@ def feed(self, data: collections.abc.Buffer) -> list[Action]: def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: """Feed *data* directly into *sink* without allocating action wrappers.""" - mv = _byte_view(data) + with _byte_view(data) as mv: + self._feed_mv(mv, sink) + + def _feed_mv(self, mv: memoryview, sink: ActionSink) -> None: n = len(mv) pos = 0 max_osc = self._limits.max_osc_bytes @@ -1314,79 +1318,6 @@ def _parse_osc_code(buf: bytes) -> int: return acc -def _parse_ascii_uint(raw: str, *, max_val: int) -> int | None: - """Parse non-empty ASCII digits ``0..9`` up to *max_val*, else ``None``.""" - if not raw: - return None - acc = 0 - for ch in raw: - code = ord(ch) - if not (0x30 <= code <= 0x39): - return None - acc = acc * 10 + (code - 0x30) - if acc > max_val: - return None - return acc - - -def _byte_view(data: collections.abc.Buffer) -> memoryview: - """Return a fresh flat byte view in logical order, copying only strided data.""" - view = memoryview(data) - if view.nbytes == 0: - view.release() - return memoryview(b"") - if view.c_contiguous: - if view.ndim == 1 and view.format == "B": - return view - strides = view.strides - if strides is None or 0 not in strides: - try: - return view.cast("B") - finally: - view.release() - try: - raw = view.tobytes() - finally: - view.release() - return memoryview(raw) - - -def _parse_ascii_int(raw: str, *, min_val: int, max_val: int) -> int | None: - """Parse optional ``+``/``-`` plus ASCII digits within ``[min_val, max_val]``.""" - if not raw: - return None - neg = False - start = 0 - first = raw[0] - if first == "-": - neg = True - start = 1 - elif first == "+": - start = 1 - if start >= len(raw): - return None - acc = 0 - if neg: - limit = -min_val - for idx in range(start, len(raw)): - code = ord(raw[idx]) - if not (0x30 <= code <= 0x39): - return None - acc = acc * 10 + (code - 0x30) - if acc > limit: - return None - val = -acc - return val if val <= max_val else None - for idx in range(start, len(raw)): - code = ord(raw[idx]) - if not (0x30 <= code <= 0x39): - return None - acc = acc * 10 + (code - 0x30) - if acc > max_val: - return None - return acc if acc >= min_val else None - - __all__ = [ "EMPTY_PARAMS", "Action", diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 847900ba..0bce6600 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -1,31 +1,22 @@ -"""Zero-based screen buffer, lazy cell/row/region views, reflow, and dual screens.""" +"""Zero-based screen buffer, dual primary/alternate screens, and resize.""" from __future__ import annotations -import bisect import collections.abc -import enum -import operator -import sys import typing as t -from dataclasses import dataclass from libvt._grid import ( _EMPTY_FROZEN_HISTORY, - _PEN_BASE_MASK, FrozenRow, RowLike, - _CellExt, - _FrozenHistory, _HistoryBuffer, _Row, _RowGenCounter, make_cell_ext, pack_pen_base, raw_width_bits, - unpack_style, - unpack_width_role, ) +from libvt._reflow import reflow_primary_screen from libvt._ucd import ( SAFE_NARROW_BMP_RE, WidthRole, @@ -33,1076 +24,32 @@ segment_graphemes, ) from libvt.config import DEFAULT_PROFILE, Profile -from libvt.graphics import GraphicsTracker, ImageMeta, ImagePlacement from libvt.input import KittyKeyboardStack from libvt.modes import Mode +from libvt.snapshot import Snapshot, _make_snapshot from libvt.status import ProgramStatus from libvt.style import DEFAULT_APPEARANCE, DEFAULT_STYLE, Appearance, Hyperlink, Style +from libvt.views import ( + BLANK_CELL, + Cell, + Cursor, + CursorShape, + RegionView, + RowRun, + RowView, + ScrollRegion, + _format_display_row, + _frozen_row_runs, # noqa: F401 + _HistoryView, + _materialize_cell, # noqa: F401 + _row_groups, # noqa: F401 + _unwrapped_rows, # noqa: F401 + format_rows_text, + slice_grid, +) if t.TYPE_CHECKING: - from libvt.terminal import Snapshot - -_ITEM0 = operator.itemgetter(0) - - -class CursorShape(enum.StrEnum): - """Cursor glyph shape configured via ``DECSCUSR`` (``CSI Ps SP q``).""" - - BLOCK = "block" - UNDERLINE = "underline" - BAR = "bar" - - -@dataclass(frozen=True, slots=True) -class Cursor: - """Zero-based cursor state on a :class:`Screen`. - - Attributes - ---------- - row : int - Zero-based row index in ``0..rows - 1``. - col : int - Zero-based column index in ``0..cols - 1``. - visible : bool - Whether the cursor is visible (``DECTCEM`` ``?25``). - shape : CursorShape - Visual cursor shape. - blinking : bool - Whether cursor blinking is active. - pending_wrap : bool - ``True`` when a glyph filled ``cols - 1`` under ``DECAWM`` and the - next printable character will wrap to the next line. - """ - - row: int = 0 - col: int = 0 - visible: bool = True - shape: CursorShape = CursorShape.BLOCK - blinking: bool = True - pending_wrap: bool = False - - -@dataclass(frozen=True, slots=True) -class ScrollRegion: - """Inclusive zero-based scroll margin bounds (``DECSTBM`` / ``DECSLRM``). - - Attributes - ---------- - top : int - Top margin row index (inclusive, ``0``-based). - bottom : int - Bottom margin row index (inclusive, ``0``-based). - left : int - Left margin column index (inclusive, ``0``-based). - right : int - Right margin column index (inclusive, ``0``-based). - """ - - top: int - bottom: int - left: int - right: int - - -@dataclass(frozen=True, slots=True) -class Cell: - r"""Immutable view of a single terminal grid cell. - - Attributes - ---------- - text : str - Grapheme cluster string (``" "`` for narrow blanks, ``""`` for - :attr:`WidthRole.SPACER_TAIL` and :attr:`WidthRole.SPACER_HEAD`). - style : Style - Unpacked SGR rendition attributes. - width_role : WidthRole - Column occupancy role (narrow, wide lead, or spacer). - hyperlink : Hyperlink | None - Active ``OSC 8`` hyperlink, when present. - protected : bool - ``DECSCA`` protection attribute respected by ``DECSED`` / ``DECSEL``. - - Examples - -------- - >>> term = Terminal(rows=1, cols=8) - >>> term.feed("\x1b[1;32m日\x1b[0mok".encode()) - >>> snap = term.committed - >>> snap[0, 0].text, snap[0, 0].width, snap[0, 0].style.bold - ('日', 2, True) - >>> snap[0, 1].width_role.name, snap[0, 1].width - ('SPACER_TAIL', 0) - """ - - text: str = " " - style: Style = DEFAULT_STYLE - width_role: WidthRole = WidthRole.NARROW - hyperlink: Hyperlink | None = None - protected: bool = False - - @property - def width(self) -> int: - """Return column width (``2`` wide, ``0`` spacer, ``1`` narrow).""" - if self.width_role == WidthRole.WIDE: - return 2 - if self.width_role in (WidthRole.SPACER_TAIL, WidthRole.SPACER_HEAD): - return 0 - return 1 - - @property - def is_blank(self) -> bool: - """Return ``True`` when the cell holds an unstyled narrow space.""" - return ( - self.text == " " - and self.style == DEFAULT_STYLE - and self.width_role == WidthRole.NARROW - and self.hyperlink is None - ) - - -BLANK_CELL = Cell() - - -@dataclass(frozen=True, slots=True) -class RowRun: - r"""Contiguous run of identically styled cells within a :class:`RowView`. - - Attributes - ---------- - start_col : int - Inclusive zero-based start column. - end_col : int - Exclusive zero-based end column. - text : str - Rendered text across ``start_col..end_col`` (omitting spacer empty strings). - style : Style - Shared :class:`~libvt.style.Style` across the run. - hyperlink : Hyperlink | None - Shared ``OSC 8`` hyperlink across the run, if any. - - Examples - -------- - >>> term = Terminal(rows=1, cols=12) - >>> term.feed(b"\x1b[1;32mPASS\x1b[0m test") - >>> [(r.start_col, r.end_col, r.text, r.style.bold) for r in term.committed[0].runs] - [(0, 4, 'PASS', True), (4, 10, ' test', False)] - """ - - start_col: int - end_col: int - text: str - style: Style = DEFAULT_STYLE - hyperlink: Hyperlink | None = None - - -def _materialize_cell(row: RowLike, col: int) -> Cell: - ch = row.char_at(col) - word = row.attr_at(col) - if word == 0 and ch == " ": - return BLANK_CELL - ext = row.ext_at(col) - style = unpack_style(word, ext) - role = unpack_width_role(word) - hyperlink = ext.hyperlink if ext is not None else None - protected = bool(ext is not None and ext.protected) - return Cell( - text=ch, - style=style, - width_role=role, - hyperlink=hyperlink, - protected=protected, - ) - - -def _normalize_index(idx: int, length: int, *, axis: str) -> int: - norm = idx + length if idx < 0 else idx - if norm < 0 or norm >= length: - msg = f"{axis} index {idx} out of range for size {length}" - raise IndexError(msg) - return norm - - -def _slice_indices(s: slice, length: int) -> range: - start, stop, step = s.indices(length) - if step != 1: - msg = "grid slices only support step=1" - raise ValueError(msg) - return range(start, stop) - - -def _frozen_row_runs( - row: FrozenRow, - start_c: int, - limit: int, -) -> tuple[RowRun, ...]: - """Coalesce ``(style, hyperlink)`` spans on *row* in ``O(runs + exts)``.""" - if not row.runs and not row.exts and row.cells is None: - t_len = len(row.text) - if limit <= t_len: - txt = row.text[start_c:limit] - elif start_c >= t_len: - txt = " " * (limit - start_c) - else: - txt = row.text[start_c:t_len] + (" " * (limit - t_len)) - return ( - RowRun( - start_col=start_c, - end_col=limit, - text=txt, - style=DEFAULT_STYLE, - hyperlink=None, - ), - ) - - out: list[RowRun] = [] - runs = row.runs - exts = row.exts - r_len = len(runs) - e_len = len(exts) - r_idx = bisect.bisect_right(runs, start_c, key=_ITEM0) if r_len else 0 - e_idx = bisect.bisect_left(exts, start_c, key=_ITEM0) if e_len else 0 - - has_cur = False - run_start = start_c - cur_style = DEFAULT_STYLE - cur_link: Hyperlink | None = None - buf: list[str] = [] - pos = start_c - - while pos < limit: - if r_idx < r_len: - raw_r_end, word = runs[r_idx] - r_end = min(limit, raw_r_end) - else: - raw_r_end = limit + 1 - word = 0 - r_end = limit - - while e_idx < e_len and exts[e_idx][0] < pos: - e_idx += 1 - if e_idx >= e_len: - ext: _CellExt | None = None - e_end = limit - elif exts[e_idx][0] > pos: - ext = None - e_end = min(limit, exts[e_idx][0]) - else: - ext = exts[e_idx][1] - scan_c = pos + 1 - scan_i = e_idx + 1 - while ( - scan_c < r_end - and scan_i < e_len - and exts[scan_i][0] == scan_c - and exts[scan_i][1] == ext - ): - scan_c += 1 - scan_i += 1 - e_end = scan_c - e_idx = scan_i - - seg_end = min(r_end, e_end) - if seg_end == raw_r_end: - r_idx += 1 - - role_bits = raw_width_bits(word) - if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): - if not has_cur: - cur_style = unpack_style(word, ext) - cur_link = ext.hyperlink if ext is not None else None - run_start = pos - has_cur = True - pos = seg_end - continue - - if row.cells is not None: - c_len = len(row.cells) - if seg_end <= c_len: - seg_txt = "".join(row.cells[pos:seg_end]) - elif pos >= c_len: - seg_txt = " " * (seg_end - pos) - else: - seg_txt = "".join(row.cells[pos:c_len]) + (" " * (seg_end - c_len)) - else: - t_len = len(row.text) - if seg_end <= t_len: - seg_txt = row.text[pos:seg_end] - elif pos >= t_len: - seg_txt = " " * (seg_end - pos) - else: - seg_txt = row.text[pos:t_len] + (" " * (seg_end - t_len)) - - st = unpack_style(word, ext) - lnk = ext.hyperlink if ext is not None else None - if not has_cur: - run_start = pos - cur_style = st - cur_link = lnk - buf = [seg_txt] - has_cur = True - elif st != cur_style or lnk != cur_link: - out.append( - RowRun( - start_col=run_start, - end_col=pos, - text="".join(buf), - style=cur_style, - hyperlink=cur_link, - ), - ) - run_start = pos - cur_style = st - cur_link = lnk - buf = [seg_txt] - else: - buf.append(seg_txt) - pos = seg_end - - out.append( - RowRun( - start_col=run_start, - end_col=limit, - text="".join(buf), - style=cur_style, - hyperlink=cur_link, - ), - ) - return tuple(out) - - -def _format_display_row(row: RowLike, start_c: int, stop_c: int) -> str: - """Format ``row[start_c:stop_c]`` padded and clipped to column width.""" - if stop_c <= start_c: - return "" - if isinstance(row, _Row): - if not row.has_wide: - r_cols = row.cols - if stop_c <= r_cols: - return row.slice_text(start_c, stop_c) - if start_c >= r_cols: - return " " * (stop_c - start_c) - return row.slice_text(start_c, r_cols) + (" " * (stop_c - r_cols)) - elif not row.runs and row.cells is None: - t_len = len(row.text) - if stop_c <= t_len: - return row.text[start_c:stop_c] - if start_c >= t_len: - return " " * (stop_c - start_c) - return row.text[start_c:t_len] + (" " * (stop_c - t_len)) - - limit = max(start_c, min(stop_c, row.used)) - parts: list[str] = [] - for c in range(start_c, limit): - role = raw_width_bits(row.attr_at(c)) - if role == int(WidthRole.SPACER_TAIL): - if c == start_c: - parts.append(" ") - elif role == int(WidthRole.SPACER_HEAD): - parts.append(" ") - elif role == int(WidthRole.WIDE): - parts.append(row.char_at(c) if c + 1 < stop_c else " ") - else: - parts.append(row.char_at(c)) - if stop_c > limit: - parts.append(" " * (stop_c - limit)) - return "".join(parts) - - -class RowView(collections.abc.Sequence[Cell]): - r"""Read-only sequence view over one live viewport or scrollback row. - - A whole live row follows its backing row's width. A slice retains its - selected columns and clips them to the live width. Frozen rows keep their - captured width. - - Examples - -------- - >>> term = Terminal(rows=2, cols=8) - >>> term.feed(b"long_line") - >>> row0 = term.committed[0] - >>> row0.text, row0.wrapped, len(row0) - ('long_lin', True, 8) - """ - - __slots__ = ("_col_range", "_row", "_row_idx", "_screen") - - def __init__( - self, - row: RowLike, - col_range: range | None = None, - *, - screen: Screen | None = None, - row_idx: int = -1, - ) -> None: - self._row = row - self._screen = screen - self._row_idx = row_idx - self._col_range = col_range - - def _current_row(self) -> RowLike: - if self._screen is not None and 0 <= self._row_idx < len(self._screen._rows): - return self._screen._rows[self._row_idx] - return self._row - - def _columns_for(self, row: RowLike) -> range: - cols = self._col_range - if cols is None: - return range(row.cols) - if isinstance(row, _Row) and cols.stop > row.cols: - return range(cols.start, row.cols, cols.step) - return cols - - @property - def columns(self) -> range: - """Return the source columns currently visible through this row.""" - return self._columns_for(self._current_row()) - - @property - def used(self) -> int: - """Return the number of visible columns through the last written cell.""" - row = self._current_row() - cols = self._columns_for(row) - return max(0, min(cols.stop, row.used) - cols.start) - - @property - def text_used(self) -> int: - """Return the visible text extent, excluding trailing background-only cells.""" - row = self._current_row() - cols = self._columns_for(row) - return max(0, min(cols.stop, row.text_used) - cols.start) - - @property - def full_row(self) -> RowView: - """Return the uncropped row with the same live or frozen backing.""" - if self._col_range is None: - return self - return RowView(self._current_row(), screen=self._screen, row_idx=self._row_idx) - - @property - def wrapped(self) -> bool: - """Return ``True`` when this row soft-wrapped onto the next line.""" - return self._current_row().wrapped - - @property - def text(self) -> str: - """Return right-trimmed rendered text for this row slice.""" - row = self._current_row() - cols = self._columns_for(row) - row_t_used = ( - row.text_used - if isinstance(row, _Row) - else (len(row.cells) if row.cells is not None else len(row.text)) - ) - if cols.start == 0 and cols.stop >= row_t_used: - return row.rstrip_text() - limit = min(cols.stop, row_t_used) - if limit <= cols.start: - return "" - if isinstance(row, _Row): - raw = row.slice_text(cols.start, limit) - else: - raw = "".join(row.char_at(c) for c in range(cols.start, limit)) - return raw.rstrip(" ") - - @property - def display_text(self) -> str: - """Return space-padded text spanning ``len(self)`` terminal columns.""" - row = self._current_row() - cols = self._columns_for(row) - return _format_display_row(row, cols.start, cols.stop) - - @property - def runs(self) -> tuple[RowRun, ...]: - """Return coalesced ``(style, hyperlink)`` spans up to ``used`` columns.""" - row = self._current_row() - cols = self._columns_for(row) - limit = min(cols.stop, row.used) - start_c = cols.start - if limit <= start_c: - return () - if isinstance(row, FrozenRow): - return _frozen_row_runs(row, start_c, limit) - out: list[RowRun] = [] - run_start = start_c - first_ext = row.ext_at(start_c) - cur_style = unpack_style(row.attr_at(start_c), first_ext) - cur_link = first_ext.hyperlink if first_ext is not None else None - buf: list[str] = [] - - for c in range(start_c, limit): - word = row.attr_at(c) - role_bits = raw_width_bits(word) - if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): - continue - ext = row.ext_at(c) - st = unpack_style(word, ext) - lnk = ext.hyperlink if ext is not None else None - ch = row.char_at(c) - if st != cur_style or lnk != cur_link: - out.append( - RowRun( - start_col=run_start, - end_col=c, - text="".join(buf), - style=cur_style, - hyperlink=cur_link, - ), - ) - run_start = c - cur_style = st - cur_link = lnk - buf = [ch] - else: - buf.append(ch) - - out.append( - RowRun( - start_col=run_start, - end_col=limit, - text="".join(buf), - style=cur_style, - hyperlink=cur_link, - ), - ) - return tuple(out) - - def __len__(self) -> int: - """Return column count in this view.""" - return len(self._columns_for(self._current_row())) - - @t.overload - def __getitem__(self, index: int) -> Cell: ... - - @t.overload - def __getitem__(self, index: slice) -> RowView: ... - - def __getitem__(self, index: int | slice) -> Cell | RowView: - """Index one :class:`Cell` or slice a sub-range :class:`RowView`.""" - row = self._current_row() - cols = self._columns_for(row) - if isinstance(index, slice): - sub = _slice_indices(index, len(cols)) - base = cols.start - return RowView( - row, - range(base + sub.start, base + sub.stop), - screen=self._screen, - row_idx=self._row_idx, - ) - norm = _normalize_index(index, len(cols), axis="col") - return _materialize_cell(row, cols.start + norm) - - def __eq__(self, other: object) -> bool: - """Compare two :class:`RowView` instances by wrapped state and cells.""" - if self is other: - return True - if not isinstance(other, RowView): - return NotImplemented - r1 = self._current_row() - r2 = other._current_row() - c1 = self._columns_for(r1) - c2 = other._columns_for(r2) - if len(c1) != len(c2): - return False - if r1 is r2 and c1 == c2: - return True - if c1 == c2 and c1.start == 0 and c1.step == 1: - f1 = r1.freeze() if isinstance(r1, _Row) else r1 - f2 = r2.freeze() if isinstance(r2, _Row) else r2 - if c1.stop >= max(f1.used, f2.used): - return _frozen_content_key(f1) == _frozen_content_key(f2) - if r1.wrapped != r2.wrapped: - return False - return all(a == b for a, b in zip(self, other, strict=True)) - - -def _frozen_content_key( - fr: FrozenRow, -) -> tuple[ - bool, - str, - tuple[tuple[int, int], ...], - tuple[tuple[int, _CellExt], ...], - tuple[str, ...] | None, -]: - return ( - fr.wrapped, - fr.text, - fr.runs, - fr.exts, - fr.cells, - ) - - -def _row_view_to_full_frozen(value: object) -> tuple[int, FrozenRow] | None: - if not isinstance(value, RowView): - return None - r = value._current_row() - fr = r.freeze() if isinstance(r, _Row) else r - cols = value._columns_for(r) - if cols.start == 0 and cols.step == 1 and len(cols) >= fr.used: - return len(cols), fr - return None - - -class _HistoryView(collections.abc.Sequence[RowView]): - """Lazy ``O(1)`` immutable sequence view over scrollback :class:`RowView` lines.""" - - __slots__ = ("_cols", "_data", "_range") - - def __init__( - self, - data: _FrozenHistory | None = None, - index_range: range | None = None, - *, - cols: int | None = None, - ) -> None: - eff = _EMPTY_FROZEN_HISTORY if data is None else data - self._data = eff - self._range = range(len(eff)) if index_range is None else index_range - self._cols = cols - - def _eff_cols(self, fr: FrozenRow) -> int: - if self._cols is None: - return fr.cols - return max(self._cols, fr.used) - - def _wrap_row(self, fr: FrozenRow) -> RowView: - return RowView(fr, range(self._eff_cols(fr))) - - def __len__(self) -> int: - """Return number of scrollback rows in this view.""" - return len(self._range) - - def __bool__(self) -> bool: - """Return ``True`` when at least one scrollback row is present.""" - return bool(self._range) - - @t.overload - def __getitem__(self, index: int) -> RowView: ... - - @t.overload - def __getitem__(self, index: slice) -> _HistoryView: ... - - def __getitem__(self, index: int | slice) -> RowView | _HistoryView: - """Index one :class:`RowView` in ``O(1)`` or slice a sub-view.""" - if isinstance(index, slice): - return _HistoryView(self._data, self._range[index], cols=self._cols) - if isinstance(index, bool) or not isinstance(index, int): - msg = f"history indices must be int or slice, got {type(index).__name__}" - raise TypeError(msg) - return self._wrap_row(self._data.at(self._range[index])) - - def __contains__(self, value: object) -> bool: - """Return ``True`` when *value* matches a scrollback :class:`RowView`.""" - if not isinstance(value, RowView): - return False - v_len = len(value) - if self._cols is not None and v_len < self._cols: - return False - full = _row_view_to_full_frozen(value) - r = self._range - if full is None: - at = self._data.at - return any( - self._eff_cols(fr := at(idx)) == v_len and self._wrap_row(fr) == value - for idx in r - ) - v_cols, target_fr = full - target_key = _frozen_content_key(target_fr) - if r.start == 0 and r.stop == len(self._data) and r.step == 1: - return any( - self._eff_cols(fr) == v_cols and _frozen_content_key(fr) == target_key - for fr in self._data - ) - at = self._data.at - return any( - self._eff_cols(fr := at(idx)) == v_cols - and _frozen_content_key(fr) == target_key - for idx in r - ) - - def count(self, value: object) -> int: - """Return count of scrollback rows equal to *value*.""" - if not isinstance(value, RowView): - return 0 - v_len = len(value) - if self._cols is not None and v_len < self._cols: - return 0 - full = _row_view_to_full_frozen(value) - at = self._data.at - if full is None: - return sum( - 1 - for idx in self._range - if self._eff_cols(fr := at(idx)) == v_len - and self._wrap_row(fr) == value - ) - v_cols, target_fr = full - target_key = _frozen_content_key(target_fr) - return sum( - 1 - for idx in self._range - if self._eff_cols(fr := at(idx)) == v_cols - and _frozen_content_key(fr) == target_key - ) - - def index( - self, - value: object, - start: int = 0, - stop: int = sys.maxsize, - ) -> int: - """Return first zero-based index of *value* in ``[start, stop)``.""" - if isinstance(value, RowView): - v_len = len(value) - if self._cols is None or v_len >= self._cols: - sub_indices = range(len(self._range))[start:stop] - full = _row_view_to_full_frozen(value) - at = self._data.at - if full is None: - for pos in sub_indices: - fr = at(self._range[pos]) - if self._eff_cols(fr) == v_len and self._wrap_row(fr) == value: - return pos - else: - v_cols, target_fr = full - target_key = _frozen_content_key(target_fr) - for pos in sub_indices: - fr = at(self._range[pos]) - if ( - self._eff_cols(fr) == v_cols - and _frozen_content_key(fr) == target_key - ): - return pos - msg = "RowView is not in history" - raise ValueError(msg) - - def __iter__(self) -> collections.abc.Iterator[RowView]: - """Yield :class:`RowView` items across this view.""" - r = self._range - if not r: - return - if r.start == 0 and r.stop == len(self._data) and r.step == 1: - for fr in self._data: - yield self._wrap_row(fr) - return - at = self._data.at - for idx in r: - yield self._wrap_row(at(idx)) - - def __reversed__(self) -> collections.abc.Iterator[RowView]: - """Yield :class:`RowView` items in reverse order.""" - at = self._data.at - for idx in reversed(self._range): - yield self._wrap_row(at(idx)) - - def __eq__(self, other: object) -> bool: - """Compare two :class:`_HistoryView` instances by view-width rows.""" - if self is other: - return True - if not isinstance(other, _HistoryView): - return NotImplemented - if len(self._range) != len(other._range): - return False - if not self._range: - return True - if ( - self._data is other._data - and self._range == other._range - and self._cols == other._cols - ): - return True - return all( - self._eff_cols(f1 := self._data.at(i)) - == other._eff_cols(f2 := other._data.at(j)) - and _frozen_content_key(f1) == _frozen_content_key(f2) - for i, j in zip(self._range, other._range, strict=True) - ) - - def __repr__(self) -> str: - """Return concise summary representation.""" - return f"HistoryView(len={len(self._range)})" - - -class RegionView(collections.abc.Sequence[RowView]): - r"""Read-only 2D rectangular slice view over ``(rows, cols)``. - - A live region follows the width of its retained rows. Regions from a - snapshot or its viewport use the geometry captured with the frame. - - Examples - -------- - >>> from libvt.testing import serialize_vt_snapshot - >>> term = Terminal(rows=3, cols=10) - >>> term.feed(b"header\r\n\x1b[1mitem 1\x1b[0m\r\nitem 2") - >>> region = term.committed[1:3, 0:6] - >>> print(serialize_vt_snapshot(region)) - size=6x2 region=True - ┌──────┐ - │item 1│ - │item 2│ - └──────┘ - styles: - r0[0..6]: bold - """ - - __slots__ = ("_col_range", "_live_rows", "_parent_cols", "_rows") - - def __init__( - self, - rows: collections.abc.Sequence[RowLike], - col_range: range, - *, - parent_cols: int | None = None, - live: bool = True, - ) -> None: - self._rows = tuple(rows) - self._live_rows = ( - tuple(row for row in self._rows if isinstance(row, _Row)) if live else () - ) - self._col_range = col_range - self._parent_cols = ( - max((row.cols for row in self._rows), default=col_range.stop) - if parent_cols is None - else parent_cols - ) - - def _source_width(self) -> int: - if self._live_rows: - return min(row.cols for row in self._live_rows) - return self._parent_cols - - @property - def columns(self) -> range: - """Return the selected column coordinates in the source grid.""" - columns = self._col_range - if self._live_rows and (width := self._source_width()) < columns.stop: - return range(columns.start, width, columns.step) - return columns - - @property - def rows(self) -> int: - """Return height of this region in rows.""" - return len(self._rows) - - @property - def cols(self) -> int: - """Return width of this region in columns.""" - return len(self.columns) - - @property - def lines(self) -> tuple[str, ...]: - """Return right-trimmed text for each row in the region.""" - return tuple(row.text for row in self) - - @property - def display_lines(self) -> tuple[str, ...]: - """Return space-padded text of width ``cols`` for each row in the region.""" - return tuple(row.display_text for row in self) - - @property - def text(self) -> str: - """Return newline-joined text with trailing empty rows omitted.""" - lines = list(self.lines) - while lines and lines[-1] == "": - lines.pop() - return "\n".join(lines) - - @property - def unwrapped_text(self) -> str: - r"""Return newline-joined text, unwrapping full-width soft-wrapped rows. - - Full-width row slices (such as ``snap[0:5]`` or - :meth:`~libvt.terminal.Snapshot.viewport`) join contiguous - ``row.wrapped`` rows without ``"\n"`` when their original right margin - is visible. The current frame determines - the slice width even when history contains rows sealed at a different - width. Column crops return :attr:`text`. - - Examples - -------- - >>> term = Terminal(rows=3, cols=8) - >>> term.feed(b"hello world\r\nok") - >>> snap = term.committed - >>> snap[0:2].unwrapped_text, snap[0:2, 0:4].unwrapped_text - ('hello world', 'hell\nrld') - """ - columns = self.columns - if ( - columns.start == 0 - and columns.step == 1 - and columns.stop >= self._source_width() - ): - return _unwrapped_text(self._rows, visible_cols=len(columns)) - return self.text - - def __iter__(self) -> collections.abc.Iterator[RowView]: - """Iterate over rows using the current rectangular extent.""" - columns = self.columns - return (RowView(row, columns) for row in self._rows) - - def __len__(self) -> int: - """Return number of rows in this region.""" - return len(self._rows) - - @t.overload - def __getitem__(self, key: int) -> RowView: ... - - @t.overload - def __getitem__(self, key: tuple[int, int]) -> Cell: ... - - @t.overload - def __getitem__( - self, - key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice], - ) -> RegionView: ... - - @t.overload - def __getitem__( - self, - key: tuple[slice | int, slice | int], - ) -> Cell | RegionView: ... - - def __getitem__( - self, - key: int | slice | tuple[slice | int, slice | int], - ) -> RowView | Cell | RegionView: - """Index a row, single ``(row, col)`` cell, or 2D region view.""" - return slice_grid( - self._rows, - self._source_width(), - key, - columns=self.columns, - live=bool(self._live_rows), - ) - - -def _row_groups( - rows: collections.abc.Sequence[RowLike], - *, - unwrap: bool, - visible_cols: int | None = None, -) -> collections.abc.Iterator[collections.abc.Sequence[RowLike]]: - start = 0 - for end, row in enumerate(rows, 1): - if ( - not unwrap - or not row.wrapped - or (visible_cols is not None and row.cols > visible_cols) - ): - yield rows[start:end] - start = end - if start < len(rows): - yield rows[start:] - - -def _unwrapped_rows( - group: collections.abc.Sequence[RowLike], *, include_styles: bool -) -> collections.abc.Iterator[tuple[RowLike, int]]: - end = len(group) - while end > 0: - last = group[end - 1] - used = last.used if include_styles else last.text_used - if used: - break - end -= 1 - - for index, row in enumerate(group[:end]): - padding = 0 - if index + 1 < end: - used = row.used if include_styles else row.text_used - # The high-water marks count the wide-wrap spacer at the right edge. - padding = max(0, row.cols - used) - yield row, padding - - -def _unwrapped_text( - rows: collections.abc.Sequence[RowLike], *, visible_cols: int | None = None -) -> str: - lines = ( - "".join( - row.rstrip_text() + " " * padding - for row, padding in _unwrapped_rows(group, include_styles=False) - ) - for group in _row_groups(rows, unwrap=True, visible_cols=visible_cols) - ) - return "\n".join(lines).rstrip("\n") - - -def format_rows_text( - rows: collections.abc.Sequence[RowLike], - *, - unwrap: bool = False, -) -> str: - r"""Format *rows* as newline-joined text omitting trailing blank lines. - - Parameters - ---------- - rows : collections.abc.Sequence[RowLike] - Viewport or scrollback rows to format. - unwrap : bool - When ``True``, join contiguous ``row.wrapped`` continuation rows onto - the same logical line without inserting ``"\n"``. - - Returns - ------- - str - Rendered text with trailing blank lines omitted. - - Examples - -------- - >>> term = Terminal(rows=2, cols=8) - >>> term.feed(b"hello world") - >>> term.screen.text, term.screen.unwrapped_text - ('hello wo\nrld', 'hello world') - """ - if unwrap: - return _unwrapped_text(rows) - lines = [r.rstrip_text() for r in rows] - while lines and lines[-1] == "": - lines.pop() - return "\n".join(lines) - - -def _grid_span(index: int | slice, size: int, *, axis: str) -> slice: - if isinstance(index, slice): - span = _slice_indices(index, size) - return slice(span.start, span.stop) - if isinstance(index, int): - at = _normalize_index(index, size, axis=axis) - return slice(at, at + 1) - msg = f"unsupported {axis} index {index!r}" - raise TypeError(msg) - - -def slice_grid( - rows: collections.abc.Sequence[RowLike], - cols: int, - key: int | slice | tuple[slice | int, slice | int], - *, - screen: Screen | None = None, - columns: range | None = None, - live: bool = False, -) -> RowView | Cell | RegionView: - """Index a grid or a rectangular view in its own coordinates.""" - height = len(rows) - if isinstance(key, int): - nr = _normalize_index(key, height, axis="row") - return RowView(rows[nr], columns, screen=screen, row_idx=nr) - visible = range(cols) if columns is None else columns - r_key, c_key = (key, slice(None)) if isinstance(key, slice) else key - if isinstance(r_key, int) and isinstance(c_key, int): - nr = _normalize_index(r_key, height, axis="row") - nc = _normalize_index(c_key, len(visible), axis="col") - return _materialize_cell(rows[nr], visible[nc]) - row_span = _grid_span(r_key, height, axis="row") - col_span = _grid_span(c_key, len(visible), axis="col") - return RegionView( - rows[row_span], - visible[col_span], - parent_cols=cols, - live=screen is not None or live, - ) + from libvt.graphics import GraphicsTracker, ImageMeta, ImagePlacement class Screen: @@ -1211,16 +158,6 @@ def _bind_counter(self, counter: _RowGenCounter) -> None: for r in self._rows: r.bind_counter(counter, stamp=False) - @property - def profile(self) -> Profile: - """Return the profile used to interpret cells on this screen.""" - return self._profile - - @property - def is_alt(self) -> bool: - """Return whether this grid belongs to the alternate screen.""" - return self._is_alt - @property def rows(self) -> int: """Return visible screen height in rows.""" @@ -1231,6 +168,16 @@ def cols(self) -> int: """Return screen width in columns.""" return self._cols + @property + def profile(self) -> Profile: + """Return :class:`~libvt.config.Profile` governing width and grid behavior.""" + return self._profile + + @property + def is_alt(self) -> bool: + """Return ``True`` when this screen is an alternate screen buffer.""" + return self._is_alt + @property def scrolled_total(self) -> int: """Return cumulative primary rows scrolled off the top margin.""" @@ -1303,8 +250,10 @@ def clear_history(self) -> None: self._gfx.clear_history(self._scrolled_total) def ensure_graphics(self) -> GraphicsTracker: - """Return (lazily creating) this screen's :class:`GraphicsTracker`.""" + """Lazily create and return this screen's graphics tracker.""" if self._gfx is None: + from libvt.graphics import GraphicsTracker + self._gfx = GraphicsTracker( max_images=self._max_images, max_placements=self._max_placements, @@ -1725,346 +674,6 @@ def push_scrollback_and_clear( for r in self._rows: r.reset_blank(self._cols, bce_word) - def _reflow_primary( - self, - *, - rows: int, - cols: int, - extra_pins: collections.abc.Sequence[tuple[int, int]] = (), - ) -> tuple[tuple[int, int], ...]: - hist_rows = list(self._history.freeze()) - hist_len = len(hist_rows) - old_first_abs = self._scrolled_total - hist_len - - last_active = self._cur_row - for r_idx in range(len(self._rows) - 1, self._cur_row, -1): - if self._rows[r_idx].used > 0 or self._rows[r_idx].wrapped: - last_active = r_idx - break - - total = hist_len + last_active + 1 - cur_abs_idx = hist_len + self._cur_row - eff_cur_col = self._cur_col + (1 if self._pending_wrap else 0) - - gfx_roots = self._gfx.root_placement_pins() if self._gfx is not None else [] - n_extra = len(extra_pins) - all_pins: list[tuple[int, int]] = list(extra_pins) - for _, g_abs, g_col in gfx_roots: - all_pins.append((g_abs, g_col)) - - mapped_out: list[tuple[int, int] | None] = [None] * len(all_pins) - pins_by_row: dict[int, list[tuple[int, int]]] = {} - for p_idx, (p_abs, p_col) in enumerate(all_pins): - rel_in = p_abs - old_first_abs - if 0 <= rel_in < total: - pins_by_row.setdefault(rel_in, []).append((p_idx, p_col)) - - new_all: list[RowLike] = [] - new_cur_abs = 0 - new_cur_col = 0 - new_pending_wrap = False - cursor_placed = False - viewport_start = 0 - - idx = 0 - while idx < total: - if idx < hist_len: - fr = hist_rows[idx] - if not fr.wrapped: - fr_t_cols = len(fr.cells) if fr.cells is not None else len(fr.text) - fr_used = ( - fr_t_cols - if (not fr.runs and not fr.exts) - else max( - fr_t_cols, - fr.runs[-1][0] if fr.runs else 0, - (fr.exts[-1][0] + 1) if fr.exts else 0, - ) - ) - if fr_used <= cols: - out_idx = len(new_all) - new_all.append(fr) - if pins_by_row: - row_ps = pins_by_row.get(idx) - if row_ps is not None: - for p_idx, p_col in row_ps: - mapped_out[p_idx] = ( - out_idx, - min(cols - 1, max(0, p_col)), - ) - idx += 1 - continue - - group_start = idx - if group_start == hist_len: - viewport_start = len(new_all) - while idx + 1 < total: - cur_src = ( - hist_rows[idx] if idx < hist_len else self._rows[idx - hist_len] - ) - if not cur_src.wrapped: - break - idx += 1 - group_end = idx - idx += 1 - - if group_start <= cur_abs_idx < group_end: - cur_r_src = ( - hist_rows[cur_abs_idx] - if cur_abs_idx < hist_len - else self._rows[cur_abs_idx - hist_len] - ) - cur_r_cols = cur_r_src.cols - if eff_cur_col >= cur_r_cols: - cur_abs_idx += 1 - eff_cur_col = 0 - - cells: list[tuple[str, int, int, _CellExt | None, int]] = [] - cell_pins: dict[int, list[tuple[int, int]]] = {} - carried_pins: list[int] = [] - after_group_pins: list[tuple[int, int]] = [] - cur_after_extra: int | None = None - carry_cur = False - - for r_i in range(group_start, group_end + 1): - src = hist_rows[r_i] if r_i < hist_len else self._rows[r_i - hist_len] - is_last = r_i == group_end - src_cols = src.cols - src_t_used = ( - src.text_used - if isinstance(src, _Row) - else (len(src.cells) if src.cells is not None else len(src.text)) - ) - row_limit = src_cols if not is_last else src_t_used - if r_i == cur_abs_idx and eff_cur_col >= row_limit: - cur_after_extra = eff_cur_col - row_limit - - row_ps = pins_by_row.get(r_i) - col_pins_map: dict[int, list[int]] | None = None - if row_ps is not None: - col_pins_map = {} - for p_idx, p_col in row_ps: - eff_pc = max(0, p_col) - if eff_pc >= row_limit: - if is_last: - after_group_pins.append((p_idx, eff_pc - row_limit)) - else: - carried_pins.append(p_idx) - else: - col_pins_map.setdefault(eff_pc, []).append(p_idx) - - for c_i in range(row_limit): - word = src.attr_at(c_i) - rb = raw_width_bits(word) - is_cur = r_i == cur_abs_idx and c_i == eff_cur_col - here_pins = ( - col_pins_map.get(c_i) if col_pins_map is not None else None - ) - if rb == int(WidthRole.SPACER_HEAD): - if is_cur: - carry_cur = True - if here_pins: - carried_pins.extend(here_pins) - continue - if rb == int(WidthRole.SPACER_TAIL): - if is_cur and cells: - p_ch, p_w, p_cw, p_ext, _ = cells[-1] - cells[-1] = (p_ch, p_w, p_cw, p_ext, 1) - if here_pins: - if cells: - prev_k = len(cells) - 1 - tgt = cell_pins.setdefault(prev_k, []) - for p_idx in here_pins: - tgt.append((p_idx, 1)) - else: - carried_pins.extend(here_pins) - continue - cw = 2 if rb == int(WidthRole.WIDE) else 1 - base_word = word & _PEN_BASE_MASK - cur_off = 0 if (is_cur or carry_cur) else -1 - carry_cur = False - cell_k = len(cells) - if carried_pins or here_pins: - tgt = cell_pins.setdefault(cell_k, []) - for p_idx in carried_pins: - tgt.append((p_idx, 0)) - carried_pins.clear() - if here_pins: - for p_idx in here_pins: - tgt.append((p_idx, 0)) - ch_val = src.char_at(c_i) - cells.append( - ( - ch_val, - base_word, - cw, - src.ext_at(c_i), - cur_off, - ) - ) - - if not cells: - empty_row = _Row(cols, gen_counter=self._gen_counter) - new_all.append(empty_row) - out_idx = len(new_all) - 1 - if group_start <= cur_abs_idx <= group_end and not cursor_placed: - extra = 0 if cur_after_extra is None else cur_after_extra - new_cur_abs = out_idx - new_cur_col = min(cols - 1, extra) - new_pending_wrap = False - cursor_placed = True - for p_idx in carried_pins: - mapped_out[p_idx] = (out_idx, 0) - for p_idx, p_extra in after_group_pins: - mapped_out[p_idx] = (out_idx, min(cols - 1, p_extra)) - continue - - cur_out = _Row(cols, gen_counter=self._gen_counter) - new_all.append(cur_out) - out_col = 0 - for cell_k, (ch, base_w, cw, ce, cur_off) in enumerate(cells): - eff_cw = cw - eff_ch = ch - if eff_cw == 2 and cols == 1: - eff_ch = "\ufffd" - eff_cw = 1 - - if out_col + eff_cw > cols: - if out_col < cols: - cur_out.write_spacer_head(out_col, 0, None) - cur_out.wrapped = True - cur_out = _Row(cols, gen_counter=self._gen_counter) - new_all.append(cur_out) - out_col = 0 - - out_idx = len(new_all) - 1 - if cur_off >= 0 and not cursor_placed: - new_cur_abs = out_idx - new_cur_col = min(cols - 1, out_col + cur_off) - new_pending_wrap = False - cursor_placed = True - - c_ps = cell_pins.get(cell_k) - if c_ps is not None: - for p_idx, p_off in c_ps: - mapped_out[p_idx] = ( - out_idx, - min(cols - 1, out_col + p_off), - ) - - if eff_cw == 2: - cur_out.write_wide(out_col, eff_ch, base_w, ce) - out_col += 2 - else: - cur_out.write_narrow(out_col, eff_ch, base_w, ce) - out_col += 1 - - last_out_idx = len(new_all) - 1 - for p_idx in carried_pins: - mapped_out[p_idx] = (last_out_idx, min(cols - 1, out_col)) - for p_idx, p_extra in after_group_pins: - mapped_out[p_idx] = ( - last_out_idx, - min(cols - 1, out_col + p_extra), - ) - - if (cur_after_extra is not None or carry_cur) and not cursor_placed: - extra = 0 if cur_after_extra is None else cur_after_extra - new_cur_abs = last_out_idx - if extra == 0 and out_col == cols: - new_cur_col = cols - 1 - new_pending_wrap = True - else: - new_cur_col = min(cols - 1, out_col + extra) - new_pending_wrap = False - cursor_placed = True - - if not new_all: - new_all.append(_Row(cols, gen_counter=self._gen_counter)) - - last_in_abs = old_first_abs + total - 1 - last_out_base = len(new_all) - 1 - for p_idx, (p_abs, p_col) in enumerate(all_pins): - if p_abs > last_in_abs: - mapped_out[p_idx] = ( - last_out_base + (p_abs - last_in_abs), - min(cols - 1, max(0, p_col)), - ) - - hist_cut = max(0, len(new_all) - rows) - # Keep existing bottom padding from pulling hard history lines into view. - if hist_cut < viewport_start: - trailing_blanks = len(self._rows) - last_active - 1 - hist_cut = min(viewport_start, hist_cut + trailing_blanks) - hist_cut = min(hist_cut, new_cur_abs) - - prev_scrolled = self._scrolled_total - prev_evicted = self._evicted_total - evicted_in_reflow = self._history.replace_all(new_all[:hist_cut]) - new_hist_len = len(self._history) - new_evicted = max( - prev_evicted + evicted_in_reflow, - prev_scrolled - new_hist_len, - ) - self._evicted_total = new_evicted - self._scrolled_total = new_evicted + new_hist_len - - viewport: list[_Row] = [ - ( - r_v.thaw(cols, gen_counter=self._gen_counter) - if isinstance(r_v, FrozenRow) - else r_v - ) - for r_v in new_all[hist_cut : hist_cut + rows] - ] - while len(viewport) < rows: - viewport.append(_Row(cols, gen_counter=self._gen_counter)) - for r_v in viewport: - r_v.bind_counter(self._gen_counter) - self._rows = viewport - self._cols = cols - self._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut)) - self._cur_col = max(0, min(cols - 1, new_cur_col)) - self._pending_wrap = new_pending_wrap - - if not all_pins: - if self._gfx is not None: - self._gfx.apply_reflow_pins( - (), - new_cols=cols, - min_retained_abs_row=self._evicted_total, - max_abs=self._scrolled_total + rows, - ) - return () - - final_pins: list[tuple[int, int]] = [] - new_first_abs = self._scrolled_total - hist_cut - for p_idx, (old_abs, old_col) in enumerate(all_pins): - m_pair = mapped_out[p_idx] - if m_pair is None: - if old_abs < old_first_abs: - mapped_abs = new_first_abs + (old_abs - old_first_abs) - else: - mapped_abs = old_abs - final_pins.append((mapped_abs, min(cols - 1, max(0, old_col)))) - else: - out_r, new_c = m_pair - final_pins.append((new_first_abs + out_r, new_c)) - - if self._gfx is not None: - remapped_gfx = [ - (gfx_idx, final_pins[n_extra + k][0], final_pins[n_extra + k][1]) - for k, (gfx_idx, _, _) in enumerate(gfx_roots) - ] - self._gfx.apply_reflow_pins( - remapped_gfx, - new_cols=cols, - min_retained_abs_row=self._evicted_total, - max_abs=self._scrolled_total + rows, - ) - - return tuple(final_pins[:n_extra]) - def _resize_with_pins( self, *, @@ -2084,7 +693,8 @@ def _resize_with_pins( self._on_mutate(True) if reflow and cols != old_cols: - remapped = self._reflow_primary( + remapped = reflow_primary_screen( + self, rows=rows, cols=cols, extra_pins=extra_pins, @@ -2278,19 +888,16 @@ def blit( cols_range = source.columns src_col_base = cols_range.start src_cols = len(cols_range) + elif isinstance(source, Snapshot): + src_rows = source._rows + src_col_base = 0 + src_cols = source._cols else: - from libvt.terminal import Snapshot as _Snapshot - - if isinstance(source, _Snapshot): - src_rows = source._rows - src_col_base = 0 - src_cols = source._cols - else: - msg = ( - "source must be Snapshot, Screen, or RegionView, got " - f"{type(source).__name__}" - ) - raise TypeError(msg) + msg = ( + "source must be Snapshot, Screen, or RegionView, got " + f"{type(source).__name__}" + ) + raise TypeError(msg) src_h = len(src_rows) dst_h = len(self._rows) @@ -2578,8 +1185,6 @@ def snapshot( >>> snap.lines, (snap.cursor.row, snap.cursor.col) (('ready', ''), (0, 5)) """ - from libvt.terminal import _make_snapshot - eff_cursor = self.cursor if cursor is None else cursor eff_modes = frozenset(modes) eff_app = ( diff --git a/src/libvt/snapshot.py b/src/libvt/snapshot.py new file mode 100644 index 00000000..aa63e15f --- /dev/null +++ b/src/libvt/snapshot.py @@ -0,0 +1,1050 @@ +"""Immutable terminal snapshots, incremental sync watermarks, and deltas.""" + +from __future__ import annotations + +import collections.abc +import enum +import types +import typing as t +from dataclasses import dataclass + +from libvt._grid import ( + _EMPTY_FROZEN_HISTORY, + FrozenRow, + _FrozenHistory, + _Row, + raw_width_bits, +) +from libvt._ucd import WidthRole +from libvt.config import DEFAULT_POLICY, DEFAULT_PROFILE, Charset, Policy, Profile +from libvt.events import PromptZone +from libvt.format import _DEFAULT_VT_PEN, Formatter, OutputFormat, _VtPen +from libvt.modes import Mode +from libvt.status import ProgramStatus +from libvt.style import DEFAULT_APPEARANCE, DEFAULT_STYLE, Appearance, Style +from libvt.views import ( + Cell, + Cursor, + RegionView, + RowView, + ScrollRegion, + _format_display_row, + _HistoryView, + format_rows_text, + slice_grid, +) + +if t.TYPE_CHECKING: + from libvt.graphics import ImageMeta, ImagePlacement + +#: Buffer view selector for :meth:`~libvt.terminal.Terminal.sync_token` and deltas. +type SyncView = t.Literal["working", "committed"] + + +class ResyncReason(enum.StrEnum): + """Reason :meth:`~libvt.terminal.Terminal.changes_since` emitted a full resync.""" + + #: Incremental delta; cached consumer state remains valid. + NONE = "none" + #: No prior :class:`SyncToken` was supplied (`token=None`). + INITIAL = "initial" + #: Token belonged to another terminal or a different ``view``. + TERMINAL_MISMATCH = "terminal_mismatch" + #: Terminal resized, reset, switched screens, or rewrote retained history. + EPOCH_CHANGED = "epoch_changed" + #: Scrollback evicted rows older than the caller's previous watermark. + HISTORY_EVICTED = "history_evicted" + + +@dataclass(frozen=True, slots=True) +class _SyncState: + terminal_id: int + view: SyncView + epoch: int + revision: int + scrolled_total: int + evicted_total: int + history_clear_at: int + history_clear_seq: int + cursor: Cursor + modes: frozenset[Mode] + title: str + cwd: str + cwd_uri: str = "" + aux_revision: int = 0 + graphics_revision: int = 0 + appearance_revision: int = 0 + + +def _make_sync_token(state: _SyncState) -> SyncToken: + tok = object.__new__(SyncToken) + object.__setattr__(tok, "_state", state) + return tok + + +class SyncToken: + r"""Opaque per-:class:`~libvt.terminal.Terminal` watermark for incremental sync. + + Compare tokens with ``==`` and store them in sets or dictionaries via + :func:`hash`; obtain instances from + :meth:`~libvt.terminal.Terminal.sync_token` or :attr:`ScreenDelta.token`. + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(rows=2, cols=12) + >>> tok0 = term.sync_token() + >>> term.feed(b"status: ok") + >>> delta = term.changes_since(tok0) + >>> delta.dirty_rows, delta.snapshot.lines + ((0,), ('status: ok', '')) + """ + + __slots__ = ("_state",) + _state: _SyncState + + def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn: + """Disallow direct construction; use ``Terminal.sync_token()``.""" + msg = "SyncToken cannot be instantiated directly; call Terminal.sync_token()" + raise TypeError(msg) + + def __setattr__(self, name: str, value: object) -> t.NoReturn: + """Disallow attribute mutation on immutable tokens.""" + msg = f"cannot assign to attribute {name!r} on immutable SyncToken" + raise AttributeError(msg) + + def __delattr__(self, name: str) -> t.NoReturn: + """Disallow attribute deletion on immutable tokens.""" + msg = f"cannot delete attribute {name!r} on immutable SyncToken" + raise AttributeError(msg) + + def __eq__(self, other: object) -> bool: + """Return ``True`` when *other* captures the identical watermark state.""" + if self is other: + return True + if not isinstance(other, SyncToken): + return NotImplemented + return self._state == other._state + + def __hash__(self) -> int: + """Return hash of the captured watermark state.""" + return hash(self._state) + + def __repr__(self) -> str: + """Return compact opaque representation.""" + st = self._state + return f"SyncToken(view={st.view!r}, epoch={st.epoch}, revision={st.revision})" + + def __copy__(self) -> SyncToken: + """Return ``self`` (immutable value).""" + return self + + def __deepcopy__(self, memo: dict[int, object]) -> SyncToken: + """Return ``self`` (immutable value).""" + return self + + def __reduce__( + self, + ) -> tuple[collections.abc.Callable[[_SyncState], SyncToken], tuple[_SyncState]]: + """Serialize token state for :mod:`pickle`.""" + return (_make_sync_token, (self._state,)) + + +@dataclass(frozen=True, slots=True) +class ScreenDelta: + """Multi-consumer incremental update from ``Terminal.changes_since``. + + Attributes + ---------- + token : SyncToken + New watermark representing *snapshot*. + from_token : SyncToken | None + Previous watermark supplied by the caller. + resync_reason : ResyncReason + ``ResyncReason.NONE`` for an incremental delta, or the reason a full + resynchronization was required. + viewport_scroll_up : int + Count of rows the primary viewport scrolled up into history since + *from_token* (``0`` on full resync or non-history scroll). + dirty_rows : tuple[int, ...] + Sorted zero-based viewport row indices modified after shifting the + previous viewport upward by :attr:`viewport_scroll_up`. + new_history : collections.abc.Sequence[RowView] + Newly sealed scrollback rows appended since *from_token*, ordered + oldest to newest. + history_evicted : int + Count of oldest scrollback rows evicted by scrollback capacity since + *from_token* when :attr:`history_cleared` is ``False``. + history_cleared : bool + ``True`` when ``ED 3`` cleared scrollback since *from_token*. + cursor_changed : bool + ``True`` when cursor position, visibility, shape, or ``pending_wrap`` + changed. + modes_changed : bool + ``True`` when enabled ANSI/DEC modes changed. + metadata_changed : bool + ``True`` when ``title`` or ``cwd`` changed. + graphics_changed : bool + ``True`` when ``SIXEL`` or Kitty placements mutated. + appearance_changed : bool + ``True`` when :attr:`Snapshot.appearance` (theme scheme, default RGBs, + ``OSC 4`` palette overrides, or ``?5`` reverse video) changed. + snapshot : Snapshot + Immutable target :class:`Snapshot` corresponding to :attr:`token`. + """ + + token: SyncToken + from_token: SyncToken | None + resync_reason: ResyncReason + viewport_scroll_up: int + dirty_rows: tuple[int, ...] + new_history: collections.abc.Sequence[RowView] + history_evicted: int + history_cleared: bool + cursor_changed: bool + modes_changed: bool + metadata_changed: bool + graphics_changed: bool + snapshot: Snapshot + appearance_changed: bool = False + + @property + def full_resync(self) -> bool: + """Return ``True`` when the consumer must replace cached state.""" + return self.resync_reason is not ResyncReason.NONE + + @property + def has_changes(self) -> bool: + """Return ``True`` when any grid, history, cursor, mode, or metadata changed.""" + return ( + self.full_resync + or self.viewport_scroll_up > 0 + or bool(self.dirty_rows) + or bool(self.new_history) + or self.history_evicted > 0 + or self.history_cleared + or self.cursor_changed + or self.modes_changed + or self.metadata_changed + or self.graphics_changed + or self.appearance_changed + ) + + def apply_lines(self, history: list[str], viewport: list[str]) -> None: + r"""Apply this delta in place to mutable *history* and *viewport* line lists. + + Parameters + ---------- + history : list[str] + Cached scrollback text lines maintained by the consumer. + viewport : list[str] + Cached visible-viewport text lines maintained by the consumer. + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(rows=2, cols=10) + >>> hist, view = [], [] + >>> d0 = term.changes_since(None) + >>> d0.apply_lines(hist, view) + >>> term.feed(b"row 1\r\nrow 2\r\nrow 3") + >>> term.changes_since(d0.token).apply_lines(hist, view) + >>> hist, view + (['row 1'], ['row 2', 'row 3']) + """ + if self.full_resync or len(viewport) != self.snapshot.rows: + history[:] = [r.text for r in self.snapshot.history] + viewport[:] = list(self.snapshot.lines) + return + if self.history_cleared: + history.clear() + elif self.history_evicted > 0: + del history[: self.history_evicted] + if self.new_history: + history.extend(r.text for r in self.new_history) + if self.viewport_scroll_up > 0: + shift = min(len(viewport), self.viewport_scroll_up) + del viewport[:shift] + viewport.extend([""] * shift) + for r_idx in self.dirty_rows: + viewport[r_idx] = self.snapshot[r_idx].text + + def apply_rows(self, history: list[RowView], viewport: list[RowView]) -> None: + """Apply this delta in place to mutable *history* and *viewport* row views. + + Parameters + ---------- + history : list[RowView] + Cached scrollback :class:`~libvt.views.RowView` entries. + viewport : list[RowView] + Cached visible :class:`~libvt.views.RowView` entries. + """ + if self.full_resync or len(viewport) != self.snapshot.rows: + history[:] = list(self.snapshot.history) + viewport[:] = [self.snapshot[r] for r in range(self.snapshot.rows)] + return + if self.history_cleared: + history.clear() + elif self.history_evicted > 0: + del history[: self.history_evicted] + if self.new_history: + history.extend(self.new_history) + if self.viewport_scroll_up > 0: + shift = min(len(viewport), self.viewport_scroll_up) + del viewport[:shift] + base = len(viewport) + viewport.extend([self.snapshot[base + i] for i in range(shift)]) + for r_idx in self.dirty_rows: + viewport[r_idx] = self.snapshot[r_idx] + + +@dataclass(frozen=True, slots=True) +class _SavedCursor: + """Internal ``DECSC`` per-screen saved cursor and charset state. + + Attributes + ---------- + row : int + Saved zero-based row. + col : int + Saved zero-based column. + pending_wrap : bool + Saved pending-wrap state. + style : Style + Saved SGR pen. + decom : bool + Saved ``DECOM`` origin-mode flag. + g_sets : tuple[Charset, Charset, Charset, Charset] + Saved ``G0``..``G3`` character-set designations. + gl : int + Saved active locking-shift slot index (``0..3``). + single_shift : int | None + Saved pending single-shift slot (``2`` for ``SS2``, ``3`` for ``SS3``). + protected : bool + Saved ``DECSCA`` character-protection pen attribute. + """ + + row: int = 0 + col: int = 0 + pending_wrap: bool = False + style: Style = DEFAULT_STYLE + decom: bool = False + g_sets: tuple[Charset, Charset, Charset, Charset] = ("B", "B", "B", "B") + gl: int = 0 + single_shift: int | None = None + protected: bool = False + + +class _CursorDict(t.TypedDict): + row: int + col: int + visible: bool + shape: str + blinking: bool + pending_wrap: bool + + +class _AppearanceDict(t.TypedDict): + scheme: str + fg_rgb: list[int] + bg_rgb: list[int] + cursor_rgb: list[int] + palette_overrides: dict[str, list[int]] + reverse_video: bool + + +class _ProgramStatusDict(t.TypedDict): + state: str + id: str + progress: int | None + kind: str | None + app: str | None + effective_app: str | None + title: str | None + msg: str | None + + +class _PlacementDict(t.TypedDict): + protocol: str + image_id: int + placement_id: int + abs_row: int + viewport_row: int | None + col: int + rows: int + cols: int + z_index: int + virtual: bool + + +class SnapshotDict(t.TypedDict): + """Typed JSON-compatible dictionary returned by :meth:`Snapshot.to_dict`.""" + + rows: int + cols: int + scrolled_total: int + evicted_total: int + lines: list[str] + history_lines: list[str] + cursor: _CursorDict + title: str + cwd: str + cwd_uri: str + active_is_alt: bool + appearance: _AppearanceDict + modes: list[str] + program_status: _ProgramStatusDict | None + placements: list[_PlacementDict] + + +def _make_snapshot( + *, + rows: tuple[_Row, ...], + history: _FrozenHistory | collections.abc.Sequence[FrozenRow] = ( + _EMPTY_FROZEN_HISTORY + ), + cols: int, + cursor: Cursor, + scroll_region: ScrollRegion, + title: str, + cwd: str, + cwd_uri: str = "", + modes: frozenset[Mode], + active_is_alt: bool, + prompt_zones: tuple[PromptZone, ...], + program_status: ProgramStatus | None, + program_statuses: collections.abc.Mapping[str, ProgramStatus], + generation: int, + appearance: Appearance = DEFAULT_APPEARANCE, + images: collections.abc.Mapping[int, ImageMeta] | None = None, + placements: tuple[ImagePlacement, ...] = (), + scrolled_total: int | None = None, + evicted_total: int | None = None, + profile: Profile = DEFAULT_PROFILE, + pen: _VtPen = _DEFAULT_VT_PEN, +) -> Snapshot: + snap = object.__new__(Snapshot) + object.__setattr__(snap, "_frozen", False) + snap._rows = rows + hist_obj = _FrozenHistory.from_sequence(history) + snap._history = hist_obj + snap._cols = cols + snap._profile = profile + snap._scroll_region = scroll_region + snap._vt_pen = pen + eff_scrolled = ( + (0 if active_is_alt else len(hist_obj)) + if scrolled_total is None + else scrolled_total + ) + snap._scrolled_total = eff_scrolled + snap._evicted_total = ( + (0 if active_is_alt else max(0, eff_scrolled - len(hist_obj))) + if evicted_total is None + else evicted_total + ) + snap._unwrapped_text_cache = None + snap.cursor = cursor + snap.title = title + snap.cwd = cwd + snap.cwd_uri = cwd_uri + snap.modes = modes + snap.active_is_alt = active_is_alt + snap.prompt_zones = prompt_zones + snap.program_status = program_status + snap.program_statuses = types.MappingProxyType(dict(program_statuses)) + snap.generation = generation + snap.appearance = appearance + snap.images = types.MappingProxyType(dict(images) if images is not None else {}) + snap.placements = placements + object.__setattr__(snap, "_frozen", True) + return snap + + +class Snapshot: + r"""Immutable point-in-time capture of terminal screen, history, and metadata. + + Obtain instances via :attr:`~libvt.terminal.Terminal.committed` (tear-free + across ``?2026`` synchronized frames) or + :meth:`~libvt.terminal.Terminal.snapshot` (immediate working buffer). Once + captured, a ``Snapshot`` never mutates when later bytes arrive on the + :class:`~libvt.terminal.Terminal` and can be shared across threads without + locking. + + Index ``snap[row]`` for a :class:`~libvt.views.RowView`, ``snap[row, col]`` + for an immutable :class:`~libvt.views.Cell`, or ``snap[r0:r1, c0:c1]`` for + a rectangular :class:`~libvt.views.RegionView`. Render a visual grid box + with :func:`~libvt.testing.format_screen_box` or include header metadata and + ``SGR`` spans with :func:`~libvt.testing.serialize_vt_snapshot`. + + Attributes + ---------- + cursor : Cursor + Zero-based cursor position, shape, visibility, and ``pending_wrap``. + title : str + Window title set via ``OSC 0`` / ``OSC 2``. + cwd : str + Local working directory accepted under ``Policy.osc7_hosts``. + cwd_uri : str + Raw ``OSC 7`` / ``OSC 9;9`` working directory URI. + modes : frozenset[Mode] + Enabled ANSI and DEC private modes. + active_is_alt : bool + ``True`` when the alternate screen buffer is active. + prompt_zones : tuple[PromptZone, ...] + Recorded primary-screen ``OSC 133`` semantic prompt zones (empty when + :attr:`active_is_alt` is ``True``). + program_status : ProgramStatus | None + Highest-urgency active ``OSC 7501`` / ``OSC 9;4`` status record. + program_statuses : collections.abc.Mapping[str, ProgramStatus] + Read-only mapping of active ``OSC 7501`` task records keyed by ``id``. + generation : int + Terminal mutation generation when this snapshot was captured. + appearance : Appearance + Committed theme scheme, default RGBs, palette overrides, and ``?5`` + reverse-video state. + images : collections.abc.Mapping[int, ImageMeta] + Read-only mapping of stored ``SIXEL`` / Kitty + :class:`~libvt.graphics.ImageMeta` items. + placements : tuple[ImagePlacement, ...] + Immutable active + scrollback :class:`~libvt.graphics.ImagePlacement` + records. + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> from libvt.testing import serialize_vt_snapshot + >>> term = Terminal(rows=2, cols=14) + >>> term.feed(b"\x1b[1;32mREADY\x1b[0m api\r\n\x1b[7m> worker\x1b[0m") + >>> snap = term.committed + >>> print(serialize_vt_snapshot(snap)) + size=14x2 cursor=(1,8,vis=True) alt=False modes=[] + ┌──────────────┐ + │READY api │ + │> worker │ + └──────────────┘ + styles: + r0[0..5]: bold fg=green + r1[0..8]: reverse + >>> snap[0, 0].text, snap[0, 0].style.bold, snap[1, 0].style.reverse + ('R', True, True) + """ + + __slots__ = ( + "_cols", + "_evicted_total", + "_frozen", + "_history", + "_profile", + "_rows", + "_scroll_region", + "_scrolled_total", + "_unwrapped_text_cache", + "_vt_pen", + "active_is_alt", + "appearance", + "cursor", + "cwd", + "cwd_uri", + "generation", + "images", + "modes", + "placements", + "program_status", + "program_statuses", + "prompt_zones", + "title", + ) + + _cols: int + _evicted_total: int + _frozen: bool + _history: _FrozenHistory + _profile: Profile + _rows: tuple[_Row, ...] + _scroll_region: ScrollRegion + _scrolled_total: int + _unwrapped_text_cache: str | None + _vt_pen: _VtPen + active_is_alt: bool + appearance: Appearance + cursor: Cursor + cwd: str + cwd_uri: str + generation: int + images: collections.abc.Mapping[int, ImageMeta] + modes: frozenset[Mode] + placements: tuple[ImagePlacement, ...] + program_status: ProgramStatus | None + program_statuses: collections.abc.Mapping[str, ProgramStatus] + prompt_zones: tuple[PromptZone, ...] + title: str + + def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn: + """Disallow direct construction; use ``Terminal.snapshot()``.""" + msg = "Snapshot cannot be instantiated directly; call Terminal.snapshot()" + raise TypeError(msg) + + def __setattr__(self, name: str, value: object) -> None: + """Reject attribute mutation once snapshot initialization completes.""" + if getattr(self, "_frozen", False): + msg = f"Snapshot is immutable; cannot assign {name!r}" + raise AttributeError(msg) + object.__setattr__(self, name, value) + + @property + def profile(self) -> Profile: + """Return the profile captured with this frame.""" + return self._profile + + @property + def rows(self) -> int: + """Return snapshot height in rows. + + Examples + -------- + >>> Terminal(rows=3, cols=10).committed.rows + 3 + """ + return len(self._rows) + + @property + def cols(self) -> int: + """Return snapshot width in columns. + + Examples + -------- + >>> Terminal(rows=3, cols=10).committed.cols + 10 + """ + return self._cols + + @property + def scrolled_total(self) -> int: + r"""Return monotonic count of rows scrolled off the active screen's top. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"a\r\nb\r\nc") + >>> term.committed.scrolled_total + 1 + """ + return self._scrolled_total + + @property + def evicted_total(self) -> int: + r"""Return count of scrollback rows evicted from the active screen. + + Examples + -------- + >>> term = Terminal(rows=1, cols=8, scrollback=1) + >>> term.feed(b"a\r\nb\r\nc") + >>> term.committed.evicted_total + 1 + """ + return self._evicted_total + + def viewport_row(self, abs_row: int) -> int | None: + r"""Return zero-based viewport row for *abs_row*, or ``None``. + + Parameters + ---------- + abs_row : int + Monotonic absolute row coordinate (e.g. + :attr:`~libvt.events.PromptZone.abs_row` or + :attr:`~libvt.graphics.ImagePlacement.abs_row`). + + Returns + ------- + int | None + ``0 <= row < rows`` when *abs_row* is visible in this snapshot's + active viewport, else ``None``. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"r0\r\nr1\r\nr2") + >>> snap = term.committed + >>> snap.viewport_row(0), snap.viewport_row(1), snap.viewport_row(2) + (None, 0, 1) + """ + if isinstance(abs_row, bool) or not isinstance(abs_row, int): + msg = f"abs_row must be int, got {type(abs_row).__name__}" + raise TypeError(msg) + rel = abs_row - self._scrolled_total + if 0 <= rel < len(self._rows): + return rel + return None + + def at_abs(self, abs_row: int) -> RowView: + r"""Return :class:`~libvt.views.RowView` at *abs_row* in history or viewport. + + Parameters + ---------- + abs_row : int + Monotonic absolute row coordinate. + + Returns + ------- + RowView + Immutable view of the row from scrollback or the active viewport. + + Raises + ------ + IndexError + When *abs_row* has been evicted from history or is out of range. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"hist\r\nvis1\r\nvis2") + >>> snap = term.committed + >>> snap.at_abs(0).text, snap.at_abs(2).text + ('hist', 'vis2') + """ + if isinstance(abs_row, bool) or not isinstance(abs_row, int): + msg = f"abs_row must be int, got {type(abs_row).__name__}" + raise TypeError(msg) + if self.active_is_alt: + if 0 <= abs_row < len(self._rows): + return RowView(self._rows[abs_row]) + msg = f"abs_row {abs_row} out of range for alternate screen" + raise IndexError(msg) + first_abs = self._scrolled_total - len(self._history) + if abs_row < first_abs: + msg = f"abs_row {abs_row} was evicted (earliest retained is {first_abs})" + raise IndexError(msg) + if abs_row < self._scrolled_total: + fr = self._history.at(abs_row - first_abs) + return RowView(fr, range(max(self._cols, fr.used))) + rel = abs_row - self._scrolled_total + if rel < len(self._rows): + return RowView(self._rows[rel]) + msg = f"abs_row {abs_row} out of range" + raise IndexError(msg) + + @property + def history(self) -> collections.abc.Sequence[RowView]: + r"""Return ``O(1)`` immutable :class:`RowView` sequence over scrollback rows. + + Examples + -------- + >>> term = Terminal(rows=1, cols=10) + >>> term.feed(b"first\r\nsecond") + >>> [row.text for row in term.committed.history] + ['first'] + """ + return _HistoryView(self._history, cols=self._cols) + + def viewport(self, offset: int = 0) -> RegionView: + r"""Return a ``(rows, cols)`` :class:`~libvt.views.RegionView` at *offset*. + + Parameters + ---------- + offset : int + Zero-based upward scroll offset in terminal rows. ``0`` returns the + captured active viewport; positive values scroll into retained + primary history (clamped to ``len(history)``). Alternate-screen + snapshots (:attr:`~libvt.terminal.Snapshot.active_is_alt` is + ``True``) always return their alternate viewport without blending + primary scrollback. + + Returns + ------- + RegionView + Immutable rectangular view with height + :attr:`~libvt.terminal.Snapshot.rows` and width + :attr:`~libvt.terminal.Snapshot.cols`. + + Raises + ------ + TypeError + If *offset* is not an ``int`` (or is a ``bool``). + ValueError + If *offset* is negative. + + Examples + -------- + >>> from libvt.testing import serialize_vt_snapshot + >>> term = Terminal(rows=2, cols=10) + >>> term.feed(b"line 1\r\nline 2\r\nline 3") + >>> snap = term.committed + >>> print(serialize_vt_snapshot(snap.viewport(offset=1))) + size=10x2 region=True + ┌──────────┐ + │line 1 │ + │line 2 │ + └──────────┘ + """ + if isinstance(offset, bool) or not isinstance(offset, int): + msg = f"offset must be int, got {type(offset).__name__}" + raise TypeError(msg) + if offset < 0: + msg = f"offset must be >= 0, got {offset}" + raise ValueError(msg) + cols = self._cols + if self.active_is_alt or offset == 0 or not self._history: + return RegionView(self._rows, range(cols), parent_cols=cols, live=False) + h_len = len(self._history) + v_rows = len(self._rows) + eff_offset = min(offset, h_len) + win_start = h_len - eff_offset + win_stop = win_start + v_rows + out_rows: list[_Row | FrozenRow] = [] + for idx in range(win_start, min(win_stop, h_len)): + fr = self._history.at(idx) + if fr.used > cols or ( + 0 < fr.cols < cols + and fr.runs + and raw_width_bits(fr.attr_at(fr.cols - 1)) + == int(WidthRole.SPACER_HEAD) + ): + out_rows.append(fr.thaw(cols)) + else: + out_rows.append(fr) + if win_stop > h_len: + out_rows.extend(self._rows[: win_stop - h_len]) + return RegionView(out_rows, range(cols), parent_cols=cols, live=False) + + @property + def lines(self) -> tuple[str, ...]: + r"""Return visible row text with unwritten trailing blank cells omitted. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"ok") + >>> term.committed.lines + ('ok', '') + """ + return tuple(r.rstrip_text() for r in self._rows) + + @property + def display_lines(self) -> tuple[str, ...]: + r"""Return space-padded text of width ``cols`` for every visible row. + + Examples + -------- + >>> term = Terminal(rows=2, cols=6) + >>> term.feed(b"ok") + >>> term.committed.display_lines + ('ok ', ' ') + """ + cols = self._cols + return tuple(_format_display_row(r, 0, cols) for r in self._rows) + + @property + def text(self) -> str: + r"""Return visible snapshot text with trailing blank rows omitted. + + Examples + -------- + >>> term = Terminal(rows=3, cols=8) + >>> term.feed(b"top\r\nnext") + >>> term.committed.text + 'top\nnext' + """ + return format_rows_text(self._rows) + + @property + def unwrapped_text(self) -> str: + r"""Return visible snapshot text with soft-wrapped rows joined. + + Contiguous ``row.wrapped`` rows join without ``"\n"`` while hard + linebreaks stay ``"\n"`` and trailing blank rows are omitted. + + Examples + -------- + >>> term = Terminal(rows=3, cols=8) + >>> term.feed(b"hello world\r\nok") + >>> term.committed.unwrapped_text + 'hello world\nok' + """ + cached = self._unwrapped_text_cache + if cached is None: + cached = format_rows_text(self._rows, unwrap=True) + object.__setattr__(self, "_unwrapped_text_cache", cached) + return cached + + @t.overload + def __getitem__(self, key: int) -> RowView: ... + + @t.overload + def __getitem__(self, key: tuple[int, int]) -> Cell: ... + + @t.overload + def __getitem__( + self, + key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice], + ) -> RegionView: ... + + @t.overload + def __getitem__( + self, + key: tuple[slice | int, slice | int], + ) -> Cell | RegionView: ... + + def __getitem__( + self, + key: int | slice | tuple[slice | int, slice | int], + ) -> RowView | Cell | RegionView: + r"""Index a row, single ``(row, col)`` cell, or 2D region view. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"\x1b[1mAB\x1b[0mCD\r\nEFGH") + >>> snap = term.committed + >>> snap[0, 1].text, snap[0, 1].style.bold + ('B', True) + >>> snap[0:2, 1:3].lines + ('BC', 'FG') + """ + return slice_grid(self._rows, self._cols, key) + + def format( + self, + output_format: OutputFormat = OutputFormat.PLAIN, + *, + policy: Policy = DEFAULT_POLICY, + profile: Profile | None = None, + unwrap: bool = False, + ) -> str: + r"""Render this snapshot using :class:`~libvt.format.Formatter`. + + Replay ``VT`` into a fresh :class:`~libvt.terminal.Terminal` of the same + size and profile. + The stream restores cell protection, scroll margins, and the active + SGR, OSC 8, and DECSCA pen. Pending wrap is restored when the stream + can redraw the captured edge glyph in place. + + Parameters + ---------- + output_format : OutputFormat, default OutputFormat.PLAIN + Target export representation (``PLAIN``, ``VT``, or ``HTML``). + policy : Policy, optional + URI and sequence policy applied when exporting hyperlinks or VT. + profile : Profile | None, optional + Terminal profile governing export defaults; defaults to the + profile captured on this snapshot. + unwrap : bool + When ``True``, join soft-wrapped continuation rows onto a single + line in ``PLAIN`` and ``HTML`` output. + + Returns + ------- + str + Formatted plain text, ANSI/DEC VT stream, or ``
`` HTML block.
+
+        Examples
+        --------
+        >>> from libvt.terminal import OutputFormat, Terminal
+        >>> term = Terminal(rows=2, cols=8)
+        >>> term.feed(b"\x1b[1;32mhello world\x1b[0m")
+        >>> snap = term.committed
+        >>> snap.format(OutputFormat.PLAIN, unwrap=True)
+        'hello world'
+        >>> " SnapshotDict:
+        r"""Serialize snapshot state into a deterministic JSON-compatible dict.
+
+        Returns
+        -------
+        SnapshotDict
+            JSON-serializable dictionary of dimensions, ``lines``,
+            ``history_lines``, ``cursor``, ``modes``, ``appearance``,
+            ``program_status``, and ``placements``.
+
+        Examples
+        --------
+        >>> term = Terminal(rows=2, cols=8)
+        >>> term.feed(b"\x1b]2;ci\x07pass")
+        >>> data = term.committed.to_dict()
+        >>> data["title"], data["lines"], data["cursor"]["col"]
+        ('ci', ['pass', ''], 4)
+        """
+        return {
+            "rows": self.rows,
+            "cols": self.cols,
+            "scrolled_total": self.scrolled_total,
+            "evicted_total": self.evicted_total,
+            "lines": list(self.lines),
+            "history_lines": [fr.text for fr in self._history],
+            "cursor": {
+                "row": self.cursor.row,
+                "col": self.cursor.col,
+                "visible": self.cursor.visible,
+                "shape": self.cursor.shape.value,
+                "blinking": self.cursor.blinking,
+                "pending_wrap": self.cursor.pending_wrap,
+            },
+            "title": self.title,
+            "cwd": self.cwd,
+            "cwd_uri": self.cwd_uri,
+            "active_is_alt": self.active_is_alt,
+            "appearance": {
+                "scheme": self.appearance.scheme.name.lower(),
+                "fg_rgb": list(self.appearance.fg_rgb),
+                "bg_rgb": list(self.appearance.bg_rgb),
+                "cursor_rgb": list(self.appearance.cursor_rgb),
+                "palette_overrides": {
+                    str(idx): list(rgb)
+                    for idx, rgb in self.appearance.palette_overrides
+                },
+                "reverse_video": self.appearance.reverse_video,
+            },
+            "modes": sorted(m.name for m in self.modes if m.name is not None),
+            "program_status": (
+                {
+                    "state": self.program_status.state.value,
+                    "id": self.program_status.id,
+                    "progress": self.program_status.progress,
+                    "kind": (
+                        self.program_status.kind.value
+                        if self.program_status.kind is not None
+                        else None
+                    ),
+                    "app": self.program_status.app,
+                    "effective_app": self.program_status.effective_app,
+                    "title": self.program_status.title,
+                    "msg": self.program_status.msg,
+                }
+                if self.program_status is not None
+                else None
+            ),
+            "placements": [
+                {
+                    "protocol": p.protocol.value,
+                    "image_id": p.image_id,
+                    "placement_id": p.placement_id,
+                    "abs_row": p.abs_row,
+                    "viewport_row": self.viewport_row(p.abs_row),
+                    "col": p.col,
+                    "rows": p.rows,
+                    "cols": p.cols,
+                    "z_index": p.z_index,
+                    "virtual": p.virtual,
+                }
+                for p in self.placements
+            ],
+        }
+
+
+__all__ = [
+    "ResyncReason",
+    "ScreenDelta",
+    "Snapshot",
+    "SnapshotDict",
+    "SyncToken",
+    "SyncView",
+]
diff --git a/src/libvt/status.py b/src/libvt/status.py
index 8bf53ddd..1e3b8b3f 100644
--- a/src/libvt/status.py
+++ b/src/libvt/status.py
@@ -8,7 +8,7 @@
 import re
 from dataclasses import dataclass
 
-from libvt.parser import _parse_ascii_uint
+from libvt._util import _parse_ascii_uint
 
 _APP_RE = re.compile(r"^[A-Za-z0-9_.+-]{1,32}$")
 _KEY_RE = re.compile(r"^[a-z]{1,16}$")
diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py
index 9280f392..dc08548e 100644
--- a/src/libvt/terminal.py
+++ b/src/libvt/terminal.py
@@ -10,28 +10,20 @@
 import encodings.cp437
 import enum
 import functools
-import html
 import itertools
 import os
 import re
-import types
 import typing as t
 import urllib.parse
 from dataclasses import dataclass
 
 from libvt._grid import (
-    _EMPTY_FROZEN_HISTORY,
     _PEN_BASE_MASK,
     _PEN_BG_MASK,
-    FrozenRow,
-    RowLike,
     _CellExt,
-    _FrozenHistory,
-    _Row,
     make_cell_ext,
     pack_pen_base,
     raw_width_bits,
-    unpack_style,
 )
 from libvt._ucd import (
     CLUSTER_NONE,
@@ -45,6 +37,7 @@
     step_cluster,
     ucd_lookup,
 )
+from libvt._util import _byte_view, _parse_ascii_int, _parse_ascii_uint
 from libvt.config import (
     DEFAULT_LIMITS,
     DEFAULT_OSC7_HOSTS,
@@ -92,7 +85,13 @@
     WorkingDirectoryChanged,
 )
 from libvt.exc import ProtocolError
-from libvt.graphics import ImageMeta, ImagePlacement
+from libvt.format import (
+    Formatter,
+    OutputFormat,
+    _format_osc_rgb,
+    _style_to_sgr,
+    _VtPen,
+)
 from libvt.input import InputEvent, KittyKeyboardFlags, encode_input
 from libvt.modes import (
     ALT_SCREEN_MODES,
@@ -107,9 +106,6 @@
     Parser,
     ParserEncoding,
     ParserState,
-    _byte_view,
-    _parse_ascii_int,
-    _parse_ascii_uint,
     parse_sgr,
 )
 from libvt.screen import (
@@ -121,27 +117,31 @@
     Screen,
     ScreenSet,
     ScrollRegion,
-    _format_display_row,
-    _HistoryView,
-    _row_groups,
-    _unwrapped_rows,
-    format_rows_text,
-    slice_grid,
+)
+from libvt.snapshot import (
+    ResyncReason,
+    ScreenDelta,
+    Snapshot,
+    SnapshotDict,
+    SyncToken,
+    SyncView,
+    _make_snapshot,
+    _make_sync_token,
+    _SyncState,
 )
 from libvt.status import ProgramStatus, ProgramStatusStore
 from libvt.style import (
-    DEFAULT_APPEARANCE,
     DEFAULT_STYLE,
-    AnsiColor,
     Appearance,
-    Color,
     Hyperlink,
     IndexedColor,
     Style,
-    UnderlineStyle,
     _resolve_color_rgb,
 )
 
+if t.TYPE_CHECKING:
+    from libvt.graphics import ImageMeta, ImagePlacement
+
 # DEC Special Graphics ('0') mapping for 0x5F..0x7E (VT100 / xterm / tmux tty-acs.c).
 _DEC_SPECIAL_GRAPHICS = str.maketrans(
     {
@@ -186,7 +186,6 @@
     {chr(i): encodings.cp437.decoding_table[i] for i in range(0xA0, 0x100)},
 )
 
-_SAFE_URI_PREFIXES = ("https://", "http://", "mailto:")
 _PRINT_ASCII_RE = re.compile(rb"[\x20-\x7e]+")
 _STR_BODY_UTF8_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f]+")
 _STR_BODY_LATIN1_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f\x80-\x9f]+")
@@ -217,267 +216,6 @@ def _alloc_terminal_id() -> int:
     return _TERMINAL_IDS.alloc()
 
 
-#: Buffer view selector for :meth:`Terminal.sync_token` and incremental deltas.
-type SyncView = t.Literal["working", "committed"]
-
-
-class ResyncReason(enum.StrEnum):
-    """Reason :meth:`Terminal.changes_since` emitted a full resynchronization."""
-
-    #: Incremental delta; cached consumer state remains valid.
-    NONE = "none"
-    #: No prior :class:`SyncToken` was supplied (`token=None`).
-    INITIAL = "initial"
-    #: Token belonged to another :class:`Terminal` or different ``view``.
-    TERMINAL_MISMATCH = "terminal_mismatch"
-    #: Terminal resized, reset, switched screens, or rewrote retained history.
-    EPOCH_CHANGED = "epoch_changed"
-    #: Scrollback evicted rows older than the caller's previous watermark.
-    HISTORY_EVICTED = "history_evicted"
-
-
-@dataclass(frozen=True, slots=True)
-class _SyncState:
-    terminal_id: int
-    view: SyncView
-    epoch: int
-    revision: int
-    scrolled_total: int
-    evicted_total: int
-    history_clear_at: int
-    history_clear_seq: int
-    cursor: Cursor
-    modes: frozenset[Mode]
-    title: str
-    cwd: str
-    cwd_uri: str = ""
-    aux_revision: int = 0
-    graphics_revision: int = 0
-    appearance_revision: int = 0
-
-
-def _make_sync_token(state: _SyncState) -> SyncToken:
-    tok = object.__new__(SyncToken)
-    object.__setattr__(tok, "_state", state)
-    return tok
-
-
-class SyncToken:
-    r"""Opaque per-:class:`Terminal` watermark passed to :meth:`Terminal.changes_since`.
-
-    Compare tokens with ``==`` and store them in sets or dictionaries via
-    :func:`hash`; obtain instances from :meth:`Terminal.sync_token` or
-    :attr:`ScreenDelta.token`.
-
-    Examples
-    --------
-    >>> from libvt.terminal import Terminal
-    >>> term = Terminal(rows=2, cols=12)
-    >>> tok0 = term.sync_token()
-    >>> term.feed(b"status: ok")
-    >>> delta = term.changes_since(tok0)
-    >>> delta.dirty_rows, delta.snapshot.lines
-    ((0,), ('status: ok', ''))
-    """
-
-    __slots__ = ("_state",)
-    _state: _SyncState
-
-    def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn:
-        """Disallow direct construction; call :meth:`Terminal.sync_token`."""
-        msg = "SyncToken cannot be instantiated directly; call Terminal.sync_token()"
-        raise TypeError(msg)
-
-    def __setattr__(self, name: str, value: object) -> t.NoReturn:
-        """Disallow attribute mutation on immutable tokens."""
-        msg = f"cannot assign to attribute {name!r} on immutable SyncToken"
-        raise AttributeError(msg)
-
-    def __delattr__(self, name: str) -> t.NoReturn:
-        """Disallow attribute deletion on immutable tokens."""
-        msg = f"cannot delete attribute {name!r} on immutable SyncToken"
-        raise AttributeError(msg)
-
-    def __eq__(self, other: object) -> bool:
-        """Return ``True`` when *other* captures the identical watermark state."""
-        if self is other:
-            return True
-        if not isinstance(other, SyncToken):
-            return NotImplemented
-        return self._state == other._state
-
-    def __hash__(self) -> int:
-        """Return hash of the captured watermark state."""
-        return hash(self._state)
-
-    def __repr__(self) -> str:
-        """Return compact opaque representation."""
-        st = self._state
-        return f"SyncToken(view={st.view!r}, epoch={st.epoch}, revision={st.revision})"
-
-    def __copy__(self) -> SyncToken:
-        """Return ``self`` (immutable value)."""
-        return self
-
-    def __deepcopy__(self, memo: dict[int, object]) -> SyncToken:
-        """Return ``self`` (immutable value)."""
-        return self
-
-    def __reduce__(
-        self,
-    ) -> tuple[collections.abc.Callable[[_SyncState], SyncToken], tuple[_SyncState]]:
-        """Serialize token state for :mod:`pickle`."""
-        return (_make_sync_token, (self._state,))
-
-
-@dataclass(frozen=True, slots=True)
-class ScreenDelta:
-    """Multi-consumer incremental screen update from :meth:`Terminal.changes_since`.
-
-    Attributes
-    ----------
-    token : SyncToken
-        New watermark representing *snapshot*.
-    from_token : SyncToken | None
-        Previous watermark supplied by the caller.
-    resync_reason : ResyncReason
-        ``ResyncReason.NONE`` for an incremental delta, or the reason a full
-        resynchronization was required.
-    viewport_scroll_up : int
-        Count of rows the primary viewport scrolled up into history since
-        *from_token* (``0`` on full resync or non-history scroll).
-    dirty_rows : tuple[int, ...]
-        Sorted zero-based viewport row indices modified after shifting the
-        previous viewport upward by :attr:`viewport_scroll_up`.
-    new_history : collections.abc.Sequence[RowView]
-        Newly sealed scrollback rows appended since *from_token*, ordered
-        oldest to newest.
-    history_evicted : int
-        Count of oldest scrollback rows evicted by scrollback capacity since
-        *from_token* when :attr:`history_cleared` is ``False``.
-    history_cleared : bool
-        ``True`` when ``ED 3`` cleared scrollback since *from_token*.
-    cursor_changed : bool
-        ``True`` when cursor position, visibility, shape, or ``pending_wrap``
-        changed.
-    modes_changed : bool
-        ``True`` when enabled ANSI/DEC modes changed.
-    metadata_changed : bool
-        ``True`` when ``title`` or ``cwd`` changed.
-    graphics_changed : bool
-        ``True`` when ``SIXEL`` or Kitty placements mutated.
-    appearance_changed : bool
-        ``True`` when :attr:`Snapshot.appearance` (theme scheme, default RGBs,
-        ``OSC 4`` palette overrides, or ``?5`` reverse video) changed.
-    snapshot : Snapshot
-        Immutable target :class:`Snapshot` corresponding to :attr:`token`.
-    """
-
-    token: SyncToken
-    from_token: SyncToken | None
-    resync_reason: ResyncReason
-    viewport_scroll_up: int
-    dirty_rows: tuple[int, ...]
-    new_history: collections.abc.Sequence[RowView]
-    history_evicted: int
-    history_cleared: bool
-    cursor_changed: bool
-    modes_changed: bool
-    metadata_changed: bool
-    graphics_changed: bool
-    snapshot: Snapshot
-    appearance_changed: bool = False
-
-    @property
-    def full_resync(self) -> bool:
-        """Return ``True`` when the consumer must replace cached state."""
-        return self.resync_reason is not ResyncReason.NONE
-
-    @property
-    def has_changes(self) -> bool:
-        """Return ``True`` when any grid, history, cursor, mode, or metadata changed."""
-        return (
-            self.full_resync
-            or self.viewport_scroll_up > 0
-            or bool(self.dirty_rows)
-            or bool(self.new_history)
-            or self.history_evicted > 0
-            or self.history_cleared
-            or self.cursor_changed
-            or self.modes_changed
-            or self.metadata_changed
-            or self.graphics_changed
-            or self.appearance_changed
-        )
-
-    def apply_lines(self, history: list[str], viewport: list[str]) -> None:
-        r"""Apply this delta in place to mutable *history* and *viewport* line lists.
-
-        Parameters
-        ----------
-        history : list[str]
-            Cached scrollback text lines maintained by the consumer.
-        viewport : list[str]
-            Cached visible-viewport text lines maintained by the consumer.
-
-        Examples
-        --------
-        >>> from libvt.terminal import Terminal
-        >>> term = Terminal(rows=2, cols=10)
-        >>> hist, view = [], []
-        >>> d0 = term.changes_since(None)
-        >>> d0.apply_lines(hist, view)
-        >>> term.feed(b"row 1\r\nrow 2\r\nrow 3")
-        >>> term.changes_since(d0.token).apply_lines(hist, view)
-        >>> hist, view
-        (['row 1'], ['row 2', 'row 3'])
-        """
-        if self.full_resync or len(viewport) != self.snapshot.rows:
-            history[:] = [r.text for r in self.snapshot.history]
-            viewport[:] = list(self.snapshot.lines)
-            return
-        if self.history_cleared:
-            history.clear()
-        elif self.history_evicted > 0:
-            del history[: self.history_evicted]
-        if self.new_history:
-            history.extend(r.text for r in self.new_history)
-        if self.viewport_scroll_up > 0:
-            shift = min(len(viewport), self.viewport_scroll_up)
-            del viewport[:shift]
-            viewport.extend([""] * shift)
-        for r_idx in self.dirty_rows:
-            viewport[r_idx] = self.snapshot[r_idx].text
-
-    def apply_rows(self, history: list[RowView], viewport: list[RowView]) -> None:
-        """Apply this delta in place to mutable *history* and *viewport* row views.
-
-        Parameters
-        ----------
-        history : list[RowView]
-            Cached scrollback :class:`~libvt.screen.RowView` entries.
-        viewport : list[RowView]
-            Cached visible :class:`~libvt.screen.RowView` entries.
-        """
-        if self.full_resync or len(viewport) != self.snapshot.rows:
-            history[:] = list(self.snapshot.history)
-            viewport[:] = [self.snapshot[r] for r in range(self.snapshot.rows)]
-            return
-        if self.history_cleared:
-            history.clear()
-        elif self.history_evicted > 0:
-            del history[: self.history_evicted]
-        if self.new_history:
-            history.extend(self.new_history)
-        if self.viewport_scroll_up > 0:
-            shift = min(len(viewport), self.viewport_scroll_up)
-            del viewport[:shift]
-            base = len(viewport)
-            viewport.extend([self.snapshot[base + i] for i in range(shift)])
-        for r_idx in self.dirty_rows:
-            viewport[r_idx] = self.snapshot[r_idx]
-
-
 class StopOn(enum.IntFlag):
     """Boundary conditions for :meth:`Terminal.feed_until`."""
 
@@ -513,17 +251,6 @@ class StepResult:
     stopped_on: StopOn
 
 
-class OutputFormat(enum.StrEnum):
-    """Export target formats supported by :class:`Formatter`."""
-
-    #: Right-trimmed plain text without escape sequences.
-    PLAIN = "plain"
-    #: ANSI/DEC VT stream with the active viewport, pen, and modes.
-    VT = "vt"
-    #: Self-contained ``
`` HTML fragment with ```` SGR styling.
-    HTML = "html"
-
-
 class FlightRecorder:
     r"""Bounded raw-byte ring buffer capturing recent VT traffic for diagnostics.
 
@@ -561,18 +288,18 @@ def total_bytes(self) -> int:
 
     def record(self, data: collections.abc.Buffer) -> None:
         """Append *data*, retaining at most ``max_bytes`` trailing bytes."""
-        mv = _byte_view(data)
-        n = len(mv)
-        if n == 0:
-            return
-        self._total_bytes += n
-        if n >= self._max_bytes:
-            self._buf[:] = mv[n - self._max_bytes :]
-            return
-        overflow = len(self._buf) + n - self._max_bytes
-        if overflow > 0:
-            del self._buf[:overflow]
-        self._buf.extend(mv)
+        with _byte_view(data) as mv:
+            n = len(mv)
+            if n == 0:
+                return
+            self._total_bytes += n
+            if n >= self._max_bytes:
+                self._buf[:] = mv[n - self._max_bytes :]
+                return
+            overflow = len(self._buf) + n - self._max_bytes
+            if overflow > 0:
+                del self._buf[:overflow]
+            self._buf.extend(mv)
 
     def tail(self, max_bytes: int = 256) -> bytes:
         """Return up to *max_bytes* of the most recently recorded input bytes."""
@@ -623,1186 +350,6 @@ class _SavedCursor:
     protected: bool = False
 
 
-@dataclass(frozen=True, slots=True)
-class _VtPen:
-    style: Style = DEFAULT_STYLE
-    hyperlink: Hyperlink | None = None
-    protected: bool = False
-
-
-_DEFAULT_VT_PEN = _VtPen()
-
-
-def _make_snapshot(
-    *,
-    rows: tuple[_Row, ...],
-    history: _FrozenHistory | collections.abc.Sequence[FrozenRow] = (
-        _EMPTY_FROZEN_HISTORY
-    ),
-    cols: int,
-    cursor: Cursor,
-    scroll_region: ScrollRegion,
-    title: str,
-    cwd: str,
-    cwd_uri: str = "",
-    modes: frozenset[Mode],
-    active_is_alt: bool,
-    prompt_zones: tuple[PromptZone, ...],
-    program_status: ProgramStatus | None,
-    program_statuses: collections.abc.Mapping[str, ProgramStatus],
-    generation: int,
-    appearance: Appearance = DEFAULT_APPEARANCE,
-    images: collections.abc.Mapping[int, ImageMeta] | None = None,
-    placements: tuple[ImagePlacement, ...] = (),
-    scrolled_total: int | None = None,
-    evicted_total: int | None = None,
-    profile: Profile = DEFAULT_PROFILE,
-    pen: _VtPen = _DEFAULT_VT_PEN,
-) -> Snapshot:
-    snap = object.__new__(Snapshot)
-    object.__setattr__(snap, "_frozen", False)
-    snap._rows = rows
-    hist_obj = _FrozenHistory.from_sequence(history)
-    snap._history = hist_obj
-    snap._cols = cols
-    snap._profile = profile
-    snap._scroll_region = scroll_region
-    snap._vt_pen = pen
-    eff_scrolled = (
-        (0 if active_is_alt else len(hist_obj))
-        if scrolled_total is None
-        else scrolled_total
-    )
-    snap._scrolled_total = eff_scrolled
-    snap._evicted_total = (
-        (0 if active_is_alt else max(0, eff_scrolled - len(hist_obj)))
-        if evicted_total is None
-        else evicted_total
-    )
-    snap._unwrapped_text_cache = None
-    snap.cursor = cursor
-    snap.title = title
-    snap.cwd = cwd
-    snap.cwd_uri = cwd_uri
-    snap.modes = modes
-    snap.active_is_alt = active_is_alt
-    snap.prompt_zones = prompt_zones
-    snap.program_status = program_status
-    snap.program_statuses = types.MappingProxyType(dict(program_statuses))
-    snap.generation = generation
-    snap.appearance = appearance
-    snap.images = types.MappingProxyType(dict(images) if images is not None else {})
-    snap.placements = placements
-    object.__setattr__(snap, "_frozen", True)
-    return snap
-
-
-class Snapshot:
-    r"""Immutable point-in-time capture of terminal screen, history, and metadata.
-
-    Obtain instances via :attr:`Terminal.committed` (tear-free across ``?2026``
-    synchronized frames) or :meth:`Terminal.snapshot` (immediate working
-    buffer). Once captured, a ``Snapshot`` never mutates when later bytes
-    arrive on the :class:`Terminal` and can be shared across threads without
-    locking.
-
-    Index ``snap[row]`` for a :class:`~libvt.screen.RowView`, ``snap[row, col]``
-    for an immutable :class:`~libvt.screen.Cell`, or ``snap[r0:r1, c0:c1]`` for
-    a rectangular :class:`~libvt.screen.RegionView`. Render a visual grid box
-    with :func:`~libvt.testing.format_screen_box` or include header metadata and
-    ``SGR`` spans with :func:`~libvt.testing.serialize_vt_snapshot`.
-
-    Attributes
-    ----------
-    cursor : Cursor
-        Zero-based cursor position, shape, visibility, and ``pending_wrap``.
-    title : str
-        Window title set via ``OSC 0`` / ``OSC 2``.
-    cwd : str
-        Local working directory accepted under ``Policy.osc7_hosts``.
-    cwd_uri : str
-        Raw ``OSC 7`` / ``OSC 9;9`` working directory URI.
-    modes : frozenset[Mode]
-        Enabled ANSI and DEC private modes.
-    active_is_alt : bool
-        ``True`` when the alternate screen buffer is active.
-    prompt_zones : tuple[PromptZone, ...]
-        Recorded primary-screen ``OSC 133`` semantic prompt zones (empty when
-        :attr:`active_is_alt` is ``True``).
-    program_status : ProgramStatus | None
-        Highest-urgency active ``OSC 7501`` / ``OSC 9;4`` status record.
-    program_statuses : collections.abc.Mapping[str, ProgramStatus]
-        Read-only mapping of active ``OSC 7501`` task records keyed by ``id``.
-    generation : int
-        Terminal mutation generation when this snapshot was captured.
-    appearance : Appearance
-        Committed theme scheme, default RGBs, palette overrides, and ``?5``
-        reverse-video state.
-    images : collections.abc.Mapping[int, ImageMeta]
-        Read-only mapping of stored ``SIXEL`` / Kitty :class:`ImageMeta` items.
-    placements : tuple[ImagePlacement, ...]
-        Immutable active + scrollback :class:`ImagePlacement` records.
-
-    Examples
-    --------
-    >>> from libvt.terminal import Terminal
-    >>> from libvt.testing import serialize_vt_snapshot
-    >>> term = Terminal(rows=2, cols=14)
-    >>> term.feed(b"\x1b[1;32mREADY\x1b[0m  api\r\n\x1b[7m> worker\x1b[0m")
-    >>> snap = term.committed
-    >>> print(serialize_vt_snapshot(snap))
-    size=14x2 cursor=(1,8,vis=True) alt=False modes=[]
-    ┌──────────────┐
-    │READY  api    │
-    │> worker      │
-    └──────────────┘
-    styles:
-      r0[0..5]: bold fg=green
-      r1[0..8]: reverse
-    >>> snap[0, 0].text, snap[0, 0].style.bold, snap[1, 0].style.reverse
-    ('R', True, True)
-    """
-
-    __slots__ = (
-        "_cols",
-        "_evicted_total",
-        "_frozen",
-        "_history",
-        "_profile",
-        "_rows",
-        "_scroll_region",
-        "_scrolled_total",
-        "_unwrapped_text_cache",
-        "_vt_pen",
-        "active_is_alt",
-        "appearance",
-        "cursor",
-        "cwd",
-        "cwd_uri",
-        "generation",
-        "images",
-        "modes",
-        "placements",
-        "program_status",
-        "program_statuses",
-        "prompt_zones",
-        "title",
-    )
-
-    _cols: int
-    _evicted_total: int
-    _frozen: bool
-    _history: _FrozenHistory
-    _profile: Profile
-    _rows: tuple[_Row, ...]
-    _scroll_region: ScrollRegion
-    _scrolled_total: int
-    _unwrapped_text_cache: str | None
-    _vt_pen: _VtPen
-    active_is_alt: bool
-    appearance: Appearance
-    cursor: Cursor
-    cwd: str
-    cwd_uri: str
-    generation: int
-    images: collections.abc.Mapping[int, ImageMeta]
-    modes: frozenset[Mode]
-    placements: tuple[ImagePlacement, ...]
-    program_status: ProgramStatus | None
-    program_statuses: collections.abc.Mapping[str, ProgramStatus]
-    prompt_zones: tuple[PromptZone, ...]
-    title: str
-
-    def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn:
-        """Disallow direct construction; call :meth:`Terminal.snapshot`."""
-        msg = "Snapshot cannot be instantiated directly; call Terminal.snapshot()"
-        raise TypeError(msg)
-
-    def __setattr__(self, name: str, value: object) -> None:
-        """Reject attribute mutation once snapshot initialization completes."""
-        if getattr(self, "_frozen", False):
-            msg = f"Snapshot is immutable; cannot assign {name!r}"
-            raise AttributeError(msg)
-        object.__setattr__(self, name, value)
-
-    @property
-    def profile(self) -> Profile:
-        """Return the profile captured with this frame."""
-        return self._profile
-
-    @property
-    def rows(self) -> int:
-        """Return snapshot height in rows.
-
-        Examples
-        --------
-        >>> Terminal(rows=3, cols=10).committed.rows
-        3
-        """
-        return len(self._rows)
-
-    @property
-    def cols(self) -> int:
-        """Return snapshot width in columns.
-
-        Examples
-        --------
-        >>> Terminal(rows=3, cols=10).committed.cols
-        10
-        """
-        return self._cols
-
-    @property
-    def scrolled_total(self) -> int:
-        r"""Return monotonic count of rows scrolled off the active screen's top.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"a\r\nb\r\nc")
-        >>> term.committed.scrolled_total
-        1
-        """
-        return self._scrolled_total
-
-    @property
-    def evicted_total(self) -> int:
-        r"""Return count of scrollback rows evicted from the active screen.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=1, cols=8, scrollback=1)
-        >>> term.feed(b"a\r\nb\r\nc")
-        >>> term.committed.evicted_total
-        1
-        """
-        return self._evicted_total
-
-    def viewport_row(self, abs_row: int) -> int | None:
-        r"""Return zero-based viewport row for *abs_row*, or ``None``.
-
-        Parameters
-        ----------
-        abs_row : int
-            Monotonic absolute row coordinate (e.g.
-            :attr:`~libvt.events.PromptZone.abs_row` or
-            :attr:`~libvt.graphics.ImagePlacement.abs_row`).
-
-        Returns
-        -------
-        int | None
-            ``0 <= row < rows`` when *abs_row* is visible in this snapshot's
-            active viewport, else ``None``.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"r0\r\nr1\r\nr2")
-        >>> snap = term.committed
-        >>> snap.viewport_row(0), snap.viewport_row(1), snap.viewport_row(2)
-        (None, 0, 1)
-        """
-        if isinstance(abs_row, bool) or not isinstance(abs_row, int):
-            msg = f"abs_row must be int, got {type(abs_row).__name__}"
-            raise TypeError(msg)
-        rel = abs_row - self._scrolled_total
-        if 0 <= rel < len(self._rows):
-            return rel
-        return None
-
-    def at_abs(self, abs_row: int) -> RowView:
-        r"""Return :class:`~libvt.screen.RowView` at *abs_row* in history or viewport.
-
-        Parameters
-        ----------
-        abs_row : int
-            Monotonic absolute row coordinate.
-
-        Returns
-        -------
-        RowView
-            Immutable view of the row from scrollback or the active viewport.
-
-        Raises
-        ------
-        IndexError
-            When *abs_row* has been evicted from history or is out of range.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"hist\r\nvis1\r\nvis2")
-        >>> snap = term.committed
-        >>> snap.at_abs(0).text, snap.at_abs(2).text
-        ('hist', 'vis2')
-        """
-        if isinstance(abs_row, bool) or not isinstance(abs_row, int):
-            msg = f"abs_row must be int, got {type(abs_row).__name__}"
-            raise TypeError(msg)
-        if self.active_is_alt:
-            if 0 <= abs_row < len(self._rows):
-                return RowView(self._rows[abs_row])
-            msg = f"abs_row {abs_row} out of range for alternate screen"
-            raise IndexError(msg)
-        first_abs = self._scrolled_total - len(self._history)
-        if abs_row < first_abs:
-            msg = f"abs_row {abs_row} was evicted (earliest retained is {first_abs})"
-            raise IndexError(msg)
-        if abs_row < self._scrolled_total:
-            fr = self._history.at(abs_row - first_abs)
-            return RowView(fr, range(max(self._cols, fr.used)))
-        rel = abs_row - self._scrolled_total
-        if rel < len(self._rows):
-            return RowView(self._rows[rel])
-        msg = f"abs_row {abs_row} out of range"
-        raise IndexError(msg)
-
-    @property
-    def history(self) -> collections.abc.Sequence[RowView]:
-        r"""Return ``O(1)`` immutable :class:`RowView` sequence over scrollback rows.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=1, cols=10)
-        >>> term.feed(b"first\r\nsecond")
-        >>> [row.text for row in term.committed.history]
-        ['first']
-        """
-        return _HistoryView(self._history, cols=self._cols)
-
-    def viewport(self, offset: int = 0) -> RegionView:
-        r"""Return a ``(rows, cols)`` :class:`~libvt.screen.RegionView` at *offset*.
-
-        Parameters
-        ----------
-        offset : int
-            Zero-based upward scroll offset in terminal rows. ``0`` returns the
-            captured active viewport; positive values scroll into retained
-            primary history (clamped to ``len(history)``). Alternate-screen
-            snapshots (:attr:`~libvt.terminal.Snapshot.active_is_alt` is
-            ``True``) always return their alternate viewport without blending
-            primary scrollback.
-
-        Returns
-        -------
-        RegionView
-            Immutable rectangular view with height
-            :attr:`~libvt.terminal.Snapshot.rows` and width
-            :attr:`~libvt.terminal.Snapshot.cols`.
-
-        Raises
-        ------
-        TypeError
-            If *offset* is not an ``int`` (or is a ``bool``).
-        ValueError
-            If *offset* is negative.
-
-        Examples
-        --------
-        >>> from libvt.testing import serialize_vt_snapshot
-        >>> term = Terminal(rows=2, cols=10)
-        >>> term.feed(b"line 1\r\nline 2\r\nline 3")
-        >>> snap = term.committed
-        >>> print(serialize_vt_snapshot(snap.viewport(offset=1)))
-        size=10x2 region=True
-        ┌──────────┐
-        │line 1    │
-        │line 2    │
-        └──────────┘
-        """
-        if isinstance(offset, bool) or not isinstance(offset, int):
-            msg = f"offset must be int, got {type(offset).__name__}"
-            raise TypeError(msg)
-        if offset < 0:
-            msg = f"offset must be >= 0, got {offset}"
-            raise ValueError(msg)
-        cols = self._cols
-        if self.active_is_alt or offset == 0 or not self._history:
-            return RegionView(self._rows, range(cols), parent_cols=cols, live=False)
-        h_len = len(self._history)
-        v_rows = len(self._rows)
-        eff_offset = min(offset, h_len)
-        win_start = h_len - eff_offset
-        win_stop = win_start + v_rows
-        out_rows: list[_Row | FrozenRow] = []
-        for idx in range(win_start, min(win_stop, h_len)):
-            fr = self._history.at(idx)
-            if fr.used > cols or (
-                0 < fr.cols < cols
-                and fr.runs
-                and raw_width_bits(fr.attr_at(fr.cols - 1))
-                == int(WidthRole.SPACER_HEAD)
-            ):
-                out_rows.append(fr.thaw(cols))
-            else:
-                out_rows.append(fr)
-        if win_stop > h_len:
-            out_rows.extend(self._rows[: win_stop - h_len])
-        return RegionView(out_rows, range(cols), parent_cols=cols, live=False)
-
-    @property
-    def lines(self) -> tuple[str, ...]:
-        r"""Return visible row text with unwritten trailing blank cells omitted.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"ok")
-        >>> term.committed.lines
-        ('ok', '')
-        """
-        return tuple(r.rstrip_text() for r in self._rows)
-
-    @property
-    def display_lines(self) -> tuple[str, ...]:
-        r"""Return space-padded text of width ``cols`` for every visible row.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=6)
-        >>> term.feed(b"ok")
-        >>> term.committed.display_lines
-        ('ok    ', '      ')
-        """
-        cols = self._cols
-        return tuple(_format_display_row(r, 0, cols) for r in self._rows)
-
-    @property
-    def text(self) -> str:
-        r"""Return visible snapshot text with trailing blank rows omitted.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=3, cols=8)
-        >>> term.feed(b"top\r\nnext")
-        >>> term.committed.text
-        'top\nnext'
-        """
-        return format_rows_text(self._rows)
-
-    @property
-    def unwrapped_text(self) -> str:
-        r"""Return visible snapshot text with soft-wrapped rows joined.
-
-        Contiguous ``row.wrapped`` rows join without ``"\n"`` while hard
-        linebreaks stay ``"\n"`` and trailing blank rows are omitted.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=3, cols=8)
-        >>> term.feed(b"hello world\r\nok")
-        >>> term.committed.unwrapped_text
-        'hello world\nok'
-        """
-        cached = self._unwrapped_text_cache
-        if cached is None:
-            cached = format_rows_text(self._rows, unwrap=True)
-            object.__setattr__(self, "_unwrapped_text_cache", cached)
-        return cached
-
-    @t.overload
-    def __getitem__(self, key: int) -> RowView: ...
-
-    @t.overload
-    def __getitem__(self, key: tuple[int, int]) -> Cell: ...
-
-    @t.overload
-    def __getitem__(
-        self,
-        key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice],
-    ) -> RegionView: ...
-
-    @t.overload
-    def __getitem__(
-        self,
-        key: tuple[slice | int, slice | int],
-    ) -> Cell | RegionView: ...
-
-    def __getitem__(
-        self,
-        key: int | slice | tuple[slice | int, slice | int],
-    ) -> RowView | Cell | RegionView:
-        r"""Index a row, single ``(row, col)`` cell, or 2D region view.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"\x1b[1mAB\x1b[0mCD\r\nEFGH")
-        >>> snap = term.committed
-        >>> snap[0, 1].text, snap[0, 1].style.bold
-        ('B', True)
-        >>> snap[0:2, 1:3].lines
-        ('BC', 'FG')
-        """
-        return slice_grid(self._rows, self._cols, key)
-
-    def format(
-        self,
-        output_format: OutputFormat = OutputFormat.PLAIN,
-        *,
-        policy: Policy = DEFAULT_POLICY,
-        profile: Profile = DEFAULT_PROFILE,
-        unwrap: bool = False,
-    ) -> str:
-        r"""Render this snapshot using :class:`Formatter`.
-
-        Replay ``VT`` into a fresh :class:`Terminal` of the same size and
-        profile.
-        The stream restores cell protection, scroll margins, and the active
-        SGR, OSC 8, and DECSCA pen. Pending wrap is restored when the stream
-        can redraw the captured edge glyph in place.
-
-        Parameters
-        ----------
-        output_format : OutputFormat, default OutputFormat.PLAIN
-            Target export representation (``PLAIN``, ``VT``, or ``HTML``).
-        policy : Policy, optional
-            URI and sequence policy applied when exporting hyperlinks or VT.
-        profile : Profile, optional
-            Terminal profile governing width rules during export.
-        unwrap : bool
-            When ``True``, join soft-wrapped continuation rows onto a single
-            line in ``PLAIN`` and ``HTML`` output.
-
-        Returns
-        -------
-        str
-            Formatted plain text, ANSI/DEC VT stream, or ``
`` HTML block.
-
-        Examples
-        --------
-        >>> from libvt.terminal import OutputFormat, Terminal
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"\x1b[1;32mhello world\x1b[0m")
-        >>> snap = term.committed
-        >>> snap.format(OutputFormat.PLAIN, unwrap=True)
-        'hello world'
-        >>> " dict[str, t.Any]:
-        r"""Serialize snapshot state into a deterministic JSON-compatible dict.
-
-        Returns
-        -------
-        dict[str, Any]
-            JSON-serializable dictionary of dimensions, ``lines``,
-            ``history_lines``, ``cursor``, ``modes``, ``appearance``,
-            ``program_status``, and ``placements``.
-
-        Examples
-        --------
-        >>> term = Terminal(rows=2, cols=8)
-        >>> term.feed(b"\x1b]2;ci\x07pass")
-        >>> data = term.committed.to_dict()
-        >>> data["title"], data["lines"], data["cursor"]["col"]
-        ('ci', ['pass', ''], 4)
-        """
-        return {
-            "rows": self.rows,
-            "cols": self.cols,
-            "scrolled_total": self.scrolled_total,
-            "evicted_total": self.evicted_total,
-            "lines": list(self.lines),
-            "history_lines": [fr.text for fr in self._history],
-            "cursor": {
-                "row": self.cursor.row,
-                "col": self.cursor.col,
-                "visible": self.cursor.visible,
-                "shape": self.cursor.shape.value,
-                "blinking": self.cursor.blinking,
-                "pending_wrap": self.cursor.pending_wrap,
-            },
-            "title": self.title,
-            "cwd": self.cwd,
-            "cwd_uri": self.cwd_uri,
-            "active_is_alt": self.active_is_alt,
-            "appearance": {
-                "scheme": self.appearance.scheme.name.lower(),
-                "fg_rgb": list(self.appearance.fg_rgb),
-                "bg_rgb": list(self.appearance.bg_rgb),
-                "cursor_rgb": list(self.appearance.cursor_rgb),
-                "palette_overrides": {
-                    str(idx): list(rgb)
-                    for idx, rgb in self.appearance.palette_overrides
-                },
-                "reverse_video": self.appearance.reverse_video,
-            },
-            "modes": sorted(m.name for m in self.modes if m.name is not None),
-            "program_status": (
-                {
-                    "state": self.program_status.state.value,
-                    "id": self.program_status.id,
-                    "progress": self.program_status.progress,
-                    "kind": (
-                        self.program_status.kind.value
-                        if self.program_status.kind is not None
-                        else None
-                    ),
-                    "app": self.program_status.app,
-                    "effective_app": self.program_status.effective_app,
-                    "title": self.program_status.title,
-                    "msg": self.program_status.msg,
-                }
-                if self.program_status is not None
-                else None
-            ),
-            "placements": [
-                {
-                    "protocol": p.protocol.value,
-                    "image_id": p.image_id,
-                    "placement_id": p.placement_id,
-                    "abs_row": p.abs_row,
-                    "viewport_row": self.viewport_row(p.abs_row),
-                    "col": p.col,
-                    "rows": p.rows,
-                    "cols": p.cols,
-                    "z_index": p.z_index,
-                    "virtual": p.virtual,
-                }
-                for p in self.placements
-            ],
-        }
-
-
-def _color_sgr_tokens(color: Color, *, fg: bool) -> list[str]:
-    if color is None:
-        return ["39" if fg else "49"]
-    if isinstance(color, AnsiColor):
-        idx = int(color)
-        if idx < 8:
-            return [str((30 if fg else 40) + idx)]
-        return [str((90 if fg else 100) + (idx - 8))]
-    prefix = "38" if fg else "48"
-    if isinstance(color, IndexedColor):
-        return [f"{prefix};5;{color.index}"]
-    return [f"{prefix};2;{color.r};{color.g};{color.b}"]
-
-
-def _style_to_sgr(style: Style) -> str:
-    if style == DEFAULT_STYLE:
-        return "\x1b[0m"
-    parts: list[str] = ["0"]
-    if style.bold:
-        parts.append("1")
-    if style.dim:
-        parts.append("2")
-    if style.italic:
-        parts.append("3")
-    if style.underline == UnderlineStyle.SINGLE:
-        parts.append("4")
-    elif style.underline != UnderlineStyle.NONE:
-        parts.append(f"4:{int(style.underline)}")
-    if style.blink:
-        parts.append("5")
-    if style.reverse:
-        parts.append("7")
-    if style.hidden:
-        parts.append("8")
-    if style.strikethrough:
-        parts.append("9")
-    if style.overline:
-        parts.append("53")
-    if style.fg is not None:
-        parts.extend(_color_sgr_tokens(style.fg, fg=True))
-    if style.bg is not None:
-        parts.extend(_color_sgr_tokens(style.bg, fg=False))
-    if style.underline_color is not None:
-        ul = style.underline_color
-        if isinstance(ul, AnsiColor):
-            parts.append(f"58:5:{int(ul)}")
-        elif isinstance(ul, IndexedColor):
-            parts.append(f"58:5:{ul.index}")
-        else:
-            parts.append(f"58:2::{ul.r}:{ul.g}:{ul.b}")
-    return f"\x1b[{';'.join(parts)}m"
-
-
-def _is_safe_uri(uri: str) -> bool:
-    low = uri.lstrip().lower()
-    return low.startswith(_SAFE_URI_PREFIXES)
-
-
-def _vt_cell_pen(row: _Row, col: int) -> _VtPen:
-    ext = row.ext_at(col)
-    return _VtPen(
-        style=unpack_style(row.attr_at(col), ext),
-        hyperlink=ext.hyperlink if ext is not None else None,
-        protected=ext is not None and ext.protected,
-    )
-
-
-def _vt_glyph_state(
-    text: str,
-    width: int,
-    state: int,
-    *,
-    mode_2027: bool,
-    profile: Profile,
-) -> int | None:
-    """Return the cluster state if printing *text* adds one glyph of *width*."""
-    if not text:
-        return None
-    unicode = profile.unicode
-    actual_width = char_width(text[0], ambiguous_width=unicode.ambiguous_width)
-    for idx, ch in enumerate(text):
-        extends, state, override = step_cluster(
-            state,
-            ord(ch),
-            mode_2027=mode_2027,
-            vs15_narrows=unicode.vs15_narrows_wide_emoji,
-            vs16_always_wide=unicode.vs16_always_wide,
-            ambiguous_width=unicode.ambiguous_width,
-        )
-        if extends != (idx > 0):
-            return None
-        if override >= 0:
-            actual_width = override
-    return state if actual_width == width else None
-
-
-def _vt_wrap_position(
-    snapshot: Snapshot, *, left: int, right: int
-) -> tuple[int, int, int] | None:
-    """Find the write position and captured glyph column for pending wrap."""
-    cur = snapshot.cursor
-    if not cur.pending_wrap or Mode.DECAWM not in snapshot.modes:
-        return None
-    edge = right if cur.col <= right else snapshot.cols - 1
-    if cur.col != edge or edge < 0 or not 0 <= cur.row < snapshot.rows:
-        return None
-    row = snapshot._rows[cur.row]
-    if edge >= row.text_used:
-        return None
-    role = raw_width_bits(row.attr_at(edge))
-    if role == WidthRole.SPACER_HEAD:
-        return None
-    col = edge - 1 if role == WidthRole.SPACER_TAIL else edge
-    if col < 0:
-        return None
-    last_col = snapshot.cols - 1
-    if (
-        col <= 1
-        and cur.row > 0
-        and raw_width_bits(snapshot._rows[cur.row - 1].attr_at(last_col))
-        == WidthRole.SPACER_HEAD
-    ):
-        # Printing from the spacer head keeps the wide glyph paired across rows.
-        margins = snapshot._scroll_region
-        if (
-            col == 0
-            and role == WidthRole.SPACER_TAIL
-            and (left, right) == (0, last_col)
-            and cur.row - 1 != margins.bottom
-            and (Mode.DECOM not in snapshot.modes or margins.top < cur.row)
-        ):
-            return cur.row - 1, last_col, col
-        return None
-    return cur.row, col, col
-
-
-def _unwrapped_style_runs(
-    rows: collections.abc.Sequence[RowLike],
-) -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]:
-    def runs() -> collections.abc.Iterator[tuple[str, Style, Hyperlink | None]]:
-        for row, padding in _unwrapped_rows(rows, include_styles=True):
-            yield from (
-                (run.text, run.style, run.hyperlink)
-                for run in RowView(row).runs
-                if run.text
-            )
-            if padding:
-                yield " " * padding, DEFAULT_STYLE, None
-
-    for (style, link), group in itertools.groupby(
-        runs(), key=lambda item: (item[1], item[2])
-    ):
-        yield "".join(text for text, _, _ in group), style, link
-
-
-class Formatter:
-    r"""Serialize a :class:`Snapshot` to plain text, VT sequences, or HTML.
-
-    Replay VT output into a fresh :class:`Terminal` of the same size and
-    profile.
-    See :meth:`Snapshot.format` for the VT export contract.
-
-    Attributes
-    ----------
-    output_format : OutputFormat
-        Target export format (``PLAIN``, ``VT``, or ``HTML``).
-    policy : Policy
-        URI and sequence policy applied during export.
-    profile : Profile
-        Terminal profile governing width and appearance rules.
-    unwrap : bool
-        When ``True``, join soft-wrapped continuation rows onto a single line
-        in ``PLAIN`` and ``HTML`` output.
-
-    Examples
-    --------
-    >>> from libvt.terminal import Formatter, OutputFormat, Terminal
-    >>> term = Terminal(rows=2, cols=8)
-    >>> term.feed(b"\x1b[31mhello world\x1b[0m")
-    >>> Formatter(OutputFormat.PLAIN, unwrap=True).format_snapshot(term.committed)
-    'hello world'
-    """
-
-    __slots__ = ("output_format", "policy", "profile", "unwrap")
-
-    def __init__(
-        self,
-        output_format: OutputFormat = OutputFormat.PLAIN,
-        *,
-        policy: Policy = DEFAULT_POLICY,
-        profile: Profile = DEFAULT_PROFILE,
-        unwrap: bool = False,
-    ) -> None:
-        self.output_format = output_format
-        self.policy = policy
-        self.profile = profile
-        self.unwrap = unwrap
-
-    def format_snapshot(self, snapshot: Snapshot) -> str:
-        """Render *snapshot* in :attr:`output_format`."""
-        if self.output_format == OutputFormat.PLAIN:
-            return snapshot.unwrapped_text if self.unwrap else snapshot.text
-        if self.output_format == OutputFormat.VT:
-            return self._render_vt(snapshot)
-        return self._render_html(snapshot)
-
-    def _render_vt(self, snapshot: Snapshot) -> str:
-        out: list[str] = []
-        export_modes = snapshot.modes - TRANSIENT_SNAPSHOT_MODES
-        if Mode.DECCOLM in export_modes:
-            if Mode.ALLOW_80_132 in export_modes:
-                out.append("\x1b[?40h\x1b[?3h")
-            else:
-                out.append("\x1b[?40h\x1b[?3h\x1b[?40l")
-        if not snapshot.active_is_alt:
-            export_modes = export_modes - ALT_SCREEN_MODES
-        else:
-            for alt_mode in sorted(export_modes & ALT_SCREEN_MODES, key=int):
-                code = int(alt_mode) & ~DEC_PRIVATE_MASK
-                out.append(f"\x1b[?{code}h")
-        mode_2027 = Mode.GRAPHEME_CLUSTERING in export_modes
-        if not mode_2027:
-            out.append("\x1b[?2027l")
-        app = snapshot.appearance
-        for ov_idx, ov_rgb in app.palette_overrides:
-            out.append(f"\x1b]4;{ov_idx};{_format_osc_rgb(ov_rgb)}\x1b\\")
-        if app.fg_rgb != self.profile.queries.fg_rgb:
-            out.append(f"\x1b]10;{_format_osc_rgb(app.fg_rgb)}\x1b\\")
-        if app.bg_rgb != self.profile.queries.bg_rgb:
-            out.append(f"\x1b]11;{_format_osc_rgb(app.bg_rgb)}\x1b\\")
-        if app.cursor_rgb != self.profile.queries.cursor_rgb:
-            out.append(f"\x1b]12;{_format_osc_rgb(app.cursor_rgb)}\x1b\\")
-        cur_pen = _DEFAULT_VT_PEN
-        cluster_state = CLUSTER_NONE
-        cols = snapshot.cols
-        n_rows = len(snapshot._rows)
-
-        def set_pen(pen: _VtPen) -> None:
-            nonlocal cur_pen
-            if pen.hyperlink != cur_pen.hyperlink:
-                link = pen.hyperlink
-                if link is None:
-                    out.append("\x1b]8;;\x1b\\")
-                else:
-                    param = f"id={link.id}" if link.id else ""
-                    out.append(f"\x1b]8;{param};{link.uri}\x1b\\")
-            if pen.style != cur_pen.style:
-                out.append(_style_to_sgr(pen.style))
-            if pen.protected != cur_pen.protected:
-                out.append('\x1b[1"q' if pen.protected else '\x1b[0"q')
-            cur_pen = pen
-
-        def set_grapheme_mode(enabled: bool) -> None:
-            nonlocal mode_2027
-            if enabled != mode_2027:
-                out.append("\x1b[?2027h" if enabled else "\x1b[?2027l")
-                mode_2027 = enabled
-
-        def move_cursor(r: int, c: int) -> None:
-            nonlocal cluster_state
-            out.append(f"\x1b[{r + 1};{c + 1}H")
-            cluster_state = CLUSTER_NONE
-
-        def glyph_mode(text: str, width: int, anchor: int) -> tuple[bool, int] | None:
-            for mode in (mode_2027, not mode_2027):
-                state = _vt_glyph_state(
-                    text, width, anchor, mode_2027=mode, profile=snapshot._profile
-                )
-                if state is not None:
-                    return mode, state
-            return None
-
-        def write_glyph(r: int, c: int) -> None:
-            nonlocal cluster_state
-            row = snapshot._rows[r]
-            text = row.char_at(c)
-            width = 2 if raw_width_bits(row.attr_at(c)) == WidthRole.WIDE else 1
-            variant = glyph_mode(text, width, cluster_state)
-            if variant is None and cluster_state != CLUSTER_NONE:
-                variant = glyph_mode(text, width, CLUSTER_NONE)
-                if variant is not None:
-                    if r > 0 and c == 0 and snapshot._rows[r - 1].wrapped:
-                        prev = snapshot._rows[r - 1]
-                        if (
-                            raw_width_bits(prev.attr_at(cols - 1))
-                            == WidthRole.SPACER_HEAD
-                        ):
-                            move_cursor(r - 1, cols - 1)
-                        else:
-                            # Consume pending wrap before addressing the row.
-                            out.append(" ")
-                            move_cursor(r, c)
-                    else:
-                        move_cursor(r, c)
-            if variant is not None:
-                mode, cluster_state = variant
-                set_grapheme_mode(mode)
-            out.append(text)
-
-        for r_idx, row in enumerate(snapshot._rows):
-            eff_wrapped = row.wrapped and r_idx + 1 < n_rows
-            if r_idx > 0:
-                prev_wrapped = snapshot._rows[r_idx - 1].wrapped
-                if not prev_wrapped:
-                    out.append("\r\n")
-                    cluster_state = CLUSTER_NONE
-                elif not eff_wrapped and row.text_used == 0 and cols > 0:
-                    set_pen(_DEFAULT_VT_PEN)
-                    out.append(f" \x1b[{r_idx + 1};1H\x1b[X")
-                    cluster_state = CLUSTER_NONE
-            if eff_wrapped:
-                has_spacer_head = (
-                    cols > 0
-                    and raw_width_bits(row.attr_at(cols - 1))
-                    == int(WidthRole.SPACER_HEAD)
-                    and raw_width_bits(snapshot._rows[r_idx + 1].attr_at(0))
-                    == int(WidthRole.WIDE)
-                )
-                limit = max(0, cols - 1) if has_spacer_head else cols
-            else:
-                limit = min(cols, row.text_used)
-            for c in range(limit):
-                rb = raw_width_bits(row.attr_at(c))
-                if rb in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)):
-                    continue
-                set_pen(_vt_cell_pen(row, c))
-                write_glyph(r_idx, c)
-            if not eff_wrapped and row.used > limit:
-                cur_col_pos = limit
-                span_c = limit
-                row_used = min(cols, row.used)
-                while span_c < row_used:
-                    pen = _vt_cell_pen(row, span_c)
-                    end_c = span_c + 1
-                    while end_c < row_used and _vt_cell_pen(row, end_c) == pen:
-                        end_c += 1
-                    if pen != _DEFAULT_VT_PEN:
-                        if cur_col_pos != span_c:
-                            move_cursor(r_idx, span_c)
-                            cur_col_pos = span_c
-                        set_pen(pen)
-                        if pen.protected or pen.hyperlink is not None:
-                            out.append(" " * (end_c - span_c))
-                            cur_col_pos = end_c
-                        elif end_c == cols:
-                            out.append("\x1b[K")
-                        else:
-                            out.append(f"\x1b[{end_c - span_c}X")
-                    span_c = end_c
-        margins = snapshot._scroll_region
-        if (margins.top, margins.bottom) != (0, n_rows - 1):
-            out.append(f"\x1b[{margins.top + 1};{margins.bottom + 1}r")
-        left, right = 0, cols - 1
-        if Mode.DECLRMM in export_modes:
-            out.append("\x1b[?69h")
-            left, right = margins.left, margins.right
-            if (left, right) != (0, cols - 1):
-                out.append(f"\x1b[{left + 1};{right + 1}s")
-        positioned_modes = ALT_SCREEN_MODES | {Mode.DECLRMM, Mode.IRM}
-        for mode in sorted(export_modes - positioned_modes, key=int):
-            raw = int(mode)
-            if raw & DEC_PRIVATE_MASK:
-                code = raw & ~DEC_PRIVATE_MASK
-                if mode not in (
-                    Mode.DECCOLM,
-                    Mode.DECAWM,
-                    Mode.AUTO_REPEAT,
-                    Mode.DECTCEM,
-                    Mode.ALTERNATE_SCROLL,
-                    Mode.GRAPHEME_CLUSTERING,
-                ) and not (mode == Mode.ALLOW_80_132 and Mode.DECCOLM in export_modes):
-                    out.append(f"\x1b[?{code}h")
-            else:
-                out.append(f"\x1b[{raw}h")
-        if Mode.DECAWM not in export_modes:
-            out.append("\x1b[?7l")
-        if Mode.AUTO_REPEAT not in export_modes:
-            out.append("\x1b[?8l")
-        if Mode.DECTCEM not in export_modes:
-            out.append("\x1b[?25l")
-        if Mode.ALTERNATE_SCROLL not in export_modes:
-            out.append("\x1b[?1007l")
-        cur = snapshot.cursor
-        if (cur.shape, cur.blinking) != (CursorShape.BLOCK, True):
-            decscusr_map: dict[tuple[CursorShape, bool], int] = {
-                (CursorShape.BLOCK, False): 2,
-                (CursorShape.UNDERLINE, True): 3,
-                (CursorShape.UNDERLINE, False): 4,
-                (CursorShape.BAR, True): 5,
-                (CursorShape.BAR, False): 6,
-            }
-            ps = decscusr_map.get((cur.shape, cur.blinking), 1)
-            out.append(f"\x1b[{ps} q")
-        origin = Mode.DECOM in export_modes
-        row_offset, col_offset = (margins.top, left) if origin else (0, 0)
-        wrap = _vt_wrap_position(snapshot, left=left, right=right)
-        r, c, glyph_col = wrap if wrap is not None else (cur.row, cur.col, None)
-        move_cursor(r - row_offset, c - col_offset)
-        if glyph_col is not None:
-            row = snapshot._rows[cur.row]
-            set_pen(_vt_cell_pen(row, glyph_col))
-            write_glyph(cur.row, glyph_col)
-        set_grapheme_mode(Mode.GRAPHEME_CLUSTERING in export_modes)
-        if Mode.IRM in export_modes:
-            out.append("\x1b[4h")
-        set_pen(snapshot._vt_pen)
-        return "".join(out)
-
-    def _render_html(self, snapshot: Snapshot) -> str:
-        r"""Render *snapshot* as an HTML ``
`` block.
-
-        References
-        ----------
-        - `VT510 Video Terminal Programmer Information — DECSCNM
-          `__
-
-        Examples
-        --------
-        >>> from libvt.terminal import OutputFormat, Terminal
-        >>> term = Terminal(rows=1, cols=4)
-        >>> term.feed(b"\x1b[?5h\x1b[31mR")
-        >>> "color:rgb(205,0,0)" in term.snapshot().format(OutputFormat.HTML)
-        True
-        """
-        app = snapshot.appearance
-        scr_fg, scr_bg = (
-            (app.bg_rgb, app.fg_rgb) if app.reverse_video else (app.fg_rgb, app.bg_rgb)
-        )
-        if app.reverse_video or (scr_fg, scr_bg) != (
-            DEFAULT_APPEARANCE.fg_rgb,
-            DEFAULT_APPEARANCE.bg_rgb,
-        ):
-            pre_tag = (
-                '
'
-            )
-        else:
-            pre_tag = '
'
-        lines: list[str] = [pre_tag]
-        allow_unsafe = self.policy.allow_unsafe_uris
-        ul_styles = {
-            UnderlineStyle.DOUBLE: "double",
-            UnderlineStyle.CURLY: "wavy",
-            UnderlineStyle.DOTTED: "dotted",
-            UnderlineStyle.DASHED: "dashed",
-        }
-        for rows in _row_groups(snapshot._rows, unwrap=self.unwrap):
-            runs = (
-                _unwrapped_style_runs(rows)
-                if self.unwrap
-                else (
-                    (run.text, run.style, run.hyperlink)
-                    for run in RowView(rows[0]).runs
-                )
-            )
-            chunks: list[str] = []
-            for run_text, style, hyperlink in runs:
-                escaped = html.escape(run_text)
-                css: list[str] = []
-                background: str | None = None
-                if style.bold:
-                    css.append("font-weight:bold")
-                if style.dim:
-                    css.append("opacity:0.65")
-                if style.italic:
-                    css.append("font-style:italic")
-                if style.reverse:
-                    fg_r, fg_g, fg_b = app.resolve_rgb(
-                        style.bg,
-                        default_rgb=scr_bg,
-                    )
-                    bg_r, bg_g, bg_b = app.resolve_rgb(
-                        style.fg,
-                        default_rgb=scr_fg,
-                    )
-                    css.append(f"color:rgb({fg_r},{fg_g},{fg_b})")
-                    background = f"background-color:rgb({bg_r},{bg_g},{bg_b})"
-                else:
-                    if style.fg is not None:
-                        fg_r, fg_g, fg_b = app.resolve_rgb(
-                            style.fg,
-                            default_rgb=scr_fg,
-                        )
-                        css.append(f"color:rgb({fg_r},{fg_g},{fg_b})")
-                    if style.bg is not None:
-                        bg_r, bg_g, bg_b = app.resolve_rgb(
-                            style.bg,
-                            default_rgb=scr_bg,
-                        )
-                        background = f"background-color:rgb({bg_r},{bg_g},{bg_b})"
-                if background is not None and not style.hidden:
-                    css.append(background)
-                dec_lines: list[str] = []
-                if style.underline != UnderlineStyle.NONE:
-                    dec_lines.append("underline")
-                if style.overline:
-                    dec_lines.append("overline")
-                if style.strikethrough:
-                    dec_lines.append("line-through")
-                if dec_lines:
-                    css.append(f"text-decoration-line:{' '.join(dec_lines)}")
-                ul_css = ul_styles.get(style.underline)
-                if ul_css is not None:
-                    css.append(f"text-decoration-style:{ul_css}")
-                if style.underline_color is not None:
-                    ur, ug, ub = app.resolve_rgb(
-                        style.underline_color,
-                        default_rgb=scr_fg,
-                    )
-                    css.append(f"text-decoration-color:rgb({ur},{ug},{ub})")
-                span = (
-                    f'{escaped}'
-                    if css
-                    else escaped
-                )
-                if hyperlink is not None and (
-                    allow_unsafe or _is_safe_uri(hyperlink.uri)
-                ):
-                    href = html.escape(hyperlink.uri, quote=True)
-                    span = f'{span}'
-                if style.hidden:
-                    span = f'{span}'
-                    if background is not None:
-                        span = f'{span}'
-                chunks.append(span)
-            lines.append("".join(chunks))
-        lines.append("
") - return "\n".join(lines) - - class _TerminalSink: """Private ``ActionSink`` forwarding parser actions into :class:`Terminal`.""" @@ -2060,11 +607,6 @@ def _parse_ascii_uint_bytes(raw: bytes, *, max_val: int) -> int | None: return acc -def _format_osc_rgb(rgb: tuple[int, int, int]) -> str: - r, g, b = rgb - return f"rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}" - - def _parse_ascii_hex(raw: str) -> int | None: if not raw: return None @@ -3914,13 +2456,13 @@ def feed(self, data: collections.abc.Buffer, /) -> None: │line 2 │ └──────────┘ """ - mv = _byte_view(data) - if not mv: - return - if self._recorder is not None: - self._recorder.record(mv) - self._parser.feed_to(mv, self._sink) - self._generation += 1 + with _byte_view(data) as mv: + if not mv: + return + if self._recorder is not None: + self._recorder.record(mv) + self._parser.feed_to(mv, self._sink) + self._generation += 1 def feed_until( self, @@ -3940,74 +2482,74 @@ def feed_until( >>> step.stopped_on == StopOn.SYNC_END, term.committed.lines, buf[step.offset:] (True, ('frame 1',), b'trailing') """ - mv = _byte_view(data) - n = len(mv) - if offset < 0 or offset > n: - msg = f"offset {offset} out of range for buffer of length {n}" - raise ValueError(msg) - idx = offset - while idx < n: - self._step_event = StopOn.NONE - state = self._parser.state - - # Bulk-advance GROUND printable ASCII when StopOn.GROUND is not requested. - if ( - state == ParserState.GROUND - and not self._parser.utf8_pending - and not (stop & StopOn.GROUND) - ): - ascii_m = _PRINT_ASCII_RE.match(mv, idx) - if ascii_m is not None: - end = ascii_m.end() - span = mv[idx:end] - if self._recorder is not None: - self._recorder.record(span) - self._parser.feed_to(span, self._sink) - idx = end - self._generation += 1 - continue + with _byte_view(data) as mv: + n = len(mv) + if offset < 0 or offset > n: + msg = f"offset {offset} out of range for buffer of length {n}" + raise ValueError(msg) + idx = offset + while idx < n: + self._step_event = StopOn.NONE + state = self._parser.state + + # Bulk-advance GROUND printable ASCII unless StopOn.GROUND is set. + if ( + state == ParserState.GROUND + and not self._parser.utf8_pending + and not (stop & StopOn.GROUND) + ): + ascii_m = _PRINT_ASCII_RE.match(mv, idx) + if ascii_m is not None: + end = ascii_m.end() + span = mv[idx:end] + if self._recorder is not None: + self._recorder.record(span) + self._parser.feed_to(span, self._sink) + idx = end + self._generation += 1 + continue - # Bulk-advance interior payload bytes inside OSC / DCS / APC strings. - if state in ( - ParserState.OSC_STRING, - ParserState.DCS_PASSTHROUGH, - ParserState.SOS_PM_APC_STRING, - ): - body_re = ( - _STR_BODY_LATIN1_RE - if self._parser.encoding == "latin-1" - else _STR_BODY_UTF8_RE - ) - body_m = body_re.match(mv, idx) - if body_m is not None: - end = body_m.end() - span = mv[idx:end] - if self._recorder is not None: - self._recorder.record(span) - self._parser.feed_to(span, self._sink) - idx = end - self._generation += 1 - continue + # Bulk-advance interior payload bytes inside OSC / DCS / APC strings. + if state in ( + ParserState.OSC_STRING, + ParserState.DCS_PASSTHROUGH, + ParserState.SOS_PM_APC_STRING, + ): + body_re = ( + _STR_BODY_LATIN1_RE + if self._parser.encoding == "latin-1" + else _STR_BODY_UTF8_RE + ) + body_m = body_re.match(mv, idx) + if body_m is not None: + end = body_m.end() + span = mv[idx:end] + if self._recorder is not None: + self._recorder.record(span) + self._parser.feed_to(span, self._sink) + idx = end + self._generation += 1 + continue - one = mv[idx : idx + 1] - if self._recorder is not None: - self._recorder.record(one) - self._parser.feed_to(one, self._sink) - idx += 1 - self._generation += 1 - matched = self._step_event & stop - if ( - (stop & StopOn.GROUND) - and self._parser.state == ParserState.GROUND - and not self._parser.utf8_pending - ): - matched |= StopOn.GROUND - if matched: - return StepResult(offset=idx, stopped_on=matched) - return StepResult( - offset=n, - stopped_on=StopOn.EOF, - ) + one = mv[idx : idx + 1] + if self._recorder is not None: + self._recorder.record(one) + self._parser.feed_to(one, self._sink) + idx += 1 + self._generation += 1 + matched = self._step_event & stop + if ( + (stop & StopOn.GROUND) + and self._parser.state == ParserState.GROUND + and not self._parser.utf8_pending + ): + matched |= StopOn.GROUND + if matched: + return StepResult(offset=idx, stopped_on=matched) + return StepResult( + offset=n, + stopped_on=StopOn.EOF, + ) # --- Internal sink handlers --- @@ -7547,6 +6089,7 @@ def strip(data: collections.abc.Buffer | str, /) -> str: "ResyncReason", "ScreenDelta", "Snapshot", + "SnapshotDict", "StepResult", "StopOn", "SyncToken", diff --git a/src/libvt/views.py b/src/libvt/views.py new file mode 100644 index 00000000..a571ed44 --- /dev/null +++ b/src/libvt/views.py @@ -0,0 +1,1186 @@ +"""Read-only cursor, cell, row, history, and rectangular region views.""" + +from __future__ import annotations + +import bisect +import collections.abc +import enum +import operator +import sys +import typing as t +from dataclasses import dataclass + +from libvt._grid import ( + _EMPTY_FROZEN_HISTORY, + _PEN_BASE_MASK, + FrozenRow, + RowLike, + _CellExt, + _FrozenHistory, + _Row, + raw_width_bits, + unpack_style, + unpack_width_role, +) +from libvt._ucd import WidthRole +from libvt.style import DEFAULT_STYLE, Hyperlink, Style + +if t.TYPE_CHECKING: + from libvt.screen import Screen + +_ITEM0 = operator.itemgetter(0) + + +class CursorShape(enum.StrEnum): + """Cursor glyph shape configured via ``DECSCUSR`` (``CSI Ps SP q``).""" + + BLOCK = "block" + UNDERLINE = "underline" + BAR = "bar" + + +@dataclass(frozen=True, slots=True) +class Cursor: + """Zero-based cursor state on a :class:`~libvt.screen.Screen`. + + Attributes + ---------- + row : int + Zero-based row index in ``0..rows - 1``. + col : int + Zero-based column index in ``0..cols - 1``. + visible : bool + Whether the cursor is visible (``DECTCEM`` ``?25``). + shape : CursorShape + Visual cursor shape. + blinking : bool + Whether cursor blinking is active. + pending_wrap : bool + ``True`` when a glyph filled ``cols - 1`` under ``DECAWM`` and the + next printable character will wrap to the next line. + """ + + row: int = 0 + col: int = 0 + visible: bool = True + shape: CursorShape = CursorShape.BLOCK + blinking: bool = True + pending_wrap: bool = False + + +@dataclass(frozen=True, slots=True) +class ScrollRegion: + """Inclusive zero-based scroll margin bounds (``DECSTBM`` / ``DECSLRM``). + + Attributes + ---------- + top : int + Top margin row index (inclusive, ``0``-based). + bottom : int + Bottom margin row index (inclusive, ``0``-based). + left : int + Left margin column index (inclusive, ``0``-based). + right : int + Right margin column index (inclusive, ``0``-based). + """ + + top: int + bottom: int + left: int + right: int + + +@dataclass(frozen=True, slots=True) +class Cell: + r"""Immutable view of a single terminal grid cell. + + Attributes + ---------- + text : str + Grapheme cluster string (``" "`` for narrow blanks, ``""`` for + :attr:`WidthRole.SPACER_TAIL` and :attr:`WidthRole.SPACER_HEAD`). + style : Style + Unpacked SGR rendition attributes. + width_role : WidthRole + Column occupancy role (narrow, wide lead, or spacer). + hyperlink : Hyperlink | None + Active ``OSC 8`` hyperlink, when present. + protected : bool + ``DECSCA`` protection attribute respected by ``DECSED`` / ``DECSEL``. + + Examples + -------- + >>> term = Terminal(rows=1, cols=8) + >>> term.feed("\x1b[1;32m日\x1b[0mok".encode()) + >>> snap = term.committed + >>> snap[0, 0].text, snap[0, 0].width, snap[0, 0].style.bold + ('日', 2, True) + >>> snap[0, 1].width_role.name, snap[0, 1].width + ('SPACER_TAIL', 0) + """ + + text: str = " " + style: Style = DEFAULT_STYLE + width_role: WidthRole = WidthRole.NARROW + hyperlink: Hyperlink | None = None + protected: bool = False + + @property + def width(self) -> int: + """Return column width (``2`` wide, ``0`` spacer, ``1`` narrow).""" + if self.width_role == WidthRole.WIDE: + return 2 + if self.width_role in (WidthRole.SPACER_TAIL, WidthRole.SPACER_HEAD): + return 0 + return 1 + + @property + def is_blank(self) -> bool: + """Return ``True`` when the cell holds an unstyled narrow space.""" + return ( + self.text == " " + and self.style == DEFAULT_STYLE + and self.width_role == WidthRole.NARROW + and self.hyperlink is None + ) + + +BLANK_CELL = Cell() + + +@dataclass(frozen=True, slots=True) +class RowRun: + r"""Contiguous run of identically styled cells within a :class:`RowView`. + + Attributes + ---------- + start_col : int + Inclusive zero-based start column. + end_col : int + Exclusive zero-based end column. + text : str + Rendered text across ``start_col..end_col`` (omitting spacer empty strings). + style : Style + Shared :class:`~libvt.style.Style` across the run. + hyperlink : Hyperlink | None + Shared ``OSC 8`` hyperlink across the run, if any. + + Examples + -------- + >>> term = Terminal(rows=1, cols=12) + >>> term.feed(b"\x1b[1;32mPASS\x1b[0m test") + >>> [(r.start_col, r.end_col, r.text, r.style.bold) for r in term.committed[0].runs] + [(0, 4, 'PASS', True), (4, 10, ' test', False)] + """ + + start_col: int + end_col: int + text: str + style: Style = DEFAULT_STYLE + hyperlink: Hyperlink | None = None + + +def _materialize_cell(row: RowLike, col: int) -> Cell: + ch = row.char_at(col) + word = row.attr_at(col) + if word == 0 and ch == " ": + return BLANK_CELL + ext = row.ext_at(col) + style = unpack_style(word, ext) + role = unpack_width_role(word) + hyperlink = ext.hyperlink if ext is not None else None + protected = bool(ext is not None and ext.protected) + return Cell( + text=ch, + style=style, + width_role=role, + hyperlink=hyperlink, + protected=protected, + ) + + +def _normalize_index(idx: int, length: int, *, axis: str) -> int: + norm = idx + length if idx < 0 else idx + if norm < 0 or norm >= length: + msg = f"{axis} index {idx} out of range for size {length}" + raise IndexError(msg) + return norm + + +def _slice_indices(s: slice, length: int) -> range: + start, stop, step = s.indices(length) + if step != 1: + msg = "grid slices only support step=1" + raise ValueError(msg) + return range(start, stop) + + +def _frozen_row_runs( + row: FrozenRow, + start_c: int, + limit: int, +) -> tuple[RowRun, ...]: + """Coalesce ``(style, hyperlink)`` spans on *row* in ``O(runs + exts)``.""" + if not row.runs and not row.exts and row.cells is None: + t_len = len(row.text) + if limit <= t_len: + txt = row.text[start_c:limit] + elif start_c >= t_len: + txt = " " * (limit - start_c) + else: + txt = row.text[start_c:t_len] + (" " * (limit - t_len)) + return ( + RowRun( + start_col=start_c, + end_col=limit, + text=txt, + style=DEFAULT_STYLE, + hyperlink=None, + ), + ) + + out: list[RowRun] = [] + runs = row.runs + exts = row.exts + r_len = len(runs) + e_len = len(exts) + r_idx = bisect.bisect_right(runs, start_c, key=_ITEM0) if r_len else 0 + e_idx = bisect.bisect_left(exts, start_c, key=_ITEM0) if e_len else 0 + + has_cur = False + run_start = start_c + cur_style = DEFAULT_STYLE + cur_link: Hyperlink | None = None + buf: list[str] = [] + pos = start_c + + while pos < limit: + if r_idx < r_len: + raw_r_end, word = runs[r_idx] + r_end = min(limit, raw_r_end) + else: + raw_r_end = limit + 1 + word = 0 + r_end = limit + + while e_idx < e_len and exts[e_idx][0] < pos: + e_idx += 1 + if e_idx >= e_len: + ext: _CellExt | None = None + e_end = limit + elif exts[e_idx][0] > pos: + ext = None + e_end = min(limit, exts[e_idx][0]) + else: + ext = exts[e_idx][1] + scan_c = pos + 1 + scan_i = e_idx + 1 + while ( + scan_c < r_end + and scan_i < e_len + and exts[scan_i][0] == scan_c + and exts[scan_i][1] == ext + ): + scan_c += 1 + scan_i += 1 + e_end = scan_c + e_idx = scan_i + + seg_end = min(r_end, e_end) + if seg_end == raw_r_end: + r_idx += 1 + + role_bits = raw_width_bits(word) + if role_bits in (int(WidthRole.SPACER_TAIL), int(WidthRole.SPACER_HEAD)): + if not has_cur: + cur_style = unpack_style(word, ext) + cur_link = ext.hyperlink if ext is not None else None + run_start = pos + has_cur = True + pos = seg_end + continue + + if row.cells is not None: + c_len = len(row.cells) + if seg_end <= c_len: + seg_txt = "".join(row.cells[pos:seg_end]) + elif pos >= c_len: + seg_txt = " " * (seg_end - pos) + else: + seg_txt = "".join(row.cells[pos:c_len]) + (" " * (seg_end - c_len)) + else: + t_len = len(row.text) + if seg_end <= t_len: + seg_txt = row.text[pos:seg_end] + elif pos >= t_len: + seg_txt = " " * (seg_end - pos) + else: + seg_txt = row.text[pos:t_len] + (" " * (seg_end - t_len)) + + st = unpack_style(word, ext) + lnk = ext.hyperlink if ext is not None else None + if not has_cur: + run_start = pos + cur_style = st + cur_link = lnk + buf = [seg_txt] + has_cur = True + elif st != cur_style or lnk != cur_link: + out.append( + RowRun( + start_col=run_start, + end_col=pos, + text="".join(buf), + style=cur_style, + hyperlink=cur_link, + ), + ) + run_start = pos + cur_style = st + cur_link = lnk + buf = [seg_txt] + else: + buf.append(seg_txt) + pos = seg_end + + out.append( + RowRun( + start_col=run_start, + end_col=limit, + text="".join(buf), + style=cur_style, + hyperlink=cur_link, + ), + ) + return tuple(out) + + +def _live_row_runs( + row: _Row, + start_c: int, + limit: int, +) -> tuple[RowRun, ...]: + """Coalesce ``(style, hyperlink)`` spans on a mutable :class:`_Row`.""" + attrs = row._attrs + chars = row._chars + ext_map = row._ext + + if attrs is None and not ext_map and not row._has_wide: + return ( + RowRun( + start_col=start_c, + end_col=limit, + text="".join(chars[start_c:limit]), + style=unpack_style(row._uniform_attr, None), + hyperlink=None, + ), + ) + + if attrs is not None and not ext_map and not row._has_wide: + cur_word = attrs[start_c] + if attrs[limit - 1] == cur_word and attrs.count(cur_word) == len(attrs): + return ( + RowRun( + start_col=start_c, + end_col=limit, + text="".join(chars[start_c:limit]), + style=unpack_style(cur_word, None), + hyperlink=None, + ), + ) + out: list[RowRun] = [] + run_start = start_c + for c in range(start_c + 1, limit): + word = attrs[c] + if word != cur_word: + out.append( + RowRun( + start_col=run_start, + end_col=c, + text="".join(chars[run_start:c]), + style=unpack_style(cur_word, None), + hyperlink=None, + ), + ) + run_start = c + cur_word = word + out.append( + RowRun( + start_col=run_start, + end_col=limit, + text="".join(chars[run_start:limit]), + style=unpack_style(cur_word, None), + hyperlink=None, + ), + ) + return tuple(out) + + out = [] + run_start = start_c + first_word = row._uniform_attr if attrs is None else attrs[start_c] + first_ext = ext_map.get(start_c) if ext_map else None + cur_word = first_word + cur_base = first_word & _PEN_BASE_MASK + cur_ext = first_ext + cur_style = unpack_style(first_word, first_ext) + cur_link = first_ext.hyperlink if first_ext is not None else None + buf: list[str] = [] + spacer_tail = int(WidthRole.SPACER_TAIL) + spacer_head = int(WidthRole.SPACER_HEAD) + + for c in range(start_c, limit): + word = row._uniform_attr if attrs is None else attrs[c] + role_bits = raw_width_bits(word) + if role_bits in (spacer_tail, spacer_head): + continue + ext = ext_map.get(c) if ext_map else None + ch = chars[c] + if word == cur_word and ext is cur_ext: + buf.append(ch) + continue + base = word & _PEN_BASE_MASK + if base == cur_base and ext == cur_ext: + cur_word = word + cur_ext = ext + buf.append(ch) + continue + st = unpack_style(word, ext) + lnk = ext.hyperlink if ext is not None else None + if st != cur_style or lnk != cur_link: + out.append( + RowRun( + start_col=run_start, + end_col=c, + text="".join(buf), + style=cur_style, + hyperlink=cur_link, + ), + ) + run_start = c + cur_style = st + cur_link = lnk + buf = [ch] + else: + buf.append(ch) + cur_word = word + cur_base = base + cur_ext = ext + + out.append( + RowRun( + start_col=run_start, + end_col=limit, + text="".join(buf), + style=cur_style, + hyperlink=cur_link, + ), + ) + return tuple(out) + + +def _format_display_row(row: RowLike, start_c: int, stop_c: int) -> str: + """Format ``row[start_c:stop_c]`` padded and clipped to column width.""" + if stop_c <= start_c: + return "" + if isinstance(row, _Row): + if not row.has_wide: + r_cols = row.cols + if stop_c <= r_cols: + return row.slice_text(start_c, stop_c) + if start_c >= r_cols: + return " " * (stop_c - start_c) + return row.slice_text(start_c, r_cols) + (" " * (stop_c - r_cols)) + elif not row.runs and row.cells is None: + t_len = len(row.text) + if stop_c <= t_len: + return row.text[start_c:stop_c] + if start_c >= t_len: + return " " * (stop_c - start_c) + return row.text[start_c:t_len] + (" " * (stop_c - t_len)) + + limit = max(start_c, min(stop_c, row.used)) + parts: list[str] = [] + for c in range(start_c, limit): + role = raw_width_bits(row.attr_at(c)) + if role == int(WidthRole.SPACER_TAIL): + if c == start_c: + parts.append(" ") + elif role == int(WidthRole.SPACER_HEAD): + parts.append(" ") + elif role == int(WidthRole.WIDE): + parts.append(row.char_at(c) if c + 1 < stop_c else " ") + else: + parts.append(row.char_at(c)) + if stop_c > limit: + parts.append(" " * (stop_c - limit)) + return "".join(parts) + + +class RowView(collections.abc.Sequence[Cell]): + r"""Read-only sequence view over one live viewport or scrollback row. + + A whole live row follows its backing row's width. A slice retains its + selected columns and clips them to the live width. Frozen rows keep their + captured width. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"long_line") + >>> row0 = term.committed[0] + >>> row0.text, row0.wrapped, len(row0) + ('long_lin', True, 8) + """ + + __slots__ = ("_col_range", "_row", "_row_idx", "_screen") + + def __init__( + self, + row: RowLike, + col_range: range | None = None, + *, + screen: Screen | None = None, + row_idx: int = -1, + ) -> None: + self._row = row + self._screen = screen + self._row_idx = row_idx + self._col_range = col_range + + def _current_row(self) -> RowLike: + if self._screen is not None and 0 <= self._row_idx < len(self._screen._rows): + return self._screen._rows[self._row_idx] + return self._row + + def _columns_for(self, row: RowLike) -> range: + cols = self._col_range + if cols is None: + return range(row.cols) + if isinstance(row, _Row) and cols.stop > row.cols: + return range(cols.start, row.cols, cols.step) + return cols + + @property + def columns(self) -> range: + """Return the source columns currently visible through this row.""" + return self._columns_for(self._current_row()) + + @property + def used(self) -> int: + """Return the number of visible columns through the last written cell.""" + row = self._current_row() + cols = self._columns_for(row) + return max(0, min(cols.stop, row.used) - cols.start) + + @property + def text_used(self) -> int: + """Return the visible text extent, excluding trailing background-only cells.""" + row = self._current_row() + cols = self._columns_for(row) + return max(0, min(cols.stop, row.text_used) - cols.start) + + @property + def full_row(self) -> RowView: + """Return the uncropped row with the same live or frozen backing.""" + if self._col_range is None: + return self + return RowView(self._current_row(), screen=self._screen, row_idx=self._row_idx) + + @property + def wrapped(self) -> bool: + """Return ``True`` when this row soft-wrapped onto the next line.""" + return self._current_row().wrapped + + @property + def text(self) -> str: + """Return right-trimmed rendered text for this row slice.""" + row = self._current_row() + cols = self._columns_for(row) + row_t_used = ( + row.text_used + if isinstance(row, _Row) + else (len(row.cells) if row.cells is not None else len(row.text)) + ) + if cols.start == 0 and cols.stop >= row_t_used: + return row.rstrip_text() + limit = min(cols.stop, row_t_used) + if limit <= cols.start: + return "" + if isinstance(row, _Row): + raw = row.slice_text(cols.start, limit) + else: + raw = "".join(row.char_at(c) for c in range(cols.start, limit)) + return raw.rstrip(" ") + + @property + def display_text(self) -> str: + """Return space-padded text spanning ``len(self)`` terminal columns.""" + row = self._current_row() + cols = self._columns_for(row) + return _format_display_row(row, cols.start, cols.stop) + + @property + def runs(self) -> tuple[RowRun, ...]: + """Return coalesced ``(style, hyperlink)`` spans up to ``used`` columns.""" + row = self._current_row() + cols = self._columns_for(row) + limit = min(cols.stop, row.used) + start_c = cols.start + if limit <= start_c: + return () + if isinstance(row, FrozenRow): + return _frozen_row_runs(row, start_c, limit) + return _live_row_runs(row, start_c, limit) + + def __len__(self) -> int: + """Return column count in this view.""" + return len(self._columns_for(self._current_row())) + + @t.overload + def __getitem__(self, index: int) -> Cell: ... + + @t.overload + def __getitem__(self, index: slice) -> RowView: ... + + def __getitem__(self, index: int | slice) -> Cell | RowView: + """Index one :class:`Cell` or slice a sub-range :class:`RowView`.""" + row = self._current_row() + cols = self._columns_for(row) + if isinstance(index, slice): + sub = _slice_indices(index, len(cols)) + base = cols.start + return RowView( + row, + range(base + sub.start, base + sub.stop), + screen=self._screen, + row_idx=self._row_idx, + ) + norm = _normalize_index(index, len(cols), axis="col") + return _materialize_cell(row, cols.start + norm) + + def __eq__(self, other: object) -> bool: + """Compare two :class:`RowView` instances by wrapped state and cells.""" + if self is other: + return True + if not isinstance(other, RowView): + return NotImplemented + r1 = self._current_row() + r2 = other._current_row() + c1 = self._columns_for(r1) + c2 = other._columns_for(r2) + if len(c1) != len(c2): + return False + if r1 is r2 and c1 == c2: + return True + if c1 == c2 and c1.start == 0 and c1.step == 1: + f1 = r1.freeze() if isinstance(r1, _Row) else r1 + f2 = r2.freeze() if isinstance(r2, _Row) else r2 + if c1.stop >= max(f1.used, f2.used): + return _frozen_content_key(f1) == _frozen_content_key(f2) + if r1.wrapped != r2.wrapped: + return False + return all(a == b for a, b in zip(self, other, strict=True)) + + +def _frozen_content_key( + fr: FrozenRow, +) -> tuple[ + bool, + str, + tuple[tuple[int, int], ...], + tuple[tuple[int, _CellExt], ...], + tuple[str, ...] | None, +]: + return ( + fr.wrapped, + fr.text, + fr.runs, + fr.exts, + fr.cells, + ) + + +def _row_view_to_full_frozen(value: object) -> tuple[int, FrozenRow] | None: + if not isinstance(value, RowView): + return None + r = value._current_row() + fr = r.freeze() if isinstance(r, _Row) else r + cols = value._columns_for(r) + if cols.start == 0 and cols.step == 1 and len(cols) >= fr.used: + return len(cols), fr + return None + + +class _HistoryView(collections.abc.Sequence[RowView]): + """Lazy ``O(1)`` immutable sequence view over scrollback :class:`RowView` lines.""" + + __slots__ = ("_cols", "_data", "_range") + + def __init__( + self, + data: _FrozenHistory | None = None, + index_range: range | None = None, + *, + cols: int | None = None, + ) -> None: + eff = _EMPTY_FROZEN_HISTORY if data is None else data + self._data = eff + self._range = range(len(eff)) if index_range is None else index_range + self._cols = cols + + def _eff_cols(self, fr: FrozenRow) -> int: + if self._cols is None: + return fr.cols + return max(self._cols, fr.used) + + def _wrap_row(self, fr: FrozenRow) -> RowView: + return RowView(fr, range(self._eff_cols(fr))) + + def __len__(self) -> int: + """Return number of scrollback rows in this view.""" + return len(self._range) + + def __bool__(self) -> bool: + """Return ``True`` when at least one scrollback row is present.""" + return bool(self._range) + + @t.overload + def __getitem__(self, index: int) -> RowView: ... + + @t.overload + def __getitem__(self, index: slice) -> _HistoryView: ... + + def __getitem__(self, index: int | slice) -> RowView | _HistoryView: + """Index one :class:`RowView` in ``O(1)`` or slice a sub-view.""" + if isinstance(index, slice): + return _HistoryView(self._data, self._range[index], cols=self._cols) + if isinstance(index, bool) or not isinstance(index, int): + msg = f"history indices must be int or slice, got {type(index).__name__}" + raise TypeError(msg) + return self._wrap_row(self._data.at(self._range[index])) + + def __contains__(self, value: object) -> bool: + """Return ``True`` when *value* matches a scrollback :class:`RowView`.""" + if not isinstance(value, RowView): + return False + v_len = len(value) + if self._cols is not None and v_len < self._cols: + return False + full = _row_view_to_full_frozen(value) + r = self._range + if full is None: + at = self._data.at + return any( + self._eff_cols(fr := at(idx)) == v_len and self._wrap_row(fr) == value + for idx in r + ) + v_cols, target_fr = full + target_key = _frozen_content_key(target_fr) + if r.start == 0 and r.stop == len(self._data) and r.step == 1: + return any( + self._eff_cols(fr) == v_cols and _frozen_content_key(fr) == target_key + for fr in self._data + ) + at = self._data.at + return any( + self._eff_cols(fr := at(idx)) == v_cols + and _frozen_content_key(fr) == target_key + for idx in r + ) + + def count(self, value: object) -> int: + """Return count of scrollback rows equal to *value*.""" + if not isinstance(value, RowView): + return 0 + v_len = len(value) + if self._cols is not None and v_len < self._cols: + return 0 + full = _row_view_to_full_frozen(value) + at = self._data.at + if full is None: + return sum( + 1 + for idx in self._range + if self._eff_cols(fr := at(idx)) == v_len + and self._wrap_row(fr) == value + ) + v_cols, target_fr = full + target_key = _frozen_content_key(target_fr) + return sum( + 1 + for idx in self._range + if self._eff_cols(fr := at(idx)) == v_cols + and _frozen_content_key(fr) == target_key + ) + + def index( + self, + value: object, + start: int = 0, + stop: int = sys.maxsize, + ) -> int: + """Return first zero-based index of *value* in ``[start, stop)``.""" + if isinstance(value, RowView): + v_len = len(value) + if self._cols is None or v_len >= self._cols: + sub_indices = range(len(self._range))[start:stop] + full = _row_view_to_full_frozen(value) + at = self._data.at + if full is None: + for pos in sub_indices: + fr = at(self._range[pos]) + if self._eff_cols(fr) == v_len and self._wrap_row(fr) == value: + return pos + else: + v_cols, target_fr = full + target_key = _frozen_content_key(target_fr) + for pos in sub_indices: + fr = at(self._range[pos]) + if ( + self._eff_cols(fr) == v_cols + and _frozen_content_key(fr) == target_key + ): + return pos + msg = "RowView is not in history" + raise ValueError(msg) + + def __iter__(self) -> collections.abc.Iterator[RowView]: + """Yield :class:`RowView` items across this view.""" + r = self._range + if not r: + return + if r.start == 0 and r.stop == len(self._data) and r.step == 1: + for fr in self._data: + yield self._wrap_row(fr) + return + at = self._data.at + for idx in r: + yield self._wrap_row(at(idx)) + + def __reversed__(self) -> collections.abc.Iterator[RowView]: + """Yield :class:`RowView` items in reverse order.""" + at = self._data.at + for idx in reversed(self._range): + yield self._wrap_row(at(idx)) + + def __eq__(self, other: object) -> bool: + """Compare two :class:`_HistoryView` instances by view-width rows.""" + if self is other: + return True + if not isinstance(other, _HistoryView): + return NotImplemented + if len(self._range) != len(other._range): + return False + if not self._range: + return True + if ( + self._data is other._data + and self._range == other._range + and self._cols == other._cols + ): + return True + return all( + self._eff_cols(f1 := self._data.at(i)) + == other._eff_cols(f2 := other._data.at(j)) + and _frozen_content_key(f1) == _frozen_content_key(f2) + for i, j in zip(self._range, other._range, strict=True) + ) + + def __repr__(self) -> str: + """Return concise summary representation.""" + return f"HistoryView(len={len(self._range)})" + + +class RegionView(collections.abc.Sequence[RowView]): + r"""Read-only 2D rectangular slice view over ``(rows, cols)``. + + A live region follows the width of its retained rows. Regions from a + snapshot or its viewport use the geometry captured with the frame. + + Examples + -------- + >>> from libvt.testing import serialize_vt_snapshot + >>> term = Terminal(rows=3, cols=10) + >>> term.feed(b"header\r\n\x1b[1mitem 1\x1b[0m\r\nitem 2") + >>> region = term.committed[1:3, 0:6] + >>> print(serialize_vt_snapshot(region)) + size=6x2 region=True + ┌──────┐ + │item 1│ + │item 2│ + └──────┘ + styles: + r0[0..6]: bold + """ + + __slots__ = ("_col_range", "_live_rows", "_parent_cols", "_rows") + + def __init__( + self, + rows: collections.abc.Sequence[RowLike], + col_range: range, + *, + parent_cols: int | None = None, + live: bool = True, + ) -> None: + self._rows = tuple(rows) + self._live_rows = ( + tuple(row for row in self._rows if isinstance(row, _Row)) if live else () + ) + self._col_range = col_range + self._parent_cols = ( + max((row.cols for row in self._rows), default=col_range.stop) + if parent_cols is None + else parent_cols + ) + + def _source_width(self) -> int: + if self._live_rows: + return min(row.cols for row in self._live_rows) + return self._parent_cols + + @property + def columns(self) -> range: + """Return the selected column coordinates in the source grid.""" + columns = self._col_range + if self._live_rows and (width := self._source_width()) < columns.stop: + return range(columns.start, width, columns.step) + return columns + + @property + def rows(self) -> int: + """Return height of this region in rows.""" + return len(self._rows) + + @property + def cols(self) -> int: + """Return width of this region in columns.""" + return len(self.columns) + + @property + def lines(self) -> tuple[str, ...]: + """Return right-trimmed text for each row in the region.""" + return tuple(row.text for row in self) + + @property + def display_lines(self) -> tuple[str, ...]: + """Return space-padded text of width ``cols`` for each row in the region.""" + return tuple(row.display_text for row in self) + + @property + def text(self) -> str: + """Return newline-joined text with trailing empty rows omitted.""" + lines = list(self.lines) + while lines and lines[-1] == "": + lines.pop() + return "\n".join(lines) + + @property + def unwrapped_text(self) -> str: + r"""Return newline-joined text, unwrapping full-width soft-wrapped rows. + + Full-width row slices (such as ``snap[0:5]`` or + :meth:`~libvt.terminal.Snapshot.viewport`) join contiguous + ``row.wrapped`` rows without ``"\n"`` when their original right margin + is visible. The current frame determines + the slice width even when history contains rows sealed at a different + width. Column crops return :attr:`text`. + + Examples + -------- + >>> term = Terminal(rows=3, cols=8) + >>> term.feed(b"hello world\r\nok") + >>> snap = term.committed + >>> snap[0:2].unwrapped_text, snap[0:2, 0:4].unwrapped_text + ('hello world', 'hell\nrld') + """ + columns = self.columns + if ( + columns.start == 0 + and columns.step == 1 + and columns.stop >= self._source_width() + ): + return _unwrapped_text(self._rows, visible_cols=len(columns)) + return self.text + + def __iter__(self) -> collections.abc.Iterator[RowView]: + """Iterate over rows using the current rectangular extent.""" + columns = self.columns + return (RowView(row, columns) for row in self._rows) + + def __len__(self) -> int: + """Return number of rows in this region.""" + return len(self._rows) + + @t.overload + def __getitem__(self, key: int) -> RowView: ... + + @t.overload + def __getitem__(self, key: tuple[int, int]) -> Cell: ... + + @t.overload + def __getitem__( + self, + key: slice | tuple[int, slice] | tuple[slice, int] | tuple[slice, slice], + ) -> RegionView: ... + + @t.overload + def __getitem__( + self, + key: tuple[slice | int, slice | int], + ) -> Cell | RegionView: ... + + def __getitem__( + self, + key: int | slice | tuple[slice | int, slice | int], + ) -> RowView | Cell | RegionView: + """Index a row, single ``(row, col)`` cell, or 2D region view.""" + return slice_grid( + self._rows, + self._source_width(), + key, + columns=self.columns, + live=bool(self._live_rows), + ) + + +def _row_groups( + rows: collections.abc.Sequence[RowLike], + *, + unwrap: bool, + visible_cols: int | None = None, +) -> collections.abc.Iterator[collections.abc.Sequence[RowLike]]: + start = 0 + for end, row in enumerate(rows, 1): + if ( + not unwrap + or not row.wrapped + or (visible_cols is not None and row.cols > visible_cols) + ): + yield rows[start:end] + start = end + if start < len(rows): + yield rows[start:] + + +def _unwrapped_rows( + group: collections.abc.Sequence[RowLike], *, include_styles: bool +) -> collections.abc.Iterator[tuple[RowLike, int]]: + end = len(group) + while end > 0: + last = group[end - 1] + used = last.used if include_styles else last.text_used + if used: + break + end -= 1 + + for index, row in enumerate(group[:end]): + padding = 0 + if index + 1 < end: + used = row.used if include_styles else row.text_used + # The high-water marks count the wide-wrap spacer at the right edge. + padding = max(0, row.cols - used) + yield row, padding + + +def _unwrapped_text( + rows: collections.abc.Sequence[RowLike], *, visible_cols: int | None = None +) -> str: + lines = ( + "".join( + row.rstrip_text() + " " * padding + for row, padding in _unwrapped_rows(group, include_styles=False) + ) + for group in _row_groups(rows, unwrap=True, visible_cols=visible_cols) + ) + return "\n".join(lines).rstrip("\n") + + +def format_rows_text( + rows: collections.abc.Sequence[RowLike], + *, + unwrap: bool = False, +) -> str: + r"""Format *rows* as newline-joined text omitting trailing blank lines. + + Parameters + ---------- + rows : collections.abc.Sequence[RowLike] + Viewport or scrollback rows to format. + unwrap : bool + When ``True``, join contiguous ``row.wrapped`` continuation rows onto + the same logical line without inserting ``"\n"``. + + Returns + ------- + str + Rendered text with trailing blank lines omitted. + + Examples + -------- + >>> term = Terminal(rows=2, cols=8) + >>> term.feed(b"hello world") + >>> term.screen.text, term.screen.unwrapped_text + ('hello wo\nrld', 'hello world') + """ + if unwrap: + return _unwrapped_text(rows) + lines = [r.rstrip_text() for r in rows] + while lines and lines[-1] == "": + lines.pop() + return "\n".join(lines) + + +def _grid_span(index: int | slice, size: int, *, axis: str) -> slice: + if isinstance(index, slice): + span = _slice_indices(index, size) + return slice(span.start, span.stop) + if isinstance(index, int): + at = _normalize_index(index, size, axis=axis) + return slice(at, at + 1) + msg = f"unsupported {axis} index {index!r}" + raise TypeError(msg) + + +def slice_grid( + rows: collections.abc.Sequence[RowLike], + cols: int, + key: int | slice | tuple[slice | int, slice | int], + *, + screen: Screen | None = None, + columns: range | None = None, + live: bool = False, +) -> RowView | Cell | RegionView: + """Index a grid or a rectangular view in its own coordinates.""" + height = len(rows) + if isinstance(key, int): + nr = _normalize_index(key, height, axis="row") + return RowView(rows[nr], columns, screen=screen, row_idx=nr) + visible = range(cols) if columns is None else columns + r_key, c_key = (key, slice(None)) if isinstance(key, slice) else key + if isinstance(r_key, int) and isinstance(c_key, int): + nr = _normalize_index(r_key, height, axis="row") + nc = _normalize_index(c_key, len(visible), axis="col") + return _materialize_cell(rows[nr], visible[nc]) + row_span = _grid_span(r_key, height, axis="row") + col_span = _grid_span(c_key, len(visible), axis="col") + return RegionView( + rows[row_span], + visible[col_span], + parent_cols=cols, + live=screen is not None or live, + ) + + +__all__ = [ + "BLANK_CELL", + "Cell", + "Cursor", + "CursorShape", + "RegionView", + "RowRun", + "RowView", + "ScrollRegion", + "format_rows_text", + "slice_grid", +] diff --git a/tests/test_libvt.py b/tests/test_libvt.py index 55c93777..89bd7574 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -332,3 +332,81 @@ def test_documented_examples_include_explicit_imports( res = doctest.DocTestRunner(optionflags=flags).run(dt, clear_globs=False) assert res.failed == 0, f"{rel}[{idx}] failed without implicit imports" assert res.attempted >= 1 + + +def test_core_split_has_no_screen_to_terminal_cycle_and_keeps_reexports() -> None: + """``screen``/``views``/``snapshot``/``format`` never import ``libvt.terminal``.""" + repo_root = pathlib.Path(__file__).resolve().parent.parent + checked = ( + "src/libvt/screen.py", + "src/libvt/views.py", + "src/libvt/_reflow.py", + "src/libvt/snapshot.py", + "src/libvt/format.py", + "src/libvt/_util.py", + ) + for rel in checked: + tree = ast.parse((repo_root / rel).read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + assert not alias.name.startswith("libvt.terminal"), rel + elif isinstance(node, ast.ImportFrom): + mod = node.module or "" + assert not mod.startswith("libvt.terminal"), rel + + isolation_script = ( + "import sys; " + "from libvt.screen import Screen; " + "from libvt.format import OutputFormat; " + "s = Screen(rows=2, cols=8); " + "s.put_text(0, 0, 'ok'); " + "snap = s.snapshot(); " + "s.blit(snap); " + "assert snap.format(OutputFormat.PLAIN) == 'ok'; " + "assert 'libvt.terminal' not in sys.modules; " + "assert 'libvt.parser' not in sys.modules; " + "assert 'libvt.graphics' not in sys.modules" + ) + proc = subprocess.run( + (sys.executable, "-c", isolation_script), + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, proc.stderr + + import libvt._util as util_mod + import libvt.format as fmt_mod + import libvt.screen as screen_mod + import libvt.snapshot as snap_mod + import libvt.terminal as term_mod + import libvt.views as views_mod + + for name in ( + "BLANK_CELL", + "Cell", + "Cursor", + "CursorShape", + "RegionView", + "RowRun", + "RowView", + "ScrollRegion", + "format_rows_text", + "slice_grid", + ): + assert getattr(screen_mod, name) is getattr(views_mod, name) + for name in ( + "ResyncReason", + "ScreenDelta", + "Snapshot", + "SnapshotDict", + "SyncToken", + "SyncView", + ): + assert getattr(term_mod, name) is getattr(snap_mod, name) + for name in ("Formatter", "OutputFormat"): + assert getattr(term_mod, name) is getattr(fmt_mod, name) + assert callable(util_mod._byte_view) + assert callable(util_mod._parse_ascii_uint) + assert callable(util_mod._parse_ascii_int) diff --git a/tests/test_screen.py b/tests/test_screen.py index b667b39b..c203fab6 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -12,13 +12,13 @@ import pytest import libvt -from libvt._grid import _Row, raw_width_bits +from libvt._grid import _Row, make_cell_ext, pack_pen_base, raw_width_bits from libvt._ucd import WidthRole from libvt.config import DEFAULT_PROFILE, Profile, ScreenBehavior, UnicodeBehavior from libvt.events import InBandResize from libvt.modes import Mode from libvt.profiles import GHOSTTY_PROFILE, XTERM_PROFILE -from libvt.screen import Cursor, Screen +from libvt.screen import Cursor, RowView, Screen from libvt.style import ( AnsiColor, Hyperlink, @@ -1201,3 +1201,68 @@ def test_sever_dangling_wrap_on_erase_display_erase_line_decaln_and_edit() -> No assert post_wide.history[-1][4].width_role == WidthRole.NARROW assert t_wide.lines[0] == expected_r0.rstrip(" ") _assert_grid_invariants(t_wide) + + +def test_row_view_runs_fast_paths_match_frozen_row() -> None: + """``RowView.runs`` fast paths on ``_Row`` match ``FrozenRow`` across slices.""" + t_default = libvt.Terminal(rows=1, cols=8) + t_default.feed(b"hello") + assert t_default.screen._rows[0]._attrs is None + + t_bce = libvt.Terminal(rows=1, cols=8) + t_bce.feed(b"\x1b[42m\x1b[2J") + assert t_bce.screen._rows[0]._attrs is None + + t_green = libvt.Terminal(rows=1, cols=8) + t_green.feed(b"\x1b[32m" + b"A" * 8) + assert t_green.screen._rows[0]._attrs is not None + + t_multi = libvt.Terminal(rows=1, cols=10) + t_multi.feed(b"\x1b[31mAA\x1b[32mBBB\x1b[1;34mCC\x1b[0mDD") + + t_wide = libvt.Terminal(rows=2, cols=7) + t_wide.feed("\x1b[32mA日本B日".encode()) + + t_ext = libvt.Terminal(rows=1, cols=12) + t_ext.feed( + b'\x1b[32m\x1b[1"qPP\x1b[0"qUU' + b"\x1b]8;;https://a.test\x07LL\x1b]8;;\x07" + b"\x1b[58:2::10:20:30mCC\x1b[59mDD" + ) + + r_uniform_ext = _Row(6) + p_ext = make_cell_ext(Style(fg=AnsiColor.GREEN), None, protected=True) + r_uniform_ext.reset_blank(6, pack_pen_base(Style(fg=AnsiColor.GREEN)), p_ext) + + r_distinct_ext = _Row(6) + e1 = make_cell_ext(Style(), Hyperlink(uri="https://x.test", id="1")) + e2 = make_cell_ext(Style(), Hyperlink(uri="https://x.test", id="1")) + r_distinct_ext.write_narrow(0, "a", 0, e1) + r_distinct_ext.write_narrow(1, "b", 0, e2) + r_distinct_ext.write_wide(2, "日", 0, e1) + r_distinct_ext.write_narrow(4, "c", 0, None) + + rows = ( + t_default.screen._rows[0], + t_bce.screen._rows[0], + t_green.screen._rows[0], + t_multi.screen._rows[0], + t_wide.screen._rows[0], + t_wide.screen._rows[1], + t_ext.screen._rows[0], + r_uniform_ext, + r_distinct_ext, + ) + for row in rows: + frozen = row.freeze() + for start in range(row.cols + 1): + for stop in range(start, row.cols + 1): + assert ( + RowView(row, range(start, stop)).runs + == RowView(frozen, range(start, stop)).runs + ) + # DECSCA protected cells coalesce with adjacent unprotected cells of equal style. + assert t_ext.screen[0].runs[0].text == "PPUU" + r_distinct_ext_runs = RowView(r_distinct_ext).runs + assert len(r_distinct_ext_runs) == 2 + assert r_distinct_ext_runs[0].text == "ab日" From dede8d0033bd109a91d785a18239a1d483c3247f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 08:16:56 -0600 Subject: [PATCH 2/4] terminal(refactor): Add slots, dispatch, recorder why: Bound Terminal memory with __slots__, move CSI/OSC/ESC/DCS dispatch out of terminal.py, add a typed recorder seam without monkey-patching, and centralize donor state transfer in replace_from. what: - Extract recorder.py with TerminalRecorder, FlightRecorder, CompositeRecorder, and find_flight_recorder - Extract _vt_dispatch.py for CSI/OSC/ESC/DCS handling - Add single-truth private mode support helpers in modes.py - Add Terminal.__slots__, _attach_recorder, _attach_reply_sink, _resize_internal, batched feed_until recording, and replace_from - Switch tmux control adoption to Terminal.replace_from --- src/libvt/_vt_dispatch.py | 2015 ++++++++++++++++++++++ src/libvt/aio.py | 3 +- src/libvt/contrib/tmux/control.py | 48 +- src/libvt/modes.py | 101 ++ src/libvt/recorder.py | 164 ++ src/libvt/terminal.py | 2661 +++++------------------------ src/libvt/testing.py | 3 +- tests/test_libvt.py | 3 + tests/test_terminal.py | 384 ++++- tests/test_tmux.py | 11 + 10 files changed, 3115 insertions(+), 2278 deletions(-) create mode 100644 src/libvt/_vt_dispatch.py create mode 100644 src/libvt/recorder.py diff --git a/src/libvt/_vt_dispatch.py b/src/libvt/_vt_dispatch.py new file mode 100644 index 00000000..a7fc7277 --- /dev/null +++ b/src/libvt/_vt_dispatch.py @@ -0,0 +1,2015 @@ +"""VT sequence dispatch (CSI, OSC, ESC, DCS) and wire-format helpers for Terminal.""" + +from __future__ import annotations + +import base64 +import binascii +import typing as t + +from libvt._grid import _PEN_BG_MASK +from libvt._ucd import display_width, sanitize_terminal_text +from libvt._util import _parse_ascii_int, _parse_ascii_uint +from libvt.config import ClipboardReadPolicy +from libvt.events import ( + ClipboardReadRequested, + ClipboardWrite, + ColorSchemeQueried, + CwdSource, + EraseCause, + Notification, + NotificationSource, + NotificationUrgency, + Passthrough, + ProgramStatusChanged, + PromptKind, + Rect, + ShellCommandReported, + ShellPropertyChanged, + SixelData, + SixelGraphic, + TitleChanged, + TitleTarget, +) +from libvt.format import _format_osc_rgb, _style_to_sgr +from libvt.modes import ( + ALT_SCREEN_MODES, + DEC_PRIVATE_MASK, + Mode, + is_private_mode_supported, +) +from libvt.parser import CsiParams, Parser, parse_sgr +from libvt.screen import ScrollRegion +from libvt.style import Hyperlink +from libvt.views import CursorShape + +if t.TYPE_CHECKING: + from libvt.terminal import Terminal + +_OSC52_SELECTION_BYTES: frozenset[int] = frozenset(b"cpqs01234567") + +_TERMINFO_CAPS: dict[str, str] = { + "TN": "xterm-256color", + "Co": "256", + "colors": "256", + "RGB": "8/8/8", + "Tc": "", + "Smulx": "\x1b[4:%p1%dm", + "Setulc": "\x1b[58:2::%p1%{65536}%/%d:%p1%{256}%/%{255}%&%d:%p1%{255}%&%dm", + "Sync": "\x1b[?2026%?%p1%{1}%-%tl%eh%;", +} + + +def _parse_ascii_uint_bytes(raw: bytes, *, max_val: int) -> int | None: + if not raw: + return None + acc = 0 + for b in raw: + if not (0x30 <= b <= 0x39): + return None + acc = acc * 10 + (b - 0x30) + if acc > max_val: + return None + return acc + + +def _parse_ascii_hex(raw: str) -> int | None: + if not raw: + return None + acc = 0 + for ch in raw: + code = ord(ch) + if 0x30 <= code <= 0x39: + digit = code - 0x30 + elif 0x41 <= code <= 0x46: + digit = code - 0x41 + 10 + elif 0x61 <= code <= 0x66: + digit = code - 0x61 + 10 + else: + return None + acc = (acc << 4) | digit + return acc + + +def _parse_osc_rgb(spec: bytes) -> tuple[int, int, int] | None: + try: + text = spec.decode("ascii").strip() + except UnicodeDecodeError: + return None + if text.startswith("#") and len(text) == 7: + r = _parse_ascii_hex(text[1:3]) + g = _parse_ascii_hex(text[3:5]) + b = _parse_ascii_hex(text[5:7]) + if r is None or g is None or b is None: + return None + return (r, g, b) + if text.lower().startswith("rgb:"): + parts = text[4:].split("/") + if len(parts) != 3: + return None + vals: list[int] = [] + for comp in parts: + if not (1 <= len(comp) <= 4): + return None + raw = _parse_ascii_hex(comp) + if raw is None: + return None + scale = (1 << (4 * len(comp))) - 1 + vals.append((raw * 255) // scale) + return (vals[0], vals[1], vals[2]) + return None + + +def _parse_osc52_selection(raw: bytes) -> str | None: + r"""Validate an ``OSC 52`` selection designator token against ``[cpqs0-7]*``. + + Parameters + ---------- + raw : bytes + Bytes preceding the first ``;`` inside an ``OSC 52`` payload. + + Returns + ------- + str | None + Validated ASCII selection string (``"c"`` when *raw* is empty), or + ``None`` if *raw* exceeds ``16`` bytes or contains any byte outside + ``cpqs01234567``. + + References + ---------- + - `xterm Control Sequences — Manipulate Selection Data (OSC 52) + `__ + - `tmux/tmux input.c — input_osc_52 (3.8) + `__ + + Examples + -------- + >>> from libvt._vt_dispatch import _parse_osc52_selection + >>> _parse_osc52_selection(b""), _parse_osc52_selection(b"pc") + ('c', 'pc') + >>> _parse_osc52_selection(b"\x00evil"), _parse_osc52_selection(b"\xff") + (None, None) + """ + if not raw: + return "c" + if len(raw) > 16 or any(b not in _OSC52_SELECTION_BYTES for b in raw): + return None + return raw.decode("ascii") + + +def _hex_encode(text: str) -> str: + return text.encode("utf-8").hex() + + +def _unescape_osc_633(raw: str) -> str: + r"""Decode ``OSC 633`` backslash and ``\xAB`` hex-byte escape sequences. + + VS Code shell-integration scripts serialize ``\`` as ``\\`` and ``;`` plus + control bytes ``0x00..0x20`` as ``\xAB`` so semicolons inside command text + or paths never collide with ``OSC 633`` field delimiters. Split ``OSC 633`` + fields on ``;`` first, then pass each field through :func:`_unescape_osc_633`. + Consecutive ``\xAB`` escapes are buffered and decoded together as UTF-8. + + Parameters + ---------- + raw : str + Single semicolon-delimited ``OSC 633`` field before unescaping. + + Returns + ------- + str + Unescaped field string. + + References + ---------- + - `VS Code Terminal Shell Integration — Escaping values + `__ + - `microsoft/vscode osc633Parser.ts (1.148.0) + `__ + - `microsoft/vscode shellIntegrationAddon.ts (1.148.0) + `__ + + Examples + -------- + >>> from libvt._vt_dispatch import _unescape_osc_633 + >>> _unescape_osc_633(r"printf \\x3b\x3becho\x0aok") + 'printf \\x3b;echo\nok' + >>> _unescape_osc_633(r"/tmp/\xe6\x97\xa5\xe6\x9c\xac") + '/tmp/日本' + """ + if "\\" not in raw: + return raw + out: list[str] = [] + hex_buf = bytearray() + i = 0 + n = len(raw) + while i < n: + if raw[i] == "\\" and i + 1 < n: + nxt = raw[i + 1] + if nxt in ("x", "X") and i + 3 < n: + hv = _parse_ascii_hex(raw[i + 2 : i + 4]) + if hv is not None: + hex_buf.append(hv) + i += 4 + continue + if hex_buf: + out.append(hex_buf.decode("utf-8", errors="replace")) + hex_buf.clear() + if nxt == "\\": + out.append("\\") + i += 2 + continue + if hex_buf: + out.append(hex_buf.decode("utf-8", errors="replace")) + hex_buf.clear() + out.append(raw[i]) + i += 1 + if hex_buf: + out.append(hex_buf.decode("utf-8", errors="replace")) + return "".join(out) + + +def _cap_sanitized_bytes( + raw: bytes | bytearray, + max_bytes: int, +) -> tuple[str, int]: + r"""Decode, sanitize, and cap *raw* UTF-8 bytes to at most *max_bytes*. + + Examples + -------- + >>> from libvt._vt_dispatch import _cap_sanitized_bytes + >>> _cap_sanitized_bytes(b"ok\x01", 6) + ('ok\\x01', 6) + >>> _cap_sanitized_bytes(b"ok\x01", 5) + ('ok', 2) + """ + if max_bytes <= 0 or not raw: + return ("", 0) + decoded = bytes(raw[:max_bytes]).decode("utf-8", errors="ignore") + sanitized = sanitize_terminal_text(decoded) + enc = sanitized.encode("utf-8") + if len(enc) <= max_bytes: + return (sanitized, len(enc)) + out: list[str] = [] + used = 0 + for ch in decoded: + frag = sanitize_terminal_text(ch) + cost = len(frag.encode("utf-8")) + if used + cost > max_bytes: + break + out.append(frag) + used += cost + return ("".join(out), used) + + +def handle_esc(term: Terminal, intermediates: bytes, final: int) -> None: + """Dispatch a completed ``ESC`` sequence onto *term*.""" + term._interrupt_rep() + scr = term._screens.active + if not intermediates: + if final == 0x37: # ESC 7 DECSC + term._save_cursor() + elif final == 0x38: # ESC 8 DECRC + term._restore_cursor() + elif final == 0x44: # ESC D IND + term._linefeed(scr) + elif final == 0x45: # ESC E NEL + term._linefeed(scr, carriage_return=True) + elif final == 0x48: # ESC H HTS + scr.add_tabstop(scr._cur_col) + elif final == 0x4D: # ESC M RI + term._before_mutate() + top, bottom, left, right = term._effective_margins(scr) + keep_wrap = ( + term._profile.screen.pending_wrap_phantom_col and scr._pending_wrap + ) + if scr._cur_row == top and left <= scr._cur_col <= right: + scr.scroll_down( + 1, + top=top, + bottom=bottom, + left=left, + right=right, + bce_word=term._pen_word & _PEN_BG_MASK, + ) + term._notify_erase( + Rect(top, left, 1, right - left + 1), + EraseCause.SCROLL, + ) + term._clear_cluster_anchor() + elif scr._cur_row > 0: + term._set_cursor( + scr, + scr._cur_row - 1, + scr._cur_col, + pending_wrap=keep_wrap, + ) + elif final == 0x4E: # ESC N SS2 -> G2 + term._single_shift = 2 + elif final == 0x4F: # ESC O SS3 -> G3 + term._single_shift = 3 + elif final == 0x6E: # ESC n LS2 -> G2 + term._gl = 2 + elif final == 0x6F: # ESC o LS3 -> G3 + term._gl = 3 + elif final == 0x63: # ESC c RIS + term.reset(soft=False) + elif final == 0x3D: # ESC = DECKPAM + term._apply_mode(66, private=True, enabled=True) + elif final == 0x3E: # ESC > DECKPNM + term._apply_mode(66, private=True, enabled=False) + else: + term._unhandled("esc", f"ESC {chr(final)}") + elif intermediates in (b"(", b")", b"*", b"+"): + slot = {b"(": 0, b")": 1, b"*": 2, b"+": 3}[intermediates] + desig = chr(final) + if desig in ("0", "A", "B", "U"): + term._g_sets[slot] = desig + else: + term._g_sets[slot] = "B" + elif intermediates == b"%" and final in (0x40, 0x47): # ISO-2022 DOCS + if term._profile.screen.allow_encoding_switch: + if final == 0x47: # ESC % G -> UTF-8 + if not term._docs_utf8_active: + term._before_mutate() + term._saved_docs_charset = ( + ( + term._g_sets[0], + term._g_sets[1], + term._g_sets[2], + term._g_sets[3], + ), + term._gl, + term._single_shift, + ) + term._g_sets = [ + "B", + term._profile.screen.default_g1_charset, + "B", + "B", + ] + term._gl = 0 + term._single_shift = None + term._docs_utf8_active = True + elif term._docs_utf8_active: # ESC % @ -> legacy 8-bit + term._before_mutate() + if term._saved_docs_charset is not None: + saved_g, saved_gl, saved_ss = term._saved_docs_charset + term._g_sets = list(saved_g) + term._gl = saved_gl + term._single_shift = saved_ss + term._saved_docs_charset = None + term._docs_utf8_active = False + elif intermediates == b"#" and final == 0x38: # DECALN + term._before_mutate() + scr._sever_incoming_wrap(0) + fill = "E" * scr.cols + for r in scr._rows: + r.reset_blank(scr.cols) + r.write_ascii_slice(0, fill, 0, None) + scr.scroll_region = ScrollRegion( + top=0, + bottom=scr.rows - 1, + left=0, + right=scr.cols - 1, + ) + term._set_cursor(scr, 0, 0, pending_wrap=False) + else: + inter_s = intermediates.decode("ascii", errors="replace") + term._unhandled("esc", f"ESC {inter_s}{chr(final)}") + + +def handle_xtsmgraphics(term: Terminal, params: CsiParams) -> None: + r"""Handle ``XTSMGRAPHICS`` (``CSI ? Pi ; Pa ; Pv S``) register queries. + + Supports color-register count (``Pi = 1``) and ``SIXEL`` pixel geometry + (``Pi = 2``) across read (``Pa = 1``), reset (``Pa = 2``), set + (``Pa = 3``), and read-maximum (``Pa = 4``), clamped by + :attr:`~libvt.config.Limits.max_image_dimension` and + :attr:`~libvt.config.QueryBehavior.max_sixel_color_registers`. Replies + ``CSI ? Pi ; 3 S`` when disabled or unsupported so ``SIXEL`` clients + never stall. + + References + ---------- + - `xterm Control Sequences — XTSMGRAPHICS (CSI ? Pi ; Pa ; Pv S) + `__ + - `tmux/tmux input.c — input_csi_dispatch_sm_graphics (3.8) + `__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(rows=10, cols=20) + >>> term.feed(b"\x1b[?1;1;0S\x1b[?2;1;0S") + >>> term.drain_replies() + b'\x1b[?1;0;256S\x1b[?2;0;160;160S' + """ + q_cfg = term._profile.queries + if not q_cfg.xtsmgraphics_enabled: + return + pi = params.raw_or_default(0, 0) + pa = params.raw_or_default(1, 0) + if not term._policy.track_graphics or params.colon_mask != 0: + term._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) + return + if pi not in (1, 2, 3): + term._emit_reply(f"\x1b[?{pi};1S".encode("ascii")) + return + if pa not in (1, 2, 3, 4): + term._emit_reply(f"\x1b[?{pi};2S".encode("ascii")) + return + + if pi == 1: + max_regs = q_cfg.max_sixel_color_registers + def_regs = min(q_cfg.sixel_color_registers, max_regs) + if pa == 1: + term._emit_reply( + f"\x1b[?1;0;{term._sixel_color_registers}S".encode("ascii"), + ) + elif pa == 2: + if term._sixel_color_registers != def_regs: + term._before_mutate() + term._sixel_color_registers = def_regs + term._emit_reply(f"\x1b[?1;0;{def_regs}S".encode("ascii")) + elif ( + pa == 3 + and q_cfg.xtsmgraphics_set_enabled + and len(params.values) == 3 + and ((params.omitted_mask >> 2) & 1) == 0 + and params.values[2] >= 2 + ): + clamped_regs = min(params.values[2], max_regs) + if term._sixel_color_registers != clamped_regs: + term._before_mutate() + term._sixel_color_registers = clamped_regs + term._emit_reply(f"\x1b[?1;0;{clamped_regs}S".encode("ascii")) + elif pa == 4: + term._emit_reply(f"\x1b[?1;0;{max_regs}S".encode("ascii")) + else: + term._emit_reply(b"\x1b[?1;3S") + return + + if pi == 2 and q_cfg.xtsmgraphics_geometry_enabled: + cw = term._profile.screen.cell_width_px + ch = term._profile.screen.cell_height_px + max_dim = term._limits.max_image_dimension + if cw <= 0 or ch <= 0 or max_dim <= 0: + term._emit_reply(b"\x1b[?2;3S") + return + def_w = min(max_dim, term.cols * cw) + def_h = min(max_dim, term.rows * ch) + if pa == 1: + cur_w, cur_h = ( + term._sixel_geometry_px + if term._sixel_geometry_px is not None + else (def_w, def_h) + ) + term._emit_reply( + f"\x1b[?2;0;{min(max_dim, cur_w)};{min(max_dim, cur_h)}S".encode( + "ascii", + ), + ) + elif pa == 2: + if term._sixel_geometry_px is not None: + term._before_mutate() + term._sixel_geometry_px = None + term._emit_reply(f"\x1b[?2;0;{def_w};{def_h}S".encode("ascii")) + elif ( + pa == 3 + and q_cfg.xtsmgraphics_set_enabled + and len(params.values) == 4 + and (params.omitted_mask & 0b1100) == 0 + and params.values[2] >= 1 + and params.values[3] >= 1 + ): + clamped_geo = ( + min(params.values[2], max_dim), + min(params.values[3], max_dim), + ) + if term._sixel_geometry_px != clamped_geo: + term._before_mutate() + term._sixel_geometry_px = clamped_geo + term._emit_reply( + f"\x1b[?2;0;{clamped_geo[0]};{clamped_geo[1]}S".encode("ascii"), + ) + elif pa == 4: + term._emit_reply(f"\x1b[?2;0;{max_dim};{max_dim}S".encode("ascii")) + else: + term._emit_reply(b"\x1b[?2;3S") + return + + term._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) + + +def xtsave_modes(term: Terminal, params: CsiParams) -> None: + r"""Save DEC private mode flags for ``XTSAVE`` (``CSI ? Pm s``). + + When *params* carries no arguments (``CSI ? s``), snapshots every + profile-supported DEC private mode except ``?1048``; otherwise saves + each explicit ``Pm`` code while ignoring omitted parameters. + + Parameters + ---------- + term : Terminal + Target terminal emulator instance. + params : CsiParams + Parsed ``CSI ? ... s`` parameter list. + + References + ---------- + - `xterm Control Sequences — XTSAVE (CSI ? Pm s) + `__ + - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) + `__ + - `tmux/tmux input.c (3.8) + `__ + + Examples + -------- + >>> from libvt.modes import Mode + >>> from libvt.terminal import Terminal + >>> term = Terminal(rows=4, cols=10) + >>> term.feed(b"\x1b[?2004h\x1b[?2004s\x1b[?2004l") + >>> term.modes.is_set(Mode.BRACKETED_PASTE) + False + >>> term._saved_private_modes[Mode.BRACKETED_PASTE] + True + """ + if not term._profile.screen.xtsave_enabled: + return + prof = term._profile + if not params.values: + entered_alt = next( + iter(term._modes.enabled_modes() & ALT_SCREEN_MODES), + Mode.ALT_SCREEN, + ) + for alt_m in ALT_SCREEN_MODES: + if alt_m != entered_alt: + term._saved_private_modes.pop(alt_m, None) + targets = [ + m + for m in Mode + if (int(m) & DEC_PRIVATE_MASK) + and m not in (Mode.DECSC_1048, Mode.SYNCHRONIZED_OUTPUT) + and (m not in ALT_SCREEN_MODES or m == entered_alt) + and is_private_mode_supported(m, prof) + ] + else: + targets = [] + for idx, code in enumerate(params.values): + if (params.omitted_mask >> idx) & 1: + continue + if not (0 <= code < DEC_PRIVATE_MASK): + continue + try: + m = Mode(DEC_PRIVATE_MASK | code) + except ValueError: + continue + if m != Mode.DECSC_1048 and is_private_mode_supported(m, prof): + targets.append(m) + for m in targets: + if m in ALT_SCREEN_MODES: + for alt_m in ALT_SCREEN_MODES: + if alt_m != m: + term._saved_private_modes.pop(alt_m, None) + term._saved_private_modes[m] = term._screens.active_is_alt + else: + term._saved_private_modes[m] = term._modes.is_set(m) + + +def xtrestore_modes(term: Terminal, params: CsiParams) -> None: + r"""Restore saved DEC private modes for ``XTRESTORE`` (``CSI ? Pm r``). + + Applies each previously saved mode whose effective state differs from + the saved value through :meth:`~libvt.terminal.Terminal._apply_mode` so + screen-switching (``?1049``), synchronized-output (``?2026``), and margin + (``?69``) transitions execute identically to ``DECSET`` / ``DECRST`` + without disturbing unchanged modes. + + Parameters + ---------- + term : Terminal + Target terminal emulator instance. + params : CsiParams + Parsed ``CSI ? ... r`` parameter list. + + References + ---------- + - `xterm Control Sequences — XTRESTORE (CSI ? Pm r) + `__ + - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) + `__ + + Examples + -------- + >>> from libvt.modes import Mode + >>> from libvt.terminal import Terminal + >>> term = Terminal(rows=4, cols=10) + >>> term.feed(b"\x1b[?2004h\x1b[?2004s\x1b[?2004l\x1b[?2004r") + >>> term.modes.is_set(Mode.BRACKETED_PASTE) + True + """ + if not term._profile.screen.xtsave_enabled or not term._saved_private_modes: + return + if not params.values: + items = [ + (m, v) + for m, v in term._saved_private_modes.items() + if m != Mode.SYNCHRONIZED_OUTPUT + ] + else: + items = [] + for idx, code in enumerate(params.values): + if (params.omitted_mask >> idx) & 1: + continue + if not (0 <= code < DEC_PRIVATE_MASK): + continue + try: + m = Mode(DEC_PRIVATE_MASK | code) + except ValueError: + continue + if m in ALT_SCREEN_MODES: + saved_alt = next( + ( + term._saved_private_modes[alt_m] + for alt_m in ALT_SCREEN_MODES + if alt_m in term._saved_private_modes + ), + None, + ) + if saved_alt is not None: + items.append((m, saved_alt)) + elif m in term._saved_private_modes: + items.append((m, term._saved_private_modes[m])) + items.sort( + key=lambda item: ( + 0 + if item[0] == Mode.DECNCSM + else ( + 1 + if ( + item[0] != Mode.DECCOLM + and not (item[0] == Mode.ALLOW_80_132 and not item[1]) + ) + else (2 if item[0] == Mode.DECCOLM else 3) + ) + ), + ) + for m, saved_enabled in items: + cur_enabled = ( + term._screens.active_is_alt + if m in ALT_SCREEN_MODES + else term._modes.is_set(m) + ) + if cur_enabled == saved_enabled: + continue + term._apply_mode( + int(m) & ~DEC_PRIVATE_MASK, + private=True, + enabled=saved_enabled, + ) + + +def _handle_plain_csi( + term: Terminal, + params: CsiParams, + final: int, + prev_printed: str, +) -> None: + """Dispatch unprefixed, intermediate-free CSI sequences (hot path).""" + scr = term._screens.active + if final in (0x48, 0x66): # H / f: CUP / HVP + row_1 = params.get(0, 1) + col_1 = params.get(1, 1) + if term._modes.is_set(Mode.DECOM): + top, bottom, left, right = term._effective_margins(scr) + r = min(bottom, max(top, top + row_1 - 1)) + c = min(right, max(left, left + col_1 - 1)) + else: + r = min(scr.rows - 1, max(0, row_1 - 1)) + c = min(scr.cols - 1, max(0, col_1 - 1)) + term._set_cursor(scr, r, c) + return + if final == 0x4B: # K: EL + term._erase_line(scr, params.raw_or_default(0, 0), selective=False) + return + if final == 0x4A: # J: ED + term._erase_display(scr, params.raw_or_default(0, 0), selective=False) + return + if final in (0x68, 0x6C): # h / l: SM / RM + enable = final == 0x68 + for val in params.values: + term._apply_mode(val, private=False, enabled=enable) + return + + top, bottom, left, right = term._effective_margins(scr) + c_row = scr._cur_row + c_col = scr._cur_col + + if final == 0x41: # A: CUU + n = params.get(0, 1) + floor = top if c_row >= top else 0 + term._set_cursor(scr, max(floor, c_row - n), c_col) + elif final == 0x42: # B: CUD + n = params.get(0, 1) + ceil = bottom if c_row <= bottom else scr.rows - 1 + term._set_cursor(scr, min(ceil, c_row + n), c_col) + elif final == 0x43: # C: CUF + n = params.get(0, 1) + ceil = right if c_col <= right else scr.cols - 1 + term._set_cursor(scr, c_row, min(ceil, c_col + n)) + elif final == 0x44: # D: CUB + term._cursor_left(scr, params.get(0, 1), is_backspace=False) + elif final == 0x45: # E: CNL + n = params.get(0, 1) + ceil = bottom if c_row <= bottom else scr.rows - 1 + term._set_cursor(scr, min(ceil, c_row + n), left) + elif final == 0x46: # F: CPL + n = params.get(0, 1) + floor = top if c_row >= top else 0 + term._set_cursor(scr, max(floor, c_row - n), left) + elif final in (0x47, 0x60): # G / `: CHA / HPA + col_1 = params.get(0, 1) + if term._modes.is_set(Mode.DECOM): + target_c = min(right, left + col_1 - 1) + else: + target_c = min(scr.cols - 1, col_1 - 1) + term._set_cursor(scr, c_row, max(0, target_c)) + elif final == 0x49: # I: CHT (Cursor Forward Tabulation) + term._forward_tab(scr, params.get(0, 1), right) + elif final == 0x5A: # Z: CBT (Cursor Backward Tabulation) + count = params.get(0, 1) + floor = left if c_col >= left else 0 + col_iter = c_col + for _ in range(count): + prev_tabs = [t_c for t_c in scr._tabstops_sorted if floor <= t_c < col_iter] + col_iter = prev_tabs[-1] if prev_tabs else floor + if col_iter <= floor: + break + pending = scr._pending_wrap and term._profile.screen.cbt_preserves_pending_wrap + term._set_cursor(scr, c_row, col_iter, pending_wrap=pending) + elif final == 0x61: # a: HPR + if not term._profile.screen.hpr_vpr_enabled: + return + n = params.get(0, 1) + ceil = right if term._modes.is_set(Mode.DECOM) else scr.cols - 1 + term._set_cursor(scr, c_row, min(ceil, c_col + n), pending_wrap=False) + elif final == 0x64: # d: VPA + row_1 = params.get(0, 1) + if term._modes.is_set(Mode.DECOM): + target_r = min(bottom, top + row_1 - 1) + else: + target_r = min(scr.rows - 1, row_1 - 1) + keep_wrap = term._profile.screen.pending_wrap_phantom_col and scr._pending_wrap + term._set_cursor(scr, max(0, target_r), c_col, pending_wrap=keep_wrap) + elif final == 0x65: # e: VPR + if not term._profile.screen.hpr_vpr_enabled: + return + n = params.get(0, 1) + ceil = bottom if term._modes.is_set(Mode.DECOM) else scr.rows - 1 + term._set_cursor(scr, min(ceil, c_row + n), c_col, pending_wrap=False) + elif final == 0x58: # X: ECH + if term._profile.screen.pending_wrap_phantom_col and scr._pending_wrap: + return + term._before_mutate() + n = min(scr.cols - c_col, params.get(0, 1)) + bce_w = term._pen_word & _PEN_BG_MASK + scr.heal_before_edit(c_row, c_col, c_col + n) + scr._rows[c_row].clear_range(c_col, c_col + n, bce_w, None) + if c_col + n >= scr.cols: + scr._rows[c_row].wrapped = False + if scr._gfx is not None and scr._gfx.has_sixels: + scr._gfx.erase_sixel_rect( + row=c_row, + col=c_col, + rows=1, + cols=n, + scrolled_total=scr._scrolled_total, + policy=term._profile.screen.sixel_erase_policy, + ) + term._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH) + term._set_cursor(scr, c_row, c_col, pending_wrap=False) + elif final == 0x40: # @: ICH + if term._profile.screen.pending_wrap_phantom_col and scr._pending_wrap: + return + term._before_mutate() + if left <= c_col <= right: + n = params.get(0, 1) + bce_w = term._pen_word & _PEN_BG_MASK + scr.heal_before_edit(c_row, c_col, right + 1) + scr._rows[c_row].insert_blanks( + c_col, + n, + left=left, + right=right, + bce_word=bce_w, + bce_ext=None, + ) + if scr._gfx is not None and scr._gfx.has_sixels: + scr._gfx.erase_sixel_rect( + row=c_row, + col=c_col, + rows=1, + cols=right - c_col + 1, + scrolled_total=scr._scrolled_total, + policy=term._profile.screen.sixel_erase_policy, + ) + term._set_cursor(scr, c_row, c_col, pending_wrap=False) + elif final == 0x50: # P: DCH + if term._profile.screen.pending_wrap_phantom_col and scr._pending_wrap: + return + term._before_mutate() + if left <= c_col <= right: + n = params.get(0, 1) + bce_w = term._pen_word & _PEN_BG_MASK + scr.heal_before_edit(c_row, c_col, right + 1) + if c_col == 0 and left == 0 and c_row > 0 and scr._rows[c_row - 1].wrapped: + scr._rows[c_row - 1].wrapped = False + scr._rows[c_row].delete_cells( + c_col, + n, + left=left, + right=right, + bce_word=bce_w, + bce_ext=None, + ) + if right == scr.cols - 1: + scr._rows[c_row].wrapped = False + if scr._gfx is not None and scr._gfx.has_sixels: + scr._gfx.erase_sixel_rect( + row=c_row, + col=c_col, + rows=1, + cols=right - c_col + 1, + scrolled_total=scr._scrolled_total, + policy=term._profile.screen.sixel_erase_policy, + ) + term._set_cursor(scr, c_row, c_col, pending_wrap=False) + elif final == 0x4C: # L: IL + if top <= c_row <= bottom and left <= c_col <= right: + term._before_mutate() + n = params.get(0, 1) + bce_w = term._pen_word & _PEN_BG_MASK + keep_wrap = ( + not term._profile.screen.il_dl_resets_col + and term._profile.screen.pending_wrap_phantom_col + and scr._pending_wrap + ) + scr.scroll_down( + n, + top=c_row, + bottom=bottom, + left=left, + right=right, + bce_word=bce_w, + is_line_op=True, + ) + term._notify_erase( + Rect(c_row, left, min(n, bottom - c_row + 1), right - left + 1), + EraseCause.SCROLL, + ) + target_col = left if term._profile.screen.il_dl_resets_col else c_col + term._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap) + elif final == 0x4D: # M: DL + if top <= c_row <= bottom and left <= c_col <= right: + term._before_mutate() + n = params.get(0, 1) + bce_w = term._pen_word & _PEN_BG_MASK + keep_wrap = ( + not term._profile.screen.il_dl_resets_col + and term._profile.screen.pending_wrap_phantom_col + and scr._pending_wrap + ) + scr.scroll_up( + n, + top=c_row, + bottom=bottom, + left=left, + right=right, + save_history=False, + bce_word=bce_w, + is_line_op=True, + ) + term._notify_erase( + Rect( + max(c_row, bottom - n + 1), + left, + min(n, bottom - c_row + 1), + right - left + 1, + ), + EraseCause.SCROLL, + ) + target_col = left if term._profile.screen.il_dl_resets_col else c_col + term._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap) + elif final == 0x53: # S: SU + term._before_mutate() + region_h = bottom - top + 1 + n = min(params.get(0, 1), region_h) + prev_scrolled = scr._scrolled_total + scr.scroll_up( + n, + top=top, + bottom=bottom, + left=left, + right=right, + save_history=not term._screens.active_is_alt, + bce_word=term._pen_word & _PEN_BG_MASK, + ) + hist_delta = scr._scrolled_total - prev_scrolled + if hist_delta > 0 and left == 0 and right == scr.cols - 1: + term._remap_prompt_zones_on_scroll( + prev_scrolled, + top=top, + bottom=bottom, + rows=scr.rows, + hist_delta=hist_delta, + ) + term._notify_erase( + Rect( + max(top, bottom - n + 1), + left, + min(n, region_h), + right - left + 1, + ), + EraseCause.SCROLL, + ) + term._clear_cluster_anchor() + elif final == 0x54: # T: SD + term._before_mutate() + n = params.get(0, 1) + scr.scroll_down( + n, + top=top, + bottom=bottom, + left=left, + right=right, + bce_word=term._pen_word & _PEN_BG_MASK, + ) + term._notify_erase( + Rect(top, left, min(n, bottom - top + 1), right - left + 1), + EraseCause.SCROLL, + ) + term._clear_cluster_anchor() + elif final == 0x62: # b: REP + if prev_printed: + count = min(term._limits.max_rep_count, params.get(0, 1)) + if not term._profile.screen.rep_wraps and term._modes.is_set(Mode.DECAWM): + if scr._pending_wrap and term._profile.screen.pending_wrap_phantom_col: + term._last_printed = prev_printed + else: + w = max( + 1, + display_width( + prev_printed, + mode_2027=term._modes.is_set(Mode.GRAPHEME_CLUSTERING), + profile=term._profile, + ), + ) + max_c = right if c_col <= right else scr.cols - 1 + avail_cols = max_c - c_col + 1 + fit = max(0, avail_cols // w) + if fit > 0: + term._handle_print(prev_printed * min(count, fit)) + term._last_printed = prev_printed + else: + term._handle_print(prev_printed * count) + elif final == 0x72: # r: DECSTBM + t_arg = params.get(0, 1) - 1 + b_arg = params.get(1, scr.rows) - 1 + t_clamped = max(0, min(scr.rows - 1, t_arg)) + b_clamped = max(0, min(scr.rows - 1, b_arg)) + if t_clamped < b_clamped: + sr = scr.scroll_region + scr.scroll_region = ScrollRegion( + top=t_clamped, + bottom=b_clamped, + left=sr.left, + right=sr.right, + ) + decom = term._modes.is_set(Mode.DECOM) + _, _, eff_left, _ = term._effective_margins(scr) + term._set_cursor( + scr, + t_clamped if decom else 0, + eff_left if decom else 0, + ) + elif final == 0x73: # s: DECSLRM (when ?69 set) or SCOSC + if term._modes.is_set(Mode.DECLRMM): + if len(params.values) <= 2: + l_arg = params.get(0, 1) - 1 + r_arg = params.get(1, scr.cols) - 1 + l_clamped = max(0, min(scr.cols - 1, l_arg)) + r_clamped = max(0, min(scr.cols - 1, r_arg)) + if l_clamped < r_clamped: + sr = scr.scroll_region + scr.scroll_region = ScrollRegion( + top=sr.top, + bottom=sr.bottom, + left=l_clamped, + right=r_clamped, + ) + decom = term._modes.is_set(Mode.DECOM) + term._set_cursor( + scr, + sr.top if decom else 0, + l_clamped if decom else 0, + ) + elif not term._profile.screen.declrmm_enabled or not params.values: + term._save_cursor() + elif final == 0x75: # u: SCORC + term._restore_cursor() + elif final == 0x67: # g: TBC + mode = params.raw_or_default(0, 0) + if mode == 0: + scr.clear_tabstop(c_col) + elif mode == 3: + scr.clear_all_tabstops() + elif final == 0x63: # c: DA1 + if params.raw_or_default(0, 0) == 0 and term._profile.identity.da1: + term._emit_reply(term._profile.identity.da1) + elif final == 0x6E: # n: DSR + ps = params.raw_or_default(0, 0) + if ps == 5: + term._emit_reply(b"\x1b[0n") + elif ps == 6: + phantom_extra = ( + 1 + if (term._profile.screen.pending_wrap_phantom_col and scr._pending_wrap) + else 0 + ) + r_out = (c_row - top + 1) if term._modes.is_set(Mode.DECOM) else (c_row + 1) + c_out = ( + (c_col - left + 1 + phantom_extra) + if term._modes.is_set(Mode.DECOM) + else (c_col + 1 + phantom_extra) + ) + term._emit_reply(f"\x1b[{r_out};{c_out}R".encode("ascii")) + elif final == 0x74: # t: XTWINOPS + op = params.raw_or_default(0, 0) + if op == 18: # report text area size in chars + term._emit_reply(f"\x1b[8;{scr.rows};{scr.cols}t".encode("ascii")) + elif op == 14: # report text area size in pixels + px_h = scr.rows * max(0, term._profile.screen.cell_height_px) + px_w = scr.cols * max(0, term._profile.screen.cell_width_px) + term._emit_reply(f"\x1b[4;{px_h};{px_w}t".encode("ascii")) + elif op == 16: # report cell size in pixels + ch_px = max(0, term._profile.screen.cell_height_px) + cw_px = max(0, term._profile.screen.cell_width_px) + term._emit_reply(f"\x1b[6;{ch_px};{cw_px}t".encode("ascii")) + elif op == 21 and term._policy.allow_title_report: + safe_title = "".join( + ch for ch in term._title if " " <= ch <= "~" and ch != "\\" + ) + term._emit_reply(f"\x1b]l{safe_title}\x1b\\".encode("ascii")) + elif op == 22: # push icon/window title onto stack + sub_op = params.raw_or_default(1, 0) + if sub_op in (0, 1) and len(term._icon_title_stack) < 16: + term._icon_title_stack.append(term._icon_title) + if sub_op in (0, 2) and len(term._title_stack) < 16: + term._title_stack.append(term._title) + elif op == 23: # pop icon/window title from stack + sub_op = params.raw_or_default(1, 0) + if sub_op == 0: + pop_icon = bool(term._icon_title_stack) + pop_win = bool(term._title_stack) + if pop_icon or pop_win: + term._before_mutate() + if pop_icon: + term._icon_title = term._icon_title_stack.pop() + if pop_win: + term._title = term._title_stack.pop() + term._aux_revision += 1 + if pop_icon and pop_win and term._icon_title == term._title: + term._emit_event( + TitleChanged( + title=term._title, + target=TitleTarget.BOTH, + ), + ) + else: + if pop_icon: + term._emit_event( + TitleChanged( + title=term._icon_title, + target=TitleTarget.ICON, + ), + ) + if pop_win: + term._emit_event( + TitleChanged( + title=term._title, + target=TitleTarget.WINDOW, + ), + ) + elif sub_op == 1 and term._icon_title_stack: + term._before_mutate() + term._icon_title = term._icon_title_stack.pop() + term._aux_revision += 1 + term._emit_event( + TitleChanged(title=term._icon_title, target=TitleTarget.ICON), + ) + elif sub_op == 2 and term._title_stack: + term._before_mutate() + term._title = term._title_stack.pop() + term._aux_revision += 1 + term._emit_event( + TitleChanged(title=term._title, target=TitleTarget.WINDOW), + ) + else: + term._unhandled("csi", f"CSI {chr(final)}") + + +def handle_csi( + term: Terminal, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, +) -> None: + """Dispatch a completed ``CSI`` sequence onto *term*.""" + prev_printed = term._last_printed + term._interrupt_rep() + + # Fast path: unprefixed, intermediate-free CSI (SGR, CUP, EL, ED, cursor ops). + if prefix == 0 and not intermediates: + if final == 0x6D: # 'm' SGR (allows colon subparameters) + term._before_mutate() + term._style = parse_sgr(params, term._style, memo=term._sgr_memo) + term._sync_pen_cache() + return + if params.colon_mask != 0: + return + _handle_plain_csi(term, params, final, prev_printed) + return + + if params.colon_mask != 0: + return + + scr = term._screens.active + + # DA2: CSI > Ps c + if prefix == 0x3E and not intermediates and final == 0x63: + if params.raw_or_default(0, 0) == 0 and term._profile.identity.da2: + term._emit_reply(term._profile.identity.da2) + return + + # XTVERSION: CSI > q + if prefix == 0x3E and not intermediates and final == 0x71: + if term._profile.identity.xtversion: + term._emit_reply( + f"\x1bP>|{term._profile.identity.xtversion}\x1b\\".encode("ascii"), + ) + return + + # Kitty keyboard protocol: CSI > flags u | CSI < n u | CSI = flags;m u | CSI ? u + if not intermediates and final == 0x75 and prefix in (0x3E, 0x3C, 0x3D, 0x3F): + kbd = scr.keyboard_stack + if prefix == 0x3F: + if term._profile.queries.kitty_keyboard_query_enabled: + term._emit_reply(f"\x1b[?{int(kbd.flags)}u".encode("ascii")) + elif term._profile.input.kitty_keyboard_enabled: + if prefix == 0x3E: + kbd.push(params.raw_or_default(0, 0)) + elif prefix == 0x3C: + kbd.pop(params.get(0, 1)) + elif prefix == 0x3D: + kbd.set_flags(params.raw_or_default(0, 0), params.get(1, 1)) + return + + # DECRQM: CSI ? Ps $ p or CSI Ps $ p + if intermediates == b"$" and final == 0x70: + if prefix not in (0, 0x3F) or len(params.values) > 1: + return + private = prefix == 0x3F + code = params.raw_or_default(0, 0) + pm = int( + term._modes.decrpm( + code, + private=private, + active_is_alt=term._screens.active_is_alt, + screen=term._profile.screen, + ), + ) + q = "?" if private else "" + term._emit_reply(f"\x1b[{q}{code};{pm}$y".encode("ascii")) + return + + # DECSTR: CSI ! p + if prefix == 0 and intermediates == b"!" and final == 0x70: + if term._profile.screen.decstr_enabled: + term.reset(soft=True) + return + + # DECSCUSR: CSI Ps SP q + if prefix == 0 and intermediates == b" " and final == 0x71: + term._before_mutate() + ps = params.raw_or_default(0, 0) + shape = CursorShape.BLOCK + blinking = True + if ps == 2: + shape, blinking = CursorShape.BLOCK, False + elif ps == 3: + shape, blinking = CursorShape.UNDERLINE, True + elif ps == 4: + shape, blinking = CursorShape.UNDERLINE, False + elif ps == 5: + shape, blinking = CursorShape.BAR, True + elif ps == 6: + shape, blinking = CursorShape.BAR, False + scr._cur_shape = shape + scr._cur_blinking = blinking + return + + # DECSCA: CSI Ps " q (character protection attribute) + if prefix == 0 and intermediates == b'"' and final == 0x71: + ps = params.raw_or_default(0, 0) + term._before_mutate() + term._protected = ps == 1 + term._sync_pen_cache() + return + + # DECRQCRA: CSI Pid ; Pp ; Pt ; Pl ; Pb ; Pr * y (dispatched no-op) + if prefix == 0 and intermediates == b"*" and final == 0x79: + return + + if intermediates: + inter_s = intermediates.decode("ascii", errors="replace") + pfx_s = chr(prefix) if prefix else "" + term._unhandled("csi", f"CSI {pfx_s}{inter_s}{chr(final)}") + return + + if prefix == 0x3F: # '?' + if final in (0x68, 0x6C): # h / l + enable = final == 0x68 + for val in params.values: + term._apply_mode(val, private=True, enabled=enable) + elif final == 0x4A: # J: DECSED + term._erase_display(scr, params.raw_or_default(0, 0), selective=True) + elif final == 0x4B: # K: DECSEL + term._erase_line(scr, params.raw_or_default(0, 0), selective=True) + elif final == 0x6E: # n: Private DSR (?6n DECXCPR, ?996n color scheme) + ps = params.raw_or_default(0, 0) + if ps == 6: + top, _, left, _ = term._effective_margins(scr) + phantom_extra = ( + 1 + if ( + term._profile.screen.pending_wrap_phantom_col + and scr._pending_wrap + ) + else 0 + ) + r_out = ( + (scr._cur_row - top + 1) + if term._modes.is_set(Mode.DECOM) + else (scr._cur_row + 1) + ) + c_out = ( + (scr._cur_col - left + 1 + phantom_extra) + if term._modes.is_set(Mode.DECOM) + else (scr._cur_col + 1 + phantom_extra) + ) + term._emit_reply(f"\x1b[?{r_out};{c_out}R".encode("ascii")) + elif ps == 996 and term._policy.allow_color_queries: + scheme = term._host_scheme + term._emit_reply(f"\x1b[?997;{int(scheme)}n".encode("ascii")) + term._emit_event(ColorSchemeQueried(scheme=scheme)) + elif final == 0x6D: # m: XTQMODKEYS: CSI ? Pp m + if ( + term._profile.input.modify_other_keys_enabled + and len(params.values) == 1 + and params.raw_or_default(0, -1) == 4 + ): + term._emit_reply( + f"\x1b[>4;{scr._modify_other_keys}m".encode("ascii"), + ) + elif final == 0x53 and 1 <= len(params.values) <= 4: # S: XTSMGRAPHICS + handle_xtsmgraphics(term, params) + elif final == 0x73: # s: XTSAVE: CSI ? Pm s + xtsave_modes(term, params) + elif final == 0x72: # r: XTRESTORE: CSI ? Pm r + xtrestore_modes(term, params) + return + + if prefix == 0x3E and final == 0x6D: # '>m' XTMODKEYS + if not term._profile.input.modify_other_keys_enabled: + return + if not params.values: + if scr._modify_other_keys != 0: + term._before_mutate() + scr._modify_other_keys = 0 + elif len(params.values) <= 2: + pp = params.raw_or_default(0, 0) + if pp == 0 and len(params.values) == 1: + if scr._modify_other_keys != 0: + term._before_mutate() + scr._modify_other_keys = 0 + elif pp == 4: + pv = params.raw_or_default(1, 0) if len(params.values) == 2 else 0 + if pv in (0, 1, 2) and scr._modify_other_keys != pv: + term._before_mutate() + scr._modify_other_keys = pv + return + if prefix == 0x3E and final == 0x6E: # '>n' XTMODKEYS reset + if ( + term._profile.input.modify_other_keys_enabled + and ( + not params.values + or (len(params.values) == 1 and params.raw_or_default(0, -1) in (0, 4)) + ) + and scr._modify_other_keys != 0 + ): + term._before_mutate() + scr._modify_other_keys = 0 + return + term._unhandled("csi", f"CSI {chr(prefix)}{chr(final)}") + + +def handle_osc_777(term: Terminal, data: bytes) -> None: + r"""Parse ``OSC 777 ; notify ; ; <body>`` desktop notifications. + + References + ---------- + - `ghostty-org/ghostty rxvt_extension.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/osc/parsers/rxvt_extension.zig#L8-L45>`__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(record_events=True) + >>> term.feed(b"\x1b]777;notify;Alert;Done\x07") + >>> term.drain_events()[0].title + 'Alert' + """ + if not term._policy.allow_notifications: + return + k = data.find(b";") + if k == -1 or data[:k] != b"notify": + return + t_sep = data.find(b";", k + 1) + if t_sep == -1: + return + max_nb = max(0, term._limits.max_notification_bytes) + title_s, title_used = _cap_sanitized_bytes(data[k + 1 : t_sep], max_nb) + body_s, _ = _cap_sanitized_bytes( + data[t_sep + 1 :], + max(0, max_nb - title_used), + ) + if not title_s and not body_s: + return + term._emit_event( + Notification( + source=NotificationSource.OSC_777, + title=title_s, + body=body_s, + ), + ) + + +def handle_osc_99(term: Terminal, data: bytes, out_term: bytes) -> None: + r"""Parse Kitty ``OSC 99 ; <metadata> ; <payload>`` desktop notifications. + + Supports ``i=`` identifiers, ``d=0``/``1`` multi-chunk reassembly + bounded by :attr:`~libvt.config.Limits.max_pending_notifications` and + :attr:`~libvt.config.Limits.max_notification_bytes`, ``e=1`` Base64 + decoding, ``p=title``/``body``/``?``/``close``/``alive``, and + ``u=0``/``1``/``2`` urgency levels. + + References + ---------- + - `Kitty Desktop Notification Protocol (OSC 99) + <https://sw.kovidgoyal.net/kitty/desktop-notifications/>`__ + - `ghostty-org/ghostty kitty_desktop_notification.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/osc/parsers/kitty_desktop_notification.zig#L287-L335>`__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(record_events=True) + >>> term.feed(b"\x1b]99;i=n1:d=0:p=title;Hi\x1b\\") + >>> term.feed(b"\x1b]99;i=n1:d=1:p=body;Ok\x1b\\") + >>> ev = term.drain_events()[0] + >>> (ev.notification_id, ev.title, ev.body) + ('n1', 'Hi', 'Ok') + """ + if not term._policy.allow_notifications: + return + sep = data.find(b";") + if sep == -1 or not data[:sep].isascii(): + return + meta_s = data[:sep].decode("ascii") + payload_b = data[sep + 1 :] + + notif_id = "" + done = True + b64 = False + ptype = "title" + urgency: NotificationUrgency | None = None + if meta_s: + for item in meta_s.split(":"): + eq = item.find("=") + if eq == -1: + continue + key = item[:eq] + val = item[eq + 1 :] + if key == "i": + if val and all( + "a" <= ch <= "z" + or "A" <= ch <= "Z" + or "0" <= ch <= "9" + or ch in "-_+." + for ch in val + ): + notif_id = val[:128] + elif key == "d": + done = val != "0" + elif key == "e": + b64 = val == "1" + elif key == "p": + ptype = val or "unknown" + elif key == "u": + if val == "0": + urgency = NotificationUrgency.LOW + elif val == "1": + urgency = NotificationUrgency.NORMAL + elif val == "2": + urgency = NotificationUrgency.HIGH + + if ptype == "?": + if term._policy.allow_notification_queries: + qid = notif_id or "0" + reply = ( + f"\x1b]99;i={qid}:p=?;p=title,body:a=focus:u=0,1,2".encode("ascii") + + out_term + ) + term._emit_reply(reply) + return + + if ptype in ("close", "alive"): + term._pending_osc99.pop(notif_id, None) + return + + max_nb = max(0, term._limits.max_notification_bytes) + max_pend = max(0, term._limits.max_pending_notifications) + entry = term._pending_osc99.get(notif_id) + if entry is None: + title_buf = bytearray() + body_buf = bytearray() + cur_urg = urgency if urgency is not None else NotificationUrgency.NORMAL + used = 0 + else: + title_buf, body_buf, prev_urg, used = entry + cur_urg = urgency if urgency is not None else prev_urg + + rem = max(0, max_nb - used) + if ptype in ("title", "body"): + if b64: + cleaned = payload_b.strip(b" \t\r\n") + if len(cleaned) % 4 == 1: + return + padded = cleaned + (b"=" * ((-len(cleaned)) % 4)) + try: + decoded_b = base64.b64decode(padded, validate=True) if rem > 0 else b"" + except binascii.Error: + return + else: + decoded_b = payload_b + chunk_b = decoded_b[:rem] + used += len(chunk_b) + if ptype == "body": + body_buf.extend(chunk_b) + else: + title_buf.extend(chunk_b) + + if not done: + if max_pend > 0: + if ( + notif_id not in term._pending_osc99 + and len(term._pending_osc99) >= max_pend + ): + oldest_key = next(iter(term._pending_osc99)) + term._pending_osc99.pop(oldest_key, None) + term._pending_osc99[notif_id] = (title_buf, body_buf, cur_urg, used) + return + + term._pending_osc99.pop(notif_id, None) + title_s, title_used = _cap_sanitized_bytes(title_buf, max_nb) + body_s, _ = _cap_sanitized_bytes(body_buf, max(0, max_nb - title_used)) + if not title_s and not body_s: + return + term._emit_event( + Notification( + source=NotificationSource.OSC_99, + notification_id=sanitize_terminal_text(notif_id), + title=title_s, + body=body_s, + urgency=cur_urg, + ), + ) + + +def handle_osc( + term: Terminal, + code: int, + data: bytes, + terminator: bytes, +) -> None: + """Dispatch a completed ``OSC`` sequence onto *term*.""" + term._interrupt_rep() + out_term = b"\x07" if terminator == b"\x07" else b"\x1b\\" + + if code == 0: + term._before_mutate() + text = data.decode("utf-8", errors="replace") + term._title = text + term._icon_title = text + term._emit_event(TitleChanged(title=text, target=TitleTarget.BOTH)) + elif code == 1: + term._before_mutate() + text = data.decode("utf-8", errors="replace") + term._icon_title = text + term._aux_revision += 1 + term._emit_event(TitleChanged(title=text, target=TitleTarget.ICON)) + elif code == 2: + term._before_mutate() + text = data.decode("utf-8", errors="replace") + term._title = text + term._emit_event(TitleChanged(title=text, target=TitleTarget.WINDOW)) + elif code == 4: + if not data: + return + pos = 0 + n_data = len(data) + while pos <= n_data: + semi1 = data.find(b";", pos) + if semi1 == -1: + break + pal_idx = _parse_ascii_uint_bytes(data[pos:semi1], max_val=255) + if pal_idx is None: + break + semi2 = data.find(b";", semi1 + 1) + if semi2 == -1: + spec_b = data[semi1 + 1 :] + pos = n_data + 1 + else: + spec_b = data[semi1 + 1 : semi2] + pos = semi2 + 1 + if spec_b == b"?": + if ( + term._policy.emit_replies + and term._policy.allow_color_queries + and ( + term._on_pty_write is not None + or len(term._replies) + 24 <= term._limits.max_reply_bytes + ) + ): + rgb_val = term._effective_palette_entry(pal_idx) + reply = (f"\x1b]4;{pal_idx};{_format_osc_rgb(rgb_val)}").encode( + "ascii", + ) + term._emit_reply(reply + out_term) + continue + parsed_pal = _parse_osc_rgb(spec_b) + if parsed_pal is None: + break + if term._guest_palette.get(pal_idx) != parsed_pal: + term._before_mutate() + term._guest_palette[pal_idx] = parsed_pal + term._bump_appearance() + elif code == 7: + term._update_cwd( + data.decode("utf-8", errors="replace"), + source=CwdSource.OSC_7, + ) + elif code == 8: + text = data.decode("utf-8", errors="replace") + sep = text.find(";") + if sep == -1: + return + params_part = text[:sep] + uri = text[sep + 1 :] + term._before_mutate() + if not uri: + term._hyperlink = None + else: + link_id = "" + for kv in params_part.split(":"): + if kv.startswith("id="): + link_id = kv[3:] + break + term._hyperlink = Hyperlink(uri=uri, id=link_id) + term._sync_pen_cache() + elif code == 9: + text = data.decode("utf-8", errors="replace") + parts = text.split(";") + if ( + len(parts) >= 2 + and parts[0] == "4" + and parts[1] in ("0", "1", "2", "3", "4") + ): + sub = int(parts[1]) + term._before_mutate() + prog = ( + _parse_ascii_uint(parts[2], max_val=1_000) if len(parts) >= 3 else None + ) + changed, status = term._status_store.apply_osc_9_4(sub, prog) + if changed: + term._aux_revision += 1 + term._emit_event(ProgramStatusChanged(status=status, task_id="")) + elif len(parts) >= 2 and parts[0] == "9": + term._update_cwd(";".join(parts[1:]), source=CwdSource.OSC_9_9) + elif ( + (len(parts) == 1 and parts[0] in ("5", "10", "12")) + or ( + len(parts) == 2 + and parts[0] == "10" + and parts[1] in ("0", "1", "2", "3") + ) + or (len(parts) >= 2 and parts[0] in ("1", "2", "3", "6", "7", "8", "11")) + ): + return + elif data and term._policy.allow_notifications: + max_nb = max(0, term._limits.max_notification_bytes) + body_s, _ = _cap_sanitized_bytes(data, max_nb) + if body_s: + term._emit_event( + Notification( + source=NotificationSource.OSC_9, + body=body_s, + ), + ) + elif code in (10, 11, 12): + if not data: + return + cur_code = code + pos = 0 + n_data = len(data) + while cur_code <= 12 and pos <= n_data: + semi = data.find(b";", pos) + if semi == -1: + spec_b = data[pos:] + pos = n_data + 1 + else: + spec_b = data[pos:semi] + pos = semi + 1 + if spec_b == b"?": + if ( + term._policy.emit_replies + and term._policy.allow_color_queries + and ( + term._on_pty_write is not None + or len(term._replies) + 23 <= term._limits.max_reply_bytes + ) + ): + cur_rgb = ( + term._effective_fg_rgb() + if cur_code == 10 + else ( + term._effective_bg_rgb() + if cur_code == 11 + else term._effective_cursor_rgb() + ) + ) + reply = (f"\x1b]{cur_code};{_format_osc_rgb(cur_rgb)}").encode( + "ascii", + ) + term._emit_reply(reply + out_term) + else: + parsed_rgb = _parse_osc_rgb(spec_b) + if parsed_rgb is None: + break + if cur_code == 10 and term._guest_fg_rgb != parsed_rgb: + term._before_mutate() + term._guest_fg_rgb = parsed_rgb + term._bump_appearance() + elif cur_code == 11 and term._guest_bg_rgb != parsed_rgb: + term._before_mutate() + term._guest_bg_rgb = parsed_rgb + term._bump_appearance() + elif cur_code == 12 and term._guest_cursor_rgb != parsed_rgb: + term._before_mutate() + term._guest_cursor_rgb = parsed_rgb + term._bump_appearance() + cur_code += 1 + elif code == 99: + handle_osc_99(term, data, out_term) + elif code == 777: + handle_osc_777(term, data) + elif code == 104: + if not term._guest_palette: + return + if not data: + term._before_mutate() + term._guest_palette.clear() + term._bump_appearance() + return + saw_nonempty = False + mutated_pal = False + pos = 0 + n_data = len(data) + while pos <= n_data: + semi = data.find(b";", pos) + if semi == -1: + tok = data[pos:] + pos = n_data + 1 + else: + tok = data[pos:semi] + pos = semi + 1 + if not tok: + continue + saw_nonempty = True + pal_idx = _parse_ascii_uint_bytes(tok, max_val=255) + if pal_idx is not None and pal_idx in term._guest_palette: + if not mutated_pal: + term._before_mutate() + mutated_pal = True + term._guest_palette.pop(pal_idx, None) + if not saw_nonempty and term._guest_palette: + term._before_mutate() + term._guest_palette.clear() + mutated_pal = True + if mutated_pal: + term._bump_appearance() + elif code == 110: + if not data and term._guest_fg_rgb is not None: + term._before_mutate() + term._guest_fg_rgb = None + term._bump_appearance() + elif code == 111: + if not data and term._guest_bg_rgb is not None: + term._before_mutate() + term._guest_bg_rgb = None + term._bump_appearance() + elif code == 112: + if not data and term._guest_cursor_rgb is not None: + term._before_mutate() + term._guest_cursor_rgb = None + term._bump_appearance() + elif code == 52: + semi = data.find(b";") + if semi == -1: + return + sel = _parse_osc52_selection(data[:semi]) + if sel is None: + return + body = data[semi + 1 :] + if body == b"?": + if term._policy.clipboard_read == ClipboardReadPolicy.EMIT_EVENT: + term._emit_event(ClipboardReadRequested(selection=sel)) + return + if term._policy.allow_clipboard_write: + try: + raw_clip = base64.b64decode(body, validate=False) + clip_text = raw_clip.decode("utf-8", errors="replace") + except (binascii.Error, ValueError): + return + term._emit_event(ClipboardWrite(selection=sel, text=clip_text)) + elif code == 133: + text = data.decode("utf-8", errors="replace") + parts = text.split(";") + raw_kind = parts[0][:1] if parts and parts[0] else "" + if raw_kind in ("A", "B", "C", "D"): + kind = PromptKind(raw_kind) + exit_code: int | None = None + is_continuation = any(p.strip() in ("k=c", "k=s", "k=r") for p in parts[1:]) + if kind == PromptKind.COMMAND_FINISHED and len(parts) >= 2: + exit_code = _parse_ascii_int( + parts[1], + min_val=-2_147_483_648, + max_val=2_147_483_647, + ) + term._record_prompt_mark( + kind, + osc_code=133, + exit_code=exit_code, + is_continuation=is_continuation, + ) + elif code == 633: + text = data.decode("utf-8", errors="replace") + subcmd, sep0, rest = text.partition(";") + if subcmd in ("A", "B", "C", "D"): + parts = text.split(";") + kind = PromptKind(subcmd) + exit_code_633: int | None = None + is_cont_633 = any(p.strip() in ("k=c", "k=s", "k=r") for p in parts[1:]) + if kind == PromptKind.COMMAND_FINISHED and len(parts) >= 2: + exit_code_633 = _parse_ascii_int( + parts[1], + min_val=-2_147_483_648, + max_val=2_147_483_647, + ) + term._record_prompt_mark( + kind, + osc_code=633, + exit_code=exit_code_633, + is_continuation=is_cont_633, + ) + elif subcmd == "E" and sep0: + cmd_raw, sep_n, nonce_raw = rest.partition(";") + command = _unescape_osc_633(cmd_raw) + nonce = _unescape_osc_633(nonce_raw) if sep_n and nonce_raw else None + term._emit_event(ShellCommandReported(command=command, nonce=nonce)) + elif subcmd == "P" and sep0: + prop_field, _, _ = rest.partition(";") + prop_k_raw, sep_eq, prop_v_raw = prop_field.partition("=") + prop_k = _unescape_osc_633(prop_k_raw) + if sep_eq and prop_k: + prop_v = _unescape_osc_633(prop_v_raw) + if prop_k == "Cwd": + term._update_cwd(prop_v, source=CwdSource.OSC_633_P) + else: + term._emit_event( + ShellPropertyChanged(name=prop_k, value=prop_v), + ) + elif code == 7501: + if data == b"?": + cap = term._profile.identity.osc_7501_capabilities + if term._policy.allow_program_status_query and cap: + term._emit_reply(f"\x1b]7501;{cap}".encode("ascii") + out_term) + return + term._before_mutate() + changed, rec = term._status_store.apply_osc_7501(data) + if changed: + term._aux_revision += 1 + tid = rec.id if rec is not None else "" + term._emit_event(ProgramStatusChanged(status=rec, task_id=tid)) + else: + term._unhandled("osc", f"OSC {code}") + + +def handle_decrqss(term: Terminal, req: bytes) -> None: + """Dispatch a ``DECRQSS`` (``DCS $ q <req> ST``) status-string request.""" + scr = term._screens.active + if req == b"m": + sgr_body = _style_to_sgr(term._style)[2:] # strip leading ESC [ + term._emit_reply(f"\x1bP1$r{sgr_body}\x1b\\".encode("ascii")) + elif req == b"r": + sr = scr.scroll_region + term._emit_reply( + f"\x1bP1$r{sr.top + 1};{sr.bottom + 1}r\x1b\\".encode("ascii"), + ) + elif req == b"s" and term._modes.is_set(Mode.DECLRMM): + sr = scr.scroll_region + term._emit_reply( + f"\x1bP1$r{sr.left + 1};{sr.right + 1}s\x1b\\".encode("ascii"), + ) + elif req == b" q": + shape_map = { + (CursorShape.BLOCK, True): 1, + (CursorShape.BLOCK, False): 2, + (CursorShape.UNDERLINE, True): 3, + (CursorShape.UNDERLINE, False): 4, + (CursorShape.BAR, True): 5, + (CursorShape.BAR, False): 6, + } + code = shape_map[(scr._cur_shape, scr._cur_blinking)] + term._emit_reply(f"\x1bP1$r{code} q\x1b\\".encode("ascii")) + elif req == b'"q': + code = 1 if term._protected else 0 + term._emit_reply(f'\x1bP1$r{code}"q\x1b\\'.encode("ascii")) + else: + term._emit_reply(b"\x1bP0$r\x1b\\") + + +def handle_xtgettcap(term: Terminal, data: bytes) -> None: + """Dispatch an ``XTGETTCAP`` (``DCS + q <hex-names> ST``) capability query.""" + for hex_name in data.split(b";"): + if not hex_name: + continue + try: + cap_name = bytes.fromhex(hex_name.decode("ascii")).decode("ascii") + except ValueError: + term._emit_reply(b"\x1bP0+r\x1b\\") + continue + if cap_name in _TERMINFO_CAPS: + val = _TERMINFO_CAPS[cap_name] + enc_k = _hex_encode(cap_name) + if val: + enc_v = _hex_encode(val) + term._emit_reply(f"\x1bP1+r{enc_k}={enc_v}\x1b\\".encode("ascii")) + else: + term._emit_reply(f"\x1bP1+r{enc_k}\x1b\\".encode("ascii")) + else: + term._emit_reply(b"\x1bP0+r\x1b\\") + + +def handle_dcs( + term: Terminal, + prefix: int, + params: CsiParams, + intermediates: bytes, + final: int, + data: bytes, +) -> None: + """Dispatch a completed ``DCS`` sequence onto *term*.""" + term._interrupt_rep() + # DECRQSS: DCS $ q <req> ST + if prefix == 0 and intermediates == b"$" and final == 0x71: + if term._profile.queries.decrqss_enabled: + handle_decrqss(term, data) + return + + # XTGETTCAP: DCS + q <hex-names> ST + if prefix == 0 and intermediates == b"+" and final == 0x71: + if term._profile.queries.xtgettcap_enabled: + handle_xtgettcap(term, data) + return + + # tmux passthrough: DCS tmux; ESC ESC ... ST (final='t', data=b"mux;...") + if ( + prefix == 0 + and not intermediates + and not params.values + and final == 0x74 + and data.startswith(b"mux;") + ): + unwrapped = bytes(memoryview(data)[4:]) + if term._record_events or term._on_event is not None: + term._emit_event(Passthrough(data=unwrapped)) + if term._policy.allow_passthrough and term._passthrough_depth < 2: + if term._passthrough_depth == 0: + if term._passthrough_parser is None: + term._passthrough_parser = Parser( + encoding=term._parser.encoding, + allow_encoding_switch=term._profile.screen.allow_encoding_switch, + tmux_window_rename=term._profile.screen.allow_esc_k_title, + abort_dispatch_osc=term._policy.abort_dispatch_osc, + limits=term._limits, + ) + inner_parser = term._passthrough_parser + else: + inner_parser = Parser( + encoding=term._parser.encoding, + allow_encoding_switch=term._profile.screen.allow_encoding_switch, + tmux_window_rename=term._profile.screen.allow_esc_k_title, + abort_dispatch_osc=term._policy.abort_dispatch_osc, + limits=term._limits, + ) + term._passthrough_depth += 1 + try: + inner_parser.feed_to(unwrapped, term._sink) + finally: + term._passthrough_depth -= 1 + return + + # SIXEL: DCS Ps... q <sixel> ST + if prefix == 0 and not intermediates and final == 0x71: + scr = term._screens.active + orig_row, orig_col = scr._cur_row, scr._cur_col + if term._policy.track_graphics: + term._before_mutate() + decsdm = term._modes.is_set(Mode.DECSDM) + anchor_r = 0 if decsdm else orig_row + anchor_c = 0 if decsdm else orig_col + gfx = scr.ensure_graphics() + prepared = gfx.prepare_sixel( + data, + col=anchor_c, + screen_cols=scr.cols, + cell_width_px=term._profile.screen.cell_width_px, + cell_height_px=term._profile.screen.cell_height_px, + ) + if prepared is not None: + w_px, h_px, s_rows, s_cols = prepared + pre_scrolled = scr._scrolled_total + top, bottom, left, right = term._effective_margins(scr) + in_margins = top <= orig_row <= bottom and left <= orig_col <= right + if decsdm: + post_r = anchor_r + eff_rows = max(1, min(s_rows, scr.rows - anchor_r)) + min_sixel_abs = 0 + else: + post_r = term._advance_rows(scr, s_rows, final_col=0) + eff_rows = min(s_rows, max(1, scr.rows - post_r)) + if in_margins and top > 0: + min_sixel_abs = scr._scrolled_total + top + elif scr._scrolled_total == pre_scrolled: + min_sixel_abs = scr._scrolled_total + (top if in_margins else 0) + else: + min_sixel_abs = scr._scrolled_total - len(scr._history) + gfx.commit_sixel( + payload_len=len(data), + width_px=w_px, + height_px=h_px, + row=post_r, + col=anchor_c, + rows=eff_rows, + cols=s_cols, + scrolled_total=scr._scrolled_total, + min_abs=min_sixel_abs, + ) + if term._record_events or term._on_event is not None: + term._emit_event( + SixelGraphic( + data=SixelData( + row=orig_row, + col=orig_col, + params=params.values, + payload=data, + ), + ), + ) + return + + inter_s = intermediates.decode("ascii", errors="replace") + term._unhandled("dcs", f"DCS {inter_s}{chr(final)}") diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 337dcb6e..c38ee08b 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -36,6 +36,7 @@ PasteEvent, ) from libvt.parser import ParserEncoding +from libvt.recorder import find_flight_recorder from libvt.terminal import FlightRecorder, Snapshot, StopOn, Terminal type TtyMode = t.Literal["cooked", "cbreak", "raw"] @@ -216,7 +217,7 @@ def _make_timeout_error( ) -> TerminalTimeoutError: from libvt.testing import format_flight_recorder, format_screen_box - rec = terminal.recorder + rec = find_flight_recorder(terminal.recorder) recent = rec.tail(256) if rec is not None else b"" box = format_screen_box(snap, rows=min(snap.rows, 12), cols=min(snap.cols, 80)) diag = format_flight_recorder(terminal) diff --git a/src/libvt/contrib/tmux/control.py b/src/libvt/contrib/tmux/control.py index 0ac79c6b..3ca1c738 100644 --- a/src/libvt/contrib/tmux/control.py +++ b/src/libvt/contrib/tmux/control.py @@ -96,53 +96,7 @@ def _parse_layout_pane_size(layout: str, pane_id: str) -> tuple[int, int] | None def _adopt_terminal_state(dst: Terminal, src: Terminal) -> None: """Replace *dst* screen/mode/parser state from *src* in place and advance epoch.""" - dst._screens = src._screens - dst._screens._on_mutate = dst._on_screen_mutate - dst._screens.primary._on_mutate = dst._on_screen_mutate - dst._screens.alternate._on_mutate = dst._on_screen_mutate - dst._modes._enabled = set(src._modes._enabled) - dst._parser = src._parser - dst._docs_utf8_active = src._docs_utf8_active - dst._saved_docs_charset = src._saved_docs_charset - dst._passthrough_parser = src._passthrough_parser - dst._style = src._style - dst._protected = src._protected - dst._hyperlink = src._hyperlink - dst._sync_pen_cache() - dst._g_sets = list(src._g_sets) - dst._gl = src._gl - dst._single_shift = src._single_shift - dst._saved_primary = src._saved_primary - dst._saved_alt = src._saved_alt - dst._saved_decsc = src._saved_decsc - dst._saved_private_modes = dict(src._saved_private_modes) - dst._has_alt_saved = src._has_alt_saved - dst._last_printed = src._last_printed - dst._last_printed_pos = src._last_printed_pos - dst._cluster_state = src._cluster_state - dst._cluster_len = src._cluster_len - dst._pending_prepend = src._pending_prepend - dst._title = src._title - dst._icon_title = src._icon_title - dst._window_name = src._window_name - dst._cwd = src._cwd - dst._cwd_uri = src._cwd_uri - dst._prompt_zones.clear() - dst._prompt_zones.extend(src._prompt_zones) - dst._last_prompt_osc_code = src._last_prompt_osc_code - dst._last_prompt_zone = src._last_prompt_zone - dst._sync_hold_pending = src._sync_hold_pending - dst._held_snapshot = None - dst._held_sync_token = None - if src.synchronized: - dst._sync_generation += 1 - dst._cached_appearance = None - dst._appearance_revision += 1 - dst._aux_revision += 1 - dst._cached_snapshot = None - dst._epoch += 1 - dst._generation += 1 - dst._committed_generation += 1 + dst.replace_from(src) def _tmux_quote(arg: str) -> str: diff --git a/src/libvt/modes.py b/src/libvt/modes.py index cddc0738..ecda7279 100644 --- a/src/libvt/modes.py +++ b/src/libvt/modes.py @@ -5,6 +5,8 @@ import collections.abc import enum +from libvt.config import DeccolmBehavior, Profile, ScreenBehavior + DEC_PRIVATE_MASK = 0x8000 @@ -93,6 +95,98 @@ class DecrpmValue(enum.IntEnum): _RECOGNIZED_MODES: frozenset[int] = frozenset(int(m) for m in Mode) +def private_mode_unsupported_status( + mode: Mode, + screen: ScreenBehavior, +) -> DecrpmValue | None: + """Return forced ``DECRPM`` status when *mode* is unsupported, else ``None``. + + Single source of truth for profile-gated DEC private modes across + :meth:`ModeState.set_mode` interception, ``DECSET``/``DECRST``, + ``XTSAVE``/``XTRESTORE``, and ``DECRQM`` queries. + + Parameters + ---------- + mode : Mode + DEC private mode to evaluate. + screen : ScreenBehavior + Active profile screen behavior configuration. + + Returns + ------- + DecrpmValue | None + :attr:`DecrpmValue.PERMANENTLY_RESET` or + :attr:`DecrpmValue.NOT_RECOGNIZED` when *screen* disables *mode*, + otherwise ``None``. + + References + ---------- + - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L81-L95>`__ + - `tmux/tmux input.c (3.8) + <https://github.com/tmux/tmux/blob/3.8/input.c#L1945-L1993>`__ + + Examples + -------- + >>> from libvt.config import DeccolmBehavior, ScreenBehavior + >>> from libvt.modes import DecrpmValue, Mode, private_mode_unsupported_status + >>> private_mode_unsupported_status( + ... Mode.DECCOLM, ScreenBehavior(deccolm=DeccolmBehavior.CLEAR_ONLY) + ... ) + <DecrpmValue.PERMANENTLY_RESET: 4> + >>> private_mode_unsupported_status(Mode.DECLRMM, ScreenBehavior()) is None + True + """ + if mode == Mode.DECCOLM: + if screen.deccolm == DeccolmBehavior.CLEAR_ONLY: + return DecrpmValue.PERMANENTLY_RESET + if screen.deccolm == DeccolmBehavior.IGNORE: + return DecrpmValue.NOT_RECOGNIZED + return None + if mode in (Mode.ALLOW_80_132, Mode.DECNCSM): + if screen.deccolm in (DeccolmBehavior.IGNORE, DeccolmBehavior.CLEAR_ONLY): + return DecrpmValue.NOT_RECOGNIZED + return None + if mode == Mode.DECLRMM and not screen.declrmm_enabled: + return DecrpmValue.NOT_RECOGNIZED + if mode == Mode.DECSC_1048 and screen.separate_alt_save_cursor: + return DecrpmValue.NOT_RECOGNIZED + if mode == Mode.MOUSE_SGR_PIXELS and ( + screen.cell_width_px <= 0 or screen.cell_height_px <= 0 + ): + return DecrpmValue.NOT_RECOGNIZED + return None + + +def is_private_mode_supported(mode: Mode, profile: Profile) -> bool: + """Return ``True`` when DEC private *mode* is supported by *profile*. + + Parameters + ---------- + mode : Mode + DEC private mode candidate. + profile : Profile + Active terminal profile. + + Returns + ------- + bool + ``True`` when :func:`private_mode_unsupported_status` returns ``None``. + + Examples + -------- + >>> from libvt.config import DEFAULT_PROFILE, Profile, ScreenBehavior + >>> from libvt.modes import Mode, is_private_mode_supported + >>> is_private_mode_supported(Mode.DECLRMM, DEFAULT_PROFILE) + True + >>> is_private_mode_supported( + ... Mode.DECLRMM, Profile(screen=ScreenBehavior(declrmm_enabled=False)) + ... ) + False + """ + return private_mode_unsupported_status(mode, profile.screen) is None + + class ModeState: """Mutable set of active ANSI and DEC private modes.""" @@ -182,6 +276,7 @@ def decrpm( *, private: bool, active_is_alt: bool | None = None, + screen: ScreenBehavior | None = None, ) -> DecrpmValue: """Return the ``DECRPM`` status value for raw mode number *code*.""" if not (0 <= code < DEC_PRIVATE_MASK): @@ -190,6 +285,10 @@ def decrpm( if raw not in _RECOGNIZED_MODES: return DecrpmValue.NOT_RECOGNIZED mode = Mode(raw) + if private and screen is not None: + forced = private_mode_unsupported_status(mode, screen) + if forced is not None: + return forced if mode in ALT_SCREEN_MODES and active_is_alt is False: return DecrpmValue.RESET return DecrpmValue.SET if mode in self._enabled else DecrpmValue.RESET @@ -212,4 +311,6 @@ def clone(self) -> ModeState: "DecrpmValue", "Mode", "ModeState", + "is_private_mode_supported", + "private_mode_unsupported_status", ] diff --git a/src/libvt/recorder.py b/src/libvt/recorder.py new file mode 100644 index 00000000..2508d808 --- /dev/null +++ b/src/libvt/recorder.py @@ -0,0 +1,164 @@ +"""Terminal input/resize recorder protocol and bounded diagnostic ring buffer.""" + +from __future__ import annotations + +import collections.abc +import typing as t + +from libvt._util import _byte_view + + +@t.runtime_checkable +class TerminalRecorder(t.Protocol): + r"""Structural recorder hook receiving normalized bytes and host resizes. + + Implementations receive every non-empty byte span fed into + :meth:`~libvt.terminal.Terminal.feed` or + :meth:`~libvt.terminal.Terminal.feed_until` as a contiguous 1-D unsigned + byte :class:`memoryview`, plus every explicit host-initiated + :meth:`~libvt.terminal.Terminal.resize` (excluding internal ``DECCOLM`` + column switches already present in the recorded VT stream). + + Recorders that retain input beyond :meth:`on_feed` must copy bytes (for + example ``bytes(data)``) before returning because callers may reuse or + mutate the underlying buffer after ``feed()`` completes. + """ + + def on_feed(self, data: memoryview, /) -> None: + """Record a contiguous 1-D ``"B"`` byte span fed to the terminal.""" + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + """Record an explicit external terminal resize to ``(rows, cols)``.""" + + +class FlightRecorder: + r"""Bounded raw-byte ring buffer capturing recent VT traffic for diagnostics. + + Implements :class:`TerminalRecorder` so it can be attached directly to + :class:`~libvt.terminal.Terminal` via ``recorder=FlightRecorder()``. + + Examples + -------- + >>> from libvt.recorder import FlightRecorder + >>> from libvt.terminal import Terminal + >>> rec = FlightRecorder(max_bytes=128) + >>> term = Terminal(rows=2, cols=10, recorder=rec) + >>> term.feed(b"\x1b[1;32mREADY\x1b[0m") + >>> rec.total_bytes, rec.tail() + (16, b'\x1b[1;32mREADY\x1b[0m') + """ + + __slots__ = ("_buf", "_max_bytes", "_total_bytes") + + def __init__(self, *, max_bytes: int = 4_096) -> None: + if ( + isinstance(max_bytes, bool) + or not isinstance(max_bytes, int) + or max_bytes < 0 + ): + msg = f"max_bytes must be a nonnegative integer, got {max_bytes!r}" + raise ValueError(msg) + self._max_bytes = max_bytes + self._buf = bytearray() + self._total_bytes = 0 + + @property + def total_bytes(self) -> int: + """Return total byte count observed since initialization or ``clear()``.""" + return self._total_bytes + + def _append_view(self, mv: memoryview) -> None: + n = len(mv) + if n == 0: + return + self._total_bytes += n + if self._max_bytes == 0: + return + if n >= self._max_bytes: + self._buf[:] = mv[n - self._max_bytes :] + return + overflow = len(self._buf) + n - self._max_bytes + if overflow > 0: + del self._buf[:overflow] + self._buf.extend(mv) + + def on_feed(self, data: memoryview, /) -> None: + """Append normalized *data* span into the bounded diagnostic buffer.""" + with _byte_view(data) as mv: + self._append_view(mv) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + """Ignore external resizes (ring buffer records raw VT bytes only).""" + + def record(self, data: collections.abc.Buffer) -> None: + """Append *data*, retaining at most ``max_bytes`` trailing bytes.""" + with _byte_view(data) as mv: + self._append_view(mv) + + def tail(self, max_bytes: int = 256) -> bytes: + """Return up to *max_bytes* of the most recently recorded input bytes.""" + if max_bytes <= 0 or not self._buf: + return b"" + return bytes(self._buf[-max_bytes:]) + + def clear(self) -> None: + """Clear recorded bytes and reset ``total_bytes``.""" + self._buf.clear() + self._total_bytes = 0 + + +class CompositeRecorder: + r"""Fan-out :class:`TerminalRecorder` dispatching to multiple child recorders. + + Flattens nested :class:`CompositeRecorder` instances at construction so + hot-path dispatch remains a single flat tuple loop and + :func:`find_flight_recorder` inspects every member in ``O(k)``. + """ + + __slots__ = ("_recorders",) + + def __init__(self, *recorders: TerminalRecorder) -> None: + flat: list[TerminalRecorder] = [] + for rec in recorders: + if isinstance(rec, CompositeRecorder): + flat.extend(rec._recorders) + else: + flat.append(rec) + self._recorders: tuple[TerminalRecorder, ...] = tuple(flat) + + @property + def recorders(self) -> tuple[TerminalRecorder, ...]: + """Return flattened child :class:`TerminalRecorder` instances.""" + return self._recorders + + def on_feed(self, data: memoryview, /) -> None: + """Forward normalized *data* span to every child recorder in order.""" + with _byte_view(data) as mv: + for rec in self._recorders: + rec.on_feed(mv) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + """Forward external resize to every child recorder in order.""" + for rec in self._recorders: + rec.on_resize(rows, cols, reflow) + + +def find_flight_recorder( + recorder: TerminalRecorder | None, +) -> FlightRecorder | None: + """Return the first :class:`FlightRecorder` in *recorder*, unwrapping composites.""" + if isinstance(recorder, FlightRecorder): + return recorder + if isinstance(recorder, CompositeRecorder): + for child in recorder.recorders: + if isinstance(child, FlightRecorder): + return child + return None + + +__all__ = [ + "CompositeRecorder", + "FlightRecorder", + "TerminalRecorder", + "find_flight_recorder", +] diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index dc08548e..3db176e1 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -2,8 +2,6 @@ from __future__ import annotations -import base64 -import binascii import collections import collections.abc import dataclasses @@ -31,20 +29,25 @@ SAFE_NARROW_BMP_RE, WidthRole, char_width, - display_width, init_cluster_state, sanitize_terminal_text, step_cluster, ucd_lookup, ) -from libvt._util import _byte_view, _parse_ascii_int, _parse_ascii_uint +from libvt._util import _byte_view +from libvt._vt_dispatch import ( + _cap_sanitized_bytes, + handle_csi, + handle_dcs, + handle_esc, + handle_osc, +) from libvt.config import ( DEFAULT_LIMITS, DEFAULT_OSC7_HOSTS, DEFAULT_POLICY, DEFAULT_PROFILE, Charset, - ClipboardReadPolicy, ColorScheme, DeccolmBehavior, Limits, @@ -65,7 +68,6 @@ KittyGraphic, KnownEvent, Notification, - NotificationSource, NotificationUrgency, Passthrough, ProgramStatusChanged, @@ -77,7 +79,6 @@ ScreenErased, ShellCommandReported, ShellPropertyChanged, - SixelData, SixelGraphic, TitleChanged, TitleTarget, @@ -85,39 +86,24 @@ WorkingDirectoryChanged, ) from libvt.exc import ProtocolError -from libvt.format import ( - Formatter, - OutputFormat, - _format_osc_rgb, - _style_to_sgr, - _VtPen, -) +from libvt.format import Formatter, OutputFormat, _VtPen from libvt.input import InputEvent, KittyKeyboardFlags, encode_input from libvt.modes import ( ALT_SCREEN_MODES, DEC_PRIVATE_MASK, TRANSIENT_SNAPSHOT_MODES, - DecrpmValue, Mode, ModeState, + is_private_mode_supported, ) from libvt.parser import ( CsiParams, Parser, ParserEncoding, ParserState, - parse_sgr, -) -from libvt.screen import ( - Cell, - Cursor, - CursorShape, - RegionView, - RowView, - Screen, - ScreenSet, - ScrollRegion, ) +from libvt.recorder import CompositeRecorder, FlightRecorder, TerminalRecorder +from libvt.screen import Screen, ScreenSet, ScrollRegion from libvt.snapshot import ( ResyncReason, ScreenDelta, @@ -127,6 +113,7 @@ SyncView, _make_snapshot, _make_sync_token, + _SavedCursor, _SyncState, ) from libvt.status import ProgramStatus, ProgramStatusStore @@ -138,6 +125,7 @@ Style, _resolve_color_rgb, ) +from libvt.views import Cell, Cursor, CursorShape, RegionView, RowView if t.TYPE_CHECKING: from libvt.graphics import ImageMeta, ImagePlacement @@ -251,105 +239,6 @@ class StepResult: stopped_on: StopOn -class FlightRecorder: - r"""Bounded raw-byte ring buffer capturing recent VT traffic for diagnostics. - - Set ``max_bytes`` to the number of input bytes to retain. Zero counts - input in :attr:`total_bytes` without retaining the payload. - - Examples - -------- - >>> from libvt.terminal import FlightRecorder, Terminal - >>> rec = FlightRecorder(max_bytes=128) - >>> term = Terminal(rows=2, cols=10, recorder=rec) - >>> term.feed(b"\x1b[1;32mREADY\x1b[0m") - >>> rec.total_bytes, rec.tail() - (16, b'\x1b[1;32mREADY\x1b[0m') - """ - - __slots__ = ("_buf", "_max_bytes", "_total_bytes") - - def __init__(self, *, max_bytes: int = 4_096) -> None: - if ( - isinstance(max_bytes, bool) - or not isinstance(max_bytes, int) - or max_bytes < 0 - ): - msg = f"max_bytes must be a nonnegative integer, got {max_bytes!r}" - raise ValueError(msg) - self._max_bytes = max_bytes - self._buf = bytearray() - self._total_bytes = 0 - - @property - def total_bytes(self) -> int: - """Return total byte count observed since initialization or ``clear()``.""" - return self._total_bytes - - def record(self, data: collections.abc.Buffer) -> None: - """Append *data*, retaining at most ``max_bytes`` trailing bytes.""" - with _byte_view(data) as mv: - n = len(mv) - if n == 0: - return - self._total_bytes += n - if n >= self._max_bytes: - self._buf[:] = mv[n - self._max_bytes :] - return - overflow = len(self._buf) + n - self._max_bytes - if overflow > 0: - del self._buf[:overflow] - self._buf.extend(mv) - - def tail(self, max_bytes: int = 256) -> bytes: - """Return up to *max_bytes* of the most recently recorded input bytes.""" - if max_bytes <= 0 or not self._buf: - return b"" - return bytes(self._buf[-max_bytes:]) - - def clear(self) -> None: - """Clear recorded bytes and reset ``total_bytes``.""" - self._buf.clear() - self._total_bytes = 0 - - -@dataclass(frozen=True, slots=True) -class _SavedCursor: - """Internal ``DECSC`` per-screen saved cursor and charset state. - - Attributes - ---------- - row : int - Saved zero-based row. - col : int - Saved zero-based column. - pending_wrap : bool - Saved pending-wrap state. - style : Style - Saved SGR pen. - decom : bool - Saved ``DECOM`` origin-mode flag. - g_sets : tuple[Charset, Charset, Charset, Charset] - Saved ``G0``..``G3`` character-set designations. - gl : int - Saved active locking-shift slot index (``0..3``). - single_shift : int | None - Saved pending single-shift slot (``2`` for ``SS2``, ``3`` for ``SS3``). - protected : bool - Saved ``DECSCA`` character-protection pen attribute. - """ - - row: int = 0 - col: int = 0 - pending_wrap: bool = False - style: Style = DEFAULT_STYLE - decom: bool = False - g_sets: tuple[Charset, Charset, Charset, Charset] = ("B", "B", "B", "B") - gl: int = 0 - single_shift: int | None = None - protected: bool = False - - class _TerminalSink: """Private ``ActionSink`` forwarding parser actions into :class:`Terminal`.""" @@ -365,7 +254,7 @@ def on_execute(self, byte: int) -> None: self._term._handle_execute(byte) def on_esc(self, intermediates: bytes, final: int) -> None: - self._term._handle_esc(intermediates, final) + handle_esc(self._term, intermediates, final) def on_csi( self, @@ -374,10 +263,10 @@ def on_csi( intermediates: bytes, final: int, ) -> None: - self._term._handle_csi(prefix, params, intermediates, final) + handle_csi(self._term, prefix, params, intermediates, final) def on_osc(self, code: int, data: bytes, terminator: bytes) -> None: - self._term._handle_osc(code, data, terminator) + handle_osc(self._term, code, data, terminator) def on_dcs( self, @@ -387,7 +276,7 @@ def on_dcs( final: int, data: bytes, ) -> None: - self._term._handle_dcs(prefix, params, intermediates, final, data) + handle_dcs(self._term, prefix, params, intermediates, final, data) def on_apc(self, data: bytes) -> None: self._term._handle_apc(data) @@ -594,190 +483,6 @@ def _event_byte_cost(event: Event) -> int: return 32 + _value_byte_cost(event) -def _parse_ascii_uint_bytes(raw: bytes, *, max_val: int) -> int | None: - if not raw: - return None - acc = 0 - for b in raw: - if not (0x30 <= b <= 0x39): - return None - acc = acc * 10 + (b - 0x30) - if acc > max_val: - return None - return acc - - -def _parse_ascii_hex(raw: str) -> int | None: - if not raw: - return None - acc = 0 - for ch in raw: - code = ord(ch) - if 0x30 <= code <= 0x39: - digit = code - 0x30 - elif 0x41 <= code <= 0x46: - digit = code - 0x41 + 10 - elif 0x61 <= code <= 0x66: - digit = code - 0x61 + 10 - else: - return None - acc = (acc << 4) | digit - return acc - - -def _parse_osc_rgb(spec: bytes) -> tuple[int, int, int] | None: - try: - text = spec.decode("ascii").strip() - except UnicodeDecodeError: - return None - if text.startswith("#") and len(text) == 7: - r = _parse_ascii_hex(text[1:3]) - g = _parse_ascii_hex(text[3:5]) - b = _parse_ascii_hex(text[5:7]) - if r is None or g is None or b is None: - return None - return (r, g, b) - if text.lower().startswith("rgb:"): - parts = text[4:].split("/") - if len(parts) != 3: - return None - vals: list[int] = [] - for comp in parts: - if not (1 <= len(comp) <= 4): - return None - raw = _parse_ascii_hex(comp) - if raw is None: - return None - scale = (1 << (4 * len(comp))) - 1 - vals.append((raw * 255) // scale) - return (vals[0], vals[1], vals[2]) - return None - - -_OSC52_SELECTION_BYTES: frozenset[int] = frozenset(b"cpqs01234567") - - -def _parse_osc52_selection(raw: bytes) -> str | None: - r"""Validate an ``OSC 52`` selection designator token against ``[cpqs0-7]*``. - - Parameters - ---------- - raw : bytes - Bytes preceding the first ``;`` inside an ``OSC 52`` payload. - - Returns - ------- - str | None - Validated ASCII selection string (``"c"`` when *raw* is empty), or - ``None`` if *raw* exceeds ``16`` bytes or contains any byte outside - ``cpqs01234567``. - - References - ---------- - - `xterm Control Sequences — Manipulate Selection Data (OSC 52) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - `tmux/tmux input.c — input_osc_52 (3.8) - <https://github.com/tmux/tmux/blob/3.8/input.c#L3376-L3392>`__ - - Examples - -------- - >>> from libvt.terminal import _parse_osc52_selection - >>> _parse_osc52_selection(b""), _parse_osc52_selection(b"pc") - ('c', 'pc') - >>> _parse_osc52_selection(b"\x00evil"), _parse_osc52_selection(b"\xff") - (None, None) - """ - if not raw: - return "c" - if len(raw) > 16 or any(b not in _OSC52_SELECTION_BYTES for b in raw): - return None - return raw.decode("ascii") - - -def _hex_encode(text: str) -> str: - return text.encode("utf-8").hex() - - -def _unescape_osc_633(raw: str) -> str: - r"""Decode ``OSC 633`` backslash and ``\xAB`` hex-byte escape sequences. - - VS Code shell-integration scripts serialize ``\`` as ``\\`` and ``;`` plus - control bytes ``0x00..0x20`` as ``\xAB`` so semicolons inside command text - or paths never collide with ``OSC 633`` field delimiters. Split ``OSC 633`` - fields on ``;`` first, then pass each field through :func:`_unescape_osc_633`. - Consecutive ``\xAB`` escapes are buffered and decoded together as UTF-8. - - Parameters - ---------- - raw : str - Single semicolon-delimited ``OSC 633`` field before unescaping. - - Returns - ------- - str - Unescaped field string. - - References - ---------- - - `VS Code Terminal Shell Integration — Escaping values - <https://code.visualstudio.com/docs/terminal/shell-integration>`__ - - `microsoft/vscode osc633Parser.ts (1.148.0) - <https://github.com/microsoft/vscode/blob/1.148.0/src/vs/platform/agentHost/node/osc633Parser.ts#L86-L97>`__ - - `microsoft/vscode shellIntegrationAddon.ts (1.148.0) - <https://github.com/microsoft/vscode/blob/1.148.0/src/vs/platform/terminal/common/xterm/shellIntegrationAddon.ts#L812-L835>`__ - - Examples - -------- - >>> from libvt.terminal import _unescape_osc_633 - >>> _unescape_osc_633(r"printf \\x3b\x3becho\x0aok") - 'printf \\x3b;echo\nok' - >>> _unescape_osc_633(r"/tmp/\xe6\x97\xa5\xe6\x9c\xac") - '/tmp/日本' - """ - if "\\" not in raw: - return raw - out: list[str] = [] - hex_buf = bytearray() - i = 0 - n = len(raw) - while i < n: - if raw[i] == "\\" and i + 1 < n: - nxt = raw[i + 1] - if nxt in ("x", "X") and i + 3 < n: - hv = _parse_ascii_hex(raw[i + 2 : i + 4]) - if hv is not None: - hex_buf.append(hv) - i += 4 - continue - if hex_buf: - out.append(hex_buf.decode("utf-8", errors="replace")) - hex_buf.clear() - if nxt == "\\": - out.append("\\") - i += 2 - continue - if hex_buf: - out.append(hex_buf.decode("utf-8", errors="replace")) - hex_buf.clear() - out.append(raw[i]) - i += 1 - if hex_buf: - out.append(hex_buf.decode("utf-8", errors="replace")) - return "".join(out) - - -_TERMINFO_CAPS: dict[str, str] = { - "TN": "xterm-256color", - "Co": "256", - "colors": "256", - "RGB": "8/8/8", - "Tc": "", - "Smulx": "\x1b[4:%p1%dm", - "Setulc": "\x1b[58:2::%p1%{65536}%/%d:%p1%{256}%/%{255}%&%d:%p1%{255}%&%dm", - "Sync": "\x1b[?2026%?%p1%{1}%-%tl%eh%;", -} - - def _validate_rgb_triplet( val: tuple[int, int, int], label: str, @@ -824,6 +529,180 @@ class Terminal: r0[0..5]: bold fg=green """ + __slots__ = ( + "_active_recorder", + "_appearance_revision", + "_aux_revision", + "_cached_appearance", + "_cached_row_gen", + "_cached_snapshot", + "_cell_ext", + "_cluster_len", + "_cluster_state", + "_committed_generation", + "_cwd", + "_cwd_uri", + "_docs_utf8_active", + "_encoding", + "_epoch", + "_event_bytes", + "_events", + "_g_sets", + "_generation", + "_gl", + "_guest_bg_rgb", + "_guest_cursor_rgb", + "_guest_fg_rgb", + "_guest_palette", + "_has_alt_saved", + "_held_snapshot", + "_held_sync_token", + "_host_bg_rgb", + "_host_cursor_rgb", + "_host_fg_rgb", + "_host_palette", + "_host_scheme", + "_hyperlink", + "_icon_title", + "_icon_title_stack", + "_last_printed", + "_last_printed_pos", + "_last_prompt_osc_code", + "_last_prompt_zone", + "_limits", + "_modes", + "_newline_mode", + "_on_event", + "_on_pty_write", + "_on_reply_queued", + "_parser", + "_passthrough_depth", + "_passthrough_parser", + "_pen_word", + "_pending_osc99", + "_pending_prepend", + "_policy", + "_profile", + "_prompt_zones", + "_protected", + "_record_events", + "_recorder", + "_replies", + "_saved_alt", + "_saved_decsc", + "_saved_docs_charset", + "_saved_primary", + "_saved_private_modes", + "_screens", + "_sgr_memo", + "_single_shift", + "_sink", + "_sixel_color_registers", + "_sixel_geometry_px", + "_status_store", + "_step_event", + "_style", + "_sync_generation", + "_sync_hold_pending", + "_terminal_id", + "_title", + "_title_stack", + "_window_name", + ) + + _REPLACE_TRANSFERRED_SLOTS: t.ClassVar[frozenset[str]] = frozenset( + { + "_cell_ext", + "_cluster_len", + "_cluster_state", + "_cwd", + "_cwd_uri", + "_docs_utf8_active", + "_g_sets", + "_gl", + "_guest_bg_rgb", + "_guest_cursor_rgb", + "_guest_fg_rgb", + "_guest_palette", + "_has_alt_saved", + "_hyperlink", + "_icon_title", + "_icon_title_stack", + "_last_printed", + "_last_printed_pos", + "_last_prompt_osc_code", + "_last_prompt_zone", + "_modes", + "_parser", + "_passthrough_parser", + "_pen_word", + "_pending_osc99", + "_pending_prepend", + "_prompt_zones", + "_protected", + "_saved_alt", + "_saved_decsc", + "_saved_docs_charset", + "_saved_primary", + "_saved_private_modes", + "_screens", + "_single_shift", + "_sixel_color_registers", + "_sixel_geometry_px", + "_status_store", + "_style", + "_sync_hold_pending", + "_title", + "_title_stack", + "_window_name", + }, + ) + + _REPLACE_PRESERVED_SLOTS: t.ClassVar[frozenset[str]] = frozenset( + { + "_active_recorder", + "_encoding", + "_event_bytes", + "_events", + "_host_bg_rgb", + "_host_cursor_rgb", + "_host_fg_rgb", + "_host_palette", + "_host_scheme", + "_limits", + "_newline_mode", + "_on_event", + "_on_pty_write", + "_on_reply_queued", + "_passthrough_depth", + "_policy", + "_profile", + "_record_events", + "_recorder", + "_replies", + "_sgr_memo", + "_sink", + "_terminal_id", + }, + ) + + _REPLACE_RESET_SLOTS: t.ClassVar[frozenset[str]] = frozenset( + { + "_appearance_revision", + "_aux_revision", + "_cached_appearance", + "_cached_row_gen", + "_cached_snapshot", + "_committed_generation", + "_epoch", + "_generation", + "_held_snapshot", + "_held_sync_token", + "_step_event", + "_sync_generation", + }, + ) + def __init__( self, *, @@ -836,7 +715,7 @@ def __init__( on_event: collections.abc.Callable[[Event], None] | None = None, on_pty_write: collections.abc.Callable[[bytes], None] | None = None, record_events: bool = False, - recorder: FlightRecorder | None = None, + recorder: TerminalRecorder | None = None, encoding: ParserEncoding = "utf-8", newline_mode: bool = False, ) -> None: @@ -850,6 +729,7 @@ def __init__( self._on_reply_queued: collections.abc.Callable[[], None] | None = None self._record_events = record_events self._recorder = recorder + self._active_recorder = recorder self._events: collections.deque[Event] = collections.deque() self._event_bytes: int = 0 self._terminal_id: int = _alloc_terminal_id() @@ -1052,10 +932,17 @@ def at_ground_state(self) -> bool: ) @property - def recorder(self) -> FlightRecorder | None: - """Return attached :class:`FlightRecorder`, if any.""" + def recorder(self) -> TerminalRecorder | None: + """Return attached :class:`~libvt.recorder.TerminalRecorder`, if any.""" return self._recorder + def _attach_recorder(self, recorder: TerminalRecorder) -> None: + """Attach an auxiliary recorder without altering :attr:`recorder`.""" + if self._active_recorder is None: + self._active_recorder = recorder + else: + self._active_recorder = CompositeRecorder(self._active_recorder, recorder) + @property def screen(self) -> Screen: """Return the currently active :class:`~libvt.screen.Screen`.""" @@ -1946,7 +1833,8 @@ def enqueue_reply(self, data: collections.abc.Buffer, /) -> None: >>> term.drain_replies() b'\x1b]52;c;aGVsbG8=\x1b\\' """ - payload = bytes(data) + with _byte_view(data) as mv: + payload = mv.tobytes() if not payload: return if self._on_pty_write is not None: @@ -1957,6 +1845,20 @@ def enqueue_reply(self, data: collections.abc.Buffer, /) -> None: if self._on_reply_queued is not None: self._on_reply_queued() + def _attach_reply_sink( + self, + callback: collections.abc.Callable[[], None], + ) -> collections.abc.Callable[[], None]: + """Attach *callback* if unset and return an idempotent ownership-safe detach.""" + if self._on_reply_queued is None: + self._on_reply_queued = callback + + def _detach() -> None: + if self._on_reply_queued == callback: + self._on_reply_queued = None + + return _detach + def encode(self, event: InputEvent, /) -> bytes: r"""Encode *event* into outbound PTY bytes using active terminal modes. @@ -2065,9 +1967,114 @@ def _sync_pen_cache(self) -> None: ) def _bce_pair(self) -> tuple[int, _CellExt | None]: - if self._style.bg is None: - return 0, None - return pack_pen_base(Style(bg=self._style.bg)), None + return self._pen_word & _PEN_BG_MASK, None + + def replace_from(self, other: Terminal) -> None: + r"""Replace emulated screen, mode, parser, and guest state from *other*. + + Preserves host identity and wiring (``_terminal_id``, callbacks, + ``recorder``, host theme, policy, and limits) while transferring live + emulated state from donor *other* in place and advancing the sync epoch + so existing :class:`SyncToken` consumers receive + :attr:`ResyncReason.EPOCH_CHANGED`. + + Ownership of *other*'s internal screen buffers and parser transfers to + ``self``; do not continue mutating *other* afterwards. + + Parameters + ---------- + other : Terminal + Donor terminal whose emulated guest state replaces ``self``. + + Raises + ------ + TypeError + If *other* is not a :class:`Terminal`. + + Examples + -------- + >>> from libvt.terminal import ResyncReason, Terminal + >>> dst = Terminal(rows=2, cols=10) + >>> dst.feed(b"\x1b]10;#ff0000\x07old") + >>> tok = dst.sync_token() + >>> src = Terminal(rows=2, cols=10) + >>> src.feed(b"fresh") + >>> dst.replace_from(src) + >>> dst.lines[0], dst.changes_since(tok).resync_reason + ('fresh', <ResyncReason.EPOCH_CHANGED: 'epoch_changed'>) + """ + if not isinstance(other, Terminal): + msg = f"other must be Terminal, got {type(other).__name__}" + raise TypeError(msg) + if other is self: + return + self._screens = other._screens + self._screens._on_mutate = self._on_screen_mutate + self._screens.primary._on_mutate = functools.partial( + self._on_screen_mutate, screen=self._screens.primary + ) + self._screens.alternate._on_mutate = functools.partial( + self._on_screen_mutate, screen=self._screens.alternate + ) + self._modes._enabled = set(other._modes._enabled) + self._parser = other._parser + self._docs_utf8_active = other._docs_utf8_active + self._saved_docs_charset = other._saved_docs_charset + self._passthrough_parser = other._passthrough_parser + self._style = other._style + self._protected = other._protected + self._hyperlink = other._hyperlink + self._sync_pen_cache() + self._g_sets = list(other._g_sets) + self._gl = other._gl + self._single_shift = other._single_shift + self._saved_primary = other._saved_primary + self._saved_alt = other._saved_alt + self._saved_decsc = other._saved_decsc + self._saved_private_modes = dict(other._saved_private_modes) + self._has_alt_saved = other._has_alt_saved + self._last_printed = other._last_printed + self._last_printed_pos = other._last_printed_pos + self._cluster_state = other._cluster_state + self._cluster_len = other._cluster_len + self._pending_prepend = other._pending_prepend + self._title = other._title + self._icon_title = other._icon_title + self._window_name = other._window_name + self._title_stack = list(other._title_stack) + self._icon_title_stack = list(other._icon_title_stack) + self._cwd = other._cwd + self._cwd_uri = other._cwd_uri + self._prompt_zones.clear() + self._prompt_zones.extend(other._prompt_zones) + self._last_prompt_osc_code = other._last_prompt_osc_code + self._last_prompt_zone = other._last_prompt_zone + self._guest_fg_rgb = other._guest_fg_rgb + self._guest_bg_rgb = other._guest_bg_rgb + self._guest_cursor_rgb = other._guest_cursor_rgb + self._guest_palette = dict(other._guest_palette) + self._sixel_color_registers = other._sixel_color_registers + self._sixel_geometry_px = other._sixel_geometry_px + self._status_store._records = dict(other._status_store._records) + self._status_store._native_7501_seen = other._status_store._native_7501_seen + self._pending_osc99 = { + k: (bytearray(t_b), bytearray(b_b), urg, used) + for k, (t_b, b_b, urg, used) in other._pending_osc99.items() + } + self._sync_hold_pending = other._sync_hold_pending or other.synchronized + self._held_snapshot = None + self._held_sync_token = None + if other.synchronized: + self._sync_generation += 1 + self._step_event = StopOn.NONE + self._cached_appearance = None + self._cached_snapshot = None + self._cached_row_gen = -1 + self._appearance_revision += 1 + self._aux_revision += 1 + self._epoch += 1 + self._generation += 1 + self._committed_generation += 1 def _notify_erase(self, rect: Rect, cause: EraseCause) -> None: if ( @@ -2111,13 +2118,24 @@ def resize( msg = f"rows and cols must be >= 1, got ({rows!r}, {cols!r})" raise ValueError(msg) eff_reflow = self._profile.screen.reflow_on_resize if reflow is None else reflow + if self._active_recorder is not None: + self._active_recorder.on_resize(rows, cols, eff_reflow) + self._resize_internal(rows=rows, cols=cols, reflow=eff_reflow) + + def _resize_internal( + self, + *, + rows: int, + cols: int, + reflow: bool, + ) -> None: self._before_mutate() old_zones = tuple(self._prompt_zones) zone_pins = tuple((z.abs_row, z.col) for z in old_zones) remapped_pins = self._screens._resize_with_pins( rows=rows, cols=cols, - reflow=eff_reflow, + reflow=reflow, primary_pins=zone_pins, ) if old_zones and len(remapped_pins) == len(old_zones): @@ -2376,23 +2394,8 @@ def _intercept_mode_set(self, mode: Mode, enabled: bool) -> bool: self._bump_appearance() return True if ( - mode == Mode.DECLRMM - and not self._profile.screen.declrmm_enabled - and enabled - ): - return True - if mode == Mode.DECSC_1048 and self._profile.screen.separate_alt_save_cursor: - return True - if ( - mode in (Mode.DECCOLM, Mode.ALLOW_80_132, Mode.DECNCSM) - and enabled - and not self._is_private_mode_supported(mode) - ): - return True - if mode == Mode.MOUSE_SGR_PIXELS and ( - self._profile.screen.cell_width_px <= 0 - or self._profile.screen.cell_height_px <= 0 - ): + enabled or mode in (Mode.DECSC_1048, Mode.MOUSE_SGR_PIXELS) + ) and not is_private_mode_supported(mode, self._profile): return True if mode == Mode.DECTCEM: self._screens.primary._cur_visible = enabled @@ -2459,10 +2462,10 @@ def feed(self, data: collections.abc.Buffer, /) -> None: with _byte_view(data) as mv: if not mv: return - if self._recorder is not None: - self._recorder.record(mv) + if self._active_recorder is not None: + self._active_recorder.on_feed(mv) self._parser.feed_to(mv, self._sink) - self._generation += 1 + self._generation += 1 def feed_until( self, @@ -2483,16 +2486,27 @@ def feed_until( (True, ('frame 1',), b'trailing') """ with _byte_view(data) as mv: - n = len(mv) - if offset < 0 or offset > n: - msg = f"offset {offset} out of range for buffer of length {n}" - raise ValueError(msg) - idx = offset + return self._feed_until_mv(mv, offset=offset, stop=stop) + + def _feed_until_mv( + self, + mv: memoryview, + *, + offset: int, + stop: StopOn, + ) -> StepResult: + n = len(mv) + if offset < 0 or offset > n: + msg = f"offset {offset} out of range for buffer of length {n}" + raise ValueError(msg) + idx = offset + consumed = offset + try: while idx < n: self._step_event = StopOn.NONE state = self._parser.state - # Bulk-advance GROUND printable ASCII unless StopOn.GROUND is set. + # Bulk-advance GROUND printable ASCII when StopOn.GROUND is unset. if ( state == ParserState.GROUND and not self._parser.utf8_pending @@ -2501,10 +2515,9 @@ def feed_until( ascii_m = _PRINT_ASCII_RE.match(mv, idx) if ascii_m is not None: end = ascii_m.end() - span = mv[idx:end] - if self._recorder is not None: - self._recorder.record(span) - self._parser.feed_to(span, self._sink) + with mv[idx:end] as span: + consumed = end + self._parser.feed_to(span, self._sink) idx = end self._generation += 1 continue @@ -2523,18 +2536,16 @@ def feed_until( body_m = body_re.match(mv, idx) if body_m is not None: end = body_m.end() - span = mv[idx:end] - if self._recorder is not None: - self._recorder.record(span) - self._parser.feed_to(span, self._sink) + with mv[idx:end] as span: + consumed = end + self._parser.feed_to(span, self._sink) idx = end self._generation += 1 continue - one = mv[idx : idx + 1] - if self._recorder is not None: - self._recorder.record(one) - self._parser.feed_to(one, self._sink) + with mv[idx : idx + 1] as one: + consumed = idx + 1 + self._parser.feed_to(one, self._sink) idx += 1 self._generation += 1 matched = self._step_event & stop @@ -2550,6 +2561,10 @@ def feed_until( offset=n, stopped_on=StopOn.EOF, ) + finally: + if consumed > offset and self._active_recorder is not None: + with mv[offset:consumed] as rec_span: + self._active_recorder.on_feed(rec_span) # --- Internal sink handlers --- @@ -3405,120 +3420,7 @@ def _restore_cursor(self) -> None: self._apply_saved_cursor(saved) def _handle_esc(self, intermediates: bytes, final: int) -> None: - self._interrupt_rep() - scr = self._screens.active - if not intermediates: - if final == 0x37: # ESC 7 DECSC - self._save_cursor() - elif final == 0x38: # ESC 8 DECRC - self._restore_cursor() - elif final == 0x44: # ESC D IND - self._linefeed(scr) - elif final == 0x45: # ESC E NEL - self._linefeed(scr, carriage_return=True) - elif final == 0x48: # ESC H HTS - scr.add_tabstop(scr._cur_col) - elif final == 0x4D: # ESC M RI - self._before_mutate() - top, bottom, left, right = self._effective_margins(scr) - keep_wrap = ( - self._profile.screen.pending_wrap_phantom_col and scr._pending_wrap - ) - if scr._cur_row == top and left <= scr._cur_col <= right: - bce_w, _ = self._bce_pair() - scr.scroll_down( - 1, - top=top, - bottom=bottom, - left=left, - right=right, - bce_word=bce_w, - ) - self._notify_erase( - Rect(top, left, 1, right - left + 1), - EraseCause.SCROLL, - ) - self._clear_cluster_anchor() - elif scr._cur_row > 0: - self._set_cursor( - scr, - scr._cur_row - 1, - scr._cur_col, - pending_wrap=keep_wrap, - ) - elif final == 0x4E: # ESC N SS2 -> G2 - self._single_shift = 2 - elif final == 0x4F: # ESC O SS3 -> G3 - self._single_shift = 3 - elif final == 0x6E: # ESC n LS2 -> G2 - self._gl = 2 - elif final == 0x6F: # ESC o LS3 -> G3 - self._gl = 3 - elif final == 0x63: # ESC c RIS - self.reset(soft=False) - elif final == 0x3D: # ESC = DECKPAM - self._apply_mode(66, private=True, enabled=True) - elif final == 0x3E: # ESC > DECKPNM - self._apply_mode(66, private=True, enabled=False) - else: - self._unhandled("esc", f"ESC {chr(final)}") - elif intermediates in (b"(", b")", b"*", b"+"): - slot = {b"(": 0, b")": 1, b"*": 2, b"+": 3}[intermediates] - desig = chr(final) - if desig in ("0", "A", "B", "U"): - self._g_sets[slot] = desig - else: - self._g_sets[slot] = "B" - elif intermediates == b"%" and final in (0x40, 0x47): # ISO-2022 DOCS - if self._profile.screen.allow_encoding_switch: - if final == 0x47: # ESC % G -> UTF-8 - if not self._docs_utf8_active: - self._before_mutate() - self._saved_docs_charset = ( - ( - self._g_sets[0], - self._g_sets[1], - self._g_sets[2], - self._g_sets[3], - ), - self._gl, - self._single_shift, - ) - self._g_sets = [ - "B", - self._profile.screen.default_g1_charset, - "B", - "B", - ] - self._gl = 0 - self._single_shift = None - self._docs_utf8_active = True - elif self._docs_utf8_active: # ESC % @ -> legacy 8-bit - self._before_mutate() - if self._saved_docs_charset is not None: - saved_g, saved_gl, saved_ss = self._saved_docs_charset - self._g_sets = list(saved_g) - self._gl = saved_gl - self._single_shift = saved_ss - self._saved_docs_charset = None - self._docs_utf8_active = False - elif intermediates == b"#" and final == 0x38: # DECALN - self._before_mutate() - scr._sever_incoming_wrap(0) - fill = "E" * scr.cols - for r in scr._rows: - r.reset_blank(scr.cols) - r.write_ascii_slice(0, fill, 0, None) - scr.scroll_region = ScrollRegion( - top=0, - bottom=scr.rows - 1, - left=0, - right=scr.cols - 1, - ) - self._set_cursor(scr, 0, 0, pending_wrap=False) - else: - inter_s = intermediates.decode("ascii", errors="replace") - self._unhandled("esc", f"ESC {inter_s}{chr(final)}") + handle_esc(self, intermediates, final) def _is_private_mode_supported(self, mode: Mode) -> bool: """Return ``True`` when DEC private *mode* is supported by the active profile. @@ -3552,386 +3454,71 @@ def _is_private_mode_supported(self, mode: Mode) -> bool: >>> Terminal(profile=tmux_profile())._is_private_mode_supported(Mode.DECLRMM) False """ + return is_private_mode_supported(mode, self._profile) + + def _apply_deccolm(self, *, enabled: bool) -> None: deccolm_cfg = self._profile.screen.deccolm - if mode in (Mode.DECCOLM, Mode.ALLOW_80_132, Mode.DECNCSM) and deccolm_cfg in ( - DeccolmBehavior.IGNORE, - DeccolmBehavior.CLEAR_ONLY, - ): - return False - if mode == Mode.DECLRMM and not self._profile.screen.declrmm_enabled: - return False - if mode == Mode.DECSC_1048 and self._profile.screen.separate_alt_save_cursor: - return False - return not ( - mode == Mode.MOUSE_SGR_PIXELS - and ( - self._profile.screen.cell_width_px <= 0 - or self._profile.screen.cell_height_px <= 0 + if deccolm_cfg == DeccolmBehavior.IGNORE: + return + if deccolm_cfg == DeccolmBehavior.CLEAR_ONLY: + scr = self._screens.active + top, _, left, _ = self._effective_margins(scr) + decom = self._modes.is_set(Mode.DECOM) + self._set_cursor( + scr, + top if decom else 0, + left if decom else 0, + pending_wrap=False, ) - ) - - def _handle_xtsmgraphics(self, params: CsiParams) -> None: - r"""Handle ``XTSMGRAPHICS`` (``CSI ? Pi ; Pa ; Pv S``) register queries. - - Supports color-register count (``Pi = 1``) and ``SIXEL`` pixel geometry - (``Pi = 2``) across read (``Pa = 1``), reset (``Pa = 2``), set - (``Pa = 3``), and read-maximum (``Pa = 4``), clamped by - :attr:`~libvt.config.Limits.max_image_dimension` and - :attr:`~libvt.config.QueryBehavior.max_sixel_color_registers`. Replies - ``CSI ? Pi ; 3 S`` when disabled or unsupported so ``SIXEL`` clients - never stall. - - References - ---------- - - `xterm Control Sequences — XTSMGRAPHICS (CSI ? Pi ; Pa ; Pv S) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - `tmux/tmux input.c — input_csi_dispatch_sm_graphics (3.8) - <https://github.com/tmux/tmux/blob/3.8/input.c#L2103-L2120>`__ - - Examples - -------- - >>> from libvt.terminal import Terminal - >>> term = Terminal(rows=10, cols=20) - >>> term.feed(b"\x1b[?1;1;0S\x1b[?2;1;0S") - >>> term.drain_replies() - b'\x1b[?1;0;256S\x1b[?2;0;160;160S' - """ - q_cfg = self._profile.queries - if not q_cfg.xtsmgraphics_enabled: + self._erase_display(scr, 2, selective=False) return - pi = params.raw_or_default(0, 0) - pa = params.raw_or_default(1, 0) - if not self._policy.track_graphics or params.colon_mask != 0: - self._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) + if deccolm_cfg == DeccolmBehavior.GATED_BY_MODE_40 and not self._modes.is_set( + Mode.ALLOW_80_132 + ): return - if pi not in (1, 2, 3): - self._emit_reply(f"\x1b[?{pi};1S".encode("ascii")) + + self._before_mutate() + self._clear_cluster_anchor() + self._modes.set_mode(Mode.DECCOLM, enabled=enabled) + target_cols = 132 if enabled else 80 + if self.cols != target_cols: + self._resize_internal(rows=self.rows, cols=target_cols, reflow=False) + scr = self._screens.active + scr.scroll_region = ScrollRegion( + top=0, + bottom=scr.rows - 1, + left=0, + right=scr.cols - 1, + ) + if not self._modes.is_set(Mode.DECNCSM): + bce_w, bce_e = self._bce_pair() + for r in range(scr.rows): + scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e) + scr._rows[r].wrapped = False + if scr._gfx is not None: + scr._gfx.clear_active_screen(scr._scrolled_total, scr.rows) + self._notify_erase(Rect(0, 0, scr.rows, scr.cols), EraseCause.ED) + self._set_cursor(scr, 0, 0, pending_wrap=False) + + def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: + if not (0 <= code < DEC_PRIVATE_MASK): return - if pa not in (1, 2, 3, 4): - self._emit_reply(f"\x1b[?{pi};2S".encode("ascii")) + raw = (DEC_PRIVATE_MASK | code) if private else code + try: + mode = Mode(raw) + except ValueError: return - if pi == 1: - max_regs = q_cfg.max_sixel_color_registers - def_regs = min(q_cfg.sixel_color_registers, max_regs) - if pa == 1: - self._emit_reply( - f"\x1b[?1;0;{self._sixel_color_registers}S".encode("ascii"), - ) - elif pa == 2: - if self._sixel_color_registers != def_regs: - self._before_mutate() - self._sixel_color_registers = def_regs - self._emit_reply(f"\x1b[?1;0;{def_regs}S".encode("ascii")) - elif ( - pa == 3 - and q_cfg.xtsmgraphics_set_enabled - and len(params.values) == 3 - and ((params.omitted_mask >> 2) & 1) == 0 - and params.values[2] >= 2 - ): - clamped_regs = min(params.values[2], max_regs) - if self._sixel_color_registers != clamped_regs: - self._before_mutate() - self._sixel_color_registers = clamped_regs - self._emit_reply(f"\x1b[?1;0;{clamped_regs}S".encode("ascii")) - elif pa == 4: - self._emit_reply(f"\x1b[?1;0;{max_regs}S".encode("ascii")) - else: - self._emit_reply(b"\x1b[?1;3S") + if mode == Mode.SYNCHRONIZED_OUTPUT: + self._set_synchronized_output(enabled) return - if pi == 2 and q_cfg.xtsmgraphics_geometry_enabled: - cw = self._profile.screen.cell_width_px - ch = self._profile.screen.cell_height_px - max_dim = self._limits.max_image_dimension - if cw <= 0 or ch <= 0 or max_dim <= 0: - self._emit_reply(b"\x1b[?2;3S") - return - def_w = min(max_dim, self.cols * cw) - def_h = min(max_dim, self.rows * ch) - if pa == 1: - cur_w, cur_h = ( - self._sixel_geometry_px - if self._sixel_geometry_px is not None - else (def_w, def_h) - ) - self._emit_reply( - f"\x1b[?2;0;{min(max_dim, cur_w)};{min(max_dim, cur_h)}S".encode( - "ascii", - ), - ) - elif pa == 2: - if self._sixel_geometry_px is not None: - self._before_mutate() - self._sixel_geometry_px = None - self._emit_reply(f"\x1b[?2;0;{def_w};{def_h}S".encode("ascii")) - elif ( - pa == 3 - and q_cfg.xtsmgraphics_set_enabled - and len(params.values) == 4 - and (params.omitted_mask & 0b1100) == 0 - and params.values[2] >= 1 - and params.values[3] >= 1 - ): - clamped_geo = ( - min(params.values[2], max_dim), - min(params.values[3], max_dim), - ) - if self._sixel_geometry_px != clamped_geo: - self._before_mutate() - self._sixel_geometry_px = clamped_geo - self._emit_reply( - f"\x1b[?2;0;{clamped_geo[0]};{clamped_geo[1]}S".encode("ascii"), - ) - elif pa == 4: - self._emit_reply(f"\x1b[?2;0;{max_dim};{max_dim}S".encode("ascii")) - else: - self._emit_reply(b"\x1b[?2;3S") + if mode == Mode.DECCOLM: + self._apply_deccolm(enabled=enabled) return - self._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) - - def _xtsave_modes(self, params: CsiParams) -> None: - r"""Save DEC private mode flags for ``XTSAVE`` (``CSI ? Pm s``). - - When *params* carries no arguments (``CSI ? s``), snapshots every - profile-supported DEC private mode except ``?1048``; otherwise saves - each explicit ``Pm`` code while ignoring omitted parameters. - - Parameters - ---------- - params : CsiParams - Parsed ``CSI ? ... s`` parameter list. - - References - ---------- - - `xterm Control Sequences — XTSAVE (CSI ? Pm s) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) - <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L57-L68>`__ - - `tmux/tmux input.c (3.8) - <https://github.com/tmux/tmux/blob/3.8/input.c#L1945-L1993>`__ - - Examples - -------- - >>> from libvt.modes import Mode - >>> from libvt.terminal import Terminal - >>> term = Terminal(rows=4, cols=10) - >>> term.feed(b"\x1b[?2004h\x1b[?2004s\x1b[?2004l") - >>> term.modes.is_set(Mode.BRACKETED_PASTE) - False - >>> term._saved_private_modes[Mode.BRACKETED_PASTE] - True - """ - if not self._profile.screen.xtsave_enabled: - return - if not params.values: - entered_alt = next( - iter(self._modes.enabled_modes() & ALT_SCREEN_MODES), - Mode.ALT_SCREEN, - ) - for alt_m in ALT_SCREEN_MODES: - if alt_m != entered_alt: - self._saved_private_modes.pop(alt_m, None) - targets = [ - m - for m in Mode - if (int(m) & DEC_PRIVATE_MASK) - and m not in (Mode.DECSC_1048, Mode.SYNCHRONIZED_OUTPUT) - and (m not in ALT_SCREEN_MODES or m == entered_alt) - and self._is_private_mode_supported(m) - ] - else: - targets = [] - for idx, code in enumerate(params.values): - if (params.omitted_mask >> idx) & 1: - continue - if not (0 <= code < DEC_PRIVATE_MASK): - continue - try: - m = Mode(DEC_PRIVATE_MASK | code) - except ValueError: - continue - if m != Mode.DECSC_1048 and self._is_private_mode_supported(m): - targets.append(m) - for m in targets: - if m in ALT_SCREEN_MODES: - for alt_m in ALT_SCREEN_MODES: - if alt_m != m: - self._saved_private_modes.pop(alt_m, None) - self._saved_private_modes[m] = self._screens.active_is_alt - else: - self._saved_private_modes[m] = self._modes.is_set(m) - - def _xtrestore_modes(self, params: CsiParams) -> None: - r"""Restore saved DEC private modes for ``XTRESTORE`` (``CSI ? Pm r``). - - Applies each previously saved mode whose effective state differs from - the saved value through :meth:`_apply_mode` so screen-switching - (``?1049``), synchronized-output (``?2026``), and margin (``?69``) - transitions execute identically to ``DECSET`` / ``DECRST`` without - disturbing unchanged modes. - - Parameters - ---------- - params : CsiParams - Parsed ``CSI ? ... r`` parameter list. - - References - ---------- - - `xterm Control Sequences — XTRESTORE (CSI ? Pm r) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) - <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L70-L79>`__ - - Examples - -------- - >>> from libvt.modes import Mode - >>> from libvt.terminal import Terminal - >>> term = Terminal(rows=4, cols=10) - >>> term.feed(b"\x1b[?2004h\x1b[?2004s\x1b[?2004l\x1b[?2004r") - >>> term.modes.is_set(Mode.BRACKETED_PASTE) - True - """ - if not self._profile.screen.xtsave_enabled or not self._saved_private_modes: - return - if not params.values: - items = [ - (m, v) - for m, v in self._saved_private_modes.items() - if m != Mode.SYNCHRONIZED_OUTPUT - ] - else: - items = [] - for idx, code in enumerate(params.values): - if (params.omitted_mask >> idx) & 1: - continue - if not (0 <= code < DEC_PRIVATE_MASK): - continue - try: - m = Mode(DEC_PRIVATE_MASK | code) - except ValueError: - continue - if m in ALT_SCREEN_MODES: - saved_alt = next( - ( - self._saved_private_modes[alt_m] - for alt_m in ALT_SCREEN_MODES - if alt_m in self._saved_private_modes - ), - None, - ) - if saved_alt is not None: - items.append((m, saved_alt)) - elif m in self._saved_private_modes: - items.append((m, self._saved_private_modes[m])) - items.sort( - key=lambda item: ( - 0 - if item[0] == Mode.DECNCSM - else ( - 1 - if ( - item[0] != Mode.DECCOLM - and not (item[0] == Mode.ALLOW_80_132 and not item[1]) - ) - else (2 if item[0] == Mode.DECCOLM else 3) - ) - ), - ) - for m, saved_enabled in items: - cur_enabled = ( - self._screens.active_is_alt - if m in ALT_SCREEN_MODES - else self._modes.is_set(m) - ) - if cur_enabled == saved_enabled: - continue - self._apply_mode( - int(m) & ~DEC_PRIVATE_MASK, - private=True, - enabled=saved_enabled, - ) - - def _apply_deccolm(self, *, enabled: bool) -> None: - deccolm_cfg = self._profile.screen.deccolm - if deccolm_cfg == DeccolmBehavior.IGNORE: - return - if deccolm_cfg == DeccolmBehavior.CLEAR_ONLY: - scr = self._screens.active - top, _, left, _ = self._effective_margins(scr) - decom = self._modes.is_set(Mode.DECOM) - self._set_cursor( - scr, - top if decom else 0, - left if decom else 0, - pending_wrap=False, - ) - self._erase_display(scr, 2, selective=False) - return - if deccolm_cfg == DeccolmBehavior.GATED_BY_MODE_40 and not self._modes.is_set( - Mode.ALLOW_80_132 - ): - return - - self._before_mutate() - self._clear_cluster_anchor() - self._modes.set_mode(Mode.DECCOLM, enabled=enabled) - target_cols = 132 if enabled else 80 - if self.cols != target_cols: - self.resize(rows=self.rows, cols=target_cols, reflow=False) - scr = self._screens.active - scr.scroll_region = ScrollRegion( - top=0, - bottom=scr.rows - 1, - left=0, - right=scr.cols - 1, - ) - if not self._modes.is_set(Mode.DECNCSM): - bce_w, bce_e = self._bce_pair() - for r in range(scr.rows): - scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e) - scr._rows[r].wrapped = False - if scr._gfx is not None: - scr._gfx.clear_active_screen(scr._scrolled_total, scr.rows) - self._notify_erase(Rect(0, 0, scr.rows, scr.cols), EraseCause.ED) - self._set_cursor(scr, 0, 0, pending_wrap=False) - - def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: - if not (0 <= code < DEC_PRIVATE_MASK): - return - raw = (DEC_PRIVATE_MASK | code) if private else code - try: - mode = Mode(raw) - except ValueError: - return - - if mode == Mode.SYNCHRONIZED_OUTPUT: - self._set_synchronized_output(enabled) - return - - if mode == Mode.DECCOLM: - self._apply_deccolm(enabled=enabled) - return - - if mode in ( - Mode.ALLOW_80_132, - Mode.DECNCSM, - ) and not self._is_private_mode_supported(mode): - return - - if mode == Mode.DECLRMM and not self._profile.screen.declrmm_enabled: - return - - if mode == Mode.DECSC_1048 and self._profile.screen.separate_alt_save_cursor: - return - - if mode == Mode.MOUSE_SGR_PIXELS and ( - self._profile.screen.cell_width_px <= 0 - or self._profile.screen.cell_height_px <= 0 - ): - return + if private and not is_private_mode_supported(mode, self._profile): + return if mode in ALT_SCREEN_MODES: self._before_mutate() @@ -4264,693 +3851,7 @@ def _handle_csi( intermediates: bytes, final: int, ) -> None: - prev_printed = self._last_printed - self._interrupt_rep() - if params.colon_mask != 0 and not ( - prefix == 0 and not intermediates and final == ord("m") - ): - return - scr = self._screens.active - top, bottom, left, right = self._effective_margins(scr) - - # DA2: CSI > Ps c - if prefix == ord(">") and not intermediates and final == ord("c"): - if params.raw_or_default(0, 0) == 0 and self._profile.identity.da2: - self._emit_reply(self._profile.identity.da2) - return - - # XTVERSION: CSI > q - if prefix == ord(">") and not intermediates and final == ord("q"): - if self._profile.identity.xtversion: - self._emit_reply( - f"\x1bP>|{self._profile.identity.xtversion}\x1b\\".encode("ascii") - ) - return - - # Kitty keyboard protocol: CSI > flags u | CSI < n u | CSI = flags;m u | CSI ? u - if ( - not intermediates - and final == ord("u") - and prefix - in ( - ord(">"), - ord("<"), - ord("="), - ord("?"), - ) - ): - kbd = scr.keyboard_stack - if prefix == ord("?"): - if self._profile.queries.kitty_keyboard_query_enabled: - self._emit_reply(f"\x1b[?{int(kbd.flags)}u".encode("ascii")) - elif self._profile.input.kitty_keyboard_enabled: - if prefix == ord(">"): - kbd.push(params.raw_or_default(0, 0)) - elif prefix == ord("<"): - kbd.pop(params.get(0, 1)) - elif prefix == ord("="): - kbd.set_flags(params.raw_or_default(0, 0), params.get(1, 1)) - return - - # DECRQM: CSI ? Ps $ p or CSI Ps $ p - if intermediates == b"$" and final == ord("p"): - if prefix not in (0, ord("?")) or len(params.values) > 1: - return - private = prefix == ord("?") - code = params.raw_or_default(0, 0) - if ( - private - and code == 3 - and self._profile.screen.deccolm == DeccolmBehavior.CLEAR_ONLY - ): - pm = int(DecrpmValue.PERMANENTLY_RESET) - elif private and ( - ( - code in (3, 40, 95) - and self._profile.screen.deccolm - in (DeccolmBehavior.IGNORE, DeccolmBehavior.CLEAR_ONLY) - ) - or (code == 69 and not self._profile.screen.declrmm_enabled) - or (code == 1048 and self._profile.screen.separate_alt_save_cursor) - or ( - code == 1016 - and ( - self._profile.screen.cell_width_px <= 0 - or self._profile.screen.cell_height_px <= 0 - ) - ) - ): - pm = int(DecrpmValue.NOT_RECOGNIZED) - else: - pm = int( - self._modes.decrpm( - code, - private=private, - active_is_alt=self._screens.active_is_alt, - ), - ) - q = "?" if private else "" - self._emit_reply(f"\x1b[{q}{code};{pm}$y".encode("ascii")) - return - - # DECSTR: CSI ! p - if prefix == 0 and intermediates == b"!" and final == ord("p"): - if self._profile.screen.decstr_enabled: - self.reset(soft=True) - return - - # DECSCUSR: CSI Ps SP q - if prefix == 0 and intermediates == b" " and final == ord("q"): - self._before_mutate() - ps = params.raw_or_default(0, 0) - shape = CursorShape.BLOCK - blinking = True - if ps == 2: - shape, blinking = CursorShape.BLOCK, False - elif ps == 3: - shape, blinking = CursorShape.UNDERLINE, True - elif ps == 4: - shape, blinking = CursorShape.UNDERLINE, False - elif ps == 5: - shape, blinking = CursorShape.BAR, True - elif ps == 6: - shape, blinking = CursorShape.BAR, False - scr._cur_shape = shape - scr._cur_blinking = blinking - return - - # DECSCA: CSI Ps " q (character protection attribute) - if prefix == 0 and intermediates == b'"' and final == ord("q"): - ps = params.raw_or_default(0, 0) - self._before_mutate() - self._protected = ps == 1 - self._sync_pen_cache() - return - - # DECRQCRA: CSI Pid ; Pp ; Pt ; Pl ; Pb ; Pr * y (dispatched no-op) - if prefix == 0 and intermediates == b"*" and final == ord("y"): - return - - if intermediates: - inter_s = intermediates.decode("ascii", errors="replace") - pfx_s = chr(prefix) if prefix else "" - self._unhandled("csi", f"CSI {pfx_s}{inter_s}{chr(final)}") - return - - if prefix == ord("?"): - if final in (ord("h"), ord("l")): - enable = final == ord("h") - for val in params.values: - self._apply_mode(val, private=True, enabled=enable) - elif final == ord("J"): # DECSED - self._erase_display(scr, params.raw_or_default(0, 0), selective=True) - elif final == ord("K"): # DECSEL - self._erase_line(scr, params.raw_or_default(0, 0), selective=True) - elif final == ord("n"): # Private DSR (?6n DECXCPR, ?996n color scheme) - ps = params.raw_or_default(0, 0) - if ps == 6: - phantom_extra = ( - 1 - if ( - self._profile.screen.pending_wrap_phantom_col - and scr._pending_wrap - ) - else 0 - ) - r_out = ( - (scr._cur_row - top + 1) - if self._modes.is_set(Mode.DECOM) - else (scr._cur_row + 1) - ) - c_out = ( - (scr._cur_col - left + 1 + phantom_extra) - if self._modes.is_set(Mode.DECOM) - else (scr._cur_col + 1 + phantom_extra) - ) - self._emit_reply(f"\x1b[?{r_out};{c_out}R".encode("ascii")) - elif ps == 996 and self._policy.allow_color_queries: - scheme = self._host_scheme - self._emit_reply(f"\x1b[?997;{int(scheme)}n".encode("ascii")) - self._emit_event(ColorSchemeQueried(scheme=scheme)) - elif final == ord("m"): # XTQMODKEYS: CSI ? Pp m - if ( - self._profile.input.modify_other_keys_enabled - and len(params.values) == 1 - and params.raw_or_default(0, -1) == 4 - ): - self._emit_reply( - f"\x1b[>4;{scr._modify_other_keys}m".encode("ascii"), - ) - elif final == ord("S") and 1 <= len(params.values) <= 4: # XTSMGRAPHICS - self._handle_xtsmgraphics(params) - elif final == ord("s"): # XTSAVE: CSI ? Pm s - self._xtsave_modes(params) - elif final == ord("r"): # XTRESTORE: CSI ? Pm r - self._xtrestore_modes(params) - return - - if prefix != 0: - if prefix == ord(">") and final == ord("m"): - if not self._profile.input.modify_other_keys_enabled: - return - if not params.values: - if scr._modify_other_keys != 0: - self._before_mutate() - scr._modify_other_keys = 0 - elif len(params.values) <= 2: - pp = params.raw_or_default(0, 0) - if pp == 0 and len(params.values) == 1: - if scr._modify_other_keys != 0: - self._before_mutate() - scr._modify_other_keys = 0 - elif pp == 4: - pv = ( - params.raw_or_default(1, 0) - if len(params.values) == 2 - else 0 - ) - if pv in (0, 1, 2) and scr._modify_other_keys != pv: - self._before_mutate() - scr._modify_other_keys = pv - return - if prefix == ord(">") and final == ord("n"): - if ( - self._profile.input.modify_other_keys_enabled - and ( - not params.values - or ( - len(params.values) == 1 - and params.raw_or_default(0, -1) in (0, 4) - ) - ) - and scr._modify_other_keys != 0 - ): - self._before_mutate() - scr._modify_other_keys = 0 - return - self._unhandled("csi", f"CSI {chr(prefix)}{chr(final)}") - return - - ch_final = chr(final) - c_row = scr._cur_row - c_col = scr._cur_col - - if ch_final == "m": - self._before_mutate() - self._style = parse_sgr(params, self._style, memo=self._sgr_memo) - self._sync_pen_cache() - elif ch_final in ("h", "l"): - enable = ch_final == "h" - for val in params.values: - self._apply_mode(val, private=False, enabled=enable) - elif ch_final == "A": # CUU - n = params.get(0, 1) - floor = top if c_row >= top else 0 - self._set_cursor(scr, max(floor, c_row - n), c_col) - elif ch_final == "B": # CUD - n = params.get(0, 1) - ceil = bottom if c_row <= bottom else scr.rows - 1 - self._set_cursor(scr, min(ceil, c_row + n), c_col) - elif ch_final == "C": # CUF - n = params.get(0, 1) - ceil = right if c_col <= right else scr.cols - 1 - self._set_cursor(scr, c_row, min(ceil, c_col + n)) - elif ch_final == "D": # CUB - self._cursor_left(scr, params.get(0, 1), is_backspace=False) - elif ch_final == "E": # CNL - n = params.get(0, 1) - ceil = bottom if c_row <= bottom else scr.rows - 1 - self._set_cursor(scr, min(ceil, c_row + n), left) - elif ch_final == "F": # CPL - n = params.get(0, 1) - floor = top if c_row >= top else 0 - self._set_cursor(scr, max(floor, c_row - n), left) - elif ch_final in ("G", "`"): # CHA / HPA - col_1 = params.get(0, 1) - if self._modes.is_set(Mode.DECOM): - target_c = min(right, left + col_1 - 1) - else: - target_c = min(scr.cols - 1, col_1 - 1) - self._set_cursor(scr, c_row, max(0, target_c)) - elif ch_final == "I": # CHT (Cursor Forward Tabulation) - self._forward_tab(scr, params.get(0, 1), right) - elif ch_final == "Z": # CBT (Cursor Backward Tabulation) - count = params.get(0, 1) - floor = left if c_col >= left else 0 - col_iter = c_col - for _ in range(count): - prev_tabs = [ - t_c for t_c in scr._tabstops_sorted if floor <= t_c < col_iter - ] - col_iter = prev_tabs[-1] if prev_tabs else floor - if col_iter <= floor: - break - pending = ( - scr._pending_wrap and self._profile.screen.cbt_preserves_pending_wrap - ) - self._set_cursor(scr, c_row, col_iter, pending_wrap=pending) - elif ch_final == "a": # HPR - if not self._profile.screen.hpr_vpr_enabled: - return - n = params.get(0, 1) - ceil = right if self._modes.is_set(Mode.DECOM) else scr.cols - 1 - self._set_cursor(scr, c_row, min(ceil, c_col + n), pending_wrap=False) - elif ch_final == "d": # VPA - row_1 = params.get(0, 1) - if self._modes.is_set(Mode.DECOM): - target_r = min(bottom, top + row_1 - 1) - else: - target_r = min(scr.rows - 1, row_1 - 1) - keep_wrap = ( - self._profile.screen.pending_wrap_phantom_col and scr._pending_wrap - ) - self._set_cursor(scr, max(0, target_r), c_col, pending_wrap=keep_wrap) - elif ch_final == "e": # VPR - if not self._profile.screen.hpr_vpr_enabled: - return - n = params.get(0, 1) - ceil = bottom if self._modes.is_set(Mode.DECOM) else scr.rows - 1 - self._set_cursor(scr, min(ceil, c_row + n), c_col, pending_wrap=False) - elif ch_final in ("H", "f"): # CUP / HVP - row_1 = params.get(0, 1) - col_1 = params.get(1, 1) - if self._modes.is_set(Mode.DECOM): - r = min(bottom, max(top, top + row_1 - 1)) - c = min(right, max(left, left + col_1 - 1)) - else: - r = min(scr.rows - 1, max(0, row_1 - 1)) - c = min(scr.cols - 1, max(0, col_1 - 1)) - self._set_cursor(scr, r, c) - elif ch_final == "J": # ED - self._erase_display(scr, params.raw_or_default(0, 0), selective=False) - elif ch_final == "K": # EL - self._erase_line(scr, params.raw_or_default(0, 0), selective=False) - elif ch_final == "X": # ECH - if self._profile.screen.pending_wrap_phantom_col and scr._pending_wrap: - return - self._before_mutate() - n = min(scr.cols - c_col, params.get(0, 1)) - bce_w, bce_e = self._bce_pair() - scr.heal_before_edit(c_row, c_col, c_col + n) - scr._rows[c_row].clear_range(c_col, c_col + n, bce_w, bce_e) - if c_col + n >= scr.cols: - scr._rows[c_row].wrapped = False - if scr._gfx is not None and scr._gfx.has_sixels: - scr._gfx.erase_sixel_rect( - row=c_row, - col=c_col, - rows=1, - cols=n, - scrolled_total=scr._scrolled_total, - policy=self._profile.screen.sixel_erase_policy, - ) - self._notify_erase(Rect(c_row, c_col, 1, n), EraseCause.ECH) - self._set_cursor(scr, c_row, c_col, pending_wrap=False) - elif ch_final == "@": # ICH - if self._profile.screen.pending_wrap_phantom_col and scr._pending_wrap: - return - self._before_mutate() - if left <= c_col <= right: - n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() - scr.heal_before_edit(c_row, c_col, right + 1) - scr._rows[c_row].insert_blanks( - c_col, - n, - left=left, - right=right, - bce_word=bce_w, - bce_ext=bce_e, - ) - if scr._gfx is not None and scr._gfx.has_sixels: - scr._gfx.erase_sixel_rect( - row=c_row, - col=c_col, - rows=1, - cols=right - c_col + 1, - scrolled_total=scr._scrolled_total, - policy=self._profile.screen.sixel_erase_policy, - ) - self._set_cursor(scr, c_row, c_col, pending_wrap=False) - elif ch_final == "P": # DCH - if self._profile.screen.pending_wrap_phantom_col and scr._pending_wrap: - return - self._before_mutate() - if left <= c_col <= right: - n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() - scr.heal_before_edit(c_row, c_col, right + 1) - if ( - c_col == 0 - and left == 0 - and c_row > 0 - and scr._rows[c_row - 1].wrapped - ): - scr._rows[c_row - 1].wrapped = False - scr._rows[c_row].delete_cells( - c_col, - n, - left=left, - right=right, - bce_word=bce_w, - bce_ext=bce_e, - ) - if right == scr.cols - 1: - scr._rows[c_row].wrapped = False - if scr._gfx is not None and scr._gfx.has_sixels: - scr._gfx.erase_sixel_rect( - row=c_row, - col=c_col, - rows=1, - cols=right - c_col + 1, - scrolled_total=scr._scrolled_total, - policy=self._profile.screen.sixel_erase_policy, - ) - self._set_cursor(scr, c_row, c_col, pending_wrap=False) - elif ch_final == "L": # IL - if top <= c_row <= bottom and left <= c_col <= right: - self._before_mutate() - n = params.get(0, 1) - bce_w, _ = self._bce_pair() - keep_wrap = ( - not self._profile.screen.il_dl_resets_col - and self._profile.screen.pending_wrap_phantom_col - and scr._pending_wrap - ) - scr.scroll_down( - n, - top=c_row, - bottom=bottom, - left=left, - right=right, - bce_word=bce_w, - is_line_op=True, - ) - self._notify_erase( - Rect(c_row, left, min(n, bottom - c_row + 1), right - left + 1), - EraseCause.SCROLL, - ) - target_col = left if self._profile.screen.il_dl_resets_col else c_col - self._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap) - elif ch_final == "M": # DL - if top <= c_row <= bottom and left <= c_col <= right: - self._before_mutate() - n = params.get(0, 1) - bce_w, _ = self._bce_pair() - keep_wrap = ( - not self._profile.screen.il_dl_resets_col - and self._profile.screen.pending_wrap_phantom_col - and scr._pending_wrap - ) - scr.scroll_up( - n, - top=c_row, - bottom=bottom, - left=left, - right=right, - save_history=False, - bce_word=bce_w, - is_line_op=True, - ) - self._notify_erase( - Rect( - max(c_row, bottom - n + 1), - left, - min(n, bottom - c_row + 1), - right - left + 1, - ), - EraseCause.SCROLL, - ) - target_col = left if self._profile.screen.il_dl_resets_col else c_col - self._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap) - elif ch_final == "S": # SU - self._before_mutate() - region_h = bottom - top + 1 - n = min(params.get(0, 1), region_h) - prev_scrolled = scr._scrolled_total - bce_w, _ = self._bce_pair() - scr.scroll_up( - n, - top=top, - bottom=bottom, - left=left, - right=right, - save_history=not self._screens.active_is_alt, - bce_word=bce_w, - ) - hist_delta = scr._scrolled_total - prev_scrolled - if hist_delta > 0 and left == 0 and right == scr.cols - 1: - self._remap_prompt_zones_on_scroll( - prev_scrolled, - top=top, - bottom=bottom, - rows=scr.rows, - hist_delta=hist_delta, - ) - self._notify_erase( - Rect( - max(top, bottom - n + 1), - left, - min(n, region_h), - right - left + 1, - ), - EraseCause.SCROLL, - ) - self._clear_cluster_anchor() - elif ch_final == "T": # SD - self._before_mutate() - n = params.get(0, 1) - bce_w, _ = self._bce_pair() - scr.scroll_down( - n, - top=top, - bottom=bottom, - left=left, - right=right, - bce_word=bce_w, - ) - self._notify_erase( - Rect(top, left, min(n, bottom - top + 1), right - left + 1), - EraseCause.SCROLL, - ) - self._clear_cluster_anchor() - elif ch_final == "b": # REP - if prev_printed: - count = min(self._limits.max_rep_count, params.get(0, 1)) - if not self._profile.screen.rep_wraps and self._modes.is_set( - Mode.DECAWM - ): - if ( - scr._pending_wrap - and self._profile.screen.pending_wrap_phantom_col - ): - self._last_printed = prev_printed - else: - w = max( - 1, - display_width( - prev_printed, - mode_2027=self._modes.is_set(Mode.GRAPHEME_CLUSTERING), - profile=self._profile, - ), - ) - max_c = right if c_col <= right else scr.cols - 1 - avail_cols = max_c - c_col + 1 - fit = max(0, avail_cols // w) - if fit > 0: - self._handle_print(prev_printed * min(count, fit)) - self._last_printed = prev_printed - else: - self._handle_print(prev_printed * count) - elif ch_final == "r": # DECSTBM - t_arg = params.get(0, 1) - 1 - b_arg = params.get(1, scr.rows) - 1 - t_clamped = max(0, min(scr.rows - 1, t_arg)) - b_clamped = max(0, min(scr.rows - 1, b_arg)) - if t_clamped < b_clamped: - sr = scr.scroll_region - scr.scroll_region = ScrollRegion( - top=t_clamped, - bottom=b_clamped, - left=sr.left, - right=sr.right, - ) - decom = self._modes.is_set(Mode.DECOM) - _, _, eff_left, _ = self._effective_margins(scr) - self._set_cursor( - scr, - t_clamped if decom else 0, - eff_left if decom else 0, - ) - elif ch_final == "s": # DECSLRM (when ?69 set) or SCOSC - if self._modes.is_set(Mode.DECLRMM): - if len(params.values) <= 2: - l_arg = params.get(0, 1) - 1 - r_arg = params.get(1, scr.cols) - 1 - l_clamped = max(0, min(scr.cols - 1, l_arg)) - r_clamped = max(0, min(scr.cols - 1, r_arg)) - if l_clamped < r_clamped: - sr = scr.scroll_region - scr.scroll_region = ScrollRegion( - top=sr.top, - bottom=sr.bottom, - left=l_clamped, - right=r_clamped, - ) - decom = self._modes.is_set(Mode.DECOM) - self._set_cursor( - scr, - sr.top if decom else 0, - l_clamped if decom else 0, - ) - elif not self._profile.screen.declrmm_enabled or not params.values: - self._save_cursor() - elif ch_final == "u": # SCORC - self._restore_cursor() - elif ch_final == "g": # TBC - mode = params.raw_or_default(0, 0) - if mode == 0: - scr.clear_tabstop(c_col) - elif mode == 3: - scr.clear_all_tabstops() - elif ch_final == "c": # DA1 - if params.raw_or_default(0, 0) == 0 and self._profile.identity.da1: - self._emit_reply(self._profile.identity.da1) - elif ch_final == "n": # DSR - ps = params.raw_or_default(0, 0) - if ps == 5: - self._emit_reply(b"\x1b[0n") - elif ps == 6: - phantom_extra = ( - 1 - if ( - self._profile.screen.pending_wrap_phantom_col - and scr._pending_wrap - ) - else 0 - ) - r_out = ( - (c_row - top + 1) if self._modes.is_set(Mode.DECOM) else (c_row + 1) - ) - c_out = ( - (c_col - left + 1 + phantom_extra) - if self._modes.is_set(Mode.DECOM) - else (c_col + 1 + phantom_extra) - ) - self._emit_reply(f"\x1b[{r_out};{c_out}R".encode("ascii")) - elif ch_final == "t": # XTWINOPS - op = params.raw_or_default(0, 0) - if op == 18: # report text area size in chars - self._emit_reply(f"\x1b[8;{scr.rows};{scr.cols}t".encode("ascii")) - elif op == 14: # report text area size in pixels - px_h = scr.rows * max(0, self._profile.screen.cell_height_px) - px_w = scr.cols * max(0, self._profile.screen.cell_width_px) - self._emit_reply(f"\x1b[4;{px_h};{px_w}t".encode("ascii")) - elif op == 16: # report cell size in pixels - ch_px = max(0, self._profile.screen.cell_height_px) - cw_px = max(0, self._profile.screen.cell_width_px) - self._emit_reply(f"\x1b[6;{ch_px};{cw_px}t".encode("ascii")) - elif op == 21 and self._policy.allow_title_report: - safe_title = "".join( - ch for ch in self._title if " " <= ch <= "~" and ch != "\\" - ) - self._emit_reply(f"\x1b]l{safe_title}\x1b\\".encode("ascii")) - elif op == 22: # push icon/window title onto stack - sub_op = params.raw_or_default(1, 0) - if sub_op in (0, 1) and len(self._icon_title_stack) < 16: - self._icon_title_stack.append(self._icon_title) - if sub_op in (0, 2) and len(self._title_stack) < 16: - self._title_stack.append(self._title) - elif op == 23: # pop icon/window title from stack - sub_op = params.raw_or_default(1, 0) - if sub_op == 0: - pop_icon = bool(self._icon_title_stack) - pop_win = bool(self._title_stack) - if pop_icon or pop_win: - self._before_mutate() - if pop_icon: - self._icon_title = self._icon_title_stack.pop() - if pop_win: - self._title = self._title_stack.pop() - self._aux_revision += 1 - if pop_icon and pop_win and self._icon_title == self._title: - self._emit_event( - TitleChanged( - title=self._title, - target=TitleTarget.BOTH, - ) - ) - else: - if pop_icon: - self._emit_event( - TitleChanged( - title=self._icon_title, - target=TitleTarget.ICON, - ) - ) - if pop_win: - self._emit_event( - TitleChanged( - title=self._title, - target=TitleTarget.WINDOW, - ) - ) - elif sub_op == 1 and self._icon_title_stack: - self._before_mutate() - self._icon_title = self._icon_title_stack.pop() - self._aux_revision += 1 - self._emit_event( - TitleChanged(title=self._icon_title, target=TitleTarget.ICON) - ) - elif sub_op == 2 and self._title_stack: - self._before_mutate() - self._title = self._title_stack.pop() - self._aux_revision += 1 - self._emit_event( - TitleChanged(title=self._title, target=TitleTarget.WINDOW) - ) - else: - self._unhandled("csi", f"CSI {ch_final}") + handle_csi(self, prefix, params, intermediates, final) def _handle_window_rename(self, raw: bytes) -> None: self._interrupt_rep() @@ -5192,593 +4093,10 @@ def _cap_sanitized_bytes( >>> Terminal._cap_sanitized_bytes(b"ok\x01", 5) ('ok', 2) """ - if max_bytes <= 0 or not raw: - return ("", 0) - decoded = bytes(raw[:max_bytes]).decode("utf-8", errors="ignore") - sanitized = sanitize_terminal_text(decoded) - enc = sanitized.encode("utf-8") - if len(enc) <= max_bytes: - return (sanitized, len(enc)) - out: list[str] = [] - used = 0 - for ch in decoded: - frag = sanitize_terminal_text(ch) - cost = len(frag.encode("utf-8")) - if used + cost > max_bytes: - break - out.append(frag) - used += cost - return ("".join(out), used) - - def _handle_osc_777(self, data: bytes) -> None: - r"""Parse ``OSC 777 ; notify ; <title> ; <body>`` desktop notifications. - - References - ---------- - - `ghostty-org/ghostty rxvt_extension.zig (v1.4.0) - <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/osc/parsers/rxvt_extension.zig#L8-L45>`__ - - Examples - -------- - >>> from libvt.terminal import Terminal - >>> term = Terminal(record_events=True) - >>> term.feed(b"\x1b]777;notify;Alert;Done\x07") - >>> term.drain_events()[0].title - 'Alert' - """ - if not self._policy.allow_notifications: - return - k = data.find(b";") - if k == -1 or data[:k] != b"notify": - return - t_sep = data.find(b";", k + 1) - if t_sep == -1: - return - max_nb = max(0, self._limits.max_notification_bytes) - title_s, title_used = self._cap_sanitized_bytes(data[k + 1 : t_sep], max_nb) - body_s, _ = self._cap_sanitized_bytes( - data[t_sep + 1 :], - max(0, max_nb - title_used), - ) - if not title_s and not body_s: - return - self._emit_event( - Notification( - source=NotificationSource.OSC_777, - title=title_s, - body=body_s, - ), - ) - - def _handle_osc_99(self, data: bytes, out_term: bytes) -> None: - r"""Parse Kitty ``OSC 99 ; <metadata> ; <payload>`` desktop notifications. - - Supports ``i=`` identifiers, ``d=0``/``1`` multi-chunk reassembly - bounded by :attr:`~libvt.config.Limits.max_pending_notifications` and - :attr:`~libvt.config.Limits.max_notification_bytes`, ``e=1`` Base64 - decoding, ``p=title``/``body``/``?``/``close``/``alive``, and - ``u=0``/``1``/``2`` urgency levels. - - References - ---------- - - `Kitty Desktop Notification Protocol (OSC 99) - <https://sw.kovidgoyal.net/kitty/desktop-notifications/>`__ - - `ghostty-org/ghostty kitty_desktop_notification.zig (v1.4.0) - <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/osc/parsers/kitty_desktop_notification.zig#L287-L335>`__ - - Examples - -------- - >>> from libvt.terminal import Terminal - >>> term = Terminal(record_events=True) - >>> term.feed(b"\x1b]99;i=n1:d=0:p=title;Hi\x1b\\") - >>> term.feed(b"\x1b]99;i=n1:d=1:p=body;Ok\x1b\\") - >>> ev = term.drain_events()[0] - >>> (ev.notification_id, ev.title, ev.body) - ('n1', 'Hi', 'Ok') - """ - if not self._policy.allow_notifications: - return - sep = data.find(b";") - if sep == -1 or not data[:sep].isascii(): - return - meta_s = data[:sep].decode("ascii") - payload_b = data[sep + 1 :] - - notif_id = "" - done = True - b64 = False - ptype = "title" - urgency: NotificationUrgency | None = None - if meta_s: - for item in meta_s.split(":"): - eq = item.find("=") - if eq == -1: - continue - key = item[:eq] - val = item[eq + 1 :] - if key == "i": - if val and all( - "a" <= ch <= "z" - or "A" <= ch <= "Z" - or "0" <= ch <= "9" - or ch in "-_+." - for ch in val - ): - notif_id = val[:128] - elif key == "d": - done = val != "0" - elif key == "e": - b64 = val == "1" - elif key == "p": - ptype = val or "unknown" - elif key == "u": - if val == "0": - urgency = NotificationUrgency.LOW - elif val == "1": - urgency = NotificationUrgency.NORMAL - elif val == "2": - urgency = NotificationUrgency.HIGH - - if ptype == "?": - if self._policy.allow_notification_queries: - qid = notif_id or "0" - reply = ( - f"\x1b]99;i={qid}:p=?;p=title,body:a=focus:u=0,1,2".encode("ascii") - + out_term - ) - self._emit_reply(reply) - return - - if ptype in ("close", "alive"): - self._pending_osc99.pop(notif_id, None) - return - - max_nb = max(0, self._limits.max_notification_bytes) - max_pend = max(0, self._limits.max_pending_notifications) - entry = self._pending_osc99.get(notif_id) - if entry is None: - title_buf = bytearray() - body_buf = bytearray() - cur_urg = urgency if urgency is not None else NotificationUrgency.NORMAL - used = 0 - else: - title_buf, body_buf, prev_urg, used = entry - cur_urg = urgency if urgency is not None else prev_urg - - rem = max(0, max_nb - used) - if ptype in ("title", "body"): - if b64: - cleaned = payload_b.strip(b" \t\r\n") - if len(cleaned) % 4 == 1: - return - padded = cleaned + (b"=" * ((-len(cleaned)) % 4)) - try: - decoded_b = ( - base64.b64decode(padded, validate=True) if rem > 0 else b"" - ) - except binascii.Error: - return - else: - decoded_b = payload_b - chunk_b = decoded_b[:rem] - used += len(chunk_b) - if ptype == "body": - body_buf.extend(chunk_b) - else: - title_buf.extend(chunk_b) - - if not done: - if max_pend > 0: - if ( - notif_id not in self._pending_osc99 - and len(self._pending_osc99) >= max_pend - ): - oldest_key = next(iter(self._pending_osc99)) - self._pending_osc99.pop(oldest_key, None) - self._pending_osc99[notif_id] = (title_buf, body_buf, cur_urg, used) - return - - self._pending_osc99.pop(notif_id, None) - title_s, title_used = self._cap_sanitized_bytes(title_buf, max_nb) - body_s, _ = self._cap_sanitized_bytes(body_buf, max(0, max_nb - title_used)) - if not title_s and not body_s: - return - self._emit_event( - Notification( - source=NotificationSource.OSC_99, - notification_id=sanitize_terminal_text(notif_id), - title=title_s, - body=body_s, - urgency=cur_urg, - ), - ) + return _cap_sanitized_bytes(raw, max_bytes) def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: - self._interrupt_rep() - out_term = b"\x07" if terminator == b"\x07" else b"\x1b\\" - - if code == 0: - self._before_mutate() - text = data.decode("utf-8", errors="replace") - self._title = text - self._icon_title = text - self._emit_event(TitleChanged(title=text, target=TitleTarget.BOTH)) - elif code == 1: - self._before_mutate() - text = data.decode("utf-8", errors="replace") - self._icon_title = text - self._aux_revision += 1 - self._emit_event(TitleChanged(title=text, target=TitleTarget.ICON)) - elif code == 2: - self._before_mutate() - text = data.decode("utf-8", errors="replace") - self._title = text - self._emit_event(TitleChanged(title=text, target=TitleTarget.WINDOW)) - elif code == 4: - if not data: - return - pos = 0 - n_data = len(data) - while pos <= n_data: - semi1 = data.find(b";", pos) - if semi1 == -1: - break - pal_idx = _parse_ascii_uint_bytes(data[pos:semi1], max_val=255) - if pal_idx is None: - break - semi2 = data.find(b";", semi1 + 1) - if semi2 == -1: - spec_b = data[semi1 + 1 :] - pos = n_data + 1 - else: - spec_b = data[semi1 + 1 : semi2] - pos = semi2 + 1 - if spec_b == b"?": - if ( - self._policy.emit_replies - and self._policy.allow_color_queries - and ( - self._on_pty_write is not None - or len(self._replies) + 24 <= self._limits.max_reply_bytes - ) - ): - rgb_val = self._effective_palette_entry(pal_idx) - reply = (f"\x1b]4;{pal_idx};{_format_osc_rgb(rgb_val)}").encode( - "ascii" - ) - self._emit_reply(reply + out_term) - continue - parsed_pal = _parse_osc_rgb(spec_b) - if parsed_pal is None: - break - if self._guest_palette.get(pal_idx) != parsed_pal: - self._before_mutate() - self._guest_palette[pal_idx] = parsed_pal - self._bump_appearance() - elif code == 7: - self._update_cwd( - data.decode("utf-8", errors="replace"), - source=CwdSource.OSC_7, - ) - elif code == 8: - text = data.decode("utf-8", errors="replace") - sep = text.find(";") - if sep == -1: - return - params_part = text[:sep] - uri = text[sep + 1 :] - self._before_mutate() - if not uri: - self._hyperlink = None - else: - link_id = "" - for kv in params_part.split(":"): - if kv.startswith("id="): - link_id = kv[3:] - break - self._hyperlink = Hyperlink(uri=uri, id=link_id) - self._sync_pen_cache() - elif code == 9: - text = data.decode("utf-8", errors="replace") - parts = text.split(";") - if ( - len(parts) >= 2 - and parts[0] == "4" - and parts[1] - in ( - "0", - "1", - "2", - "3", - "4", - ) - ): - sub = int(parts[1]) - self._before_mutate() - prog = ( - _parse_ascii_uint(parts[2], max_val=1_000) - if len(parts) >= 3 - else None - ) - changed, status = self._status_store.apply_osc_9_4(sub, prog) - if changed: - self._aux_revision += 1 - self._emit_event(ProgramStatusChanged(status=status, task_id="")) - elif len(parts) >= 2 and parts[0] == "9": - self._update_cwd(";".join(parts[1:]), source=CwdSource.OSC_9_9) - elif ( - (len(parts) == 1 and parts[0] in ("5", "10", "12")) - or ( - len(parts) == 2 - and parts[0] == "10" - and parts[1] in ("0", "1", "2", "3") - ) - or ( - len(parts) >= 2 and parts[0] in ("1", "2", "3", "6", "7", "8", "11") - ) - ): - return - elif data and self._policy.allow_notifications: - max_nb = max(0, self._limits.max_notification_bytes) - body_s, _ = self._cap_sanitized_bytes(data, max_nb) - if body_s: - self._emit_event( - Notification( - source=NotificationSource.OSC_9, - body=body_s, - ), - ) - elif code in (10, 11, 12): - if not data: - return - cur_code = code - pos = 0 - n_data = len(data) - while cur_code <= 12 and pos <= n_data: - semi = data.find(b";", pos) - if semi == -1: - spec_b = data[pos:] - pos = n_data + 1 - else: - spec_b = data[pos:semi] - pos = semi + 1 - if spec_b == b"?": - if ( - self._policy.emit_replies - and self._policy.allow_color_queries - and ( - self._on_pty_write is not None - or len(self._replies) + 23 <= self._limits.max_reply_bytes - ) - ): - cur_rgb = ( - self._effective_fg_rgb() - if cur_code == 10 - else ( - self._effective_bg_rgb() - if cur_code == 11 - else self._effective_cursor_rgb() - ) - ) - reply = (f"\x1b]{cur_code};{_format_osc_rgb(cur_rgb)}").encode( - "ascii" - ) - self._emit_reply(reply + out_term) - else: - parsed_rgb = _parse_osc_rgb(spec_b) - if parsed_rgb is None: - break - if cur_code == 10 and self._guest_fg_rgb != parsed_rgb: - self._before_mutate() - self._guest_fg_rgb = parsed_rgb - self._bump_appearance() - elif cur_code == 11 and self._guest_bg_rgb != parsed_rgb: - self._before_mutate() - self._guest_bg_rgb = parsed_rgb - self._bump_appearance() - elif cur_code == 12 and self._guest_cursor_rgb != parsed_rgb: - self._before_mutate() - self._guest_cursor_rgb = parsed_rgb - self._bump_appearance() - cur_code += 1 - elif code == 99: - self._handle_osc_99(data, out_term) - elif code == 777: - self._handle_osc_777(data) - elif code == 104: - if not self._guest_palette: - return - if not data: - self._before_mutate() - self._guest_palette.clear() - self._bump_appearance() - return - saw_nonempty = False - mutated_pal = False - pos = 0 - n_data = len(data) - while pos <= n_data: - semi = data.find(b";", pos) - if semi == -1: - tok = data[pos:] - pos = n_data + 1 - else: - tok = data[pos:semi] - pos = semi + 1 - if not tok: - continue - saw_nonempty = True - pal_idx = _parse_ascii_uint_bytes(tok, max_val=255) - if pal_idx is not None and pal_idx in self._guest_palette: - if not mutated_pal: - self._before_mutate() - mutated_pal = True - self._guest_palette.pop(pal_idx, None) - if not saw_nonempty and self._guest_palette: - self._before_mutate() - self._guest_palette.clear() - mutated_pal = True - if mutated_pal: - self._bump_appearance() - elif code == 110: - if not data and self._guest_fg_rgb is not None: - self._before_mutate() - self._guest_fg_rgb = None - self._bump_appearance() - elif code == 111: - if not data and self._guest_bg_rgb is not None: - self._before_mutate() - self._guest_bg_rgb = None - self._bump_appearance() - elif code == 112: - if not data and self._guest_cursor_rgb is not None: - self._before_mutate() - self._guest_cursor_rgb = None - self._bump_appearance() - elif code == 52: - semi = data.find(b";") - if semi == -1: - return - sel = _parse_osc52_selection(data[:semi]) - if sel is None: - return - body = data[semi + 1 :] - if body == b"?": - if self._policy.clipboard_read == ClipboardReadPolicy.EMIT_EVENT: - self._emit_event(ClipboardReadRequested(selection=sel)) - return - if self._policy.allow_clipboard_write: - try: - raw_clip = base64.b64decode(body, validate=False) - clip_text = raw_clip.decode("utf-8", errors="replace") - except (binascii.Error, ValueError): - return - self._emit_event(ClipboardWrite(selection=sel, text=clip_text)) - elif code == 133: - text = data.decode("utf-8", errors="replace") - parts = text.split(";") - raw_kind = parts[0][:1] if parts and parts[0] else "" - if raw_kind in ("A", "B", "C", "D"): - kind = PromptKind(raw_kind) - exit_code: int | None = None - is_continuation = any( - p.strip() in ("k=c", "k=s", "k=r") for p in parts[1:] - ) - if kind == PromptKind.COMMAND_FINISHED and len(parts) >= 2: - exit_code = _parse_ascii_int( - parts[1], - min_val=-2_147_483_648, - max_val=2_147_483_647, - ) - self._record_prompt_mark( - kind, - osc_code=133, - exit_code=exit_code, - is_continuation=is_continuation, - ) - elif code == 633: - text = data.decode("utf-8", errors="replace") - subcmd, sep0, rest = text.partition(";") - if subcmd in ("A", "B", "C", "D"): - parts = text.split(";") - kind = PromptKind(subcmd) - exit_code_633: int | None = None - is_cont_633 = any(p.strip() in ("k=c", "k=s", "k=r") for p in parts[1:]) - if kind == PromptKind.COMMAND_FINISHED and len(parts) >= 2: - exit_code_633 = _parse_ascii_int( - parts[1], - min_val=-2_147_483_648, - max_val=2_147_483_647, - ) - self._record_prompt_mark( - kind, - osc_code=633, - exit_code=exit_code_633, - is_continuation=is_cont_633, - ) - elif subcmd == "E" and sep0: - cmd_raw, sep_n, nonce_raw = rest.partition(";") - command = _unescape_osc_633(cmd_raw) - nonce = _unescape_osc_633(nonce_raw) if sep_n and nonce_raw else None - self._emit_event(ShellCommandReported(command=command, nonce=nonce)) - elif subcmd == "P" and sep0: - prop_field, _, _ = rest.partition(";") - prop_k_raw, sep_eq, prop_v_raw = prop_field.partition("=") - prop_k = _unescape_osc_633(prop_k_raw) - if sep_eq and prop_k: - prop_v = _unescape_osc_633(prop_v_raw) - if prop_k == "Cwd": - self._update_cwd(prop_v, source=CwdSource.OSC_633_P) - else: - self._emit_event( - ShellPropertyChanged(name=prop_k, value=prop_v) - ) - elif code == 7501: - if data == b"?": - cap = self._profile.identity.osc_7501_capabilities - if self._policy.allow_program_status_query and cap: - self._emit_reply(f"\x1b]7501;{cap}".encode("ascii") + out_term) - return - self._before_mutate() - changed, rec = self._status_store.apply_osc_7501(data) - if changed: - self._aux_revision += 1 - tid = rec.id if rec is not None else "" - self._emit_event(ProgramStatusChanged(status=rec, task_id=tid)) - else: - self._unhandled("osc", f"OSC {code}") - - def _handle_decrqss(self, req: bytes) -> None: - scr = self._screens.active - if req == b"m": - sgr_body = _style_to_sgr(self._style)[2:] # strip leading ESC [ - self._emit_reply(f"\x1bP1$r{sgr_body}\x1b\\".encode("ascii")) - elif req == b"r": - sr = scr.scroll_region - self._emit_reply( - f"\x1bP1$r{sr.top + 1};{sr.bottom + 1}r\x1b\\".encode("ascii"), - ) - elif req == b"s" and self._modes.is_set(Mode.DECLRMM): - sr = scr.scroll_region - self._emit_reply( - f"\x1bP1$r{sr.left + 1};{sr.right + 1}s\x1b\\".encode("ascii"), - ) - elif req == b" q": - shape_map = { - (CursorShape.BLOCK, True): 1, - (CursorShape.BLOCK, False): 2, - (CursorShape.UNDERLINE, True): 3, - (CursorShape.UNDERLINE, False): 4, - (CursorShape.BAR, True): 5, - (CursorShape.BAR, False): 6, - } - code = shape_map[(scr._cur_shape, scr._cur_blinking)] - self._emit_reply(f"\x1bP1$r{code} q\x1b\\".encode("ascii")) - elif req == b'"q': - code = 1 if self._protected else 0 - self._emit_reply(f'\x1bP1$r{code}"q\x1b\\'.encode("ascii")) - else: - self._emit_reply(b"\x1bP0$r\x1b\\") - - def _handle_xtgettcap(self, data: bytes) -> None: - for hex_name in data.split(b";"): - if not hex_name: - continue - try: - cap_name = bytes.fromhex(hex_name.decode("ascii")).decode("ascii") - except ValueError: - self._emit_reply(b"\x1bP0+r\x1b\\") - continue - if cap_name in _TERMINFO_CAPS: - val = _TERMINFO_CAPS[cap_name] - enc_k = _hex_encode(cap_name) - if val: - enc_v = _hex_encode(val) - self._emit_reply(f"\x1bP1+r{enc_k}={enc_v}\x1b\\".encode("ascii")) - else: - self._emit_reply(f"\x1bP1+r{enc_k}\x1b\\".encode("ascii")) - else: - self._emit_reply(b"\x1bP0+r\x1b\\") + handle_osc(self, code, data, terminator) def _handle_dcs( self, @@ -5788,119 +4106,7 @@ def _handle_dcs( final: int, data: bytes, ) -> None: - self._interrupt_rep() - # DECRQSS: DCS $ q <req> ST - if prefix == 0 and intermediates == b"$" and final == ord("q"): - if self._profile.queries.decrqss_enabled: - self._handle_decrqss(data) - return - - # XTGETTCAP: DCS + q <hex-names> ST - if prefix == 0 and intermediates == b"+" and final == ord("q"): - if self._profile.queries.xtgettcap_enabled: - self._handle_xtgettcap(data) - return - - # tmux passthrough: DCS tmux; ESC ESC ... ST (final='t', data=b"mux;...") - if ( - prefix == 0 - and not intermediates - and not params.values - and final == ord("t") - and data.startswith(b"mux;") - ): - unwrapped = bytes(memoryview(data)[4:]) - if self._record_events or self._on_event is not None: - self._emit_event(Passthrough(data=unwrapped)) - if self._policy.allow_passthrough and self._passthrough_depth < 2: - if self._passthrough_depth == 0: - if self._passthrough_parser is None: - self._passthrough_parser = Parser( - encoding=self._parser.encoding, - allow_encoding_switch=self._profile.screen.allow_encoding_switch, - tmux_window_rename=self._profile.screen.allow_esc_k_title, - abort_dispatch_osc=self._policy.abort_dispatch_osc, - limits=self._limits, - ) - inner_parser = self._passthrough_parser - else: - inner_parser = Parser( - encoding=self._parser.encoding, - allow_encoding_switch=self._profile.screen.allow_encoding_switch, - tmux_window_rename=self._profile.screen.allow_esc_k_title, - abort_dispatch_osc=self._policy.abort_dispatch_osc, - limits=self._limits, - ) - self._passthrough_depth += 1 - try: - inner_parser.feed_to(unwrapped, self._sink) - finally: - self._passthrough_depth -= 1 - return - - # SIXEL: DCS Ps... q <sixel> ST - if prefix == 0 and not intermediates and final == ord("q"): - scr = self._screens.active - orig_row, orig_col = scr._cur_row, scr._cur_col - if self._policy.track_graphics: - self._before_mutate() - decsdm = self._modes.is_set(Mode.DECSDM) - anchor_r = 0 if decsdm else orig_row - anchor_c = 0 if decsdm else orig_col - gfx = scr.ensure_graphics() - prepared = gfx.prepare_sixel( - data, - col=anchor_c, - screen_cols=scr.cols, - cell_width_px=self._profile.screen.cell_width_px, - cell_height_px=self._profile.screen.cell_height_px, - ) - if prepared is not None: - w_px, h_px, s_rows, s_cols = prepared - pre_scrolled = scr._scrolled_total - top, bottom, left, right = self._effective_margins(scr) - in_margins = top <= orig_row <= bottom and left <= orig_col <= right - if decsdm: - post_r = anchor_r - eff_rows = max(1, min(s_rows, scr.rows - anchor_r)) - min_sixel_abs = 0 - else: - post_r = self._advance_rows(scr, s_rows, final_col=0) - eff_rows = min(s_rows, max(1, scr.rows - post_r)) - if in_margins and top > 0: - min_sixel_abs = scr._scrolled_total + top - elif scr._scrolled_total == pre_scrolled: - min_sixel_abs = scr._scrolled_total + ( - top if in_margins else 0 - ) - else: - min_sixel_abs = scr._scrolled_total - len(scr._history) - gfx.commit_sixel( - payload_len=len(data), - width_px=w_px, - height_px=h_px, - row=post_r, - col=anchor_c, - rows=eff_rows, - cols=s_cols, - scrolled_total=scr._scrolled_total, - min_abs=min_sixel_abs, - ) - if self._record_events or self._on_event is not None: - self._emit_event( - SixelGraphic( - data=SixelData( - row=orig_row, - col=orig_col, - params=params.values, - payload=data, - ), - ), - ) - return - - inter_s = intermediates.decode("ascii", errors="replace") - self._unhandled("dcs", f"DCS {inter_s}{chr(final)}") + handle_dcs(self, prefix, params, intermediates, final, data) def _handle_apc(self, data: bytes) -> None: self._interrupt_rep() @@ -6095,6 +4301,7 @@ def strip(data: collections.abc.Buffer | str, /) -> str: "SyncToken", "SyncView", "Terminal", + "TerminalRecorder", "render", "strip", ] diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 67f903ae..30d566fc 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -23,6 +23,7 @@ from libvt.config import DEFAULT_PROFILE, Profile, UnicodeBehavior from libvt.exc import ScreenAssertionError from libvt.modes import ALT_SCREEN_MODES, TRANSIENT_SNAPSHOT_MODES, Mode +from libvt.recorder import find_flight_recorder from libvt.screen import Cell, RegionView, RowView, Screen from libvt.style import ( DEFAULT_STYLE, @@ -176,7 +177,7 @@ def format_flight_recorder(target: Terminal) -> str: lines.append( f" program_status={ps.state.value} id={ps.id!r} progress={ps.progress}", ) - rec = target.recorder + rec = find_flight_recorder(target.recorder) if rec is not None: tail = rec.tail(256) lines.append(f" recent_bytes ({len(tail)}/{rec.total_bytes}B): {tail!r}") diff --git a/tests/test_libvt.py b/tests/test_libvt.py index 89bd7574..dbbf16d8 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -378,6 +378,7 @@ def test_core_split_has_no_screen_to_terminal_cycle_and_keeps_reexports() -> Non import libvt._util as util_mod import libvt.format as fmt_mod + import libvt.recorder as rec_mod import libvt.screen as screen_mod import libvt.snapshot as snap_mod import libvt.terminal as term_mod @@ -407,6 +408,8 @@ def test_core_split_has_no_screen_to_terminal_cycle_and_keeps_reexports() -> Non assert getattr(term_mod, name) is getattr(snap_mod, name) for name in ("Formatter", "OutputFormat"): assert getattr(term_mod, name) is getattr(fmt_mod, name) + assert term_mod.FlightRecorder is rec_mod.FlightRecorder + assert term_mod.TerminalRecorder is rec_mod.TerminalRecorder assert callable(util_mod._byte_view) assert callable(util_mod._parse_ascii_uint) assert callable(util_mod._parse_ascii_int) diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 51214224..bc00dbac 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -2,10 +2,14 @@ from __future__ import annotations +import ast import copy import dataclasses +import inspect import pickle import random +import subprocess +import sys import time import typing as t @@ -16,6 +20,7 @@ from libvt.config import ( DEFAULT_PROFILE, ColorScheme, + DeccolmBehavior, Identity, InputBehavior, Policy, @@ -30,17 +35,22 @@ from libvt.contrib.tmux.profile import TMUX_PROFILE, tmux_profile from libvt.events import Bell, Event, RenderHoldChanged, ScreenErased from libvt.exc import ProtocolError -from libvt.modes import Mode +from libvt.modes import DecrpmValue, Mode, is_private_mode_supported from libvt.profiles import ( GHOSTTY_PROFILE, KITTY_PROFILE, LINUX_CONSOLE_PROFILE, XTERM_PROFILE, ) +from libvt.recorder import ( + CompositeRecorder, + FlightRecorder, + TerminalRecorder, + find_flight_recorder, +) from libvt.screen import CursorShape, RowView, ScrollRegion, format_rows_text from libvt.style import AnsiColor, Hyperlink from libvt.terminal import ( - FlightRecorder, Formatter, OutputFormat, ResyncReason, @@ -49,6 +59,7 @@ StopOn, SyncToken, ) +from libvt.testing import format_flight_recorder class TmuxVersionCase(t.NamedTuple): @@ -1893,3 +1904,372 @@ def test_unwrapped_viewport_preserves_hidden_historical_wrap_margin() -> None: assert region[2:].unwrapped_text == "abcdef" assert region.unwrapped_text == "ab\nC\nabcdef" assert original.unwrapped_text == "ab C" + + +def test_terminal_slots_and_lazy_graphics_import() -> None: + """``Terminal`` uses ``__slots__`` and lazy-loads ``libvt.graphics`` on demand.""" + term = libvt.Terminal(rows=2, cols=8) + assert not hasattr(term, "__dict__") + dyn_attr = "unexpected_dynamic_attr" + with pytest.raises(AttributeError): + setattr(term, dyn_attr, 123) + + sixel_script = ( + "import sys, libvt; " + "t = libvt.Terminal(rows=4, cols=10); " + "assert not hasattr(t, '__dict__'); " + "t.feed(b'\\x1b[32mplain text\\x1b[0m\\r\\n'); " + "_ = t.snapshot(); " + "assert 'libvt.graphics' not in sys.modules, 'loaded prematurely'; " + "t.feed(b'\\x1bPq\"1;1;8;16#0~\\x1b\\\\'); " + "assert 'libvt.graphics' in sys.modules; " + "assert len(t.placements) == 1" + ) + kitty_script = ( + "import base64, sys, libvt; " + "t = libvt.Terminal(rows=4, cols=10); " + "assert 'libvt.graphics' not in sys.modules; " + "raw = base64.b64encode(b'\\xff' * (8 * 16 * 3)); " + "t.feed(b'\\x1b_Ga=T,f=24,s=8,v=16,i=5;' + raw + b'\\x1b\\\\'); " + "assert 'libvt.graphics' in sys.modules; " + "assert len(t.placements) == 1" + ) + for snippet in (sixel_script, kitty_script): + proc = subprocess.run( + (sys.executable, "-c", snippet), + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, proc.stderr + + +def test_terminal_replace_from_slot_completeness_and_no_guest_leak() -> None: + """Every ``Terminal`` slot is categorized and guest state never leaks on resync.""" + all_slots = set(libvt.Terminal.__slots__) + transferred = libvt.Terminal._REPLACE_TRANSFERRED_SLOTS + preserved = libvt.Terminal._REPLACE_PRESERVED_SLOTS + reset_slots = libvt.Terminal._REPLACE_RESET_SLOTS + assert transferred.isdisjoint(preserved) + assert transferred.isdisjoint(reset_slots) + assert preserved.isdisjoint(reset_slots) + assert (transferred | preserved | reset_slots) == all_slots + + # AST-verify Terminal.replace_from handles every transferred/reset slot and + # never directly assigns to any preserved slot. + src_code = inspect.getsource(libvt.Terminal.replace_from) + dedented = "\n".join(ln.removeprefix(" ") for ln in src_code.splitlines()) + tree = ast.parse(dedented) + written_self_attrs: set[str] = set() + mutated_containers: set[str] = set() + called_sync_pen = False + for node in ast.walk(tree): + if isinstance(node, (ast.Assign, ast.AugAssign)): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + for tgt in targets: + if ( + isinstance(tgt, ast.Attribute) + and isinstance(tgt.value, ast.Name) + and tgt.value.id == "self" + ): + written_self_attrs.add(tgt.attr) + elif ( + isinstance(tgt, ast.Attribute) + and isinstance(tgt.value, ast.Attribute) + and isinstance(tgt.value.value, ast.Name) + and tgt.value.value.id == "self" + ): + mutated_containers.add(tgt.value.attr) + elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute): + if ( + isinstance(node.func.value, ast.Name) + and node.func.value.id == "self" + and node.func.attr == "_sync_pen_cache" + ): + called_sync_pen = True + elif ( + isinstance(node.func.value, ast.Attribute) + and isinstance(node.func.value.value, ast.Name) + and node.func.value.value.id == "self" + ): + mutated_containers.add(node.func.value.attr) + assert called_sync_pen + handled = written_self_attrs | mutated_containers | {"_pen_word", "_cell_ext"} + assert (transferred | reset_slots) <= handled + assert written_self_attrs.isdisjoint(preserved) + + # Runtime verification: host wiring/theme preserved; guest OSC 10 + 7501 cleared. + seen_events: list[libvt.Event] = [] + rec = FlightRecorder() + reply_wakes: list[int] = [] + + def _wake() -> None: + reply_wakes.append(1) + + dst = libvt.Terminal( + rows=3, + cols=12, + on_event=seen_events.append, + recorder=rec, + ) + dst._on_reply_queued = _wake + dst.set_theme( + scheme=ColorScheme.LIGHT, + fg_rgb=(10, 20, 30), + bg_rgb=(240, 241, 242), + palette={1: (11, 22, 33)}, + ) + dst.feed( + b"\x1b]10;#ff0000\x07" + b"\x1b]11;#00ff00\x07" + b"\x1b]12;#0000ff\x07" + b"\x1b]4;2;#abcdef\x07" + b"\x1b]7501;state=working:id=job:progress=42\x07" + b"\x1b]99;i=pending:d=0:p=title;half\x1b\\" + b"\x1b]2;old-title\x07\x1b[22;0t" + b"\x1b[?1;3;128S" + b"stale" + ) + dst.drain_replies() + assert dst.appearance.fg_rgb == (0xFF, 0x00, 0x00) + assert dst.program_status is not None and dst.program_status.id == "job" + tok0 = dst.sync_token() + tid0 = dst._terminal_id + epoch0 = dst._epoch + + src = libvt.Terminal(rows=3, cols=12) + src.feed(b"fresh") + dst.replace_from(src) + + assert dst._terminal_id == tid0 + assert dst._on_event == seen_events.append + assert dst.recorder is rec + assert dst._on_reply_queued is _wake + assert dst._epoch == epoch0 + 1 + assert dst.lines == ("fresh", "", "") + assert dst.appearance.scheme == ColorScheme.LIGHT + assert dst.appearance.fg_rgb == (10, 20, 30) + assert dst.appearance.bg_rgb == (240, 241, 242) + assert dict(dst.appearance.palette_overrides) == {1: (11, 22, 33)} + assert dst.program_status is None + assert dst.program_statuses == {} + assert dst._pending_osc99 == {} + assert dst._title_stack == [] + assert dst._icon_title_stack == [] + dst.feed(b"\x1b[?1;1;0S") + assert dst.drain_replies() == b"\x1b[?1;0;256S" + delta = dst.changes_since(tok0) + assert delta.resync_reason == ResyncReason.EPOCH_CHANGED + + # Self-replace is a no-op; non-Terminal raises TypeError. + epoch_after = dst._epoch + dst.replace_from(dst) + assert dst._epoch == epoch_after + replace_fn = getattr(dst, "replace_" + "from") + with pytest.raises(TypeError, match="Terminal"): + replace_fn("not-a-terminal") + + +def test_terminal_recorder_protocol_strided_latin1_and_resize_without_monkeypatch() -> ( + None +): + """Custom ``TerminalRecorder`` replays strided Latin-1 and resize cleanly.""" + + class ReplayRecorder: + """Minimal custom recorder implementing only ``TerminalRecorder``.""" + + __slots__ = ("ops",) + + def __init__(self) -> None: + self.ops: list[tuple[str, object]] = [] + + def on_feed(self, data: memoryview, /) -> None: + assert data.format == "B" and data.ndim == 1 and data.c_contiguous + self.ops.append(("feed", bytes(data))) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + self.ops.append(("resize", (rows, cols, reflow))) + + rec = ReplayRecorder() + assert isinstance(rec, TerminalRecorder) + assert isinstance(FlightRecorder(), TerminalRecorder) + + term = libvt.Terminal(rows=3, cols=10, encoding="latin-1", recorder=rec) + assert not hasattr(term, "__dict__") + + # Strided non-contiguous memoryview carrying Latin-1 (0xE9 = 'é') + SGR bytes. + payload = b"\x1b[1mcaf\xe9\x1b[0m\r\n" + interleaved = bytearray() + for b in payload: + interleaved.append(b) + interleaved.append(0xFF) + strided = memoryview(interleaved)[::2] + assert not strided.c_contiguous + term.feed(strided) + + # External resize is recorded; internal DECCOLM 132-col switch is NOT duplicated. + term.resize(rows=4, cols=12, reflow=True) + term.feed(b"\x1b[?40h\x1b[?3hwide") + assert term.cols == 132 + + # feed_until batches recorder dispatch into a single on_feed event. + before_step_ops = len(rec.ops) + step_raw = b"123\x1b[?2026h45\x1b[?2026l" + step_interleaved = bytearray() + for b in step_raw: + step_interleaved.append(b) + step_interleaved.append(0x00) + step_strided = memoryview(step_interleaved)[::2] + res = term.feed_until(step_strided, stop=StopOn.SYNC_END) + assert res.stopped_on == StopOn.SYNC_END + assert rec.ops[before_step_ops:] == [("feed", step_raw)] + + resize_ops = [op for op in rec.ops if op[0] == "resize"] + assert resize_ops == [("resize", (4, 12, True))] + + # Diagnostic formatting works cleanly with non-FlightRecorder custom recorders. + diag = format_flight_recorder(term) + assert "Flight Recorder:" in diag + assert "recent_bytes" not in diag + + # Replay recorded operations onto a fresh slotted Terminal -> exact match. + replay = libvt.Terminal(rows=3, cols=10, encoding="latin-1") + for kind, arg in rec.ops: + if kind == "feed": + assert isinstance(arg, bytes) + replay.feed(arg) + else: + assert isinstance(arg, tuple) + r, c, rf = arg + replay.resize(rows=r, cols=c, reflow=rf) + assert replay.rows == term.rows + assert replay.cols == term.cols + assert replay.snapshot().lines == term.snapshot().lines + assert replay.cursor == term.cursor + assert replay.modes.enabled_modes() == term.modes.enabled_modes() + + # FlightRecorder backward compatibility with record() on strided buffers. + fr = FlightRecorder(max_bytes=128) + fr.record(strided) + assert fr.tail() == payload + + # FlightRecorder(max_bytes=0) counts bytes with zero retention; rejects invalid. + zero_fr = FlightRecorder(max_bytes=0) + zero_fr.record(b"abcdef") + assert zero_fr.total_bytes == 6 + assert zero_fr.tail() == b"" + for bad in (-1, True, False): + with pytest.raises(ValueError, match="max_bytes"): + FlightRecorder(max_bytes=bad) + + # CompositeRecorder, find_flight_recorder, and _attach_recorder keep term.recorder. + spy_ops: list[tuple[str, object]] = [] + + class _Spy: + def on_feed(self, data: memoryview, /) -> None: + spy_ops.append(("feed", bytes(data))) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + spy_ops.append(("resize", (rows, cols, reflow))) + + flight = FlightRecorder(max_bytes=64) + comp = CompositeRecorder(CompositeRecorder(flight), _Spy()) + assert len(comp.recorders) == 2 + assert find_flight_recorder(comp) is flight + assert find_flight_recorder(_Spy()) is None + comp_term = libvt.Terminal(rows=2, cols=8, recorder=comp) + comp_term.feed(b"hi") + assert "recent_bytes (2/2B): b'hi'" in format_flight_recorder(comp_term) + + aux_ops: list[bytes] = [] + + class _Aux: + def on_feed(self, data: memoryview, /) -> None: + aux_ops.append(bytes(data)) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + pass + + attached_term = libvt.Terminal(rows=2, cols=8, recorder=flight) + attached_term._attach_recorder(_Aux()) + assert attached_term.recorder is flight + attached_term.feed(b"xyz") + assert aux_ops == [b"xyz"] + assert flight.tail() == b"hixyz" + + +def test_private_mode_single_truth_matrix() -> None: + """``DECRQM``, ``DECSET``, ``ModeState``, and ``XTSAVE`` share one support table.""" + profiles = ( + DEFAULT_PROFILE, + TMUX_PROFILE, + Profile(screen=ScreenBehavior(deccolm=DeccolmBehavior.CLEAR_ONLY)), + Profile(screen=ScreenBehavior(cell_width_px=0, cell_height_px=0)), + ) + gated = ( + (3, Mode.DECCOLM), + (40, Mode.ALLOW_80_132), + (95, Mode.DECNCSM), + (69, Mode.DECLRMM), + (1048, Mode.DECSC_1048), + (1016, Mode.MOUSE_SGR_PIXELS), + ) + for prof in profiles: + term = libvt.Terminal(rows=4, cols=10, profile=prof) + for code, mode in gated: + supported = is_private_mode_supported(mode, prof) + assert term._is_private_mode_supported(mode) is supported + term.feed(f"\x1b[?{code}$p".encode("ascii")) + reply = term.drain_replies() + if not supported: + expected_pm = ( + int(DecrpmValue.PERMANENTLY_RESET) + if mode == Mode.DECCOLM + and prof.screen.deccolm == DeccolmBehavior.CLEAR_ONLY + else int(DecrpmValue.NOT_RECOGNIZED) + ) + assert reply == f"\x1b[?{code};{expected_pm}$y".encode("ascii") + term.modes.set_mode(mode, enabled=True) + assert term.modes.is_set(mode) is False + term.feed(f"\x1b[?{code}h".encode("ascii")) + assert term.modes.is_set(mode) is False + else: + assert reply == f"\x1b[?{code};2$y".encode("ascii") + + +def test_strided_memoryview_buffer_and_snapshot_format_profile_default() -> None: + """Non-contiguous buffers feed cleanly and ``Snapshot.format`` uses its profile.""" + strided = memoryview(b"Hxexlxlxo")[::2] + assert not strided.c_contiguous + term = libvt.Terminal(rows=1, cols=10) + term.feed(strided) + assert term.lines == ("Hello",) + + # Empty 2-D memoryview slice must not fail with TypeError on cast("B") or leak. + empty_2d = memoryview(b"abcd").cast("B", shape=(2, 2))[:0] + term.feed(empty_2d) + term.feed(empty_2d) + assert term.lines == ("Hello",) + + term2 = libvt.Terminal(rows=1, cols=10) + step = term2.feed_until(memoryview(b"AxBx")[::2]) + assert (term2.lines, step.offset) == (("AB",), 2) + + buf = bytearray(b"\x1b[999z") + strict = libvt.Terminal(rows=1, cols=10, policy=Policy(strict=True)) + with pytest.raises(ProtocolError): + strict.feed(buf) + buf.append(0x21) + assert buf.endswith(b"!") + + custom = Profile( + queries=QueryBehavior(fg_rgb=(12, 34, 56), bg_rgb=(200, 210, 220)), + ) + ct = libvt.Terminal(rows=1, cols=6, profile=custom) + ct.feed(b"hi") + snap = ct.snapshot() + assert "\x1b]10;" not in snap.format(OutputFormat.VT) + assert "\x1b]11;" not in snap.format(OutputFormat.VT) + vt_default = snap.format(OutputFormat.VT, profile=DEFAULT_PROFILE) + assert "\x1b]10;rgb:0c0c/2222/3838\x1b\\" in vt_default + assert "\x1b]11;rgb:c8c8/d2d2/dcdc\x1b\\" in vt_default diff --git a/tests/test_tmux.py b/tests/test_tmux.py index 85d596f1..dfbbacdf 100644 --- a/tests/test_tmux.py +++ b/tests/test_tmux.py @@ -1403,6 +1403,14 @@ def test_tmux_metadata_cursor_keys_history_bounds_layout_resize_and_resync() -> ) assert sync.phase == TmuxAttachPhase.LIVE + # Inject guest OSC 10 color and OSC 7501 status before resync to prove no leak. + live_term.feed( + b"\x1b]10;#ff00aa\x07\x1b]7501;state=working:id=pre-resync:progress=75\x07" + ) + assert live_term.appearance.fg_rgb == (0xFF, 0x00, 0xAA) + assert live_term.program_status is not None + assert live_term.program_status.id == "pre-resync" + # Flow-control %pause -> %continue resyncs while preserving live_term identity: tok_before = live_term.sync_token() sync.handle_event(TmuxPause(pane_id="%1")) @@ -1448,6 +1456,9 @@ def test_tmux_metadata_cursor_keys_history_bounds_layout_resize_and_resync() -> assert (live_term.rows, live_term.cols) == (3, 12) assert live_term.lines == ("RESYNC!", "ROW2", "") assert live_term.cursor.shape == CursorShape.UNDERLINE + assert live_term.appearance.fg_rgb == live_term.profile.queries.fg_rgb + assert live_term.program_status is None + assert live_term.program_statuses == {} delta = live_term.changes_since(tok_before) assert delta.full_resync is True assert delta.resync_reason == ResyncReason.EPOCH_CHANGED From eaba96c3818973fdf05ff7e55e35787579562d49 Mon Sep 17 00:00:00 2001 From: Tony Narlock <tony@git-pull.com> Date: Sat, 5 Dec 2026 08:20:07 -0600 Subject: [PATCH 3/4] testing(refactor): Decouple SupportsVtTarget why: Remove libvt.testing's runtime dependency on contrib.tmux and eliminate unsafe blind `.snapshot()` probing on arbitrary objects. what: - Add SupportsVtTarget (__vt_target__) guarded against class objects in testing.py and remove contrib.tmux imports and blind `.snapshot()` - Implement __vt_target__ on TmuxCaptureResult, AsyncTerminalStream, and PtySession - Widen pytest_plugin recorder annotations to TerminalRecorder | None - Update docs/api/testing.md, migrate test_syrupy _SnapHolder, and widen live tmux capture polling iterations in test_testing.py --- docs/api/testing.md | 4 +- src/libvt/aio.py | 8 ++++ src/libvt/contrib/tmux/capture.py | 4 ++ src/libvt/pytest_plugin.py | 7 +-- src/libvt/testing.py | 76 ++++++++++++++++++------------- tests/test_syrupy.py | 4 +- tests/test_testing.py | 54 +++++++++++++++++++++- 7 files changed, 117 insertions(+), 40 deletions(-) diff --git a/docs/api/testing.md b/docs/api/testing.md index ddcfb2dc..9ba8260b 100644 --- a/docs/api/testing.md +++ b/docs/api/testing.md @@ -43,7 +43,7 @@ immutable {class}`~libvt.terminal.Snapshot` objects, inline .. py:type:: VtTarget :module: libvt.testing - :canonical: Terminal | Snapshot | Screen | RegionView | TmuxCaptureResult + :canonical: Terminal | Snapshot | Screen | RegionView | SupportsVtTarget - Terminal, snapshot, screen, region slice, ``tmux`` capture result, or duck-typed pane wrapper (``.terminal``, ``.snapshot()``, or ``.capture_vt()``) accepted by :func:`~libvt.testing.vt_screen` and :func:`~libvt.testing.serialize_vt_snapshot`. + Terminal, snapshot, screen, region slice, :class:`~libvt.testing.SupportsVtTarget` provider (such as :class:`~libvt.contrib.tmux.capture.TmuxCaptureResult`, :class:`~libvt.aio.AsyncTerminalStream`, or :class:`~libvt.aio.PtySession`), or pane wrapper exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()`` accepted by :func:`~libvt.testing.vt_screen` and :func:`~libvt.testing.serialize_vt_snapshot`. ``` diff --git a/src/libvt/aio.py b/src/libvt/aio.py index c38ee08b..07440df5 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -1374,6 +1374,10 @@ async def _close_stream(self) -> None: self._last_committed_gen = self.terminal.committed_generation self._frame_event.set() + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(committed_snapshot, empty_unexposed)`` for :mod:`libvt.testing`.""" + return self.terminal.committed, frozenset() + async def __aenter__(self) -> t.Self: """Start background pumping when entering an ``async with`` block.""" self.start() @@ -1668,6 +1672,10 @@ def _ensure_writer(self) -> None: loop.add_writer(self._master_fd, self._on_writable) self._writer_registered = True + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(committed_snapshot, empty_unexposed)`` for :mod:`libvt.testing`.""" + return self.terminal.committed, frozenset() + def _mark_eof(self) -> None: self._eof = True self._cancel_sync_timer() diff --git a/src/libvt/contrib/tmux/capture.py b/src/libvt/contrib/tmux/capture.py index f9377c0b..0bbe9ced 100644 --- a/src/libvt/contrib/tmux/capture.py +++ b/src/libvt/contrib/tmux/capture.py @@ -538,6 +538,10 @@ class TmuxCaptureResult: metadata: TmuxPaneMetadata = field(default_factory=TmuxPaneMetadata) post_metadata: TmuxPaneMetadata | None = None + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(snapshot, unexposed_fields)`` for :mod:`libvt.testing`.""" + return self.snapshot, self.completeness.unexposed_fields + def _rewrite_tmux_overline_sgr(params: CsiParams) -> CsiParams: """Rewrite ``tmux`` ``grid_string_cells_code`` ``5:3`` SGR groups to ``53``. diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index fe56d230..3a50fc5b 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -15,7 +15,8 @@ from libvt.config import Limits, Policy, Profile from libvt.events import Event from libvt.parser import Parser, ParserEncoding - from libvt.terminal import FlightRecorder, Terminal + from libvt.recorder import FlightRecorder, TerminalRecorder + from libvt.terminal import Terminal class TerminalFactory(t.Protocol): @@ -33,7 +34,7 @@ def __call__( on_event: collections.abc.Callable[[Event], None] | None = None, encoding: ParserEncoding = "utf-8", record_events: bool = False, - recorder: FlightRecorder | None = None, + recorder: TerminalRecorder | None = None, ) -> Terminal: """Create a configured :class:`~libvt.terminal.Terminal` instance.""" @@ -145,7 +146,7 @@ def _make( on_event: collections.abc.Callable[[Event], None] | None = None, encoding: ParserEncoding = "utf-8", record_events: bool = False, - recorder: FlightRecorder | None = None, + recorder: TerminalRecorder | None = None, ) -> Terminal: return Terminal( rows=rows, diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 30d566fc..2e898533 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -4,6 +4,7 @@ import collections.abc import difflib +import inspect import itertools import json import os @@ -35,9 +36,6 @@ ) from libvt.terminal import Snapshot, Terminal -if t.TYPE_CHECKING: - from libvt.contrib.tmux.capture import TmuxCaptureResult - def _box_row_cells(row: RowView) -> list[str]: """Project the row slice as one string per captured column.""" @@ -389,6 +387,17 @@ def assert_screen_box( _raise_mismatch(target, snap, expected_box, actual_box, cursor) +@t.runtime_checkable +class SupportsVtTarget(t.Protocol): + """Protocol for objects projecting a snapshot target for :mod:`libvt.testing`.""" + + def __vt_target__( + self, + ) -> tuple[Snapshot | Screen | RegionView, frozenset[str]]: + """Return ``(view, unexposed_fields)`` for boxed snapshot serialization.""" + ... + + class _SupportsTerminal(t.Protocol): @property def terminal(self) -> Terminal: ... @@ -399,12 +408,8 @@ class _SupportsSnapshotProperty(t.Protocol): def snapshot(self) -> Snapshot: ... -class _SupportsSnapshotMethod(t.Protocol): - def snapshot(self) -> Snapshot: ... - - class _SupportsCaptureVt(t.Protocol): - def capture_vt(self) -> TmuxCaptureResult: ... + def capture_vt(self) -> SupportsVtTarget | Snapshot | Screen | RegionView: ... type ScrubberSpec = tuple[str | re.Pattern[str] | os.PathLike[str], str] @@ -458,10 +463,9 @@ class _UriContext: | Snapshot | Screen | RegionView - | TmuxCaptureResult + | SupportsVtTarget | _SupportsTerminal | _SupportsSnapshotProperty - | _SupportsSnapshotMethod | _SupportsCaptureVt ) @@ -475,8 +479,8 @@ class VtScreenView: target : VtTarget :class:`~libvt.terminal.Terminal`, :class:`~libvt.terminal.Snapshot`, :class:`~libvt.screen.Screen`, :class:`~libvt.screen.RegionView`, - :class:`~libvt.contrib.tmux.capture.TmuxCaptureResult`, or duck-typed - pane handle exposing ``.terminal``, ``.snapshot()``, or ``.capture_vt()``. + :class:`SupportsVtTarget` provider, or pane handle exposing + ``.terminal``, ``.snapshot``, or ``.capture_vt()``. diff : VtTarget | VtScreenView | None Baseline frame for a contextual diff. A prepared view inherits this view's region and display options, with its own explicit values taking @@ -1058,32 +1062,40 @@ def _render_fixed_rows( return "\n".join(box_lines), style_lines, out_col +def _accepts_no_args(fn: collections.abc.Callable[..., object]) -> bool: + try: + inspect.signature(fn).bind() + except (TypeError, ValueError): + return False + return True + + def _extract_target( data: object, -) -> tuple[Snapshot | Screen | RegionView, set[str]] | None: - from libvt.contrib.tmux.capture import TmuxCaptureResult - - if isinstance(data, TmuxCaptureResult): - return data.snapshot, set(data.completeness.unexposed_fields) +) -> tuple[Snapshot | Screen | RegionView, frozenset[str]] | None: if isinstance(data, (Snapshot, RegionView, Screen)): - return data, set() + return data, frozenset() if isinstance(data, Terminal): - return data.committed, set() + return data.committed, frozenset() + if not isinstance(data, type) and isinstance(data, SupportsVtTarget): + view, unexposed = data.__vt_target__() + if isinstance(view, (Snapshot, Screen, RegionView)): + return view, frozenset(unexposed) term = getattr(data, "terminal", None) if isinstance(term, Terminal): - return term.committed, set() + return term.committed, frozenset() snap = getattr(data, "snapshot", None) if isinstance(snap, Snapshot): - return snap, set() - if callable(snap): - res = snap() - if isinstance(res, Snapshot): - return res, set() + return snap, frozenset() cap_vt = getattr(data, "capture_vt", None) - if callable(cap_vt): + if callable(cap_vt) and not isinstance(data, type) and _accepts_no_args(cap_vt): res = cap_vt() - if isinstance(res, TmuxCaptureResult): - return res.snapshot, set(res.completeness.unexposed_fields) + if isinstance(res, (Snapshot, RegionView, Screen)): + return res, frozenset() + if not isinstance(res, type) and isinstance(res, SupportsVtTarget): + view, unexposed = res.__vt_target__() + if isinstance(view, (Snapshot, Screen, RegionView)): + return view, frozenset(unexposed) return None @@ -1140,9 +1152,8 @@ def serialize_vt_snapshot( target : VtTarget | VtScreenView :class:`~libvt.terminal.Terminal`, :class:`~libvt.terminal.Snapshot`, :class:`~libvt.screen.Screen`, :class:`~libvt.screen.RegionView`, - :class:`~libvt.contrib.tmux.capture.TmuxCaptureResult`, :class:`VtScreenView`, - or duck-typed pane wrapper exposing ``.terminal``, ``.snapshot()``, or - ``.capture_vt()``. + :class:`SupportsVtTarget` provider, :class:`VtScreenView`, or pane + wrapper exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()``. scrubbers : Sequence[ScrubberSpec], optional Regex or literal path pairs applied to each visible row. See :type:`ScrubberSpec` for path matching rules. @@ -1255,7 +1266,7 @@ def _serialize_view( def _serialize_extracted( - extracted: tuple[Snapshot | Screen | RegionView, set[str]], + extracted: tuple[Snapshot | Screen | RegionView, frozenset[str]], *, region: tuple[int, int, int, int] | None = None, scrubbers: _CompiledScrubbers = (), @@ -1683,6 +1694,7 @@ def format_vt_diff_lines( __all__ = [ "ScrubberSpec", + "SupportsVtTarget", "VtScreenView", "VtTarget", "assert_screen", diff --git a/tests/test_syrupy.py b/tests/test_syrupy.py index 9c5b28d4..9b29760e 100644 --- a/tests/test_syrupy.py +++ b/tests/test_syrupy.py @@ -185,8 +185,8 @@ class _SnapHolder: def __init__(self, snap: Snapshot) -> None: self._snap = snap - def snapshot(self) -> Snapshot: - return self._snap + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + return self._snap, frozenset() holder = _SnapHolder(t_prev.snapshot()) inst = c1() diff --git a/tests/test_testing.py b/tests/test_testing.py index 6f75ae97..c53034b0 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -1204,7 +1204,7 @@ def test_live_tmux_server_vs_pure_terminal_snapshot_parity( cap_cmd = build_tmux_capture_command( "%0", tmux_version=ver_str, history_lines=0 ) - for _ in range(40): + for _ in range(100): proc = subprocess.run( ["tmux", "-S", str(sock), *cap_cmd.argv], capture_output=True, @@ -1755,3 +1755,55 @@ def __fspath__(self) -> bytes: serialize_vt_snapshot(term, scrubbers=[(re.compile(b"raw"), "<B>")]) # ty: ignore[invalid-argument-type] with pytest.raises(TypeError, match="scrubber"): serialize_vt_snapshot(term, scrubbers=[(123, "<X>")]) # ty: ignore[invalid-argument-type] + + +def test_supports_vt_target_boundary_screen_profile_and_strided_buffers() -> None: + """``testing`` stays ``contrib``-free and handles ``Screen.profile`` + strides.""" + import asyncio + + from libvt.aio import AsyncTerminalStream + from libvt.contrib.tmux.control import ( + TmuxControlParser, + unescape_tmux_control_output, + ) + from libvt.testing import SupportsVtTarget, _extract_target + + class _ObjWithRequiredArgSnapshot: + def snapshot(self, path: str) -> str: + return path + + assert _extract_target(_ObjWithRequiredArgSnapshot()) is None + assert _extract_target(Terminal) is None + assert _extract_target(SupportsVtTarget) is None + + async def _check_stream_target() -> None: + stream = AsyncTerminalStream(asyncio.StreamReader(), rows=1, cols=8) + assert isinstance(stream, SupportsVtTarget) + stream.terminal.feed(b"live") + assert "│live │" in serialize_vt_snapshot(stream) + + asyncio.run(_check_stream_target()) + + cjk = Profile(unicode=UnicodeBehavior(ambiguous_width=2)) + term = Terminal(rows=1, cols=4, profile=cjk) + term.feed_str("A±B") + assert term.screen.profile == cjk + assert term.screen.is_alt is False + assert serialize_vt_snapshot(term.screen) == serialize_vt_snapshot(term) + + strided = memoryview(b"hXeYlZlWo")[::2] + rec = FlightRecorder() + t_buf = Terminal(rows=1, cols=10, recorder=rec) + t_buf.feed(strided) + assert t_buf.text == "hello" + assert rec.tail() == b"hello" + t_step = Terminal(rows=1, cols=10) + step = t_step.feed_until(strided) + assert step.offset == 5 and t_step.text == "hello" + from libvt.parser import Print + + act = Parser().feed(strided)[0] + assert isinstance(act, Print) and act.text == "hello" + assert unescape_tmux_control_output(strided) == b"hello" + ctrl_ev = TmuxControlParser().feed(memoryview(b"%XeYxZiWtW\n")[::2]) + assert len(ctrl_ev) == 1 From fa5e1d2b9c50cf94cfefdb1fae7e22026051d0c2 Mon Sep 17 00:00:00 2001 From: Tony Narlock <tony@git-pull.com> Date: Sat, 5 Dec 2026 08:26:09 -0600 Subject: [PATCH 4/4] aio(refactor): Split package with _SessionCore why: Deduplicate session sync-timer, input-encoding, reply-sink, and wait_for logic across streams and PTYs while isolating POSIX PTY code into its own module. what: - Replace aio.py with aio/__init__.py, _core.py, _stream.py, and _pty.py using relative imports and shared _SessionCore inheritance - Preserve _FrameWaits, shared foreground stream reads, Linux pidfd process groups, cancel-safe close, and PTY fd cleanup on failure - Document inherited members in docs/api/aio.md, update aio package loading in tests/test_aio.py, and record #203 in CHANGES --- CHANGES | 20 + docs/api/aio.md | 2 + src/libvt/aio.py | 2412 ------------------------------------- src/libvt/aio/__init__.py | 22 + src/libvt/aio/_core.py | 790 ++++++++++++ src/libvt/aio/_pty.py | 907 ++++++++++++++ src/libvt/aio/_stream.py | 655 ++++++++++ tests/test_aio.py | 81 +- 8 files changed, 2474 insertions(+), 2415 deletions(-) delete mode 100644 src/libvt/aio.py create mode 100644 src/libvt/aio/__init__.py create mode 100644 src/libvt/aio/_core.py create mode 100644 src/libvt/aio/_pty.py create mode 100644 src/libvt/aio/_stream.py diff --git a/CHANGES b/CHANGES index 240e8396..9fa02473 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,26 @@ _Notes on the upcoming release will go here._ <!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE --> +### What's new + +#### Recorder protocol, target protocol, and state replacement (#203) + +Pass any {class}`~libvt.terminal.TerminalRecorder` implementation to +{class}`~libvt.terminal.Terminal` to observe normalized input spans and +external resizes without monkey-patching. Call +{meth}`~libvt.terminal.Terminal.replace_from` to replace emulated screen, mode, +and parser state in place while preserving host callbacks, theme settings, and +sync identity. + +Implement {class}`~libvt.testing.SupportsVtTarget` (`__vt_target__`) on custom +wrappers passed to {func}`~libvt.testing.vt_screen` and +{func}`~libvt.testing.serialize_vt_snapshot`. +{class}`~libvt.aio.AsyncTerminalStream`, {class}`~libvt.aio.PtySession`, and +{class}`~libvt.contrib.tmux.capture.TmuxCaptureResult` implement this protocol +directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode +support queries, and {class}`~libvt.terminal.SnapshotDict` types the dictionary +returned by {meth}`~libvt.terminal.Snapshot.to_dict`. + ## libvt 0.0.1a6 (2026-12-05) `libvt` 0.0.1a6 adds soft-wrapped logical-line reading and `wait_for()` diff --git a/docs/api/aio.md b/docs/api/aio.md index 61a27355..0fe6fc1f 100644 --- a/docs/api/aio.md +++ b/docs/api/aio.md @@ -3,6 +3,8 @@ ```{eval-rst} .. automodule:: libvt.aio :members: + :inherited-members: + :no-show-inheritance: :no-private-members: .. py:type:: TtyMode diff --git a/src/libvt/aio.py b/src/libvt/aio.py deleted file mode 100644 index 07440df5..00000000 --- a/src/libvt/aio.py +++ /dev/null @@ -1,2412 +0,0 @@ -"""``asyncio`` stream and POSIX PTY adapters over :class:`~libvt.terminal.Terminal`.""" - -from __future__ import annotations - -import asyncio -import collections -import collections.abc -import contextlib -import dataclasses -import errno -import math -import os -import signal -import socket -import struct -import sys -import time -import typing as t - -from libvt._util import _byte_view, _parse_ascii_uint -from libvt.config import ( - DEFAULT_LIMITS, - DEFAULT_OSC7_HOSTS, - DEFAULT_POLICY, - DEFAULT_PROFILE, - Limits, - Policy, - Profile, -) -from libvt.exc import TerminalTimeoutError -from libvt.input import ( - InputEvent, - KeyEvent, - MouseEvent, - MouseTracker, - PasteEvent, -) -from libvt.parser import ParserEncoding -from libvt.recorder import find_flight_recorder -from libvt.terminal import FlightRecorder, Snapshot, StopOn, Terminal - -type TtyMode = t.Literal["cooked", "cbreak", "raw"] - -_PIDFD_SIGNAL_PROCESS_GROUP = 1 << 2 -_PIDFD_WIRE = struct.Struct("i") - -_PTY_TRAMPOLINE = ( - "stage = 'bootstrap'\n" - "err_fd = -1\n" - "try:\n" - " import errno, fcntl, os, signal, sys, termios\n" - " err_fd = int(sys.argv[1])\n" - " os.set_inheritable(err_fd, False)\n" - " stage = 'ctty'\n" - " if hasattr(termios, 'TIOCSCTTY'):\n" - " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" - " stage = 'signal'\n" - " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n" - " if hasattr(signal, 'SIGXFSZ'):\n" - " signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n" - " if sys.platform == 'linux':\n" - " stage = 'group'\n" - " import socket, struct\n" - " pidfd = None\n" - " try:\n" - " pidfd = os.pidfd_open(os.getpid())\n" - " signal.pidfd_send_signal(" - f"pidfd, 0, None, {_PIDFD_SIGNAL_PROCESS_GROUP})\n" - " except (AttributeError, OSError):\n" - " pass\n" - " else:\n" - " with socket.socket(fileno=os.dup(err_fd)) as channel:\n" - " rights = (socket.SOL_SOCKET, socket.SCM_RIGHTS,\n" - " struct.pack('i', pidfd))\n" - " channel.sendmsg([b'\\x02'], [rights])\n" - " if channel.recv(1) != b'\\x00':\n" - " raise OSError(errno.EPIPE, 'PTY launch channel closed')\n" - " finally:\n" - " if pidfd is not None:\n" - " os.close(pidfd)\n" - " stage = 'exec'\n" - " os.write(err_fd, b'\\x00')\n" - " os.execvp(sys.argv[2], sys.argv[2:])\n" - "except BaseException as exc:\n" - " try:\n" - " import errno as _e, os as _os\n" - " if err_fd >= 0:\n" - " code = getattr(exc, 'errno', None)\n" - " if not isinstance(code, int):\n" - " code = _e.ENOEXEC\n" - " msg = (getattr(exc, 'strerror', None) or str(exc))[:360]\n" - " pkt = b'\\x01' + f'{stage}:{code}:{msg}'.encode('utf-8', 'replace')\n" - " _os.write(err_fd, pkt[:500])\n" - " except BaseException:\n" - " pass\n" - " import os as _os2\n" - " _os2._exit(127)\n" -) - - -def _raise_exec_error(err_payload: bytes, cmd: str, default_errno: int) -> t.NoReturn: - if not err_payload: - msg = f"PTY launcher exited before pre-exec handoff while starting {cmd!r}" - raise RuntimeError(msg) - idx = err_payload.find(b"\x01") - body = err_payload[idx + 1 :] if idx != -1 else err_payload - parts = body.decode("utf-8", "replace").split(":", 2) - if len(parts) == 3: - stage, code_s, err_msg = parts - else: - stage, code_s, err_msg = "exec", "", body.decode("utf-8", "replace") - parsed_err = _parse_ascii_uint(code_s, max_val=65_535) - err_no = default_errno if parsed_err is None else parsed_err - target = cmd if stage == "exec" else f"open_pty({stage})" - raise OSError(err_no, err_msg or os.strerror(err_no), target) - - -class _PtyGroup: - """Own the Linux launcher identity used for process-group signals.""" - - def __init__(self) -> None: - self.pidfd: int | None = None - - def send(self, process: asyncio.subprocess.Process, signum: int) -> bool: - try: - if sys.platform == "linux" and self.pidfd is not None: - signal.pidfd_send_signal( - self.pidfd, signum, None, _PIDFD_SIGNAL_PROCESS_GROUP - ) - elif sys.platform != "win32" and process.returncode is None: - os.killpg(process.pid, signum) - else: - return False - except (ProcessLookupError, PermissionError): - return False - return True - - def close(self) -> None: - fd, self.pidfd = self.pidfd, None - if fd is not None: - with contextlib.suppress(OSError): - os.close(fd) - - -async def _read_pty_handoff( - loop: asyncio.AbstractEventLoop, - channel: socket.socket, - group: _PtyGroup, -) -> bytes: - """Receive the launcher identity and collect its exec status through EOF.""" - chunks: list[bytes] = [] - done = loop.create_future() - - def _on_ready() -> None: - if done.done(): - return - while True: - try: - if sys.platform == "linux": - data, ancillary, _, _ = channel.recvmsg( - 4_096, - socket.CMSG_SPACE(_PIDFD_WIRE.size), - socket.MSG_CMSG_CLOEXEC, - ) - else: - data, ancillary = channel.recv(4_096), [] - except (BlockingIOError, InterruptedError): - return - except OSError as exc: - loop.remove_reader(channel) - if not done.done(): - done.set_exception(exc) - return - if sys.platform == "linux" and (ancillary or data == b"\x02"): - fds = [ - fd - for level, kind, raw in ancillary - if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS - for (fd,) in _PIDFD_WIRE.iter_unpack(raw) - ] - if data != b"\x02" or group.pidfd is not None or len(fds) != 1: - for fd in fds: - os.close(fd) - done.set_exception(OSError(errno.EIO, "invalid PTY group handoff")) - loop.remove_reader(channel) - return - group.pidfd = fds[0] - try: - channel.sendall(b"\x00") - except OSError as exc: - done.set_exception(exc) - loop.remove_reader(channel) - return - continue - if not data: - loop.remove_reader(channel) - if not done.done(): - done.set_result(b"".join(chunks)) - return - chunks.append(data) - - loop.add_reader(channel, _on_ready) - try: - return await done - finally: - with contextlib.suppress(Exception): - loop.remove_reader(channel) - - -def _make_timeout_error( - terminal: Terminal, - snap: Snapshot, - header: str, - *, - eof: bool, - attach_note: bool = True, -) -> TerminalTimeoutError: - from libvt.testing import format_flight_recorder, format_screen_box - - rec = find_flight_recorder(terminal.recorder) - recent = rec.tail(256) if rec is not None else b"" - box = format_screen_box(snap, rows=min(snap.rows, 12), cols=min(snap.cols, 80)) - diag = format_flight_recorder(terminal) - return TerminalTimeoutError( - header, - parser_state=terminal.parser_state, - screen_text=snap.text, - recent_bytes=recent, - eof=eof, - diagnostics=f"{box}\n{diag}", - attach_note=attach_note, - ) - - -class ReplyWriter(t.Protocol): - """Structural writer protocol satisfied by :class:`asyncio.StreamWriter`.""" - - def write(self, data: bytes, /) -> object: - """Buffer outbound *data* bytes.""" - - async def drain(self) -> None: - """Flush buffered outbound bytes.""" - - def close(self) -> object: - """Initiate writer close.""" - - async def wait_closed(self) -> None: - """Wait until writer close completes.""" - - -@t.runtime_checkable -class AsyncSession(t.Protocol): - """Bidirectional interactive terminal session shared by streams and PTYs. - - Satisfied by both :class:`AsyncTerminalStream` (cross-platform pipes, - sockets, and SSH channels) and :class:`PtySession` (POSIX pseudo-terminals). - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncSession, AsyncTerminalStream - >>> async def _check() -> bool: - ... return isinstance(AsyncTerminalStream(asyncio.StreamReader()), AsyncSession) - >>> asyncio.run(_check()) - True - """ - - @property - def terminal(self) -> Terminal: - """Return attached :class:`~libvt.terminal.Terminal`.""" - - @property - def eof(self) -> bool: - """Return ``True`` once inbound terminal output reaches end-of-stream.""" - - def send(self, data: collections.abc.Buffer | str, /) -> None: - """Enqueue raw *data* bytes (or UTF-8 string) for outbound delivery.""" - - def send_event(self, event: InputEvent, /) -> None: - """Encode *event* against active modes and enqueue outbound bytes.""" - - def send_key(self, chord: str, /) -> None: - """Parse *chord* (e.g. ``"ctrl+c"``) and enqueue outbound bytes.""" - - def paste(self, text: str, /, *, sanitize: bool = False) -> None: - """Encode *text* as an atomic :class:`~libvt.input.PasteEvent` frame.""" - - async def drain(self) -> None: - """Pause while outbound buffered bytes exceed ``write_high_water``.""" - - async def wait_for( - self, - predicate: collections.abc.Callable[[Snapshot], bool] | str, - *, - timeout: float = 2.0, - attach_note: bool = True, - ) -> Snapshot: - r"""Wait until *predicate* matches a committed ``Snapshot``. - - ``str`` predicates match against ``snapshot.unwrapped_text``. Pass a - callable using ``snapshot.text`` to test physical rows. - """ - - async def aclose(self) -> object: - """Close the session and expire any active ``?2026`` hold.""" - - -_PEER_EOF_ERRNOS = ( - errno.EIO, - errno.EPIPE, - errno.ENXIO, - errno.ECONNRESET, - errno.ECONNABORTED, -) -_COALESCE_SLAB = 16_384 - - -def _write_aborted() -> OSError: - message = "terminal session closed before queued writes drained" - return OSError(errno.ECANCELED, message) - - -def _snapshot_matches( - snapshot: Snapshot, predicate: collections.abc.Callable[[Snapshot], bool] | str -) -> bool: - if isinstance(predicate, str): - return predicate in snapshot.unwrapped_text - return predicate(snapshot) - - -def _validate_nonneg_seconds(value: float, name: str) -> None: - if ( - isinstance(value, bool) - or not isinstance(value, (int, float)) - or not math.isfinite(value) - or value < 0 - ): - msg = f"{name} must be a finite non-negative number, got {value!r}" - raise ValueError(msg) - - -def _validate_pty_dims(rows: int, cols: int) -> None: - if ( - isinstance(rows, bool) - or isinstance(cols, bool) - or not isinstance(rows, int) - or not isinstance(cols, int) - or not (1 <= rows <= 65_535) - or not (1 <= cols <= 65_535) - ): - msg = f"rows and cols must be integers in 1..65535, got ({rows!r}, {cols!r})" - raise ValueError(msg) - - -def _pack_winsize(rows: int, cols: int, profile: Profile) -> bytes: - xpixel = min(65_535, max(0, cols * profile.screen.cell_width_px)) - ypixel = min(65_535, max(0, rows * profile.screen.cell_height_px)) - return struct.pack("HHHH", rows, cols, xpixel, ypixel) - - -def _resolve_write_limits( - write_high_water: int | None, - max_write_buffer: int, -) -> tuple[int, int]: - """Validate and resolve ``(write_high_water, max_write_buffer)`` byte caps. - - Parameters - ---------- - write_high_water : int | None - Optional outbound high-water mark in bytes; ``None`` selects - ``min(65_536, max_write_buffer)``. - max_write_buffer : int - Hard cap in bytes above which outbound writes raise :exc:`BufferError`. - - Returns - ------- - tuple[int, int] - Validated ``(effective_high_water, max_write_buffer)`` pair. - - Raises - ------ - ValueError - If either bound is ``bool``, negative, or ``max_write_buffer`` is less - than ``write_high_water`` or ``1``. - - Examples - -------- - >>> from libvt.aio import _resolve_write_limits - >>> _resolve_write_limits(None, 4096) - (4096, 4096) - >>> _resolve_write_limits(1024, 8192) - (1024, 8192) - """ - if ( - isinstance(max_write_buffer, bool) - or not isinstance(max_write_buffer, int) - or max_write_buffer < 1 - ): - msg = f"max_write_buffer must be an int >= 1, got {max_write_buffer!r}" - raise ValueError(msg) - if write_high_water is None: - eff_hw = min(65_536, max_write_buffer) - else: - if ( - isinstance(write_high_water, bool) - or not isinstance(write_high_water, int) - or write_high_water < 0 - ): - msg = f"write_high_water must be >= 0, got {write_high_water!r}" - raise ValueError(msg) - if max_write_buffer < write_high_water: - msg = ( - "max_write_buffer must be >= write_high_water, " - f"got {max_write_buffer!r} < {write_high_water!r}" - ) - raise ValueError(msg) - eff_hw = write_high_water - return eff_hw, max_write_buffer - - -async def _join_close_task[T](task: asyncio.Task[T]) -> T: - """Join the cleanup task even when its caller is cancelled.""" - cancelled: asyncio.CancelledError | None = None - while not task.done(): - try: - await asyncio.wait((task,)) - except asyncio.CancelledError as error: - cancelled = error - if cancelled is not None: - raise cancelled from task.exception() - return task.result() - - -@dataclasses.dataclass(eq=False, slots=True) -class _FrameWait: - """Hold one published batch for an observer.""" - - predicate: collections.abc.Callable[[Snapshot], bool] - frames: tuple[Snapshot, ...] = () - - -_FRAMES_PER_BATCH = 32 - - -class _FrameWaits: - """Publish one shared batch, then let its observers consume it.""" - - def __init__(self, changed: asyncio.Event) -> None: - self._active: set[_FrameWait] = set() - self._changed = changed - self.drained = asyncio.Event() - self.drained.set() - - @contextlib.contextmanager - def watch( - self, predicate: collections.abc.Callable[[Snapshot], bool] - ) -> collections.abc.Generator[_FrameWait, None, None]: - waiter = _FrameWait(predicate) - self._active.add(waiter) - try: - yield waiter - finally: - self._active.remove(waiter) - self._release_batch() - - def _release_batch(self) -> None: - if not any(waiter.frames for waiter in self._active): - self.drained.set() - - def match(self, waiter: _FrameWait, current: Snapshot) -> Snapshot | None: - frames, waiter.frames = waiter.frames, () - self._release_batch() - for frame in frames: - if waiter.predicate(frame): - return frame - if frames and frames[-1] is current: - return None - return current if waiter.predicate(current) else None - - def feed(self, terminal: Terminal, data: bytes, offset: int = 0) -> int: - """Feed until the chunk ends or one frame batch is ready.""" - assert self.drained.is_set() - if not self._active: - terminal.feed(data if offset == 0 else memoryview(data)[offset:]) - return len(data) - frames: list[Snapshot] = [] - while offset < len(data) and len(frames) < _FRAMES_PER_BATCH: - before = terminal.committed_generation - offset = terminal.feed_until( - data, offset=offset, stop=StopOn.SYNC_START | StopOn.SYNC_END - ).offset - if terminal.committed_generation != before: - frames.append(terminal.committed) - if frames: - batch = tuple(frames) - self.drained.clear() - for waiter in self._active: - waiter.frames = batch - self._changed.set() - return offset - - -class AsyncTerminalStream: - """Bidirectional ``asyncio`` stream adapter over :class:`~libvt.terminal.Terminal`. - - Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output - batches (bounded by *sync_timeout* using generation-safe expiry), expires - any active ``?2026`` hold on ``EOF`` and :meth:`aclose`, and queues outbound - :meth:`send`, :meth:`send_event`, :meth:`send_key`, :meth:`paste`, and - automatic query replies onto a non-blocking single-FIFO writer queue so - inbound reads never block on outbound backpressure. - """ - - def __init__( - self, - reader: asyncio.StreamReader, - writer: ReplyWriter | None = None, - *, - terminal: Terminal | None = None, - rows: int = 24, - cols: int = 80, - chunk_size: int = 4_096, - sync_timeout: float = 1.0, - write_high_water: int | None = None, - max_write_buffer: int = 16_777_216, - ) -> None: - if ( - isinstance(chunk_size, bool) - or not isinstance(chunk_size, int) - or chunk_size < 1 - ): - msg = f"chunk_size must be >= 1, got {chunk_size!r}" - raise ValueError(msg) - if terminal is None: - _validate_pty_dims(rows, cols) - _validate_nonneg_seconds(sync_timeout, "sync_timeout") - eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) - self.reader = reader - self.writer = writer - self.terminal = ( - terminal - if terminal is not None - else Terminal(rows=rows, cols=cols, recorder=FlightRecorder()) - ) - self.chunk_size = chunk_size - self.sync_timeout = sync_timeout - self.write_high_water = eff_hw - self.max_write_buffer = eff_max - self._mouse_tracker = MouseTracker() - self._frame_event = asyncio.Event() - self._frame_waits = _FrameWaits(self._frame_event) - self._read_pending: tuple[bytes, int] | None = None - self._eof_pending = False - self._drain_event = asyncio.Event() - self._drain_event.set() - self._write_wakeup = asyncio.Event() - self._write_queue: collections.deque[bytes | None] = collections.deque() - self._write_buffered_bytes: int = 0 - self._writer_draining = False - self._write_eof_queued = False - self._write_error: OSError | None = None - self._eof = False - self._closed = False - self._sync_started_at: float | None = None - self._sync_gen_tracked: int | None = None - self._sync_timer_handle: asyncio.TimerHandle | None = None - self._sync_timer_gen: int | None = None - self._last_committed_gen: int = self.terminal.committed_generation - self._task: asyncio.Task[None] | None = None - self._read_task: asyncio.Task[bool] | None = None - self._read_waiters = 0 - self._writer_task: asyncio.Task[None] | None = None - self._close_task: asyncio.Task[None] | None = None - self._attach_reply_writer(flush_pending=False) - - def _attach_reply_writer(self, *, flush_pending: bool = True) -> None: - if self.writer is None: - return - owner = self.terminal._on_reply_queued - if owner is None: - self.terminal._on_reply_queued = self._flush_terminal_replies - if flush_pending and (owner is None or owner == self._flush_terminal_replies): - self._flush_terminal_replies() - - def _flush_terminal_replies(self) -> None: - r"""Flush out-of-band :meth:`~libvt.terminal.Terminal.enqueue_reply` bytes. - - References - ---------- - - `xterm Control Sequences — Manipulate Selection Data (OSC 52) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> async def _demo() -> bytes: - ... buf = bytearray() - ... class _W: - ... def write(self, data: bytes, /) -> None: buf.extend(data) - ... async def drain(self) -> None: pass - ... def close(self) -> None: pass - ... async def wait_closed(self) -> None: pass - ... stream = AsyncTerminalStream(asyncio.StreamReader(), _W()) - ... stream.terminal.enqueue_reply(b"\x1b]52;c;aGk=\x07") - ... await stream.aclose() - ... return bytes(buf) - >>> asyncio.run(_demo()) - b'\x1b]52;c;aGk=\x07' - """ - if self._closed or self.writer is None: - return - replies = self.terminal.drain_replies() - if replies: - self._enqueue_stream_write(replies, is_reply=True) - - @property - def eof(self) -> bool: - """Return ``True`` once ``reader`` reaches end-of-stream.""" - return self._eof - - @property - def write_buffer_size(self) -> int: - """Return number of outbound bytes currently buffered for ``writer``. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> async def _check() -> int: - ... return AsyncTerminalStream(asyncio.StreamReader()).write_buffer_size - >>> asyncio.run(_check()) - 0 - """ - return self._write_buffered_bytes - - def _ensure_writer_task(self) -> None: - """Spawn the background ``_writer_loop`` task when a loop is running. - - Safe to call synchronously outside an event loop; when no loop is - running yet, the task is started lazily on the next :meth:`drain` or - running-loop write. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> async def _check() -> bool: - ... stream = AsyncTerminalStream(asyncio.StreamReader()) - ... stream._ensure_writer_task() - ... return stream._writer_task is None - >>> asyncio.run(_check()) - True - """ - if self._closed or self.writer is None: - return - if self._writer_task is None or self._writer_task.done(): - with contextlib.suppress(RuntimeError): - asyncio.get_running_loop() - self._writer_task = asyncio.create_task(self._writer_loop()) - - def _enqueue_stream_write( - self, - data: collections.abc.Buffer, - *, - is_reply: bool = False, - ) -> None: - """Queue outbound *data* onto the single-FIFO writer without awaiting. - - Writes the first chunk synchronously to ``writer.write()`` when idle so - non-stalled writers observe bytes immediately, while queuing subsequent - frames in FIFO order until ``writer.drain()`` completes. Automatic - query replies (*is_reply* ``True``) drop silently if ``writer`` is - missing, closed, or full rather than aborting inbound parsing. - - Parameters - ---------- - data : collections.abc.Buffer - Outbound byte sequence. - is_reply : bool - ``True`` when *data* originates from automatic VT query replies. - - Raises - ------ - RuntimeError - If ``writer`` is ``None`` and *is_reply* is ``False``. - OSError - If the stream is closed or half-closed and *is_reply* is ``False``. - BufferError - If buffering *data* would exceed :attr:`max_write_buffer` and - *is_reply* is ``False``. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> class _BufWriter: - ... def __init__(self) -> None: - ... self.buf = bytearray() - ... def write(self, data: bytes, /) -> None: - ... self.buf.extend(data) - ... async def drain(self) -> None: - ... pass - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> tuple[bytes, int]: - ... w = _BufWriter() - ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as s: - ... s._enqueue_stream_write(b"ping") - ... size = s.write_buffer_size - ... return bytes(w.buf), size - >>> asyncio.run(_demo()) - (b'ping', 4) - """ - payload = bytes(data) - if not payload: - return - if self.writer is None: - if is_reply: - return - msg = "AsyncTerminalStream has no writer attached" - raise RuntimeError(msg) - if self._closed or self._write_eof_queued: - if is_reply: - return - raise OSError(errno.EBADF, "stream writer is closed") - if not is_reply and self._write_error is None: - self._attach_reply_writer() - if self._write_error is not None: - if is_reply: - return - raise self._write_error - if self._write_buffered_bytes + len(payload) > self.max_write_buffer: - if is_reply: - return - msg = ( - f"stream write buffer exceeded {self.max_write_buffer} bytes; " - "await stream.drain()" - ) - raise BufferError(msg) - - if not self._write_queue and not self._writer_draining: - try: - self.writer.write(payload) - except (BrokenPipeError, ConnectionResetError, OSError) as exc: - self._write_error = exc - if not is_reply: - raise - return - self._writer_draining = True - self._write_buffered_bytes = len(payload) - else: - self._write_queue.append(payload) - self._write_buffered_bytes += len(payload) - - self._drain_event.clear() - self._write_wakeup.set() - self._ensure_writer_task() - - async def _writer_loop(self) -> None: - """Drain queued outbound payloads and half-close sentinels in FIFO order. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> class _MemWriter: - ... def __init__(self) -> None: - ... self.buf = bytearray() - ... def write(self, data: bytes, /) -> None: - ... self.buf.extend(data) - ... async def drain(self) -> None: - ... await asyncio.sleep(0) - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> bytes: - ... w = _MemWriter() - ... stream = AsyncTerminalStream( - ... asyncio.StreamReader(), - ... w, - ... write_high_water=0, - ... ) - ... async with stream as s: - ... s.send("a") - ... s.send("b") - ... await s.drain() - ... return bytes(w.buf) - >>> asyncio.run(_demo()) - b'ab' - """ - try: - while not self._closed: - if self._writer_draining and self.writer is not None: - try: - await self.writer.drain() - except (BrokenPipeError, ConnectionResetError, OSError) as exc: - self._write_error = exc - self._write_queue.clear() - self._write_buffered_bytes = 0 - self._writer_draining = False - self._drain_event.set() - return - queued_sum = sum(len(x) for x in self._write_queue if x is not None) - self._write_buffered_bytes = queued_sum - self._writer_draining = False - - if self._write_queue and not self._closed: - item = self._write_queue.popleft() - if item is None: - if self.writer is not None: - eof_fn = getattr(self.writer, "write_eof", None) - if callable(eof_fn): - with contextlib.suppress( - OSError, - RuntimeError, - NotImplementedError, - ): - eof_fn() - self._drain_event.set() - return - if self.writer is not None: - try: - self.writer.write(item) - except ( - BrokenPipeError, - ConnectionResetError, - OSError, - ) as exc: - self._write_error = exc - self._write_queue.clear() - self._write_buffered_bytes = 0 - self._writer_draining = False - self._drain_event.set() - return - self._writer_draining = True - continue - - self._write_wakeup.clear() - if self._write_queue or self._writer_draining or self._closed: - continue - self._drain_event.set() - await self._write_wakeup.wait() - finally: - self._writer_draining = False - self._drain_event.set() - - def send(self, data: collections.abc.Buffer | str, /) -> None: - r"""Enqueue raw *data* bytes (or UTF-8 string) onto the stream write queue. - - Parameters - ---------- - data : collections.abc.Buffer | str - Raw outbound bytes or text encoded as UTF-8. - - Raises - ------ - RuntimeError - If no ``writer`` was attached to this stream. - OSError - If the stream writer has been closed or half-closed via - :meth:`write_eof`. - BufferError - If buffered outbound bytes exceed :attr:`max_write_buffer`. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> class _MemWriter: - ... def __init__(self) -> None: - ... self.buf = bytearray() - ... def write(self, data: bytes, /) -> None: - ... self.buf.extend(data) - ... async def drain(self) -> None: - ... pass - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> bytes: - ... w = _MemWriter() - ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: - ... stream.send("ls\n") - ... return bytes(w.buf) - >>> asyncio.run(_demo()) - b'ls\n' - """ - if isinstance(data, str): - self._enqueue_stream_write(data.encode("utf-8")) - else: - self._enqueue_stream_write(data) - - def send_event(self, event: InputEvent, /) -> None: - r"""Encode *event* (filtering ``?1002`` drags) and enqueue outbound bytes. - - Parameters - ---------- - event : InputEvent - Keyboard, mouse, focus, or paste event to encode against - ``self.terminal.modes``. - - References - ---------- - - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) - <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L385-L393>`__ - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> from libvt.input import KeyEvent - >>> class _MemWriter: - ... def __init__(self) -> None: - ... self.buf = bytearray() - ... def write(self, data: bytes, /) -> None: - ... self.buf.extend(data) - ... async def drain(self) -> None: - ... pass - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> bytes: - ... w = _MemWriter() - ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: - ... stream.send_event(KeyEvent("up")) - ... return bytes(w.buf) - >>> asyncio.run(_demo()) - b'\x1b[A' - """ - if isinstance(event, MouseEvent): - filtered = self._mouse_tracker.filter_event( - event, - modes=self.terminal.modes, - ) - if filtered is None: - return - event = filtered - encoded = self.terminal.encode(event) - if encoded: - self._enqueue_stream_write(encoded) - - def send_key(self, chord: str, /) -> None: - r"""Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and enqueue outbound. - - Parameters - ---------- - chord : str - Human-readable key chord parsed via :meth:`~libvt.input.KeyEvent.parse`. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> class _MemWriter: - ... def __init__(self) -> None: - ... self.buf = bytearray() - ... def write(self, data: bytes, /) -> None: - ... self.buf.extend(data) - ... async def drain(self) -> None: - ... pass - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> bytes: - ... w = _MemWriter() - ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: - ... stream.send_key("ctrl+c") - ... return bytes(w.buf) - >>> asyncio.run(_demo()) - b'\x03' - """ - self.send_event(KeyEvent.parse(chord)) - - def paste(self, text: str, /, *, sanitize: bool = False) -> None: - r"""Encode *text* as an atomic :class:`~libvt.input.PasteEvent` frame. - - Wraps *text* in ``ESC [ 200 ~ ... ESC [ 201 ~`` when DEC mode ``?2004`` - is enabled on ``self.terminal`` and enqueues the entire bracketed frame - as a single FIFO item so concurrent replies never interleave inside it. - - Parameters - ---------- - text : str - Clipboard text to paste. - sanitize : bool - When ``False`` (default), raise :exc:`~libvt.exc.UnsafePasteError` - on control/escape injection bytes; when ``True``, strip them. - - Raises - ------ - UnsafePasteError - If *sanitize* is ``False`` and *text* contains disallowed controls. - - References - ---------- - - `xterm Control Sequences — Bracketed Paste Mode (?2004) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) - <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L401>`__ - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> class _MemWriter: - ... def __init__(self) -> None: - ... self.buf = bytearray() - ... def write(self, data: bytes, /) -> None: - ... self.buf.extend(data) - ... async def drain(self) -> None: - ... pass - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> bytes: - ... w = _MemWriter() - ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: - ... stream.terminal.feed(b"\x1b[?2004h") - ... stream.paste("line1\nline2") - ... return bytes(w.buf) - >>> asyncio.run(_demo()) - b'\x1b[200~line1\nline2\x1b[201~' - """ - self.send_event(PasteEvent(text=text, sanitize=sanitize)) - - def write_eof(self) -> None: - """Signal half-close EOF on ``writer`` after queued outbound bytes flush. - - Raises - ------ - RuntimeError - If no ``writer`` was attached to this stream. - OSError - If the stream has already been closed via :meth:`aclose`. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> class _EofWriter: - ... def __init__(self) -> None: - ... self.eof_sent = False - ... def write(self, data: bytes, /) -> None: - ... pass - ... def write_eof(self) -> None: - ... self.eof_sent = True - ... async def drain(self) -> None: - ... pass - ... def close(self) -> None: - ... pass - ... async def wait_closed(self) -> None: - ... pass - >>> async def _demo() -> bool: - ... w = _EofWriter() - ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: - ... stream.write_eof() - ... return w.eof_sent - >>> asyncio.run(_demo()) - True - """ - if self.writer is None: - msg = "AsyncTerminalStream has no writer attached" - raise RuntimeError(msg) - if self._closed: - raise OSError(errno.EBADF, "stream writer is closed") - if self._write_eof_queued: - return - self._write_eof_queued = True - if not self._write_queue and not self._writer_draining: - eof_fn = getattr(self.writer, "write_eof", None) - if callable(eof_fn): - with contextlib.suppress(OSError, RuntimeError, NotImplementedError): - eof_fn() - return - self._drain_event.clear() - self._write_queue.append(None) - self._write_wakeup.set() - self._ensure_writer_task() - - async def drain(self) -> None: - """Flush queued outbound frames and await ``writer.drain()``. - - Always yields at least one event-loop turn (``await asyncio.sleep(0)``) - and propagates non-EOF peer write errors recorded by the background - writer task. - - Raises - ------ - OSError - If flushing fails or :meth:`aclose` interrupts queued writes. - A local interruption has errno ``ECANCELED``. - - Examples - -------- - >>> import asyncio - >>> from libvt.aio import AsyncTerminalStream - >>> async def _check() -> int: - ... s = AsyncTerminalStream(asyncio.StreamReader()) - ... await s.drain() - ... return s.write_buffer_size - >>> asyncio.run(_check()) - 0 - """ - if self.writer is None: - await asyncio.sleep(0) - return - if not self._write_queue and not self._writer_draining: - await asyncio.sleep(0) - while ( - (self._write_queue or self._writer_draining) - and not self._closed - and self._write_error is None - ): - self._ensure_writer_task() - await self._drain_event.wait() - if ( - self._write_error is not None - and self._write_error.errno not in _PEER_EOF_ERRNOS - ): - raise self._write_error - - def _cancel_sync_timer(self) -> None: - if self._sync_timer_handle is not None: - self._sync_timer_handle.cancel() - self._sync_timer_handle = None - self._sync_timer_gen = None - - def _on_sync_timeout(self) -> None: - self._sync_timer_handle = None - self._sync_timer_gen = None - self._update_sync_timer(time.monotonic()) - - def _mark_eof(self) -> None: - self._eof = True - self._eof_pending = False - self._cancel_sync_timer() - self.terminal.expire_synchronized_output() - self._sync_started_at = None - self._sync_gen_tracked = None - self._last_committed_gen = self.terminal.committed_generation - self._frame_event.set() - - def _update_sync_timer(self, now: float) -> None: - if self.terminal.synchronized: - cur_gen = self.terminal.sync_generation - if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: - self._sync_gen_tracked = cur_gen - self._sync_started_at = now - if ( - now - self._sync_started_at >= self.sync_timeout - and self.terminal.expire_synchronized_output(cur_gen) - ): - self._cancel_sync_timer() - self._sync_started_at = None - self._sync_gen_tracked = None - elif ( - self._task is not None - and not self._task.done() - and self._sync_timer_gen != cur_gen - ): - self._cancel_sync_timer() - delay = max(0.0, self._sync_started_at + self.sync_timeout - now) - with contextlib.suppress(RuntimeError): - loop = asyncio.get_running_loop() - self._sync_timer_gen = cur_gen - self._sync_timer_handle = loop.call_later( - delay, - self._on_sync_timeout, - ) - else: - self._cancel_sync_timer() - self._sync_started_at = None - self._sync_gen_tracked = None - cur_committed = self.terminal.committed_generation - if cur_committed != self._last_committed_gen: - self._last_committed_gen = cur_committed - self._frame_event.set() - - async def pump_once(self) -> bool: - """Feed one stream read and return whether it delivered data. - - Concurrent callers join the current read and share its result. - EOF or close returns ``False``. Cancelling the last caller releases - the reader. - """ - if not await self._pump_batch(): - return False - while self._read_pending is not None and await self._pump_batch(): - pass - if self._eof_pending: - await self._frame_waits.drained.wait() - if not self._closed: - self._mark_eof() - return True - - async def _pump_batch(self) -> bool: - """Share the reader task that advances one frame batch.""" - while not self._closed and not self._eof: - task = self._read_task - if task is not None and not task.done() and task.cancelling(): - await asyncio.wait((task,)) - continue - if task is None or task.done(): - task = asyncio.create_task(self._read_chunk()) - self._read_task = task - self._read_waiters = 0 - self._read_waiters += 1 - try: - # A cancelled observer must leave other observers' read running. - await asyncio.wait((task,)) - return False if task.cancelled() else task.result() - finally: - if self._read_task is task: - self._read_waiters -= 1 - if self._read_waiters == 0 and not task.done(): - if not task.cancelling(): - task.cancel() - # Further cancellation of this caller must not interrupt - # the reader while it is releasing transport resources. - while not task.done(): - with contextlib.suppress(asyncio.CancelledError): - await asyncio.wait((task,)) - if self._read_task is task and task.done(): - if not task.cancelled(): - task.exception() - self._read_task = None - return False - - async def _read_chunk(self) -> bool: - """Feed a frame batch from the current input read.""" - if self._closed: - return False - await self._frame_waits.drained.wait() - if self._closed: - return False - self._attach_reply_writer() - pending = self._read_pending - chunk, offset = ( - (await self.reader.read(self.chunk_size), 0) if pending is None else pending - ) - if not chunk: - self._mark_eof() - return False - offset = self._frame_waits.feed(self.terminal, chunk, offset) - self._read_pending = (chunk, offset) if offset < len(chunk) else None - self._eof_pending = self.reader.at_eof() - replies = self.terminal.drain_replies() - self._mark_eof_if_drained() - if not self._eof: - self._update_sync_timer(time.monotonic()) - if replies and self.writer is not None and not self._closed: - self._enqueue_stream_write(replies, is_reply=True) - return True - - def _mark_eof_if_drained(self) -> None: - if ( - self._eof_pending - and self._read_pending is None - and self._frame_waits.drained.is_set() - ): - self._mark_eof() - - async def _finish_pending_read(self) -> None: - """Publish the remaining bytes already received from the reader.""" - while self._read_pending is not None: - await self._frame_waits.drained.wait() - pending = self._read_pending - if pending is None: - break - chunk, offset = pending - if offset == len(chunk): - self._read_pending = None - break - self._read_pending = ( - chunk, - self._frame_waits.feed(self.terminal, chunk, offset), - ) - self.terminal.drain_replies() - if self._eof_pending: - await self._frame_waits.drained.wait() - self._mark_eof_if_drained() - - async def _pump_loop(self) -> None: - try: - while await self.pump_once(): - pass - finally: - self._cancel_sync_timer() - self._frame_event.set() - - def start(self) -> asyncio.Task[None]: - """Start background stream pumping on the running event loop.""" - if self._close_task is not None and not self._close_task.done(): - msg = "Cannot start a stream while it is closing" - raise RuntimeError(msg) - if self._task is None or self._task.done(): - self._close_task = None - self._closed = False - self._attach_reply_writer() - self._task = asyncio.create_task(self._pump_loop()) - if self._write_queue or self._writer_draining: - self._ensure_writer_task() - return self._task - - async def aclose(self) -> None: - """Join owned tasks, close the writer and expire any held frame. - - Concurrent callers share cleanup. A cancelled caller receives - :exc:`asyncio.CancelledError` once cleanup finishes. - """ - task = self._close_task - if task is None: - if self._closed: - return - if self._write_buffered_bytes and self._write_error is None: - self._write_error = _write_aborted() - self._closed = True - task = self._close_task = asyncio.create_task(self._close_stream()) - try: - await _join_close_task(task) - finally: - if self._close_task is task and task.done(): - self._close_task = None - - async def _close_stream(self) -> None: - """Close the writer after both owned tasks have stopped.""" - self._write_wakeup.set() - self._drain_event.set() - self._cancel_sync_timer() - try: - tasks = [ - task - for task in (self._task, self._writer_task, self._read_task) - if task is not None - ] - for task in tasks: - if not task.cancelling(): - task.cancel() - results = await asyncio.gather(*tasks, return_exceptions=True) - if self.writer is not None: - self.writer.close() - with contextlib.suppress(OSError): - await self.writer.wait_closed() - for result in results: - if isinstance(result, BaseException) and not isinstance( - result, asyncio.CancelledError - ): - raise result - finally: - if self.terminal._on_reply_queued == self._flush_terminal_replies: - self.terminal._on_reply_queued = None - self._task = None - self._writer_task = None - try: - await self._finish_pending_read() - finally: - self._read_pending = None - self._eof_pending = False - self._write_queue.clear() - self._write_buffered_bytes = 0 - self._writer_draining = False - self._drain_event.set() - self._cancel_sync_timer() - self.terminal.expire_synchronized_output() - self._sync_started_at = None - self._sync_gen_tracked = None - self._last_committed_gen = self.terminal.committed_generation - self._frame_event.set() - - def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: - """Return ``(committed_snapshot, empty_unexposed)`` for :mod:`libvt.testing`.""" - return self.terminal.committed, frozenset() - - async def __aenter__(self) -> t.Self: - """Start background pumping when entering an ``async with`` block.""" - self.start() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: object, - ) -> None: - """Stop background pumping and close writer when leaving ``async with``.""" - await self.aclose() - - async def wait_for( - self, - predicate: collections.abc.Callable[[Snapshot], bool] | str, - *, - timeout: float = 2.0, - attach_note: bool = True, - ) -> Snapshot: - r"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`. - - Parameters - ---------- - predicate : collections.abc.Callable[[Snapshot], bool] | str - Callable evaluated in the waiting task at read and synchronized - frame boundaries, or a substring matched against - :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows. Hard linebreaks remain ``"\n"``. Use a callable with - :attr:`~libvt.terminal.Snapshot.text` to match physical rows. - timeout : float - Maximum wait duration in seconds before raising - :exc:`~libvt.exc.TerminalTimeoutError`. - attach_note : bool - When ``True`` (default), attach multi-line screen and flight - recorder diagnostics via PEP 678 ``__notes__``. - - Returns - ------- - Snapshot - First matching :class:`~libvt.terminal.Snapshot`. - - Raises - ------ - TerminalTimeoutError - If the stream reaches EOF/close before matching or *timeout* - expires. - """ - _validate_nonneg_seconds(timeout, "timeout") - check = ( - (lambda snap: _snapshot_matches(snap, predicate)) - if isinstance(predicate, str) - else predicate - ) - with self._frame_waits.watch(check) as waiter: - deadline = time.monotonic() + timeout - while True: - if self._task is not None and self._task.done(): - if self._task.cancelled(): - self._task = None - else: - task_exc = self._task.exception() - if task_exc is not None: - raise task_exc - now = time.monotonic() - if self.terminal.synchronized: - self._update_sync_timer(now) - ended = self._eof or ( - self._closed - and self._read_pending is None - and not self._eof_pending - ) - snap = self.terminal.snapshot() if ended else self.terminal.committed - match = self._frame_waits.match(waiter, snap) - if match is not None: - if self._task is None: - self._mark_eof_if_drained() - return match - if ended: - reason = ( - "stream reached EOF before predicate matched" - if self._eof - else "stream closed before predicate matched" - ) - raise _make_timeout_error( - self.terminal, - snap, - reason, - eof=self._eof, - attach_note=attach_note, - ) - remaining = deadline - now - if remaining <= 0: - live = self.terminal.snapshot() - raise _make_timeout_error( - self.terminal, - live, - f"timed out after {timeout:.2f}s waiting for terminal state", - eof=False, - attach_note=attach_note, - ) - self._frame_event.clear() - if self.terminal.synchronized: - sync_rem = ( - self.sync_timeout - if self._sync_started_at is None - else max(0.0, self._sync_started_at + self.sync_timeout - now) - ) - wait_slice = min(remaining, sync_rem) - else: - wait_slice = remaining - if self._task is None and not self._closed: - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self._pump_batch(), timeout=wait_slice) - if self.terminal.synchronized: - self._update_sync_timer(time.monotonic()) - else: - with contextlib.suppress(TimeoutError): - await asyncio.wait_for( - self._frame_event.wait(), - timeout=wait_slice, - ) - if self.terminal.synchronized: - self._update_sync_timer(time.monotonic()) - - -class PtySession: - """Async POSIX PTY subprocess session over :class:`~libvt.terminal.Terminal`. - - Outbound bytes from :meth:`send`, :meth:`send_event`, :meth:`send_key`, - :meth:`paste`, and synchronous terminal query auto-replies share a single - bounded FIFO queue drained via ``loop.add_writer``, paired with - :meth:`drain` for high-water backpressure. - - Attributes - ---------- - process : asyncio.subprocess.Process - Managed child process attached to the slave PTY. - terminal : Terminal - Live :class:`~libvt.terminal.Terminal` fed from ``master_fd``. - sync_timeout : float - Watchdog timeout in seconds before expiring stalled ``?2026`` frames. - write_high_water : int - High-water mark in bytes above which :meth:`drain` suspends. - max_write_buffer : int - Hard cap in bytes above which :meth:`send` raises :exc:`BufferError`. - """ - - process: asyncio.subprocess.Process - terminal: Terminal - sync_timeout: float - write_high_water: int - max_write_buffer: int - - def __init__( - self, - *, - master_fd: int, - process: asyncio.subprocess.Process, - terminal: Terminal, - sync_timeout: float = 1.0, - write_high_water: int | None = None, - max_write_buffer: int = 16_777_216, - ) -> None: - """Initialize a :class:`PtySession` around an open non-blocking *master_fd*. - - Parameters - ---------- - master_fd : int - Non-blocking master pseudo-terminal file descriptor. - process : asyncio.subprocess.Process - Spawned child process bound to the slave PTY. - terminal : Terminal - Target :class:`~libvt.terminal.Terminal` instance. - sync_timeout : float - Watchdog timeout in seconds before expiring stalled ``?2026`` holds. - write_high_water : int | None - Outbound high-water mark in bytes (defaults to - ``min(65_536, max_write_buffer)``). - max_write_buffer : int - Maximum queued outbound bytes before raising :exc:`BufferError`. - """ - _validate_nonneg_seconds(sync_timeout, "sync_timeout") - eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) - self._master_fd = master_fd - self.process = process - self.terminal = terminal - self.sync_timeout = sync_timeout - self.write_high_water = eff_hw - self.max_write_buffer = eff_max - self._mouse_tracker = MouseTracker() - self._frame_event = asyncio.Event() - self._frame_waits = _FrameWaits(self._frame_event) - self._read_followup: asyncio.Task[None] | None = None - self._close_task: asyncio.Task[int] | None = None - self._draining_master = False - self._drain_event = asyncio.Event() - self._drain_event.set() - self._eof = False - self._closed = False - self._fd_closed = False - self._closed_before_eof = False - self._group = _PtyGroup() - self._reader_registered = False - self._writer_registered = False - self._write_closed = False - self._write_error: OSError | None = None - self._async_write_error: OSError | None = None - self._read_error: OSError | None = None - self._write_queue: collections.deque[bytearray] = collections.deque() - self._write_head_offset: int = 0 - self._write_buffered_bytes: int = 0 - self._sync_started_at: float | None = None - self._sync_gen_tracked: int | None = None - self._sync_timer_handle: asyncio.TimerHandle | None = None - self._sync_timer_gen: int | None = None - self._last_committed_gen: int = self.terminal.committed_generation - self._loop: asyncio.AbstractEventLoop | None = None - if self.terminal._on_reply_queued is None: - self.terminal._on_reply_queued = self._flush_terminal_replies - - def _flush_terminal_replies(self) -> None: - """Enqueue out-of-band terminal replies onto the PTY write FIFO. - - References - ---------- - - `xterm Control Sequences — Manipulate Selection Data (OSC 52) - <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ - - Examples - -------- - >>> hasattr(PtySession, "_flush_terminal_replies") - True - """ - if self._closed or self._fd_closed: - return - replies = self.terminal.drain_replies() - if replies: - self._enqueue_write(replies, is_reply=True) - - @property - def eof(self) -> bool: - """Return ``True`` once the PTY master reaches EOF.""" - return self._eof - - @property - def closed_before_eof(self) -> bool: - """Return whether close began before the PTY master reported EOF.""" - return self._closed_before_eof - - @property - def write_buffer_size(self) -> int: - """Return number of outbound bytes currently buffered for ``master_fd``.""" - return self._write_buffered_bytes - - def _cancel_sync_timer(self) -> None: - if self._sync_timer_handle is not None: - self._sync_timer_handle.cancel() - self._sync_timer_handle = None - self._sync_timer_gen = None - - def _on_sync_timeout(self) -> None: - self._sync_timer_handle = None - self._sync_timer_gen = None - self._sync_frame_wakeup(time.monotonic()) - - def _remove_reader(self) -> None: - if self._loop is not None and self._reader_registered: - self._reader_registered = False - with contextlib.suppress(Exception): - self._loop.remove_reader(self._master_fd) - - def _remove_writer(self) -> None: - if self._loop is not None and self._writer_registered: - self._writer_registered = False - with contextlib.suppress(Exception): - self._loop.remove_writer(self._master_fd) - - def _ensure_writer(self) -> None: - if ( - self._writer_registered - or self._closed - or self._fd_closed - or self._write_closed - ): - return - loop = self._loop - if loop is None: - loop = asyncio.get_running_loop() - self._loop = loop - loop.add_writer(self._master_fd, self._on_writable) - self._writer_registered = True - - def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: - """Return ``(committed_snapshot, empty_unexposed)`` for :mod:`libvt.testing`.""" - return self.terminal.committed, frozenset() - - def _mark_eof(self) -> None: - self._eof = True - self._cancel_sync_timer() - self._remove_reader() - self.terminal.expire_synchronized_output() - self._sync_started_at = None - self._sync_gen_tracked = None - self._last_committed_gen = self.terminal.committed_generation - self._frame_event.set() - - def _sync_frame_wakeup(self, now: float) -> None: - if self.terminal.synchronized: - cur_gen = self.terminal.sync_generation - if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: - self._sync_gen_tracked = cur_gen - self._sync_started_at = now - if ( - now - self._sync_started_at >= self.sync_timeout - and self.terminal.expire_synchronized_output(cur_gen) - ): - self._cancel_sync_timer() - self._sync_started_at = None - self._sync_gen_tracked = None - elif ( - self._loop is not None - and not self._closed - and not self._eof - and self._sync_timer_gen != cur_gen - ): - self._cancel_sync_timer() - delay = max(0.0, self._sync_started_at + self.sync_timeout - now) - with contextlib.suppress(RuntimeError): - self._sync_timer_gen = cur_gen - self._sync_timer_handle = self._loop.call_later( - delay, - self._on_sync_timeout, - ) - else: - self._cancel_sync_timer() - self._sync_started_at = None - self._sync_gen_tracked = None - cur_committed = self.terminal.committed_generation - if cur_committed != self._last_committed_gen: - self._last_committed_gen = cur_committed - self._frame_event.set() - - def _append_queued_bytes(self, mv: memoryview) -> None: - if ( - self._write_queue - and (len(self._write_queue) > 1 or self._write_head_offset == 0) - and len(self._write_queue[-1]) + len(mv) <= _COALESCE_SLAB - ): - self._write_queue[-1].extend(mv) - else: - self._write_queue.append(bytearray(mv)) - self._write_buffered_bytes += len(mv) - - def _enqueue_write( - self, - data: collections.abc.Buffer, - *, - is_reply: bool = False, - ) -> None: - with _byte_view(data) as mv: - n_total = len(mv) - if n_total == 0: - return - if self._closed or self._fd_closed: - if is_reply: - return - raise OSError(errno.EBADF, "PTY session is closed") - if self._write_closed: - if is_reply: - return - if self._write_error is not None: - raise self._write_error - raise OSError(errno.EBADF, "PTY session is closing") - if self._write_buffered_bytes + n_total > self.max_write_buffer: - if is_reply: - return - msg = ( - f"PTY write buffer exceeded {self.max_write_buffer} bytes; " - "await session.drain()" - ) - raise BufferError(msg) - - if not self._write_queue: - pos = 0 - while pos < n_total: - try: - with mv[pos:] as tail: - n = os.write(self._master_fd, tail) - except (BlockingIOError, InterruptedError): - break - except OSError as exc: - self._write_closed = True - self._write_error = exc - if is_reply: - self._async_write_error = exc - return - raise - if n <= 0: - break - pos += n - if pos >= n_total: - return - with mv[pos:] as rem: - self._write_queue.append(bytearray(rem)) - self._write_head_offset = 0 - self._write_buffered_bytes = len(rem) - else: - self._append_queued_bytes(mv) - - if self._write_buffered_bytes > 0: - if self._write_buffered_bytes > self.write_high_water: - self._drain_event.clear() - self._ensure_writer() - - def _on_writable(self) -> None: - if self._closed or self._fd_closed or not self._write_queue: - self._remove_writer() - self._drain_event.set() - return - while self._write_queue: - head = self._write_queue[0] - try: - with memoryview(head) as mv, mv[self._write_head_offset :] as tail: - n = os.write(self._master_fd, tail) - except (BlockingIOError, InterruptedError): - if self._write_buffered_bytes <= self.write_high_water: - self._drain_event.set() - return - except OSError as exc: - self._write_closed = True - self._write_error = exc - self._async_write_error = exc - self._write_queue.clear() - self._write_head_offset = 0 - self._write_buffered_bytes = 0 - self._remove_writer() - self._drain_event.set() - return - if n <= 0: - if self._write_buffered_bytes <= self.write_high_water: - self._drain_event.set() - return - self._write_head_offset += n - self._write_buffered_bytes -= n - if self._write_head_offset >= len(head): - self._write_queue.popleft() - self._write_head_offset = 0 - if self._write_buffered_bytes <= self.write_high_water: - self._drain_event.set() - self._remove_writer() - self._drain_event.set() - - async def drain(self) -> None: - """Pause while outbound buffered bytes exceed :attr:`write_high_water`. - - Raises - ------ - OSError - If writing fails or :meth:`aclose` interrupts queued writes. - A local interruption has errno ``ECANCELED``. - """ - if self._write_buffered_bytes <= self.write_high_water: - if self._write_buffered_bytes > 0: - self._ensure_writer() - await asyncio.sleep(0) - while ( - self._write_buffered_bytes > self.write_high_water - and not self._closed - and not self._fd_closed - and not self._write_closed - ): - self._ensure_writer() - await self._drain_event.wait() - if ( - self._async_write_error is not None - and self._async_write_error.errno not in _PEER_EOF_ERRNOS - ): - raise self._async_write_error - - async def _drain_nonblocking_master(self) -> None: - """Consume buffered non-blocking bytes from ``master_fd`` on teardown.""" - if self._read_followup is not None: - await self._read_followup - if self._closed or self._fd_closed or self._eof: - return - for _ in range(256): - await self._frame_waits.drained.wait() - try: - chunk = os.read(self._master_fd, 16_384) - except (BlockingIOError, InterruptedError): - break - except OSError as exc: - if exc.errno in _PEER_EOF_ERRNOS: - chunk = b"" - else: - break - if not chunk: - self._eof = True - break - offset = 0 - while offset < len(chunk): - await self._frame_waits.drained.wait() - offset = self._frame_waits.feed(self.terminal, chunk, offset) - self.terminal.drain_replies() - - def _feed_read_batch(self, chunk: bytes, offset: int = 0) -> int: - offset = self._frame_waits.feed(self.terminal, chunk, offset) - if not self._draining_master: - replies = self.terminal.drain_replies() - if replies: - self._enqueue_write(replies, is_reply=True) - self._sync_frame_wakeup(time.monotonic()) - return offset - - async def _continue_read(self, chunk: bytes, offset: int) -> None: - try: - while offset < len(chunk): - await self._frame_waits.drained.wait() - offset = self._feed_read_batch(chunk, offset) - await self._frame_waits.drained.wait() - finally: - self._read_followup = None - if not (self._draining_master or self._closed or self._eof): - loop = asyncio.get_running_loop() - loop.add_reader(self._master_fd, self._on_readable) - self._reader_registered = True - - def _delay_read(self, chunk: bytes, offset: int) -> None: - self._remove_reader() - self._read_followup = asyncio.create_task(self._continue_read(chunk, offset)) - - def _on_readable(self) -> None: - if self._closed or self._fd_closed or self._draining_master: - return - if not self._frame_waits.drained.is_set(): - self._delay_read(b"", 0) - return - try: - chunk = os.read(self._master_fd, 16_384) - except (BlockingIOError, InterruptedError): - return - except OSError as exc: - if exc.errno in _PEER_EOF_ERRNOS: - chunk = b"" - else: - self._read_error = exc - self._mark_eof() - return - if not chunk: - self._mark_eof() - return - offset = self._feed_read_batch(chunk) - if offset < len(chunk): - self._delay_read(chunk, offset) - - def send(self, data: collections.abc.Buffer | str, /) -> None: - """Enqueue raw *data* bytes (or UTF-8 string) onto the PTY write queue.""" - if isinstance(data, str): - self._enqueue_write(data.encode("utf-8")) - else: - self._enqueue_write(data) - - def send_event(self, event: InputEvent, /) -> None: - """Encode *event* via :meth:`~libvt.terminal.Terminal.encode` and enqueue.""" - if isinstance(event, MouseEvent): - filtered = self._mouse_tracker.filter_event( - event, - modes=self.terminal.modes, - ) - if filtered is None: - return - event = filtered - encoded = self.terminal.encode(event) - if encoded: - self._enqueue_write(encoded) - - def send_key(self, chord: str, /) -> None: - """Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and enqueue for the PTY.""" - self.send_event(KeyEvent.parse(chord)) - - def paste(self, text: str, /, *, sanitize: bool = False) -> None: - """Encode *text* as an atomic :class:`~libvt.input.PasteEvent` on the queue.""" - self.send_event(PasteEvent(text=text, sanitize=sanitize)) - - def resize( - self, - *, - rows: int, - cols: int, - reflow: bool | None = None, - ) -> None: - """Update ``TIOCSWINSZ``, resize :attr:`terminal`, and flush ``?2048``.""" - if sys.platform == "win32": - msg = "PtySession.resize requires POSIX termios" - raise NotImplementedError(msg) - _validate_pty_dims(rows, cols) - if self._closed or self._fd_closed: - raise OSError(errno.EBADF, "PTY session is closed") - import fcntl - import termios - - winsz = _pack_winsize(rows, cols, self.terminal.profile) - fcntl.ioctl(self._master_fd, termios.TIOCSWINSZ, winsz) - self.terminal.resize(rows=rows, cols=cols, reflow=reflow) - replies = self.terminal.drain_replies() - if replies: - self._enqueue_write(replies, is_reply=True) - self._sync_frame_wakeup(time.monotonic()) - - async def wait_for( - self, - predicate: collections.abc.Callable[[Snapshot], bool] | str, - *, - timeout: float = 2.0, - attach_note: bool = True, - ) -> Snapshot: - r"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`. - - Parameters - ---------- - predicate : collections.abc.Callable[[Snapshot], bool] | str - Callable evaluated in the waiting task at read and synchronized - frame boundaries, or a substring matched against - :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped - rows. Hard linebreaks remain ``"\n"``. Use a callable with - :attr:`~libvt.terminal.Snapshot.text` to match physical rows. - timeout : float - Maximum wait duration in seconds before raising - :exc:`~libvt.exc.TerminalTimeoutError`. - attach_note : bool - When ``True`` (default), attach multi-line screen and flight - recorder diagnostics via PEP 678 ``__notes__``. - - Returns - ------- - Snapshot - First matching :class:`~libvt.terminal.Snapshot`. - - Raises - ------ - TerminalTimeoutError - If the PTY reaches EOF/close before matching or *timeout* expires. - """ - _validate_nonneg_seconds(timeout, "timeout") - check = ( - (lambda snap: _snapshot_matches(snap, predicate)) - if isinstance(predicate, str) - else predicate - ) - with self._frame_waits.watch(check) as waiter: - deadline = time.monotonic() + timeout - while True: - if self._read_error is not None: - err = self._read_error - self._read_error = None - raise err - now = time.monotonic() - if self.terminal.synchronized: - self._sync_frame_wakeup(now) - ended = self._eof or self._closed - snap = self.terminal.snapshot() if ended else self.terminal.committed - match = self._frame_waits.match(waiter, snap) - if match is not None: - return match - if ended: - reason = ( - "PTY reached EOF before predicate matched" - if self._eof - else "PTY session closed before predicate matched" - ) - raise _make_timeout_error( - self.terminal, - snap, - reason, - eof=self._eof, - attach_note=attach_note, - ) - remaining = deadline - now - if remaining <= 0: - live = self.terminal.snapshot() - raise _make_timeout_error( - self.terminal, - live, - f"timed out after {timeout:.2f}s waiting for PTY state", - eof=False, - attach_note=attach_note, - ) - self._frame_event.clear() - if self.terminal.synchronized: - sync_rem = ( - self.sync_timeout - if self._sync_started_at is None - else max(0.0, self._sync_started_at + self.sync_timeout - now) - ) - wait_slice = min(remaining, sync_rem) - else: - wait_slice = remaining - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice) - - async def _stop_process(self) -> None: - if sys.platform != "win32": - loop = asyncio.get_running_loop() - for sig in (signal.SIGHUP, signal.SIGTERM): - if not self._group.send(self.process, sig): - break - if self._group.pidfd is None: - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self.process.wait(), timeout=0.4) - else: - deadline = loop.time() + 0.4 - while self._group.send(self.process, 0): - remaining = deadline - loop.time() - if remaining <= 0: - break - await asyncio.sleep(min(0.02, remaining)) - self._group.send(self.process, signal.SIGKILL) - elif self.process.returncode is None: - with contextlib.suppress(ProcessLookupError): - self.process.terminate() - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self.process.wait(), timeout=0.4) - if self.process.returncode is None: - with contextlib.suppress(ProcessLookupError): - self.process.kill() - await self.process.wait() - - async def aclose(self) -> int: - """Signal the owned process group, drain PTY output, and close master fd.""" - task = self._close_task - if task is None: - if self._closed: - return self.process.returncode or 0 - if not self._eof: - self._closed_before_eof = True - if self._write_buffered_bytes and self._async_write_error is None: - failure = _write_aborted() - self._async_write_error = failure - self._write_error = failure - self._write_closed = True - self._remove_writer() - self._drain_event.set() - task = self._close_task = asyncio.create_task(self._close_pty()) - try: - return await _join_close_task(task) - finally: - if self._close_task is task and task.done(): - self._close_task = None - - async def _close_pty(self) -> int: - """Tear down the child and deliver the final output as one operation.""" - try: - await self._stop_process() - except BaseException: - if sys.platform != "win32": - self._group.send(self.process, signal.SIGKILL) - if self.process.returncode is None: - with contextlib.suppress(ProcessLookupError): - self.process.kill() - await self.process.wait() - raise - finally: - self._group.close() - if self.terminal._on_reply_queued == self._flush_terminal_replies: - self.terminal._on_reply_queued = None - self._draining_master = True - self._cancel_sync_timer() - self._remove_reader() - self._remove_writer() - try: - await self._drain_nonblocking_master() - finally: - was_closed = self._closed - self._closed = True - self._write_queue.clear() - self._write_head_offset = 0 - self._write_buffered_bytes = 0 - self._drain_event.set() - if not self._fd_closed: - self._fd_closed = True - with contextlib.suppress(OSError): - os.close(self._master_fd) - self.terminal.expire_synchronized_output() - self._sync_started_at = None - self._sync_gen_tracked = None - if not was_closed: - self.terminal.notify_process_exit() - self._last_committed_gen = self.terminal.committed_generation - self._frame_event.set() - - return self.process.returncode or 0 - - -@contextlib.asynccontextmanager -async def open_pty( - argv: collections.abc.Sequence[str], - *, - rows: int = 24, - cols: int = 80, - scrollback: int = 2_000, - env: collections.abc.Mapping[str, str] | None = None, - cwd: str | os.PathLike[str] | None = None, - tty_mode: TtyMode = "cooked", - python_executable: str | os.PathLike[str] | None = None, - profile: Profile = DEFAULT_PROFILE, - policy: Policy = DEFAULT_POLICY, - limits: Limits = DEFAULT_LIMITS, - encoding: ParserEncoding = "utf-8", - record_events: bool = False, - sync_timeout: float = 1.0, - write_high_water: int | None = None, - max_write_buffer: int = 16_777_216, -) -> collections.abc.AsyncGenerator[PtySession]: - """Spawn *argv* on a POSIX PTY driven by :class:`~libvt.terminal.Terminal`. - - Parameters - ---------- - argv : collections.abc.Sequence[str] - Command and arguments executed via ``os.execvp``. - rows : int - Initial PTY height in rows (``1..65535``). - cols : int - Initial PTY width in columns (``1..65535``). - scrollback : int - Primary-screen scrollback line capacity (``>= 0``). - env : collections.abc.Mapping[str, str] | None - Environment variables passed to the child process (defaults to - ``os.environ`` with ``TERM=xterm-256color``). - cwd : str | os.PathLike[str] | None - Working directory for the child process. - tty_mode : TtyMode - Initial slave terminal mode (``"cooked"``, ``"cbreak"``, or ``"raw"``). - python_executable : str | os.PathLike[str] | None - Python interpreter used for the ``TIOCSCTTY`` pre-exec trampoline. - profile : Profile - Terminal compatibility profile. - policy : Policy - Host security and query policy. - limits : Limits - Parser and state resource ceilings. - encoding : ParserEncoding - Initial byte encoding for child output (``"utf-8"`` or ``"latin-1"``). - record_events : bool - Retain events from the first read for - ``session.terminal.drain_events()``. - sync_timeout : float - Watchdog timeout in seconds before expiring stalled ``?2026`` frames. - write_high_water : int | None - High-water mark in bytes for outbound PTY writes (defaults to - ``min(65_536, max_write_buffer)``). - max_write_buffer : int - Maximum outbound bytes queued before :meth:`PtySession.send` raises - :exc:`BufferError`. - - Yields - ------ - PtySession - Active session connected to the child process and master PTY fd. - - Raises - ------ - NotImplementedError - On platforms lacking POSIX ``pty.openpty()`` (Windows). - TypeError - If *argv* is a bare string. Use ``[executable]`` for one command. - ValueError - If *argv*, dimensions, *tty_mode*, *encoding*, *sync_timeout*, or - buffer sizes are invalid. - OSError - If PTY allocation or ``execvp`` fails. - """ - if sys.platform == "win32": - msg = "open_pty requires POSIX pty.openpty()" - raise NotImplementedError(msg) - if isinstance(argv, str): - msg = "argv must be a sequence of strings such as [executable]" - raise TypeError(msg) - if not argv: - msg = "argv must not be empty" - raise ValueError(msg) - _validate_pty_dims(rows, cols) - if ( - isinstance(scrollback, bool) - or not isinstance(scrollback, int) - or scrollback < 0 - ): - msg = f"scrollback must be an int >= 0, got {scrollback!r}" - raise ValueError(msg) - if tty_mode not in ("cooked", "cbreak", "raw"): - msg = f"unsupported tty_mode: {tty_mode!r}" - raise ValueError(msg) - _validate_nonneg_seconds(sync_timeout, "sync_timeout") - eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) - recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) - - if python_executable is None: - if getattr(sys, "frozen", False) or not sys.executable: - msg = ( - "open_pty requires python_executable in frozen or embedded " - "Python runtimes" - ) - raise RuntimeError(msg) - py_bin = sys.executable - else: - py_bin = os.fspath(python_executable) - - eff_policy = policy - if policy.osc7_hosts is None: - fqdn = socket.gethostname().lower() - short = fqdn.partition(".")[0] - eff_policy = dataclasses.replace( - policy, - osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), - ) - - terminal = Terminal( - rows=rows, - cols=cols, - scrollback=scrollback, - profile=profile, - policy=eff_policy, - limits=limits, - encoding=encoding, - record_events=record_events, - recorder=recorder, - ) - - import fcntl - import pty - import termios - import tty - - loop = asyncio.get_running_loop() - master_fd, slave_fd = pty.openpty() - receiver: socket.socket | None = None - sender: socket.socket | None = None - group = _PtyGroup() - slave_closed = False - master_handed_off = False - proc: asyncio.subprocess.Process | None = None - try: - receiver, sender = socket.socketpair() - fcntl.ioctl( - slave_fd, - termios.TIOCSWINSZ, - _pack_winsize(rows, cols, profile), - ) - if tty_mode == "cbreak": - tty.setcbreak(slave_fd) - elif tty_mode == "raw": - tty.setraw(slave_fd) - os.set_blocking(master_fd, False) - receiver.setblocking(False) - child_env = dict(os.environ if env is None else env) - child_env.setdefault("TERM", "xterm-256color") - launch_fd = sender.fileno() - proc = await asyncio.create_subprocess_exec( - py_bin, - "-I", - "-S", - "-c", - _PTY_TRAMPOLINE, - str(launch_fd), - *argv, - stdin=slave_fd, - stdout=slave_fd, - stderr=slave_fd, - cwd=cwd, - env=child_env, - start_new_session=True, - pass_fds=(launch_fd,), - close_fds=True, - ) - os.close(slave_fd) - slave_closed = True - sender.close() - - err_payload = await _read_pty_handoff(loop, receiver, group) - if err_payload != b"\x00": - await proc.wait() - _raise_exec_error(err_payload, argv[0], errno.ENOEXEC) - - session = PtySession( - master_fd=master_fd, - process=proc, - terminal=terminal, - sync_timeout=sync_timeout, - write_high_water=eff_hw, - max_write_buffer=eff_max, - ) - session._loop = loop - session._group = group - master_handed_off = True - except BaseException: - if proc is not None: - group.send(proc, signal.SIGKILL) - if proc.returncode is None: - with contextlib.suppress(ProcessLookupError): - proc.kill() - await proc.wait() - raise - finally: - if not slave_closed: - with contextlib.suppress(OSError): - os.close(slave_fd) - if sender is not None: - sender.close() - if receiver is not None: - receiver.close() - if not master_handed_off: - group.close() - with contextlib.suppress(OSError): - os.close(master_fd) - - try: - loop.add_reader(master_fd, session._on_readable) - session._reader_registered = True - yield session - finally: - await session.aclose() - - -__all__ = [ - "AsyncSession", - "AsyncTerminalStream", - "PtySession", - "ReplyWriter", - "TtyMode", - "open_pty", -] diff --git a/src/libvt/aio/__init__.py b/src/libvt/aio/__init__.py new file mode 100644 index 00000000..49d15172 --- /dev/null +++ b/src/libvt/aio/__init__.py @@ -0,0 +1,22 @@ +"""``asyncio`` stream and POSIX PTY adapters over :class:`~libvt.terminal.Terminal`.""" + +from __future__ import annotations + +from ._core import ( + AsyncSession, + ReplyWriter, + TtyMode, + _pack_winsize, + _resolve_write_limits, +) +from ._pty import PtySession, open_pty +from ._stream import AsyncTerminalStream + +__all__ = [ + "AsyncSession", + "AsyncTerminalStream", + "PtySession", + "ReplyWriter", + "TtyMode", + "open_pty", +] diff --git a/src/libvt/aio/_core.py b/src/libvt/aio/_core.py new file mode 100644 index 00000000..8e956210 --- /dev/null +++ b/src/libvt/aio/_core.py @@ -0,0 +1,790 @@ +"""Shared ``asyncio`` session base, protocols, and validation helpers.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import dataclasses +import errno +import math +import struct +import time +import typing as t + +from libvt.config import Profile +from libvt.exc import TerminalTimeoutError +from libvt.input import ( + InputEvent, + KeyEvent, + MouseEvent, + MouseTracker, + PasteEvent, +) +from libvt.recorder import find_flight_recorder +from libvt.snapshot import Snapshot +from libvt.terminal import StopOn, Terminal + +type TtyMode = t.Literal["cooked", "cbreak", "raw"] + +_PEER_EOF_ERRNOS = ( + errno.EIO, + errno.EPIPE, + errno.ENXIO, + errno.ECONNRESET, + errno.ECONNABORTED, +) + + +def _make_timeout_error( + terminal: Terminal, + snap: Snapshot, + header: str, + *, + eof: bool, + attach_note: bool = True, +) -> TerminalTimeoutError: + from libvt.testing import format_flight_recorder, format_screen_box + + rec = find_flight_recorder(terminal.recorder) + recent = rec.tail(256) if rec is not None else b"" + box = format_screen_box(snap, rows=min(snap.rows, 12), cols=min(snap.cols, 80)) + diag = format_flight_recorder(terminal) + return TerminalTimeoutError( + header, + parser_state=terminal.parser_state, + screen_text=snap.text, + recent_bytes=recent, + eof=eof, + diagnostics=f"{box}\n{diag}", + attach_note=attach_note, + ) + + +class ReplyWriter(t.Protocol): + """Structural writer protocol satisfied by :class:`asyncio.StreamWriter`.""" + + def write(self, data: bytes, /) -> object: + """Buffer outbound *data* bytes.""" + + async def drain(self) -> None: + """Flush buffered outbound bytes.""" + + def close(self) -> object: + """Initiate writer close.""" + + async def wait_closed(self) -> None: + """Wait until writer close completes.""" + + +@t.runtime_checkable +class AsyncSession(t.Protocol): + """Bidirectional interactive terminal session shared by streams and PTYs. + + Satisfied by both :class:`AsyncTerminalStream` (cross-platform pipes, + sockets, and SSH channels) and :class:`PtySession` (POSIX pseudo-terminals). + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncSession, AsyncTerminalStream + >>> async def _check() -> bool: + ... return isinstance(AsyncTerminalStream(asyncio.StreamReader()), AsyncSession) + >>> asyncio.run(_check()) + True + """ + + @property + def terminal(self) -> Terminal: + """Return attached :class:`~libvt.terminal.Terminal`.""" + + @property + def eof(self) -> bool: + """Return ``True`` once inbound terminal output reaches end-of-stream.""" + + def send(self, data: collections.abc.Buffer | str, /) -> None: + """Enqueue raw *data* bytes (or UTF-8 string) for outbound delivery.""" + + def send_event(self, event: InputEvent, /) -> None: + """Encode *event* against active modes and enqueue outbound bytes.""" + + def send_key(self, chord: str, /) -> None: + """Parse *chord* (e.g. ``"ctrl+c"``) and enqueue outbound bytes.""" + + def paste(self, text: str, /, *, sanitize: bool = False) -> None: + """Encode *text* as an atomic :class:`~libvt.input.PasteEvent` frame.""" + + async def drain(self) -> None: + """Pause while outbound buffered bytes exceed ``write_high_water``.""" + + async def wait_for( + self, + predicate: collections.abc.Callable[[Snapshot], bool] | str, + *, + timeout: float = 2.0, + attach_note: bool = True, + ) -> Snapshot: + r"""Wait until *predicate* matches a committed ``Snapshot``. + + ``str`` predicates match against ``snapshot.unwrapped_text``. Pass a + callable using ``snapshot.text`` to test physical rows. + """ + + async def aclose(self) -> object: + """Close the session and expire any active ``?2026`` hold.""" + + +def _validate_nonneg_seconds(value: float, name: str) -> None: + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or value < 0 + ): + msg = f"{name} must be a finite non-negative number, got {value!r}" + raise ValueError(msg) + + +def _validate_pty_dims(rows: int, cols: int) -> None: + if ( + isinstance(rows, bool) + or isinstance(cols, bool) + or not isinstance(rows, int) + or not isinstance(cols, int) + or not (1 <= rows <= 65_535) + or not (1 <= cols <= 65_535) + ): + msg = f"rows and cols must be integers in 1..65535, got ({rows!r}, {cols!r})" + raise ValueError(msg) + + +def _pack_winsize(rows: int, cols: int, profile: Profile) -> bytes: + xpixel = min(65_535, max(0, cols * profile.screen.cell_width_px)) + ypixel = min(65_535, max(0, rows * profile.screen.cell_height_px)) + return struct.pack("HHHH", rows, cols, xpixel, ypixel) + + +def _resolve_write_limits( + write_high_water: int | None, + max_write_buffer: int, +) -> tuple[int, int]: + """Validate and resolve ``(write_high_water, max_write_buffer)`` byte caps. + + Parameters + ---------- + write_high_water : int | None + Optional outbound high-water mark in bytes; ``None`` selects + ``min(65_536, max_write_buffer)``. + max_write_buffer : int + Hard cap in bytes above which outbound writes raise :exc:`BufferError`. + + Returns + ------- + tuple[int, int] + Validated ``(effective_high_water, max_write_buffer)`` pair. + + Raises + ------ + ValueError + If either bound is ``bool``, negative, or ``max_write_buffer`` is less + than ``write_high_water`` or ``1``. + + Examples + -------- + >>> from libvt.aio import _resolve_write_limits + >>> _resolve_write_limits(None, 4096) + (4096, 4096) + >>> _resolve_write_limits(1024, 8192) + (1024, 8192) + """ + if ( + isinstance(max_write_buffer, bool) + or not isinstance(max_write_buffer, int) + or max_write_buffer < 1 + ): + msg = f"max_write_buffer must be an int >= 1, got {max_write_buffer!r}" + raise ValueError(msg) + if write_high_water is None: + eff_hw = min(65_536, max_write_buffer) + else: + if ( + isinstance(write_high_water, bool) + or not isinstance(write_high_water, int) + or write_high_water < 0 + ): + msg = f"write_high_water must be >= 0, got {write_high_water!r}" + raise ValueError(msg) + if max_write_buffer < write_high_water: + msg = ( + "max_write_buffer must be >= write_high_water, " + f"got {max_write_buffer!r} < {write_high_water!r}" + ) + raise ValueError(msg) + eff_hw = write_high_water + return eff_hw, max_write_buffer + + +def _write_aborted() -> OSError: + message = "terminal session closed before queued writes drained" + return OSError(errno.ECANCELED, message) + + +def _snapshot_matches( + snapshot: Snapshot, + predicate: collections.abc.Callable[[Snapshot], bool] | str, +) -> bool: + if isinstance(predicate, str): + return predicate in snapshot.unwrapped_text + return predicate(snapshot) + + +async def _join_close_task[T](task: asyncio.Task[T]) -> T: + """Join the cleanup task even when its caller is cancelled.""" + cancelled: asyncio.CancelledError | None = None + while not task.done(): + try: + await asyncio.wait((task,)) + except asyncio.CancelledError as error: + cancelled = error + if cancelled is not None: + raise cancelled from task.exception() + return task.result() + + +def _noop_detach() -> None: + pass + + +@dataclasses.dataclass(eq=False, slots=True) +class _FrameWait: + """Hold one published batch for an observer.""" + + predicate: collections.abc.Callable[[Snapshot], bool] + frames: tuple[Snapshot, ...] = () + + +_FRAMES_PER_BATCH = 32 + + +class _FrameWaits: + """Publish one shared batch, then let its observers consume it.""" + + def __init__(self, changed: asyncio.Event) -> None: + self._active: set[_FrameWait] = set() + self._changed = changed + self.drained = asyncio.Event() + self.drained.set() + + @contextlib.contextmanager + def watch( + self, predicate: collections.abc.Callable[[Snapshot], bool] + ) -> collections.abc.Generator[_FrameWait, None, None]: + waiter = _FrameWait(predicate) + self._active.add(waiter) + try: + yield waiter + finally: + self._active.remove(waiter) + self._release_batch() + + def _release_batch(self) -> None: + if not any(waiter.frames for waiter in self._active): + self.drained.set() + + def match(self, waiter: _FrameWait, current: Snapshot) -> Snapshot | None: + frames, waiter.frames = waiter.frames, () + self._release_batch() + for frame in frames: + if waiter.predicate(frame): + return frame + if frames and frames[-1] is current: + return None + return current if waiter.predicate(current) else None + + def feed(self, terminal: Terminal, data: bytes, offset: int = 0) -> int: + """Feed until the chunk ends or one frame batch is ready.""" + assert self.drained.is_set() + if not self._active: + terminal.feed(data if offset == 0 else memoryview(data)[offset:]) + return len(data) + frames: list[Snapshot] = [] + while offset < len(data) and len(frames) < _FRAMES_PER_BATCH: + before = terminal.committed_generation + offset = terminal.feed_until( + data, offset=offset, stop=StopOn.SYNC_START | StopOn.SYNC_END + ).offset + if terminal.committed_generation != before: + frames.append(terminal.committed) + if frames: + batch = tuple(frames) + self.drained.clear() + for waiter in self._active: + waiter.frames = batch + self._changed.set() + return offset + + +class _SessionCore: + """Shared sync-timer, input-encoding, reply-sink, and ``wait_for`` base.""" + + terminal: Terminal + sync_timeout: float + write_high_water: int + max_write_buffer: int + + _eof_wait_reason: t.ClassVar[str] + _closed_wait_reason: t.ClassVar[str] + _timeout_target_label: t.ClassVar[str] + + def _init_session( + self, + *, + terminal: Terminal, + sync_timeout: float, + write_high_water: int, + max_write_buffer: int, + ) -> None: + self.terminal = terminal + self.sync_timeout = sync_timeout + self.write_high_water = write_high_water + self.max_write_buffer = max_write_buffer + self._mouse_tracker = MouseTracker() + self._frame_event = asyncio.Event() + self._frame_waits = _FrameWaits(self._frame_event) + self._drain_event = asyncio.Event() + self._drain_event.set() + self._write_buffered_bytes: int = 0 + self._eof = False + self._closed = False + self._sync_started_at: float | None = None + self._sync_gen_tracked: int | None = None + self._sync_timer_handle: asyncio.TimerHandle | None = None + self._sync_timer_gen: int | None = None + self._last_committed_gen: int = terminal.committed_generation + self._detach_reply_sink: collections.abc.Callable[[], None] = _noop_detach + self._attach_reply_writer(flush_pending=False) + + def _attach_reply_writer(self, *, flush_pending: bool = True) -> None: + if not self._is_reply_sink_open(): + return + if self.terminal._on_reply_queued is None: + self._detach_reply_sink = self.terminal._attach_reply_sink( + self._flush_terminal_replies, + ) + if ( + flush_pending + and self.terminal._on_reply_queued == self._flush_terminal_replies + ): + self._flush_terminal_replies() + + def _is_wait_ended(self) -> bool: + return self._eof or self._closed + + def _on_wait_matched(self) -> None: + pass + + def _is_reply_sink_open(self) -> bool: + raise NotImplementedError + + def _enqueue_outbound( + self, + data: collections.abc.Buffer, + *, + is_reply: bool = False, + ) -> None: + raise NotImplementedError + + def _sync_timer_loop(self) -> asyncio.AbstractEventLoop | None: + raise NotImplementedError + + def _check_wait_error(self) -> None: + raise NotImplementedError + + async def _wait_for_frame(self, wait_slice: float) -> None: + raise NotImplementedError + + def _flush_terminal_replies(self) -> None: + r"""Flush out-of-band :meth:`~libvt.terminal.Terminal.enqueue_reply` bytes. + + References + ---------- + - `xterm Control Sequences — Manipulate Selection Data (OSC 52) + <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream, PtySession + >>> hasattr(PtySession, "_flush_terminal_replies") + True + >>> async def _demo() -> bytes: + ... buf = bytearray() + ... class _W: + ... def write(self, data: bytes, /) -> None: buf.extend(data) + ... async def drain(self) -> None: pass + ... def close(self) -> None: pass + ... async def wait_closed(self) -> None: pass + ... stream = AsyncTerminalStream(asyncio.StreamReader(), _W()) + ... stream.terminal.enqueue_reply(b"\x1b]52;c;aGk=\x07") + ... await stream.aclose() + ... return bytes(buf) + >>> asyncio.run(_demo()) + b'\x1b]52;c;aGk=\x07' + """ + if self._closed or not self._is_reply_sink_open(): + return + replies = self.terminal.drain_replies() + if replies: + self._enqueue_outbound(replies, is_reply=True) + + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(committed, frozenset())`` for :mod:`libvt.testing`.""" + return self.terminal.committed, frozenset() + + @property + def eof(self) -> bool: + """Return ``True`` once inbound terminal output reaches end-of-stream.""" + return self._eof + + @property + def write_buffer_size(self) -> int: + """Return number of outbound bytes currently buffered for writing. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> async def _check() -> int: + ... return AsyncTerminalStream(asyncio.StreamReader()).write_buffer_size + >>> asyncio.run(_check()) + 0 + """ + return self._write_buffered_bytes + + def send(self, data: collections.abc.Buffer | str, /) -> None: + r"""Enqueue raw *data* bytes (or UTF-8 string) onto the outbound write queue. + + Parameters + ---------- + data : collections.abc.Buffer | str + Raw outbound bytes or text encoded as UTF-8. + + Raises + ------ + RuntimeError + If no outbound writer is attached. + OSError + If the outbound transport is closed or half-closed. + BufferError + If buffered outbound bytes exceed :attr:`max_write_buffer`. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _MemWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> bytes: + ... w = _MemWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: + ... stream.send("ls\n") + ... return bytes(w.buf) + >>> asyncio.run(_demo()) + b'ls\n' + """ + if isinstance(data, str): + self._enqueue_outbound(data.encode("utf-8")) + else: + self._enqueue_outbound(data) + + def send_event(self, event: InputEvent, /) -> None: + r"""Encode *event* (filtering ``?1002`` drags) and enqueue outbound bytes. + + Parameters + ---------- + event : InputEvent + Keyboard, mouse, focus, or paste event to encode against + ``self.terminal.modes``. + + References + ---------- + - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L385-L393>`__ + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> from libvt.input import KeyEvent + >>> class _MemWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> bytes: + ... w = _MemWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: + ... stream.send_event(KeyEvent("up")) + ... return bytes(w.buf) + >>> asyncio.run(_demo()) + b'\x1b[A' + """ + if isinstance(event, MouseEvent): + filtered = self._mouse_tracker.filter_event( + event, + modes=self.terminal.modes, + ) + if filtered is None: + return + event = filtered + encoded = self.terminal.encode(event) + if encoded: + self._enqueue_outbound(encoded) + + def send_key(self, chord: str, /) -> None: + r"""Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and enqueue outbound. + + Parameters + ---------- + chord : str + Human-readable key chord parsed via :meth:`~libvt.input.KeyEvent.parse`. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _MemWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> bytes: + ... w = _MemWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: + ... stream.send_key("ctrl+c") + ... return bytes(w.buf) + >>> asyncio.run(_demo()) + b'\x03' + """ + self.send_event(KeyEvent.parse(chord)) + + def paste(self, text: str, /, *, sanitize: bool = False) -> None: + r"""Encode *text* as an atomic :class:`~libvt.input.PasteEvent` frame. + + Wraps *text* in ``ESC [ 200 ~ ... ESC [ 201 ~`` when DEC mode ``?2004`` + is enabled on ``self.terminal`` and enqueues the entire bracketed frame + as a single FIFO item so concurrent replies never interleave inside it. + + Parameters + ---------- + text : str + Clipboard text to paste. + sanitize : bool + When ``False`` (default), raise :exc:`~libvt.exc.UnsafePasteError` + on control/escape injection bytes; when ``True``, strip them. + + Raises + ------ + UnsafePasteError + If *sanitize* is ``False`` and *text* contains disallowed controls. + + References + ---------- + - `xterm Control Sequences — Bracketed Paste Mode (?2004) + <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__ + - `ghostty-org/ghostty src/terminal/modes.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/modes.zig#L401>`__ + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _MemWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> bytes: + ... w = _MemWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: + ... stream.terminal.feed(b"\x1b[?2004h") + ... stream.paste("line1\nline2") + ... return bytes(w.buf) + >>> asyncio.run(_demo()) + b'\x1b[200~line1\nline2\x1b[201~' + """ + self.send_event(PasteEvent(text=text, sanitize=sanitize)) + + def _cancel_sync_timer(self) -> None: + if self._sync_timer_handle is not None: + self._sync_timer_handle.cancel() + self._sync_timer_handle = None + self._sync_timer_gen = None + + def _on_sync_timeout(self) -> None: + self._sync_timer_handle = None + self._sync_timer_gen = None + self._update_sync_timer(time.monotonic()) + + def _expire_sync_and_wake(self) -> None: + self._cancel_sync_timer() + self.terminal.expire_synchronized_output() + self._sync_started_at = None + self._sync_gen_tracked = None + self._last_committed_gen = self.terminal.committed_generation + self._frame_event.set() + + def _mark_eof(self) -> None: + self._eof = True + self._expire_sync_and_wake() + + def _update_sync_timer(self, now: float) -> None: + if self.terminal.synchronized: + cur_gen = self.terminal.sync_generation + if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: + self._sync_gen_tracked = cur_gen + self._sync_started_at = now + if ( + now - self._sync_started_at >= self.sync_timeout + and self.terminal.expire_synchronized_output(cur_gen) + ): + self._cancel_sync_timer() + self._sync_started_at = None + self._sync_gen_tracked = None + elif self._sync_timer_gen != cur_gen: + loop = self._sync_timer_loop() + if loop is not None: + self._cancel_sync_timer() + delay = max(0.0, self._sync_started_at + self.sync_timeout - now) + with contextlib.suppress(RuntimeError): + self._sync_timer_gen = cur_gen + self._sync_timer_handle = loop.call_later( + delay, + self._on_sync_timeout, + ) + else: + self._cancel_sync_timer() + self._sync_started_at = None + self._sync_gen_tracked = None + cur_committed = self.terminal.committed_generation + if cur_committed != self._last_committed_gen: + self._last_committed_gen = cur_committed + self._frame_event.set() + + async def wait_for( + self, + predicate: collections.abc.Callable[[Snapshot], bool] | str, + *, + timeout: float = 2.0, + attach_note: bool = True, + ) -> Snapshot: + r"""Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`. + + Parameters + ---------- + predicate : collections.abc.Callable[[Snapshot], bool] | str + Callable evaluated in the waiting task at read and synchronized + frame boundaries, or a substring matched against + :attr:`~libvt.terminal.Snapshot.unwrapped_text` across soft-wrapped + rows. Hard linebreaks remain ``"\n"``. Use a callable with + :attr:`~libvt.terminal.Snapshot.text` to match physical rows. + timeout : float + Maximum wait duration in seconds before raising + :exc:`~libvt.exc.TerminalTimeoutError`. + attach_note : bool + When ``True`` (default), attach multi-line screen and flight + recorder diagnostics via PEP 678 ``__notes__``. + + Returns + ------- + Snapshot + First matching :class:`~libvt.terminal.Snapshot`. + + Raises + ------ + TerminalTimeoutError + If the session reaches EOF/close before matching or *timeout* + expires. + """ + _validate_nonneg_seconds(timeout, "timeout") + check = ( + (lambda snap: _snapshot_matches(snap, predicate)) + if isinstance(predicate, str) + else predicate + ) + with self._frame_waits.watch(check) as waiter: + deadline = time.monotonic() + timeout + while True: + self._check_wait_error() + now = time.monotonic() + if self.terminal.synchronized: + self._update_sync_timer(now) + ended = self._is_wait_ended() + snap = self.terminal.snapshot() if ended else self.terminal.committed + match = self._frame_waits.match(waiter, snap) + if match is not None: + self._on_wait_matched() + return match + if ended: + reason = ( + self._eof_wait_reason if self._eof else self._closed_wait_reason + ) + raise _make_timeout_error( + self.terminal, + snap, + reason, + eof=self._eof, + attach_note=attach_note, + ) + remaining = deadline - now + if remaining <= 0: + live = self.terminal.snapshot() + msg = ( + f"timed out after {timeout:.2f}s waiting for " + f"{self._timeout_target_label}" + ) + raise _make_timeout_error( + self.terminal, + live, + msg, + eof=False, + attach_note=attach_note, + ) + self._frame_event.clear() + if self.terminal.synchronized: + sync_rem = ( + self.sync_timeout + if self._sync_started_at is None + else max(0.0, self._sync_started_at + self.sync_timeout - now) + ) + wait_slice = min(remaining, sync_rem) + else: + wait_slice = remaining + await self._wait_for_frame(wait_slice) diff --git a/src/libvt/aio/_pty.py b/src/libvt/aio/_pty.py new file mode 100644 index 00000000..79568736 --- /dev/null +++ b/src/libvt/aio/_pty.py @@ -0,0 +1,907 @@ +"""POSIX pseudo-terminal session and ``open_pty`` launcher.""" + +from __future__ import annotations + +import asyncio +import collections +import collections.abc +import contextlib +import dataclasses +import errno +import os +import signal +import socket +import struct +import sys +import time +import typing as t + +from libvt._util import _byte_view, _parse_ascii_uint +from libvt.config import ( + DEFAULT_LIMITS, + DEFAULT_OSC7_HOSTS, + DEFAULT_POLICY, + DEFAULT_PROFILE, + Limits, + Policy, + Profile, +) +from libvt.parser import ParserEncoding +from libvt.recorder import FlightRecorder +from libvt.terminal import Terminal + +from ._core import ( + _PEER_EOF_ERRNOS, + TtyMode, + _join_close_task, + _pack_winsize, + _resolve_write_limits, + _SessionCore, + _validate_nonneg_seconds, + _validate_pty_dims, + _write_aborted, +) + +_COALESCE_SLAB = 16_384 +_PIDFD_SIGNAL_PROCESS_GROUP = 1 << 2 +_PIDFD_WIRE = struct.Struct("i") + +_PTY_TRAMPOLINE = ( + "stage = 'bootstrap'\n" + "err_fd = -1\n" + "try:\n" + " import errno, fcntl, os, signal, sys, termios\n" + " err_fd = int(sys.argv[1])\n" + " os.set_inheritable(err_fd, False)\n" + " stage = 'ctty'\n" + " if hasattr(termios, 'TIOCSCTTY'):\n" + " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" + " stage = 'signal'\n" + " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n" + " if hasattr(signal, 'SIGXFSZ'):\n" + " signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n" + " if sys.platform == 'linux':\n" + " stage = 'group'\n" + " import socket, struct\n" + " pidfd = None\n" + " try:\n" + " pidfd = os.pidfd_open(os.getpid())\n" + " signal.pidfd_send_signal(" + f"pidfd, 0, None, {_PIDFD_SIGNAL_PROCESS_GROUP})\n" + " except (AttributeError, OSError):\n" + " pass\n" + " else:\n" + " with socket.socket(fileno=os.dup(err_fd)) as channel:\n" + " rights = (socket.SOL_SOCKET, socket.SCM_RIGHTS,\n" + " struct.pack('i', pidfd))\n" + " channel.sendmsg([b'\\x02'], [rights])\n" + " if channel.recv(1) != b'\\x00':\n" + " raise OSError(errno.EPIPE, 'PTY launch channel closed')\n" + " finally:\n" + " if pidfd is not None:\n" + " os.close(pidfd)\n" + " stage = 'exec'\n" + " os.write(err_fd, b'\\x00')\n" + " os.execvp(sys.argv[2], sys.argv[2:])\n" + "except BaseException as exc:\n" + " try:\n" + " import errno as _e, os as _os\n" + " if err_fd >= 0:\n" + " code = getattr(exc, 'errno', None)\n" + " if not isinstance(code, int):\n" + " code = _e.ENOEXEC\n" + " msg = (getattr(exc, 'strerror', None) or str(exc))[:360]\n" + " pkt = b'\\x01' + f'{stage}:{code}:{msg}'.encode('utf-8', 'replace')\n" + " _os.write(err_fd, pkt[:500])\n" + " except BaseException:\n" + " pass\n" + " import os as _os2\n" + " _os2._exit(127)\n" +) + + +def _raise_exec_error(err_payload: bytes, cmd: str, default_errno: int) -> t.NoReturn: + if not err_payload: + msg = f"PTY launcher exited before pre-exec handoff while starting {cmd!r}" + raise RuntimeError(msg) + idx = err_payload.find(b"\x01") + body = err_payload[idx + 1 :] if idx != -1 else err_payload + parts = body.decode("utf-8", "replace").split(":", 2) + if len(parts) == 3: + stage, code_s, err_msg = parts + else: + stage, code_s, err_msg = "exec", "", body.decode("utf-8", "replace") + parsed_err = _parse_ascii_uint(code_s, max_val=65_535) + err_no = default_errno if parsed_err is None else parsed_err + target = cmd if stage == "exec" else f"open_pty({stage})" + raise OSError(err_no, err_msg or os.strerror(err_no), target) + + +class _PtyGroup: + """Own the Linux launcher identity used for process-group signals.""" + + def __init__(self) -> None: + self.pidfd: int | None = None + + def send(self, process: asyncio.subprocess.Process, signum: int) -> bool: + try: + if sys.platform == "linux" and self.pidfd is not None: + signal.pidfd_send_signal( + self.pidfd, signum, None, _PIDFD_SIGNAL_PROCESS_GROUP + ) + elif sys.platform != "win32" and process.returncode is None: + os.killpg(process.pid, signum) + else: + return False + except (ProcessLookupError, PermissionError): + return False + return True + + def close(self) -> None: + fd, self.pidfd = self.pidfd, None + if fd is not None: + with contextlib.suppress(OSError): + os.close(fd) + + +async def _read_pty_handoff( + loop: asyncio.AbstractEventLoop, + channel: socket.socket, + group: _PtyGroup, +) -> bytes: + """Receive the launcher identity and collect its exec status through EOF.""" + chunks: list[bytes] = [] + done = loop.create_future() + + def _on_ready() -> None: + if done.done(): + return + while True: + try: + if sys.platform == "linux": + data, ancillary, _, _ = channel.recvmsg( + 4_096, + socket.CMSG_SPACE(_PIDFD_WIRE.size), + socket.MSG_CMSG_CLOEXEC, + ) + else: + data, ancillary = channel.recv(4_096), [] + except (BlockingIOError, InterruptedError): + return + except OSError as exc: + loop.remove_reader(channel) + if not done.done(): + done.set_exception(exc) + return + if sys.platform == "linux" and (ancillary or data == b"\x02"): + fds = [ + fd + for level, kind, raw in ancillary + if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS + for (fd,) in _PIDFD_WIRE.iter_unpack(raw) + ] + if data != b"\x02" or group.pidfd is not None or len(fds) != 1: + for fd in fds: + os.close(fd) + done.set_exception(OSError(errno.EIO, "invalid PTY group handoff")) + loop.remove_reader(channel) + return + group.pidfd = fds[0] + try: + channel.sendall(b"\x00") + except OSError as exc: + done.set_exception(exc) + loop.remove_reader(channel) + return + continue + if not data: + loop.remove_reader(channel) + if not done.done(): + done.set_result(b"".join(chunks)) + return + chunks.append(data) + + loop.add_reader(channel, _on_ready) + try: + return await done + finally: + with contextlib.suppress(Exception): + loop.remove_reader(channel) + + +class PtySession(_SessionCore): + """Async POSIX PTY subprocess session over :class:`~libvt.terminal.Terminal`. + + Outbound bytes from :meth:`send`, :meth:`send_event`, :meth:`send_key`, + :meth:`paste`, and synchronous terminal query auto-replies share a single + bounded FIFO queue drained via ``loop.add_writer``, paired with + :meth:`drain` for high-water backpressure. + + Attributes + ---------- + process : asyncio.subprocess.Process + Managed child process attached to the slave PTY. + terminal : Terminal + Live :class:`~libvt.terminal.Terminal` fed from ``master_fd``. + sync_timeout : float + Watchdog timeout in seconds before expiring stalled ``?2026`` frames. + write_high_water : int + High-water mark in bytes above which :meth:`drain` suspends. + max_write_buffer : int + Hard cap in bytes above which :meth:`send` raises :exc:`BufferError`. + """ + + process: asyncio.subprocess.Process + _eof_wait_reason: t.ClassVar[str] = "PTY reached EOF before predicate matched" + _closed_wait_reason: t.ClassVar[str] = "PTY session closed before predicate matched" + _timeout_target_label: t.ClassVar[str] = "PTY state" + + def __init__( + self, + *, + master_fd: int, + process: asyncio.subprocess.Process, + terminal: Terminal, + sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, + ) -> None: + """Initialize a :class:`PtySession` around an open non-blocking *master_fd*. + + Parameters + ---------- + master_fd : int + Non-blocking master pseudo-terminal file descriptor. + process : asyncio.subprocess.Process + Spawned child process bound to the slave PTY. + terminal : Terminal + Target :class:`~libvt.terminal.Terminal` instance. + sync_timeout : float + Watchdog timeout in seconds before expiring stalled ``?2026`` holds. + write_high_water : int | None + Outbound high-water mark in bytes (defaults to + ``min(65_536, max_write_buffer)``). + max_write_buffer : int + Maximum queued outbound bytes before raising :exc:`BufferError`. + """ + _validate_nonneg_seconds(sync_timeout, "sync_timeout") + eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) + self._master_fd = master_fd + self.process = process + self._read_followup: asyncio.Task[None] | None = None + self._close_task: asyncio.Task[int] | None = None + self._draining_master = False + self._fd_closed = False + self._closed_before_eof = False + self._group = _PtyGroup() + self._reader_registered = False + self._writer_registered = False + self._write_closed = False + self._write_error: OSError | None = None + self._async_write_error: OSError | None = None + self._read_error: OSError | None = None + self._write_queue: collections.deque[bytearray] = collections.deque() + self._write_head_offset: int = 0 + self._loop: asyncio.AbstractEventLoop | None = None + self._init_session( + terminal=terminal, + sync_timeout=sync_timeout, + write_high_water=eff_hw, + max_write_buffer=eff_max, + ) + + @property + def closed_before_eof(self) -> bool: + """Return whether close began before the PTY master reported EOF.""" + return self._closed_before_eof + + def _is_reply_sink_open(self) -> bool: + return not self._fd_closed and not self._write_closed + + def _enqueue_outbound( + self, + data: collections.abc.Buffer, + *, + is_reply: bool = False, + ) -> None: + self._enqueue_write(data, is_reply=is_reply) + + def _sync_timer_loop(self) -> asyncio.AbstractEventLoop | None: + if self._loop is None or self._closed or self._eof: + return None + return self._loop + + def _check_wait_error(self) -> None: + if self._read_error is not None: + err = self._read_error + self._read_error = None + raise err + + async def _wait_for_frame(self, wait_slice: float) -> None: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice) + + def _remove_reader(self) -> None: + if self._loop is not None and self._reader_registered: + self._reader_registered = False + with contextlib.suppress(Exception): + self._loop.remove_reader(self._master_fd) + + def _remove_writer(self) -> None: + if self._loop is not None and self._writer_registered: + self._writer_registered = False + with contextlib.suppress(Exception): + self._loop.remove_writer(self._master_fd) + + def _ensure_writer(self) -> None: + if ( + self._writer_registered + or self._closed + or self._fd_closed + or self._write_closed + ): + return + loop = self._loop + if loop is None: + loop = asyncio.get_running_loop() + self._loop = loop + loop.add_writer(self._master_fd, self._on_writable) + self._writer_registered = True + + def _mark_eof(self) -> None: + self._remove_reader() + super()._mark_eof() + + def _append_queued_bytes(self, mv: memoryview) -> None: + if ( + self._write_queue + and (len(self._write_queue) > 1 or self._write_head_offset == 0) + and len(self._write_queue[-1]) + len(mv) <= _COALESCE_SLAB + ): + self._write_queue[-1].extend(mv) + else: + self._write_queue.append(bytearray(mv)) + self._write_buffered_bytes += len(mv) + + def _enqueue_write( + self, + data: collections.abc.Buffer, + *, + is_reply: bool = False, + ) -> None: + with _byte_view(data) as mv: + n_total = len(mv) + if n_total == 0: + return + if self._closed or self._fd_closed: + if is_reply: + return + raise OSError(errno.EBADF, "PTY session is closed") + if self._write_closed: + if is_reply: + return + if self._write_error is not None: + raise self._write_error + raise OSError(errno.EBADF, "PTY session is closing") + if self._write_buffered_bytes + n_total > self.max_write_buffer: + if is_reply: + return + msg = ( + f"PTY write buffer exceeded {self.max_write_buffer} bytes; " + "await session.drain()" + ) + raise BufferError(msg) + + if not self._write_queue: + pos = 0 + while pos < n_total: + try: + with mv[pos:] as tail: + n = os.write(self._master_fd, tail) + except (BlockingIOError, InterruptedError): + break + except OSError as exc: + self._write_closed = True + self._write_error = exc + if is_reply: + self._async_write_error = exc + return + raise + if n <= 0: + break + pos += n + if pos >= n_total: + return + with mv[pos:] as rem: + self._write_queue.append(bytearray(rem)) + self._write_head_offset = 0 + self._write_buffered_bytes = len(rem) + else: + self._append_queued_bytes(mv) + + if self._write_buffered_bytes > 0: + if self._write_buffered_bytes > self.write_high_water: + self._drain_event.clear() + self._ensure_writer() + + def _on_writable(self) -> None: + if self._closed or self._fd_closed or not self._write_queue: + self._remove_writer() + self._drain_event.set() + return + while self._write_queue: + head = self._write_queue[0] + try: + with memoryview(head) as mv, mv[self._write_head_offset :] as tail: + n = os.write(self._master_fd, tail) + except (BlockingIOError, InterruptedError): + if self._write_buffered_bytes <= self.write_high_water: + self._drain_event.set() + return + except OSError as exc: + self._write_closed = True + self._write_error = exc + self._async_write_error = exc + self._write_queue.clear() + self._write_head_offset = 0 + self._write_buffered_bytes = 0 + self._remove_writer() + self._drain_event.set() + return + if n <= 0: + if self._write_buffered_bytes <= self.write_high_water: + self._drain_event.set() + return + self._write_head_offset += n + self._write_buffered_bytes -= n + if self._write_head_offset >= len(head): + self._write_queue.popleft() + self._write_head_offset = 0 + if self._write_buffered_bytes <= self.write_high_water: + self._drain_event.set() + self._remove_writer() + self._drain_event.set() + + async def drain(self) -> None: + """Pause while outbound buffered bytes exceed :attr:`write_high_water`. + + Raises + ------ + OSError + If writing fails or :meth:`aclose` interrupts queued writes. + A local interruption has errno ``ECANCELED``. + """ + if self._write_buffered_bytes <= self.write_high_water: + if self._write_buffered_bytes > 0: + self._ensure_writer() + await asyncio.sleep(0) + while ( + self._write_buffered_bytes > self.write_high_water + and not self._closed + and not self._fd_closed + and not self._write_closed + ): + self._ensure_writer() + await self._drain_event.wait() + if ( + self._async_write_error is not None + and self._async_write_error.errno not in _PEER_EOF_ERRNOS + ): + raise self._async_write_error + + async def _drain_nonblocking_master(self) -> None: + """Consume buffered non-blocking bytes from ``master_fd`` on teardown.""" + if self._read_followup is not None: + await self._read_followup + if self._closed or self._fd_closed or self._eof: + return + for _ in range(256): + await self._frame_waits.drained.wait() + try: + chunk = os.read(self._master_fd, 16_384) + except (BlockingIOError, InterruptedError): + break + except OSError as exc: + if exc.errno in _PEER_EOF_ERRNOS: + chunk = b"" + else: + break + if not chunk: + self._eof = True + break + offset = 0 + while offset < len(chunk): + await self._frame_waits.drained.wait() + offset = self._frame_waits.feed(self.terminal, chunk, offset) + self.terminal.drain_replies() + + def _feed_read_batch(self, chunk: bytes, offset: int = 0) -> int: + offset = self._frame_waits.feed(self.terminal, chunk, offset) + if not self._draining_master: + replies = self.terminal.drain_replies() + if replies: + self._enqueue_write(replies, is_reply=True) + self._update_sync_timer(time.monotonic()) + return offset + + async def _continue_read(self, chunk: bytes, offset: int) -> None: + try: + while offset < len(chunk): + await self._frame_waits.drained.wait() + offset = self._feed_read_batch(chunk, offset) + await self._frame_waits.drained.wait() + finally: + self._read_followup = None + if not (self._draining_master or self._closed or self._eof): + loop = asyncio.get_running_loop() + loop.add_reader(self._master_fd, self._on_readable) + self._reader_registered = True + + def _delay_read(self, chunk: bytes, offset: int) -> None: + self._remove_reader() + self._read_followup = asyncio.create_task(self._continue_read(chunk, offset)) + + def _on_readable(self) -> None: + if self._closed or self._fd_closed or self._draining_master: + return + if not self._frame_waits.drained.is_set(): + self._delay_read(b"", 0) + return + try: + chunk = os.read(self._master_fd, 16_384) + except (BlockingIOError, InterruptedError): + return + except OSError as exc: + if exc.errno in _PEER_EOF_ERRNOS: + chunk = b"" + else: + self._read_error = exc + self._mark_eof() + return + if not chunk: + self._mark_eof() + return + offset = self._feed_read_batch(chunk) + if offset < len(chunk): + self._delay_read(chunk, offset) + + def resize( + self, + *, + rows: int, + cols: int, + reflow: bool | None = None, + ) -> None: + """Update ``TIOCSWINSZ``, resize :attr:`terminal`, and flush ``?2048``.""" + if sys.platform == "win32": + msg = "PtySession.resize requires POSIX termios" + raise NotImplementedError(msg) + _validate_pty_dims(rows, cols) + if self._closed or self._fd_closed: + raise OSError(errno.EBADF, "PTY session is closed") + import fcntl + import termios + + winsz = _pack_winsize(rows, cols, self.terminal.profile) + fcntl.ioctl(self._master_fd, termios.TIOCSWINSZ, winsz) + self.terminal.resize(rows=rows, cols=cols, reflow=reflow) + replies = self.terminal.drain_replies() + if replies: + self._enqueue_write(replies, is_reply=True) + self._update_sync_timer(time.monotonic()) + + async def _stop_process(self) -> None: + if sys.platform != "win32": + loop = asyncio.get_running_loop() + for sig in (signal.SIGHUP, signal.SIGTERM): + if not self._group.send(self.process, sig): + break + if self._group.pidfd is None: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self.process.wait(), timeout=0.4) + else: + deadline = loop.time() + 0.4 + while self._group.send(self.process, 0): + remaining = deadline - loop.time() + if remaining <= 0: + break + await asyncio.sleep(min(0.02, remaining)) + self._group.send(self.process, signal.SIGKILL) + elif self.process.returncode is None: + with contextlib.suppress(ProcessLookupError): + self.process.terminate() + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self.process.wait(), timeout=0.4) + if self.process.returncode is None: + with contextlib.suppress(ProcessLookupError): + self.process.kill() + await self.process.wait() + + async def aclose(self) -> int: + """Signal the owned process group, drain PTY output, and close master fd.""" + task = self._close_task + if task is None: + if self._closed: + return self.process.returncode or 0 + if not self._eof: + self._closed_before_eof = True + if self._write_buffered_bytes and self._async_write_error is None: + failure = _write_aborted() + self._async_write_error = failure + self._write_error = failure + self._write_closed = True + self._remove_writer() + self._drain_event.set() + task = self._close_task = asyncio.create_task(self._close_pty()) + try: + return await _join_close_task(task) + finally: + if self._close_task is task and task.done(): + self._close_task = None + + async def _close_pty(self) -> int: + """Tear down the child and deliver the final output as one operation.""" + try: + await self._stop_process() + except BaseException: + if sys.platform != "win32": + self._group.send(self.process, signal.SIGKILL) + if self.process.returncode is None: + with contextlib.suppress(ProcessLookupError): + self.process.kill() + await self.process.wait() + raise + finally: + self._group.close() + self._detach_reply_sink() + self._draining_master = True + self._cancel_sync_timer() + self._remove_reader() + self._remove_writer() + try: + await self._drain_nonblocking_master() + finally: + was_closed = self._closed + self._closed = True + self._write_queue.clear() + self._write_head_offset = 0 + self._write_buffered_bytes = 0 + self._drain_event.set() + if not self._fd_closed: + self._fd_closed = True + with contextlib.suppress(OSError): + os.close(self._master_fd) + if not was_closed: + self.terminal.notify_process_exit() + self._expire_sync_and_wake() + + return self.process.returncode or 0 + + +@contextlib.asynccontextmanager +async def open_pty( + argv: collections.abc.Sequence[str], + *, + rows: int = 24, + cols: int = 80, + scrollback: int = 2_000, + env: collections.abc.Mapping[str, str] | None = None, + cwd: str | os.PathLike[str] | None = None, + tty_mode: TtyMode = "cooked", + python_executable: str | os.PathLike[str] | None = None, + profile: Profile = DEFAULT_PROFILE, + policy: Policy = DEFAULT_POLICY, + limits: Limits = DEFAULT_LIMITS, + encoding: ParserEncoding = "utf-8", + record_events: bool = False, + sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, +) -> collections.abc.AsyncGenerator[PtySession]: + """Spawn *argv* on a POSIX PTY driven by :class:`~libvt.terminal.Terminal`. + + Parameters + ---------- + argv : collections.abc.Sequence[str] + Command and arguments executed via ``os.execvp``. + rows : int + Initial PTY height in rows (``1..65535``). + cols : int + Initial PTY width in columns (``1..65535``). + scrollback : int + Primary-screen scrollback line capacity (``>= 0``). + env : collections.abc.Mapping[str, str] | None + Environment variables passed to the child process (defaults to + ``os.environ`` with ``TERM=xterm-256color``). + cwd : str | os.PathLike[str] | None + Working directory for the child process. + tty_mode : TtyMode + Initial slave terminal mode (``"cooked"``, ``"cbreak"``, or ``"raw"``). + python_executable : str | os.PathLike[str] | None + Python interpreter used for the ``TIOCSCTTY`` pre-exec trampoline. + profile : Profile + Terminal compatibility profile. + policy : Policy + Host security and query policy. + limits : Limits + Parser and state resource ceilings. + encoding : ParserEncoding + Initial byte encoding for child output (``"utf-8"`` or ``"latin-1"``). + record_events : bool + Retain events from the first read for + ``session.terminal.drain_events()``. + sync_timeout : float + Watchdog timeout in seconds before expiring stalled ``?2026`` frames. + write_high_water : int | None + High-water mark in bytes for outbound PTY writes (defaults to + ``min(65_536, max_write_buffer)``). + max_write_buffer : int + Maximum outbound bytes queued before :meth:`PtySession.send` raises + :exc:`BufferError`. + + Yields + ------ + PtySession + Active session connected to the child process and master PTY fd. + + Raises + ------ + NotImplementedError + On platforms lacking POSIX ``pty.openpty()`` (Windows). + TypeError + If *argv* is a bare string. Use ``[executable]`` for one command. + ValueError + If *argv*, dimensions, *tty_mode*, *encoding*, *sync_timeout*, or + buffer sizes are invalid. + OSError + If PTY allocation or ``execvp`` fails. + """ + if sys.platform == "win32": + msg = "open_pty requires POSIX pty.openpty()" + raise NotImplementedError(msg) + if isinstance(argv, str): + msg = "argv must be a sequence of strings such as [executable]" + raise TypeError(msg) + if not argv: + msg = "argv must not be empty" + raise ValueError(msg) + _validate_pty_dims(rows, cols) + if ( + isinstance(scrollback, bool) + or not isinstance(scrollback, int) + or scrollback < 0 + ): + msg = f"scrollback must be an int >= 0, got {scrollback!r}" + raise ValueError(msg) + if tty_mode not in ("cooked", "cbreak", "raw"): + msg = f"unsupported tty_mode: {tty_mode!r}" + raise ValueError(msg) + _validate_nonneg_seconds(sync_timeout, "sync_timeout") + eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) + recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) + + if python_executable is None: + if getattr(sys, "frozen", False) or not sys.executable: + msg = ( + "open_pty requires python_executable in frozen or embedded " + "Python runtimes" + ) + raise RuntimeError(msg) + py_bin = sys.executable + else: + py_bin = os.fspath(python_executable) + + eff_policy = policy + if policy.osc7_hosts is None: + fqdn = socket.gethostname().lower() + short = fqdn.partition(".")[0] + eff_policy = dataclasses.replace( + policy, + osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), + ) + + terminal = Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=eff_policy, + limits=limits, + encoding=encoding, + record_events=record_events, + recorder=recorder, + ) + + import fcntl + import pty + import termios + import tty + + loop = asyncio.get_running_loop() + master_fd, slave_fd = pty.openpty() + receiver: socket.socket | None = None + sender: socket.socket | None = None + group = _PtyGroup() + slave_closed = False + master_handed_off = False + proc: asyncio.subprocess.Process | None = None + try: + receiver, sender = socket.socketpair() + fcntl.ioctl( + slave_fd, + termios.TIOCSWINSZ, + _pack_winsize(rows, cols, profile), + ) + if tty_mode == "cbreak": + tty.setcbreak(slave_fd) + elif tty_mode == "raw": + tty.setraw(slave_fd) + os.set_blocking(master_fd, False) + receiver.setblocking(False) + child_env = dict(os.environ if env is None else env) + child_env.setdefault("TERM", "xterm-256color") + launch_fd = sender.fileno() + proc = await asyncio.create_subprocess_exec( + py_bin, + "-I", + "-S", + "-c", + _PTY_TRAMPOLINE, + str(launch_fd), + *argv, + stdin=slave_fd, + stdout=slave_fd, + stderr=slave_fd, + cwd=cwd, + env=child_env, + start_new_session=True, + pass_fds=(launch_fd,), + close_fds=True, + ) + os.close(slave_fd) + slave_closed = True + sender.close() + + err_payload = await _read_pty_handoff(loop, receiver, group) + if err_payload != b"\x00": + await proc.wait() + _raise_exec_error(err_payload, argv[0], errno.ENOEXEC) + + session = PtySession( + master_fd=master_fd, + process=proc, + terminal=terminal, + sync_timeout=sync_timeout, + write_high_water=eff_hw, + max_write_buffer=eff_max, + ) + session._loop = loop + session._group = group + master_handed_off = True + except BaseException: + if proc is not None: + group.send(proc, signal.SIGKILL) + if proc.returncode is None: + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() + raise + finally: + if not slave_closed: + with contextlib.suppress(OSError): + os.close(slave_fd) + if sender is not None: + sender.close() + if receiver is not None: + receiver.close() + if not master_handed_off: + group.close() + with contextlib.suppress(OSError): + os.close(master_fd) + + try: + loop.add_reader(master_fd, session._on_readable) + session._reader_registered = True + yield session + finally: + await session.aclose() diff --git a/src/libvt/aio/_stream.py b/src/libvt/aio/_stream.py new file mode 100644 index 00000000..734d12f9 --- /dev/null +++ b/src/libvt/aio/_stream.py @@ -0,0 +1,655 @@ +"""Bidirectional ``asyncio`` stream adapter over :class:`~libvt.terminal.Terminal`.""" + +from __future__ import annotations + +import asyncio +import collections +import collections.abc +import contextlib +import errno +import time +import typing as t + +from libvt._util import _byte_view +from libvt.recorder import FlightRecorder +from libvt.terminal import Terminal + +from ._core import ( + _PEER_EOF_ERRNOS, + ReplyWriter, + _join_close_task, + _resolve_write_limits, + _SessionCore, + _validate_nonneg_seconds, + _validate_pty_dims, + _write_aborted, +) + + +class AsyncTerminalStream(_SessionCore): + """Bidirectional ``asyncio`` stream adapter over :class:`~libvt.terminal.Terminal`. + + Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output + batches (bounded by *sync_timeout* using generation-safe expiry), expires + any active ``?2026`` hold on ``EOF`` and :meth:`aclose`, and queues outbound + :meth:`send`, :meth:`send_event`, :meth:`send_key`, :meth:`paste`, and + automatic query replies onto a non-blocking single-FIFO writer queue so + inbound reads never block on outbound backpressure. + """ + + _eof_wait_reason: t.ClassVar[str] = "stream reached EOF before predicate matched" + _closed_wait_reason: t.ClassVar[str] = "stream closed before predicate matched" + _timeout_target_label: t.ClassVar[str] = "terminal state" + + def __init__( + self, + reader: asyncio.StreamReader, + writer: ReplyWriter | None = None, + *, + terminal: Terminal | None = None, + rows: int = 24, + cols: int = 80, + chunk_size: int = 4_096, + sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, + ) -> None: + if ( + isinstance(chunk_size, bool) + or not isinstance(chunk_size, int) + or chunk_size < 1 + ): + msg = f"chunk_size must be >= 1, got {chunk_size!r}" + raise ValueError(msg) + if terminal is None: + _validate_pty_dims(rows, cols) + _validate_nonneg_seconds(sync_timeout, "sync_timeout") + eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) + self.reader = reader + self.writer = writer + self.chunk_size = chunk_size + self._read_pending: tuple[bytes, int] | None = None + self._eof_pending = False + self._write_wakeup = asyncio.Event() + self._write_queue: collections.deque[bytes | None] = collections.deque() + self._writer_draining = False + self._write_eof_queued = False + self._write_error: OSError | None = None + self._task: asyncio.Task[None] | None = None + self._read_task: asyncio.Task[bool] | None = None + self._read_waiters = 0 + self._writer_task: asyncio.Task[None] | None = None + self._close_task: asyncio.Task[None] | None = None + self._init_session( + terminal=( + terminal + if terminal is not None + else Terminal(rows=rows, cols=cols, recorder=FlightRecorder()) + ), + sync_timeout=sync_timeout, + write_high_water=eff_hw, + max_write_buffer=eff_max, + ) + + def _is_reply_sink_open(self) -> bool: + return self.writer is not None + + def _enqueue_outbound( + self, + data: collections.abc.Buffer, + *, + is_reply: bool = False, + ) -> None: + self._enqueue_stream_write(data, is_reply=is_reply) + + def _sync_timer_loop(self) -> asyncio.AbstractEventLoop | None: + if self._task is None or self._task.done(): + return None + with contextlib.suppress(RuntimeError): + return asyncio.get_running_loop() + return None + + def _is_wait_ended(self) -> bool: + return self._eof or ( + self._closed and self._read_pending is None and not self._eof_pending + ) + + def _on_wait_matched(self) -> None: + if self._task is None: + self._mark_eof_if_drained() + + def _check_wait_error(self) -> None: + if self._task is not None and self._task.done(): + if self._task.cancelled(): + self._task = None + else: + task_exc = self._task.exception() + if task_exc is not None: + raise task_exc + + async def _wait_for_frame(self, wait_slice: float) -> None: + if self._task is None and not self._closed: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self._pump_batch(), timeout=wait_slice) + else: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for( + self._frame_event.wait(), + timeout=wait_slice, + ) + if self.terminal.synchronized: + self._update_sync_timer(time.monotonic()) + + def _ensure_writer_task(self) -> None: + """Spawn the background ``_writer_loop`` task when a loop is running. + + Safe to call synchronously outside an event loop; when no loop is + running yet, the task is started lazily on the next :meth:`drain` or + running-loop write. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> async def _check() -> bool: + ... stream = AsyncTerminalStream(asyncio.StreamReader()) + ... stream._ensure_writer_task() + ... return stream._writer_task is None + >>> asyncio.run(_check()) + True + """ + if self._closed or self.writer is None: + return + if self._writer_task is None or self._writer_task.done(): + with contextlib.suppress(RuntimeError): + asyncio.get_running_loop() + self._writer_task = asyncio.create_task(self._writer_loop()) + + def _enqueue_stream_write( + self, + data: collections.abc.Buffer, + *, + is_reply: bool = False, + ) -> None: + """Queue outbound *data* onto the single-FIFO writer without awaiting. + + Writes the first chunk synchronously to ``writer.write()`` when idle so + non-stalled writers observe bytes immediately, while queuing subsequent + frames in FIFO order until ``writer.drain()`` completes. Automatic + query replies (*is_reply* ``True``) drop silently if ``writer`` is + missing, closed, or full rather than aborting inbound parsing. + + Parameters + ---------- + data : collections.abc.Buffer + Outbound byte sequence. + is_reply : bool + ``True`` when *data* originates from automatic VT query replies. + + Raises + ------ + RuntimeError + If ``writer`` is ``None`` and *is_reply* is ``False``. + OSError + If the stream is closed or half-closed and *is_reply* is ``False``. + BufferError + If buffering *data* would exceed :attr:`max_write_buffer` and + *is_reply* is ``False``. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _BufWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> tuple[bytes, int]: + ... w = _BufWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as s: + ... s._enqueue_stream_write(b"ping") + ... size = s.write_buffer_size + ... return bytes(w.buf), size + >>> asyncio.run(_demo()) + (b'ping', 4) + """ + with _byte_view(data) as mv: + payload = mv.tobytes() + if not payload: + return + if self.writer is None: + if is_reply: + return + msg = "AsyncTerminalStream has no writer attached" + raise RuntimeError(msg) + if self._closed or self._write_eof_queued: + if is_reply: + return + raise OSError(errno.EBADF, "stream writer is closed") + if not is_reply and self._write_error is None: + self._attach_reply_writer() + if self._write_error is not None: + if is_reply: + return + raise self._write_error + if self._write_buffered_bytes + len(payload) > self.max_write_buffer: + if is_reply: + return + msg = ( + f"stream write buffer exceeded {self.max_write_buffer} bytes; " + "await stream.drain()" + ) + raise BufferError(msg) + + if not self._write_queue and not self._writer_draining: + try: + self.writer.write(payload) + except (BrokenPipeError, ConnectionResetError, OSError) as exc: + self._write_error = exc + if not is_reply: + raise + return + self._writer_draining = True + self._write_buffered_bytes = len(payload) + else: + self._write_queue.append(payload) + self._write_buffered_bytes += len(payload) + + self._drain_event.clear() + self._write_wakeup.set() + self._ensure_writer_task() + + async def _writer_loop(self) -> None: + """Drain queued outbound payloads and half-close sentinels in FIFO order. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _MemWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... await asyncio.sleep(0) + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> bytes: + ... w = _MemWriter() + ... stream = AsyncTerminalStream( + ... asyncio.StreamReader(), + ... w, + ... write_high_water=0, + ... ) + ... async with stream as s: + ... s.send("a") + ... s.send("b") + ... await s.drain() + ... return bytes(w.buf) + >>> asyncio.run(_demo()) + b'ab' + """ + try: + while not self._closed: + if self._writer_draining and self.writer is not None: + try: + await self.writer.drain() + except (BrokenPipeError, ConnectionResetError, OSError) as exc: + self._write_error = exc + self._write_queue.clear() + self._write_buffered_bytes = 0 + self._writer_draining = False + self._drain_event.set() + return + queued_sum = sum(len(x) for x in self._write_queue if x is not None) + self._write_buffered_bytes = queued_sum + self._writer_draining = False + + if self._write_queue and not self._closed: + item = self._write_queue.popleft() + if item is None: + if self.writer is not None: + eof_fn = getattr(self.writer, "write_eof", None) + if callable(eof_fn): + with contextlib.suppress( + OSError, + RuntimeError, + NotImplementedError, + ): + eof_fn() + self._drain_event.set() + return + if self.writer is not None: + try: + self.writer.write(item) + except ( + BrokenPipeError, + ConnectionResetError, + OSError, + ) as exc: + self._write_error = exc + self._write_queue.clear() + self._write_buffered_bytes = 0 + self._writer_draining = False + self._drain_event.set() + return + self._writer_draining = True + continue + + self._write_wakeup.clear() + if self._write_queue or self._writer_draining or self._closed: + continue + self._drain_event.set() + await self._write_wakeup.wait() + finally: + self._writer_draining = False + self._drain_event.set() + + def write_eof(self) -> None: + """Signal half-close EOF on ``writer`` after queued outbound bytes flush. + + Raises + ------ + RuntimeError + If no ``writer`` was attached to this stream. + OSError + If the stream has already been closed via :meth:`aclose`. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _EofWriter: + ... def __init__(self) -> None: + ... self.eof_sent = False + ... def write(self, data: bytes, /) -> None: + ... pass + ... def write_eof(self) -> None: + ... self.eof_sent = True + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> bool: + ... w = _EofWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as stream: + ... stream.write_eof() + ... return w.eof_sent + >>> asyncio.run(_demo()) + True + """ + if self.writer is None: + msg = "AsyncTerminalStream has no writer attached" + raise RuntimeError(msg) + if self._closed: + raise OSError(errno.EBADF, "stream writer is closed") + if self._write_eof_queued: + return + self._write_eof_queued = True + if not self._write_queue and not self._writer_draining: + eof_fn = getattr(self.writer, "write_eof", None) + if callable(eof_fn): + with contextlib.suppress(OSError, RuntimeError, NotImplementedError): + eof_fn() + return + self._drain_event.clear() + self._write_queue.append(None) + self._write_wakeup.set() + self._ensure_writer_task() + + async def drain(self) -> None: + """Flush queued outbound frames and await ``writer.drain()``. + + Always yields at least one event-loop turn (``await asyncio.sleep(0)``) + and propagates non-EOF peer write errors recorded by the background + writer task. + + Raises + ------ + OSError + If flushing fails or :meth:`aclose` interrupts queued writes. + A local interruption has errno ``ECANCELED``. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> async def _check() -> int: + ... s = AsyncTerminalStream(asyncio.StreamReader()) + ... await s.drain() + ... return s.write_buffer_size + >>> asyncio.run(_check()) + 0 + """ + if self.writer is None: + await asyncio.sleep(0) + return + if not self._write_queue and not self._writer_draining: + await asyncio.sleep(0) + while ( + (self._write_queue or self._writer_draining) + and not self._closed + and self._write_error is None + ): + self._ensure_writer_task() + await self._drain_event.wait() + if ( + self._write_error is not None + and self._write_error.errno not in _PEER_EOF_ERRNOS + ): + raise self._write_error + + def _mark_eof(self) -> None: + self._eof_pending = False + super()._mark_eof() + + async def pump_once(self) -> bool: + """Feed one stream read and return whether it delivered data. + + Concurrent callers join the current read and share its result. + EOF or close returns ``False``. Cancelling the last caller releases + the reader. + """ + if not await self._pump_batch(): + return False + while self._read_pending is not None and await self._pump_batch(): + pass + if self._eof_pending: + await self._frame_waits.drained.wait() + if not self._closed: + self._mark_eof() + return True + + async def _pump_batch(self) -> bool: + """Share the reader task that advances one frame batch.""" + while not self._closed and not self._eof: + task = self._read_task + if task is not None and not task.done() and task.cancelling(): + await asyncio.wait((task,)) + continue + if task is None or task.done(): + task = asyncio.create_task(self._read_chunk()) + self._read_task = task + self._read_waiters = 0 + self._read_waiters += 1 + try: + # A cancelled observer must leave other observers' read running. + await asyncio.wait((task,)) + return False if task.cancelled() else task.result() + finally: + if self._read_task is task: + self._read_waiters -= 1 + if self._read_waiters == 0 and not task.done(): + if not task.cancelling(): + task.cancel() + # Further cancellation of this caller must not interrupt + # the reader while it is releasing transport resources. + while not task.done(): + with contextlib.suppress(asyncio.CancelledError): + await asyncio.wait((task,)) + if self._read_task is task and task.done(): + if not task.cancelled(): + task.exception() + self._read_task = None + return False + + async def _read_chunk(self) -> bool: + """Feed a frame batch from the current input read.""" + if self._closed: + return False + await self._frame_waits.drained.wait() + if self._closed: + return False + self._attach_reply_writer() + pending = self._read_pending + chunk, offset = ( + (await self.reader.read(self.chunk_size), 0) if pending is None else pending + ) + if not chunk: + self._mark_eof() + return False + offset = self._frame_waits.feed(self.terminal, chunk, offset) + self._read_pending = (chunk, offset) if offset < len(chunk) else None + self._eof_pending = self.reader.at_eof() + replies = self.terminal.drain_replies() + self._mark_eof_if_drained() + if not self._eof: + self._update_sync_timer(time.monotonic()) + if replies and self.writer is not None and not self._closed: + self._enqueue_stream_write(replies, is_reply=True) + return True + + def _mark_eof_if_drained(self) -> None: + if ( + self._eof_pending + and self._read_pending is None + and self._frame_waits.drained.is_set() + ): + self._mark_eof() + + async def _finish_pending_read(self) -> None: + """Publish the remaining bytes already received from the reader.""" + while self._read_pending is not None: + await self._frame_waits.drained.wait() + pending = self._read_pending + if pending is None: + break + chunk, offset = pending + if offset == len(chunk): + self._read_pending = None + break + self._read_pending = ( + chunk, + self._frame_waits.feed(self.terminal, chunk, offset), + ) + self.terminal.drain_replies() + if self._eof_pending: + await self._frame_waits.drained.wait() + self._mark_eof_if_drained() + + async def _pump_loop(self) -> None: + try: + while await self.pump_once(): + pass + finally: + self._cancel_sync_timer() + self._frame_event.set() + + def start(self) -> asyncio.Task[None]: + """Start background stream pumping on the running event loop.""" + if self._close_task is not None and not self._close_task.done(): + msg = "Cannot start a stream while it is closing" + raise RuntimeError(msg) + if self._task is None or self._task.done(): + self._close_task = None + self._closed = False + self._attach_reply_writer() + self._task = asyncio.create_task(self._pump_loop()) + if self._write_queue or self._writer_draining: + self._ensure_writer_task() + return self._task + + async def aclose(self) -> None: + """Join owned tasks, close the writer and expire any held frame. + + Concurrent callers share cleanup. A cancelled caller receives + :exc:`asyncio.CancelledError` once cleanup finishes. + """ + task = self._close_task + if task is None: + if self._closed: + return + if self._write_buffered_bytes and self._write_error is None: + self._write_error = _write_aborted() + self._closed = True + task = self._close_task = asyncio.create_task(self._close_stream()) + try: + await _join_close_task(task) + finally: + if self._close_task is task and task.done(): + self._close_task = None + + async def _close_stream(self) -> None: + """Close the writer after both owned tasks have stopped.""" + self._write_wakeup.set() + self._drain_event.set() + self._cancel_sync_timer() + try: + tasks = [ + task + for task in (self._task, self._writer_task, self._read_task) + if task is not None + ] + for task in tasks: + if not task.cancelling(): + task.cancel() + results = await asyncio.gather(*tasks, return_exceptions=True) + if self.writer is not None: + self.writer.close() + with contextlib.suppress(OSError): + await self.writer.wait_closed() + for result in results: + if isinstance(result, BaseException) and not isinstance( + result, asyncio.CancelledError + ): + raise result + finally: + self._detach_reply_sink() + self._task = None + self._writer_task = None + try: + await self._finish_pending_read() + finally: + self._read_pending = None + self._eof_pending = False + self._write_queue.clear() + self._write_buffered_bytes = 0 + self._writer_draining = False + self._drain_event.set() + self._expire_sync_and_wake() + + async def __aenter__(self) -> t.Self: + """Start background pumping when entering an ``async with`` block.""" + self.start() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: object, + ) -> None: + """Stop background pumping and close writer when leaving ``async with``.""" + await self.aclose() diff --git a/tests/test_aio.py b/tests/test_aio.py index e1f17896..25a07a4b 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -350,8 +350,12 @@ async def test_aio_lazy_posix_imports_under_win32_simulation( """``libvt.aio`` imports cleanly when POSIX PTY modules are unavailable.""" for mod_name in ("pty", "termios", "tty", "fcntl"): monkeypatch.setitem(sys.modules, mod_name, None) - aio_path = pathlib.Path(libvt.__file__).resolve().parent / "aio.py" - spec = importlib.util.spec_from_file_location("_libvt_aio_win_check", aio_path) + aio_dir = pathlib.Path(libvt.__file__).resolve().parent / "aio" + spec = importlib.util.spec_from_file_location( + "_libvt_aio_win_check", + aio_dir / "__init__.py", + submodule_search_locations=[str(aio_dir)], + ) assert spec is not None and spec.loader is not None fresh_mod = importlib.util.module_from_spec(spec) sys.modules["_libvt_aio_win_check"] = fresh_mod @@ -366,7 +370,9 @@ async def test_aio_lazy_posix_imports_under_win32_simulation( pass await asyncio.sleep(0) finally: - sys.modules.pop("_libvt_aio_win_check", None) + for key in list(sys.modules): + if key == "_libvt_aio_win_check" or key.startswith("_libvt_aio_win_check."): + sys.modules.pop(key, None) @pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") @@ -1761,3 +1767,72 @@ async def test_async_terminal_stream_waits_for_wrapped_committed_frame() -> None assert before.text == baseline == "old" finally: await stream.aclose() + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_open_pty_closes_pty_fds_when_handoff_socket_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``open_pty`` closes both PTY fds if ``socket.socketpair()`` raises.""" + if sys.platform == "win32": + pytest.skip("POSIX pty required") + import pty + import socket + + opened: list[tuple[int, int]] = [] + real_openpty = pty.openpty + + def _tracking_openpty() -> tuple[int, int]: + pair = real_openpty() + opened.append(pair) + return pair + + def _failing_socketpair() -> tuple[socket.socket, socket.socket]: + raise OSError(errno.EMFILE, "Too many open files") + + monkeypatch.setattr(pty, "openpty", _tracking_openpty) + monkeypatch.setattr(socket, "socketpair", _failing_socketpair) + + with pytest.raises(OSError) as exc_info: # noqa: PT011 + async with open_pty((sys.executable, "-c", "pass")): + pass + assert exc_info.value.errno == errno.EMFILE + assert len(opened) == 1 + master_fd, slave_fd = opened[0] + for fd in (master_fd, slave_fd): + with pytest.raises(OSError) as fd_exc: # noqa: PT011 + os.fstat(fd) + assert fd_exc.value.errno == errno.EBADF + + +async def test_aio_sessions_support_vt_target_and_strided_buffers() -> None: + """Sessions implement ``SupportsVtTarget`` and accept strided buffers.""" + from libvt.testing import SupportsVtTarget, serialize_vt_snapshot + + writer = _MemoryWriter() + async with AsyncTerminalStream( + asyncio.StreamReader(), + writer, + rows=2, + cols=10, + ) as stream: + assert isinstance(stream, SupportsVtTarget) + stream.reader.feed_data(b"STREAM_OK") + await stream.wait_for("STREAM_OK", timeout=0.5) + assert "│STREAM_OK │" in serialize_vt_snapshot(stream) + stream.send(memoryview(b"aXbYc")[::2]) + await stream.drain() + assert bytes(writer.buffer) == b"abc" + bad_input: t.Any = 12345 + with pytest.raises(TypeError): + stream.send(bad_input) + + if sys.platform != "win32": + async with open_pty( + (sys.executable, "-u", "-c", "import sys; print('PTY_OK', flush=True)"), + rows=2, + cols=10, + ) as pty_sess: + assert isinstance(pty_sess, SupportsVtTarget) + await pty_sess.wait_for("PTY_OK", timeout=3.0) + assert "│PTY_OK │" in serialize_vt_snapshot(pty_sess)