From b61cee5ea3c3887fac4955b6fc2ec741feee9ef5 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:14:28 -0600 Subject: [PATCH 1/3] screen(fix[row]): Track live row width why: A live row can retain stale indices after its screen width changes. what: - Use current bounds for live row length, indexing and rendering. - Clip selected columns for retained slices. - Cover shrink, growth, and independently frozen rows. Fixes #100 --- src/libvt/screen.py | 67 ++++++++++++++++++++++++++------------------ tests/test_screen.py | 60 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 27 deletions(-) diff --git a/src/libvt/screen.py b/src/libvt/screen.py index e0a8e1f2..0c54640d 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -410,6 +410,10 @@ def _format_display_row(row: RowLike, start_c: int, stop_c: int) -> str: 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) @@ -432,14 +436,21 @@ def __init__( self._row = row self._screen = screen self._row_idx = row_idx - total_cols = screen.cols if screen is not None else row.cols - self._col_range = range(total_cols) if col_range is None else col_range + 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 wrapped(self) -> bool: """Return ``True`` when this row soft-wrapped onto the next line.""" @@ -449,34 +460,37 @@ def wrapped(self) -> bool: 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 self._col_range.start == 0 and self._col_range.stop >= row_t_used: + if cols.start == 0 and cols.stop >= row_t_used: return row.rstrip_text() - limit = min(self._col_range.stop, row_t_used) - if limit <= self._col_range.start: + limit = min(cols.stop, row_t_used) + if limit <= cols.start: return "" if isinstance(row, _Row): - raw = row.slice_text(self._col_range.start, limit) + raw = row.slice_text(cols.start, limit) else: - raw = "".join(row.char_at(c) for c in range(self._col_range.start, limit)) + 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() - return _format_display_row(row, self._col_range.start, self._col_range.stop) + 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() - limit = min(self._col_range.stop, row.used) - start_c = self._col_range.start + cols = self._columns_for(row) + limit = min(cols.stop, row.used) + start_c = cols.start if limit <= start_c: return () if isinstance(row, FrozenRow): @@ -527,7 +541,7 @@ def runs(self) -> tuple[RowRun, ...]: def __len__(self) -> int: """Return column count in this view.""" - return len(self._col_range) + return len(self._columns_for(self._current_row())) @t.overload def __getitem__(self, index: int) -> Cell: ... @@ -538,17 +552,18 @@ 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(self._col_range)) - base = self._col_range.start + 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(self._col_range), axis="col") - return _materialize_cell(row, self._col_range.start + norm) + 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.""" @@ -556,20 +571,18 @@ def __eq__(self, other: object) -> bool: return True if not isinstance(other, RowView): return NotImplemented - if len(self._col_range) != len(other._col_range): - return False r1 = self._current_row() r2 = other._current_row() - if r1 is r2 and self._col_range == other._col_range: + 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 ( - self._col_range == other._col_range - and self._col_range.start == 0 - and self._col_range.step == 1 - ): + 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 self._col_range.stop >= max(f1.used, f2.used): + if c1.stop >= max(f1.used, f2.used): return _frozen_content_key(f1) == _frozen_content_key(f2) if r1.wrapped != r2.wrapped: return False @@ -599,9 +612,9 @@ def _row_view_to_full_frozen(value: object) -> tuple[int, FrozenRow] | None: return None r = value._current_row() fr = r.freeze() if isinstance(r, _Row) else r - v_cols = len(value._col_range) - if value._col_range.start == 0 and value._col_range.step == 1 and v_cols >= fr.used: - return v_cols, fr + cols = value._columns_for(r) + if cols.start == 0 and cols.step == 1 and len(cols) >= fr.used: + return len(cols), fr return None diff --git a/tests/test_screen.py b/tests/test_screen.py index a3b95b3c..97564304 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -245,6 +245,66 @@ def test_resize_active_geometry_invalidates_grapheme_anchor() -> None: assert (term.cols, term[0, 0].text, term.cursor.col) == (8, "e", 1) +def test_retained_live_row_follows_current_columns() -> None: + """Keep full, sliced, and frozen row widths consistent after resizing.""" + term = libvt.Terminal(rows=2, cols=6) + term.feed(b"b\x1b[31mana\x1b[0mna") + live = term[0] + part = live[1:5] + tail = term.screen[0][4:6] + frozen = term.committed[0] + + term.resize(rows=2, cols=3, reflow=False) + assert len(live) == len(tuple(live)) == 3 + assert live == term[0] + assert live[-1].text == "n" + assert live.display_text == "ban" + assert part == live[1:] + assert (len(part), part.display_text, part[-1].text) == (2, "an", "n") + assert [(run.start_col, run.end_col, run.style.fg) for run in part.runs] == [ + (1, 3, AnsiColor.RED), + ] + assert len(tail) == 0 + assert tail.display_text == "" + with pytest.raises(IndexError): + _ = live[3] + with pytest.raises(IndexError): + _ = part[-3] + + term.resize(rows=2, cols=8, reflow=False) + assert len(live) == len(tuple(live)) == 8 + assert live.display_text == "ban " + assert live[7].text == " " + assert part.display_text == "an " + assert tail.display_text == " " + assert (len(frozen), frozen.display_text) == (6, "banana") + assert frozen[3].style.fg == AnsiColor.RED + + +def test_row_from_live_region_clips_to_its_backing_width() -> None: + """Keep a region's mutable row indexable after shrinking the grid.""" + term = libvt.Terminal(rows=2, cols=6) + term.feed_str("ab界cd") + region = term[:, :] + row = region[0] + tail = region[:1][0][1:] + frozen = term.committed[:, :][0] + + term.resize(rows=2, cols=3, reflow=False) + assert len(row) == len(tuple(row)) == len(term[0]) == 3 + assert row.display_text == "ab " + assert row[-3].text == "a" + assert row[2].text == row[-1].text == " " + assert row[1:] == tail == term[0][1:] + assert tail.display_text == "b " + with pytest.raises(IndexError): + _ = row[3] + with pytest.raises(IndexError): + _ = row[-4] + assert len(frozen) == 6 + assert frozen.display_text == "ab界cd" + + def test_row_wide_healing_decslrm_scroll_and_rle_history() -> None: """``SPACER_HEAD`` heals on edit, ``DECSLRM`` scrolls, and ``FrozenRow`` packs.""" narrow_term = libvt.Terminal(rows=3, cols=4) From 1a48f0f1092f7010eadba6e82eb22a626f325e7c Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:49:46 -0600 Subject: [PATCH 2/3] CHANGES(docs): Describe retained row dimensions why: A caller can keep a live row or a slice while the screen changes width. what: - Explain current live-row bounds and the captured bounds of frozen rows. --- CHANGES | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES b/CHANGES index c7c77900..de33aa79 100644 --- a/CHANGES +++ b/CHANGES @@ -106,6 +106,12 @@ Pass a sliced, reversed, or multidimensional `memoryview` to the parser, terminal, recorder, explainer, PTY writes, or `tmux` control-mode helpers. Each reads the logical bytes. Step offsets count those bytes. +#### Keep retained live rows indexable across resizes (#183) + +{class}`~libvt.screen.RowView` uses the current width for a live row's +length, indexing, and rendering. Retained slices clip their selected columns +to the current width. Frozen rows keep their captured dimensions. + ### Documentation #### Assert effective colors alongside screen goldens (#190) From 47fcaac443e71129272d5f86fbd97c30594053d6 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 07:28:05 -0600 Subject: [PATCH 3/3] screen(fix): Keep nested regions in bounds why: A second crop should use its parent's coordinates after a resize. what: - Share two-axis indexing across screens, snapshots, and regions. - Clip live regions to retained rows and preserve captured extents. - Expose row extents, source row, and screen/snapshot read properties. - Serialize and blit through the read model instead of private fields. - Document nested cropping and cover live and frozen regions in tests. --- CHANGES | 16 ++++ docs/topics/snapshots.md | 22 +++++ src/libvt/screen.py | 173 ++++++++++++++++++++++++++++----------- src/libvt/terminal.py | 9 +- src/libvt/testing.py | 70 +++++++--------- tests/test_screen.py | 59 ++++++++++++- tests/test_testing.py | 8 ++ 7 files changed, 265 insertions(+), 92 deletions(-) diff --git a/CHANGES b/CHANGES index de33aa79..44a42989 100644 --- a/CHANGES +++ b/CHANGES @@ -112,6 +112,22 @@ Each reads the logical bytes. Step offsets count those bytes. length, indexing, and rendering. Retained slices clip their selected columns to the current width. Frozen rows keep their captured dimensions. +#### Keep retained live rows and nested regions in bounds (#183) + +{class}`~libvt.screen.RowView` uses the current width for a live row's +length, indexing, and rendering. Retained slices clip their selected columns +to the current width. Frozen rows keep their captured dimensions. + +{class}`~libvt.screen.RegionView` accepts two-axis nested indexing in its own +coordinates, clipping live regions to their retained rows after a resize and +preserving captured dimensions for snapshot regions. Public read-model +properties now cover {attr}`~libvt.screen.RegionView.columns`, +{attr}`~libvt.screen.RowView.columns`, {attr}`~libvt.screen.RowView.used`, +{attr}`~libvt.screen.RowView.text_used`, +{attr}`~libvt.screen.RowView.full_row`, {attr}`~libvt.screen.Screen.profile`, +{attr}`~libvt.screen.Screen.is_alt`, and +{attr}`~libvt.terminal.Snapshot.profile`. + ### Documentation #### Assert effective colors alongside screen goldens (#190) diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index 4e934dbe..6897afc2 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -145,6 +145,28 @@ styles: r0[0..2]: bold fg=green ``` +### Crop a region again + +A region accepts the same row and column indices as its source. Nested indices +are relative to the crop. Read `columns` to locate it in the source grid. A +live region clips to its retained rows after a resize. A snapshot region keeps +its captured dimensions. + +```python +>>> from libvt import Terminal +>>> term = Terminal(rows=2, cols=6) +>>> term.feed(b"ABCDEF\r\nghijkl") +>>> outer = term.committed[:, 1:5] +>>> inner = outer[:, 1:-1] +>>> inner.display_lines, inner.columns +(('CD', 'ij'), range(2, 4)) +>>> inner[0].full_row.text +'ABCDEF' +``` + +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. + ## Stateless scrollback paging (`viewport()`) Primary-screen snapshots retain frozen scrollback alongside the active diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 0c54640d..0bcf79ad 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -451,6 +451,32 @@ def _columns_for(self, row: RowLike) -> range: 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.""" @@ -801,6 +827,9 @@ def __repr__(self) -> str: 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 @@ -817,13 +846,39 @@ class RegionView(collections.abc.Sequence[RowView]): r0[0..6]: bold """ - __slots__ = ("_col_range", "_rows") + __slots__ = ("_col_range", "_live_rows", "_parent_cols", "_rows") def __init__( - self, rows: collections.abc.Sequence[RowLike], col_range: range + 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: @@ -833,19 +888,17 @@ def rows(self) -> int: @property def cols(self) -> int: """Return width of this region in columns.""" - return len(self._col_range) + return len(self.columns) @property 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) + 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.""" - 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) + return tuple(row.display_text for row in self) @property def text(self) -> str: @@ -855,6 +908,11 @@ def text(self) -> str: lines.pop() return "\n".join(lines) + 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) @@ -863,26 +921,32 @@ def __len__(self) -> int: def __getitem__(self, key: int) -> RowView: ... @t.overload - def __getitem__(self, key: slice) -> RegionView: ... + def __getitem__(self, key: tuple[int, int]) -> Cell: ... @t.overload - def __getitem__(self, key: tuple[int, int]) -> Cell: ... + 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[int, int], - ) -> RowView | RegionView | Cell: - """Index a row, sub-region, or ``(row, col)`` cell within this region.""" - if isinstance(key, tuple): - r_idx, c_idx = key - nr = _normalize_index(r_idx, len(self._rows), axis="row") - nc = _normalize_index(c_idx, len(self._col_range), axis="col") - return _materialize_cell(self._rows[nr], self._col_range.start + nc) - if isinstance(key, slice): - sub = _slice_indices(key, len(self._rows)) - return RegionView(self._rows[sub.start : sub.stop], self._col_range) - nr = _normalize_index(key, len(self._rows), axis="row") - return RowView(self._rows[nr], self._col_range) + 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 format_rows_text(rows: collections.abc.Sequence[RowLike]) -> str: @@ -893,41 +957,45 @@ def format_rows_text(rows: collections.abc.Sequence[RowLike]) -> str: 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: - """Implement ``grid[r]``, ``grid[r, c]``, and ``grid[r1:r2, c1:c2]``.""" + """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], screen=screen, row_idx=nr) - if isinstance(key, slice): - r_range = _slice_indices(key, height) - return RegionView(rows[r_range.start : r_range.stop], range(cols)) - - r_key, c_key = key + 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, cols, axis="col") - return _materialize_cell(rows[nr], nc) - if isinstance(r_key, int) and isinstance(c_key, slice): - nr = _normalize_index(r_key, height, axis="row") - c_range = _slice_indices(c_key, cols) - return RegionView((rows[nr],), c_range) - if isinstance(r_key, slice) and isinstance(c_key, int): - r_range = _slice_indices(r_key, height) - nc = _normalize_index(c_key, cols, axis="col") - return RegionView(rows[r_range.start : r_range.stop], range(nc, nc + 1)) - if isinstance(r_key, slice) and isinstance(c_key, slice): - r_range = _slice_indices(r_key, height) - c_range = _slice_indices(c_key, cols) - return RegionView(rows[r_range.start : r_range.stop], c_range) - msg = f"unsupported grid index {key!r}" - raise TypeError(msg) + 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, + ) class Screen: @@ -1034,6 +1102,16 @@ 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.""" @@ -1999,8 +2077,9 @@ def blit( src_cols = source._cols elif isinstance(source, RegionView): src_rows = source._rows - src_col_base = source._col_range.start - src_cols = len(source._col_range) + cols_range = source.columns + src_col_base = cols_range.start + src_cols = len(cols_range) else: from libvt.terminal import Snapshot as _Snapshot diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 128e48a3..eb7281b5 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -809,6 +809,11 @@ def __setattr__(self, name: str, value: object) -> None: 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. @@ -997,7 +1002,7 @@ def viewport(self, offset: int = 0) -> RegionView: raise ValueError(msg) cols = self._cols if self.active_is_alt or offset == 0 or not self._history: - return RegionView(self._rows, range(cols)) + 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) @@ -1017,7 +1022,7 @@ def viewport(self, offset: int = 0) -> RegionView: out_rows.append(fr) if win_stop > h_len: out_rows.extend(self._rows[: win_stop - h_len]) - return RegionView(out_rows, range(cols)) + return RegionView(out_rows, range(cols), parent_cols=cols, live=False) @property def lines(self) -> tuple[str, ...]: diff --git a/src/libvt/testing.py b/src/libvt/testing.py index e1bbf073..b04c593c 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -9,7 +9,6 @@ import typing as t from dataclasses import dataclass -from libvt._grid import raw_width_bits from libvt._ucd import ( WidthRole, display_width, @@ -35,34 +34,22 @@ from libvt.contrib.tmux.capture import TmuxCaptureResult -def _format_row_cells(snap: Snapshot, row_idx: int, width: int) -> str: - row = snap._rows[row_idx] - parts: list[str] = [] - cols_used = 0 - c = 0 - limit = min(width, snap.cols) - while c < limit and cols_used < width: - word = row.attr_at(c) - rb = raw_width_bits(word) - if rb == int(WidthRole.SPACER_TAIL): - c += 1 - continue - if rb == int(WidthRole.SPACER_HEAD): - parts.append(" ") - cols_used += 1 - c += 1 - continue - cell_w = 2 if rb == int(WidthRole.WIDE) else 1 - if cols_used + cell_w > width: - parts.append(" ") - cols_used += 1 - break - parts.append(sanitize_terminal_text(row.char_at(c))) - cols_used += cell_w - c += 1 - if cols_used < width: - parts.append(" " * (width - cols_used)) - return "".join(parts) +def _box_row_cells(row: RowView) -> list[str]: + """Project the row slice as one string per captured column.""" + cells: list[str] = [] + width = len(row) + for col in range(row.used): + cell = row[col] + if cell.width_role == WidthRole.SPACER_TAIL: + cells.append(" " if col == 0 else "") + elif cell.width_role == WidthRole.SPACER_HEAD or ( + cell.width_role == WidthRole.WIDE and col + 1 == width + ): + cells.append(" ") + else: + cells.append(sanitize_terminal_text(cell.text)) + cells.extend([" "] * (width - len(cells))) + return cells def _pad_expected_line( @@ -150,8 +137,8 @@ def format_screen_box( border_h = "─" * w out = [f"┌{border_h}┐"] for r in range(h): - content = _format_row_cells(snap, r, w) - wrap_mark = "W" if snap._rows[r].wrapped else "" + content = "".join(_box_row_cells(snap[r][:w])) + wrap_mark = "W" if snap[r].wrapped else "" out.append(f"│{content}│{wrap_mark}") out.append(f"└{border_h}┘") return "\n".join(out) @@ -266,7 +253,7 @@ def assert_screen( return preview_rows = min(snap.rows, max(len(exp_lines), len(act_lines), 1)) - prof = target.profile if isinstance(target, Terminal) else snap._profile + prof = snap.profile mode_2027 = Mode.GRAPHEME_CLUSTERING in snap.modes max_exp_w = max( (display_width(x, mode_2027=mode_2027, profile=prof) for x in exp_lines), @@ -362,7 +349,7 @@ def assert_screen_box( raise ValueError(msg) snap = target.snapshot() if isinstance(target, Terminal) else target - prof = target.profile if isinstance(target, Terminal) else snap._profile + prof = snap.profile mode_2027 = Mode.GRAPHEME_CLUSTERING in snap.modes norm_lines = [top] @@ -934,10 +921,8 @@ def _slice_extracted( return extracted view, unexposed = extracted r0, r1, c0, c1 = region - if isinstance(view, (Snapshot, Screen)): + if isinstance(view, (Snapshot, Screen, RegionView)): return view[r0:r1, c0:c1], unexposed - if isinstance(view, RegionView): - return RegionView(view._rows[r0:r1], view._col_range[c0:c1]), unexposed return extracted @@ -1068,9 +1053,10 @@ def _serialize_extracted( compiled = _compile_scrubbers(scrubbers) if isinstance(view, RegionView): + cols_n = view.cols box, style_lines, _ = _render_fixed_rows( - [view[r] for r in range(view.rows)], - cols_n=view.cols, + view, + cols_n=cols_n, compiled=compiled, cur_row=None, cur_col=0, @@ -1079,22 +1065,22 @@ def _serialize_extracted( mode_2027=True, profile=DEFAULT_PROFILE, ) - out = f"size={view.cols}x{view.rows} region=True\n{box}" + out = f"size={cols_n}x{view.rows} region=True\n{box}" return f"{out}\nstyles:\n" + "\n".join(style_lines) if style_lines else out if isinstance(view, Screen): - rows_n, cols_n, alt = view.rows, view.cols, view._is_alt + rows_n, cols_n, alt = view.rows, view.cols, view.is_alt cur_row, cur_col = view.cursor.row, view.cursor.col cur_vis, cur_shape = view.cursor.visible, view.cursor.shape modes_set: frozenset[Mode] = frozenset({Mode.DECAWM, Mode.GRAPHEME_CLUSTERING}) - profile = DEFAULT_PROFILE + profile = view.profile else: assert isinstance(view, Snapshot) rows_n, cols_n, alt = view.rows, view.cols, view.active_is_alt cur_row, cur_col = view.cursor.row, view.cursor.col cur_vis, cur_shape = view.cursor.visible, view.cursor.shape modes_set = view.modes - profile = view._profile + profile = view.profile vp_rows = [view[r] for r in range(rows_n)] hist_rows = list(view.history) if not alt else [] diff --git a/tests/test_screen.py b/tests/test_screen.py index 97564304..7e9b3597 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -12,7 +12,7 @@ import pytest import libvt -from libvt._grid import raw_width_bits +from libvt._grid import _Row, raw_width_bits from libvt._ucd import WidthRole from libvt.config import DEFAULT_PROFILE, Profile, ScreenBehavior, UnicodeBehavior from libvt.events import InBandResize @@ -281,6 +281,35 @@ def test_retained_live_row_follows_current_columns() -> None: assert frozen[3].style.fg == AnsiColor.RED +def test_nested_region_slices_preserve_coordinates_and_styles() -> None: + """A nested rectangle indexes cells relative to its parent crop.""" + term = libvt.Terminal(rows=3, cols=6) + term.feed(b"A\x1b[31mBCD\x1b[0mEF\r\nghijkl\r\nmnopqr") + frame = term.committed + outer = frame[:, 1:5] + inner = outer[:2, 1:-1] + + assert inner.display_lines == ("CD", "ij") + assert inner[0, 0] == frame[0, 2] + assert outer[-1, 1:3].display_lines == ("op",) + assert outer[:2, -1].display_lines == ("E", "k") + assert outer[1:2, 1:1].cols == 0 + assert outer[1:1, :].rows == 0 + assert inner.columns == inner[0].columns == range(2, 4) + assert inner[0].full_row == frame[0] + assert (inner[0].used, inner[0].text_used) == (2, 2) + term.feed(b"\r\nnew") + assert inner.display_lines == ("CD", "ij") + with pytest.raises(ValueError, match="step=1"): + _ = outer[:, ::2] + + term.feed(b"\x1b[44m\x1b[2K") + background = term.screen[-1, 1:4][0] + assert (background.used, background.text_used) == (3, 0) + assert term.screen.profile is term.committed.profile is term.profile + assert term.screen.is_alt == term.committed.active_is_alt + + def test_row_from_live_region_clips_to_its_backing_width() -> None: """Keep a region's mutable row indexable after shrinking the grid.""" term = libvt.Terminal(rows=2, cols=6) @@ -297,6 +326,16 @@ def test_row_from_live_region_clips_to_its_backing_width() -> None: assert row[2].text == row[-1].text == " " assert row[1:] == tail == term[0][1:] assert tail.display_text == "b " + assert region[0, -1] == row[-1] + assert region[:, -2].display_lines == ("b", " ") + assert region.columns == row.columns == range(3) + assert region.display_lines == ("ab ", " ") + dst = Screen(rows=2, cols=6) + dst.put_text(0, 0, "XXXXXX") + dst.blit(region) + assert dst[0].text == "ab XXX" + with pytest.raises(IndexError, match="col index 3 out of range for size 3"): + _ = region[0, 3] with pytest.raises(IndexError): _ = row[3] with pytest.raises(IndexError): @@ -305,6 +344,24 @@ def test_row_from_live_region_clips_to_its_backing_width() -> None: assert frozen.display_text == "ab界cd" +def test_snapshot_region_shape_uses_frame_geometry( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Reading captured coordinates does not consult individual row widths.""" + term = libvt.Terminal(rows=2, cols=6) + term.feed(b"one\r\ntwo\r\nthree") + snapshot = term.committed + + def read_row_width(_row: _Row) -> int: + pytest.fail("captured geometry read a backing row's width") + + with monkeypatch.context() as patch: + patch.setattr(_Row, "cols", property(read_row_width)) + for region in (snapshot[:, :], snapshot.viewport(), snapshot.viewport(1)): + assert region.columns == range(6) + assert region[:, 1:4].cols == 3 + + def test_row_wide_healing_decslrm_scroll_and_rle_history() -> None: """``SPACER_HEAD`` heals on edit, ``DECSLRM`` scrolls, and ``FrozenRow`` packs.""" narrow_term = libvt.Terminal(rows=3, cols=4) diff --git a/tests/test_testing.py b/tests/test_testing.py index fa5c19a5..70db28a5 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -266,6 +266,14 @@ def test_vt_screen_styles_region_sync_hold_cjk_and_errors() -> None: assert "region=True" in region_str assert "│LINK │" in region_str + t_crop = Terminal(rows=2, cols=6) + t_crop.feed(b"ABCDEF\r\nghijkl") + live_outer = t_crop[:, 1:5] + t_crop.resize(rows=2, cols=3, reflow=False) + nested_str = serialize_vt_snapshot(vt_screen(live_outer, region=(0, 2, 1, 3))) + assert "size=1x2 region=True" in nested_str + assert "│C│\n│i│" in nested_str + t_prev = Terminal(rows=2, cols=14) t_prev.feed(b"Menu: [A] B") t_next = Terminal(rows=2, cols=14)