diff --git a/AGENTS.md b/AGENTS.md index 4704350..58cc611 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ what was asked for. | `src/libvt/parser.py`, `modes.py`, `style.py`, `config.py`, `profiles.py` | VT500 byte parser, CSI subparameters, modes, SGR styles, `Profile` / `Policy` / `Limits`, and host presets | | `src/libvt/_ucd.py`, `_grid.py`, `screen.py`, `terminal.py` | Unicode 17 width/clustering tables, packed viewport & RLE scrollback rows, `Screen` / `ScreenSet`, `Terminal`, `Snapshot`, and `Formatter` | | `src/libvt/status.py`, `events.py`, `input.py`, `codec.py` | Rex `OSC 7501` program status store, open `Event` hierarchy, mode-aware input encoders, and cold-path VT sequence explainer | -| `src/libvt/graphics.py`, `contrib/tmux/` | Zero-dependency `SIXEL` / Kitty `APC G` placement tracker and decoupled `tmux` `profile` / `capture` / `control` modules | +| `src/libvt/graphics.py`, `contrib/tmux/` | Zero-dependency `SIXEL` / Kitty `APC G` placement tracker and decoupled `tmux` `profile` / `capture` / `window` / `control` modules | | `src/libvt/aio.py`, `__main__.py`, `exc.py` | `AsyncTerminalStream`, POSIX `open_pty()`, `python -m libvt` CLI (`explain`, `render`, `strip`), and exceptions | | `src/libvt/testing.py` | Zero-dependency `assert_screen`, `assert_screen_box`, `FlightRecorder` diagnostics, and boxed VT + `SGR` `vt_screen` / `serialize_vt_snapshot` / `format_vt_diff_lines` utilities | | `src/libvt/pytest_plugin.py` | Import-light `pytest11` plugin (`libvt[pytest]`): `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and `vt_pty` | diff --git a/CHANGES b/CHANGES index c8ade4d..4ec121a 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,22 @@ _Notes on the upcoming release will go here._ +### What's new + +#### Compose a screen from snapshots and text (#137) + +Use {meth}`~libvt.screen.Screen.blit` to copy a rectangular region from a +screen or snapshot, retaining cell styles, hyperlinks, and written spaces. +Place text by display column with {meth}`~libvt.screen.Screen.put_text`, +then freeze the result with {meth}`~libvt.screen.Screen.snapshot`. + +#### Capture a split `tmux` window as one snapshot (#137) + +Capture a detached window from `tmux` command output, or combine existing +pane snapshots with {func}`~libvt.contrib.tmux.window.composite_tmux_window`. +The snapshot includes split borders, pane border labels, and the active pane's +cursor. A zoomed pane fills the window. + ## libvt 0.0.1a4 (2026-11-29) `libvt` 0.0.1a4 adds tool-agnostic boxed VT and `SGR` snapshot serialization, diff --git a/docs/api/contrib_tmux.md b/docs/api/contrib_tmux.md index 4608af4..367dc24 100644 --- a/docs/api/contrib_tmux.md +++ b/docs/api/contrib_tmux.md @@ -30,6 +30,21 @@ Accepted input representation for ``tmux capture-pane`` lines or raw text. ``` +## `libvt.contrib.tmux.window` + +```{eval-rst} +.. automodule:: libvt.contrib.tmux.window + :members: + :no-private-members: + :exclude-members: TmuxPaneSource + +.. py:type:: TmuxPaneSource + :module: libvt.contrib.tmux.window + :canonical: Snapshot | Screen | Terminal | TmuxCaptureResult | object + + Accepted per-pane state source for :func:`~libvt.contrib.tmux.window.composite_tmux_window`. +``` + ## `libvt.contrib.tmux.control` ```{eval-rst} diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py index d748276..498243a 100644 --- a/src/libvt/_grid.py +++ b/src/libvt/_grid.py @@ -227,10 +227,15 @@ class FrozenRow: cells: tuple[str, ...] | None = None wrapped: bool = False + @property + def text_used(self) -> int: + """Return written-text column high-water mark.""" + return len(self.cells) if self.cells is not None else len(self.text) + @property def used(self) -> int: """Return count of written columns in this sealed row.""" - text_cols = len(self.cells) if self.cells is not None else len(self.text) + text_cols = self.text_used run_end = self.runs[-1][0] if self.runs else 0 ext_end = (self.exts[-1][0] + 1) if self.exts else 0 return max(text_cols, run_end, ext_end) @@ -497,10 +502,12 @@ def _heal_wide_boundary(self, col: int) -> None: if col < 0 or col >= cols: return role = raw_width_bits(self._attrs[col]) + healed_pair_start = -1 healed_pair_end = -1 if role == int(WidthRole.WIDE): self._chars[col] = " " self._attrs[col] &= _WIDTH_CLEAR_MASK + healed_pair_start = col healed_pair_end = col + 1 if col + 1 < cols: self._chars[col + 1] = " " @@ -509,14 +516,15 @@ def _heal_wide_boundary(self, col: int) -> None: elif role == int(WidthRole.SPACER_TAIL): self._chars[col] = " " self._attrs[col] &= _WIDTH_CLEAR_MASK + healed_pair_start = col healed_pair_end = col + 1 if col - 1 >= 0: self._chars[col - 1] = " " self._attrs[col - 1] &= _WIDTH_CLEAR_MASK + healed_pair_start = col - 1 if healed_pair_end != -1: if self._text_used == healed_pair_end: - while self._text_used > 0 and self._chars[self._text_used - 1] == " ": - self._text_used -= 1 + self._text_used = healed_pair_start while ( self._used > self._text_used and self._chars[self._used - 1] == " " @@ -627,6 +635,134 @@ def copy_region_from(self, src_row: _Row, left: int, right: int) -> None: self._used = max(self._used, self._text_used) self.stamp() + def blit_from( + self, + src_row: RowLike, + *, + dst_col: int, + src_col: int, + width: int, + ) -> None: + """Copy *width* cells from ``src_row[src_col..]`` into ``self[dst_col..]``.""" + if width <= 0: + return + if src_row is self: + src_row = self.clone() + dst_end = dst_col + width + if self._has_wide and self._attrs is not None: + if raw_width_bits(self._attrs[dst_col]) == int(WidthRole.SPACER_TAIL): + self._heal_wide_boundary(dst_col) + if raw_width_bits(self._attrs[dst_end - 1]) == int(WidthRole.WIDE): + self._heal_wide_boundary(dst_end - 1) + + old_text_used = self._text_used + old_used = self._used + src_end = src_col + width + + if ( + isinstance(src_row, _Row) + and not src_row._has_wide + and src_end <= len(src_row._chars) + ): + self._chars[dst_col:dst_end] = src_row._chars[src_col:src_end] + if src_row._attrs is None: + s_u = src_row._uniform_attr + if self._attrs is None: + if s_u != self._uniform_attr: + attrs = self._ensure_attrs() + attrs[dst_col:dst_end] = array.array("Q", [s_u]) * width + else: + self._attrs[dst_col:dst_end] = array.array("Q", [s_u]) * width + else: + attrs = self._ensure_attrs() + attrs[dst_col:dst_end] = src_row._attrs[src_col:src_end] + + if self._ext: + for dc in range(dst_col, dst_end): + self._ext.pop(dc, None) + if src_row._ext: + if self._ext is None: + self._ext = {} + shift = dst_col - src_col + for sc, ce in src_row._ext.items(): + if src_col <= sc < src_end: + self._ext[sc + shift] = ce + if self._ext is not None and not self._ext: + self._ext = None + else: + src_cols = src_row.cols + for j in range(width): + sc = src_col + j + dc = dst_col + j + if sc < 0 or sc >= src_cols: + self._set_raw(dc, " ", 0, WidthRole.NARROW, None) + continue + ch = src_row.char_at(sc) + word = src_row.attr_at(sc) + ext = src_row.ext_at(sc) + rb = raw_width_bits(word) + if rb == int(WidthRole.SPACER_HEAD): + ch = " " + rb = int(WidthRole.NARROW) + elif rb == int(WidthRole.SPACER_TAIL): + if ( + j == 0 + or sc - 1 < 0 + or raw_width_bits(src_row.attr_at(sc - 1)) + != int(WidthRole.WIDE) + ): + ch = " " + rb = int(WidthRole.NARROW) + elif rb == int(WidthRole.WIDE) and ( + j == width - 1 + or sc + 1 >= src_cols + or raw_width_bits(src_row.attr_at(sc + 1)) + != int(WidthRole.SPACER_TAIL) + ): + ch = " " + rb = int(WidthRole.NARROW) + base = word & _PEN_BASE_MASK + self._set_raw(dc, ch, base, WidthRole(rb), ext) + + src_t = min(max(src_row.text_used, src_col), src_end) + while src_t > src_col and raw_width_bits(src_row.attr_at(src_t - 1)) == int( + WidthRole.SPACER_HEAD + ): + src_t -= 1 + if ( + src_t == src_end + and src_t > src_col + and raw_width_bits(src_row.attr_at(src_t - 1)) == int(WidthRole.WIDE) + ): + src_t -= 1 + if src_t == src_col + 1 and raw_width_bits(src_row.attr_at(src_col)) == int( + WidthRole.SPACER_TAIL + ): + src_t = src_col + + if old_text_used > dst_end: + new_t = old_text_used + elif src_t > src_col: + new_t = dst_col + (src_t - src_col) + else: + new_t = min(old_text_used, dst_col) + self._text_used = new_t + + floor_u = max(min(old_used, dst_col), new_t) + if old_used > dst_end: + self._used = max(old_used, new_t) + else: + new_u = max(dst_end, floor_u) + while ( + new_u > floor_u + and self._chars[new_u - 1] == " " + and self.attr_at(new_u - 1) == 0 + and self.ext_at(new_u - 1) is None + ): + new_u -= 1 + self._used = new_u + self.stamp() + def write_narrow( self, col: int, diff --git a/src/libvt/contrib/tmux/__init__.py b/src/libvt/contrib/tmux/__init__.py index 05b5ae7..56839a4 100644 --- a/src/libvt/contrib/tmux/__init__.py +++ b/src/libvt/contrib/tmux/__init__.py @@ -1,4 +1,4 @@ -"""Decoupled ``tmux`` profile, ``capture-pane``, and control-mode integration.""" +"""Decoupled ``tmux`` profile, ``capture-pane``, window, and control-mode adapters.""" from __future__ import annotations @@ -41,6 +41,20 @@ parse_tmux_version, tmux_profile, ) + from libvt.contrib.tmux.window import ( + TMUX_WINDOW_METADATA_FORMAT, + TMUX_WINDOW_PANE_FORMAT, + TmuxPaneSource, + TmuxWindowCaptureCommand, + TmuxWindowCaptureResult, + TmuxWindowLayout, + TmuxWindowListCommand, + TmuxWindowPane, + build_tmux_window_capture_command, + build_tmux_window_list_command, + composite_tmux_window, + parse_tmux_window_layout, + ) _LAZY_EXPORTS: dict[str, tuple[str, str]] = { "CaptureCompleteness": ("libvt.contrib.tmux.capture", "CaptureCompleteness"), @@ -49,6 +63,14 @@ "TMUX_METADATA_FORMAT": ("libvt.contrib.tmux.capture", "TMUX_METADATA_FORMAT"), "TMUX_OBSERVER_POLICY": ("libvt.contrib.tmux.profile", "TMUX_OBSERVER_POLICY"), "TMUX_PROFILE": ("libvt.contrib.tmux.profile", "TMUX_PROFILE"), + "TMUX_WINDOW_METADATA_FORMAT": ( + "libvt.contrib.tmux.window", + "TMUX_WINDOW_METADATA_FORMAT", + ), + "TMUX_WINDOW_PANE_FORMAT": ( + "libvt.contrib.tmux.window", + "TMUX_WINDOW_PANE_FORMAT", + ), "TmuxAttachPhase": ("libvt.contrib.tmux.control", "TmuxAttachPhase"), "TmuxCaptureCommand": ("libvt.contrib.tmux.capture", "TmuxCaptureCommand"), "TmuxCaptureResult": ("libvt.contrib.tmux.capture", "TmuxCaptureResult"), @@ -63,19 +85,44 @@ "TmuxNotification": ("libvt.contrib.tmux.control", "TmuxNotification"), "TmuxOutput": ("libvt.contrib.tmux.control", "TmuxOutput"), "TmuxPaneMetadata": ("libvt.contrib.tmux.capture", "TmuxPaneMetadata"), + "TmuxPaneSource": ("libvt.contrib.tmux.window", "TmuxPaneSource"), "TmuxPaneSync": ("libvt.contrib.tmux.control", "TmuxPaneSync"), "TmuxPause": ("libvt.contrib.tmux.control", "TmuxPause"), "TmuxSubscriptionChanged": ( "libvt.contrib.tmux.control", "TmuxSubscriptionChanged", ), + "TmuxWindowCaptureCommand": ( + "libvt.contrib.tmux.window", + "TmuxWindowCaptureCommand", + ), + "TmuxWindowCaptureResult": ( + "libvt.contrib.tmux.window", + "TmuxWindowCaptureResult", + ), + "TmuxWindowLayout": ("libvt.contrib.tmux.window", "TmuxWindowLayout"), + "TmuxWindowListCommand": ("libvt.contrib.tmux.window", "TmuxWindowListCommand"), + "TmuxWindowPane": ("libvt.contrib.tmux.window", "TmuxWindowPane"), "build_tmux_capture_command": ( "libvt.contrib.tmux.capture", "build_tmux_capture_command", ), + "build_tmux_window_capture_command": ( + "libvt.contrib.tmux.window", + "build_tmux_window_capture_command", + ), + "build_tmux_window_list_command": ( + "libvt.contrib.tmux.window", + "build_tmux_window_list_command", + ), + "composite_tmux_window": ("libvt.contrib.tmux.window", "composite_tmux_window"), "decode_tmux_capture": ("libvt.contrib.tmux.capture", "decode_tmux_capture"), "parse_flagged_line": ("libvt.contrib.tmux.capture", "parse_flagged_line"), "parse_tmux_version": ("libvt.contrib.tmux.profile", "parse_tmux_version"), + "parse_tmux_window_layout": ( + "libvt.contrib.tmux.window", + "parse_tmux_window_layout", + ), "tmux_profile": ("libvt.contrib.tmux.profile", "tmux_profile"), "unescape_tmux_control_output": ( "libvt.contrib.tmux.control", @@ -88,6 +135,8 @@ "TMUX_METADATA_FORMAT", "TMUX_OBSERVER_POLICY", "TMUX_PROFILE", + "TMUX_WINDOW_METADATA_FORMAT", + "TMUX_WINDOW_PANE_FORMAT", "CaptureCompleteness", "CaptureInput", "TmuxAttachPhase", @@ -104,13 +153,23 @@ "TmuxNotification", "TmuxOutput", "TmuxPaneMetadata", + "TmuxPaneSource", "TmuxPaneSync", "TmuxPause", "TmuxSubscriptionChanged", + "TmuxWindowCaptureCommand", + "TmuxWindowCaptureResult", + "TmuxWindowLayout", + "TmuxWindowListCommand", + "TmuxWindowPane", "build_tmux_capture_command", + "build_tmux_window_capture_command", + "build_tmux_window_list_command", + "composite_tmux_window", "decode_tmux_capture", "parse_flagged_line", "parse_tmux_version", + "parse_tmux_window_layout", "tmux_profile", "unescape_tmux_control_output", ] diff --git a/src/libvt/contrib/tmux/window.py b/src/libvt/contrib/tmux/window.py new file mode 100644 index 0000000..caaf74e --- /dev/null +++ b/src/libvt/contrib/tmux/window.py @@ -0,0 +1,3156 @@ +"""Multi-pane ``tmux`` window layout, scene compositing, and capture bundles.""" + +from __future__ import annotations + +import collections.abc +import dataclasses +import enum +import json +import math +import re +import secrets +import types +import typing as t +from dataclasses import dataclass, field + +from libvt._ucd import display_width +from libvt.config import DEFAULT_LIMITS, Limits, Policy, Profile +from libvt.contrib.tmux.capture import ( + _TMUX_MAX_DIM, + _TMUX_UINT_MAX, + CaptureInput, + TmuxCaptureCommand, + TmuxCaptureResult, + _escape_tmux_arg, + _opt_bool, + _opt_int, + _split_capture_lines, + _validate_history_lines, + build_tmux_capture_command, +) +from libvt.contrib.tmux.profile import ( + TMUX_CAPTURE_POLICY, + TMUX_PROFILE, + parse_tmux_version, + tmux_profile, +) +from libvt.modes import Mode +from libvt.parser import _parse_ascii_uint +from libvt.screen import Cursor, Screen +from libvt.style import ( + DEFAULT_STYLE, + AnsiColor, + Color, + Hyperlink, + IndexedColor, + RgbColor, + Style, + UnderlineStyle, +) +from libvt.terminal import _DEC_SPECIAL_GRAPHICS, Snapshot, Terminal + +_THEME_SLOTS: tuple[tuple[str, str, AnsiColor], ...] = ( + ("themeblack", "black", AnsiColor.BLACK), + ("themewhite", "white", AnsiColor.WHITE), + ("themelightgrey", "light-grey", AnsiColor.WHITE), + ("themedarkgrey", "dark-grey", AnsiColor.BLACK), + ("themegreen", "green", AnsiColor.GREEN), + ("themeyellow", "yellow", AnsiColor.YELLOW), + ("themered", "red", AnsiColor.RED), + ("themeblue", "blue", AnsiColor.BLUE), + ("themecyan", "cyan", AnsiColor.CYAN), + ("thememagenta", "magenta", AnsiColor.MAGENTA), +) + +_DEFAULT_THEME_COLORS: collections.abc.Mapping[str, Color] = types.MappingProxyType( + {name: term_col for name, _, term_col in _THEME_SLOTS}, +) + +#: Format string passed to ``tmux display-message -p`` for window layout state. +TMUX_WINDOW_METADATA_FORMAT: str = ( + "#{window_id}\t#{window_width}\t#{window_height}\t#{window_zoomed_flag}\t" + "#{pane-border-lines}\t#{pane-border-status}\t#{pane-border-indicators}\t" + "#{E:pane-border-style}\t#{window_layout}\t" + "#{theme}\t#{client_theme}\t#{client_colours}\t#{client_termname}\t" + + "\t".join(f"#{{E:dark-theme-{opt}}}" for _, opt, _ in _THEME_SLOTS) + + "\t" + + "\t".join(f"#{{E:light-theme-{opt}}}" for _, opt, _ in _THEME_SLOTS) +) + +#: Format string passed to ``tmux list-panes -F`` for per-pane geometry & styles. +TMUX_WINDOW_PANE_FORMAT: str = ( + "#{pane_id}\t#{pane_index}\t#{pane_left}\t#{pane_top}\t" + "#{pane_width}\t#{pane_height}\t#{pane_active}\t#{?pane_marked,1,0}\t" + "#{?pane_floating_flag,1,0}\t#{pane-border-lines}\t#{pane-border-status}\t" + "#{E:pane-border-style}\t#{E:pane-active-border-style}\t" + "#{E:pane-border-format}" +) + +_WINDOW_NONCE_RE = re.compile(r"^[0-9A-Za-z_-]{8,96}\Z", re.ASCII) +_HEX6_RE = re.compile(r"^#[0-9A-Fa-f]{6}\Z", re.ASCII) +_STYLE_DELIM_RE = re.compile(r"[ ,\n]+") +_V1_ROOT_RE = re.compile( + r"^(?:[0-9a-fA-F]{4},)?(?P\d+)x(?P\d+),\d+,\d+", + re.ASCII, +) +_V1_LEAF_RE = re.compile( + r"(?P\d+)x(?P\d+),(?P-?\d+),(?P-?\d+),(?P\d+)(?:(?=[,}\]])|\Z)", + re.ASCII, +) + +_ANSI_COLOR_NAMES: dict[str, AnsiColor] = { + "0": AnsiColor.BLACK, + "1": AnsiColor.RED, + "2": AnsiColor.GREEN, + "3": AnsiColor.YELLOW, + "4": AnsiColor.BLUE, + "5": AnsiColor.MAGENTA, + "6": AnsiColor.CYAN, + "7": AnsiColor.WHITE, + "90": AnsiColor.BRIGHT_BLACK, + "91": AnsiColor.BRIGHT_RED, + "92": AnsiColor.BRIGHT_GREEN, + "93": AnsiColor.BRIGHT_YELLOW, + "94": AnsiColor.BRIGHT_BLUE, + "95": AnsiColor.BRIGHT_MAGENTA, + "96": AnsiColor.BRIGHT_CYAN, + "97": AnsiColor.BRIGHT_WHITE, + "black": AnsiColor.BLACK, + "red": AnsiColor.RED, + "green": AnsiColor.GREEN, + "yellow": AnsiColor.YELLOW, + "blue": AnsiColor.BLUE, + "magenta": AnsiColor.MAGENTA, + "cyan": AnsiColor.CYAN, + "white": AnsiColor.WHITE, + "brightblack": AnsiColor.BRIGHT_BLACK, + "brightred": AnsiColor.BRIGHT_RED, + "brightgreen": AnsiColor.BRIGHT_GREEN, + "brightyellow": AnsiColor.BRIGHT_YELLOW, + "brightblue": AnsiColor.BRIGHT_BLUE, + "brightmagenta": AnsiColor.BRIGHT_MAGENTA, + "brightcyan": AnsiColor.BRIGHT_CYAN, + "brightwhite": AnsiColor.BRIGHT_WHITE, +} + +# 256-to-16 ANSI palette quantization table from ISC-licensed tmux colour.c. +_COLOUR_256_TO_16: bytes = bytes( + ( + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 0, + 4, + 4, + 4, + 12, + 12, + 2, + 6, + 4, + 4, + 12, + 12, + 2, + 2, + 6, + 4, + 12, + 12, + 2, + 2, + 2, + 6, + 12, + 12, + 10, + 10, + 10, + 10, + 14, + 12, + 10, + 10, + 10, + 10, + 10, + 14, + 1, + 5, + 4, + 4, + 12, + 12, + 3, + 8, + 4, + 4, + 12, + 12, + 2, + 2, + 6, + 4, + 12, + 12, + 2, + 2, + 2, + 6, + 12, + 12, + 10, + 10, + 10, + 10, + 14, + 12, + 10, + 10, + 10, + 10, + 10, + 14, + 1, + 1, + 5, + 4, + 12, + 12, + 1, + 1, + 5, + 4, + 12, + 12, + 3, + 3, + 8, + 4, + 12, + 12, + 2, + 2, + 2, + 6, + 12, + 12, + 10, + 10, + 10, + 10, + 14, + 12, + 10, + 10, + 10, + 10, + 10, + 14, + 1, + 1, + 1, + 5, + 12, + 12, + 1, + 1, + 1, + 5, + 12, + 12, + 1, + 1, + 1, + 5, + 12, + 12, + 3, + 3, + 3, + 7, + 12, + 12, + 10, + 10, + 10, + 10, + 14, + 12, + 10, + 10, + 10, + 10, + 10, + 14, + 9, + 9, + 9, + 9, + 13, + 12, + 9, + 9, + 9, + 9, + 13, + 12, + 9, + 9, + 9, + 9, + 13, + 12, + 9, + 9, + 9, + 9, + 13, + 12, + 11, + 11, + 11, + 11, + 7, + 12, + 10, + 10, + 10, + 10, + 10, + 14, + 9, + 9, + 9, + 9, + 9, + 13, + 9, + 9, + 9, + 9, + 9, + 13, + 9, + 9, + 9, + 9, + 9, + 13, + 9, + 9, + 9, + 9, + 9, + 13, + 9, + 9, + 9, + 9, + 9, + 13, + 11, + 11, + 11, + 11, + 11, + 15, + 0, + 0, + 0, + 0, + 0, + 0, + 8, + 8, + 8, + 8, + 8, + 8, + 7, + 7, + 7, + 7, + 7, + 7, + 15, + 15, + 15, + 15, + 15, + 15, + ) +) + +# Named X11 RGB table from ISC-licensed tmux colour.c colour_byname. +_X11_COLOR_SPEC: str = ( + "alice blue:f0f8ff|aliceblue:f0f8ff|antique white:faebd7|" + "antiquewhite:faebd7|antiquewhite1:ffefdb|antiquewhite2:eedfcc|" + "antiquewhite3:cdc0b0|antiquewhite4:8b8378|aqua:00ffff|aquamarine:7fffd4|" + "aquamarine1:7fffd4|aquamarine2:76eec6|aquamarine3:66cdaa|" + "aquamarine4:458b74|azure:f0ffff|azure1:f0ffff|azure2:e0eeee|" + "azure3:c1cdcd|azure4:838b8b|beige:f5f5dc|bisque:ffe4c4|bisque1:ffe4c4|" + "bisque2:eed5b7|bisque3:cdb79e|bisque4:8b7d6b|black:000000|" + "blanched almond:ffebcd|blanchedalmond:ffebcd|blue:0000ff|" + "blue violet:8a2be2|blue1:0000ff|blue2:0000ee|blue3:0000cd|blue4:00008b|" + "blueviolet:8a2be2|brown:a52a2a|brown1:ff4040|brown2:ee3b3b|brown3:cd3333|" + "brown4:8b2323|burlywood:deb887|burlywood1:ffd39b|burlywood2:eec591|" + "burlywood3:cdaa7d|burlywood4:8b7355|cadet blue:5f9ea0|cadetblue:5f9ea0|" + "cadetblue1:98f5ff|cadetblue2:8ee5ee|cadetblue3:7ac5cd|cadetblue4:53868b|" + "chartreuse:7fff00|chartreuse1:7fff00|chartreuse2:76ee00|" + "chartreuse3:66cd00|chartreuse4:458b00|chocolate:d2691e|chocolate1:ff7f24|" + "chocolate2:ee7621|chocolate3:cd661d|chocolate4:8b4513|coral:ff7f50|" + "coral1:ff7256|coral2:ee6a50|coral3:cd5b45|coral4:8b3e2f|" + "cornflower blue:6495ed|cornflowerblue:6495ed|cornsilk:fff8dc|" + "cornsilk1:fff8dc|cornsilk2:eee8cd|cornsilk3:cdc8b1|cornsilk4:8b8878|" + "crimson:dc143c|cyan:00ffff|cyan1:00ffff|cyan2:00eeee|cyan3:00cdcd|" + "cyan4:008b8b|dark blue:00008b|dark cyan:008b8b|dark goldenrod:b8860b|" + "dark gray:a9a9a9|dark green:006400|dark grey:a9a9a9|dark khaki:bdb76b|" + "dark magenta:8b008b|dark olive green:556b2f|dark orange:ff8c00|" + "dark orchid:9932cc|dark red:8b0000|dark salmon:e9967a|" + "dark sea green:8fbc8f|dark slate blue:483d8b|dark slate gray:2f4f4f|" + "dark slate grey:2f4f4f|dark turquoise:00ced1|dark violet:9400d3|" + "darkblue:00008b|darkcyan:008b8b|darkgoldenrod:b8860b|" + "darkgoldenrod1:ffb90f|darkgoldenrod2:eead0e|darkgoldenrod3:cd950c|" + "darkgoldenrod4:8b6508|darkgray:a9a9a9|darkgreen:006400|darkgrey:a9a9a9|" + "darkkhaki:bdb76b|darkmagenta:8b008b|darkolivegreen:556b2f|" + "darkolivegreen1:caff70|darkolivegreen2:bcee68|darkolivegreen3:a2cd5a|" + "darkolivegreen4:6e8b3d|darkorange:ff8c00|darkorange1:ff7f00|" + "darkorange2:ee7600|darkorange3:cd6600|darkorange4:8b4500|" + "darkorchid:9932cc|darkorchid1:bf3eff|darkorchid2:b23aee|" + "darkorchid3:9a32cd|darkorchid4:68228b|darkred:8b0000|darksalmon:e9967a|" + "darkseagreen:8fbc8f|darkseagreen1:c1ffc1|darkseagreen2:b4eeb4|" + "darkseagreen3:9bcd9b|darkseagreen4:698b69|darkslateblue:483d8b|" + "darkslategray:2f4f4f|darkslategray1:97ffff|darkslategray2:8deeee|" + "darkslategray3:79cdcd|darkslategray4:528b8b|darkslategrey:2f4f4f|" + "darkturquoise:00ced1|darkviolet:9400d3|deep pink:ff1493|" + "deep sky blue:00bfff|deeppink:ff1493|deeppink1:ff1493|deeppink2:ee1289|" + "deeppink3:cd1076|deeppink4:8b0a50|deepskyblue:00bfff|deepskyblue1:00bfff|" + "deepskyblue2:00b2ee|deepskyblue3:009acd|deepskyblue4:00688b|" + "dim gray:696969|dim grey:696969|dimgray:696969|dimgrey:696969|" + "dodger blue:1e90ff|dodgerblue:1e90ff|dodgerblue1:1e90ff|dodgerblue2:1c86ee|" + "dodgerblue3:1874cd|dodgerblue4:104e8b|firebrick:b22222|firebrick1:ff3030|" + "firebrick2:ee2c2c|firebrick3:cd2626|firebrick4:8b1a1a|floral white:fffaf0|" + "floralwhite:fffaf0|forest green:228b22|forestgreen:228b22|fuchsia:ff00ff|" + "gainsboro:dcdcdc|ghost white:f8f8ff|ghostwhite:f8f8ff|gold:ffd700|" + "gold1:ffd700|gold2:eec900|gold3:cdad00|gold4:8b7500|goldenrod:daa520|" + "goldenrod1:ffc125|goldenrod2:eeb422|goldenrod3:cd9b1d|goldenrod4:8b6914|" + "green:00ff00|green yellow:adff2f|green1:00ff00|green2:00ee00|green3:00cd00|" + "green4:008b00|greenyellow:adff2f|honeydew:f0fff0|honeydew1:f0fff0|" + "honeydew2:e0eee0|honeydew3:c1cdc1|honeydew4:838b83|hot pink:ff69b4|" + "hotpink:ff69b4|hotpink1:ff6eb4|hotpink2:ee6aa7|hotpink3:cd6090|" + "hotpink4:8b3a62|indian red:cd5c5c|indianred:cd5c5c|indianred1:ff6a6a|" + "indianred2:ee6363|indianred3:cd5555|indianred4:8b3a3a|indigo:4b0082|" + "ivory:fffff0|ivory1:fffff0|ivory2:eeeee0|ivory3:cdcdc1|ivory4:8b8b83|" + "khaki:f0e68c|khaki1:fff68f|khaki2:eee685|khaki3:cdc673|khaki4:8b864e|" + "lavender:e6e6fa|lavender blush:fff0f5|lavenderblush:fff0f5|" + "lavenderblush1:fff0f5|lavenderblush2:eee0e5|lavenderblush3:cdc1c5|" + "lavenderblush4:8b8386|lawn green:7cfc00|lawngreen:7cfc00|" + "lemon chiffon:fffacd|lemonchiffon:fffacd|lemonchiffon1:fffacd|" + "lemonchiffon2:eee9bf|lemonchiffon3:cdc9a5|lemonchiffon4:8b8970|" + "light blue:add8e6|light coral:f08080|light cyan:e0ffff|" + "light goldenrod:eedd82|light goldenrod yellow:fafad2|light gray:d3d3d3|" + "light green:90ee90|light grey:d3d3d3|light pink:ffb6c1|light salmon:ffa07a|" + "light sea green:20b2aa|light sky blue:87cefa|light slate blue:8470ff|" + "light slate gray:778899|light slate grey:778899|light steel blue:b0c4de|" + "light yellow:ffffe0|lightblue:add8e6|lightblue1:bfefff|lightblue2:b2dfee|" + "lightblue3:9ac0cd|lightblue4:68838b|lightcoral:f08080|lightcyan:e0ffff|" + "lightcyan1:e0ffff|lightcyan2:d1eeee|lightcyan3:b4cdcd|lightcyan4:7a8b8b|" + "lightgoldenrod:eedd82|lightgoldenrod1:ffec8b|lightgoldenrod2:eedc82|" + "lightgoldenrod3:cdbe70|lightgoldenrod4:8b814c|lightgoldenrodyellow:fafad2|" + "lightgray:d3d3d3|lightgreen:90ee90|lightgrey:d3d3d3|lightpink:ffb6c1|" + "lightpink1:ffaeb9|lightpink2:eea2ad|lightpink3:cd8c95|lightpink4:8b5f65|" + "lightsalmon:ffa07a|lightsalmon1:ffa07a|lightsalmon2:ee9572|" + "lightsalmon3:cd8162|lightsalmon4:8b5742|lightseagreen:20b2aa|" + "lightskyblue:87cefa|lightskyblue1:b0e2ff|lightskyblue2:a4d3ee|" + "lightskyblue3:8db6cd|lightskyblue4:607b8b|lightslateblue:8470ff|" + "lightslategray:778899|lightslategrey:778899|lightsteelblue:b0c4de|" + "lightsteelblue1:cae1ff|lightsteelblue2:bcd2ee|lightsteelblue3:a2b5cd|" + "lightsteelblue4:6e7b8b|lightyellow:ffffe0|lightyellow1:ffffe0|" + "lightyellow2:eeeed1|lightyellow3:cdcdb4|lightyellow4:8b8b7a|lime:00ff00|" + "lime green:32cd32|limegreen:32cd32|linen:faf0e6|magenta:ff00ff|" + "magenta1:ff00ff|magenta2:ee00ee|magenta3:cd00cd|magenta4:8b008b|" + "maroon:b03060|maroon1:ff34b3|maroon2:ee30a7|maroon3:cd2990|maroon4:8b1c62|" + "medium aquamarine:66cdaa|medium blue:0000cd|medium orchid:ba55d3|" + "medium purple:9370db|medium sea green:3cb371|medium slate blue:7b68ee|" + "medium spring green:00fa9a|medium turquoise:48d1cc|" + "medium violet red:c71585|mediumaquamarine:66cdaa|mediumblue:0000cd|" + "mediumorchid:ba55d3|mediumorchid1:e066ff|mediumorchid2:d15fee|" + "mediumorchid3:b452cd|mediumorchid4:7a378b|mediumpurple:9370db|" + "mediumpurple1:ab82ff|mediumpurple2:9f79ee|mediumpurple3:8968cd|" + "mediumpurple4:5d478b|mediumseagreen:3cb371|mediumslateblue:7b68ee|" + "mediumspringgreen:00fa9a|mediumturquoise:48d1cc|mediumvioletred:c71585|" + "midnight blue:191970|midnightblue:191970|mint cream:f5fffa|" + "mintcream:f5fffa|misty rose:ffe4e1|mistyrose:ffe4e1|mistyrose1:ffe4e1|" + "mistyrose2:eed5d2|mistyrose3:cdb7b5|mistyrose4:8b7d7b|moccasin:ffe4b5|" + "navajo white:ffdead|navajowhite:ffdead|navajowhite1:ffdead|" + "navajowhite2:eecfa1|navajowhite3:cdb38b|navajowhite4:8b795e|navy:000080|" + "navy blue:000080|navyblue:000080|old lace:fdf5e6|oldlace:fdf5e6|" + "olive:808000|olive drab:6b8e23|olivedrab:6b8e23|olivedrab1:c0ff3e|" + "olivedrab2:b3ee3a|olivedrab3:9acd32|olivedrab4:698b22|orange:ffa500|" + "orange red:ff4500|orange1:ffa500|orange2:ee9a00|orange3:cd8500|" + "orange4:8b5a00|orangered:ff4500|orangered1:ff4500|orangered2:ee4000|" + "orangered3:cd3700|orangered4:8b2500|orchid:da70d6|orchid1:ff83fa|" + "orchid2:ee7ae9|orchid3:cd69c9|orchid4:8b4789|pale goldenrod:eee8aa|" + "pale green:98fb98|pale turquoise:afeeee|pale violet red:db7093|" + "palegoldenrod:eee8aa|palegreen:98fb98|palegreen1:9aff9a|palegreen2:90ee90|" + "palegreen3:7ccd7c|palegreen4:548b54|paleturquoise:afeeee|" + "paleturquoise1:bbffff|paleturquoise2:aeeeee|paleturquoise3:96cdcd|" + "paleturquoise4:668b8b|palevioletred:db7093|palevioletred1:ff82ab|" + "palevioletred2:ee799f|palevioletred3:cd6889|palevioletred4:8b475d|" + "papaya whip:ffefd5|papayawhip:ffefd5|peach puff:ffdab9|peachpuff:ffdab9|" + "peachpuff1:ffdab9|peachpuff2:eecbad|peachpuff3:cdaf95|peachpuff4:8b7765|" + "peru:cd853f|pink:ffc0cb|pink1:ffb5c5|pink2:eea9b8|pink3:cd919e|" + "pink4:8b636c|plum:dda0dd|plum1:ffbbff|plum2:eeaeee|plum3:cd96cd|" + "plum4:8b668b|powder blue:b0e0e6|powderblue:b0e0e6|purple:a020f0|" + "purple1:9b30ff|purple2:912cee|purple3:7d26cd|purple4:551a8b|" + "rebecca purple:663399|rebeccapurple:663399|red:ff0000|red1:ff0000|" + "red2:ee0000|red3:cd0000|red4:8b0000|rosy brown:bc8f8f|rosybrown:bc8f8f|" + "rosybrown1:ffc1c1|rosybrown2:eeb4b4|rosybrown3:cd9b9b|rosybrown4:8b6969|" + "royal blue:4169e1|royalblue:4169e1|royalblue1:4876ff|royalblue2:436eee|" + "royalblue3:3a5fcd|royalblue4:27408b|saddle brown:8b4513|saddlebrown:8b4513|" + "salmon:fa8072|salmon1:ff8c69|salmon2:ee8262|salmon3:cd7054|salmon4:8b4c39|" + "sandy brown:f4a460|sandybrown:f4a460|sea green:2e8b57|seagreen:2e8b57|" + "seagreen1:54ff9f|seagreen2:4eee94|seagreen3:43cd80|seagreen4:2e8b57|" + "seashell:fff5ee|seashell1:fff5ee|seashell2:eee5de|seashell3:cdc5bf|" + "seashell4:8b8682|sienna:a0522d|sienna1:ff8247|sienna2:ee7942|" + "sienna3:cd6839|sienna4:8b4726|silver:c0c0c0|sky blue:87ceeb|skyblue:87ceeb|" + "skyblue1:87ceff|skyblue2:7ec0ee|skyblue3:6ca6cd|skyblue4:4a708b|" + "slate blue:6a5acd|slate gray:708090|slate grey:708090|slateblue:6a5acd|" + "slateblue1:836fff|slateblue2:7a67ee|slateblue3:6959cd|slateblue4:473c8b|" + "slategray:708090|slategray1:c6e2ff|slategray2:b9d3ee|slategray3:9fb6cd|" + "slategray4:6c7b8b|slategrey:708090|snow:fffafa|snow1:fffafa|snow2:eee9e9|" + "snow3:cdc9c9|snow4:8b8989|spring green:00ff7f|springgreen:00ff7f|" + "springgreen1:00ff7f|springgreen2:00ee76|springgreen3:00cd66|" + "springgreen4:008b45|steel blue:4682b4|steelblue:4682b4|steelblue1:63b8ff|" + "steelblue2:5cacee|steelblue3:4f94cd|steelblue4:36648b|tan:d2b48c|" + "tan1:ffa54f|tan2:ee9a49|tan3:cd853f|tan4:8b5a2b|teal:008080|" + "thistle:d8bfd8|thistle1:ffe1ff|thistle2:eed2ee|thistle3:cdb5cd|" + "thistle4:8b7b8b|tomato:ff6347|tomato1:ff6347|tomato2:ee5c42|" + "tomato3:cd4f39|tomato4:8b3626|turquoise:40e0d0|turquoise1:00f5ff|" + "turquoise2:00e5ee|turquoise3:00c5cd|turquoise4:00868b|violet:ee82ee|" + "violet red:d02090|violetred:d02090|violetred1:ff3e96|violetred2:ee3a8c|" + "violetred3:cd3278|violetred4:8b2252|web gray:808080|web green:008000|" + "web grey:808080|web maroon:800000|web purple:800080|webgray:808080|" + "webgreen:008000|webgrey:808080|webmaroon:800000|webpurple:800080|" + "wheat:f5deb3|wheat1:ffe7ba|wheat2:eed8ae|wheat3:cdba96|wheat4:8b7e66|" + "white:ffffff|white smoke:f5f5f5|whitesmoke:f5f5f5|x11 gray:bebebe|" + "x11 green:00ff00|x11 grey:bebebe|x11 maroon:b03060|x11 purple:a020f0|" + "x11gray:bebebe|x11green:00ff00|x11grey:bebebe|x11maroon:b03060|" + "x11purple:a020f0|yellow:ffff00|yellow green:9acd32|yellow1:ffff00|" + "yellow2:eeee00|yellow3:cdcd00|yellow4:8b8b00|yellowgreen:9acd32" +) + + +def _load_x11_colors() -> dict[str, int]: + out: dict[str, int] = {} + for entry in _X11_COLOR_SPEC.split("|"): + name, _, hex_str = entry.partition(":") + out[name] = int(hex_str, 16) + return out + + +_X11_NAMED_RGB: dict[str, int] = _load_x11_colors() + +_BORDER_L = 0x1 +_BORDER_R = 0x2 +_BORDER_U = 0x4 +_BORDER_D = 0x8 + +_CELL_UD = 1 +_CELL_LR = 2 +_CELL_RD = 3 +_CELL_LD = 4 +_CELL_RU = 5 +_CELL_LU = 6 +_CELL_LRD = 7 +_CELL_LRU = 8 +_CELL_URD = 9 +_CELL_ULD = 10 +_CELL_LRUD = 11 +_CELL_NONE = 12 + +_SINGLE_BORDERS: tuple[str, ...] = ( + " ", + "│", + "─", + "┌", + "┐", + "└", + "┘", + "┬", + "┴", + "├", + "┤", + "┼", + "·", +) +_DOUBLE_BORDERS: tuple[str, ...] = ( + " ", + "║", + "═", + "╔", + "╗", + "╚", + "╝", + "╦", + "╩", + "╠", + "╣", + "╬", + "·", +) +_HEAVY_BORDERS: tuple[str, ...] = ( + " ", + "┃", + "━", + "┏", + "┓", + "┗", + "┛", + "┳", + "┻", + "┣", + "┫", + "╋", + "·", +) +_SIMPLE_BORDERS: tuple[str, ...] = ( + " ", + "|", + "-", + "+", + "+", + "+", + "+", + "+", + "+", + "+", + "+", + "+", + ".", +) + +_DEFAULT_BASELINE_MODES: frozenset[Mode] = frozenset( + { + Mode.DECAWM, + Mode.AUTO_REPEAT, + Mode.DECTCEM, + Mode.ALTERNATE_SCROLL, + Mode.GRAPHEME_CLUSTERING, + } +) + + +class _ColorKind(enum.Enum): + DEFAULT = 8 + TERMINAL = 9 + INVALID = -1 + + +@dataclass(frozen=True, slots=True) +class _TmuxThemeContext: + theme_colors: collections.abc.Mapping[str, Color] = field( + default_factory=lambda: _DEFAULT_THEME_COLORS + ) + rgb_capable: bool = True + tty_colours: int = 256 + + +_DEFAULT_THEME_CTX = _TmuxThemeContext() + + +def _tmux_rgb_to_256(r: int, g: int, b: int) -> IndexedColor: + """Quantize 24-bit RGB to xterm-256 index matching ``colour_find_rgb``.""" + q2c = (0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF) + qr = 0 if r < 48 else (1 if r < 114 else (r - 35) // 40) + qg = 0 if g < 48 else (1 if g < 114 else (g - 35) // 40) + qb = 0 if b < 48 else (1 if b < 114 else (b - 35) // 40) + cr, cg, cb = q2c[qr], q2c[qg], q2c[qb] + if cr == r and cg == g and cb == b: + return IndexedColor(16 + 36 * qr + 6 * qg + qb) + grey_avg = (r + g + b) // 3 + grey_idx = 23 if grey_avg > 238 else int((grey_avg - 3) / 10) + grey = 8 + 10 * grey_idx + cube_d = (cr - r) ** 2 + (cg - g) ** 2 + (cb - b) ** 2 + grey_d = (grey - r) ** 2 + (grey - g) ** 2 + (grey - b) ** 2 + if grey_d < cube_d: + return IndexedColor(232 + grey_idx) + return IndexedColor(16 + 36 * qr + 6 * qg + qb) + + +def _parse_tmux_color( + raw: str, + *, + theme_colors: collections.abc.Mapping[str, Color] = _DEFAULT_THEME_COLORS, +) -> Color | _ColorKind: + """Parse one ``tmux`` colour token matching ``colour_fromstring``.""" + s = raw.strip() + if not s: + return _ColorKind.INVALID + if _HEX6_RE.match(s) is not None: + return RgbColor( + int(s[1:3], 16), + int(s[3:5], 16), + int(s[5:7], 16), + ) + low = s.lower() + if low == "default": + return _ColorKind.DEFAULT + if low == "terminal": + return _ColorKind.TERMINAL + if low.startswith("colour"): + idx = _parse_ascii_uint(low[6:], max_val=255) + return _ColorKind.INVALID if idx is None else IndexedColor(idx) + if low.startswith("color"): + idx = _parse_ascii_uint(low[5:], max_val=255) + return _ColorKind.INVALID if idx is None else IndexedColor(idx) + if low in _DEFAULT_THEME_COLORS: + mapped = theme_colors.get(low, _DEFAULT_THEME_COLORS[low]) + return _ColorKind.DEFAULT if mapped is None else mapped + if s in _ANSI_COLOR_NAMES: + return _ANSI_COLOR_NAMES[s] + if low in _ANSI_COLOR_NAMES and not low.isdigit(): + return _ANSI_COLOR_NAMES[low] + if low.startswith(("grey", "gray")): + suffix = low[4:] + if not suffix: + return RgbColor(0xBE, 0xBE, 0xBE) + pct = _parse_ascii_uint(suffix, max_val=100) + if pct is None: + return _ColorKind.INVALID + # Match C integer truncation of (2.55 * pct + 0.5) (gray70 -> 179). + level = min(255, math.floor(2.55 * pct + 0.5)) + return RgbColor(level, level, level) + rgb_int = _X11_NAMED_RGB.get(low) + if rgb_int is not None: + return RgbColor( + (rgb_int >> 16) & 0xFF, + (rgb_int >> 8) & 0xFF, + rgb_int & 0xFF, + ) + return _ColorKind.INVALID + + +def _quantize_tty_color( + col: Color, + *, + is_fg: bool, + bg: Color, + bold: bool, + ctx: _TmuxThemeContext, +) -> tuple[Color, bool]: + """Quantize *col* to client TTY capabilities matching ``tty_check_fg/bg``.""" + if col is None: + return None, bold + if isinstance(col, RgbColor) and not ctx.rgb_capable: + col = _tmux_rgb_to_256(col.r, col.g, col.b) + if isinstance(col, IndexedColor) and ctx.tty_colours < 256: + c16 = _COLOUR_256_TO_16[col.index] + if c16 < 8: + return AnsiColor(c16), bold + base7 = c16 & 7 + if ctx.tty_colours >= 16: + return AnsiColor(base7 + 8), bold + if is_fg: + if base7 == 0 and bg == AnsiColor.BLACK: + base7 = 7 + elif base7 == 7 and bg == AnsiColor.WHITE: + base7 = 0 + return AnsiColor(base7), bold + if isinstance(col, AnsiColor) and 8 <= int(col) <= 15 and ctx.tty_colours < 16: + return AnsiColor(int(col) - 8), (True if is_fg else bold) + return col, bold + + +def _quantize_tty_style(style: Style, ctx: _TmuxThemeContext) -> Style: + if ctx.rgb_capable and ctx.tty_colours >= 256: + return style + bg_q, _ = _quantize_tty_color( + style.bg, + is_fg=False, + bg=None, + bold=style.bold, + ctx=ctx, + ) + fg_q, bold_q = _quantize_tty_color( + style.fg, + is_fg=True, + bg=bg_q, + bold=style.bold, + ctx=ctx, + ) + if fg_q == style.fg and bg_q == style.bg and bold_q == style.bold: + return style + return dataclasses.replace(style, fg=fg_q, bg=bg_q, bold=bold_q) + + +def _resolve_theme_context( + theme_mode: str, + client_theme: str, + client_colours_raw: str, + client_termname: str, + dark_values: collections.abc.Sequence[str], + light_values: collections.abc.Sequence[str], +) -> _TmuxThemeContext: + """Resolve ``tmux 3.8+`` theme slots and client TTY color depth.""" + c_str = client_colours_raw.strip() + if not c_str: + return _DEFAULT_THEME_CTX + c_colours = _parse_ascii_uint(c_str, max_val=_TMUX_UINT_MAX) + if c_colours is None: + return _DEFAULT_THEME_CTX + + rgb_capable = c_colours >= 16_777_216 + term_low = client_termname.strip().lower() + if c_colours >= 256 or "256color" in term_low or "direct" in term_low: + tty_colours = 256 + else: + tty_colours = c_colours + + mode = theme_mode.strip().lower() + if not mode or mode == "terminal": + return _TmuxThemeContext( + theme_colors=_DEFAULT_THEME_COLORS, + rgb_capable=rgb_capable, + tty_colours=tty_colours, + ) + + use_light = mode == "light" or ( + mode == "detect" and client_theme.strip().lower() == "light" + ) + raw_slots = light_values if use_light else dark_values + resolved: dict[str, Color] = dict(_DEFAULT_THEME_COLORS) + for idx, (slot_name, _, fallback_ansi) in enumerate(_THEME_SLOTS): + if idx >= len(raw_slots): + break + val = raw_slots[idx].strip() + if not val: + resolved[slot_name] = fallback_ansi + continue + parsed = _parse_tmux_color(val) + if parsed in (_ColorKind.DEFAULT, _ColorKind.TERMINAL): + resolved[slot_name] = None + elif isinstance(parsed, _ColorKind): + resolved[slot_name] = fallback_ansi + else: + resolved[slot_name] = parsed + + return _TmuxThemeContext( + theme_colors=types.MappingProxyType(resolved), + rgb_capable=rgb_capable, + tty_colours=tty_colours, + ) + + +@dataclass(slots=True) +class _FormatStyleState: + style: Style = DEFAULT_STYLE + hyperlink: Hyperlink | None = None + acs: bool = False + noattr: bool = False + ignore: bool = False + align: str = "default" + default_action: str = "" + has_fill: bool = False + fill: Color = None + + +def _apply_attr_name( + st: _FormatStyleState, + name: str, + *, + enable: bool, +) -> bool: + low = name.lower() + if low == "acs": + st.acs = enable + return True + if low in ("bright", "bold"): + st.style = dataclasses.replace(st.style, bold=enable) + return True + if low == "dim": + st.style = dataclasses.replace(st.style, dim=enable) + return True + if low in ("italics", "italic"): + st.style = dataclasses.replace(st.style, italic=enable) + return True + if low == "blink": + st.style = dataclasses.replace(st.style, blink=enable) + return True + if low == "reverse": + st.style = dataclasses.replace(st.style, reverse=enable) + return True + if low == "hidden": + st.style = dataclasses.replace(st.style, hidden=enable) + return True + if low == "strikethrough": + st.style = dataclasses.replace(st.style, strikethrough=enable) + return True + if low == "overline": + st.style = dataclasses.replace(st.style, overline=enable) + return True + ul_map = { + "underscore": UnderlineStyle.SINGLE, + "double-underscore": UnderlineStyle.DOUBLE, + "curly-underscore": UnderlineStyle.CURLY, + "dotted-underscore": UnderlineStyle.DOTTED, + "dashed-underscore": UnderlineStyle.DASHED, + } + target_ul = ul_map.get(low) + if target_ul is not None: + if enable: + st.style = dataclasses.replace(st.style, underline=target_ul) + elif st.style.underline == target_ul: + st.style = dataclasses.replace(st.style, underline=UnderlineStyle.NONE) + return True + return False + + +def _validate_range_spec(spec: str) -> bool: + head, sep, arg = spec.partition("|") + kind = head.lower() + if kind in ("left", "right"): + return not sep + if kind == "control": + return bool(sep) and _parse_ascii_uint(arg, max_val=9) is not None + if kind == "pane": + return ( + bool(sep) + and arg.startswith("%") + and _parse_ascii_uint(arg[1:], max_val=_TMUX_UINT_MAX) is not None + ) + if kind == "window": + return bool(sep) and _parse_ascii_uint(arg, max_val=_TMUX_UINT_MAX) is not None + if kind == "session": + return ( + bool(sep) + and arg.startswith("$") + and _parse_ascii_uint(arg[1:], max_val=_TMUX_UINT_MAX) is not None + ) + if kind == "user": + return bool(sep) and bool(arg) + return False + + +def _restore_format_state(dst: _FormatStyleState, saved: _FormatStyleState) -> None: + dst.style = saved.style + dst.hyperlink = saved.hyperlink + dst.acs = saved.acs + dst.noattr = saved.noattr + dst.ignore = saved.ignore + dst.align = saved.align + dst.default_action = saved.default_action + dst.has_fill = saved.has_fill + dst.fill = saved.fill + + +def _parse_style_into( + st: _FormatStyleState, + base: Style, + spec: str, + *, + ctx: _TmuxThemeContext = _DEFAULT_THEME_CTX, +) -> bool: + """Apply ``tmux`` ``style_parse`` (*spec*) transactionally onto *st*.""" + trimmed = spec.strip(" ,\n") + if not trimmed: + return True + saved = dataclasses.replace(st) + for tok in _STYLE_DELIM_RE.split(trimmed): + if not tok: + continue + low = tok.lower() + if low == "default": + st.style = base + st.hyperlink = None + st.acs = False + st.noattr = False + elif low == "none": + st.style = Style( + fg=st.style.fg, + bg=st.style.bg, + underline_color=st.style.underline_color, + ) + st.acs = False + st.noattr = False + elif low == "ignore": + st.ignore = True + elif low == "noignore": + st.ignore = False + elif low in ("push-default", "pop-default", "set-default"): + st.default_action = low + elif low in ("nolist", "norange"): + continue + elif low.startswith("list="): + if low[5:] not in ("on", "focus", "left-marker", "right-marker"): + _restore_format_state(st, saved) + return False + elif len(tok) > 6 and low.startswith("range="): + if not _validate_range_spec(tok[6:]): + _restore_format_state(st, saved) + return False + elif low == "noalign": + st.align = "default" + elif len(tok) > 6 and low.startswith("align="): + al_val = low[6:] + if al_val == "center": + al_val = "centre" + if al_val not in ("left", "centre", "right", "absolute-centre"): + _restore_format_state(st, saved) + return False + st.align = al_val + elif len(tok) > 5 and low.startswith("fill="): + col_res = _parse_tmux_color(tok[5:], theme_colors=ctx.theme_colors) + if col_res is _ColorKind.INVALID: + _restore_format_state(st, saved) + return False + # style.c + format-draw.c: fill=default (8) is a no-op; fill=terminal + # (9) clears the status line background to None. + if col_res is _ColorKind.TERMINAL: + st.has_fill = True + st.fill = None + elif not isinstance(col_res, _ColorKind): + fill_q, _ = _quantize_tty_color( + col_res, + is_fg=False, + bg=None, + bold=False, + ctx=ctx, + ) + st.has_fill = True + st.fill = fill_q + elif len(tok) > 4 and low.startswith("dim="): + if _parse_ascii_uint(tok[4:].removesuffix("%"), max_val=100) is None: + _restore_format_state(st, saved) + return False + elif len(tok) > 6 and low.startswith("width="): + wval = tok[6:] + ok_w = ( + _parse_ascii_uint(wval[:-1], max_val=100) is not None + if wval.endswith("%") + else _parse_ascii_uint(wval, max_val=_TMUX_UINT_MAX) is not None + ) + if not ok_w: + _restore_format_state(st, saved) + return False + elif len(tok) > 4 and low.startswith("pad="): + if _parse_ascii_uint(tok[4:], max_val=_TMUX_UINT_MAX) is None: + _restore_format_state(st, saved) + return False + elif len(tok) > 3 and low.startswith(("fg=", "bg=", "us=")): + col_res = _parse_tmux_color(tok[3:], theme_colors=ctx.theme_colors) + if col_res is _ColorKind.INVALID: + _restore_format_state(st, saved) + return False + prefix = low[:2] + if prefix == "fg": + eff_c = ( + base.fg + if col_res is _ColorKind.DEFAULT + else (None if col_res is _ColorKind.TERMINAL else col_res) + ) + st.style = dataclasses.replace(st.style, fg=eff_c) + elif prefix == "bg": + eff_c = ( + base.bg + if col_res is _ColorKind.DEFAULT + else (None if col_res is _ColorKind.TERMINAL else col_res) + ) + st.style = dataclasses.replace(st.style, bg=eff_c) + else: + eff_c = ( + base.underline_color + if col_res is _ColorKind.DEFAULT + else (None if col_res is _ColorKind.TERMINAL else col_res) + ) + st.style = dataclasses.replace(st.style, underline_color=eff_c) + elif low == "nolink": + st.hyperlink = None + elif low == "noattr": + st.noattr = True + elif low.startswith("link="): + uri = tok[5:] + st.hyperlink = Hyperlink(uri=uri, id=uri) if uri else None + elif low.startswith("no") and len(low) > 2 and "|" not in low: + if not _apply_attr_name(st, low[2:], enable=False): + _restore_format_state(st, saved) + return False + else: + sub_parts = tok.split("|") + if any(not p for p in sub_parts): + _restore_format_state(st, saved) + return False + ok = True + for sub in sub_parts: + if sub.lower() in ("default", "none"): + continue + if not _apply_attr_name(st, sub, enable=True): + ok = False + break + if not ok: + _restore_format_state(st, saved) + return False + st.style = _quantize_tty_style(st.style, ctx) + return True + + +def _parse_tmux_style( + spec: str, + *, + base: Style = DEFAULT_STYLE, + ctx: _TmuxThemeContext = _DEFAULT_THEME_CTX, +) -> Style: + """Parse a ``tmux`` style string into a :class:`~libvt.style.Style`.""" + st = _FormatStyleState(style=base) + _parse_style_into(st, base, spec, ctx=ctx) + return st.style + + +def _skip_format_bracket(text: str, start: int) -> int: + """Locate closing ``]`` from *start* matching ``tmux`` ``format_skip1``.""" + depth = 0 + idx = start + n = len(text) + while idx < n: + ch = text[idx] + if ch == "#" and idx + 1 < n: + nxt = text[idx + 1] + if nxt == "{": + depth += 1 + if nxt in ",#{}:": + idx += 2 + continue + if ch == "}" and depth > 0: + depth -= 1 + if ch == "]" and depth == 0: + return idx + idx += 1 + return -1 + + +def _draw_tmux_format_line( + dst: Screen, + available: int, + base_style: Style, + expanded: str, + *, + ctx: _TmuxThemeContext = _DEFAULT_THEME_CTX, + profile: Profile = TMUX_PROFILE, +) -> None: + """Render expanded ``pane-border-format`` onto 1-row *dst* (``format-draw.c``).""" + if available <= 0 or not expanded: + return + + cap = max(available, display_width(expanded, profile=profile) + 8, 1) + sections: dict[str, Screen] = {} + widths: dict[str, int] = { + "left": 0, + "centre": 0, + "right": 0, + "absolute-centre": 0, + } + base_default = base_style + cur_default = base_style + st = _FormatStyleState(style=cur_default) + current = "left" + has_fill = False + fill_color: Color = None + + def _emit_chunk(raw_txt: str) -> None: + if not raw_txt: + return + cleaned = "".join(ch for ch in raw_txt if ord(ch) >= 0x20 and ord(ch) != 0x7F) + if not cleaned: + return + mapped = cleaned.translate(_DEC_SPECIAL_GRAPHICS) if st.acs else cleaned + scr = sections.get(current) + if scr is None: + scr = Screen(rows=1, cols=cap, scrollback=0, profile=profile) + sections[current] = scr + w = scr.put_text( + 0, + widths[current], + mapped, + style=st.style, + hyperlink=st.hyperlink, + profile=profile, + ) + widths[current] += w + + idx = 0 + n = len(expanded) + while idx < n: + if expanded[idx] == "#": + h_end = idx + while h_end < n and expanded[h_end] == "#": + h_end += 1 + h_count = h_end - idx + if h_count == 1: + if h_end < n and expanded[h_end] == "[" and not st.ignore: + close_idx = _skip_format_bracket(expanded, h_end + 1) + if close_idx < 0: + break + prev_style = st.style + st.default_action = "" + st.has_fill = False + if _parse_style_into( + st, + cur_default, + expanded[h_end + 1 : close_idx], + ctx=ctx, + ): + if st.has_fill: + has_fill = True + fill_color = st.fill + if st.default_action == "push-default": + cur_default = prev_style + st.default_action = "" + elif st.default_action == "pop-default": + cur_default = base_default + st.default_action = "" + elif st.default_action == "set-default": + base_default = prev_style + cur_default = prev_style + st.default_action = "" + current = "left" if st.align == "default" else st.align + idx = close_idx + 1 + continue + _emit_chunk("#") + idx += 1 + continue + + even = (h_count % 2) == 0 + if h_end == n or expanded[h_end] != "[": + cnt = (h_count // 2) if even else (h_count // 2 + 1) + _emit_chunk("#" * cnt) + idx = h_end + continue + if even: + idx = h_end + 1 + if not st.ignore: + _emit_chunk(("#" * (h_count // 2)) + "[") + continue + idx = h_end - 1 + if not st.ignore: + _emit_chunk("#" * (h_count // 2)) + continue + + nxt_hash = expanded.find("#", idx) + if nxt_hash < 0: + _emit_chunk(expanded[idx:]) + break + _emit_chunk(expanded[idx:nxt_hash]) + idx = nxt_hash + + if has_fill: + dst.put_text( + 0, + 0, + " " * available, + style=Style(bg=fill_color), + profile=profile, + ) + + orig_centre = widths["centre"] + orig_right = widths["right"] + w_left = widths["left"] + w_centre = orig_centre + w_right = orig_right + w_abs = min(widths["absolute-centre"], available) + + while w_left + w_centre + w_right > available: + if w_centre > 0: + w_centre -= 1 + elif w_right > 0: + w_right -= 1 + else: + w_left -= 1 + + if w_left > 0 and "left" in sections: + dst.blit( + sections["left"], + top=0, + left=0, + src_top=0, + src_left=0, + rows=1, + cols=w_left, + ) + if w_right > 0 and "right" in sections: + dst.blit( + sections["right"], + top=0, + left=available - w_right, + src_top=0, + src_left=orig_right - w_right, + rows=1, + cols=w_right, + ) + if w_centre > 0 and "centre" in sections: + centre_dst = w_left + ((available - w_right) - w_left) // 2 - w_centre // 2 + centre_src = orig_centre // 2 - w_centre // 2 + dst.blit( + sections["centre"], + top=0, + left=centre_dst, + src_top=0, + src_left=centre_src, + rows=1, + cols=w_centre, + ) + if w_abs > 0 and "absolute-centre" in sections: + dst.blit( + sections["absolute-centre"], + top=0, + left=(available - w_abs) // 2, + src_top=0, + src_left=0, + rows=1, + cols=w_abs, + ) + + +def _mask_to_cell_type(mask: int) -> int: + if mask == (_BORDER_L | _BORDER_R | _BORDER_U | _BORDER_D): + return _CELL_LRUD + if mask == (_BORDER_L | _BORDER_R | _BORDER_U): + return _CELL_LRU + if mask == (_BORDER_L | _BORDER_R | _BORDER_D): + return _CELL_LRD + if mask in (_BORDER_L | _BORDER_R, _BORDER_L, _BORDER_R): + return _CELL_LR + if mask == (_BORDER_L | _BORDER_U | _BORDER_D): + return _CELL_ULD + if mask == (_BORDER_L | _BORDER_U): + return _CELL_LU + if mask == (_BORDER_L | _BORDER_D): + return _CELL_LD + if mask == (_BORDER_R | _BORDER_U | _BORDER_D): + return _CELL_URD + if mask == (_BORDER_R | _BORDER_U): + return _CELL_RU + if mask == (_BORDER_R | _BORDER_D): + return _CELL_RD + if mask in (_BORDER_U | _BORDER_D, _BORDER_U, _BORDER_D): + return _CELL_UD + return _CELL_NONE + + +def _border_glyph( + border_lines: str, + cell_type: int, + owner: TmuxWindowPane | None, +) -> str: + mode = border_lines.strip().lower() + if mode == "number": + if cell_type == _CELL_NONE: + return _SINGLE_BORDERS[_CELL_NONE] + if owner is not None: + return str(owner.index % 10) + return "*" + if mode == "double": + return _DOUBLE_BORDERS[cell_type] + if mode == "heavy": + return _HEAVY_BORDERS[cell_type] + if mode == "simple": + return _SIMPLE_BORDERS[cell_type] + if mode in ("spaces", "none"): + return " " + return _SINGLE_BORDERS[cell_type] + + +@dataclass(frozen=True, slots=True) +class TmuxWindowPane: + """Geometry and border styling metadata for one pane inside a ``tmux`` window. + + Attributes + ---------- + pane_id : str + ``tmux`` pane identifier (e.g. ``"%0"``). + left : int + Zero-based left column offset inside the window (``#{pane_left}``). + top : int + Zero-based top row offset inside the window (``#{pane_top}``). + width : int + Pane width in columns (``#{pane_width}``). + height : int + Pane height in rows (``#{pane_height}``). + active : bool + ``True`` when this pane is the window's active pane (``#{pane_active}``). + index : int + Pane index inside the window (``#{pane_index}``). + marked : bool + ``True`` when this pane carries the ``tmux`` marked flag. + floating : bool + ``True`` when this pane floats above tiled panes (``tmux >= 3.8``). + border_lines : str | None + Optional per-pane ``pane-border-lines`` override for floating panes; + ``None`` inherits :attr:`TmuxWindowLayout.border_lines`. + border_status : str | None + Optional per-pane ``pane-border-status`` override for floating panes; + ``None`` inherits :attr:`TmuxWindowLayout.border_status`. + border_style : str + Expanded ``#{E:pane-border-style}`` string for inactive borders. + active_border_style : str + Expanded ``#{E:pane-active-border-style}`` string for active borders. + border_format : str | None + Expanded ``#{E:pane-border-format}`` string; ``None`` synthesizes the + default ``tmux`` index + title format when ``pane-border-status`` is on. + """ + + pane_id: str + left: int = 0 + top: int = 0 + width: int = 80 + height: int = 24 + active: bool = False + index: int = 0 + marked: bool = False + floating: bool = False + border_lines: str | None = None + border_status: str | None = None + border_style: str = "fg=themelightgrey" + active_border_style: str = "fg=themegreen" + border_format: str | None = None + + @classmethod + def from_format_line(cls, line: str) -> TmuxWindowPane: + r"""Parse one line emitted by ``list-panes -F TMUX_WINDOW_PANE_FORMAT``. + + Parameters + ---------- + line : str + Single tab-separated line emitted by :data:`TMUX_WINDOW_PANE_FORMAT`. + + Returns + ------- + TmuxWindowPane + Parsed pane geometry and border style record. + + Raises + ------ + ValueError + If the leading ``pane_id`` field does not start with ``"%"``. + + Examples + -------- + >>> from libvt.contrib.tmux.window import TmuxWindowPane + >>> p = TmuxWindowPane.from_format_line( + ... "%1\t1\t11\t0\t9\t6\t1\t0\t0\tsingle\toff\tfg=white\tfg=green\t1" + ... ) + >>> (p.pane_id, p.left, p.width, p.active, p.border_format) + ('%1', 11, 9, True, '1') + """ + parts = line.rstrip("\r\n").split("\t", 13) + if len(parts) < 14: + parts.extend([""] * (14 - len(parts))) + pane_id = parts[0].strip() + if not pane_id.startswith("%"): + msg = f"invalid tmux pane_id {pane_id[:32]!r}" + raise ValueError(msg) + return cls( + pane_id=pane_id, + index=max(0, _opt_int(parts[1], 0)), + left=_opt_int(parts[2], 0), + top=_opt_int(parts[3], 0), + width=min(_TMUX_MAX_DIM, max(1, _opt_int(parts[4], 80))), + height=min(_TMUX_MAX_DIM, max(1, _opt_int(parts[5], 24))), + active=_opt_bool(parts[6]), + marked=_opt_bool(parts[7]), + floating=_opt_bool(parts[8]), + border_lines=parts[9].strip() or None, + border_status=parts[10].strip() or None, + border_style=parts[11].strip() or "default", + active_border_style=parts[12].strip() or "default", + border_format=parts[13], + ) + + +@dataclass(frozen=True, slots=True) +class TmuxWindowLayout: + """Window geometry, border options, and pane descriptors for a ``tmux`` window. + + Attributes + ---------- + window_id : str + ``tmux`` window identifier (e.g. ``"@0"``). + width : int + Window width in columns (``#{window_width}``). + height : int + Window height in rows (``#{window_height}``). + zoomed : bool + ``True`` when ``#{window_zoomed_flag}`` is active. + window_layout : str + Raw ``#{window_layout}`` descriptor (V1 checksum string or V2 JSON). + border_lines : str + Window ``pane-border-lines`` setting (``"single"``, ``"double"``, + ``"heavy"``, ``"simple"``, ``"number"``, ``"spaces"``, or ``"none"``). + border_status : str + Window ``pane-border-status`` setting (``"off"``, ``"top"``, or + ``"bottom"``). + border_indicators : str + Window ``pane-border-indicators`` setting (``"off"``, ``"colour"``, + ``"arrows"``, or ``"both"``). + border_style : str + Window fallback ``#{E:pane-border-style}`` string. + panes : tuple[TmuxWindowPane, ...] + Ordered panes belonging to this window. + """ + + window_id: str = "@0" + width: int = 80 + height: int = 24 + zoomed: bool = False + window_layout: str = "" + border_lines: str = "single" + border_status: str = "off" + border_indicators: str = "colour" + border_style: str = "fg=themelightgrey" + panes: tuple[TmuxWindowPane, ...] = () + _theme_ctx: _TmuxThemeContext = field( + default=_DEFAULT_THEME_CTX, + repr=False, + compare=False, + ) + + @property + def cols(self) -> int: + """Return window width in columns.""" + return self.width + + @property + def rows(self) -> int: + """Return window height in rows.""" + return self.height + + @property + def active_pane(self) -> TmuxWindowPane | None: + """Return the active :class:`TmuxWindowPane`, or the first pane if none.""" + for p in self.panes: + if p.active: + return p + return self.panes[0] if self.panes else None + + @classmethod + def from_format_lines( + cls, + window_line: str, + pane_lines: collections.abc.Sequence[str], + ) -> TmuxWindowLayout: + r"""Parse ``TMUX_WINDOW_METADATA_FORMAT`` and ``TMUX_WINDOW_PANE_FORMAT`` lines. + + Parameters + ---------- + window_line : str + Tab-separated window metadata line emitted by + :data:`TMUX_WINDOW_METADATA_FORMAT`. + pane_lines : Sequence[str] + Per-pane lines emitted by :data:`TMUX_WINDOW_PANE_FORMAT`. + + Returns + ------- + TmuxWindowLayout + Parsed window geometry, border options, theme state, and panes. + + Examples + -------- + >>> from libvt.contrib.tmux.window import TmuxWindowLayout + >>> win = TmuxWindowLayout.from_format_lines( + ... "@0\t20\t6\t0\tsingle\toff\tcolour\tfg=white\t", + ... ["%0\t0\t0\t0\t20\t6\t1\t0\t0\tsingle\toff\tfg=white\tfg=green\t0"], + ... ) + >>> (win.window_id, win.width, win.height, len(win.panes)) + ('@0', 20, 6, 1) + """ + n_slots = len(_THEME_SLOTS) + expected = 13 + 2 * n_slots + parts = window_line.rstrip("\r\n").split("\t", expected - 1) + if len(parts) < expected: + parts.extend([""] * (expected - len(parts))) + + theme_ctx = _resolve_theme_context( + parts[9], + parts[10], + parts[11], + parts[12], + parts[13 : 13 + n_slots], + parts[13 + n_slots : 13 + 2 * n_slots], + ) + return cls( + window_id=parts[0].strip() or "@0", + width=min(_TMUX_MAX_DIM, max(1, _opt_int(parts[1], 80))), + height=min(_TMUX_MAX_DIM, max(1, _opt_int(parts[2], 24))), + zoomed=_opt_bool(parts[3]), + border_lines=parts[4].strip() or "single", + border_status=parts[5].strip() or "off", + border_indicators=parts[6].strip() or "colour", + border_style=parts[7].strip() or "default", + window_layout=parts[8].strip(), + panes=tuple( + TmuxWindowPane.from_format_line(ln) for ln in pane_lines if ln.strip() + ), + _theme_ctx=theme_ctx, + ) + + +def parse_tmux_window_layout( + window_layout: str, + *, + window_id: str = "@0", + width: int | None = None, + height: int | None = None, + zoomed: bool = False, + border_lines: str = "single", + border_status: str = "off", + border_indicators: str = "colour", + border_style: str = "fg=themelightgrey", + active_pane_id: str | None = None, +) -> TmuxWindowLayout: + r"""Parse a ``tmux`` ``#{window_layout}`` descriptor into :class:`TmuxWindowLayout`. + + Accepts both ``tmux >= 3.8`` V2 JSON layouts (``{"V":2,"L":{...}}``) and + legacy V1 checksum tree strings (``"b25f,20x6,0,0{10x6,0,0,0,9x6,11,0,1}"``), + allowing callers such as ``libtmux`` that already hold ``window_layout`` to + build a single-invocation :func:`build_tmux_window_capture_command` with + ``include_layout=True`` or composite pane handles directly. + + Parameters + ---------- + window_layout : str + Raw ``#{window_layout}`` or ``#{window_visible_layout}`` string. + window_id : str, default "@0" + ``tmux`` window identifier stored on the returned layout. + width : int | None, optional + Explicit window width override; inferred from root cell when ``None``. + height : int | None, optional + Explicit window height override; inferred from root cell when ``None``. + zoomed : bool, default False + Whether the window is currently zoomed. + border_lines : str, default "single" + Window ``pane-border-lines`` setting. + border_status : str, default "off" + Window ``pane-border-status`` setting. + border_indicators : str, default "colour" + Window ``pane-border-indicators`` setting. + border_style : str, default "fg=themelightgrey" + Window fallback ``pane-border-style``. + active_pane_id : str | None, optional + Explicit active ``pane_id`` (used for V1 strings which omit active flags). + + Returns + ------- + TmuxWindowLayout + Parsed window dimensions and :class:`TmuxWindowPane` geometries. + + Raises + ------ + ValueError + If *window_layout* is empty or malformed. + + References + ---------- + - `tmux/tmux layout-custom.c (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.window import parse_tmux_window_layout + >>> v1 = parse_tmux_window_layout( + ... "b25f,20x6,0,0{10x6,0,0,0,9x6,11,0,1}", active_pane_id="%1" + ... ) + >>> (v1.width, v1.height, [p.pane_id for p in v1.panes], v1.active_pane.pane_id) + (20, 6, ['%0', '%1'], '%1') + >>> v2 = parse_tmux_window_layout( + ... '{"V":2,"L":{"t":"h","w":20,"h":6,"x":0,"y":0,"c":[' + ... '{"t":"p","w":10,"h":6,"x":0,"y":0,"i":0,"I":"%0"},' + ... '{"t":"p","w":9,"h":6,"x":11,"y":0,"a":true,"i":1,"I":"%1"}]}}' + ... ) + >>> (v2.width, v2.height, v2.panes[1].left, v2.panes[1].active) + (20, 6, 11, True) + """ + raw = window_layout.strip() + if not raw: + msg = "empty tmux window_layout" + raise ValueError(msg) + + if raw.startswith("{"): + try: + doc = json.loads(raw) + except ValueError as exc: + msg = f"invalid JSON tmux window_layout: {raw[:64]!r}" + raise ValueError(msg) from exc + if not isinstance(doc, dict) or not isinstance(doc.get("L"), dict): + msg = f"invalid V2 tmux window_layout root: {raw[:64]!r}" + raise ValueError(msg) + root = doc["L"] + root_w = int(root.get("w", 80)) + root_h = int(root.get("h", 24)) + tiled_items: list[tuple[int, TmuxWindowPane]] = [] + float_items: list[tuple[int, TmuxWindowPane]] = [] + + def _walk_v2(node: dict[str, object]) -> None: + ntype = node.get("t") + if ntype == "p": + pid_raw = node.get("I") + idx_raw = node.get("i", len(tiled_items) + len(float_items)) + idx_val = int(idx_raw) if isinstance(idx_raw, int) else 0 + pid = ( + pid_raw + if isinstance(pid_raw, str) and pid_raw.startswith("%") + else f"%{idx_val}" + ) + raw_w = node.get("w") + raw_h = node.get("h") + raw_x = node.get("x") + raw_y = node.get("y") + w_val = raw_w if isinstance(raw_w, int) else 80 + h_val = raw_h if isinstance(raw_h, int) else 24 + x_val = raw_x if isinstance(raw_x, int) else 0 + y_val = raw_y if isinstance(raw_y, int) else 0 + z_raw = node.get("z") + is_float = isinstance(z_raw, int) + is_act = ( + (pid == active_pane_id) + if active_pane_id is not None + else bool(node.get("a", False)) + ) + wp = TmuxWindowPane( + pane_id=pid, + left=x_val, + top=y_val, + width=min(_TMUX_MAX_DIM, max(1, w_val)), + height=min(_TMUX_MAX_DIM, max(1, h_val)), + active=is_act, + index=max(0, idx_val), + floating=is_float, + border_style=border_style, + ) + if is_float and isinstance(z_raw, int): + float_items.append((z_raw, wp)) + else: + tiled_items.append((idx_val, wp)) + return + children = node.get("c") + if isinstance(children, list): + for child in children: + if isinstance(child, dict): + _walk_v2(child) + + _walk_v2(root) + if not tiled_items and not float_items: + msg = f"tmux V2 window_layout contains no panes: {raw[:64]!r}" + raise ValueError(msg) + tiled_items.sort(key=lambda item: item[0]) + # z=0 is topmost in tmux; place z=0 first so reversed(floating_panes) + # composites higher z (backmost) first and z=0 last (frontmost). + float_items.sort(key=lambda item: item[0]) + panes_out = (*(wp for _, wp in tiled_items), *(wp for _, wp in float_items)) + eff_h_default = ( + root_h + 1 if border_status.strip().lower() in ("top", "bottom") else root_h + ) + return TmuxWindowLayout( + window_id=window_id, + width=min(_TMUX_MAX_DIM, max(1, root_w if width is None else width)), + height=min( + _TMUX_MAX_DIM, max(1, eff_h_default if height is None else height) + ), + zoomed=zoomed, + window_layout=raw, + border_lines=border_lines, + border_status=border_status, + border_indicators=border_indicators, + border_style=border_style, + panes=panes_out, + ) + + m_root = _V1_ROOT_RE.match(raw) + leaves = list(_V1_LEAF_RE.finditer(raw)) + if m_root is None or not leaves: + msg = f"invalid V1 tmux window_layout: {raw[:64]!r}" + raise ValueError(msg) + root_w = int(m_root.group("w")) + root_h = int(m_root.group("h")) + v1_panes: list[TmuxWindowPane] = [] + for idx, m in enumerate(leaves): + pid = f"%{m.group('id')}" + is_act = (pid == active_pane_id) if active_pane_id is not None else (idx == 0) + v1_panes.append( + TmuxWindowPane( + pane_id=pid, + left=int(m.group("x")), + top=int(m.group("y")), + width=min(_TMUX_MAX_DIM, max(1, int(m.group("w")))), + height=min(_TMUX_MAX_DIM, max(1, int(m.group("h")))), + active=is_act, + index=idx, + border_style=border_style, + ) + ) + eff_h_default = ( + root_h + 1 if border_status.strip().lower() in ("top", "bottom") else root_h + ) + return TmuxWindowLayout( + window_id=window_id, + width=min(_TMUX_MAX_DIM, max(1, root_w if width is None else width)), + height=min(_TMUX_MAX_DIM, max(1, eff_h_default if height is None else height)), + zoomed=zoomed, + window_layout=raw, + border_lines=border_lines, + border_status=border_status, + border_indicators=border_indicators, + border_style=border_style, + panes=tuple(v1_panes), + ) + + +class _SupportsPaneTerminal(t.Protocol): + @property + def terminal(self) -> Terminal | None: ... + + +class _SupportsPaneSnapshotProperty(t.Protocol): + @property + def snapshot(self) -> Snapshot: ... + + +class _SupportsPaneSnapshotMethod(t.Protocol): + def snapshot(self) -> Snapshot: ... + + +#: Pane state handles accepted by :func:`composite_tmux_window`. +type TmuxPaneSource = ( + Snapshot + | Screen + | Terminal + | TmuxCaptureResult + | _SupportsPaneTerminal + | _SupportsPaneSnapshotProperty + | _SupportsPaneSnapshotMethod +) + + +def _resolve_pane_snapshot(source: TmuxPaneSource) -> Snapshot | None: + if isinstance(source, Snapshot): + return source + if isinstance(source, Terminal): + return source.committed + if isinstance(source, TmuxCaptureResult): + return source.snapshot + if isinstance(source, Screen): + return source.snapshot(modes=_DEFAULT_BASELINE_MODES) + term_attr = getattr(source, "terminal", None) + if isinstance(term_attr, Terminal): + return term_attr.committed + if ( + term_attr is None + and hasattr(source, "terminal") + and not hasattr(source, "snapshot") + ): + return None + snap_attr = getattr(source, "snapshot", None) + if isinstance(snap_attr, Snapshot): + return snap_attr + if callable(snap_attr): + res = snap_attr() + if isinstance(res, Snapshot): + return res + msg = ( + "pane source must be Snapshot, Screen, Terminal, TmuxCaptureResult, or " + f"handle exposing .terminal / .snapshot, got {type(source).__name__}" + ) + raise TypeError(msg) + + +@dataclass(slots=True) +class _PaneCell: + wp: TmuxWindowPane + py: int + + +@dataclass(slots=True) +class _BorderCell: + mask: int = 0 + top_wp: TmuxWindowPane | None = None + bottom_wp: TmuxWindowPane | None = None + left_wp: TmuxWindowPane | None = None + right_wp: TmuxWindowPane | None = None + style_wp: TmuxWindowPane | None = None + is_arrow: bool = False + + def has_pane(self, wp: TmuxWindowPane) -> bool: + return wp in (self.top_wp, self.bottom_wp, self.left_wp, self.right_wp) + + +@dataclass(slots=True) +class _StatusCell: + wp: TmuxWindowPane + offset: int + cell_type: int + + +def _detect_two_pane_split_type(layout: TmuxWindowLayout) -> str | None: + """Return ``'leftright'`` or ``'topbottom'`` for 2-pane tiled windows.""" + tiled = [p for p in layout.panes if not p.floating] + if len(tiled) != 2: + return None + raw = layout.window_layout.strip() + if raw.startswith("{"): + try: + doc = json.loads(raw) + except ValueError: + doc = None + if isinstance(doc, dict): + root = doc.get("L") + if isinstance(root, dict): + children = root.get("c") + if not isinstance(children, list): + return None + tiled_children = [ + ch for ch in children if isinstance(ch, dict) and "z" not in ch + ] + if len(tiled_children) != 2 or not all( + ch.get("t") == "p" for ch in tiled_children + ): + return None + node_type = root.get("t") + if node_type == "h": + return "leftright" + if node_type == "v": + return "topbottom" + return None + elif raw: + b_idx = raw.find("{") + s_idx = raw.find("[") + if b_idx >= 0 and (s_idx < 0 or b_idx < s_idx): + return "leftright" + if s_idx >= 0 and (b_idx < 0 or s_idx < b_idx): + return "topbottom" + return None + + p0, p1 = tiled + if p0.left != p1.left and p0.top == p1.top: + return "leftright" + if p0.top != p1.top and p0.left == p1.left: + return "topbottom" + return None + + +def _effective_pane_lines(layout: TmuxWindowLayout, wp: TmuxWindowPane) -> str: + if wp.floating and wp.border_lines is not None: + return wp.border_lines.strip().lower() + return layout.border_lines.strip().lower() + + +def _effective_pane_status(layout: TmuxWindowLayout, wp: TmuxWindowPane) -> str: + if not wp.floating: + st = layout.border_status.strip().lower() + return st if st in ("top", "bottom") else "off" + if _effective_pane_lines(layout, wp) == "none": + return "off" + raw = (wp.border_status or layout.border_status).strip().lower() + if raw in ("top", "top-floating"): + return "top" + if raw in ("bottom", "bottom-floating"): + return "bottom" + return "off" + + +def composite_tmux_window( + layout: TmuxWindowLayout, + panes: collections.abc.Mapping[str, TmuxPaneSource], + *, + tmux_version: tuple[int, int] | str = "3.8a", + profile: Profile = TMUX_PROFILE, +) -> Snapshot: + r"""Composite a multi-pane ``tmux`` window into one immutable :class:`Snapshot`. + + Pure sans-I/O compositor built on :meth:`~libvt.screen.Screen.blit`, + :meth:`~libvt.screen.Screen.put_text`, and + :meth:`~libvt.screen.Screen.snapshot`, matching ``tmux``'s + ``screen-redraw.c`` scene builder across perimeter ``L|R|U|D`` junctions, + ``pane-border-lines``, two-pane half-colored active borders, + ``pane-border-status`` format lines, ``theme`` color tables, full-width + soft-wrap flags, zoomed windows, and active-pane cursor positioning. + + Parameters + ---------- + layout : TmuxWindowLayout + Window dimensions, border options, and pane geometry descriptors. + panes : Mapping[str, TmuxPaneSource] + Mapping from ``pane_id`` (e.g. ``"%0"``) to each pane's + :class:`~libvt.terminal.Snapshot`, :class:`~libvt.screen.Screen`, + :class:`~libvt.terminal.Terminal`, :class:`TmuxCaptureResult`, or live + :class:`~libvt.contrib.tmux.control.TmuxPaneSync` handle. + tmux_version : tuple[int, int] | str, default "3.8a" + Target ``tmux`` version governing right-edge ``pending_wrap`` cursor + visibility (``tmux >= 3.7`` hides a ``pending_wrap`` cursor at the + window right margin via ``screen_redraw_get_visible_ranges``, whereas + ``tmux <= 3.6`` keeps it visible at ``cols - 1``). + profile : Profile, default TMUX_PROFILE + Terminal compatibility profile for width calculations and the returned + :class:`~libvt.terminal.Snapshot`. + + Returns + ------- + Snapshot + Composited window snapshot with active-pane cursor and metadata. + + References + ---------- + - `tmux/tmux screen-redraw.c (3.8) + `__ + - `tmux/tmux window-border.c (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.window import ( + ... TmuxWindowLayout, + ... TmuxWindowPane, + ... composite_tmux_window, + ... ) + >>> from libvt.terminal import Terminal + >>> from libvt.testing import format_screen_box + >>> left, right = Terminal(rows=2, cols=4), Terminal(rows=2, cols=4) + >>> left.feed(b"LEFT") + >>> right.feed(b"RGHT") + >>> win_layout = TmuxWindowLayout( + ... width=9, + ... height=2, + ... panes=( + ... TmuxWindowPane("%0", left=0, top=0, width=4, height=2, index=0), + ... TmuxWindowPane( + ... "%1", left=5, top=0, width=4, height=2, active=True, index=1 + ... ), + ... ), + ... ) + >>> snap = composite_tmux_window(win_layout, {"%0": left, "%1": right}) + >>> print(format_screen_box(snap)) + ┌─────────┐ + │LEFT│RGHT│ + │ │ │ + └─────────┘ + """ + w_cols = min(_TMUX_MAX_DIM, max(1, layout.width)) + w_rows = min(_TMUX_MAX_DIM, max(1, layout.height)) + ver = parse_tmux_version(tmux_version) + canvas = Screen(rows=w_rows, cols=w_cols, scrollback=0, profile=profile) + theme_ctx = layout._theme_ctx + + resolved: dict[str, Snapshot] = {} + for pid, src in panes.items(): + snap = _resolve_pane_snapshot(src) + if snap is not None: + resolved[pid] = snap + + total_gen = sum(s.generation for s in resolved.values()) + active_pane = layout.active_pane + marked_pane = next((p for p in layout.panes if p.marked), None) + + if layout.zoomed: + if active_pane is None: + return canvas.snapshot( + cursor=Cursor(row=0, col=0, visible=False), + modes=_DEFAULT_BASELINE_MODES, + generation=total_gen, + profile=profile, + ) + win_st = layout.border_status.strip().lower() + if win_st == "top" and w_rows >= 2: + z_pane = dataclasses.replace( + active_pane, + left=0, + top=1, + width=w_cols, + height=w_rows - 1, + active=True, + floating=False, + ) + elif win_st == "bottom" and w_rows >= 2: + z_pane = dataclasses.replace( + active_pane, + left=0, + top=0, + width=w_cols, + height=w_rows - 1, + active=True, + floating=False, + ) + else: + z_pane = dataclasses.replace( + active_pane, + left=0, + top=0, + width=w_cols, + height=w_rows, + active=True, + floating=False, + ) + eff_layout = dataclasses.replace(layout, zoomed=False, panes=(z_pane,)) + active_pane = z_pane + else: + eff_layout = layout + + # Match screen-redraw.c TAILQ_FOREACH_REVERSE(&w->z_index): tiled panes in + # reverse order, then floating panes from back to front. + tiled_panes = [p for p in eff_layout.panes if not p.floating] + floating_panes = [p for p in eff_layout.panes if p.floating] + scene_order = [*reversed(tiled_panes), *reversed(floating_panes)] + + scene: list[list[str | _PaneCell | _BorderCell | _StatusCell]] = [ + ["empty"] * w_cols for _ in range(w_rows) + ] + ind = eff_layout.border_indicators.strip().lower() + + def _mark_border_cell( + wx: int, + wy: int, + wp: TmuxWindowPane, + *, + top_owner: bool, + bottom_owner: bool, + mask: int, + floating: bool, + ) -> None: + if wx < 0 or wy < 0 or wx >= w_cols or wy >= w_rows: + return + cur_slot = scene[wy][wx] + if not floating: + if cur_slot == "empty": + bcell = _BorderCell() + scene[wy][wx] = bcell + elif isinstance(cur_slot, _BorderCell): + bcell = cur_slot + else: + return + elif isinstance(cur_slot, _BorderCell) and cur_slot.has_pane(wp): + bcell = cur_slot + else: + bcell = _BorderCell() + scene[wy][wx] = bcell + + if top_owner: + bcell.top_wp = wp + if bottom_owner: + bcell.bottom_wp = wp + if mask & (_BORDER_U | _BORDER_D): + if wx < wp.left: + bcell.right_wp = wp + elif wx >= wp.left + wp.width: + bcell.left_wp = wp + bcell.mask |= mask + + for wp in scene_order: + py0 = max(0, -wp.top) + py1 = min(wp.height, w_rows - wp.top) + px0 = max(0, -wp.left) + px1 = min(wp.width, w_cols - wp.left) + for py in range(py0, py1): + pcell = _PaneCell(wp=wp, py=py) + row_slots = scene[wp.top + py] + for px in range(px0, px1): + row_slots[wp.left + px] = pcell + + p_lines = _effective_pane_lines(eff_layout, wp) + if wp.floating and p_lines == "none": + continue + p_status = _effective_pane_status(eff_layout, wp) + + left = wp.left - 1 + right = wp.left + wp.width + top = wp.top - 1 + bottom = wp.top + wp.height + mark_left = left >= 0 + mark_top = top >= 0 + if wp.floating: + mark_right = right < w_cols + mark_bottom = bottom < w_rows + left = max(0, left) + right = min(w_cols - 1, right) + top = max(0, top) + bottom = min(w_rows - 1, bottom) + else: + mark_right = right <= w_cols + mark_bottom = bottom <= w_rows + if p_status == "top" and bottom < w_rows: + mark_bottom = False + elif p_status == "bottom": + mark_top = False + + if mark_top: + for wx in range(left, right + 1): + mask = (_BORDER_L if wx > left else 0) | ( + _BORDER_R if wx < right else 0 + ) + _mark_border_cell( + wx, + top, + wp, + top_owner=False, + bottom_owner=True, + mask=mask, + floating=wp.floating, + ) + if mark_bottom: + for wx in range(left, right + 1): + mask = (_BORDER_L if wx > left else 0) | ( + _BORDER_R if wx < right else 0 + ) + _mark_border_cell( + wx, + bottom, + wp, + top_owner=True, + bottom_owner=False, + mask=mask, + floating=wp.floating, + ) + if mark_left: + for wy in range(top, bottom + 1): + mask = (_BORDER_U if wy > top else 0) | ( + _BORDER_D if wy < bottom else 0 + ) + _mark_border_cell( + left, + wy, + wp, + top_owner=False, + bottom_owner=False, + mask=mask, + floating=wp.floating, + ) + if mark_right: + for wy in range(top, bottom + 1): + mask = (_BORDER_U if wy > top else 0) | ( + _BORDER_D if wy < bottom else 0 + ) + _mark_border_cell( + right, + wy, + wp, + top_owner=False, + bottom_owner=False, + mask=mask, + floating=wp.floating, + ) + + if p_status != "off": + st_wy = top if p_status == "top" else bottom + sx = wp.left + 2 + status_w = ( + 0 if wp.width < 4 else (wp.width - 4 if ver < (3, 6) else wp.width - 2) + ) + ex = min(w_cols - 1, sx + status_w - 1) + if 0 <= st_wy < w_rows and sx <= ex: + for off, wx in enumerate(range(sx, ex + 1)): + if 0 <= wx < w_cols: + cur_b = scene[st_wy][wx] + if isinstance(cur_b, _BorderCell): + scene[st_wy][wx] = _StatusCell( + wp=wp, + offset=off, + cell_type=_mask_to_cell_type(cur_b.mask), + ) + + if ind in ("arrows", "both"): + ax = wp.left + 1 + if left <= ax <= right: + for ay in (top, bottom): + if 0 <= ax < w_cols and 0 <= ay < w_rows: + b_slot = scene[ay][ax] + if isinstance(b_slot, _BorderCell): + b_slot.is_arrow = True + ay = wp.top + 1 + if top <= ay <= bottom: + for ax_e in (left, right): + if 0 <= ax_e < w_cols and 0 <= ay < w_rows: + b_slot = scene[ay][ax_e] + if isinstance(b_slot, _BorderCell): + b_slot.is_arrow = True + + if ind in ("colour", "both"): + split_type = _detect_two_pane_split_type(eff_layout) + if split_type == "leftright": + half_y = w_rows // 2 + for wy in range(w_rows): + row_s = scene[wy] + for wx in range(w_cols): + slot = row_s[wx] + if ( + isinstance(slot, _BorderCell) + and slot.left_wp is not None + and slot.right_wp is not None + ): + slot.style_wp = slot.left_wp if wy <= half_y else slot.right_wp + elif split_type == "topbottom": + half_x = w_cols // 2 + for wy in range(w_rows): + row_s = scene[wy] + for wx in range(w_cols): + slot = row_s[wx] + if ( + isinstance(slot, _BorderCell) + and slot.top_wp is not None + and slot.bottom_wp is not None + ): + slot.style_wp = slot.top_wp if wx <= half_x else slot.bottom_wp + + for wp in scene_order: + p_snap = resolved.get(wp.pane_id) + if p_snap is not None: + full_w = ( + not wp.floating + and wp.left == 0 + and wp.width == w_cols + and p_snap.cols == w_cols + ) + canvas.blit( + p_snap, + top=wp.top, + left=wp.left, + src_top=0, + src_left=0, + rows=wp.height, + cols=wp.width, + preserve_wrap=full_w, + ) + + style_cache: dict[str, Style] = {} + + def _cached_style(raw_style: str) -> Style: + cached = style_cache.get(raw_style) + if cached is None: + cached = _parse_tmux_style(raw_style, ctx=theme_ctx) + style_cache[raw_style] = cached + return cached + + def _pane_border_style(wp: TmuxWindowPane | None) -> Style: + if wp is None: + return _cached_style(eff_layout.border_style) + return _cached_style(wp.active_border_style if wp.active else wp.border_style) + + # window-border.c + options-table.c: REDRAW_SPAN_EMPTY merges default + # inside fill-character `#[bg=themedarkgrey] ` over default border style. + empty_fill_style = _parse_tmux_style( + "bg=themedarkgrey", + base=_cached_style(eff_layout.border_style), + ctx=theme_ctx, + ) + + def _z_border_owner_37(wx: int, wy: int) -> TmuxWindowPane | None: + if not tiled_panes: + return None + start_idx = -1 + for idx, p in enumerate(tiled_panes): + if ( + p.left - 1 <= wx <= p.left + p.width + and p.top - 1 <= wy <= p.top + p.height + ): + start_idx = idx + break + if start_idx < 0: + start_idx = ( + tiled_panes.index(active_pane) if active_pane in tiled_panes else 0 + ) + n_tiled = len(tiled_panes) + for k in range(n_tiled): + p = tiled_panes[(start_idx + k) % n_tiled] + ex_p = p.left + p.width + ey_p = p.top + p.height + if ( + (p.top == 0 or wy >= p.top - 1) + and wy <= ey_p + and wx in (p.left - 1, ex_p) + ): + return p + p_st = _effective_pane_status(eff_layout, p) + if (p.left == 0 or wx >= p.left) and wx <= ex_p: + if p_st != "bottom" and p.top != 0 and wy == p.top - 1: + return p + if p_st != "top" and wy == ey_p: + return p + return None + + status_spans: dict[str, tuple[TmuxWindowPane, int, list[tuple[int, int, int]]]] = {} + for wy in range(w_rows): + row_s = scene[wy] + run_start = -1 + run_style = DEFAULT_STYLE + run_chars: list[str] = [] + for wx in range(w_cols): + slot = row_s[wx] + if isinstance(slot, _BorderCell): + if slot.style_wp is not None: + owner = slot.style_wp + elif active_pane is not None and slot.has_pane(active_pane): + owner = active_pane + else: + owner = ( + slot.top_wp or slot.bottom_wp or slot.left_wp or slot.right_wp + ) + glyph_owner = ( + (_z_border_owner_37(wx, wy) or owner) + if ( + ver == (3, 7) + and slot.style_wp is None + and (owner is None or not owner.floating) + ) + else owner + ) + st = _pane_border_style(owner) + if marked_pane is not None and slot.has_pane(marked_pane): + st = dataclasses.replace(st, reverse=not st.reverse) + eff_lines = ( + _effective_pane_lines(eff_layout, glyph_owner) + if glyph_owner is not None + else eff_layout.border_lines + ) + ch = _border_glyph( + eff_lines, _mask_to_cell_type(slot.mask), glyph_owner + ) + if slot.is_arrow and active_pane is not None: + if slot.left_wp is active_pane: + ch = "←" + elif slot.right_wp is active_pane: + ch = "→" + elif slot.top_wp is active_pane: + ch = "↑" + elif slot.bottom_wp is active_pane: + ch = "↓" + if run_start >= 0 and st == run_style: + run_chars.append(ch) + else: + if run_start >= 0: + canvas.put_text( + wy, + run_start, + "".join(run_chars), + style=run_style, + profile=profile, + ) + run_start = wx + run_style = st + run_chars = [ch] + elif slot == "empty": + if run_start >= 0 and empty_fill_style == run_style: + run_chars.append(" ") + else: + if run_start >= 0: + canvas.put_text( + wy, + run_start, + "".join(run_chars), + style=run_style, + profile=profile, + ) + run_start = wx + run_style = empty_fill_style + run_chars = [" "] + else: + if run_start >= 0: + canvas.put_text( + wy, + run_start, + "".join(run_chars), + style=run_style, + profile=profile, + ) + run_start = -1 + if isinstance(slot, _StatusCell): + entry = status_spans.get(slot.wp.pane_id) + if entry is None: + entry = (slot.wp, wy, []) + status_spans[slot.wp.pane_id] = entry + entry[2].append((wx, slot.offset, slot.cell_type)) + if run_start >= 0: + canvas.put_text( + wy, + run_start, + "".join(run_chars), + style=run_style, + profile=profile, + ) + + for wp, st_wy, cells_info in status_spans.values(): + if not cells_info: + continue + st_width = max(off for _, off, _ in cells_info) + 1 + st_scr = Screen(rows=1, cols=st_width, scrollback=0, profile=profile) + base_st = _pane_border_style(wp) + eff_lines = _effective_pane_lines(eff_layout, wp) + cell_types_by_off = {off: ct for _, off, ct in cells_info} + bg_chars = [ + _border_glyph(eff_lines, cell_types_by_off.get(off, _CELL_LR), wp) + for off in range(st_width) + ] + st_scr.put_text(0, 0, "".join(bg_chars), style=base_st, profile=profile) + + if wp.border_format is not None: + fmt_text = wp.border_format + else: + p_snap = resolved.get(wp.pane_id) + p_title = p_snap.title if p_snap is not None else "" + rev_prefix = "#[reverse]" if wp.active else "" + fmt_text = f'{rev_prefix}{wp.index}#[default] "{p_title}"' + + _draw_tmux_format_line( + st_scr, + st_width, + base_st, + fmt_text, + ctx=theme_ctx, + profile=profile, + ) + + span_wx = cells_info[0][0] + span_off = cells_info[0][1] + span_len = 1 + for wx, off, _ in cells_info[1:]: + if wx == span_wx + span_len and off == span_off + span_len: + span_len += 1 + else: + canvas.blit( + st_scr, + top=st_wy, + left=span_wx, + src_top=0, + src_left=span_off, + rows=1, + cols=span_len, + ) + span_wx = wx + span_off = off + span_len = 1 + canvas.blit( + st_scr, + top=st_wy, + left=span_wx, + src_top=0, + src_left=span_off, + rows=1, + cols=span_len, + ) + + # tty-draw.c:222-231 & 55-64: full-width soft-wrap survives onto the client + # terminal only when wy+1 is the next row of the same full-width pane and + # wy did not end with >= 10 trailing default-bg spaces (cleared via CSI K). + for wy in range(w_rows): + dst_r = canvas._rows[wy] + if not dst_r.wrapped: + continue + c0 = scene[wy][0] + keep_wrap = ( + wy + 1 < w_rows + and isinstance(c0, _PaneCell) + and all( + isinstance(slot, _PaneCell) and slot.wp is c0.wp and slot.py == c0.py + for slot in scene[wy] + ) + and all( + isinstance(slot, _PaneCell) + and slot.wp is c0.wp + and slot.py == c0.py + 1 + for slot in scene[wy + 1] + ) + ) + if keep_wrap: + trailing_empty = 0 + for cx in range(w_cols - 1, -1, -1): + if ( + dst_r.char_at(cx) == " " + and dst_r.attr_at(cx) == 0 + and dst_r.ext_at(cx) is None + ): + trailing_empty += 1 + else: + break + if trailing_empty >= 10 and not ( + trailing_empty == w_cols and wy > 0 and canvas._rows[wy - 1].wrapped + ): + keep_wrap = False + if not keep_wrap: + dst_r.wrapped = False + dst_r.trim_trailing_blanks() + + if active_pane is not None and active_pane.pane_id in resolved: + act_snap = resolved[active_pane.pane_id] + cur = act_snap.cursor + # server-client.c: pending_wrap places s->cx at pane_width; when a right + # divider column exists inside the window, the cursor lands visibly on + # that divider. At raw_cx == w_cols, tmux >= 3.7 hides the cursor via + # screen_redraw_get_visible_ranges while tmux <= 3.6 keeps cursor=1. + s_cx = ( + active_pane.width + if cur.pending_wrap + else min(max(0, cur.col), max(0, active_pane.width - 1)) + ) + pane_row_ok = 0 <= cur.row < active_pane.height + raw_cx = active_pane.left + s_cx + raw_cy = active_pane.top + min(max(0, cur.row), max(0, active_pane.height - 1)) + x_ok = (0 <= raw_cx < w_cols) if ver >= (3, 7) else (0 <= raw_cx <= w_cols) + in_bounds = pane_row_ok and x_ok and (0 <= raw_cy < w_rows) + out_cur = Cursor( + row=min(w_rows - 1, max(0, raw_cy)), + col=min(w_cols - 1, max(0, raw_cx)), + visible=cur.visible and in_bounds, + shape=cur.shape, + blinking=cur.blinking, + pending_wrap=False, + ) + return canvas.snapshot( + cursor=out_cur, + title=act_snap.title, + cwd=act_snap.cwd, + cwd_uri=act_snap.cwd_uri, + modes=act_snap.modes, + active_is_alt=act_snap.active_is_alt, + appearance=act_snap.appearance, + program_status=act_snap.program_status, + program_statuses=act_snap.program_statuses, + generation=total_gen, + profile=profile, + ) + + return canvas.snapshot( + cursor=Cursor(row=0, col=0, visible=False), + modes=_DEFAULT_BASELINE_MODES, + generation=total_gen, + profile=profile, + ) + + +def _parse_window_list_section( + lines: collections.abc.Sequence[str], + nonce: str, +) -> TmuxWindowLayout: + win_prefix = f"{nonce}:WIN:" + pane_prefix = f"{nonce}:PANE:" + end_marker = f"{nonce}:END" + + if not lines or not lines[0].startswith(win_prefix): + msg = "missing tmux window list WIN header" + raise ValueError(msg) + if lines[-1] != end_marker: + msg = "missing tmux window list END footer" + raise ValueError(msg) + + win_raw = lines[0][len(win_prefix) :] + pane_raws: list[str] = [] + for ln in lines[1:-1]: + if ln.startswith(pane_prefix): + pane_raws.append(ln[len(pane_prefix) :]) + elif pane_raws: + pane_raws[-1] = f"{pane_raws[-1]}\n{ln}" + else: + msg = f"unexpected line in tmux window list output: {ln[:32]!r}" + raise ValueError(msg) + return TmuxWindowLayout.from_format_lines(win_raw, pane_raws) + + +@dataclass(frozen=True, slots=True) +class TmuxWindowListCommand: + """Stateless Step 1 ``tmux`` command querying window geometry and panes. + + Attributes + ---------- + argv : tuple[str, ...] + Chained ``tmux`` ``display-message`` + ``list-panes`` arguments. + nonce : str + Boundary sentinel token prefixing output lines. + """ + + argv: tuple[str, ...] + nonce: str + + def parse(self, output: CaptureInput) -> TmuxWindowLayout: + r"""Parse ``tmux`` stdout from :attr:`argv` into a :class:`TmuxWindowLayout`. + + Parameters + ---------- + output : CaptureInput + Raw stdout ``str``/``bytes`` or line sequence produced by :attr:`argv`. + + Returns + ------- + TmuxWindowLayout + Parsed window geometry, border options, theme state, and panes. + + Raises + ------ + ValueError + If expected ``WIN`` or ``END`` boundary markers are missing. + + Examples + -------- + >>> from libvt.contrib.tmux.window import build_tmux_window_list_command + >>> cmd = build_tmux_window_list_command("@0", nonce="WIN_NONCE_1") + >>> pane_row = ( + ... "WIN_NONCE_1:PANE:%0\t0\t0\t0\t20\t6\t1\t0\t0" + ... "\tsingle\toff\tfg=white\tfg=green\t0" + ... ) + >>> layout = cmd.parse( + ... [ + ... "WIN_NONCE_1:WIN:@0\t20\t6\t0\tsingle\toff\tcolour\tfg=white\t", + ... pane_row, + ... "WIN_NONCE_1:END", + ... ] + ... ) + >>> (layout.window_id, layout.width, len(layout.panes)) + ('@0', 20, 1) + """ + return _parse_window_list_section(_split_capture_lines(output), self.nonce) + + +def build_tmux_window_list_command( + target: str | None = None, + *, + nonce: str | None = None, +) -> TmuxWindowListCommand: + r"""Build Step 1 ``tmux`` command querying window layout and pane descriptors. + + Chains ``display-message`` and ``list-panes`` in one atomic ``tmux`` + command-queue batch so window dimensions, zoom state, client theme colors, + border styles, and expanded ``pane-border-format`` strings come from a + single server tick. + + Parameters + ---------- + target : str | None, optional + Optional ``tmux`` target window (e.g. ``"@0"`` or ``"mysess:0"``); + ``None`` targets the current window. + nonce : str | None, optional + Explicit ASCII boundary token matching ``[0-9A-Za-z_-]{8,96}``; + generated via :func:`secrets.token_hex` when ``None``. + + Returns + ------- + TmuxWindowListCommand + Command specification with :attr:`~TmuxWindowListCommand.argv` and + :meth:`~TmuxWindowListCommand.parse`. + + Raises + ------ + ValueError + If *target* or *nonce* is invalid. + + Examples + -------- + >>> from libvt.contrib.tmux.window import build_tmux_window_list_command + >>> cmd = build_tmux_window_list_command("@0", nonce="WIN_LIST_1") + >>> "list-panes" in cmd.argv + True + """ + if target is not None and ( + not target or any(ch in target for ch in ("\x00", "\r", "\n")) + ): + msg = f"invalid tmux target {target[:64]!r}" + raise ValueError(msg) + eff_nonce = f"__LIBVT_WIN_{secrets.token_hex(12)}__" if nonce is None else nonce + if _WINDOW_NONCE_RE.match(eff_nonce) is None: + msg = ( + f"invalid tmux window nonce {eff_nonce[:64]!r}; expected 8..96 " + "[0-9A-Za-z_-] characters" + ) + raise ValueError(msg) + + t_args: tuple[str, ...] = ( + ("-t", _escape_tmux_arg(target)) if target is not None else () + ) + argv = ( + "display-message", + "-p", + *t_args, + f"{eff_nonce}:WIN:{TMUX_WINDOW_METADATA_FORMAT}", + ";", + "list-panes", + *t_args, + "-F", + f"{eff_nonce}:PANE:{TMUX_WINDOW_PANE_FORMAT}", + ";", + "display-message", + "-p", + *t_args, + f"{eff_nonce}:END", + ) + return TmuxWindowListCommand(argv=argv, nonce=eff_nonce) + + +@dataclass(frozen=True, slots=True) +class TmuxWindowCaptureResult: + """Decoded ``tmux`` window capture of pane application screens. + + Attributes + ---------- + snapshot : Snapshot + Composited application-screen :class:`~libvt.terminal.Snapshot`, + excluding copy-mode overlays (use :func:`~libvt.aio.open_pty` for client + views) and inheriting ``capture-pane`` erased-bg and emoji-width limits. + panes : collections.abc.Mapping[str, TmuxCaptureResult] + Read-only ``pane_id`` to :class:`TmuxCaptureResult` mapping. + layout : TmuxWindowLayout + Window geometry and border options used during compositing. + zoomed : bool + ``True`` when captured zoomed. + layout_stable : bool + ``True`` when post-capture size, zoom, active pane, and layout matched. + """ + + snapshot: Snapshot + panes: collections.abc.Mapping[str, TmuxCaptureResult] + layout: TmuxWindowLayout + zoomed: bool + layout_stable: bool = True + + +@dataclass(frozen=True, slots=True) +class TmuxWindowCaptureCommand: + """Stateless ``tmux`` command capturing all panes in a window. + + Attributes + ---------- + argv : tuple[str, ...] + Chained ``tmux`` ``display-message`` + ``capture-pane`` arguments across + every pane in :attr:`layout` (optionally prefixed with an inline + :class:`TmuxWindowListCommand` when ``include_layout=True``). + layout : TmuxWindowLayout + Window layout from Step 1 or :func:`parse_tmux_window_layout`. + nonce : str + Outer boundary sentinel token bracketing per-pane sections. + pane_commands : tuple[tuple[str, TmuxCaptureCommand], ...] + Ordered ``(pane_id, capture_command)`` pairs chained inside :attr:`argv`. + include_layout : bool + ``True`` when :attr:`argv` embeds a fresh ``WIN`` + ``list-panes`` + header ahead of the per-pane captures for 1-round-trip capture. + tmux_version : tuple[int, int] | str + Target ``tmux`` version forwarded to :func:`composite_tmux_window`. + """ + + argv: tuple[str, ...] + layout: TmuxWindowLayout + nonce: str + pane_commands: tuple[tuple[str, TmuxCaptureCommand], ...] + include_layout: bool = False + tmux_version: tuple[int, int] | str = "3.8a" + + def parse( + self, + output: CaptureInput, + *, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy = TMUX_CAPTURE_POLICY, + limits: Limits = DEFAULT_LIMITS, + ) -> TmuxWindowCaptureResult: + r"""Decode chained multi-pane ``tmux`` stdout and composite the window. + + Parameters + ---------- + output : CaptureInput + Raw stdout ``str``/``bytes`` or line sequence produced by :attr:`argv`. + scrollback : int | None, optional + Explicit per-pane scrollback ceiling override. + profile : Profile | None, optional + Compatibility profile override; defaults to + ``tmux_profile(self.tmux_version)``. + policy : Policy, default TMUX_CAPTURE_POLICY + Security policy for reconstructed pane terminals. + limits : Limits, default DEFAULT_LIMITS + Resource ceilings for reconstructed pane terminals. + + Returns + ------- + TmuxWindowCaptureResult + Composited window snapshot, per-pane capture results, and layout. + + Raises + ------ + ValueError + If *output* is missing expected per-pane or ``WIN_POST`` markers. + + Examples + -------- + >>> from libvt.contrib.tmux.window import ( + ... TmuxWindowLayout, + ... TmuxWindowPane, + ... build_tmux_window_capture_command, + ... ) + >>> layout = TmuxWindowLayout( + ... window_id="@0", + ... width=8, + ... height=2, + ... panes=(TmuxWindowPane("%0", width=8, height=2, active=True),), + ... ) + >>> cmd = build_tmux_window_capture_command(layout, nonce="WCAP_NONCE") + >>> res = cmd.parse( + ... [ + ... "WCAP_NONCE:PANE_START:0", + ... "WCAP_NONCE_P0:PRE:8\t2\t2\t0", + ... "WCAP_NONCE_P0:CAPTURE", + ... "- ok", + ... "- ", + ... "WCAP_NONCE_P0:POST:8\t2\t2\t0", + ... "WCAP_NONCE:WIN_POST:@0\t8\t2\t0\t", + ... ] + ... ) + >>> res.snapshot.lines, res.panes["%0"].snapshot.lines, res.layout_stable + (('ok', ''), ('ok', ''), True) + """ + lines = _split_capture_lines(output) + win_post_prefix = f"{self.nonce}:WIN_POST:" + win_post_idx = -1 + for idx in range(len(lines) - 1, -1, -1): + if lines[idx].startswith(win_post_prefix): + win_post_idx = idx + break + if win_post_idx < 0: + msg = "missing tmux window capture WIN_POST footer" + raise ValueError(msg) + + search_from = 0 + eff_layout = self.layout + if self.include_layout: + list_nonce = f"{self.nonce}_L" + list_end = f"{list_nonce}:END" + list_end_idx = -1 + for idx in range(win_post_idx): + if lines[idx] == list_end: + list_end_idx = idx + break + if list_end_idx < 0: + msg = f"missing inline tmux window list END marker: {list_end}" + raise ValueError(msg) + eff_layout = _parse_window_list_section( + lines[: list_end_idx + 1], list_nonce + ) + search_from = list_end_idx + 1 + + eff_profile = tmux_profile(self.tmux_version) if profile is None else profile + pane_results: dict[str, TmuxCaptureResult] = {} + if self.pane_commands: + start_indices: list[int] = [] + for idx in range(len(self.pane_commands)): + marker = f"{self.nonce}:PANE_START:{idx}" + found = -1 + for pos in range(search_from, win_post_idx): + if lines[pos] == marker: + found = pos + break + if found < 0: + msg = f"missing tmux window capture marker: {marker}" + raise ValueError(msg) + start_indices.append(found) + search_from = found + 1 + + stops = [*start_indices[1:], win_post_idx] + for idx, (pane_id, p_cmd) in enumerate(self.pane_commands): + chunk = lines[start_indices[idx] + 1 : stops[idx]] + pane_results[pane_id] = p_cmd.parse( + chunk, + scrollback=scrollback, + profile=eff_profile, + policy=policy, + limits=limits, + ) + + post_raw = lines[win_post_idx][len(win_post_prefix) :] + post_parts = post_raw.split("\t", 5) + if len(post_parts) < 6: + post_parts.extend([""] * (6 - len(post_parts))) + post_w = _opt_int(post_parts[1], eff_layout.width) + post_h = _opt_int(post_parts[2], eff_layout.height) + post_zoomed = _opt_bool(post_parts[3], default=eff_layout.zoomed) + post_layout = post_parts[4].strip() + post_active_id = post_parts[5].strip() + cursor_pane = eff_layout.active_pane + cursor_pane_id = cursor_pane.pane_id if cursor_pane is not None else "" + panes_complete = all(wp.pane_id in pane_results for wp in eff_layout.panes) + stable = ( + panes_complete + and post_w == eff_layout.width + and post_h == eff_layout.height + and post_zoomed == eff_layout.zoomed + and ( + not eff_layout.window_layout or post_layout == eff_layout.window_layout + ) + and (not post_active_id or post_active_id == cursor_pane_id) + ) + + win_snap = composite_tmux_window( + eff_layout, + pane_results, + tmux_version=self.tmux_version, + profile=eff_profile, + ) + return TmuxWindowCaptureResult( + snapshot=win_snap, + panes=types.MappingProxyType(pane_results), + layout=eff_layout, + zoomed=eff_layout.zoomed, + layout_stable=stable, + ) + + +def build_tmux_window_capture_command( + layout: TmuxWindowLayout, + *, + tmux_version: tuple[int, int] | str = "3.8a", + include_saved_primary: bool = False, + history_lines: int | None = 0, + include_layout: bool = False, + nonce: str | None = None, +) -> TmuxWindowCaptureCommand: + r"""Build an atomic ``tmux`` command capturing every pane in *layout*. + + Chains per-pane :func:`build_tmux_capture_command` invocations separated by + ``";"`` inside a single ``tmux`` command batch, optionally prepending an + inline :func:`build_tmux_window_list_command` header when + ``include_layout=True`` (for 1-round-trip capture from + :func:`parse_tmux_window_layout`), and appends a ``WIN_POST`` layout + stability check. + + Parameters + ---------- + layout : TmuxWindowLayout + Window descriptor from :func:`build_tmux_window_list_command` or + :func:`parse_tmux_window_layout`. + tmux_version : tuple[int, int] | str, default "3.8a" + Target ``tmux`` version string or ``(major, minor)`` tuple. + include_saved_primary : bool, default False + Whether each per-pane capture includes ``capture-pane -a -q`` primary + history when ``alternate_on`` is active. + history_lines : int | None, default 0 + Scrollback lines captured per pane (``0`` for viewport-only, ``None`` + for full history, or ``N > 0`` for ``-S -N``). + include_layout : bool, default False + When ``True``, query live window metadata, client theme colors, border + styles, and ``pane-border-format`` inline in the same ``tmux`` batch. + nonce : str | None, optional + Explicit ASCII boundary token matching ``[0-9A-Za-z_-]{8,80}``; + generated via :func:`secrets.token_hex` when ``None``. + + Returns + ------- + TmuxWindowCaptureCommand + Chained multi-pane capture command with + :attr:`~TmuxWindowCaptureCommand.argv` and + :meth:`~TmuxWindowCaptureCommand.parse`. + + Raises + ------ + TypeError + If *history_lines* is not an ``int`` or ``None``. + ValueError + If *tmux_version*, *history_lines*, or *nonce* is invalid. + + Examples + -------- + >>> from libvt.contrib.tmux.window import ( + ... TmuxWindowLayout, + ... TmuxWindowPane, + ... build_tmux_window_capture_command, + ... ) + >>> layout = TmuxWindowLayout( + ... panes=(TmuxWindowPane("%0"), TmuxWindowPane("%1", active=True)), + ... ) + >>> cmd = build_tmux_window_capture_command(layout, nonce="WCAP_1234") + >>> len(cmd.pane_commands) + 2 + """ + eff_hist = _validate_history_lines(history_lines) + eff_nonce = f"__LIBVT_WCAP_{secrets.token_hex(12)}__" if nonce is None else nonce + if len(eff_nonce) > 80 or _WINDOW_NONCE_RE.match(eff_nonce) is None: + msg = ( + f"invalid tmux window nonce {eff_nonce[:64]!r}; expected 8..80 " + "[0-9A-Za-z_-] characters" + ) + raise ValueError(msg) + if layout.window_id and any(ch in layout.window_id for ch in ("\x00", "\r", "\n")): + msg = f"invalid tmux window_id {layout.window_id[:64]!r}" + raise ValueError(msg) + + parse_tmux_version(tmux_version) + argv: list[str] = [] + if include_layout: + list_cmd = build_tmux_window_list_command( + layout.window_id or None, + nonce=f"{eff_nonce}_L", + ) + argv.extend(list_cmd.argv) + + pane_cmds: list[tuple[str, TmuxCaptureCommand]] = [] + for idx, wp in enumerate(layout.panes): + p_cmd = build_tmux_capture_command( + wp.pane_id, + tmux_version=tmux_version, + include_saved_primary=include_saved_primary, + history_lines=eff_hist, + nonce=f"{eff_nonce}_P{idx}", + ) + pane_cmds.append((wp.pane_id, p_cmd)) + if argv: + argv.append(";") + argv.extend( + [ + "display-message", + "-p", + f"{eff_nonce}:PANE_START:{idx}", + ";", + *p_cmd.argv, + ] + ) + + win_t_args: tuple[str, ...] = ( + ("-t", _escape_tmux_arg(layout.window_id)) if layout.window_id else () + ) + if argv: + argv.append(";") + argv.extend( + [ + "display-message", + "-p", + *win_t_args, + ( + f"{eff_nonce}:WIN_POST:" + "#{window_id}\t#{window_width}\t#{window_height}\t" + "#{window_zoomed_flag}\t#{window_layout}\t#{pane_id}" + ), + ] + ) + return TmuxWindowCaptureCommand( + argv=tuple(argv), + layout=layout, + nonce=eff_nonce, + pane_commands=tuple(pane_cmds), + include_layout=include_layout, + tmux_version=tmux_version, + ) + + +__all__ = [ + "TMUX_WINDOW_METADATA_FORMAT", + "TMUX_WINDOW_PANE_FORMAT", + "TmuxPaneSource", + "TmuxWindowCaptureCommand", + "TmuxWindowCaptureResult", + "TmuxWindowLayout", + "TmuxWindowListCommand", + "TmuxWindowPane", + "build_tmux_window_capture_command", + "build_tmux_window_list_command", + "composite_tmux_window", + "parse_tmux_window_layout", +] diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 7c933b8..4b15ae4 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -20,14 +20,27 @@ _HistoryBuffer, _Row, _RowGenCounter, + make_cell_ext, + pack_pen_base, raw_width_bits, unpack_style, unpack_width_role, ) -from libvt._ucd import WidthRole +from libvt._ucd import ( + SAFE_NARROW_BMP_RE, + WidthRole, + display_width, + segment_graphemes, +) +from libvt.config import DEFAULT_PROFILE, Profile from libvt.graphics import GraphicsTracker, ImageMeta, ImagePlacement from libvt.input import KittyKeyboardStack -from libvt.style import DEFAULT_STYLE, Hyperlink, Style +from libvt.modes import Mode +from libvt.status import ProgramStatus +from libvt.style import DEFAULT_APPEARANCE, DEFAULT_STYLE, Appearance, Hyperlink, Style + +if t.TYPE_CHECKING: + from libvt.terminal import Snapshot _ITEM0 = operator.itemgetter(0) @@ -936,6 +949,7 @@ class Screen: "_modify_other_keys", "_on_mutate", "_pending_wrap", + "_profile", "_rows", "_scrolled_total", "_tabstops", @@ -958,12 +972,14 @@ def __init__( max_image_dimension: int = 10_000, is_alt: bool = False, top_margin_scrolls_to_history: bool = False, + profile: Profile = DEFAULT_PROFILE, on_mutate: collections.abc.Callable[[bool], None] | None = None, ) -> None: if rows < 1 or cols < 1: msg = f"rows and cols must be >= 1, got ({rows}, {cols})" raise ValueError(msg) self._cols = cols + self._profile: Profile = profile self._gen_counter: _RowGenCounter = _RowGenCounter() self._on_mutate = on_mutate self._rows: list[_Row] = [ @@ -1895,6 +1911,420 @@ def reset(self) -> None: if self._gfx is not None: self._gfx.reset() + def blit( + self, + source: Snapshot | Screen | RegionView, + *, + top: int = 0, + left: int = 0, + src_top: int = 0, + src_left: int = 0, + rows: int | None = None, + cols: int | None = None, + preserve_wrap: bool = False, + ) -> None: + r"""Copy a rectangular 2D cell region from *source* onto this screen. + + Copies packed 64-bit SGR attributes, grapheme strings, + :class:`~libvt._ucd.WidthRole`, ``OSC 8`` hyperlinks, and ``DECSCA`` + protection without re-encoding ANSI sequences. Out-of-bounds source or + destination coordinates clip cleanly, split wide glyphs heal to narrow + blanks at clip boundaries, and source ``SPACER_HEAD`` soft-wrap markers + convert to narrow blanks. Rows overwritten up to ``cols`` clear + ``wrapped`` unless *preserve_wrap* is ``True`` on a full-width copy. + + Parameters + ---------- + source : Snapshot | Screen | RegionView + Source grid surface to copy cells from. + top : int, default 0 + Destination zero-based top row offset (negative values clip). + left : int, default 0 + Destination zero-based left column offset (negative values clip). + src_top : int, default 0 + Source zero-based starting row offset. + src_left : int, default 0 + Source zero-based starting column offset. + rows : int | None, optional + Maximum row count to copy; ``None`` copies ``source.rows - src_top``. + cols : int | None, optional + Maximum column count to copy; ``None`` copies ``source.cols - src_left``. + preserve_wrap : bool, default False + Preserve source ``wrapped`` flags when blitting full-width rows + (``dst_col == 0`` and ``width == self.cols == source_row.cols``). + + Examples + -------- + >>> from libvt.screen import Screen + >>> from libvt.terminal import Terminal + >>> pane = Terminal(rows=2, cols=6) + >>> pane.feed("日本!\r\nok".encode()) + >>> canvas = Screen(rows=3, cols=10) + >>> canvas.blit(pane.committed, top=1, left=2) + >>> canvas.lines + ('', ' 日本!', ' ok') + """ + for label, val in ( + ("top", top), + ("left", left), + ("src_top", src_top), + ("src_left", src_left), + ): + if isinstance(val, bool) or not isinstance(val, int): + msg = f"{label} must be int, got {type(val).__name__}" + raise TypeError(msg) + for label, opt_val in (("rows", rows), ("cols", cols)): + if opt_val is not None and ( + isinstance(opt_val, bool) or not isinstance(opt_val, int) + ): + msg = f"{label} must be int or None, got {type(opt_val).__name__}" + raise TypeError(msg) + + if isinstance(source, Screen): + src_rows: collections.abc.Sequence[RowLike] = source._rows + src_col_base = 0 + 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) + else: + from libvt.terminal import Snapshot as _Snapshot + + if isinstance(source, _Snapshot): + src_rows = source._rows + src_col_base = 0 + src_cols = source._cols + else: + msg = ( + "source must be Snapshot, Screen, or RegionView, got " + f"{type(source).__name__}" + ) + raise TypeError(msg) + + src_h = len(src_rows) + dst_h = len(self._rows) + dst_w = self._cols + eff_rows = (src_h - src_top) if rows is None else rows + eff_cols = (src_cols - src_left) if cols is None else cols + if eff_rows <= 0 or eff_cols <= 0: + return + + r_k0 = max(0, -top, -src_top) + r_k1 = min(eff_rows, dst_h - top, src_h - src_top) + c_j0 = max(0, -left, -src_left) + c_j1 = min(eff_cols, dst_w - left, src_cols - src_left) + if r_k0 >= r_k1 or c_j0 >= c_j1: + return + + h = r_k1 - r_k0 + w = c_j1 - c_j0 + dst_r0 = top + r_k0 + src_r0 = src_top + r_k0 + dst_c0 = left + c_j0 + dst_c1 = dst_c0 + w + raw_sc0 = src_col_base + src_left + c_j0 + + if self._on_mutate is not None: + self._on_mutate(False) + + self_ids = {id(r) for r in self._rows} + raw_slice = src_rows[src_r0 : src_r0 + h] + src_slice: collections.abc.Sequence[RowLike] = ( + [r.clone() if isinstance(r, _Row) else r for r in raw_slice] + if any(id(r) in self_ids for r in raw_slice) + else raw_slice + ) + + full_dst_width = dst_c0 == 0 and dst_c1 == dst_w and raw_sc0 == 0 + for k in range(h): + dr = dst_r0 + k + src_r = src_slice[k] + self.heal_before_edit(dr, dst_c0, dst_c1) + dst_row = self._rows[dr] + if dst_c1 >= dst_w: + dst_row.wrapped = bool( + preserve_wrap + and full_dst_width + and w == src_r.cols + and src_r.wrapped + and dr + 1 < dst_h + ) + dst_row.blit_from(src_r, dst_col=dst_c0, src_col=raw_sc0, width=w) + + if self._gfx is not None and self._gfx.has_sixels: + self._gfx.erase_sixel_rect( + row=dst_r0, + col=dst_c0, + rows=h, + cols=w, + scrolled_total=self._scrolled_total, + policy=self._profile.screen.sixel_erase_policy, + ) + + def put_text( + self, + row: int, + col: int, + text: str, + *, + style: Style = DEFAULT_STYLE, + hyperlink: Hyperlink | None = None, + protected: bool = False, + max_cols: int | None = None, + profile: Profile | None = None, + ) -> int: + r"""Write display-width-aware *text* onto *row* starting at *col*. + + Places narrow, wide, and combining grapheme clusters on a single row + without moving :attr:`cursor` or setting ``wrapped``, clipping negative + *col* offsets and healing split wide cells at start and end boundaries. + + Parameters + ---------- + row : int + Zero-based destination row index (out-of-range values return ``0``). + col : int + Zero-based starting column index (negative values left-clip). + text : str + Text to draw; control characters are skipped and wide clusters stop + before overflowing ``max_cols`` or ``cols``. + style : Style, default DEFAULT_STYLE + Cell SGR rendition applied to written clusters. + hyperlink : Hyperlink | None, optional + ``OSC 8`` hyperlink attached to written cells. + protected : bool, default False + ``DECSCA`` character-protection flag respected by ``DECSED`` and + ``DECSEL``. + max_cols : int | None, optional + Maximum display columns to examine from *col*; ``None`` writes up to + ``cols - col``. + profile : Profile | None, optional + Compatibility profile used for grapheme display width; defaults to + this screen's profile. + + Returns + ------- + int + Number of visible destination columns written on ``0..cols``. + + Examples + -------- + >>> from libvt.screen import Screen + >>> from libvt.style import AnsiColor, Style + >>> scr = Screen(rows=1, cols=8) + >>> scr.put_text(0, 1, "日本ok", style=Style(fg=AnsiColor.GREEN), max_cols=5) + 5 + >>> scr.lines, scr[0, 1].style.fg + ((' 日本o',), ) + """ + if isinstance(row, bool) or not isinstance(row, int): + msg = f"row must be int, got {type(row).__name__}" + raise TypeError(msg) + if isinstance(col, bool) or not isinstance(col, int): + msg = f"col must be int, got {type(col).__name__}" + raise TypeError(msg) + if max_cols is not None and ( + isinstance(max_cols, bool) or not isinstance(max_cols, int) + ): + msg = f"max_cols must be int or None, got {type(max_cols).__name__}" + raise TypeError(msg) + + if row < 0 or row >= len(self._rows) or col >= self._cols or not text: + return 0 + stop_col = self._cols if max_cols is None else min(self._cols, col + max_cols) + if stop_col <= 0 or (max_cols is not None and max_cols <= 0): + return 0 + + eff_profile = self._profile if profile is None else profile + pen_word = pack_pen_base(style) + cell_ext = make_cell_ext(style, hyperlink, protected=bool(protected)) + row_obj = self._rows[row] + + if ( + col >= 0 + and eff_profile.unicode.ambiguous_width == 1 + and SAFE_NARROW_BMP_RE.fullmatch(text) is not None + ): + avail = stop_col - col + if avail <= 0: + return 0 + sub = text[:avail] + n = len(sub) + if self._on_mutate is not None: + self._on_mutate(False) + self.heal_before_edit(row, col, col + n) + row_obj.write_ascii_slice(col, sub, pen_word, cell_ext) + if self._gfx is not None and self._gfx.has_sixels: + self._gfx.erase_sixel_rect( + row=row, + col=col, + rows=1, + cols=n, + scrolled_total=self._scrolled_total, + policy=eff_profile.screen.sixel_erase_policy, + ) + return n + + start_c = max(0, col) + clusters: list[tuple[str, int]] = [] + pos = col + skip_clipped_combining = False + for cluster in segment_graphemes(text): + cp0 = ord(cluster[0]) + if cp0 < 0x20 or 0x7F <= cp0 <= 0x9F: + continue + cw = display_width(cluster, profile=eff_profile) + if cw == 0: + if not skip_clipped_combining and clusters: + prev_cl, prev_cw = clusters[-1] + clusters[-1] = (prev_cl + cluster, prev_cw) + continue + if pos < 0: + if pos + cw <= 0: + pos += cw + skip_clipped_combining = True + continue + # Wide glyph straddling -1..0 clips its right half to a blank at 0. + if stop_col < 1: + break + clusters.append((" ", 1)) + pos = 1 + skip_clipped_combining = True + continue + skip_clipped_combining = False + if pos + cw > stop_col: + break + clusters.append((cluster, cw)) + pos += cw + + cols_written = pos - start_c + if cols_written <= 0 or not clusters: + return 0 + + if self._on_mutate is not None: + self._on_mutate(False) + self.heal_before_edit(row, start_c, start_c + cols_written) + cur_c = start_c + for cluster, cw in clusters: + if cw == 2: + row_obj.write_wide(cur_c, cluster, pen_word, cell_ext) + cur_c += 2 + else: + row_obj.write_narrow(cur_c, cluster, pen_word, cell_ext) + cur_c += 1 + if self._gfx is not None and self._gfx.has_sixels: + self._gfx.erase_sixel_rect( + row=row, + col=start_c, + rows=1, + cols=cols_written, + scrolled_total=self._scrolled_total, + policy=eff_profile.screen.sixel_erase_policy, + ) + return cols_written + + def snapshot( + self, + *, + cursor: Cursor | None = None, + title: str = "", + cwd: str = "", + cwd_uri: str = "", + modes: frozenset[Mode] = frozenset(), + active_is_alt: bool = False, + appearance: Appearance | None = None, + program_status: ProgramStatus | None = None, + program_statuses: collections.abc.Mapping[str, ProgramStatus] | None = None, + generation: int | None = None, + profile: Profile | None = None, + ) -> Snapshot: + r"""Freeze this screen into an immutable :class:`~libvt.terminal.Snapshot`. + + Clones visible viewport rows and CoW scrollback blocks so subsequent + edits on this :class:`Screen` never mutate the returned snapshot. + + Parameters + ---------- + cursor : Cursor | None, optional + Explicit cursor state for the snapshot; defaults to + :attr:`~libvt.screen.Screen.cursor`. + title : str, default "" + Window title metadata stored on the snapshot. + cwd : str, default "" + Working directory path stored on the snapshot. + cwd_uri : str, default "" + Raw ``OSC 7`` / ``OSC 9;9`` working directory URI. + modes : frozenset[Mode], optional + Enabled ANSI and DEC private modes stored on the snapshot. + active_is_alt : bool, default False + Whether the snapshot marks the alternate screen active (omitting + primary scrollback when ``True``). + appearance : Appearance | None, optional + Theme scheme, default RGBs, palette overrides, and reverse-video + state; inferred from *modes* when ``None``. + program_status : ProgramStatus | None, optional + Highest-urgency ``OSC 7501`` / ``OSC 9;4`` status record. + program_statuses : Mapping[str, ProgramStatus] | None, optional + Active ``OSC 7501`` task records keyed by ``id``. + generation : int | None, optional + Explicit generation watermark; defaults to the row mutation counter. + profile : Profile | None, optional + Terminal compatibility profile stored on the snapshot; defaults to + this screen's profile. + + Returns + ------- + Snapshot + Point-in-time immutable screen capture. + + Examples + -------- + >>> from libvt.screen import Cursor, Screen + >>> scr = Screen(rows=2, cols=8) + >>> _ = scr.put_text(0, 0, "ready") + >>> snap = scr.snapshot(cursor=Cursor(row=0, col=5)) + >>> _ = scr.put_text(0, 0, "later") + >>> snap.lines, (snap.cursor.row, snap.cursor.col) + (('ready', ''), (0, 5)) + """ + from libvt.terminal import _make_snapshot + + eff_cursor = self.cursor if cursor is None else cursor + eff_modes = frozenset(modes) + eff_app = ( + ( + Appearance(reverse_video=True) + if Mode.DECSCNM in eff_modes + else DEFAULT_APPEARANCE + ) + if appearance is None + else appearance + ) + return _make_snapshot( + rows=tuple(r.clone() for r in self._rows), + history=( + _EMPTY_FROZEN_HISTORY if active_is_alt else self._history.freeze() + ), + cols=self._cols, + cursor=eff_cursor, + title=title, + cwd=cwd, + cwd_uri=cwd_uri, + modes=eff_modes, + active_is_alt=active_is_alt, + prompt_zones=(), + program_status=program_status, + program_statuses={} if program_statuses is None else program_statuses, + generation=self._gen_counter.value if generation is None else generation, + appearance=eff_app, + images=self.images, + placements=self.placements, + scrolled_total=0 if active_is_alt else self._scrolled_total, + evicted_total=0 if active_is_alt else self._evicted_total, + profile=self._profile if profile is None else profile, + ) + class ScreenSet: """Dual primary and alternate (``?1049``) screen pair.""" @@ -1913,6 +2343,7 @@ def __init__( max_placements: int = 1_024, max_image_dimension: int = 10_000, top_margin_scrolls_to_history: bool = False, + profile: Profile = DEFAULT_PROFILE, on_mutate: collections.abc.Callable[[bool], None] | None = None, ) -> None: counter = _RowGenCounter() @@ -1928,6 +2359,7 @@ def __init__( max_placements=max_placements, max_image_dimension=max_image_dimension, top_margin_scrolls_to_history=top_margin_scrolls_to_history, + profile=profile, on_mutate=on_mutate, ) self.primary._bind_counter(counter) @@ -1941,6 +2373,7 @@ def __init__( max_placements=max_placements, max_image_dimension=max_image_dimension, is_alt=True, + profile=profile, on_mutate=on_mutate, ) self.alternate._bind_counter(counter) diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index e358f3c..cdb7c22 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -2085,6 +2085,7 @@ def __init__( max_placements=limits.max_placements, max_image_dimension=limits.max_image_dimension, top_margin_scrolls_to_history=profile.screen.top_margin_scrolls_to_history, + profile=profile, on_mutate=self._on_screen_mutate, ) self._modes = ModeState( @@ -3497,6 +3498,11 @@ def reset(self, *, soft: bool = False) -> None: def _on_screen_mutate(self, structural: bool) -> None: self._before_mutate() + self._last_printed = "" + self._last_printed_pos = None + self._cluster_state = CLUSTER_NONE + self._cluster_len = 0 + self._pending_prepend = "" if structural: self._epoch += 1 diff --git a/tests/test_screen.py b/tests/test_screen.py index e2b583f..d37bf5e 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -12,12 +12,21 @@ import pytest import libvt +from libvt._grid import raw_width_bits from libvt._ucd import WidthRole -from libvt.config import DEFAULT_PROFILE, Profile +from libvt.config import DEFAULT_PROFILE, Profile, ScreenBehavior, UnicodeBehavior from libvt.events import InBandResize from libvt.modes import Mode from libvt.profiles import XTERM_PROFILE -from libvt.style import AnsiColor +from libvt.screen import Cursor, Screen +from libvt.style import ( + AnsiColor, + Hyperlink, + IndexedColor, + RgbColor, + Style, + UnderlineStyle, +) def _assert_grid_invariants(term: libvt.Terminal) -> None: @@ -477,3 +486,232 @@ def test_array_q_memoryview_and_moving_gc_stability() -> None: assert snap_before.history[0].text.endswith("日本") assert term[0].text == "cleared" _assert_grid_invariants(term) + + +def _assert_blit_cell_invariants( + target: Screen | libvt.Snapshot, + *, + allow_wrap: bool = True, +) -> None: + rows = target._rows + cols = target.cols + for r_idx, row in enumerate(rows): + if not allow_wrap: + assert row.wrapped is False, f"row {r_idx} unexpectedly marked wrapped" + c = 0 + while c < cols: + rb = raw_width_bits(row.attr_at(c)) + assert rb != int(WidthRole.SPACER_HEAD), ( + f"row {r_idx} col {c} leaked SPACER_HEAD" + ) + if rb == int(WidthRole.WIDE): + assert c + 1 < cols, f"row {r_idx} col {c} dangling WIDE at right edge" + next_rb = raw_width_bits(row.attr_at(c + 1)) + assert next_rb == int(WidthRole.SPACER_TAIL), ( + f"row {r_idx} col {c} WIDE not followed by SPACER_TAIL" + ) + assert row.char_at(c + 1) == "" + c += 2 + else: + assert rb == int(WidthRole.NARROW), ( + f"row {r_idx} col {c} orphaned SPACER_TAIL" + ) + c += 1 + + +def test_screen_blit_wide_clipping_hyperlinks_and_invariants() -> None: + """``Screen.blit`` heals split wide glyphs, preserves links, and scopes wraps.""" + link = Hyperlink(uri="https://libvt.git-pull.com/guide", id="g1") + rich_style = Style( + fg=RgbColor(10, 200, 120), + bg=IndexedColor(236), + bold=True, + underline=UnderlineStyle.CURLY, + underline_color=RgbColor(255, 80, 40), + ) + + src_term = libvt.Terminal(rows=3, cols=5, scrollback=10) + src_term.feed(b"HIST!\r\n") + src_term.feed("A日本".encode()) + src_term.feed("\r\nABCD漢".encode()) + src_term.feed( + b"\x1b]8;id=g1;https://libvt.git-pull.com/guide\x1b\\" + b"\x1b[1;4:3;38;2;10;200;120;48;5;236;58;2;255;80;40m" + b'\x1b[1"qOK!\x1b[0"q\x1b[0m\x1b]8;;\x1b\\' + ) + src_snap = src_term.snapshot() + assert src_snap[1].wrapped is True + assert src_snap[1][4].width_role == WidthRole.SPACER_HEAD + + # Blit from FrozenRow via scrolled viewport(offset=1). + scrolled_view = src_snap.viewport(offset=1) + dst_hist = Screen(rows=2, cols=5) + dst_hist.blit(scrolled_view, top=0, left=0, rows=2, cols=5) + assert dst_hist[0].text == "HIST!" + assert dst_hist[1].text == "A日本" + + # Shrunk non-reflow RegionView where physical row buffer was narrower is safe. + wide_term = libvt.Terminal(rows=2, cols=4) + wide_term.feed(b"XY") + wide_term.resize(rows=2, cols=8, reflow=False) + shrunk_reg = wide_term.snapshot()[0:2, 0:8] + dst_shrunk = Screen(rows=2, cols=8) + dst_shrunk.blit(shrunk_reg) + assert dst_shrunk[0].text == "XY" + + # Narrow sub-row blit inside a wrapped Terminal row preserves outer wrapped flag + # and right-margin SPACER_HEAD outside the blitted column span. + wrap_dst_term = libvt.Terminal(rows=2, cols=5) + wrap_dst_term.feed("ABCD漢X".encode()) + assert wrap_dst_term.screen[0].wrapped is True + assert wrap_dst_term.screen[0][4].width_role == WidthRole.SPACER_HEAD + patch = Screen(rows=1, cols=2) + patch.put_text(0, 0, "12") + wrap_dst_term.screen.blit(patch, top=0, left=1, rows=1, cols=2) + assert wrap_dst_term.screen[0].wrapped is True + assert wrap_dst_term.screen[0][4].width_role == WidthRole.SPACER_HEAD + assert wrap_dst_term.screen[0].text == "A12D" + + # Full-width blit clears wrapped by default and preserves when preserve_wrap=True. + dst_preserve = Screen(rows=3, cols=5) + dst_preserve.blit(src_snap, preserve_wrap=True) + assert dst_preserve[1].wrapped is True + _assert_blit_cell_invariants(dst_preserve, allow_wrap=True) + + # Clipping through source WIDE/SPACER_TAIL pairs heals both sides cleanly. + dst = Screen(rows=4, cols=8) + dst.put_text(0, 0, "漢字漢字") + dst.blit(src_term.screen, top=0, left=1, src_top=0, src_left=2, rows=1, cols=2) + _assert_blit_cell_invariants(dst, allow_wrap=False) + assert dst[0].text == " 漢字" + assert src_term.screen[0].text == "A日本" + + dst2 = Screen(rows=5, cols=9) + dst2.blit(src_snap, top=1, left=2) + snap2 = dst2.snapshot() + _assert_blit_cell_invariants(snap2, allow_wrap=False) + assert snap2[1].text == " A日本" + assert snap2[2].text == " ABCD" + assert snap2[3].text == " 漢OK!" + for col_off, ch in enumerate("OK!", start=4): + cell = snap2[3][col_off] + assert cell.text == ch + assert cell.style == rich_style + assert cell.hyperlink == link + assert cell.protected is True + + region = src_snap[0:3, 1:5] + dst3 = Screen(rows=3, cols=5) + dst3.blit(region, top=-1, left=1) + assert dst3[0].text == " BCD" + assert dst3[1].text == " OK!" + assert dst3[1][3].hyperlink == link + _assert_blit_cell_invariants(dst3, allow_wrap=False) + + dst3.blit(dst3, top=1, left=1, src_top=0, src_left=1, rows=2, cols=3) + _assert_blit_cell_invariants(dst3, allow_wrap=False) + assert dst3[1].text == " BCD!" + assert dst3[2].text == " OK" + + # Explicit trailing spaces survive blit across Screen, Snapshot, and RegionView, + # and blitting unwritten cells to the right preserves written spaces on the left. + sp_term = libvt.Terminal(rows=1, cols=8) + sp_term.feed(b"OK ") + sp_snap = sp_term.snapshot() + sp_region = sp_snap[0:1, 0:6] + for sp_src in (sp_term.screen, sp_snap, sp_region): + sp_dst = Screen(rows=1, cols=8) + sp_dst.blit(sp_src) + assert sp_dst[0].text == "OK " + assert sp_dst.snapshot()[0].text == "OK " + + keep_left = Screen(rows=1, cols=8) + keep_left.put_text(0, 0, "X ") + assert keep_left[0].text == "X " + keep_left.blit(Screen(rows=1, cols=1), top=0, left=6, cols=1) + assert keep_left[0].text == "X " + + blank_scr = Screen(rows=1, cols=2) + blank_snap = blank_scr.snapshot() + blank_region = blank_snap[0:1, 0:2] + for blank_src in (blank_scr, blank_snap, blank_region): + for dst_left, copy_cols in ((4, 1), (5, 1), (4, 2)): + split_dst = Screen(rows=1, cols=8) + split_dst.put_text(0, 0, "OK 界") + split_dst.blit(blank_src, top=0, left=dst_left, cols=copy_cols) + _assert_blit_cell_invariants(split_dst, allow_wrap=False) + assert split_dst[0].text == "OK " + assert split_dst.snapshot().lines == ("OK ",) + + with pytest.raises(TypeError, match="Snapshot, Screen, or RegionView"): + dst3.blit("not-a-screen") # type: ignore[arg-type] + + +def test_screen_put_text_sixel_cluster_and_negative_col_invariants() -> None: + """``Screen.put_text`` handles negative ``col``, SIXEL erase, and cluster reset.""" + term = libvt.Terminal( + rows=4, + cols=8, + profile=Profile(screen=ScreenBehavior(sixel_erase_policy="whole_image")), + ) + term.feed(b"\x1bPq#0;2;100;0;0#0~~~~~~\x1b\\") + assert len(term.screen.placements) == 1 + term.screen.put_text(0, 0, "OVER") + assert len(term.screen.placements) == 0 + + # Terminal grapheme-cluster state resets when term.screen.put_text mutates cells: + # feeding a bare combining acute accent afterwards does not attach to old cluster. + term2 = libvt.Terminal(rows=2, cols=6) + term2.feed(b"e") + term2.screen.put_text(0, 0, "Z") + term2.feed("\u0301".encode()) + assert term2.screen[0][0].text == "Z" + + # Negative col left-clips cleanly: wide glyph straddling col 0 becomes ' ', + # and combining marks before col 0 do not attach onto col 0's existing cell. + scr = Screen(rows=2, cols=6) + scr.put_text(0, 0, "ABCDEF") + assert scr.put_text(0, -1, "日X") == 2 + assert scr[0].text == " X" + "CDEF" + _assert_blit_cell_invariants(scr, allow_wrap=False) + + scr2 = Screen(rows=1, cols=4) + scr2.put_text(0, 0, "ABCD") + assert scr2.put_text(0, 3, "日") == 0 + assert scr2[0].text == "ABCD" + + frozen = scr2.snapshot( + cursor=Cursor(row=0, col=2, visible=False), + title="win-title", + cwd="/workspace", + cwd_uri="file://host/workspace", + modes=frozenset({Mode.DECAWM, Mode.BRACKETED_PASTE}), + active_is_alt=True, + ) + scr2.reset() + assert frozen[0].text == "ABCD" + assert frozen.cwd_uri == "file://host/workspace" + assert frozen.active_is_alt is True + + # East Asian Ambiguous characters in SAFE_NARROW_BMP_RE (like 'Ω') must take + # the 2-column path when UnicodeBehavior(ambiguous_width=2) is active. + amb2 = Profile(unicode=UnicodeBehavior(ambiguous_width=2)) + amb_term = libvt.Terminal(rows=1, cols=6, profile=amb2) + amb_term.feed("ΩX".encode()) + amb_scr = Screen(rows=1, cols=6) + assert amb_scr.put_text(0, 0, "ΩX", profile=amb2) == 3 + assert amb_scr[0][2].text == "X" + assert amb_scr[0].display_text == amb_term.screen[0].display_text + + # protected=True marks cells protected across both fast ASCII and grapheme + # write paths so DECSEL (CSI ? 2 K) preserves only the protected labels. + prot_term = libvt.Terminal(rows=1, cols=8) + prot_term.screen.put_text(0, 0, "L", protected=True) + prot_term.screen.put_text(0, 1, "u") + prot_term.screen.put_text(0, 2, "日", protected=True) + prot_term.screen.put_text(0, 4, "z") + prot_term.feed(b"\x1b[?2K") + assert prot_term.screen[0].text == "L 日" + assert prot_term.screen[0][0].protected is True + assert prot_term.screen[0][2].protected is True + assert prot_term.screen[0][1].protected is False diff --git a/tests/test_tmux_window_capture.py b/tests/test_tmux_window_capture.py new file mode 100644 index 0000000..c58d3ff --- /dev/null +++ b/tests/test_tmux_window_capture.py @@ -0,0 +1,853 @@ +"""Tests for ``Screen`` blitting and ``tmux`` multi-pane window compositing.""" + +from __future__ import annotations + +import asyncio +import os +import shutil +import subprocess +import sys +import time +import zlib + +import pytest + +from libvt import Snapshot, Terminal +from libvt._grid import raw_width_bits +from libvt._ucd import WidthRole +from libvt.aio import open_pty +from libvt.contrib.tmux import ( + TmuxPaneMetadata, + TmuxWindowCaptureResult, + TmuxWindowLayout, + TmuxWindowPane, + build_tmux_window_capture_command, + build_tmux_window_list_command, + composite_tmux_window, + decode_tmux_capture, + parse_tmux_version, + parse_tmux_window_layout, +) +from libvt.screen import Screen +from libvt.style import ( + AnsiColor, + Hyperlink, + Style, +) +from libvt.testing import format_screen_box, serialize_vt_snapshot + + +def _assert_screen_cell_invariants( + target: Screen | Snapshot, + *, + allow_wrap: bool = True, +) -> None: + """Assert packed wide-cell pairing and absence of leaked ``SPACER_HEAD`` cells.""" + rows = target._rows + cols = target.cols + for r_idx, row in enumerate(rows): + if not allow_wrap: + assert row.wrapped is False, f"row {r_idx} unexpectedly marked wrapped" + c = 0 + while c < cols: + rb = raw_width_bits(row.attr_at(c)) + assert rb != int(WidthRole.SPACER_HEAD), ( + f"row {r_idx} col {c} leaked SPACER_HEAD" + ) + if rb == int(WidthRole.WIDE): + assert c + 1 < cols, f"row {r_idx} col {c} dangling WIDE at right edge" + next_rb = raw_width_bits(row.attr_at(c + 1)) + assert next_rb == int(WidthRole.SPACER_TAIL), ( + f"row {r_idx} col {c} WIDE not followed by SPACER_TAIL" + ) + assert row.char_at(c + 1) == "" + c += 2 + else: + assert rb == int(WidthRole.NARROW), ( + f"row {r_idx} col {c} orphaned SPACER_TAIL" + ) + c += 1 + + +def test_sans_io_layout_parsing_and_sync_committed_handle() -> None: + """``parse_tmux_window_layout`` and ``composite_tmux_window`` preserve `?2026`.""" + v1 = parse_tmux_window_layout( + "b25f,13x3,0,0{6x3,0,0,0,6x3,7,0,1}", + window_id="@9", + active_pane_id="%1", + ) + assert (v1.window_id, v1.width, v1.height) == ("@9", 13, 3) + assert [(p.pane_id, p.left, p.active) for p in v1.panes] == [ + ("%0", 0, False), + ("%1", 7, True), + ] + + v2 = parse_tmux_window_layout( + '{"V":2,"L":{"t":"h","w":13,"h":3,"x":0,"y":0,"c":[' + '{"t":"p","w":6,"h":3,"x":0,"y":0,"i":0,"I":"%0"},' + '{"t":"p","w":6,"h":3,"x":7,"y":0,"a":true,"i":1,"I":"%1"},' + '{"t":"p","w":5,"h":2,"x":2,"y":1,"i":2,"z":1,"I":"%2"},' + '{"t":"p","w":5,"h":2,"x":4,"y":1,"i":3,"z":0,"I":"%3"}]}}' + ) + assert [p.pane_id for p in v2.panes if p.floating] == ["%3", "%2"] + + # Handle exposing BOTH .terminal (under ?2026 hold) and .snapshot() (live torn + # frame) must resolve via .terminal.committed so in-flight frames never tear. + sync_term = Terminal(rows=3, cols=6) + sync_term.feed(b"STABLE") + sync_term.feed(b"\x1b[?2026h\rTORN!!") + + class _DualHandle: + def __init__(self, term: Terminal) -> None: + self.terminal = term + + def snapshot(self) -> Snapshot: + return self.terminal.snapshot() + + right_scr = Screen(rows=3, cols=6) + right_scr.put_text(0, 0, "R-SIDE") + snap = composite_tmux_window(v1, {"%0": _DualHandle(sync_term), "%1": right_scr}) + assert snap[0].text == "STABLE│R-SIDE" + + # Once ?2026 ends, committed advances to the new frame. + sync_term.feed(b"\x1b[?2026l") + snap_after = composite_tmux_window( + v1, {"%0": _DualHandle(sync_term), "%1": right_scr} + ) + assert snap_after[0].text == "TORN!!│R-SIDE" + + # Style edge cases: fill=default (no-op) vs fill=terminal (clear), escaped #, + # and invalid token transactional rollback. + fmt_layout = TmuxWindowLayout( + width=14, + height=3, + border_status="top", + panes=( + TmuxWindowPane( + "%0", + left=0, + top=1, + width=14, + height=2, + active=True, + active_border_style="fg=green,bg=blue", + border_format="#[fill=default]#[fg=yellow,bogus_tok]A#[fill=terminal]B", + ), + ), + ) + fmt_snap = composite_tmux_window(fmt_layout, {"%0": Screen(rows=2, cols=14)}) + # Invalid `bogus_tok` rolled back `fg=yellow`; `fill=terminal` cleared bg=blue + # across cols 2..12 while cols 0..1 kept active border `fg=green,bg=blue`. + assert fmt_snap[0][0].style == Style(fg=AnsiColor.GREEN, bg=AnsiColor.BLUE) + assert fmt_snap[0][2].style == Style(fg=AnsiColor.GREEN, bg=AnsiColor.BLUE) + assert fmt_snap[0][4].style == Style(bg=None) + + list_cmd = build_tmux_window_list_command("@1", nonce="BAD_TEST_1") + with pytest.raises(ValueError, match="missing tmux window list WIN header"): + list_cmd.parse(["wrong"]) + + cap_cmd = build_tmux_window_capture_command(v1, nonce="BAD_TEST_2") + with pytest.raises(ValueError, match="missing tmux window capture WIN_POST footer"): + cap_cmd.parse(["BAD_TEST_2:PANE_START:0"]) + + cap_res = decode_tmux_capture(["CAP"], metadata=TmuxPaneMetadata(cols=6, rows=3)) + snap_from_cap = composite_tmux_window(v1, {"%0": cap_res, "%1": right_scr}) + assert snap_from_cap[0].text == "CAP │R-SIDE" + + # Right-edge pending_wrap cursor visibility differs across tmux 3.7+: + # tmux <= 3.6 keeps cursor visible at cols - 1; tmux >= 3.7 hides it. + edge_right = Terminal(rows=3, cols=6) + edge_right.feed(b"123456") + assert edge_right.snapshot().cursor.pending_wrap is True + snap_34 = composite_tmux_window( + v1, {"%0": sync_term, "%1": edge_right}, tmux_version="3.4" + ) + snap_38 = composite_tmux_window( + v1, {"%0": sync_term, "%1": edge_right}, tmux_version="3.8a" + ) + assert (snap_34.cursor.col, snap_34.cursor.visible) == (12, True) + assert (snap_38.cursor.col, snap_38.cursor.visible) == (12, False) + + # V1 layouts omit active-pane flags; WIN_POST active pane ID must flag a + # focus switch between layout discovery and capture as layout_stable=False. + v1_active_0 = parse_tmux_window_layout( + "b25f,13x3,0,0{6x3,0,0,0,6x3,7,0,1}", + window_id="@0", + active_pane_id="%0", + ) + focus_cmd = build_tmux_window_capture_command( + v1_active_0, tmux_version="3.4", nonce="FOCUS_NONCE" + ) + assert focus_cmd.argv[-1].endswith("\t#{pane_id}") + focus_res = focus_cmd.parse( + [ + "FOCUS_NONCE:PANE_START:0", + "FOCUS_NONCE_P0:PRE:6\t3\t3\t0", + "FOCUS_NONCE_P0:CAPTURE", + "L", + "", + "", + "FOCUS_NONCE_P0:JOINED", + "L", + "FOCUS_NONCE_P0:POST:6\t3\t3\t0", + "FOCUS_NONCE:PANE_START:1", + "FOCUS_NONCE_P1:PRE:6\t3\t3\t0", + "FOCUS_NONCE_P1:CAPTURE", + "R", + "", + "", + "FOCUS_NONCE_P1:JOINED", + "R", + "FOCUS_NONCE_P1:POST:6\t3\t3\t0", + "FOCUS_NONCE:WIN_POST:@0\t13\t3\t0\tb25f,13x3,0,0{6x3,0,0,0,6x3,7,0,1}\t%1", + ] + ) + assert focus_res.layout_stable is False + assert focus_res.panes["%0"].terminal.profile.identity.xtversion == "tmux 3.4" + + # Versioned border rules: + # 1) tmux <= 3.5 sizes pane-border-status to wp->sx - 4 (vs wp->sx - 2 on 3.6+). + # 2) tmux 3.7..3.7c resolves numbered border digits in z-index order (0/1 vs 2). + bdr_panes = ( + TmuxWindowPane( + "%0", + index=0, + left=0, + top=1, + width=18, + height=8, + active=False, + border_style="fg=white", + active_border_style="fg=green", + border_format="#[align=right][x]", + ), + TmuxWindowPane( + "%1", + index=1, + left=19, + top=1, + width=17, + height=3, + active=False, + border_style="fg=white", + active_border_style="fg=green", + border_format="#[align=right][x]", + ), + TmuxWindowPane( + "%2", + index=2, + left=19, + top=5, + width=17, + height=4, + active=True, + border_style="fg=white", + active_border_style="fg=green", + border_format="#[align=right][x]", + ), + ) + st_layout = TmuxWindowLayout( + width=36, + height=9, + border_status="top", + border_lines="single", + panes=bdr_panes, + ) + snap_st_35 = composite_tmux_window(st_layout, {}, tmux_version="3.5") + snap_st_36 = composite_tmux_window(st_layout, {}, tmux_version="3.6") + assert snap_st_35[0].text[13:19] == "[x]──┬" + assert snap_st_36[0].text[13:19] == "──[x]┬" + assert snap_st_35[0].text[31:36] == "[x]──" + assert snap_st_36[0].text[31:36] == "──[x]" + + num_panes = tuple( + TmuxWindowPane( + p.pane_id, + index=p.index, + left=p.left, + top=p.top - 1 if p.top == 1 else p.top, + width=p.width, + height=p.height + 1 if p.top == 1 else p.height, + active=p.active, + border_style=p.border_style, + active_border_style=p.active_border_style, + ) + for p in bdr_panes + ) + num_layout = TmuxWindowLayout( + width=36, + height=9, + border_status="off", + border_lines="number", + panes=num_panes, + ) + for ver_37 in ("3.7", "3.7a", "3.7c"): + snap_num_37 = composite_tmux_window(num_layout, {}, tmux_version=ver_37) + assert [snap_num_37[r][18].text for r in range(9)] == ["0"] * 9 + assert [snap_num_37[4][c].text for c in range(19, 36)] == ["1"] * 17 + assert snap_num_37[6][18].style == Style(fg=AnsiColor.GREEN) + assert snap_num_37[4][20].style == Style(fg=AnsiColor.GREEN) + for ver_other in ("3.6", "3.8"): + snap_num_other = composite_tmux_window(num_layout, {}, tmux_version=ver_other) + assert snap_num_other[6][18].text == "2" + assert snap_num_other[4][20].text == "2" + + +def _tmux_version() -> str: + return subprocess.run( + ["tmux", "-V"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + +def _start_tmux_session( + sock: str, + *, + cols: int, + rows: int, + shell_cmd: str, +) -> None: + subprocess.run( + [ + "tmux", + "-L", + sock, + "-f", + "/dev/null", + "new-session", + "-d", + "-s", + "s", + "-x", + str(cols), + "-y", + str(rows), + "sh", + "-c", + shell_cmd, + ], + check=True, + ) + _run_tmux(sock, "set-option", "-g", "status", "off") + _run_tmux(sock, "set-option", "-g", "window-size", "manual") + + +def _kill_tmux(sock: str) -> None: + subprocess.run( + ["tmux", "-L", sock, "kill-server"], + check=False, + capture_output=True, + ) + + +def _run_tmux(sock: str, *args: str) -> str: + return subprocess.run( + ["tmux", "-L", sock, *args], + check=True, + capture_output=True, + text=True, + ).stdout + + +def _wait_pane_text(sock: str, pane_id: str, needle: str, timeout: float = 3.0) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + out = _run_tmux(sock, "capture-pane", "-J", "-p", "-t", pane_id) + if needle in out: + return + time.sleep(0.01) + pytest.fail(f"timed out waiting for {needle!r} in {pane_id}") + + +def _capture_window( + sock: str, + target: str = "@0", + *, + tmux_version: str = "3.8", +) -> TmuxWindowCaptureResult: + list_cmd = build_tmux_window_list_command(target) + layout = list_cmd.parse(_run_tmux(sock, *list_cmd.argv)) + cap_cmd = build_tmux_window_capture_command(layout, tmux_version=tmux_version) + return cap_cmd.parse(_run_tmux(sock, *cap_cmd.argv)) + + +async def _attach_and_capture_both( + sock: str, + *, + rows: int, + cols: int, + sentinel: str, + tmux_version: str, + tmux_client_flags: tuple[str, ...] = (), + term_env: str = "xterm-256color", +) -> tuple[TmuxWindowCaptureResult, Snapshot]: + """Attach live ``tmux`` client in ``open_pty`` and capture window while attached.""" + env = {**os.environ, "TERM": term_env} + async with open_pty( + ("tmux", *tmux_client_flags, "-L", sock, "attach-session", "-t", "s", "-r"), + rows=rows, + cols=cols, + env=env, + ) as sess: + await sess.wait_for(sentinel, timeout=3.0) + deadline = time.monotonic() + 1.5 + while time.monotonic() < deadline: + gen_before = sess.terminal.committed.generation + await asyncio.sleep(0.04) + if ( + sess.terminal.committed.generation == gen_before + and not sess.terminal._sync_hold_pending + ): + break + win_res = await asyncio.to_thread( + _capture_window, + sock, + tmux_version=tmux_version, + ) + return win_res, sess.terminal.committed + + +def _assert_window_matches_pty(win_snap: Snapshot, pty_snap: Snapshot) -> None: + """Assert cell grid, wraps, SGR ``styles:``, hyperlink URIs, and cursor match.""" + _assert_screen_cell_invariants(win_snap, allow_wrap=True) + assert (win_snap.rows, win_snap.cols) == (pty_snap.rows, pty_snap.cols) + assert [r.wrapped for r in win_snap] == [r.wrapped for r in pty_snap] + assert format_screen_box(win_snap) == format_screen_box(pty_snap) + + win_body = serialize_vt_snapshot(win_snap).splitlines()[1:] + pty_body = serialize_vt_snapshot(pty_snap).splitlines()[1:] + assert win_body == pty_body + + for r in range(win_snap.rows): + for c in range(win_snap.cols): + wc = win_snap[r][c] + pc = pty_snap[r][c] + assert wc.width_role == pc.width_role, f"width_role mismatch at ({r}, {c})" + assert (wc.text or " ") == (pc.text or " "), f"text mismatch at ({r}, {c})" + assert wc.style == pc.style, f"style mismatch at ({r}, {c})" + w_uri = None if wc.hyperlink is None else wc.hyperlink.uri + p_uri = None if pc.hyperlink is None else pc.hyperlink.uri + assert w_uri == p_uri, f"hyperlink URI mismatch at ({r}, {c})" + + assert ( + win_snap.cursor.row, + win_snap.cursor.col, + win_snap.cursor.visible, + ) == ( + pty_snap.cursor.row, + pty_snap.cursor.col, + pty_snap.cursor.visible, + ) + + +_SKIP_LIVE_TMUX = pytest.mark.skipif( + sys.platform == "win32" or shutil.which("tmux") is None, + reason="POSIX PTY and tmux binary required", +) + + +@pytest.mark.integration +@_SKIP_LIVE_TMUX +async def test_live_tmux_pty_parity_three_pane_across_client_depths() -> None: + """3-pane ``T``-junction matches unmodified ``tmux`` across 16/256/RGB clients.""" + sock = f"libvt-win-t3-{os.getpid()}-{zlib.crc32(b't-junction')}" + w_cols, w_rows = 34, 10 + try: + ver_out = _tmux_version() + _start_tmux_session(sock, cols=w_cols, rows=w_rows, shell_cmd="sleep 60") + _run_tmux( + sock, + "set-option", + "-as", + "terminal-features", + ",xterm*:hyperlinks", + ) + + _run_tmux( + sock, + "split-window", + "-h", + "-t", + "%0", + "sh", + "-c", + ( + "printf '\\033[4;48;2;20;40;60;38;2;240;220;100mRIGHT-TOP\\033[0m\\r\\n" + "漢字テスト P1_OK'; sleep 60" + ), + ) + _run_tmux( + sock, + "split-window", + "-v", + "-t", + "%1", + "sh", + "-c", + "printf '\\033[7;36mBOT-R\\033[0m end P2_OK'; sleep 60", + ) + _run_tmux( + sock, + "respawn-pane", + "-k", + "-t", + "%0", + "sh", + "-c", + ( + "printf '\\033[1;38;5;208mTOP-L\\033[0m 日本語\\r\\n" + "wrap_long_alpha_beta_gamma\\r\\n" + "界\\033]8;id=lnk1;https://libvt.git-pull.com\\033\\\\" + "DOCS\\033]8;;\\033\\\\ P0_OK'; sleep 60" + ), + ) + _wait_pane_text(sock, "%0", "P0_OK") + _wait_pane_text(sock, "%1", "P1_OK") + _wait_pane_text(sock, "%2", "P2_OK") + + # 1) Test default 16-color and `-2` 256-color clients on unmodified `theme`: + # `capture-pane -e` preserves 24-bit RGB losslessly while non-RGB TTY clients + # quantize 24-bit pane SGR, so exercise 16/256-color pane SGR here. + _run_tmux( + sock, + "respawn-pane", + "-k", + "-t", + "%1", + "sh", + "-c", + ( + "printf '\\033[4;48;5;235;38;5;221mRIGHT-TOP\\033[0m\\r\\n" + "漢字テスト P1_Q'; sleep 60" + ), + ) + _wait_pane_text(sock, "%1", "P1_Q") + for client_flags in ((), ("-2",)): + _run_tmux(sock, "select-pane", "-t", "%0") + win_res_q, pty_snap_q = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="P1_Q", + tmux_version=ver_out, + tmux_client_flags=client_flags, + ) + assert win_res_q.layout_stable is True + _assert_window_matches_pty(win_res_q.snapshot, pty_snap_q) + + # 2) Test 24-bit RGB client (`-T RGB,hyperlinks`) with 24-bit RGB pane SGR + + # unmodified 24-bit `theme detect` X11 border colors (`gray70` / `yellowgreen`). + _run_tmux( + sock, + "set-option", + "-as", + "terminal-features", + ",xterm*:RGB", + ) + _run_tmux( + sock, + "respawn-pane", + "-k", + "-t", + "%1", + "sh", + "-c", + ( + "printf '\\033[4;48;2;20;40;60;38;2;240;220;100mRIGHT-TOP\\033[0m\\r\\n" + "漢字テスト P1_R'; sleep 60" + ), + ) + _wait_pane_text(sock, "%1", "P1_R") + for active_pane in ("%2", "%0"): + _run_tmux(sock, "select-pane", "-t", active_pane) + win_res, pty_snap = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="P1_R", + tmux_version=ver_out, + tmux_client_flags=("-T", "RGB,hyperlinks"), + ) + assert win_res.layout_stable is True + _assert_window_matches_pty(win_res.snapshot, pty_snap) + + doc_row = win_res.snapshot[3] + doc_col = next(c for c, cell in enumerate(doc_row) if cell.text == "D") + assert doc_col == 2 + if parse_tmux_version(ver_out) >= (3, 4): + assert doc_row[doc_col].hyperlink == Hyperlink( + uri="https://libvt.git-pull.com", + id="lnk1", + ) + else: + assert doc_row[doc_col].hyperlink is None + assert any(r.wrapped for r in win_res.panes["%0"].snapshot) + assert not any(r.wrapped for r in win_res.snapshot) + + # 1-round-trip capture via parse_tmux_window_layout + include_layout=True. + raw_wlayout = _run_tmux( + sock, "display-message", "-p", "-t", "@0", "#{window_layout}" + ).strip() + seeded = parse_tmux_window_layout(raw_wlayout, window_id="@0") + one_rt_cmd = build_tmux_window_capture_command( + seeded, + tmux_version=ver_out, + include_layout=True, + ) + one_rt_res = one_rt_cmd.parse(_run_tmux(sock, *one_rt_cmd.argv)) + assert one_rt_res.layout_stable is True + assert format_screen_box(one_rt_res.snapshot) == format_screen_box( + win_res.snapshot + ) + finally: + _kill_tmux(sock) + + +@pytest.mark.integration +@_SKIP_LIVE_TMUX +async def test_live_tmux_pty_parity_two_pane_splits_and_full_width_wrap() -> None: + """2-pane half-colors, ``pending_wrap`` cursor, and full-width ``│W`` wrap.""" + sock = f"libvt-win-2p-{os.getpid()}-{zlib.crc32(b'two-pane')}" + w_cols, w_rows = 25, 8 + try: + ver_out = _tmux_version() + _start_tmux_session( + sock, + cols=w_cols, + rows=w_rows, + shell_cmd="printf 'ABCDEFGHIJKL'; sleep 60", + ) + _run_tmux( + sock, + "split-window", + "-h", + "-t", + "%0", + "sh", + "-c", + "printf '123456789012'; sleep 60", + ) + _run_tmux(sock, "select-layout", "even-horizontal") + _wait_pane_text(sock, "%0", "ABCDEFGHIJKL") + _wait_pane_text(sock, "%1", "123456789012") + + # %0 active: pending_wrap places cursor visibly on interior divider (col 12). + _run_tmux(sock, "select-pane", "-t", "%0") + win_left, pty_left = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="123456789012", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + _assert_window_matches_pty(win_left.snapshot, pty_left) + assert (win_left.snapshot.cursor.col, win_left.snapshot.cursor.visible) == ( + 12, + True, + ) + + # Switching active pane between list_cmd and cap_cmd marks layout_stable=False + # even on tmux < 3.8 where V1 window_layout omits active-pane flags. + _run_tmux(sock, "select-pane", "-t", "%0") + saved_list = build_tmux_window_list_command("@0") + saved_layout = saved_list.parse(_run_tmux(sock, *saved_list.argv)) + _run_tmux(sock, "select-pane", "-t", "%1") + stale_cap = build_tmux_window_capture_command( + saved_layout, tmux_version=ver_out + ) + stale_res = stale_cap.parse(_run_tmux(sock, *stale_cap.argv)) + assert stale_res.layout_stable is False + + # %1 active: pending_wrap at right window edge hides cursor on tmux >= 3.7 + # and keeps cursor visible at cols - 1 on tmux <= 3.6. + _run_tmux(sock, "select-pane", "-t", "%1") + win_right, pty_right = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="123456789012", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + _assert_window_matches_pty(win_right.snapshot, pty_right) + assert win_right.snapshot.cursor.visible is ( + parse_tmux_version(ver_out) < (3, 7) + ) + + # Switch to even-vertical and write a >25-col soft-wrapping line into %0 to + # verify full-width `│W` soft-wrap preservation across attached PTY! + _run_tmux(sock, "select-layout", "even-vertical") + _run_tmux( + sock, + "respawn-pane", + "-k", + "-t", + "%0", + "sh", + "-c", + "printf 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_WRAP_END'; sleep 60", + ) + _wait_pane_text(sock, "%0", "WRAP_END") + for active_pane in ("%0", "%1"): + _run_tmux(sock, "select-pane", "-t", active_pane) + win_v, pty_v = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="WRAP_END", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + _assert_window_matches_pty(win_v.snapshot, pty_v) + assert win_v.snapshot[0].wrapped is True + assert pty_v[0].wrapped is True + finally: + _kill_tmux(sock) + + +@pytest.mark.integration +@_SKIP_LIVE_TMUX +async def test_live_tmux_pty_parity_zoomed_off_and_border_status_top() -> None: + """Zoomed pane matches live ``tmux`` both with status ``off`` and ``top``.""" + sock = f"libvt-win-zoom-{os.getpid()}-{zlib.crc32(b'zoomed')}" + w_cols, w_rows = 26, 7 + try: + ver_out = _tmux_version() + _start_tmux_session( + sock, + cols=w_cols, + rows=w_rows, + shell_cmd="printf 'UNZOOM_P0'; sleep 60", + ) + _wait_pane_text(sock, "%0", "UNZOOM_P0") + _run_tmux( + sock, + "split-window", + "-h", + "-t", + "%0", + "sh", + "-c", + ( + "printf '\\033]2;zoom-title\\033\\\\" + "\\033[1;35mZOOM_ACTIVE_P1_LONG_WRAPPING_TEXT\\033[0m 日本'; sleep 60" + ), + ) + _wait_pane_text(sock, "%1", "ZOOM_ACTIVE_P1") + _run_tmux(sock, "resize-pane", "-Z", "-t", "%1") + + # 1) Zoomed with pane-border-status off. + win_zoom, pty_zoom = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="ZOOM_ACTIVE_P1", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + assert win_zoom.zoomed is True + _assert_window_matches_pty(win_zoom.snapshot, pty_zoom) + assert "UNZOOM_P0" not in "\n".join(win_zoom.snapshot.lines) + + # 2) Zoomed with pane-border-status top (row 0 draws zoomed status bar!). + _run_tmux(sock, "set-window-option", "pane-border-status", "top") + win_zoom_st, pty_zoom_st = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="ZOOM_ACTIVE_P1", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + assert win_zoom_st.zoomed is True + _assert_window_matches_pty(win_zoom_st.snapshot, pty_zoom_st) + assert "zoom-title" in win_zoom_st.snapshot[0].text + finally: + _kill_tmux(sock) + + +@pytest.mark.integration +@_SKIP_LIVE_TMUX +async def test_live_tmux_pty_parity_border_lines_and_border_status_top() -> None: + """``pane-border-lines`` and ``pane-border-status top`` match live ``tmux``.""" + sock = f"libvt-win-bdr-{os.getpid()}-{zlib.crc32(b'borders')}" + w_cols, w_rows = 36, 9 + try: + ver_out = _tmux_version() + _start_tmux_session( + sock, + cols=w_cols, + rows=w_rows, + shell_cmd="printf '\\033]2;alpha\\033\\\\BDR_P0'; sleep 60", + ) + _run_tmux( + sock, + "split-window", + "-h", + "-t", + "%0", + "sh", + "-c", + "printf '\\033]2;beta\\033\\\\BDR_P1'; sleep 60", + ) + _run_tmux( + sock, + "split-window", + "-v", + "-t", + "%1", + "sh", + "-c", + "printf '\\033]2;gamma\\033\\\\BDR_P2'; sleep 60", + ) + _wait_pane_text(sock, "%0", "BDR_P0") + _wait_pane_text(sock, "%1", "BDR_P1") + _wait_pane_text(sock, "%2", "BDR_P2") + + for line_mode in ("heavy", "double", "simple", "number"): + _run_tmux(sock, "set-window-option", "pane-border-lines", line_mode) + win_res, pty_snap = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="BDR_P2", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + _assert_window_matches_pty(win_res.snapshot, pty_snap) + + _run_tmux(sock, "set-window-option", "pane-border-lines", "single") + _run_tmux(sock, "set-window-option", "pane-border-status", "top") + win_default_fmt, pty_default_fmt = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="BDR_P2", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + _assert_window_matches_pty(win_default_fmt.snapshot, pty_default_fmt) + + _run_tmux( + sock, + "set-window-option", + "pane-border-format", + ( + "#{?pane_active,#[reverse],}#[fg=yellow,bold]#P:#T#[default]" + "#[align=right]#[range=user|close][x]#[norange]" + ), + ) + win_custom_fmt, pty_custom_fmt = await _attach_and_capture_both( + sock, + rows=w_rows, + cols=w_cols, + sentinel="BDR_P2", + tmux_version=ver_out, + tmux_client_flags=("-2",), + ) + _assert_window_matches_pty(win_custom_fmt.snapshot, pty_custom_fmt) + finally: + _kill_tmux(sock)