diff --git a/CHANGES b/CHANGES index 008aad0a..3760e3df 100644 --- a/CHANGES +++ b/CHANGES @@ -28,6 +28,16 @@ returned by {meth}`~libvt.snapshot.Snapshot.to_dict`. ### Fixes +#### Keep retained live regions aligned across scroll and reflow (#197) + +A live {class}`~libvt.views.RegionView` and its nested crops resolve viewport +coordinates from the live {class}`~libvt.screen.Screen` on each read, clipping +to current dimensions after scrolls, reflows, and resizes. Live +{class}`~libvt.views.RowView` instances track their viewport row coordinate and +read as empty while out of bounds after a vertical shrink, while regions from a +{class}`~libvt.snapshot.Snapshot` or {meth}`~libvt.snapshot.Snapshot.viewport` +keep their captured rows. + #### Include `examples/` in source distributions (#196) `pyproject.toml` source distribution builds include `examples/` files diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index 9314836d..e09c659e 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -158,8 +158,10 @@ styles: 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. +live region resolves its selected viewport coordinates from the live screen on +each read, staying aligned across scrolls, reflows, and resizes while clipping +to the current dimensions. A snapshot region keeps its captured rows and +dimensions. ```python >>> from libvt import Terminal @@ -173,6 +175,23 @@ its captured dimensions. 'ABCDEF' ``` +Retaining a live region alongside a snapshot region shows how each behaves +across scrolling and reflow: + +```python +>>> from libvt import Terminal +>>> term = Terminal(rows=2, cols=6) +>>> term.feed(b"012345\r\nabcdef") +>>> live = term[:, 1:5] +>>> frozen = term.committed[:, 1:5] +>>> term.feed(b"\r\nghijkl") +>>> live.lines, frozen.lines +(('bcde', 'hijk'), ('1234', 'bcde')) +>>> term.resize(rows=2, cols=4, reflow=True) +>>> live.lines, live.columns, frozen.lines +(('hij', 'l'), range(1, 4), ('1234', 'bcde')) +``` + 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. diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 1485a7b8..431a2324 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -919,7 +919,7 @@ def blit( src_col_base = 0 src_cols = source._cols elif isinstance(source, RegionView): - src_rows = source._rows + src_rows = source._current_rows() cols_range = source.columns src_col_base = cols_range.start src_cols = len(cols_range) diff --git a/src/libvt/views.py b/src/libvt/views.py index a1c0c20c..eabc9d05 100644 --- a/src/libvt/views.py +++ b/src/libvt/views.py @@ -29,6 +29,7 @@ from libvt.screen import Screen _ITEM0 = operator.itemgetter(0) +_EMPTY_ROW = FrozenRow(text="", cols=0) class CursorShape(enum.StrEnum): @@ -212,9 +213,46 @@ def _slice_indices(s: slice, length: int) -> range: if step != 1: msg = "grid slices only support step=1" raise ValueError(msg) + return range(start, max(start, stop)) + + +def _normalize_range(span: range, *, axis: str) -> range: + if span.step != 1: + msg = f"{axis} range only supports step=1" + raise ValueError(msg) + if span.start < 0 or span.stop < 0: + msg = f"{axis} range bounds must be non-negative, got {span!r}" + raise ValueError(msg) + if span.stop < span.start: + return range(span.start, span.start) + return span + + +def _clip_range(span: range, limit: int) -> range: + start = min(span.start, limit) + stop = max(start, min(span.stop, limit)) + if start == span.start and stop == span.stop: + return span return range(start, stop) +def _validate_region_binding( + *, + screen: Screen | None, + live: bool | None, + row_range: range | None, +) -> None: + if screen is not None and live is False: + msg = "live=False cannot be combined with screen" + raise ValueError(msg) + if screen is None and live is True: + msg = "live=True requires screen" + raise ValueError(msg) + if screen is None and row_range is not None: + msg = "row_range requires screen" + raise ValueError(msg) + + def _frozen_row_runs( row: FrozenRow, start_c: int, @@ -519,9 +557,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. + A live row resolves its viewport row index on each read and clips to the + live screen dimensions, appearing empty while the screen is shorter than + its row index. A slice retains its selected columns and clips them to the + live width. Frozen rows keep their captured width. Examples -------- @@ -542,22 +581,30 @@ def __init__( screen: Screen | None = None, row_idx: int = -1, ) -> None: - self._row = row + if screen is not None and row_idx < 0: + msg = f"row_idx must be non-negative when screen is provided, got {row_idx}" + raise ValueError(msg) + self._row: RowLike = _EMPTY_ROW if screen is not None else row self._screen = screen self._row_idx = row_idx - self._col_range = col_range + self._col_range = ( + None if col_range is None else _normalize_range(col_range, axis="col") + ) 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] + if self._screen is not None: + rows = self._screen._rows + if 0 <= self._row_idx < len(rows): + return rows[self._row_idx] + return _EMPTY_ROW 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) + if self._screen is not None or isinstance(row, _Row): + return _clip_range(cols, row.cols) return cols @property @@ -894,8 +941,11 @@ 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. + A live region resolves its selected viewport coordinates from the live + :class:`~libvt.screen.Screen` on each read, staying aligned across scrolls, + reflows, and resizes while clipping to the current dimensions. Regions from + a snapshot or its viewport keep the rows and geometry captured with the + frame. Examples -------- @@ -913,7 +963,13 @@ class RegionView(collections.abc.Sequence[RowView]): r0[0..6]: bold """ - __slots__ = ("_col_range", "_live_rows", "_parent_cols", "_rows") + __slots__ = ( + "_col_range", + "_parent_cols", + "_row_range", + "_rows", + "_screen", + ) def __init__( self, @@ -921,36 +977,93 @@ def __init__( col_range: range, *, parent_cols: int | None = None, - live: bool = True, + live: bool | None = None, + screen: Screen | None = None, + row_range: range | None = None, ) -> None: + """Create a rectangular view over live screen coordinates or frozen rows. + + Parameters + ---------- + rows : collections.abc.Sequence[RowLike] + Captured rows backing a frozen region. Ignored when *screen* is + provided. + col_range : range + Contiguous (``step == 1``), non-negative source column range. + Empty ranges with ``stop < start`` canonicalize to + ``range(start, start)``. + parent_cols : int | None, optional + Source grid width for a frozen region; defaults to the widest row + in *rows* or ``col_range.stop``. Ignored when *screen* is provided. + live : bool | None, optional + Whether the region tracks a live :class:`~libvt.screen.Screen`. + Defaults to ``screen is not None``. Passing ``live=False`` with + *screen* or ``live=True`` without *screen* raises + :exc:`ValueError`. + screen : Screen | None, optional + Live :class:`~libvt.screen.Screen` queried on each read. + row_range : range | None, optional + Contiguous (``step == 1``), non-negative source row range on + *screen*. Defaults to ``range(screen.rows)`` when *screen* is + provided. Passing *row_range* without *screen* raises + :exc:`ValueError`. + + Raises + ------ + ValueError + If *col_range* or *row_range* has ``step != 1`` or negative + bounds, if *live* contradicts *screen*, or if *row_range* is + supplied without *screen*. + """ + _validate_region_binding(screen=screen, live=live, row_range=row_range) + norm_cols = _normalize_range(col_range, axis="col") + self._screen = screen + self._col_range = norm_cols + if screen is not None: + self._row_range: range | None = ( + range(len(screen._rows)) + if row_range is None + else _normalize_range(row_range, axis="row") + ) + self._rows: tuple[RowLike, ...] = () + self._parent_cols = 0 + return + self._row_range = 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) + max((row.cols for row in self._rows), default=norm_cols.stop) if parent_cols is None else parent_cols ) + def _current_row_range(self) -> range: + if self._screen is not None and self._row_range is not None: + return _clip_range(self._row_range, len(self._screen._rows)) + return range(len(self._rows)) + + def _current_rows(self) -> collections.abc.Sequence[RowLike]: + if self._screen is not None and self._row_range is not None: + span = _clip_range(self._row_range, len(self._screen._rows)) + return self._screen._rows[span.start : span.stop] + return self._rows + def _source_width(self) -> int: - if self._live_rows: - return min(row.cols for row in self._live_rows) + if self._screen is not None: + return self._screen.cols 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) + if self._screen is not None: + return _clip_range(columns, self._screen.cols) return columns @property def rows(self) -> int: """Return height of this region in rows.""" - return len(self._rows) + return len(self._current_row_range()) @property def cols(self) -> int: @@ -995,22 +1108,27 @@ def unwrapped_text(self) -> str: ('hello world', 'hell\nrld') """ columns = self.columns - if ( - columns.start == 0 - and columns.step == 1 - and columns.stop >= self._source_width() - ): - return _unwrapped_text(self._rows, visible_cols=len(columns)) + if not columns: + return "" + if columns.start == 0 and columns.stop >= self._source_width(): + return _unwrapped_text(self._current_rows(), visible_cols=len(columns)) return self.text def __iter__(self) -> collections.abc.Iterator[RowView]: """Iterate over rows using the current rectangular extent.""" columns = self.columns + if self._screen is not None: + screen = self._screen + span = self._current_row_range() + return ( + RowView(_EMPTY_ROW, columns, screen=screen, row_idx=r_idx) + for r_idx in span + ) return (RowView(row, columns) for row in self._rows) def __len__(self) -> int: """Return number of rows in this region.""" - return len(self._rows) + return len(self._current_row_range()) @t.overload def __getitem__(self, key: int) -> RowView: ... @@ -1035,12 +1153,22 @@ def __getitem__( key: int | slice | tuple[slice | int, slice | int], ) -> RowView | Cell | RegionView: """Index a row, single ``(row, col)`` cell, or 2D region view.""" + if self._screen is not None: + span = self._current_row_range() + rows = self._screen._rows[span.start : span.stop] + return slice_grid( + rows, + self._screen.cols, + key, + screen=self._screen, + columns=self.columns, + row_range=span, + ) return slice_grid( self._rows, - self._source_width(), + self._parent_cols, key, columns=self.columns, - live=bool(self._live_rows), ) @@ -1149,14 +1277,23 @@ def slice_grid( *, screen: Screen | None = None, columns: range | None = None, - live: bool = False, + row_range: range | None = None, + live: bool | None = None, ) -> RowView | Cell | RegionView: """Index a grid or a rectangular view in its own coordinates.""" + _validate_region_binding(screen=screen, live=live, row_range=row_range) height = len(rows) + visible_rows = ( + range(height) if row_range is None else _normalize_range(row_range, axis="row") + ) + if row_range is not None and len(visible_rows) != height: + msg = f"row_range length {len(visible_rows)} does not match {height} rows" + raise ValueError(msg) if isinstance(key, int): nr = _normalize_index(key, height, axis="row") - return RowView(rows[nr], columns, screen=screen, row_idx=nr) - visible = range(cols) if columns is None else columns + row_idx = visible_rows[nr] if screen is not None else -1 + return RowView(rows[nr], columns, screen=screen, row_idx=row_idx) + visible = range(cols) if columns is None else _normalize_range(columns, axis="col") 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") @@ -1165,10 +1302,12 @@ def slice_grid( row_span = _grid_span(r_key, height, axis="row") col_span = _grid_span(c_key, len(visible), axis="col") return RegionView( - rows[row_span], + () if screen is not None else rows[row_span], visible[col_span], - parent_cols=cols, - live=screen is not None or live, + parent_cols=None if screen is not None else cols, + live=live, + screen=screen, + row_range=visible_rows[row_span] if screen is not None else None, ) diff --git a/tests/test_screen.py b/tests/test_screen.py index c58fdbb6..739bc766 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -21,7 +21,7 @@ from libvt.events import InBandResize from libvt.modes import Mode from libvt.profiles import GHOSTTY_PROFILE, XTERM_PROFILE -from libvt.screen import Cursor, RowView, Screen +from libvt.screen import Cursor, Screen from libvt.style import ( AnsiColor, Color, @@ -33,6 +33,7 @@ ) from libvt.terminal import ResyncReason from libvt.testing import serialize_vt_snapshot +from libvt.views import RegionView, RowView, slice_grid def _assert_grid_invariants(term: libvt.Terminal) -> None: @@ -1040,6 +1041,627 @@ def read_row_width(_row: _Row) -> int: assert region[:, 1:4].cols == 3 +@pytest.mark.parametrize("chunk_size", [0, 1]) +def test_retained_live_region_and_nested_crops_track_scroll(chunk_size: int) -> None: + """Retained live regions and nested crops follow viewport rows across scrolls.""" + + 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]) + + # Scroll up across retained full region, direct row, and frozen snapshot. + repro = libvt.Terminal(rows=3, cols=5) + feed(repro, b"A\r\nB\r\nC") + region, row, region_row, frozen = ( + repro[:], + repro[0], + repro[:][0], + repro.committed[:], + ) + feed(repro, b"\r\nD") + assert region.lines == repro[:].lines == ("B", "C", "D") + assert region.display_lines == repro[:].display_lines == ("B ", "C ", "D ") + assert region.text == repro[:].text == "B\nC\nD" + assert row.text == region_row.text == "B" + assert (repro.cursor.row, repro.cursor.col) == (2, 1) + assert frozen.lines == ("A", "B", "C") + + # Styled rows with cropped outer region, nested live crop, scroll up/down, and blit. + term = libvt.Terminal(rows=3, cols=6) + feed( + term, + b"0\x1b[31mABCD\x1b[0m5\r\n1\x1b[1;32mEFGH\x1b[0m5\r\n2\x1b[34mIJKL\x1b[0m5", + ) + outer = term[:, 1:5] + outer_iter = list(outer) + inner = outer[1:3, 1:-1] + outer_row1 = outer[1] + inner_row0 = inner[0] + inner_full = inner_row0.full_row + snap = term.committed + frozen_outer = snap[:, 1:5] + frozen_inner = frozen_outer[1:3, 1:-1] + + # Scroll up by 1 row with a styled new line. + feed(term, b"\r\n3\x1b[35mMNOP\x1b[0m5") + snap_with_hist = term.committed + vp_offset = snap_with_hist.viewport(offset=1) + vp_offset_crop = vp_offset[:, 1:5] + assert len(snap_with_hist.history) == 1 + assert outer.lines == term[:, 1:5].lines == ("EFGH", "IJKL", "MNOP") + assert [r.text for r in outer_iter] == ["EFGH", "IJKL", "MNOP"] + assert inner.lines == term[1:3, 2:4].lines == ("JK", "NO") + assert inner.display_lines == ("JK", "NO") + assert outer.columns == range(1, 5) + assert inner.columns == inner[0].columns == range(2, 4) + assert outer_row1.text == "IJKL" + assert outer_row1 == term[1][1:5] + assert inner_row0.text == "JK" + assert inner_row0 == term[1][2:4] + assert inner_full.text == "2IJKL5" + assert inner_full == term[1] + assert [(r.start_col, r.end_col, r.style.fg) for r in outer[2].runs] == [ + (1, 5, AnsiColor.MAGENTA), + ] + assert [(r.start_col, r.end_col, r.style.fg) for r in inner[1].runs] == [ + (2, 4, AnsiColor.MAGENTA), + ] + assert inner[1, 0].text == "N" + assert inner[1, 0].style.fg == AnsiColor.MAGENTA + assert [r.text for r in reversed(inner)] == ["NO", "JK"] + + blitted = Screen(rows=3, cols=6) + blitted.blit(outer) + assert blitted.lines == ("EFGH", "IJKL", "MNOP") + + # Overlapping self-blit from a retained live RegionView after scrolling. + self_term = libvt.Terminal(rows=3, cols=6) + feed(self_term, b"ABCD12\r\nEFGH34\r\nIJKL56") + self_src = self_term.screen[0:2, 0:4] + feed(self_term, b"\r\nMNOP78") + assert self_src.lines == ("EFGH", "IJKL") + self_term.screen.blit(self_src, top=1, left=1) + assert self_term.screen.lines == ("EFGH34", "IEFGH6", "MIJKL8") + assert self_src.lines == ("EFGH", "IEFG") + + # Scroll down via SD (CSI 1 T) recycles bottom rows to top. + feed(term, b"\x1b[1T") + assert outer.lines == term[:, 1:5].lines == ("", "EFGH", "IJKL") + assert [r.text for r in outer_iter] == ["", "EFGH", "IJKL"] + assert inner.lines == term[1:3, 2:4].lines == ("FG", "JK") + assert outer_row1.text == "EFGH" + assert inner_row0.text == "FG" + assert inner_full.text == "1EFGH5" + assert [ + (r.start_col, r.end_col, r.style.bold, r.style.fg) for r in inner[0].runs + ] == [(2, 4, True, AnsiColor.GREEN)] + + # Partial DECSTBM scroll region (rows 1..2) recycles inside margins. + feed(term, b"\x1b[2;3r\x1b[1S") + assert outer.lines == term[:, 1:5].lines == ("", "IJKL", "") + assert inner.lines == term[1:3, 2:4].lines == ("JK", "") + + # Frozen snapshots and scrolled viewport(offset>0) stay isolated across all scrolls. + vp0 = snap.viewport(offset=0) + assert frozen_outer.lines == ("ABCD", "EFGH", "IJKL") + assert frozen_inner.lines == ("FG", "JK") + assert vp0.lines == ("0ABCD5", "1EFGH5", "2IJKL5") + assert vp_offset.lines == ("0ABCD5", "1EFGH5", "2IJKL5") + assert vp_offset_crop.lines == ("ABCD", "EFGH", "IJKL") + assert vp_offset_crop[0, 0].style.fg == AnsiColor.RED + assert vp_offset_crop[1, 0].style.bold is True + assert vp_offset_crop[1, 0].style.fg == AnsiColor.GREEN + assert frozen_outer[0, 0].style.fg == AnsiColor.RED + assert frozen_inner[0, 0].style.bold is True + assert frozen_inner[0, 0].style.fg == AnsiColor.GREEN + + +def test_retained_live_region_follows_reflow_and_resize_bounds() -> None: + """Retained live regions follow reflow row replacement and clip on resize.""" + term = libvt.Terminal(rows=3, cols=6) + term.feed(b"\x1b[32mhello world\x1b[0m\r\nnext") + full = term[:] + crop = term[:, 1:5] + nested = crop[:2, 1:-1] + bottom = term[2:3, 2:5] + row0 = full[0] + nested_row = nested[0] + frozen = term.committed[:] + frozen_nested = frozen[:, 1:5][:2, 1:-1] + + # Reflow narrower replaces every _Row in screen._rows. + term.resize(rows=3, cols=4, reflow=True) + assert full.rows == len(full) == 3 + assert full.cols == 4 + assert full.columns == range(4) + assert full.lines == term[:].lines == ("o wo", "rld", "next") + assert ( + [r.wrapped for r in full] + == [r.wrapped for r in term[:]] + == [ + True, + False, + False, + ] + ) + assert full.unwrapped_text == term.unwrapped_text == "o world\nnext" + assert [(r.start_col, r.end_col, r.style.fg) for r in full[0].runs] == [ + (0, 4, AnsiColor.GREEN), + ] + assert crop.columns == range(1, 4) + assert crop.lines == term[:, 1:5].lines == (" wo", "ld", "ext") + assert crop.unwrapped_text == crop.text == " wo\nld\next" + assert term.committed[:, 1:4].unwrapped_text == " wo\nld\next" + assert nested.columns == range(2, 4) + assert nested.lines == ("wo", "d") + assert row0 == term[0] + assert nested_row == term[0][2:4] + assert nested_row.full_row == term[0] + assert (term.cursor.row, term.cursor.col) == (2, 3) + + blitted = Screen(rows=3, cols=4) + blitted.blit(full) + assert blitted.lines == ("o wo", "rld", "next") + + # Reflow wider keeps selected rectangle bounds on the new rows. + term.resize(rows=4, cols=10, reflow=True) + assert full.rows == 3 + assert full.cols == 6 + assert full.columns == range(6) + assert full.lines == term[:3, :6].lines == ("hello", "d", "next") + assert full.display_lines == ("hello ", "d ", "next ") + assert full.unwrapped_text == full.text == "hello\nd\nnext" + assert crop.columns == range(1, 5) + assert nested.columns == range(2, 4) + + # Non-reflow shrink below start coordinates (cols < start) clips cleanly to 0. + term.resize(rows=1, cols=1, reflow=False) + assert (bottom.rows, len(bottom), bottom.cols) == (0, 0, 0) + assert (bottom.columns.start, bottom.columns.stop, bottom.columns.step) == ( + 1, + 1, + 1, + ) + assert bottom.lines == () + assert bottom.display_lines == () + assert bottom.text == "" + assert bottom.unwrapped_text == "" + assert list(bottom) == [] + with pytest.raises(IndexError, match="row index 0 out of range for size 0"): + _ = bottom[0] + with pytest.raises(IndexError, match="row index 0 out of range for size 0"): + _ = bottom[0, 0] + assert (crop.rows, crop.cols) == (1, 0) + assert (crop.columns.start, crop.columns.stop, crop.columns.step) == (1, 1, 1) + assert (nested.rows, nested.cols) == (1, 0) + assert (nested.columns.start, nested.columns.stop, nested.columns.step) == ( + 1, + 1, + 1, + ) + assert nested.lines == ("",) + assert nested.display_lines == ("",) + assert nested.unwrapped_text == "" + with pytest.raises(IndexError, match="col index 0 out of range for size 0"): + _ = nested[0, 0] + + # Growing back restores selected coordinates on both outer and nested live crops. + term.resize(rows=4, cols=6, reflow=False) + term.feed(b"\x1b[1;1Habcdef\r\nABCDEF\r\n012345") + assert (bottom.rows, bottom.cols, bottom.columns) == (1, 3, range(2, 5)) + assert bottom.lines == ("234",) + assert bottom[0].full_row.text == "012345" + assert (nested.rows, nested.cols, nested.columns) == (2, 2, range(2, 4)) + assert nested.lines == ("cd", "CD") + assert nested.display_lines == ("cd", "CD") + assert nested[0].full_row.text == "abcdef" + assert nested[1].full_row.text == "ABCDEF" + assert (crop.rows, crop.cols, crop.columns) == (3, 4, range(1, 5)) + assert crop.lines == ("bcde", "BCDE", "1234") + + # Frozen captures preserve original 6-col pre-reflow state. + assert (frozen.rows, frozen.cols, frozen.columns) == (3, 6, range(6)) + assert frozen.lines == ("hello ", "world", "next") + assert [r.wrapped for r in frozen] == [True, False, False] + assert frozen.unwrapped_text == "hello world\nnext" + assert frozen_nested.display_lines == ("ll", "rl") + assert frozen[0, 0].style.fg == AnsiColor.GREEN + + +def test_retained_live_region_boundaries_1col_cjk_bce_alt_and_sync() -> None: + """Live regions hold invariants at 1-col, wide edge, BCE, alt-screen, and ?2026.""" + # 1-column terminal scrolling and wrapping. + t1 = libvt.Terminal(rows=3, cols=1) + t1.feed(b"ABC") + reg1 = t1[:] + frozen1 = t1.committed[:] + t1.feed(b"D") + assert reg1.lines == t1[:].lines == ("B", "C", "D") + assert [r.wrapped for r in reg1] == [True, True, False] + assert reg1.unwrapped_text == "BCD" + assert (t1.cursor.row, t1.cursor.col, t1.cursor.pending_wrap) == (2, 0, True) + assert frozen1.lines == ("A", "B", "C") + + # CJK wide glyph at cols - 1 (SPACER_HEAD) split across UTF-8 byte boundaries. + t_cjk = libvt.Terminal(rows=3, cols=5) + cjk_payload = "abcd日\r\nXY".encode() + for idx in range(len(cjk_payload)): + t_cjk.feed(cjk_payload[idx : idx + 1]) + full_cjk = t_cjk[:] + right_cjk = t_cjk[:, 3:5] + frozen_cjk = t_cjk.committed[:] + assert frozen_cjk[0, 4].width_role == WidthRole.SPACER_HEAD + assert frozen_cjk[0].wrapped is True + t_cjk.feed("\r\nZ本".encode()) + assert full_cjk.lines == t_cjk[:].lines == ("日", "XY", "Z本") + assert full_cjk.display_lines == ("日 ", "XY ", "Z本 ") + assert right_cjk.display_lines == t_cjk[:, 3:5].display_lines == (" ", " ", " ") + assert full_cjk[2, 1].text == "本" + assert frozen_cjk.lines == ("abcd", "日", "XY") + assert frozen_cjk.unwrapped_text == "abcd日\nXY" + assert frozen_cjk[0, 4].width_role == WidthRole.SPACER_HEAD + + # Wide CJK glyphs straddling live crop edges (SPACER_TAIL at start, WIDE at stop). + t_edge = libvt.Terminal(rows=2, cols=6) + t_edge.feed("a日本b\r\nx漢y字".encode()) + mid_edge = t_edge[:, 2:4] + frozen_edge = t_edge.committed[:, 2:4] + assert mid_edge.display_lines == (" ", " y") + assert mid_edge[0, 0].width_role == WidthRole.SPACER_TAIL + assert mid_edge[0, 1].width_role == WidthRole.WIDE + assert mid_edge[0, 1].text == "本" + t_edge.feed("\r\n漢a本b".encode()) + assert mid_edge.display_lines == t_edge[:, 2:4].display_lines == (" y", "a ") + assert mid_edge[0, 0].width_role == WidthRole.SPACER_TAIL + assert mid_edge[0, 1].text == "y" + assert mid_edge[1, 0].text == "a" + assert mid_edge[1, 1].width_role == WidthRole.WIDE + assert frozen_edge.display_lines == (" ", " y") + + # Combining grapheme clusters (e\u0301) and ZWJ emoji under ?2027h across scrolls. + t_graph = libvt.Terminal(rows=2, cols=6) + t_graph.feed(b"\x1b[?2027h" + "ae\u0301👩‍💻z\r\n012345".encode()) + g_crop = t_graph[:, 1:4] + g_split = t_graph[:, 3:5] + g_frozen = t_graph.committed[:, 1:4] + assert g_crop[0, 0].text == "e\u0301" + assert g_crop[0, 1].text == "👩‍💻" + assert g_crop[0, 1].width == 2 + assert g_split.display_lines == (" z", "34") + t_graph.feed("\r\nX👩‍💻e\u0301Y".encode()) + assert g_crop[1, 0].text == "👩‍💻" + assert g_crop[1, 1].width_role == WidthRole.SPACER_TAIL + assert g_crop[1, 2].text == "e\u0301" + assert g_crop[1].text == "👩‍💻e\u0301" + assert g_crop[1].display_text == "👩‍💻e\u0301" + assert g_split[1].display_text == "e\u0301Y" + t_graph.feed("\r\nabc👩‍💻".encode()) + assert g_crop[1].display_text == "bc " + assert g_crop[1, 2].text == "👩‍💻" + assert g_split[1].display_text == "👩‍💻" + assert g_frozen[0, 0].text == "e\u0301" + assert g_frozen[0, 1].text == "👩‍💻" + + # BCE styled blank rows (used > 0, text_used == 0) scrolled through a live crop. + t_bce = libvt.Terminal(rows=3, cols=5) + t_bce.feed(b"\x1b[44m\x1b[2KA\r\n\x1b[42m\x1b[2KB\r\n\x1b[41m\x1b[2K") + bce_crop = t_bce[:, 1:4] + bce_row2 = bce_crop[2] + bce_frozen = t_bce.committed[:, 1:4] + t_bce.feed(b"\r\n\x1b[45m\x1b[2K") + assert (bce_crop[1].used, bce_crop[1].text_used) == (3, 0) + assert (bce_crop[2].used, bce_crop[2].text_used) == (3, 0) + assert bce_crop[1].runs[0].style.bg == AnsiColor.RED + assert bce_crop[2].runs[0].style.bg == AnsiColor.MAGENTA + assert (bce_row2.used, bce_row2.text_used) == (3, 0) + assert bce_row2.runs[0].style.bg == AnsiColor.MAGENTA + assert bce_frozen[2].runs[0].style.bg == AnsiColor.RED + + # Synchronized output (?2026): live region tracks working screen; committed holds. + t_sync = libvt.Terminal(rows=3, cols=5) + t_sync.feed(b"A\r\nB\r\nC") + live_sync = t_sync[:] + held_frozen = t_sync.committed[:] + t_sync.feed(b"\x1b[?2026h\r\nD") + assert ( + live_sync.lines + == t_sync[:].lines + == t_sync.snapshot()[:].lines + == ( + "B", + "C", + "D", + ) + ) + assert t_sync.committed[:].lines == ("A", "B", "C") + assert held_frozen.lines == ("A", "B", "C") + t_sync.feed(b"\r\nE\x1b[?2026l") + assert live_sync.lines == t_sync.committed[:].lines == ("C", "D", "E") + assert held_frozen.lines == ("A", "B", "C") + + # Alternate screen (?1049h / ?1049l): primary and alt regions track own Screen. + t_alt = libvt.Terminal(rows=2, cols=5) + t_alt.feed(b"P1\r\nP2") + prim_reg = t_alt[:] + t_alt.feed(b"\x1b[?1049hA1\r\nA2") + alt_reg = t_alt[:] + t_alt.feed(b"\r\nA3") + alt_frozen = t_alt.committed[:] + assert alt_reg.lines == t_alt[:].lines == ("A2", "A3") + assert prim_reg.lines == ("P1", "P2") + t_alt.feed(b"\x1b[?1049l\r\nP3") + assert prim_reg.lines == t_alt[:].lines == ("P2", "P3") + assert alt_reg.lines == t_alt.screens.alternate[:].lines == ("", "") + assert alt_frozen.lines == ("A2", "A3") + + +def test_live_region_inverted_slices_validation_and_row_shrink_recovery() -> None: + """Empty slices, constructor validation, and vertically shrunk live rows.""" + term = libvt.Terminal(rows=3, cols=6) + term.feed(b"0AAAAA\r\n1BBBBB\r\n2CCCCC") + + # Inverted empty slices produce canonical empty ranges across shrink & grow-back. + inv_rows = term[3:1, :] + inv_cols = term[:, 5:2] + inv_both = term[3:1, 5:2] + frozen_inv_rows = term.committed[3:1, :] + frozen_inv_cols = term.committed[:, 5:2] + + assert (inv_rows.rows, len(inv_rows), inv_rows.cols, inv_rows.columns) == ( + 0, + 0, + 6, + range(6), + ) + assert inv_rows.lines == () + assert inv_rows.text == "" + assert inv_rows.unwrapped_text == "" + assert list(inv_rows) == [] + + assert (inv_cols.rows, len(inv_cols), inv_cols.cols) == (3, 3, 0) + assert (inv_cols.columns.start, inv_cols.columns.stop, inv_cols.columns.step) == ( + 5, + 5, + 1, + ) + assert inv_cols.lines == ("", "", "") + assert inv_cols.display_lines == ("", "", "") + assert inv_cols.text == "" + assert inv_cols.unwrapped_text == "" + assert [len(r) for r in inv_cols] == [0, 0, 0] + assert [(r.columns.start, r.columns.stop, r.columns.step) for r in inv_cols] == [ + (5, 5, 1), + ] * 3 + + assert (inv_both.rows, inv_both.cols) == (0, 0) + assert (inv_both.columns.start, inv_both.columns.stop, inv_both.columns.step) == ( + 5, + 5, + 1, + ) + assert list(inv_both) == [] + assert (frozen_inv_rows.rows, frozen_inv_rows.cols) == (0, 6) + assert (frozen_inv_cols.rows, frozen_inv_cols.cols) == (3, 0) + assert ( + frozen_inv_cols.columns.start, + frozen_inv_cols.columns.stop, + frozen_inv_cols.columns.step, + ) == (5, 5, 1) + + term.resize(rows=1, cols=2, reflow=False) + assert (inv_rows.rows, inv_rows.cols, inv_rows.columns) == (0, 2, range(2)) + assert list(inv_rows) == [] + assert inv_rows.unwrapped_text == "" + assert (inv_cols.rows, inv_cols.cols) == (1, 0) + assert (inv_cols.columns.start, inv_cols.columns.stop, inv_cols.columns.step) == ( + 2, + 2, + 1, + ) + assert inv_cols.display_lines == ("",) + assert [(r.columns.start, r.columns.stop, r.columns.step) for r in inv_cols] == [ + (2, 2, 1), + ] + assert (inv_both.rows, inv_both.cols) == (0, 0) + assert (inv_both.columns.start, inv_both.columns.stop, inv_both.columns.step) == ( + 2, + 2, + 1, + ) + + term.resize(rows=4, cols=6, reflow=False) + assert (inv_rows.rows, inv_rows.cols, inv_rows.columns) == (0, 6, range(6)) + assert list(inv_rows) == [] + assert (inv_cols.rows, inv_cols.cols) == (3, 0) + assert (inv_cols.columns.start, inv_cols.columns.stop, inv_cols.columns.step) == ( + 5, + 5, + 1, + ) + assert inv_cols.unwrapped_text == "" + assert (inv_both.rows, inv_both.cols) == (0, 0) + assert (inv_both.columns.start, inv_both.columns.stop, inv_both.columns.step) == ( + 5, + 5, + 1, + ) + + # RegionView, RowView, and slice_grid constructor validation. + with pytest.raises(ValueError, match="step=1"): + RegionView((), range(0, 4, 2)) + with pytest.raises(ValueError, match="step=1"): + RegionView((), range(4), screen=term.screen, row_range=range(0, 2, 2)) + with pytest.raises(ValueError, match="non-negative"): + RegionView((), range(-1, 2)) + with pytest.raises(ValueError, match="non-negative"): + RegionView((), range(-1)) + with pytest.raises(ValueError, match="non-negative"): + RegionView((), range(2), screen=term.screen, row_range=range(-1, 1)) + with pytest.raises(ValueError, match="non-negative"): + RegionView((), range(2), screen=term.screen, row_range=range(1, -1)) + with pytest.raises(ValueError, match="live=False"): + RegionView((), range(2), screen=term.screen, live=False) + with pytest.raises(ValueError, match="live=True"): + RegionView((), range(2), live=True) + with pytest.raises(ValueError, match="row_range"): + RegionView((), range(2), row_range=range(1)) + for key in (slice(None), 0, (0, 0)): + with pytest.raises(ValueError, match="live=False"): + slice_grid( + term.screen._rows, term.cols, key, screen=term.screen, live=False + ) + with pytest.raises(ValueError, match="live=True"): + slice_grid(term.committed._rows, term.cols, key, live=True) + with pytest.raises(ValueError, match="row_range"): + slice_grid( + term.committed._rows, + term.cols, + key, + row_range=range(len(term.committed._rows)), + ) + with pytest.raises(ValueError, match="step=1"): + slice_grid(term.committed._rows, term.cols, (0, 0), columns=range(0, 4, 2)) + with pytest.raises(ValueError, match="non-negative"): + slice_grid(term.committed._rows, term.cols, (0, 0), columns=range(-1, 2)) + with pytest.raises(ValueError, match="step=1"): + slice_grid( + term.screen._rows[:2], + term.cols, + (0, 0), + screen=term.screen, + row_range=range(0, 4, 2), + ) + with pytest.raises(ValueError, match="non-negative"): + slice_grid( + term.screen._rows[:2], + term.cols, + (0, 0), + screen=term.screen, + row_range=range(-1, 1), + ) + with pytest.raises(ValueError, match="row_range length"): + slice_grid( + term.screen._rows, + term.cols, + (0, 0), + screen=term.screen, + row_range=range(1, 2), + ) + with pytest.raises(ValueError, match="row_range length"): + slice_grid( + term.screen._rows, + term.cols, + 2, + screen=term.screen, + row_range=range(1, 2), + ) + with pytest.raises(ValueError, match="row_range length"): + slice_grid( + (), + term.cols, + slice(None), + screen=term.screen, + row_range=range(1, 3), + ) + with pytest.raises(ValueError, match="row_idx"): + RowView(term.screen._rows[0], screen=term.screen, row_idx=-1) + with pytest.raises(ValueError, match="step=1"): + RowView(term.screen._rows[0], range(0, 4, 2)) + with pytest.raises(ValueError, match="non-negative"): + RowView(term.screen._rows[0], range(-1, 2)) + + default_live = RegionView((), range(4), screen=term.screen) + assert (default_live.rows, default_live.cols) == (4, 4) + canon_empty = RegionView((), range(4, 1), screen=term.screen, row_range=range(3, 1)) + assert (canon_empty.rows, canon_empty.cols) == (0, 0) + assert ( + canon_empty.columns.start, + canon_empty.columns.stop, + canon_empty.columns.step, + ) == (4, 4, 1) + frozen_canon_region = RegionView((), range(4, 1)) + assert ( + frozen_canon_region.columns.start, + frozen_canon_region.columns.stop, + frozen_canon_region.columns.step, + ) == (4, 4, 1) + frozen_canon_row = RowView(term.committed._rows[0], range(4, 1)) + assert ( + frozen_canon_row.columns.start, + frozen_canon_row.columns.stop, + frozen_canon_row.columns.step, + ) == (4, 4, 1) + empty_col_region = RegionView(term.committed._rows, range(0), parent_cols=0) + assert empty_col_region.unwrapped_text == "" + + # Retained live RowView across vertical shrink -> scroll -> grow-back never aliases + # a recycled _Row moved into screen._rows[0]. + rt = libvt.Terminal(rows=3, cols=6) + rt.feed(b"0AAAAA\r\n1BBBBB\r\n2CCCCC") + row2 = rt[2] + row2_crop = rt[:, 1:5][2] + row2_iter = list(rt[:, 1:5])[2] + row2_full = row2_crop.full_row + + # Three scrolls rotate the original _Row back to row 2 (the cursor row), so + # shrinking to 1 row moves that exact _Row into screen._rows[0]. + rt.feed(b"\r\n3DDDDD\r\n4EEEEE\r\n5FFFFF") + assert row2.text == "5FFFFF" + assert row2_crop.text == "FFFF" + assert row2_iter.text == "FFFF" + + # Shrink first to exact boundary rows=2 (row_idx == len(rows)), then rows=1. + rt.resize(rows=2, cols=6, reflow=False) + assert row2.text == "" + assert len(row2) == 0 + rt.resize(rows=1, cols=6, reflow=False) + rt.feed(b"\r\x1b[2K\x1b[31mZ99999\x1b[0m") + assert rt[0].text == "Z99999" + + for rv in (row2, row2_crop, row2_iter, row2_full): + assert rv.text == "" + assert rv.display_text == "" + assert list(rv) == [] + assert rv.runs == () + assert (rv.columns.start, rv.columns.stop, rv.columns.step) == (0, 0, 1) + assert rv.used == 0 + assert rv.text_used == 0 + assert rv.wrapped is False + assert len(rv) == 0 + assert len(rv.full_row) == 0 + assert rv.full_row.text == "" + with pytest.raises(IndexError, match="col index 0 out of range for size 0"): + _ = rv[0] + sub = rv[0:2] + assert len(sub) == 0 + assert sub.text == "" + assert row2 == row2_crop + + # Scroll while shrunk, then grow back to 3 rows: live RowViews resume row 2. + rt.feed(b"\r\nY88888") + rt.resize(rows=3, cols=6, reflow=False) + rt.feed(b"\x1b[3;1H\x1b[32mG12345\x1b[0m") + assert row2.text == "G12345" + assert row2.display_text == "G12345" + assert [c.text for c in row2] == list("G12345") + assert row2.columns == range(6) + assert (row2.used, row2.text_used) == (6, 6) + assert [(r.start_col, r.end_col, r.text, r.style.fg) for r in row2.runs] == [ + (0, 6, "G12345", AnsiColor.GREEN), + ] + assert row2[0].text == "G" + assert row2_crop.text == "1234" + assert row2_crop.display_text == "1234" + assert row2_crop.columns == range(1, 5) + assert (row2_crop.used, row2_crop.text_used) == (4, 4) + assert row2_crop.full_row.text == "G12345" + assert row2_iter.text == "1234" + assert row2_full.text == "G12345" + + 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 8fbe199c..0663e661 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -1883,3 +1883,76 @@ def test_testing_helpers_working_and_committed_frames_during_sync_output( assert format_screen_box(term.committed) == expected_new_box assert serialize_vt_snapshot(term) == expected_new_snap assert serialize_vt_snapshot(vt_screen(term)) == expected_new_snap + + +def test_serialize_retained_live_region_across_scroll_and_reflow() -> None: + """Boxed serializers read live coordinates from retained regions after scrolls.""" + term = Terminal(rows=3, cols=6) + term.feed(b"\x1b[31mA0000\x1b[0m\r\n\x1b[32mB1111\x1b[0m\r\n\x1b[34mC2222\x1b[0m") + live_full = term[:] + live_crop = term[:, 1:5] + frozen_full = term.committed[:] + frozen_crop = term.committed[:, 1:5] + + term.feed(b"\r\n\x1b[35mD3333\x1b[0m") + assert serialize_vt_snapshot(live_full) == serialize_vt_snapshot(term[:]) + assert serialize_vt_snapshot(live_full) == ( + "size=6x3 region=True\n" + "┌──────┐\n" + "│B1111 │\n" + "│C2222 │\n" + "│D3333 │\n" + "└──────┘\n" + "styles:\n" + " r0[0..5]: fg=green\n" + " r1[0..5]: fg=blue\n" + " r2[0..5]: fg=magenta" + ) + assert serialize_vt_snapshot( + vt_screen(live_crop, region=(0, 2, 1, 3)) + ) == serialize_vt_snapshot(vt_screen(term.screen, region=(0, 2, 2, 4))) + assert "│11│\n│22│" in serialize_vt_snapshot( + vt_screen(live_crop, region=(0, 2, 1, 3)) + ) + assert "│A0000 │" in serialize_vt_snapshot(frozen_full) + assert "│0000│" in serialize_vt_snapshot(frozen_crop) + assert "row 0 cols 0..4" in serialize_vt_snapshot( + vt_screen(live_crop, diff=frozen_crop) + ) + + # Reflow shrink updates serialized retained live regions; assertions track ?2026. + term.resize(rows=2, cols=4, reflow=True) + assert serialize_vt_snapshot(live_full) == serialize_vt_snapshot(term[:]) + assert serialize_vt_snapshot(live_crop) == serialize_vt_snapshot(term[:, 1:5]) + + term.feed(b"\x1b[?2026h\r\nWAIT") + assert_screen(term.committed, "D333\n3", cursor=(1, 1)) + assert_screen_box( + term.committed, + """ + ┌────┐ + │D333│W + │3 │ + └────┘ + """, + cursor=(1, 1), + ) + assert "│WAIT│" in serialize_vt_snapshot(live_full) + term.feed(b"\x1b[?2026l") + assert_screen(term.committed, "3\nWAIT", cursor=(1, 3)) + assert term.committed.cursor.pending_wrap is True + + # Wide CJK crop-edge clipping, inverted empty slice, and shrunk cols < start. + cjk_term = Terminal(rows=2, cols=6) + cjk_term.feed("a日本b\r\nx漢y字".encode()) + cjk_mid = cjk_term[:, 2:4] + cjk_inv = cjk_term[2:1, :] + cjk_term.feed("\r\n漢a本b".encode()) + assert serialize_vt_snapshot(cjk_mid) == ( + "size=2x2 region=True\n┌──┐\n│ y│\n│a │\n└──┘" + ) + assert serialize_vt_snapshot(cjk_inv) == ( + "size=6x0 region=True\n┌──────┐\n└──────┘" + ) + cjk_term.resize(rows=1, cols=1, reflow=False) + assert serialize_vt_snapshot(cjk_mid) == "size=0x1 region=True\n┌┐\n││\n└┘"