Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/project/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions docs/topics/snapshots.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
104 changes: 104 additions & 0 deletions src/libvt/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -1046,6 +1149,7 @@ def to_dict(self) -> SnapshotDict:


__all__ = [
"CellSpan",
"ResyncReason",
"ScreenDelta",
"Snapshot",
Expand Down
43 changes: 43 additions & 0 deletions tests/test_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Loading
Loading