diff --git a/CHANGES b/CHANGES index 00d58fd003..f62f3d1b85 100644 --- a/CHANGES +++ b/CHANGES @@ -15,15 +15,20 @@ Local watch mode, the editor and CI use ty 0.0.113. CI checks the minimum suppor ### What's new -#### Reconstruct pane terminal state (#934) +#### Reconstruct pane and window terminal state (#934) -Install `libtmux[vt]` on Python 3.12 and later to inspect pane screens through -{mod}`libtmux.vt` and [libvt](https://libvt.git-pull.com) while keeping core -`libtmux` dependency-free on Python 3.11 and later. +Install `libtmux[vt]` on Python 3.12 and later to inspect pane and multi-pane +window screens through {mod}`libtmux.vt` and [libvt](https://libvt.git-pull.com) +while keeping core `libtmux` dependency-free on Python 3.11 and later. {meth}`~libtmux.Pane.capture_vt` returns viewport and scrollback cells, styles, -cursor state, and active terminal modes, paired with -{func}`~libtmux.vt.assert_pane_screen` and -{func}`~libtmux.vt.assert_pane_screen_box` for test assertions; the surface is +cursor state, and active terminal modes; {meth}`~libtmux.Window.capture_vt` and +{meth}`~libtmux.vt.VtSessionObserver.snapshot_window` composite split pane +grids, box-drawing dividers and junctions, `pane-border-status` labels, and the +active pane cursor into a single window `Snapshot`, paired with +{func}`~libtmux.vt.assert_pane_screen`, +{func}`~libtmux.vt.assert_pane_screen_box`, +{func}`~libtmux.vt.assert_window_screen`, and +{func}`~libtmux.vt.assert_window_screen_box` for test assertions; the surface is provisional while `libvt` is pre-`0.1`. See {ref}`vt` for details. #### Stream live pane updates over control mode (#934) diff --git a/docs/api/libtmux.vt.md b/docs/api/libtmux.vt.md index dcf8a6b5d4..1c72b581be 100644 --- a/docs/api/libtmux.vt.md +++ b/docs/api/libtmux.vt.md @@ -3,13 +3,17 @@ # VT Integration (`libtmux.vt`) {mod}`libtmux.vt` pairs `libtmux` with [libvt](https://libvt.git-pull.com) on -Python 3.12+ to reconstruct pane screens, immutable `Snapshot` grids, and `SGR` -styles via {meth}`~libtmux.Pane.capture_vt`, stream live `tmux -C` updates via -{meth}`~libtmux.Session.observe_vt`, {meth}`~libtmux.Pane.observe_vt`, and +Python 3.12+ to reconstruct pane and multi-pane window screens, immutable +`Snapshot` grids, and `SGR` styles via {meth}`~libtmux.Pane.capture_vt` and +{meth}`~libtmux.Window.capture_vt`, stream live `tmux -C` updates via +{meth}`~libtmux.Session.observe_vt`, {meth}`~libtmux.Pane.observe_vt`, +{meth}`~libtmux.vt.VtSessionObserver.snapshot_window`, and {fixture}`vt_observer`, encode mode-aware input via {meth}`~libtmux.Pane.send_vt_input`, and check screens with -{func}`~libtmux.vt.assert_pane_screen` and -{func}`~libtmux.vt.assert_pane_screen_box`. +{func}`~libtmux.vt.assert_pane_screen`, +{func}`~libtmux.vt.assert_pane_screen_box`, +{func}`~libtmux.vt.assert_window_screen`, and +{func}`~libtmux.vt.assert_window_screen_box`. Install with the `vt` extra: @@ -20,8 +24,9 @@ $ uv add "libtmux[vt]" ```{note} {mod}`libtmux.vt`, {meth}`~libtmux.Pane.capture_vt`, {meth}`~libtmux.Pane.observe_vt`, {meth}`~libtmux.Pane.send_vt_input`, -{meth}`~libtmux.Session.observe_vt`, and {fixture}`vt_observer` are provisional -while `libvt` is pre-`0.1` and may change across minor releases. +{meth}`~libtmux.Window.capture_vt`, {meth}`~libtmux.Session.observe_vt`, and +{fixture}`vt_observer` are provisional while `libvt` is pre-`0.1` and may +change across minor releases. ``` ## Capture a pane and inspect its `Snapshot` grid @@ -90,6 +95,91 @@ styles: >>> _ = quick_pane.send_vt_input("enter") ``` +## Capture a multi-pane window (`Window.capture_vt`) + +When a window holds split panes, {meth}`~libtmux.Window.capture_vt` captures +every pane in one `tmux` command batch and composites their cells, box-drawing +dividers and junctions (`│`, `─`, `├`), `pane-border-status` labels, and the +active pane's cursor into a single window `Snapshot` (alongside each pane's +individual capture in `win_captured.panes`): + +```python +>>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE +>>> import shlex +>>> import sys +>>> from libvt.testing import serialize_vt_snapshot +>>> from libtmux.constants import PaneDirection +>>> from libtmux.test.retry import retry_until +>>> from libtmux.vt import assert_window_screen_box +>>> py = shlex.quote(sys.executable) +>>> def _pane_cmd(title: str, body: str) -> str: +... script = ( +... "import sys; " +... f"sys.stdout.write({title!r} + {body!r}); " +... "sys.stdout.flush(); sys.stdin.read(1)" +... ) +... return f"{py} -u -c {shlex.quote(script)}" +>>> win_session = server.new_session( +... session_name="vt-window", +... x=21, +... y=5, +... window_command=_pane_cmd("\x1b]2;api\x07", "\x1b[1;32m200 OK\x1b[0m\r\nready"), +... ) +>>> split_win = win_session.active_window +>>> _ = split_win.set_option("pane-border-style", "default") +>>> _ = split_win.set_option("pane-active-border-style", "fg=green") +>>> right_top = split_win.split( +... direction=PaneDirection.Right, +... attach=True, +... shell=_pane_cmd("\x1b]2;db\x07", "\x1b[36mpg:up\x1b[0m"), +... size=10, +... ) +>>> right_bot = split_win.split( +... direction=PaneDirection.Below, +... attach=True, +... shell=_pane_cmd("\x1b]2;jobs\x07", "q=0"), +... size=2, +... ) +>>> def _win_ready() -> bool: +... txt = split_win.capture_vt().snapshot.text +... return "ready" in txt and "pg:up" in txt and "q=0" in txt +>>> retry_until(_win_ready) +True +>>> win_captured = split_win.capture_vt() +>>> print(serialize_vt_snapshot(win_captured.snapshot)) +size=21x5 cursor=(3,14,vis=True) alt=False modes=[] +┌─────────────────────┐ +│200 OK │pg:up │ +│ready │ │ +│ ├──────────│ +│ │q=0 │ +│ │ │ +└─────────────────────┘ +styles: + r0[0..6]: bold fg=green + r0[11..16]: fg=cyan + r2[10..21]: fg=green + r3[10..11]: fg=green + r4[10..11]: fg=green +>>> assert_window_screen_box( +... win_captured, +... """ +... ┌─────────────────────┐ +... │200 OK │pg:up │ +... │ready │ │ +... │ ├──────────│ +... │ │q=0 │ +... │ │ │ +... └─────────────────────┘ +... """, +... cursor=(3, 14), +... ) +>>> len(win_captured.panes), win_captured.zoomed, win_captured.layout_stable +(3, False, True) +>>> for p in split_win.panes: +... _ = p.send_vt_input("enter") +``` + ## Page through captured scrollback (`snap.viewport()`) When `history_lines` retains primary scrollback (`None` for full history or a diff --git a/pyproject.toml b/pyproject.toml index 51cff539a7..9c271c43f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,7 @@ Changes = "https://github.com/tmux-python/libtmux/blob/master/CHANGES" [project.optional-dependencies] vt = [ - "libvt>=0.0.1a4,<0.1; python_version >= '3.12'", + "libvt>=0.0.1a5,<0.1; python_version >= '3.12'", ] [dependency-groups] diff --git a/src/libtmux/vt.py b/src/libtmux/vt.py index 09091da71b..ce2860d506 100644 --- a/src/libtmux/vt.py +++ b/src/libtmux/vt.py @@ -47,6 +47,7 @@ TmuxControlParser, TmuxPaneSync, ) + from libvt.contrib.tmux.window import TmuxWindowCaptureResult from libvt.input import InputEvent from libvt.terminal import ( FlightRecorder, @@ -58,6 +59,7 @@ from libtmux.pane import Pane from libtmux.session import Session + from libtmux.window import Window logger = logging.getLogger(__name__) @@ -201,6 +203,166 @@ def capture_pane_vt( ) +def capture_window_vt( + window: Window, + *, + history_lines: int | None = 0, + include_saved_primary: bool = False, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + timeout: float | _UnsetType | None = _UNSET, +) -> TmuxWindowCaptureResult: + r"""Capture *window* and composite all visible panes into a ``Snapshot``. + + Queries live window geometry, border styles, and ``pane-border-format`` + via ``build_tmux_window_list_command()``, captures every pane in one + command batch via ``build_tmux_window_capture_command()``, and composites + pane cells, box-drawing dividers and junctions, ``pane-border-status`` + labels, and the active pane's cursor into a single window ``Snapshot``. + + Parameters + ---------- + window : :class:`~libtmux.Window` + Target tmux window. + history_lines : int or None, default 0 + Maximum scrollback lines captured per pane (``0`` for viewport-only + ``-S 0``, ``None`` for full history, or ``N > 0`` for ``-S -N``). + include_saved_primary : bool, default False + Include ``capture-pane -a -q`` sections on each pane so saved primary + scrollback is available in ``result.panes[pane_id]``. + scrollback : int or None, optional + Explicit per-pane scrollback line capacity override. + profile : Profile or None, optional + Explicit terminal profile override; defaults to ``tmux_profile()`` for + the server's ``tmux`` version. + policy : Policy or None, optional + Explicit security/reply policy override. + limits : Limits or None, optional + Explicit parser/buffer resource limits override. + timeout : float or None, optional + Subprocess timeout in seconds; inherits :attr:`~libtmux.Server.timeout` + when omitted. + + Returns + ------- + TmuxWindowCaptureResult + Composited window ``snapshot``, per-pane ``panes`` mapping, parsed + ``layout``, ``zoomed`` state, and ``layout_stable`` check. + + Raises + ------ + ValueError + When ``window.window_id`` is unset or *history_lines* is negative. + TypeError + When *history_lines* is not ``int`` or ``None``. + :exc:`~libtmux.exc.LibTmuxException` + When ``tmux`` reports an error (such as a missing window). + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libvt.testing import serialize_vt_snapshot + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import capture_window_vt + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[32mworker\\x1b[0m\\r\\nidle'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="fn-win-vt", + ... x=15, + ... y=3, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.set_option("pane-border-style", "default") + >>> _ = w.set_option("pane-active-border-style", "fg=green") + >>> p_right = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=7, + ... ) + >>> def _ready() -> bool: + ... txt = capture_window_vt(w).snapshot.text + ... return "ok" in txt and "idle" in txt + >>> retry_until(_ready) + True + >>> print(serialize_vt_snapshot(capture_window_vt(w).snapshot)) + size=15x3 cursor=(1,12,vis=True) alt=False modes=[] + ┌───────────────┐ + │api │worker │ + │ok │idle │ + │ │ │ + └───────────────┘ + styles: + r0[0..3]: bold fg=cyan + r0[8..14]: fg=green + r2[7..8]: fg=green + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + _require_libvt() + from libvt.config import DEFAULT_LIMITS + from libvt.contrib.tmux.profile import TMUX_CAPTURE_POLICY + from libvt.contrib.tmux.window import ( + build_tmux_window_capture_command, + build_tmux_window_list_command, + ) + + if window.window_id is None: + msg = "Window must have a window_id to capture VT state" + raise ValueError(msg) + if history_lines is not None: + if isinstance(history_lines, bool) or not isinstance(history_lines, int): + msg = ( + f"history_lines must be int or None, got {type(history_lines).__name__}" + ) + raise TypeError(msg) + if history_lines < 0: + msg = f"history_lines must be >= 0, got {history_lines}" + raise ValueError(msg) + + ver_str = get_version_str(window.server.tmux_bin) + list_cmd = build_tmux_window_list_command(window.window_id) + list_proc = window.server.cmd(*list_cmd.argv, timeout=timeout) + if list_proc.stderr: + raise_if_stderr(list_proc, "list-panes") + layout = list_cmd.parse(list_proc.stdout) + + cap_cmd = build_tmux_window_capture_command( + layout, + tmux_version=ver_str, + include_saved_primary=include_saved_primary, + history_lines=history_lines, + include_layout=True, + ) + cap_proc = window.server.cmd(*cap_cmd.argv, timeout=timeout) + if cap_proc.stderr: + raise_if_stderr(cap_proc, "capture-pane") + + eff_policy = TMUX_CAPTURE_POLICY if policy is None else policy + eff_limits = DEFAULT_LIMITS if limits is None else limits + return cap_cmd.parse( + cap_proc.stdout, + scrollback=scrollback, + profile=profile, + policy=eff_policy, + limits=eff_limits, + ) + + def _encode_for_terminal_target( event: InputEvent | str, target: Terminal | Snapshot | TmuxCaptureResult | VtPaneHandle, @@ -920,6 +1082,101 @@ async def watch_pane( await asyncio.shield(fut) return handle + async def snapshot_window( + self, + window: Window | str, + *, + watch_missing: bool = True, + timeout: float = 5.0, + ) -> Snapshot: + """Composite a multi-pane *window* ``Snapshot`` over ``tmux -C``. + + Queries live window layout, border styles, and ``pane-border-format`` + on this control client and composites tear-free ``committed`` snapshots + from watched :class:`VtPaneHandle` instances. + + Parameters + ---------- + window : :class:`~libtmux.Window` or str + Target :class:`~libtmux.Window` or ``"@"`` window ID string. + watch_missing : bool, default True + Automatically attach any panes in *window* not yet watched on this + observer before compositing. + timeout : float, default 5.0 + Maximum seconds for layout queries and any initial pane handshakes. + + Returns + ------- + Snapshot + Composited window ``Snapshot`` with pane cells, borders, junctions, + ``pane-border-status``, and active-pane cursor. + """ + from libvt.contrib.tmux.control import TmuxAttachPhase + from libvt.contrib.tmux.profile import tmux_profile + from libvt.contrib.tmux.window import ( + TMUX_WINDOW_METADATA_FORMAT, + TMUX_WINDOW_PANE_FORMAT, + TmuxPaneSource, + TmuxWindowLayout, + composite_tmux_window, + ) + + self._raise_if_closed() + window_id = window if isinstance(window, str) else window.window_id + if window_id is None: + msg = "Window must have a window_id to snapshot" + raise ValueError(msg) + if ( + not window_id.startswith("@") + or not window_id[1:].isascii() + or not window_id[1:].isdigit() + ): + msg = f"window_id must be '@', got {window_id!r}" + raise ValueError(msg) + + pane_prefix = "__LIBTMUX_WIN_PANE__:" + async with asyncio.timeout(timeout): + win_block = await self._execute_command( + f"display-message -p -t '{window_id}' '{TMUX_WINDOW_METADATA_FORMAT}'", + timeout=timeout, + ) + panes_block = await self._execute_command( + f"list-panes -t '{window_id}' -F " + f"'{pane_prefix}{TMUX_WINDOW_PANE_FORMAT}'", + timeout=timeout, + ) + win_raw = b"\n".join(win_block.lines).decode("utf-8", errors="replace") + pane_raws: list[str] = [] + for raw_ln in panes_block.lines: + ln = raw_ln.decode("utf-8", errors="replace") + if ln.startswith(pane_prefix): + pane_raws.append(ln[len(pane_prefix) :]) + elif pane_raws: + pane_raws[-1] = f"{pane_raws[-1]}\n{ln}" + layout = TmuxWindowLayout.from_format_lines(win_raw, pane_raws) + + sources: dict[str, TmuxPaneSource] = {} + for wp in layout.panes: + handle = self._handles.get(wp.pane_id) + if ( + handle is None or handle.sync.phase != TmuxAttachPhase.LIVE + ) and watch_missing: + handle = await self.watch_pane(wp.pane_id, timeout=timeout) + if handle is not None and handle.sync.terminal is not None: + sources[wp.pane_id] = handle.terminal.committed + + eff_profile = ( + tmux_profile(self._tmux_version_str) + if self._profile is None + else self._profile + ) + return composite_tmux_window( + layout, + sources, + tmux_version=self._tmux_version_str, + profile=eff_profile, + ) + async def _resync_pane( self, pane_id: str, @@ -1146,19 +1403,34 @@ async def observe_pane_vt( def _resolve_screen_target( - target: Pane | VtPaneHandle | TmuxCaptureResult | Terminal | Snapshot, + target: ( + Pane + | Window + | VtPaneHandle + | TmuxCaptureResult + | TmuxWindowCaptureResult + | Terminal + | Snapshot + ), ) -> Terminal | Snapshot: """Extract a ``Terminal`` or ``Snapshot`` from *target*.""" _require_libvt() from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.contrib.tmux.window import TmuxWindowCaptureResult from libvt.terminal import Snapshot, Terminal + from libtmux.window import Window + if isinstance(target, (Terminal, Snapshot)): return target if isinstance(target, TmuxCaptureResult): return target.terminal + if isinstance(target, TmuxWindowCaptureResult): + return target.snapshot if isinstance(target, VtPaneHandle): return target.terminal + if isinstance(target, Window): + return capture_window_vt(target).snapshot return capture_pane_vt( target, history_lines=0, @@ -1253,12 +1525,132 @@ def assert_pane_screen_box( assert_screen_box(resolved, expected, cursor=cursor) +def assert_window_screen( + target: Window | TmuxWindowCaptureResult | Snapshot, + expected: str | collections.abc.Sequence[str], + *, + cursor: tuple[int, int] | None = None, +) -> None: + r"""Assert that *target*'s composited window text matches *expected*. + + Accepts a :class:`~libtmux.Window` directly (capturing and compositing all + panes via :func:`capture_window_vt`), a ``TmuxWindowCaptureResult``, or a + composited ``Snapshot``. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import assert_window_screen + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; sys.stdout.write('left'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; sys.stdout.write('right'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="assert-win-vt", + ... x=11, + ... y=1, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=5, + ... ) + >>> def _ready() -> bool: + ... txt = w.capture_vt().snapshot.text + ... return "left" in txt and "right" in txt + >>> retry_until(_ready) + True + >>> assert_window_screen(w, "left │right") + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + resolved = _resolve_screen_target(target) + from libvt.testing import assert_screen + + assert_screen(resolved, expected, cursor=cursor) + + +def assert_window_screen_box( + target: Window | TmuxWindowCaptureResult | Snapshot, + expected: str, + *, + cursor: tuple[int, int] | None = None, +) -> None: + r"""Assert that *target* matches a column-exact composited window box diagram. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import assert_window_screen_box + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; sys.stdout.write('日本\\r\\nok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; sys.stdout.write('go\\r\\n42'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="assert-wbox-vt", + ... x=11, + ... y=2, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=5, + ... ) + >>> def _ready() -> bool: + ... txt = w.capture_vt().snapshot.text + ... return "ok" in txt and "42" in txt + >>> retry_until(_ready) + True + >>> assert_window_screen_box( + ... w, + ... ''' + ... ┌───────────┐ + ... │日本 │go │ + ... │ok │42 │ + ... └───────────┘ + ... ''', + ... cursor=(1, 8), + ... ) + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + resolved = _resolve_screen_target(target) + from libvt.testing import assert_screen_box + + assert_screen_box(resolved, expected, cursor=cursor) + + __all__ = ( "VtPaneHandle", "VtSessionObserver", "assert_pane_screen", "assert_pane_screen_box", + "assert_window_screen", + "assert_window_screen_box", "capture_pane_vt", + "capture_window_vt", "observe_pane_vt", "send_pane_vt_input", ) diff --git a/src/libtmux/window.py b/src/libtmux/window.py index 75b25dcc8c..a4727d521d 100644 --- a/src/libtmux/window.py +++ b/src/libtmux/window.py @@ -44,6 +44,9 @@ import types from typing import Never, Self + from libvt.config import Limits, Policy, Profile + from libvt.contrib.tmux.window import TmuxWindowCaptureResult + from libtmux.formats import Format from libtmux.options import OptionValue @@ -1870,6 +1873,115 @@ def width(self) -> str | None: """ return self.window_width + # + # VT integration (optional libtmux[vt] extra on Python 3.12+) + # + def capture_vt( + self, + *, + history_lines: int | None = 0, + include_saved_primary: bool = False, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + timeout: float | _UnsetType | None = _UNSET, + ) -> TmuxWindowCaptureResult: + r"""Capture and composite all visible panes in this window into a ``Snapshot``. + + Requires Python 3.12+ and ``libtmux[vt]`` (``pip install "libtmux[vt]"``). + + Parameters + ---------- + history_lines : int or None, default 0 + Maximum scrollback lines captured per pane (``0`` for viewport-only + ``-S 0``, ``None`` for full history, or ``N > 0`` for ``-S -N``). + include_saved_primary : bool, default False + Include ``capture-pane -a -q`` sections on each pane so saved + primary scrollback is available in ``result.panes[pane_id]``. + scrollback : int or None, optional + Explicit per-pane scrollback line capacity override. + profile : Profile or None, optional + Optional ``libvt`` terminal profile override. + policy : Policy or None, optional + Optional ``libvt`` security/reply policy override. + limits : Limits or None, optional + Optional ``libvt`` parser/buffer limits override. + timeout : float or None, optional + Subprocess timeout in seconds; inherits :attr:`Server.timeout` when + omitted. + + Returns + ------- + TmuxWindowCaptureResult + Composited window ``snapshot``, per-pane ``panes`` mapping, parsed + ``layout``, ``zoomed`` state, and ``layout_stable`` check. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libvt.testing import serialize_vt_snapshot + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[32mworker\\x1b[0m\\r\\nidle'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="win-cap-vt", + ... x=15, + ... y=3, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.set_option("pane-border-style", "default") + >>> _ = w.set_option("pane-active-border-style", "fg=green") + >>> _ = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=7, + ... ) + >>> def _ready() -> bool: + ... txt = w.capture_vt().snapshot.text + ... return "ok" in txt and "idle" in txt + >>> retry_until(_ready) + True + >>> print(serialize_vt_snapshot(w.capture_vt().snapshot)) + size=15x3 cursor=(1,12,vis=True) alt=False modes=[] + ┌───────────────┐ + │api │worker │ + │ok │idle │ + │ │ │ + └───────────────┘ + styles: + r0[0..3]: bold fg=cyan + r0[8..14]: fg=green + r2[7..8]: fg=green + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + from libtmux.vt import capture_window_vt + + return capture_window_vt( + self, + history_lines=history_lines, + include_saved_primary=include_saved_primary, + scrollback=scrollback, + profile=profile, + policy=policy, + limits=limits, + timeout=timeout, + ) + # # Legacy: Redundant stuff we want to remove # diff --git a/tests/test_vt.py b/tests/test_vt.py index 50c6e6b589..fe0c92190d 100644 --- a/tests/test_vt.py +++ b/tests/test_vt.py @@ -12,12 +12,16 @@ import pytest from libtmux import exc +from libtmux.constants import PaneDirection from libtmux.test.retry import retry_until from libtmux.vt import ( VtSessionObserver, _require_libvt, assert_pane_screen, assert_pane_screen_box, + assert_window_screen, + assert_window_screen_box, + capture_window_vt, ) if t.TYPE_CHECKING: @@ -474,3 +478,230 @@ async def _exercise() -> None: await w2 asyncio.run(_exercise()) + + +def test_window_capture_vt_splits_border_status_zoom_and_errors( + session: Session, +) -> None: + """``Window.capture_vt`` composites split borders, status labels, and zoom.""" + pytest.importorskip("libvt") + from libvt.exc import ScreenAssertionError + from libvt.style import AnsiColor + + py = shlex.quote(sys.executable) + + def _hold_cmd(payload: bytes, *, wait_go: bool = False) -> str: + hex_data = payload.hex() + pre = ( + "import tty; tty.setraw(0); " + "sys.stdout.buffer.write(b'BOOT'); sys.stdout.buffer.flush(); " + "sys.stdin.buffer.read(1); " + "sys.stdout.buffer.write(b'\\x1b[2J\\x1b[3J\\x1b[H'); " + if wait_go + else "" + ) + script = ( + "import sys; " + + pre + + f"sys.stdout.buffer.write(bytes.fromhex('{hex_data}')); " + "sys.stdout.buffer.flush(); sys.stdin.buffer.read(1)" + ) + return f"{py} -u -c {shlex.quote(script)}" + + win = session.new_window( + window_name="vt-win-cap", + window_shell=_hold_cmd( + b"\x1b]2;api\x07S0\r\nH0\r\nH1\r\nH2\r\n\x1b[1;32m200 OK\x1b[0m\r\n" + + "日本".encode(), + wait_go=True, + ), + ) + p_left = win.active_pane + assert p_left is not None + retry_until(lambda: "BOOT" in "\n".join(p_left.capture_pane())) + win.resize(height=6, width=23) + win.set_option("pane-border-status", "top") + win.set_option("pane-border-format", " #{pane_index}:#{pane_title} ") + win.set_option("pane-border-style", "fg=blue") + win.set_option("pane-active-border-style", "fg=green") + p_left.send_keys("g", enter=False, literal=True) + p_top_right = win.split( + direction=PaneDirection.Right, + attach=True, + shell=_hold_cmd(b"\x1b]2;db\x07\x1b[2J\x1b[H\x1b[36mpg:ready\x1b[0m"), + size=11, + ) + p_bot_right = win.split( + direction=PaneDirection.Below, + attach=True, + shell=_hold_cmd(b"\x1b]2;job\x07\x1b[2J\x1b[Hq=0"), + size=2, + ) + + def _all_rendered() -> bool: + snap = win.capture_vt().snapshot + txt = snap.text + return ( + "0:api" in txt + and "1:db" in txt + and "2:job" in txt + and "日本" in txt + and "pg:ready" in txt + and "q=0" in txt + ) + + retry_until(_all_rendered) + + res = win.capture_vt(history_lines=2) + assert res.zoomed is False + assert res.layout_stable is True + assert len(res.panes) == 3 + assert p_left.pane_id is not None + assert p_top_right.pane_id is not None + assert p_bot_right.pane_id is not None + assert len(res.panes[p_left.pane_id].snapshot.history) >= 1 + + snap = res.snapshot + assert (snap.rows, snap.cols) == (6, 23) + assert snap[0, 11].text == "┬" + assert snap[3, 11].text == "├" + assert snap[3, 11].style.fg == AnsiColor.GREEN + assert snap[0, 0].style.fg == AnsiColor.BLUE + assert snap[1, 12].style.fg == AnsiColor.CYAN + assert snap.cursor.visible is True + assert (snap.cursor.row, snap.cursor.col) == (4, 15) + assert res.panes[p_left.pane_id].terminal.profile.identity.xtversion.startswith( + "tmux " + ) + + p_left.select() + switched_res = win.capture_vt() + assert switched_res.layout_stable is True + assert (switched_res.snapshot.cursor.row, switched_res.snapshot.cursor.col) == ( + 5, + 4, + ) + p_bot_right.select() + + assert_window_screen(win, "\n".join(snap.lines), cursor=(4, 15)) + assert_window_screen_box( + res, + """ + ┌───────────────────────┐ + │── 0:api ──┬── 1:db ───│ + │H0 │pg:ready │ + │H1 │ │ + │H2 ├── 2:job ──│ + │200 OK │q=0 │ + │日本 │ │ + └───────────────────────┘ + """, + cursor=(4, 15), + ) + + with pytest.raises(ScreenAssertionError, match="Screen state mismatch"): + assert_window_screen_box( + res, + """ + ┌───────────────────────┐ + │── WRONG ──┬── 1:db ───│ + │H0 │pg:ready │ + │H1 │ │ + │H2 ├── 2:job ──│ + │200 OK │q=0 │ + │日本 │ │ + └───────────────────────┘ + """, + ) + + win.cmd("resize-pane", "-Z") + zoom_res = capture_window_vt(win) + assert zoom_res.zoomed is True + assert (zoom_res.snapshot.rows, zoom_res.snapshot.cols) == (6, 23) + assert "q=0" in zoom_res.snapshot.text + assert "pg:ready" not in zoom_res.snapshot.text + win.cmd("resize-pane", "-Z") + + with pytest.raises(ValueError, match="history_lines must be >= 0"): + capture_window_vt(win, history_lines=-1) + with pytest.raises(TypeError, match="history_lines must be int or None"): + capture_window_vt(win, history_lines=True) + + win.kill() + with pytest.raises(exc.LibTmuxException): + win.capture_vt() + + +def test_vt_observer_snapshot_window_live_parity( + session: Session, + vt_observer: VtObserverFactory, +) -> None: + """``VtSessionObserver.snapshot_window`` matches ``Window.capture_vt``.""" + pytest.importorskip("libvt") + from libvt.testing import serialize_vt_snapshot + + py = shlex.quote(sys.executable) + + def _hold_cmd(payload: bytes) -> str: + hex_data = payload.hex() + script = ( + "import sys; " + f"sys.stdout.buffer.write(bytes.fromhex('{hex_data}')); " + "sys.stdout.buffer.flush(); sys.stdin.buffer.read(1)" + ) + return f"{py} -u -c {shlex.quote(script)}" + + win = session.new_window( + window_name="vt-obs-win", + window_shell=_hold_cmd(b"\x1b[1;35mLEFT_OK\x1b[0m\r\nrow2"), + ) + win.resize(height=3, width=19) + win.set_option("pane-border-style", "default") + win.set_option("pane-active-border-style", "fg=green") + p1 = win.active_pane + assert p1 is not None + p2 = win.split( + direction=PaneDirection.Right, + attach=True, + shell=_hold_cmd(b"\x1b[33mRIGHT\x1b[0m\r\n" + "日本".encode()), + size=9, + ) + + retry_until( + lambda: ( + "row2" in win.capture_vt().snapshot.text + and "日本" in win.capture_vt().snapshot.text + ) + ) + + async def _exercise() -> None: + async with vt_observer(history_lines=0) as obs: + h1 = await obs.watch_pane(p1) + await h1.wait_until("row2") + + # p2 is attached automatically when watch_missing=True. + live_snap = await obs.snapshot_window(win) + assert p2.pane_id in obs._handles + oneshot_snap = win.capture_vt().snapshot + + assert live_snap.display_lines == oneshot_snap.display_lines + assert (live_snap.cursor.row, live_snap.cursor.col) == ( + oneshot_snap.cursor.row, + oneshot_snap.cursor.col, + ) + assert serialize_vt_snapshot(live_snap) == serialize_vt_snapshot( + oneshot_snap + ) + + with pytest.raises(ValueError, match="window_id must be"): + await obs.snapshot_window("not-a-window-id") + with pytest.raises(exc.LibTmuxException): + await obs.snapshot_window("@99999", timeout=1.5) + + # Observer stays usable after a failed window query. + again = await obs.snapshot_window(win) + assert again.display_lines == oneshot_snap.display_lines + + asyncio.run(_exercise()) + for p in (p1, p2): + p.send_vt_input("enter") diff --git a/uv.lock b/uv.lock index a6d7ecde9a..b197c09985 100644 --- a/uv.lock +++ b/uv.lock @@ -577,7 +577,7 @@ testing = [ ] [package.metadata] -requires-dist = [{ name = "libvt", marker = "python_full_version >= '3.12' and extra == 'vt'", specifier = ">=0.0.1a4,<0.1" }] +requires-dist = [{ name = "libvt", marker = "python_full_version >= '3.12' and extra == 'vt'", specifier = ">=0.0.1a5,<0.1" }] provides-extras = ["vt"] [package.metadata.requires-dev] @@ -624,11 +624,11 @@ testing = [ [[package]] name = "libvt" -version = "0.0.1a4" +version = "0.0.1a5" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2f/e3/2aef4116c9773807fa09e5bc716a18a2d449e3ae5c4c5767b1b524021330/libvt-0.0.1a4.tar.gz", hash = "sha256:35c879576ca71e65d55d246e62e212fe910fc4918ed0ba1783c713617fccabde", size = 355784, upload-time = "2026-11-29T22:17:39.524Z" } +sdist = { url = "https://files.pythonhosted.org/packages/bb/96/2eb9fb46534a28d767fe67c22df198e39f0634a09c90395f38f825754f8b/libvt-0.0.1a5.tar.gz", hash = "sha256:704af5c37012783a96203fdbf346b60ebe8e3792ee7d5abfc37e2e63cf83c088", size = 401839, upload-time = "2026-12-01T03:22:55.088Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/3e/94566d78ca6923f4d8a8de31b64bfff9c9bc716c51e6a1ebd1f496d883bb/libvt-0.0.1a4-py3-none-any.whl", hash = "sha256:ede0a8484b3d617d8dd75f22ab3e0f479d1086ae5beebd63c68c77223f42ce90", size = 217260, upload-time = "2026-11-29T22:17:38.109Z" }, + { url = "https://files.pythonhosted.org/packages/86/f8/e7c31defff03fec80cc23f22a8d22d4483d3da5816a64954e9105d8ce803/libvt-0.0.1a5-py3-none-any.whl", hash = "sha256:c161e07791fb84acee3491f4b1e9646d15ba1dea8d2c285f1b9f6771799a0fe5", size = 253987, upload-time = "2026-12-01T03:22:53.849Z" }, ] [[package]]