From c8ae6397fdb234480ecbdd482c3f3cb57ced74d7 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 28 Nov 2026 20:07:20 -0600 Subject: [PATCH] screen(feat[viewport]): Add viewport and display (#59) why: Callers migrating from pyte.Screen.display and HistoryScreen need full-width rectangular row export and stateless scrollback paging over immutable snapshots without mutating live terminal state. what: - Add RowView.display_text and display_lines on RegionView, Screen, Snapshot, and Terminal with wide-glyph boundary clipping - Add Snapshot.viewport(offset=0) returning a clamped (rows, cols) RegionView over retained primary history without alt-screen blending - Expand docs/topics/migrating-from-pyte.md with a pyte 0.8.2 matrix, documented omissions, and runnable doctests --- CHANGES | 21 ++ docs/topics/migrating-from-pyte.md | 302 ++++++++++++++++++++++++++--- src/libvt/screen.py | 57 ++++++ src/libvt/terminal.py | 69 +++++++ tests/test_pyte_compat.py | 169 +++++++++++++++- 5 files changed, 587 insertions(+), 31 deletions(-) diff --git a/CHANGES b/CHANGES index e63eab5..17e557d 100644 --- a/CHANGES +++ b/CHANGES @@ -34,6 +34,27 @@ for ISO-2022 `DOCS` (`ESC % G` / `ESC % @`) transitions, {meth}`Terminal.feed_str ` raises {exc}`ValueError` when the wire encoding is `"latin-1"`. +#### Full-width display export and stateless snapshot history viewports (#59) + +{class}`~libvt.terminal.Terminal`, {class}`~libvt.terminal.Snapshot`, +{class}`~libvt.screen.Screen`, and {class}`~libvt.screen.RegionView` add +`display_lines` (paired with +{attr}`RowView.display_text `) returning +visible rows padded with trailing spaces to exact terminal-column width while +replacing wide glyphs clipped at slice boundaries with `" "`. +{meth}`Snapshot.viewport ` returns an +immutable `(rows, cols)` {class}`~libvt.screen.RegionView` shifted upward into +retained primary scrollback by `offset` rows without mutating live terminal +state or blending primary history into alternate-screen snapshots. See +{ref}`topics-migrating-from-pyte` for details. + +### Documentation + +- Expand {ref}`topics-migrating-from-pyte` with a `pyte` compatibility matrix, + documented omissions, and runnable doctests for coordinate indexing, legacy + encodings, `display_lines`, {meth}`~libvt.terminal.Snapshot.viewport` paging, + dirty-row deltas, query replies, and `tmux` observation (#59). + ## libvt 0.0.1a2 (2026-11-28) `libvt` 0.0.1a2 splits {class}`~libvt.config.Profile` into capability groups diff --git a/docs/topics/migrating-from-pyte.md b/docs/topics/migrating-from-pyte.md index 4f66f14..d50f3b0 100644 --- a/docs/topics/migrating-from-pyte.md +++ b/docs/topics/migrating-from-pyte.md @@ -2,44 +2,298 @@ # Migrating from `pyte` -Moving from `pyte` changes how you construct the terminal, feed output, and -inspect its state. This guide covers those API differences, alternate screens, -and terminal replies. +Moving from [pyte](https://github.com/selectel/pyte) (`0.8.2` comparison +baseline) replaces a separate `Stream` + `Screen` pair with a single +{class}`libvt.Terminal `, switches from `(cols, lines)` +arguments to keyword-only `(rows, cols)`, and replaces mutable dict/deque +buffers with typed `(row, col)` views, immutable +{class}`libvt.Snapshot ` values, and watermark deltas. -## Dimension order and coordinates +## Terminal construction and coordinates -`libvt` uses keyword-only `(rows, cols)` dimensions and zero-based `(row, col)` -indexing everywhere: +`pyte.Screen(columns, lines)` + `pyte.ByteStream(screen)` become a single +{class}`~libvt.terminal.Terminal` taking keyword-only `rows`, `cols`, and +`scrollback` (default `2_000` lines). Indexing uses zero-based `(row, col)` +coordinates everywhere, while 1-based VT sequences (`CSI row ; col H`) convert +at the parser boundary: ```python >>> import libvt ->>> term = libvt.Terminal(rows=24, cols=80) +>>> term = libvt.Terminal(rows=24, cols=80, scrollback=1_000) >>> term.feed(b"\x1b[2;5Hhello") ->>> term.cursor.row, term.cursor.col -(1, 9) +>>> (term.rows, term.cols, term.cursor.row, term.cursor.col) +(24, 80, 1, 9) >>> term[1, 4].text 'h' ``` -## Single byte-stream entry point - -Instead of pairing a separate `pyte` stream with a screen object, feed `bytes`, -`bytearray`, or {class}`memoryview` directly to -{meth}`libvt.Terminal.feed ` (or UTF-8 strings via -{meth}`libvt.Terminal.feed_str `): +Primary and alternate (`?47` / `?1047` / `?1049`) screen buffers exist by +default on {attr}`Terminal.screens `; entering +and leaving a full-screen application preserves primary contents and scrollback: ```python +>>> import libvt >>> term = libvt.Terminal(rows=4, cols=20, scrollback=500) ->>> term.feed(b"first\r\n\x1b[?1049hfullscreen\x1b[?1049l") +>>> term.feed(b"shell prompt\r\n\x1b[?1049htui view\x1b[?1049l") >>> term.text -'first' +'shell prompt' +``` + +## Feeding bytes, text, and legacy encodings + +Pass `bytes`, `bytearray`, or {class}`memoryview` chunks of any size to +{meth}`Terminal.feed `; multi-byte UTF-8 sequences +and escape sequences split across chunk boundaries reassemble in +{class}`libvt.parser.Parser`. Pass decoded Python strings to +{meth}`Terminal.feed_str ` when the wire +encoding is `"utf-8"`: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=2, cols=16) +>>> term.feed(b"caf\xc3") +>>> term.at_ground_state +False +>>> term.feed(b"\xa9 ") +>>> term.feed_str("ok") +>>> term[0].text +'café ok' +``` + +For legacy 8-bit streams (`ISO-8859-1` / `DEC` 8-bit `C1` / `CP437`), construct +`Terminal(..., encoding="latin-1")`, or opt into ISO-2022 `DOCS` wire switching +(`ESC % @` for legacy 8-bit and `ESC % G` for UTF-8) via +{data}`libvt.profiles.LINUX_CONSOLE_PROFILE` or +{attr}`ScreenBehavior.allow_encoding_switch `. +{data}`libvt.config.DEFAULT_PROFILE`, {data}`libvt.profiles.XTERM_PROFILE`, and +the `tmux` profiles keep `allow_encoding_switch=False` so untrusted output +cannot flip a UTF-8 session into 8-bit `C1` parsing. While `"latin-1"` is +active, `feed_str()` raises {exc}`ValueError` rather than UTF-8-encoding text +into Latin-1 bytes: + +```python +>>> from libvt.profiles import LINUX_CONSOLE_PROFILE +>>> from libvt.terminal import Terminal +>>> term = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) +>>> term.feed(b"\x1b%@\x1b(U\xda\xc4\xbf\x1b%G UTF-8") +>>> term[0].text +'┌─┐ UTF-8' +``` + +## Cell, style, cursor, and mode inspection + +Index `term[row]` for a {class}`~libvt.screen.RowView`, `term[row, col]` for an +immutable {class}`libvt.Cell `, or `term[r1:r2, c1:c2]` for a +{class}`~libvt.screen.RegionView`. Each `Cell` exposes `.text` (full grapheme +cluster, `""` on spacer cells), `.style` +({class}`libvt.Style ` with +{class}`~libvt.style.AnsiColor`, {class}`~libvt.style.IndexedColor`, or +`(r, g, b)` tuples), `.width_role` ({class}`~libvt.screen.WidthRole`), and +`.hyperlink` ({class}`~libvt.style.Hyperlink`). Inspect cursor state via +{attr}`Terminal.cursor ` +({class}`~libvt.screen.Cursor`) and enabled modes via +{attr}`Terminal.modes ` +({meth}`ModeState.is_set ` with +{class}`~libvt.modes.Mode`): + +```python +>>> import libvt +>>> from libvt.modes import Mode +>>> from libvt.style import AnsiColor +>>> term = libvt.Terminal(rows=3, cols=16) +>>> term.feed(b"\x1b[?25l\x1b[1;32mREADY\x1b[0m") +>>> cell = term[0, 0] +>>> (cell.text, cell.style.bold, cell.style.fg) +('R', True, ) +>>> (term.cursor.row, term.cursor.col, term.cursor.visible) +(0, 5, False) +>>> term.modes.is_set(Mode.DECTCEM) +False +``` + +## Full-width display export + +`pyte.Screen.display` returns every row padded to the terminal width in columns. +Use {attr}`Terminal.display_lines ` (also +available on +{attr}`Snapshot.display_lines `, +{attr}`Screen.display_lines `, +{attr}`RegionView.display_lines `, and +per-row {attr}`RowView.display_text `) when +callers expect rectangular space-padded lines; use +{attr}`Terminal.lines ` for right-trimmed rows or +{attr}`Terminal.text ` to omit trailing blank +rows: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=3, cols=8) +>>> term.feed_str("日本\r\nok") +>>> term.display_lines +('日本 ', 'ok ', ' ') +>>> term.lines +('日本', 'ok', '') +>>> term.text +'日本\nok' +``` + +Sub-row and sub-region slices replace wide characters split at the left or right +slice edge with `" "` so `display_text` and `display_lines` always match the +slice width in terminal columns: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=1, cols=6) +>>> term.feed_str("A日本B") +>>> snap = term.snapshot() +>>> snap[0][1:4].display_text, snap[0][2:5].display_text +('日 ', ' 本') +``` + +## Stateless history browsing + +Instead of mutating the live screen in place with `HistoryScreen.prev_page()` +and `next_page()`, capture an immutable `snap = term.snapshot()` and call +{meth}`Snapshot.viewport ` with a non-negative +row `offset` (`offset=0` returns the active viewport, positive offsets move +upward into retained scrollback, and offsets past `len(snap.history)` clamp at +the earliest retained row). Alternate-screen snapshots return their alternate +viewport without blending primary history, and subsequent `term.feed()` calls +leave existing snapshots and views unchanged: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=2, cols=8, scrollback=20) +>>> for i in range(6): +... term.feed_str(f"row-{i}" + ("\r\n" if i < 5 else "")) +>>> snap = term.snapshot() +>>> page = snap.rows +>>> max_offset = len(snap.history) +>>> offset = min(max_offset, 2 * page) # two pages up +>>> snap.viewport(offset).lines +('row-0', 'row-1') +>>> offset = max(0, offset - page) # one page down +>>> snap.viewport(offset).lines +('row-2', 'row-3') +>>> snap.viewport(0).display_lines # return to latest output +('row-4 ', 'row-5 ') ``` -## Bidirectional replies and side-effect events +## Dirty-row tracking through deltas + +Instead of clearing a mutable `screen.dirty` set, record a +{class}`~libvt.terminal.SyncToken` with +{meth}`Terminal.sync_token ` and compute a +{class}`~libvt.terminal.ScreenDelta` with +{meth}`Terminal.changes_since `. Check {attr}`ScreenDelta.full_resync ` +first (triggered on resize, `RIS`, or primary/alternate switches); otherwise +repaint {attr}`ScreenDelta.dirty_rows ` +after applying +{attr}`ScreenDelta.viewport_scroll_up `: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=4, cols=12) +>>> term.feed(b"row0\r\nrow1\r\nrow2") +>>> tok = term.sync_token() +>>> term.feed(b"\x1b[2;1HUPDATED") +>>> delta = term.changes_since(tok) +>>> (delta.full_resync, delta.dirty_rows) +(False, (1,)) +``` + +## Terminal replies and parser inspection + +Queries such as `DSR` (`CSI 6 n`), `DA1`/`DA2` (`CSI c` / `CSI > c`), `DECRQM`, +`DECRQSS`, and `OSC 10`/`11` queue wire responses for +{meth}`Terminal.drain_replies ` (or pass +`on_pty_write` to forward replies directly to a transport). For sequence +debugging (`pyte.DebugScreen`) or custom stream consumers (`pyte.Stream`), call +{func}`libvt.codec.explain` or drive {class}`~libvt.parser.Parser` with an +{class}`~libvt.parser.ActionSink`: + +```python +>>> import libvt +>>> from libvt.codec import explain +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"abc\x1b[6n") +>>> term.drain_replies() +b'\x1b[1;4R' +>>> [(s.kind, s.mnemonic, s.summary) for s in explain(b"\x1b[31mhi\x1b[0m")] +[('CSI', 'SGR', '31m'), ('PRINT', 'TEXT', "'hi'"), ('CSI', 'SGR', '0m')] +``` + +## 80/132-column switching and `tmux` pane observation + +{data}`~libvt.config.DEFAULT_PROFILE` configures +{attr}`ScreenBehavior.deccolm ` with +{attr}`DeccolmBehavior.GATED_BY_MODE_40 ` +and DEC mode `?40` ({attr}`Mode.ALLOW_80_132 `) +initially disabled: `?3h` and `?3l` are no-ops until `?40h` enables `80`/`132` +column switching, `?3l` selects `80` columns unconditionally (never restoring +an arbitrary prior width), and `?95h` +({attr}`Mode.DECNCSM `) suppresses screen clearing +during the switch. Pass +{attr}`DeccolmBehavior.ALWAYS ` when +emulating legacy applications that emit `?3h` without `?40h`: + +```python +>>> import libvt +>>> term = libvt.Terminal(rows=4, cols=90) +>>> term.feed(b"\x1b[?3h") # ignored while ?40 is disabled +>>> term.cols +90 +>>> term.feed(b"\x1b[?40h\x1b[?3h") +>>> term.cols +132 +>>> term.feed(b"\x1b[?3l") +>>> term.cols +80 +``` + +When observing a `tmux` pane via {mod}`libvt.contrib.tmux` +({func}`~libvt.contrib.tmux.capture.decode_tmux_capture`, +{func}`~libvt.contrib.tmux.capture.build_tmux_capture_command`, and +{class}`~libvt.contrib.tmux.control.TmuxPaneSync`), +{func}`~libvt.contrib.tmux.profile.tmux_profile` sets +{attr}`DeccolmBehavior.CLEAR_ONLY ` and +{data}`~libvt.contrib.tmux.profile.TMUX_OBSERVER_POLICY` sets +`emit_replies=False`. `tmux` remains authoritative for pane geometry across live +attachment, and passive observation never writes duplicate query replies back to +the application. + +## Compatibility matrix and documented omissions + +Comparison baseline: `pyte 0.8.2`. + +| Capability | `pyte` (`0.8.2`) | `libvt` equivalent | Differences and omissions | +| :--- | :--- | :--- | :--- | +| Screen + parser | `Screen(cols, lines)` + `ByteStream` | {class}`~libvt.terminal.Terminal` (`rows=`, `cols=`) | Keyword `(rows, cols)`; zero-based `(row, col)` | +| Cursor & margins | `CUU`/`CUD`/`CUF`/`CUB`/`CUP`/`DECSTBM` | `Terminal` (`DECSTBM` + `?69` `DECSLRM`) | Adds `CHT`/`CBT` (`I`/`Z`), `HPR`/`VPR`, left/right margins | +| Editing & erase | `ED`, `EL`, `ICH`, `DCH`, `IL`, `DL`, `ECH` | `Terminal` + `Screen` | Adds `DECSED`/`DECSEL` (`DECSCA` protection), `ED 3` history clear, `REP` | +| Tabstops | `HTS`, `TBC 0`/`3` | {attr}`Screen.tabstops ` | Immutable sorted `tuple[int, ...]` | +| Modes & `?1049` | Mutable bit-shifted `screen.mode` set; no alt buffer | {attr}`Terminal.modes ` ({class}`~libvt.modes.Mode`) | Dual primary/alternate screens (`?47`/`?1047`/`?1049`), `?2004`, `?2026`, `?2027`, `XTSAVE`/`XTRESTORE` | +| `DECCOLM` (`?3`) | Always resizes `132` / saved width | {class}`~libvt.config.DeccolmBehavior` (`?3`, `?40`, `?95`) | Default `GATED_BY_MODE_40`; `?3l` selects `80` cols unconditionally; `CLEAR_ONLY` on `tmux` | +| Character sets | `B`, `0`, `A`, `U` (CP437), `V` (`VAX42`) | `G0`–`G3` (`B`, `0`, `A`, `U`), `SI`/`SO`/`LS2`/`LS3`/`SS2`/`SS3` | **pyte’s VAX42 extension is unsupported** (falls back to `'B'`); `'U'` maps `0xA0..0xFF` in `"latin-1"` | +| Wire encoding | `ESC % G` / `ESC % @` always active | `Parser(encoding=...)` + `allow_encoding_switch` | Default `False` (UTF-8 locked); `True` on `LINUX_CONSOLE_PROFILE`; `feed_str()` raises `ValueError` in `"latin-1"` | +| Colors & SGR | Strings / hex RGB; basic SGR | {class}`~libvt.style.Style` (`AnsiColor`, `IndexedColor`, RGB) | Adds `dim`, `overline`, `hidden`, ITU T.416 `:` subparameters (`4:3` curly underline, `58:...` underline color), `OSC 8` links | +| Unicode & width | `wcwidth` per code point | Unicode 17 UAX #11 / #29 (`?2027`) | Zero-width combining marks, `VS15`/`VS16`, regional flags, and ZWJ emoji stay in single wide cells | +| Resizing | Truncates/pads without reflow | {meth}`Terminal.resize ` (`reflow=...`) | Soft-wrapped primary lines reflow by default (`reflow=False` opts out) | +| History paging | `HistoryScreen` mutates `screen.buffer` | {attr}`Terminal.history `, {meth}`Snapshot.viewport ` | Stateless `(rows, cols)` `RegionView` over immutable snapshots | +| Full-grid export | `screen.display` | `display_lines`, `RowView.display_text` | Space-padded to terminal columns with wide-boundary clipping | +| Change tracking | Mutable `screen.dirty` set | `sync_token()` + `changes_since()` | Watermark `ScreenDelta` safe for multiple independent observers | +| Parser debug & replies | `DebugScreen`, `write_process_input` | {func}`~libvt.codec.explain`, `Parser`, `drain_replies()`, `on_pty_write` | Replies buffered up to `Limits.max_reply_bytes` or streamed via callback | + +Intentional omissions and behavioral differences: -Terminal queries (`CSI 6 n`, `CSI c`, `DECRQM`, `DECRQSS`, `XTVERSION`, -`XTGETTCAP`, `OSC 10/11 ; ?`) accumulate in -{meth}`libvt.Terminal.drain_replies ` -rather than being dropped, and structured notifications (`OSC 0/2`, `OSC 7`, -`OSC 52`, `OSC 133`, `OSC 7501`, `?2026`) flow through `on_event` or -{meth}`libvt.Terminal.drain_events `. +- **pyte’s VAX42 extension is unsupported.** Designating `'V'` via `ESC ( V` + (or `)` / `*` / `+`) falls back to US-ASCII (`'B'`). +- **`DECCOLM` (`?3`) requires `?40h` on `DEFAULT_PROFILE` and resets to `80` + columns.** Enable `?40h` or configure + {attr}`DeccolmBehavior.ALWAYS ` when + testing bare `CSI ? 3 h` sequences; `CSI ? 3 l` always selects `80` columns + rather than restoring a pre-`DECCOLM` custom width. +- **Wire encoding switches (`ESC % @` / `ESC % G`) default off.** Enable + `allow_encoding_switch=True` (or + {data}`~libvt.profiles.LINUX_CONSOLE_PROFILE`) when replaying legacy ISO-2022 + `DOCS` byte streams. diff --git a/src/libvt/screen.py b/src/libvt/screen.py index d6fea62..dd75584 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -339,6 +339,44 @@ def _frozen_row_runs( 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]): """Read-only sequence view over one live viewport or scrollback row.""" @@ -388,6 +426,12 @@ def text(self) -> str: raw = "".join(row.char_at(c) for c in range(self._col_range.start, limit)) return raw.rstrip(" ") + @property + def display_text(self) -> str: + """Return space-padded text spanning ``len(self)`` terminal columns.""" + row = self._current_row() + return _format_display_row(row, self._col_range.start, self._col_range.stop) + @property def runs(self) -> tuple[RowRun, ...]: """Return coalesced ``(style, hyperlink)`` spans up to ``used`` columns.""" @@ -728,6 +772,13 @@ def lines(self) -> tuple[str, ...]: """Return right-trimmed text for each row in the region.""" return tuple(RowView(r, self._col_range).text for r in self._rows) + @property + def display_lines(self) -> tuple[str, ...]: + """Return space-padded text of width ``cols`` for each row in the region.""" + start_c = self._col_range.start + stop_c = self._col_range.stop + return tuple(_format_display_row(r, start_c, stop_c) for r in self._rows) + @property def text(self) -> str: """Return newline-joined text with trailing empty rows omitted.""" @@ -1054,6 +1105,12 @@ def lines(self) -> tuple[str, ...]: """Return right-trimmed text for every visible row.""" return tuple(r.rstrip_text() for r in self._rows) + @property + def display_lines(self) -> tuple[str, ...]: + """Return space-padded text of width ``cols`` for every visible row.""" + cols = self._cols + return tuple(_format_display_row(r, 0, cols) for r in self._rows) + @property def text(self) -> str: """Return visible screen text with trailing blank rows omitted.""" diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index f1c1c51..3d18b31 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -118,6 +118,7 @@ Screen, ScreenSet, ScrollRegion, + _format_display_row, _HistoryView, format_rows_text, slice_grid, @@ -800,11 +801,74 @@ def history(self) -> collections.abc.Sequence[RowView]: """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback rows.""" return _HistoryView(self._history, cols=self._cols) + def viewport(self, offset: int = 0) -> RegionView: + """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. + """ + 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)) + 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)) + @property def lines(self) -> tuple[str, ...]: """Return right-trimmed text for every visible row in the snapshot.""" return tuple(r.rstrip_text() for r in self._rows) + @property + def display_lines(self) -> tuple[str, ...]: + """Return space-padded text of width ``cols`` for every visible row.""" + cols = self._cols + return tuple(_format_display_row(r, 0, cols) for r in self._rows) + @property def text(self) -> str: """Return visible snapshot text with trailing blank rows omitted.""" @@ -2333,6 +2397,11 @@ def lines(self) -> tuple[str, ...]: """Return right-trimmed visible lines of the active screen.""" return self._screens.active.lines + @property + def display_lines(self) -> tuple[str, ...]: + """Return space-padded visible lines of width ``cols`` on the active screen.""" + return self._screens.active.display_lines + @property def text(self) -> str: """Return visible active-screen text with trailing blank rows omitted.""" diff --git a/tests/test_pyte_compat.py b/tests/test_pyte_compat.py index 6c03450..5c0db8c 100644 --- a/tests/test_pyte_compat.py +++ b/tests/test_pyte_compat.py @@ -1,4 +1,4 @@ -"""Clean-room compatibility tests for terminal modes, charsets, and DOCS.""" +"""Clean-room compatibility tests for terminal modes, charsets, DOCS, and views.""" from __future__ import annotations @@ -6,6 +6,8 @@ import pytest +import libvt +from libvt._ucd import display_width from libvt.codec import explain from libvt.config import DEFAULT_PROFILE, DeccolmBehavior, Profile from libvt.contrib.tmux import tmux_profile @@ -16,7 +18,7 @@ LINUX_CONSOLE_PROFILE, XTERM_PROFILE, ) -from libvt.style import AnsiColor +from libvt.style import AnsiColor, IndexedColor, UnderlineStyle from libvt.terminal import OutputFormat, Terminal @@ -49,6 +51,7 @@ def test_deccolm_gated_by_mode_40_default_matrix() -> None: assert not term.modes.is_set(Mode.ALLOW_80_132) assert not term.modes.is_set(Mode.DECCOLM) + # ?3h and ?3l while mode 40 is disabled: no resize, clear, margin reset, or homing. term.feed(b"\x1b[2;4r\x1b[3;10HKEEP") term.feed(b"\x1b[?3h") assert (term.rows, term.cols) == (5, 90) @@ -62,12 +65,14 @@ def test_deccolm_gated_by_mode_40_default_matrix() -> None: assert term[2].text == " KEEP" assert (term.cursor.row, term.cursor.col) == (2, 13) + # ?40h enables subsequent DECCOLM operations while retaining current dimensions. term.feed(b"\x1b[?40h") assert term.modes.is_set(Mode.ALLOW_80_132) assert (term.rows, term.cols) == (5, 90) assert term[2].text == " KEEP" assert (term.cursor.row, term.cursor.col) == (2, 13) + # ?3h while enabled: 132 columns, clear screen, reset margins, home cursor. term.feed(b"\x1b[?3h") assert term.modes.is_set(Mode.DECCOLM) assert (term.rows, term.cols) == (5, 132) @@ -80,6 +85,7 @@ def test_deccolm_gated_by_mode_40_default_matrix() -> None: term.screen.scroll_region.right, ) == (0, 4, 0, 131) + # ?3l while enabled: 80 columns unconditionally (never restoring prior 90 cols). term.feed(b"\x1b[2;4r\x1b[4;132HX\x1b[?3l") assert not term.modes.is_set(Mode.DECCOLM) assert (term.rows, term.cols) == (5, 80) @@ -87,6 +93,7 @@ def test_deccolm_gated_by_mode_40_default_matrix() -> None: assert (term.cursor.row, term.cursor.col, term.cursor.pending_wrap) == (0, 0, False) assert (term.screen.scroll_region.top, term.screen.scroll_region.bottom) == (0, 4) + # ?40l disables subsequent DECCOLM operations while retaining current dimensions. term.feed(b"\x1b[?3hWIDE\x1b[?40l") assert (term.rows, term.cols) == (5, 132) assert term[0].text == "WIDE" @@ -112,6 +119,7 @@ def test_deccolm_always_decncsm_ris_xtsave_and_vt_roundtrip() -> None: False, ) + # ?95 (DECNCSM) suppresses screen clear on DECCOLM while still resizing & homing. ncsm = Terminal(rows=4, cols=80) ncsm.feed(b"\x1b[?40h\x1b[?95h\x1b[2;3r\x1b[2;5HKEEP\x1b[?3h") assert ncsm.cols == 132 @@ -119,6 +127,7 @@ def test_deccolm_always_decncsm_ris_xtsave_and_vt_roundtrip() -> None: assert (ncsm.cursor.row, ncsm.cursor.col) == (0, 0) assert (ncsm.screen.scroll_region.top, ncsm.screen.scroll_region.bottom) == (0, 3) + # RIS restores 80 columns when DECCOLM was active, leaving non-DECCOLM sizes intact. ncsm.feed(b"\x1bc") assert ncsm.cols == 80 assert not ncsm.modes.is_set(Mode.DECCOLM) @@ -128,6 +137,7 @@ def test_deccolm_always_decncsm_ris_xtsave_and_vt_roundtrip() -> None: custom_w.feed(b"abc\x1bc") assert custom_w.cols == 94 + # XTSAVE / XTRESTORE restores ?40h before ?3h so gated 132-col state round-trips. xts = Terminal(rows=3, cols=80) xts.feed(b"\x1b[?40h\x1b[?95h\x1b[?3hSAVED\x1b[?s\x1b[?3;40l") assert xts.cols == 80 @@ -138,6 +148,7 @@ def test_deccolm_always_decncsm_ris_xtsave_and_vt_roundtrip() -> None: assert xts.modes.is_set(Mode.ALLOW_80_132) assert xts[0].text == "NARROW" + # OutputFormat.VT emits DECCOLM ahead of row text so round-trip never wipes cells. for keep_40 in (True, False): src = Terminal(rows=3, cols=80) src.feed(b"\x1b[?40h\x1b[?3h\x1b[1;125HEDGE132!") @@ -159,6 +170,7 @@ def test_deccolm_tmux_observer_and_linux_console_profiles() -> None: tm.feed(b"\x1b[2;4r\x1b[?6h\x1b[2;3HPANE\x1b[?40h\x1b[?3h") assert (tm.rows, tm.cols) == (4, 96) assert tm.text == "" + # DECOM origin-mode home in tmux places cursor at (scroll_region.top, 0). assert (tm.cursor.row, tm.cursor.col) == (1, 0) assert not tm.modes.is_set(Mode.DECCOLM) assert not tm.modes.is_set(Mode.ALLOW_80_132) @@ -177,21 +189,26 @@ def test_deccolm_tmux_observer_and_linux_console_profiles() -> None: def test_legacy_charsets_cp437_u_shifts_save_restore_and_vax42_omission() -> None: """``U`` maps CP437 GR bytes in Latin-1; ``V`` (pyte VAX42) falls back to ``B``.""" term = Terminal(rows=4, cols=20, encoding="latin-1") + # G0='U' in latin-1: 0x20..0x7E stays ASCII, 0xA0..0xFF maps CP437 glyphs. term.feed(b"\x1b(UASCII:\xda\xc4\xbf\xdb\xe0\xfb") assert term[0].text == "ASCII:┌─┐█\u03b1√" + # 8-bit C1 controls (0x9B CSI) remain control introducers in latin-1 mode. term.feed(b"\r\n\x9b31m\xb3\x9b0m") assert term[1].text == "│" assert term[1, 0].style.fg == AnsiColor.RED + # G0..G3 shifts (SO/SI/LS2/LS3/SS2/SS3) and DECSC/DECRC across '0', 'A', 'U', 'B'. shifts = Terminal(rows=3, cols=20, encoding="latin-1") shifts.feed(b"\x1b)0\x1b*A\x1b+U\x0elq\x1b7\x1bn#\x1bO\xfb\x0f#\x1b8\x1b[6Gk\x0f") assert shifts[0].text == "┌─£√#┐" + # Designating 'U' in UTF-8 mode must never corrupt UTF-8 Latin-1 code points. utf8_term = Terminal(rows=2, cols=20) utf8_term.feed("café £10".encode() + b"\x1b(U " + "café".encode()) assert utf8_term[0].text == "café £10 café" + # pyte's VAX42 ('V') is unsupported and falls back cleanly to US-ASCII ('B'). vax_fallback = Terminal(rows=2, cols=20) vax_fallback.feed(b"\x1b(0lqk\x1b(Vlqk#") assert vax_fallback[0].text == "┌─┐lqk#" @@ -212,6 +229,7 @@ def test_encoding_switches_docs_utf8_c1_isolation_and_chunking() -> None: "encoding -> UTF-8", ] + # Locked profiles ignore ESC % @ without emitting UnhandledSequence. for locked_prof in (DEFAULT_PROFILE, XTERM_PROFILE, tmux_profile("3.8a")): locked = Terminal(rows=2, cols=20, profile=locked_prof, record_events=True) locked.feed(b"\x1b%@caf\xc3\xa9") @@ -219,11 +237,13 @@ def test_encoding_switches_docs_utf8_c1_isolation_and_chunking() -> None: assert locked[0].text == "café" assert locked.drain_events() == () + # Switchable profile: UTF-8 continuation bytes, C1 stripping, pending UTF-8 flush, + # ECMA-35 charset save/restore, and same-chunk + split-chunk transitions. stream = ( - b"\xe2\x80\x9cHi\xe2\x80\x9d" - b"\xc2\x9b31m!" - b"\r\n\xc3\x1b%@\xa9" - b"\x1b(U\xda\x1b%Gcaf\xc3\xa9\x1b%@\xbf\x1b%G" + b"\xe2\x80\x9cHi\xe2\x80\x9d" # U+201C/U+201D with 0x80/0x9C/0x9D continuations + b"\xc2\x9b31m!" # UTF-8 U+009B must NOT act as CSI; "31m!" prints literally + b"\r\n\xc3\x1b%@\xa9" # Incomplete UTF-8 flushes U+FFFD, then Latin-1 '©' + b"\x1b(U\xda\x1b%Gcaf\xc3\xa9\x1b%@\xbf\x1b%G" # DOCS charset save/restore ) whole = Terminal(rows=4, cols=30, profile=_switchable_profile()) whole.feed(stream) @@ -237,9 +257,10 @@ def test_encoding_switches_docs_utf8_c1_isolation_and_chunking() -> None: for off in range(0, len(stream), step): chunked.feed(stream[off : off + step]) assert chunked.encoding == whole.encoding - assert chunked.lines == whole.lines + assert chunked.display_lines == whole.display_lines assert chunked.cursor == whole.cursor + # DECSTR preserves wire encoding; RIS restores initial wire encoding. sw = Terminal(rows=2, cols=16, profile=LINUX_CONSOLE_PROFILE) sw.feed(b"\x1b%@\x1b[!p") assert sw.encoding == "latin-1" @@ -266,12 +287,14 @@ def test_feed_str_explicit_in_legacy_encoding_state() -> None: sw.feed_str("ok") assert sw[0].text == "éok" + # Mid-string switch with trailing text raises before feeding trailing UTF-8 bytes. mid = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) with pytest.raises(ValueError, match="latin-1"): mid.feed_str("AB\x1b%@café") assert mid.encoding == "latin-1" assert mid[0].text == "AB" + # Trailing switch with no following text succeeds; split switch also catches text. clean_end = Terminal(rows=2, cols=20, profile=LINUX_CONSOLE_PROFILE) clean_end.feed_str("user@host\x1b%@") assert clean_end.encoding == "latin-1" @@ -282,3 +305,135 @@ def test_feed_str_explicit_in_legacy_encoding_state() -> None: with pytest.raises(ValueError, match="latin-1"): split_sw.feed_str("@café") assert split_sw[0].text == "HI" + + +def test_display_lines_and_row_display_text_wide_and_combining_boundaries() -> None: + """``display_lines`` and ``RowView.display_text`` preserve column width & clips.""" + term = Terminal(rows=4, cols=6) + term.feed_str("e\u0301!\r\nabcd日\r\n🧑‍🌾") + # Row 0: 'e\u0301!' (2 cols + 4 spaces) + # Row 1: 'abcd' + SPACER_HEAD (4 cols + 1 space = 5? Wait: cols=6 -> 'abcd日' fits!) + assert term.display_lines == ( + "e\u0301! ", + "abcd日", + "🧑‍🌾 ", + " ", + ) + for ln in term.display_lines: + assert display_width(ln) == 6 + + # Soft-wrap SPACER_HEAD at odd right boundary (cols=5: 'abcd' -> '日'). + wrap_term = Terminal(rows=3, cols=5) + wrap_term.feed_str("abcd日") + snap = wrap_term.snapshot() + assert snap.display_lines == ( + "abcd ", + "日 ", + " ", + ) + assert [display_width(ln) for ln in snap.display_lines] == [5, 5, 5] + assert snap.screen_lines if hasattr(snap, "screen_lines") else True + assert wrap_term.screen.display_lines == snap.display_lines + + # Exhaustive sub-slice clipping across wide CJK glyphs on a 6-column row "A日本B". + wide_term = Terminal(rows=1, cols=6) + wide_term.feed_str("A日本B") + w_snap = wide_term.snapshot() + assert w_snap.display_lines == ("A日本B",) + assert w_snap[0][1:5].display_text == "日本" + assert w_snap[0][2:5].display_text == " 本" + assert w_snap[0][1:4].display_text == "日 " + assert w_snap[0][2:4].display_text == " " + for c1 in range(7): + for c2 in range(c1, 7): + sub_row = w_snap[0][c1:c2] + sub_reg = w_snap[:, c1:c2] + assert display_width(sub_row.display_text) == c2 - c1 + assert sub_reg.display_lines == (sub_row.display_text,) + + +def test_snapshot_viewport_stateless_history_browsing() -> None: + """``Snapshot.viewport`` pages scrollback without mutating live state.""" + term = Terminal(rows=3, cols=6, scrollback=4) + for idx in range(7): + nl = "\r\n" if idx < 6 else "" + term.feed_str(f"L{idx}{nl}") + # Retained history: L1, L2, L3, L4 (L0 evicted); active viewport: L4? Wait: + # 7 lines on 3-row screen -> 4 scrolled (L0..L3 in history, L4..L6 on screen). + snap = term.snapshot() + assert [r.text for r in snap.history] == ["L0", "L1", "L2", "L3"] + assert snap.viewport(0).lines == ("L4", "L5", "L6") + assert snap.viewport(0).display_lines == ("L4 ", "L5 ", "L6 ") + assert snap.viewport(1).lines == ("L3", "L4", "L5") + assert snap.viewport(2).lines == ("L2", "L3", "L4") + assert snap.viewport(4).lines == ("L0", "L1", "L2") + # Clamping beyond retained history: + assert snap.viewport(99).lines == ("L0", "L1", "L2") + assert (snap.viewport(99).rows, snap.viewport(99).cols) == (3, 6) + + with pytest.raises(ValueError, match="offset must be >= 0"): + snap.viewport(-1) + with pytest.raises(TypeError, match="offset must be int"): + snap.viewport(True) # type: ignore[arg-type] + + # Views stay immutable when the originating terminal mutates, clears, or enters alt. + paged_view = snap.viewport(2) + term.feed(b"\r\nNEW1\r\nNEW2\x1b[3J\x1b[?1049hALT_ONLY") + assert paged_view.display_lines == ("L2 ", "L3 ", "L4 ") + assert snap.viewport(4).lines == ("L0", "L1", "L2") + + # Alternate-screen snapshots never blend primary history into viewport(offset). + alt_term = Terminal(rows=2, cols=8, scrollback=10) + alt_term.feed(b"P0\r\nP1\r\nP2\r\nP3\x1b[?1049hALT0\r\nALT1") + alt_snap = alt_term.snapshot() + assert alt_snap.active_is_alt is True + assert alt_snap.viewport(0).lines == ("ALT0", "ALT1") + assert alt_snap.viewport(3).lines == ("ALT0", "ALT1") + assert alt_snap.viewport(3).display_lines == ("ALT0 ", "ALT1 ") + + # Non-reflow shrink after wide glyph entered history heals right-clipped wide lead. + shrink = Terminal(rows=2, cols=6, scrollback=5) + shrink.feed_str("abcd日本\r\nv0\r\nv1") + # History row 0 was "abcd日" ('日' at cols 4..5); shrink to cols=5 without reflow: + shrink.resize(rows=2, cols=5, reflow=False) + sh_snap = shrink.snapshot() + top_view = sh_snap.viewport(10) + assert (top_view.rows, top_view.cols) == (2, 5) + assert [display_width(ln) for ln in top_view.display_lines] == [5, 5] + assert top_view.display_lines[0] == "abcd " + assert top_view[0, 4].text == " " + + +def test_behavioral_chunking_deltas_and_replies_equivalence() -> None: + """Whole-stream and chunked feeds agree on cells, styles, deltas, and replies.""" + ref = Terminal(rows=4, cols=12) + tok0 = ref.sync_token() + part1 = ( + b"\x1b[38;5;208;4:3mWARN\x1b[0m \xe6\x97\xa5\xe6\x9c\xac\r\n" + b"row1-data\x1b[4G\x1b[2@\x1b[32m++\x1b[0m\r\n" + b"row2" + ) + part2 = b"\x1b[?1049hALT\x1b[?1049l!\x1b[6n\x1b[c" + payload = part1 + part2 + ref.feed(part1) + delta1 = ref.changes_since(tok0) + assert not delta1.full_resync + assert set(delta1.dirty_rows) == {0, 1, 2} + ref.feed(part2) + delta2 = ref.changes_since(delta1.token) + assert delta2.full_resync is True + ref_replies = ref.drain_replies() + assert ref_replies == b"\x1b[3;6R" + DEFAULT_PROFILE.identity.da1 + assert ref[0, 0].style.fg == IndexedColor(208) + assert ref[0, 0].style.underline == UnderlineStyle.CURLY + + for chunk_size in (1, 3, 7): + cand = libvt.Terminal(rows=4, cols=12) + for i in range(0, len(payload), chunk_size): + cand.feed(payload[i : i + chunk_size]) + assert cand.display_lines == ref.display_lines + assert cand.cursor == ref.cursor + assert cand.drain_replies() == ref_replies + for r in range(4): + for c in range(12): + assert cand[r, c] == ref[r, c]