From 228801e4004eadde87806f9facc0ee7e25bd615c Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 11:13:37 -0600 Subject: [PATCH] snapshot(feat): Locate text by cell coordinates why: String indexing on Snapshot.lines returns code-point offsets instead of display cell columns, so mouse clicks and cell slices miss labels preceded by wide glyphs or multi-codepoint graphemes. what: - Add frozen dataclass libvt.snapshot.CellSpan and Snapshot.find_cells() returning ordered half-open cell spans across complete stored graphemes in the active viewport with explicit str type validation. - Keep CellSpan owned solely in libvt.snapshot with no terminal compatibility re-export. - Add unit, edge-case (wide/grapheme/?2027l/VS16/BCE/cols=1/?2026/CoW), doctest, and real-PTY mouse-click tests in tests/test_terminal.py and tests/test_aio.py. - Document CellSpan and Snapshot.find_cells() in docs/topics/snapshots.md, docs/project/public-api.md, README.md, and CHANGES. Fixes #102 --- CHANGES | 7 ++ README.md | 6 ++ docs/project/public-api.md | 3 +- docs/topics/snapshots.md | 22 +++++ src/libvt/snapshot.py | 104 +++++++++++++++++++++++ tests/test_aio.py | 43 ++++++++++ tests/test_terminal.py | 168 +++++++++++++++++++++++++++++++++++++ 7 files changed, 352 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index 008aad0a..6a51c1f3 100644 --- a/CHANGES +++ b/CHANGES @@ -26,6 +26,13 @@ directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode support queries, and {class}`~libvt.snapshot.SnapshotDict` types the dictionary returned by {meth}`~libvt.snapshot.Snapshot.to_dict`. +#### Find snapshot text by cell coordinates (#133) + +{meth}`~libvt.snapshot.Snapshot.find_cells` returns each visible match as a +{class}`~libvt.snapshot.CellSpan` with a row and a half-open column range. +Use the coordinates to click or inspect labels that include wide or +combined graphemes. + ### Fixes #### Include `examples/` in source distributions (#196) diff --git a/README.md b/README.md index af46dc13..0f266dba 100644 --- a/README.md +++ b/README.md @@ -65,8 +65,13 @@ styles: r0[0..11]: bold fg=green >>> snap.viewport(offset=1).lines ('booting', 'Loading 20%') +>>> snap.find_cells("20%") +(CellSpan(row=0, start=8, stop=11),) ``` +Use [`Snapshot.find_cells()`][find_cells] to turn a visible label into cell +coordinates for a click, highlight, or assertion. + ### Assert screen boxes inline Most unit tests can stop at [`assert_screen_box()`][assert_screen_box], which @@ -214,6 +219,7 @@ guides and API reference are at [libvt.git-pull.com](https://libvt.git-pull.com/ MIT License. See [LICENSE](LICENSE). [feed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.feed +[find_cells]: https://libvt.git-pull.com/topics/snapshots/#locate-text-by-cell-coordinates [committed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.committed [viewport]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot.viewport [assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box diff --git a/docs/project/public-api.md b/docs/project/public-api.md index e5085444..923252f7 100644 --- a/docs/project/public-api.md +++ b/docs/project/public-api.md @@ -25,8 +25,9 @@ Import specialized types and helpers from their owning submodules: - {mod}`libvt.parser`, {mod}`libvt.screen`, {mod}`libvt.views`, {mod}`libvt.snapshot`, {mod}`libvt.format`, {mod}`libvt.recorder`, and {mod}`libvt.terminal` — streaming VT500 parser, screen grids and views, - immutable snapshots and incremental {class}`~libvt.snapshot.SyncToken` / + immutable snapshots, incremental {class}`~libvt.snapshot.SyncToken` / {class}`~libvt.snapshot.ScreenDelta` replicas, + {class}`~libvt.snapshot.CellSpan` coordinates, {class}`~libvt.format.Formatter`, and {class}`~libvt.recorder.TerminalRecorder` - {mod}`libvt.input`, {mod}`libvt.aio`, and {mod}`libvt.codec` — mode-aware input encoders, {class}`~libvt.aio.AsyncSession` transports, and sequence diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index 9314836d..689ee3b0 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -176,6 +176,28 @@ its captured dimensions. A row's `used` extent includes written background-only cells. Its `text_used` extent ends with the text. Both are measured from the start of the row view. +## Locate text by cell coordinates + +Use {meth}`~libvt.snapshot.Snapshot.find_cells` to locate a label in the active +viewport. Each {class}`~libvt.snapshot.CellSpan` gives a zero-based row and a +half-open column range. Use the start column for a +{class}`~libvt.input.MouseEvent`, or slice the snapshot with both columns. + +```python +>>> from libvt import Terminal +>>> from libvt.input import MouseAction, MouseButton, MouseEvent +>>> term = Terminal(rows=2, cols=16) +>>> term.feed("\x1b[?1000;1006h界界界·Go".encode()) +>>> snap = term.committed +>>> (hit,) = snap.find_cells("Go") +>>> hit +CellSpan(row=0, start=7, stop=9) +>>> snap[hit.row, hit.start:hit.stop].text +'Go' +>>> term.encode(MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, hit.start)) +b'\x1b[<0;8;1M' +``` + ## Stateless scrollback paging (`viewport()`) Primary-screen snapshots retain frozen scrollback alongside the active diff --git a/src/libvt/snapshot.py b/src/libvt/snapshot.py index 55b3bafa..efd9c0f9 100644 --- a/src/libvt/snapshot.py +++ b/src/libvt/snapshot.py @@ -465,6 +465,36 @@ def _make_snapshot( return snap +@dataclass(frozen=True, slots=True) +class CellSpan: + """Half-open cell range on one snapshot row. + + Attributes + ---------- + row : int + Zero-based viewport row. + start : int + Inclusive zero-based column. + stop : int + Exclusive zero-based column. + + Examples + -------- + >>> term = Terminal(rows=1, cols=16) + >>> term.feed("界界·Go".encode()) + >>> snap = term.committed + >>> (hit,) = snap.find_cells("Go") + >>> (hit.row, hit.start, hit.stop) + (0, 5, 7) + >>> snap[hit.row, hit.start:hit.stop].text + 'Go' + """ + + row: int + start: int + stop: int + + class Snapshot: r"""Immutable point-in-time capture of terminal screen, history, and metadata. @@ -812,6 +842,79 @@ def viewport(self, offset: int = 0) -> RegionView: out_rows.extend(self._rows[: win_stop - h_len]) return RegionView(out_rows, range(cols), parent_cols=cols, live=False) + def find_cells(self, text: str, /) -> tuple[CellSpan, ...]: + r"""Find exact text matches by cell in the active viewport. + + Return zero-based, half-open spans in row and column order, including + overlaps. An empty tuple means no match. Search each row separately, + including soft-wrapped rows. Matches span complete stored graphemes + without normalization. Wide glyphs occupy two columns. Search skips + wrap spacers and unwritten trailing padding. Explicit trailing spaces + and blanks before later text can match. + + Parameters + ---------- + text : str + Literal text to match within a single row. + + Returns + ------- + tuple[CellSpan, ...] + Matching row and column spans in the active viewport. + + Raises + ------ + TypeError + If *text* is not a :class:`str`. + ValueError + If *text* is empty or contains a carriage return or newline. + + Examples + -------- + >>> term = Terminal(rows=2, cols=16) + >>> term.feed("界界界·Go Go".encode()) + >>> snap = term.committed + >>> snap.find_cells("Go") + (CellSpan(row=0, start=7, stop=9), CellSpan(row=0, start=10, stop=12)) + >>> hit = snap.find_cells("Go")[0] + >>> snap[hit.row, hit.start:hit.stop].text + 'Go' + """ + if not isinstance(text, str): + msg = f"text must be str, got {type(text).__name__}" + raise TypeError(msg) + if not text or "\r" in text or "\n" in text: + msg = "text must be nonempty and contain no carriage returns or newlines" + raise ValueError(msg) + + matches: list[CellSpan] = [] + for row_idx, row in enumerate(self._rows): + line = row.rstrip_text() + at = line.find(text) + if at < 0: + continue + + columns = {0: 0} + col = offset = 0 + limit = row.text_used + while col < limit: + grapheme = row.char_at(col) + if not grapheme: + # Wide continuations are skipped. A wrap spacer ends the row. + break + role = raw_width_bits(row.attr_at(col)) + col += 2 if role == WidthRole.WIDE else 1 + offset += len(grapheme) + columns[offset] = col + + while at >= 0: + end = at + len(text) + if at in columns and end in columns: + matches.append(CellSpan(row_idx, columns[at], columns[end])) + at = line.find(text, at + 1) + + return tuple(matches) + @property def lines(self) -> tuple[str, ...]: r"""Return visible row text with unwritten trailing blank cells omitted. @@ -1046,6 +1149,7 @@ def to_dict(self) -> SnapshotDict: __all__ = [ + "CellSpan", "ResyncReason", "ScreenDelta", "Snapshot", diff --git a/tests/test_aio.py b/tests/test_aio.py index 25a07a4b..8b0cc3d5 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -33,6 +33,7 @@ from libvt.modes import Mode from libvt.parser import ParserState from libvt.pytest_plugin import PtyFactory, TerminalFactory +from libvt.snapshot import CellSpan class _MemoryWriter: @@ -1836,3 +1837,45 @@ async def test_aio_sessions_support_vt_target_and_strided_buffers() -> None: assert isinstance(pty_sess, SupportsVtTarget) await pty_sess.wait_for("PTY_OK", timeout=3.0) assert "│PTY_OK │" in serialize_vt_snapshot(pty_sess) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_snapshot_find_cells_clicks_child_target() -> None: + """The child observes a different selection from a string-index click.""" + child = r""" +import sys + +out = sys.stdout.buffer +out.write("\x1b[?1000;1006h\x1b[2;1H界界e\u0301界·Go".encode()) +for _ in range(2): + packet = bytearray() + while (byte := sys.stdin.buffer.read(1)) != b"M": + if not byte: + raise EOFError("incomplete mouse event") + packet.extend(byte) + button, column, row = map(int, packet.removeprefix(b"\x1b[<").split(b";")) + assert button == 0 + choice = "Ferry" if (row, column) == (2, 9) else "Harbor" + out.write(f"\x1b[3;1HACK {choice} row={row} col={column}\x1b[K\r\nDONE".encode()) +""" + async with open_pty( + (sys.executable, "-u", "-c", child), tty_mode="raw", rows=5, cols=32 + ) as session: + snap = await session.wait_for("Go", timeout=5) + (hit,) = snap.find_cells("Go") + assert hit == CellSpan(1, 8, 10) + + session.send_event( + MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, hit.start) + ) + selected = await session.wait_for( + lambda view: view.lines[2].startswith("ACK ") and view.lines[3] == "DONE", + timeout=5, + ) + assert selected.lines[2] == "ACK Ferry row=2 col=9" + + text_index = snap.lines[hit.row].index("Go") + session.send_event( + MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, text_index) + ) + await session.wait_for("ACK Harbor row=2 col=7", timeout=5) diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 1940ac9f..470fee43 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -49,6 +49,7 @@ find_flight_recorder, ) from libvt.screen import CursorShape, RowView, Screen, ScrollRegion, format_rows_text +from libvt.snapshot import CellSpan from libvt.style import AnsiColor, Hyperlink from libvt.terminal import ( Formatter, @@ -2378,3 +2379,170 @@ def test_snapshot_rejects_attribute_deletion_and_keeps_cached_frames_intact() -> delattr(delta, "dirty_rows") assert delta.snapshot is term.snapshot() assert copy.copy(delta) == delta + + +@pytest.mark.parametrize("chunk_size", [0, 1]) +def test_snapshot_find_cells_matches_complete_graphemes_and_overlaps( + chunk_size: int, +) -> None: + """Search the captured rows in order, with offsets at cell boundaries.""" + + def feed(term: libvt.Terminal, data: bytes) -> None: + if chunk_size == 0: + term.feed(data) + return + for idx in range(0, len(data), chunk_size): + term.feed(data[idx : idx + chunk_size]) + + term = libvt.Terminal(rows=3, cols=12) + feed( + term, + ("界界界\r\ne\u0301👩\u200d🚀\x1b[1;32mGo\x1b[0m Go\r\nGo").encode(), + ) + snap = term.committed + assert snap.lines == ("界界界", "e\u0301👩\u200d🚀Go Go", "Go") + assert (snap.cursor.row, snap.cursor.col) == (2, 2) + assert [snap[r].wrapped for r in range(snap.rows)] == [False, False, False] + + hits = snap.find_cells("界界") + expected_go = (CellSpan(1, 3, 5), CellSpan(1, 6, 8), CellSpan(2, 0, 2)) + assert hits == (CellSpan(0, 0, 4), CellSpan(0, 2, 6)) + assert all(isinstance(hit, CellSpan) and not isinstance(hit, tuple) for hit in hits) + assert snap.find_cells("Go") == expected_go + assert snap.find_cells("e\u0301👩\u200d🚀") == (CellSpan(1, 0, 3),) + + # Slicing with a CellSpan preserves exact text and style spans. + first_go = expected_go[0] + sliced = snap[first_go.row, first_go.start : first_go.stop] + assert sliced.text == "Go" + assert [ + (r.start_col, r.end_col, r.style.bold, r.style.fg) for r in sliced[0].runs + ] == [ + (3, 5, True, AnsiColor.GREEN), + ] + + # CellSpan is frozen, hashable, copyable, and picklable; owned in libvt.snapshot. + assert not hasattr(libvt.terminal, "CellSpan") + assert copy.copy(first_go) == first_go + assert copy.deepcopy(first_go) == first_go + assert pickle.loads(pickle.dumps(first_go)) == first_go + assert hash(first_go) == hash(CellSpan(1, 3, 5)) + with pytest.raises(AttributeError): + first_go.start = 0 # ty: ignore[invalid-assignment] + with pytest.raises(AttributeError): + del first_go.start # ty: ignore[invalid-assignment] + + for text in ("e", "\u0301", "é", "👩", "🚀", "界e", "missing"): + assert snap.find_cells(text) == () + for text in ("", "Go\nGo", "Go\rGo"): + with pytest.raises(ValueError, match="nonempty"): + snap.find_cells(text) + for bad in (b"", b"Go", None, 123): + with pytest.raises(TypeError, match="text must be str"): + snap.find_cells(bad) # ty: ignore[invalid-argument-type] + + # CoW isolation: mutating the live terminal leaves captured spans intact. + term.feed(b"\x1b[2J") + assert term.committed.find_cells("Go") == () + assert snap.find_cells("Go") == expected_go + + # ?2027h vs ?2027l, VS16/VS15, Regional Indicator flags, and ambiguous_width=2. + uni_term = libvt.Terminal( + rows=2, + cols=16, + profile=Profile(unicode=UnicodeBehavior(ambiguous_width=2)), + ) + feed(uni_term, "\x1b[?2027h🇺🇸❤️❤\ufe0eΩGo".encode()) + uni_snap = uni_term.committed + assert uni_snap.find_cells("🇺🇸") == (CellSpan(0, 0, 2),) + assert uni_snap.find_cells("🇺") == () + assert uni_snap.find_cells("❤️") == (CellSpan(0, 2, 4),) + assert uni_snap.find_cells("❤\ufe0e") == (CellSpan(0, 4, 5),) + assert uni_snap.find_cells("Ω") == (CellSpan(0, 5, 7),) + assert uni_snap.find_cells("Go") == (CellSpan(0, 7, 9),) + + legacy_term = libvt.Terminal(rows=1, cols=16) + feed(legacy_term, "\x1b[?2027le\u0301👩\u200d🚀Go".encode()) + legacy_snap = legacy_term.committed + assert legacy_snap.find_cells("e\u0301") == (CellSpan(0, 0, 1),) + assert legacy_snap.find_cells("👩") == (CellSpan(0, 1, 3),) + assert legacy_snap.find_cells("🚀") == (CellSpan(0, 3, 5),) + assert legacy_snap.find_cells("Go") == (CellSpan(0, 5, 7),) + + # Sibling Screen.snapshot() supports find_cells with CoW isolation. + scr = Screen(rows=1, cols=12) + scr.put_text(0, 0, "界Go") + scr_snap = scr.snapshot() + scr.put_text(0, 0, " ") + assert scr_snap.find_cells("Go") == (CellSpan(0, 2, 4),) + assert scr.snapshot().find_cells("Go") == () + + +def test_snapshot_find_cells_excludes_padding_sync_hold_bce_and_narrow_edges() -> None: + """Search written extents across wraps, cols=1, BCE, ?2026 hold, and scrollback.""" + term = libvt.Terminal(rows=2, cols=4) + term.feed("abc界 ".encode()) + snap = term.committed + assert snap.lines == ("abc", "界 ") + assert (snap[0].wrapped, snap[1].wrapped) == (True, False) + assert snap[0, 3].width_role is WidthRole.SPACER_HEAD + assert snap.find_cells("abc") == (CellSpan(0, 0, 3),) + assert snap.find_cells("c") == (CellSpan(0, 2, 3),) + assert snap.find_cells(" ") == (CellSpan(1, 2, 3),) + assert snap.find_cells("界 ") == (CellSpan(1, 0, 3),) + assert snap.find_cells("c界") == () + + # Overwriting a wide glyph's SPACER_TAIL heals column 0 to a narrow space. + heal = libvt.Terminal(rows=1, cols=4) + heal.feed("界a\x1b[1;2Hx".encode()) + heal_snap = heal.committed + assert heal_snap.lines == (" xa",) + assert heal_snap.find_cells(" x") == (CellSpan(0, 0, 2),) + assert heal_snap.find_cells("界") == () + + # cols=1 positive hit and unplaceable wide replacement (U+FFFD). + one_col = libvt.Terminal(rows=2, cols=1) + one_col.feed("a\r\n界".encode()) + one_snap = one_col.committed + assert one_snap.lines == ("a", "\ufffd") + assert one_snap.find_cells("a") == (CellSpan(0, 0, 1),) + assert one_snap.find_cells("\ufffd") == (CellSpan(1, 0, 1),) + assert one_snap.find_cells("界") == () + + # ?7l (no autowrap) wide glyph at cols - 1 writes U+FFFD at the last cell. + nowrap = libvt.Terminal(rows=1, cols=3) + nowrap.feed("\x1b[?7lab界".encode()) + nowrap_snap = nowrap.committed + assert nowrap_snap.lines == ("ab\ufffd",) + assert nowrap_snap.find_cells("\ufffd") == (CellSpan(0, 2, 3),) + + # Non-reflow shrink to cols=1 removes row-1 wide glyph cleanly. + term.resize(rows=2, cols=1, reflow=False) + shrunk = term.committed + assert shrunk.find_cells("a") == (CellSpan(0, 0, 1),) + assert shrunk.find_cells("界") == () + assert shrunk.find_cells(" ") == () + + # BCE styled blank row (used > 0, text_used == 0) and trailing BCE padding. + bce = libvt.Terminal(rows=2, cols=8) + bce.feed(b"past\r\n\x1b[41m\x1b[2K\r\n\x1b[3GGo\x1b[41m\x1b[K") + bce_snap = bce.committed + assert bce_snap.history[0].text == "past" + assert (bce_snap[0].used, bce_snap[0].text_used) == (8, 0) + assert (bce_snap[1].used, bce_snap[1].text_used) == (8, 4) + assert bce_snap.find_cells("past") == () + assert bce_snap.find_cells(" ") == (CellSpan(1, 0, 1), CellSpan(1, 1, 2)) + assert bce_snap.find_cells(" Go") == (CellSpan(1, 0, 4),) + assert bce_snap.find_cells("Go ") == () + + # ?2026 synchronized hold isolates committed vs working snapshots. + sync = libvt.Terminal(rows=1, cols=12) + sync.feed("界Old".encode()) + sync.feed("\x1b[?2026h\x1b[2K\r界New".encode()) + assert sync.committed.find_cells("Old") == (CellSpan(0, 2, 5),) + assert sync.committed.find_cells("New") == () + assert sync.snapshot().find_cells("New") == (CellSpan(0, 2, 5),) + assert sync.snapshot().find_cells("Old") == () + sync.feed(b"\x1b[?2026l") + assert sync.committed.find_cells("New") == (CellSpan(0, 2, 5),) + assert sync.committed.find_cells("Old") == ()