diff --git a/CHANGES b/CHANGES index ad4b7de..e08ec50 100644 --- a/CHANGES +++ b/CHANGES @@ -140,6 +140,22 @@ prof = Profile( ### What's new +#### Stateful `XTSMGRAPHICS` color and geometry registers (#28) + +{class}`~libvt.terminal.Terminal` implements stateful `XTSMGRAPHICS` +(`CSI ? Pi ; Pa ; Pv S`) `SIXEL` color-register (`Pi = 1`) and pixel-geometry +(`Pi = 2`) read, reset, set, and maximum queries (`Pa = 1..4`) gated on +{attr}`~libvt.config.Policy.track_graphics` and +{class}`~libvt.config.QueryBehavior` +({attr}`~libvt.config.QueryBehavior.xtsmgraphics_enabled`, +{attr}`~libvt.config.QueryBehavior.xtsmgraphics_geometry_enabled`, +{attr}`~libvt.config.QueryBehavior.xtsmgraphics_set_enabled`, +{attr}`~libvt.config.QueryBehavior.sixel_color_registers`, and +{attr}`~libvt.config.QueryBehavior.max_sixel_color_registers`), with host +presets in {mod}`libvt.profiles` and +{func}`~libvt.contrib.tmux.profile.tmux_profile` configured to match upstream +terminal behavior. + #### Kitty alternate keys and associated text (#30) {class}`~libvt.input.KeyEvent` adds optional single-character diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md index 965945e..7b3f296 100644 --- a/docs/topics/protocols-and-input.md +++ b/docs/topics/protocols-and-input.md @@ -66,9 +66,9 @@ scrolls, deduplicating paired `133` and `633` markers emitted at the same cell. ## Terminal queries and events Queries (`DA1`/`DA2`, `DSR` `CSI 6 n`, `DECRQM`, `DECRQSS`, `XTVERSION`, -`XTGETTCAP`, `OSC 4` / `10`–`12` color queries, and `?2031` / `CSI ? 996 n` -color-scheme queries) write response bytes to -{meth}`~libvt.terminal.Terminal.drain_replies` according to active +`XTGETTCAP`, `XTSMGRAPHICS` `CSI ? Pi ; Pa ; Pv S`, `OSC 4` / `10`–`12` color +queries, and `?2031` / `CSI ? 996 n` color-scheme queries) write response bytes +to {meth}`~libvt.terminal.Terminal.drain_replies` according to active {class}`~libvt.config.Profile` and {class}`~libvt.config.Policy` settings (or stay silent when {attr}`~libvt.config.Policy.emit_replies` is `False` on passive observer streams). Notifications (`OSC 0`/`1`/`2` and `ESC k` title, @@ -80,7 +80,14 @@ observer streams). Notifications (`OSC 0`/`1`/`2` and `ESC k` title, `?2026`, and `DCS tmux;` passthrough) emit typed {class}`~libvt.events.Event` records to `on_event` or {meth}`~libvt.terminal.Terminal.drain_events`, while `OSC 8` hyperlinks attach -to {attr}`Cell.hyperlink `. +to {attr}`Cell.hyperlink `: + +```python +>>> term = libvt.Terminal(rows=4, cols=20) +>>> term.feed(b"\x1b[?1;1;0S") +>>> term.drain_replies() +b'\x1b[?1;0;256S' +``` ## Keyboard, mouse, and focus encoding diff --git a/src/libvt/codec.py b/src/libvt/codec.py index 3792d43..83ae4da 100644 --- a/src/libvt/codec.py +++ b/src/libvt/codec.py @@ -168,6 +168,9 @@ def _explain_csi(act: CsiDispatch) -> ExplainedSpan: mnem = "XTSAVE" if fin == "s" else "XTRESTORE" return ExplainedSpan("CSI", mnem, f"?{vals}{fin}") + if pfx == "?" and not inter and fin == "S": + return ExplainedSpan("CSI", "XTSMGRAPHICS", f"?{vals}S") + mnem = _CSI_NAMES.get(fin, f"CSI {fin}") return ExplainedSpan("CSI", mnem, f"{pfx}{vals}{inter}{fin}") diff --git a/src/libvt/config.py b/src/libvt/config.py index 31afa66..5768a18 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -101,6 +101,36 @@ class QueryBehavior: Default background 8-bit RGB reported for ``OSC 11 ; ?``. cursor_rgb : tuple[int, int, int] Default cursor 8-bit RGB reported for ``OSC 12 ; ?``. + xtsmgraphics_enabled : bool + Answer ``XTSMGRAPHICS`` (``CSI ? Pi ; Pa ; Pv S``) queries; when + ``False``, ignore ``XTSMGRAPHICS`` silently (default ``True``). + xtsmgraphics_geometry_enabled : bool + Allow ``XTSMGRAPHICS`` ``Pi = 2`` ``SIXEL`` pixel-geometry queries + (default ``True``; ``False`` in ``tmux``). + xtsmgraphics_set_enabled : bool + Allow ``XTSMGRAPHICS`` ``Pa = 3`` register and geometry writes + (default ``True``; ``False`` in ``tmux``). + sixel_color_registers : int + Default ``SIXEL`` color-register count for ``Pi = 1`` (default ``256``). + max_sixel_color_registers : int + Maximum ``SIXEL`` color-register count for ``Pi = 1, Pa = 4`` (default + ``1024``). + + Raises + ------ + ValueError + If ``sixel_color_registers < 2`` or exceeds ``max_sixel_color_registers``. + + References + ---------- + - `xterm Control Sequences — XTSMGRAPHICS (CSI ? Pi ; Pa ; Pv S) + `__ + + Examples + -------- + >>> from libvt.config import QueryBehavior + >>> QueryBehavior().sixel_color_registers + 256 """ decrqss_enabled: bool = True @@ -110,6 +140,28 @@ class QueryBehavior: fg_rgb: tuple[int, int, int] = (0xE5, 0xE5, 0xE5) bg_rgb: tuple[int, int, int] = (0x1E, 0x1E, 0x1E) cursor_rgb: tuple[int, int, int] = (0xE5, 0xE5, 0xE5) + xtsmgraphics_enabled: bool = True + xtsmgraphics_geometry_enabled: bool = True + xtsmgraphics_set_enabled: bool = True + sixel_color_registers: int = 256 + max_sixel_color_registers: int = 1_024 + + def __post_init__(self) -> None: + """Validate ``SIXEL`` color-register bounds.""" + if ( + isinstance(self.sixel_color_registers, bool) + or not isinstance(self.sixel_color_registers, int) + or isinstance(self.max_sixel_color_registers, bool) + or not isinstance(self.max_sixel_color_registers, int) + or self.sixel_color_registers < 2 + or self.max_sixel_color_registers < self.sixel_color_registers + ): + msg = ( + "expected 2 <= sixel_color_registers <= max_sixel_color_registers, " + f"got ({self.sixel_color_registers!r}, " + f"{self.max_sixel_color_registers!r})" + ) + raise ValueError(msg) @dataclass(frozen=True, slots=True, kw_only=True) diff --git a/src/libvt/contrib/tmux/profile.py b/src/libvt/contrib/tmux/profile.py index 9ead813..9ce5149 100644 --- a/src/libvt/contrib/tmux/profile.py +++ b/src/libvt/contrib/tmux/profile.py @@ -144,6 +144,11 @@ def tmux_profile( decrqss_enabled=at_least_3_6, xtgettcap_enabled=False, kitty_keyboard_query_enabled=False, + xtsmgraphics_enabled=sixel, + xtsmgraphics_geometry_enabled=False, + xtsmgraphics_set_enabled=False, + sixel_color_registers=1_024, + max_sixel_color_registers=1_024, ), screen=ScreenBehavior( pending_wrap_phantom_col=True, diff --git a/src/libvt/profiles.py b/src/libvt/profiles.py index 2541672..50382e9 100644 --- a/src/libvt/profiles.py +++ b/src/libvt/profiles.py @@ -51,6 +51,9 @@ da2=b"\x1b[>1;10;0c", xtversion="ghostty 1.4.0", ), + queries=QueryBehavior( + xtsmgraphics_enabled=False, + ), ) #: ``Kitty`` host terminal profile (CSI u keyboard stack, XTGETTCAP, reflow). @@ -62,6 +65,9 @@ xtversion="kitty(0.40.0)", osc_7501_capabilities="", ), + queries=QueryBehavior( + xtsmgraphics_enabled=False, + ), screen=ScreenBehavior( ed3_clears_scrollback_on_alt=True, ), @@ -74,7 +80,7 @@ XTERM_PROFILE: Profile = Profile( identity=Identity( name="xterm", - da1=b"\x1b[?64;1;2;6;9;15;16;17;18;21;22;28c", + da1=b"\x1b[?64;1;2;4;6;9;15;16;17;18;21;22;28c", da2=b"\x1b[>41;388;0c", xtversion="XTerm(388)", osc_7501_capabilities="", @@ -104,6 +110,7 @@ decrqss_enabled=False, xtgettcap_enabled=False, kitty_keyboard_query_enabled=False, + xtsmgraphics_enabled=False, ), screen=ScreenBehavior( reflow_on_resize=False, diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 72c2a85..6e787bf 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -1807,6 +1807,11 @@ def __init__( self._host_bg_rgb: tuple[int, int, int] = profile.queries.bg_rgb self._host_cursor_rgb: tuple[int, int, int] = profile.queries.cursor_rgb self._host_palette: dict[int, tuple[int, int, int]] = {} + self._sixel_color_registers: int = min( + profile.queries.sixel_color_registers, + profile.queries.max_sixel_color_registers, + ) + self._sixel_geometry_px: tuple[int, int] | None = None self._guest_fg_rgb: tuple[int, int, int] | None = None self._guest_bg_rgb: tuple[int, int, int] | None = None self._guest_cursor_rgb: tuple[int, int, int] | None = None @@ -2949,6 +2954,11 @@ def reset(self, *, soft: bool = False) -> None: self._guest_cursor_rgb = None self._guest_palette.clear() self._saved_private_modes.clear() + self._sixel_color_registers = min( + self._profile.queries.sixel_color_registers, + self._profile.queries.max_sixel_color_registers, + ) + self._sixel_geometry_px = None self._bump_appearance() self._title_stack.clear() self._icon_title_stack.clear() @@ -4099,6 +4109,128 @@ def _is_private_mode_supported(self, mode: Mode) -> bool: ) ) + def _handle_xtsmgraphics(self, params: CsiParams) -> None: + r"""Handle ``XTSMGRAPHICS`` (``CSI ? Pi ; Pa ; Pv S``) register queries. + + Supports color-register count (``Pi = 1``) and ``SIXEL`` pixel geometry + (``Pi = 2``) across read (``Pa = 1``), reset (``Pa = 2``), set + (``Pa = 3``), and read-maximum (``Pa = 4``), clamped by + :attr:`~libvt.config.Limits.max_image_dimension` and + :attr:`~libvt.config.QueryBehavior.max_sixel_color_registers`. Replies + ``CSI ? Pi ; 3 S`` when disabled or unsupported so ``SIXEL`` clients + never stall. + + References + ---------- + - `xterm Control Sequences — XTSMGRAPHICS (CSI ? Pi ; Pa ; Pv S) + `__ + - `tmux/tmux input.c — input_csi_dispatch_sm_graphics (3.8) + `__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(rows=10, cols=20) + >>> term.feed(b"\x1b[?1;1;0S\x1b[?2;1;0S") + >>> term.drain_replies() + b'\x1b[?1;0;256S\x1b[?2;0;160;160S' + """ + q_cfg = self._profile.queries + if not q_cfg.xtsmgraphics_enabled: + return + pi = params.raw_or_default(0, 0) + pa = params.raw_or_default(1, 0) + if not self._policy.track_graphics or params.colon_mask != 0: + self._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) + return + if pi not in (1, 2, 3): + self._emit_reply(f"\x1b[?{pi};1S".encode("ascii")) + return + if pa not in (1, 2, 3, 4): + self._emit_reply(f"\x1b[?{pi};2S".encode("ascii")) + return + + if pi == 1: + max_regs = q_cfg.max_sixel_color_registers + def_regs = min(q_cfg.sixel_color_registers, max_regs) + if pa == 1: + self._emit_reply( + f"\x1b[?1;0;{self._sixel_color_registers}S".encode("ascii"), + ) + elif pa == 2: + if self._sixel_color_registers != def_regs: + self._before_mutate() + self._sixel_color_registers = def_regs + self._emit_reply(f"\x1b[?1;0;{def_regs}S".encode("ascii")) + elif ( + pa == 3 + and q_cfg.xtsmgraphics_set_enabled + and len(params.values) == 3 + and ((params.omitted_mask >> 2) & 1) == 0 + and params.values[2] >= 2 + ): + clamped_regs = min(params.values[2], max_regs) + if self._sixel_color_registers != clamped_regs: + self._before_mutate() + self._sixel_color_registers = clamped_regs + self._emit_reply(f"\x1b[?1;0;{clamped_regs}S".encode("ascii")) + elif pa == 4: + self._emit_reply(f"\x1b[?1;0;{max_regs}S".encode("ascii")) + else: + self._emit_reply(b"\x1b[?1;3S") + return + + if pi == 2 and q_cfg.xtsmgraphics_geometry_enabled: + cw = self._profile.screen.cell_width_px + ch = self._profile.screen.cell_height_px + max_dim = self._limits.max_image_dimension + if cw <= 0 or ch <= 0 or max_dim <= 0: + self._emit_reply(b"\x1b[?2;3S") + return + def_w = min(max_dim, self.cols * cw) + def_h = min(max_dim, self.rows * ch) + if pa == 1: + cur_w, cur_h = ( + self._sixel_geometry_px + if self._sixel_geometry_px is not None + else (def_w, def_h) + ) + self._emit_reply( + f"\x1b[?2;0;{min(max_dim, cur_w)};{min(max_dim, cur_h)}S".encode( + "ascii", + ), + ) + elif pa == 2: + if self._sixel_geometry_px is not None: + self._before_mutate() + self._sixel_geometry_px = None + self._emit_reply(f"\x1b[?2;0;{def_w};{def_h}S".encode("ascii")) + elif ( + pa == 3 + and q_cfg.xtsmgraphics_set_enabled + and len(params.values) == 4 + and (params.omitted_mask & 0b1100) == 0 + and params.values[2] >= 1 + and params.values[3] >= 1 + ): + clamped_geo = ( + min(params.values[2], max_dim), + min(params.values[3], max_dim), + ) + if self._sixel_geometry_px != clamped_geo: + self._before_mutate() + self._sixel_geometry_px = clamped_geo + self._emit_reply( + f"\x1b[?2;0;{clamped_geo[0]};{clamped_geo[1]}S".encode("ascii"), + ) + elif pa == 4: + self._emit_reply(f"\x1b[?2;0;{max_dim};{max_dim}S".encode("ascii")) + else: + self._emit_reply(b"\x1b[?2;3S") + return + + self._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) + def _xtsave_modes(self, params: CsiParams) -> None: r"""Save DEC private mode flags for ``XTSAVE`` (``CSI ? Pm s``). @@ -4742,8 +4874,7 @@ def _handle_csi( f"\x1b[>4;{scr._modify_other_keys}m".encode("ascii"), ) elif final == ord("S") and 1 <= len(params.values) <= 4: # XTSMGRAPHICS - pi = params.raw_or_default(0, 0) - self._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) + self._handle_xtsmgraphics(params) elif final == ord("s"): # XTSAVE: CSI ? Pm s self._xtsave_modes(params) elif final == ord("r"): # XTRESTORE: CSI ? Pm r diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 2e1c6c5..959c91c 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -814,21 +814,62 @@ def test_osc_palette_dynamic_colors_decrqm_xtsmgraphics_and_notifications() -> N b"\x1b]12;rgb:abab/cdcd/efef\x07\x1b]12;rgb:e5e5/e5e5/e5e5\x07" ) - # DECRQM unknown modes return 0; XTSMGRAPHICS replies ?Pi;3S before DA1 sentinel. + # DECRQM unknown modes return 0; stateful XTSMGRAPHICS replies ?Pi;0;...S. term.feed( b"\x1b[4$p\x1b[99$p\x1b[?2026$p\x1b[?9999$p" b"\x1b[>1$p\x1b[?1;2$p" - b"\x1b[?1;1;0S\x1b[?2;3;800;600S\x1b[c" + b"\x1b[?1;1;0S\x1b[?2;3;800;600S\x1b[?2;1;0S\x1b[?3;1;0S\x1b[c" ) assert term.drain_replies() == ( b"\x1b[4;2$y" b"\x1b[99;0$y" b"\x1b[?2026;2$y" b"\x1b[?9999;0$y" - b"\x1b[?1;3S" - b"\x1b[?2;3S" + DEFAULT_PROFILE.identity.da1 + b"\x1b[?1;0;256S" + b"\x1b[?2;0;800;600S" + b"\x1b[?2;0;800;600S" + b"\x1b[?3;3S" + DEFAULT_PROFILE.identity.da1 ) + # XTSMGRAPHICS set/max/reset clamping, Ps=1/2/3 codes, RIS/DECSTR, & Policy/Profile: + xtsm_t = libvt.Terminal( + rows=10, + cols=20, + limits=libvt.Limits(max_image_dimension=500), + ) + xtsm_t.feed( + b"\x1b[?1;3;2048S\x1b[?1;1S\x1b[?1;4;0S\x1b[?1;2;0S" + b"\x1b[?2;3;900;700S\x1b[?2;4;0S\x1b[?2;2;0S" + b"\x1b[?99;1;0S\x1b[?1;9;0S" + ) + assert xtsm_t.drain_replies() == ( + b"\x1b[?1;0;1024S\x1b[?1;0;1024S\x1b[?1;0;1024S\x1b[?1;0;256S" + b"\x1b[?2;0;500;500S\x1b[?2;0;500;500S\x1b[?2;0;160;160S" + b"\x1b[?99;1S\x1b[?1;2S" + ) + # DECSTR preserves XTSMGRAPHICS registers; RIS resets them: + xtsm_t.feed(b"\x1b[?1;3;512S\x1b[?2;3;300;200S\x1b[!p\x1b[?1;1S\x1b[?2;1S") + assert xtsm_t.drain_replies() == ( + b"\x1b[?1;0;512S\x1b[?2;0;300;200S\x1b[?1;0;512S\x1b[?2;0;300;200S" + ) + xtsm_t.feed(b"\x1bc\x1b[?1;1S\x1b[?2;1S") + assert xtsm_t.drain_replies() == b"\x1b[?1;0;256S\x1b[?2;0;160;160S" + + gh_xtsm = libvt.Terminal(rows=4, cols=10, profile=GHOSTTY_PROFILE) + gh_xtsm.feed(b"\x1b[?1;1;0S\x1b[?2;1;0S") + assert gh_xtsm.drain_replies() == b"" + tm_nosx = libvt.Terminal(rows=4, cols=10, profile=tmux_profile("3.8", sixel=False)) + tm_nosx.feed(b"\x1b[?1;1;0S") + assert tm_nosx.drain_replies() == b"" + tm_sx = libvt.Terminal(rows=4, cols=10, profile=tmux_profile("3.8", sixel=True)) + tm_sx.feed(b"\x1b[?1;1;0S\x1b[?1;4;0S\x1b[?1;3;512S\x1b[?2;1;0S") + assert ( + tm_sx.drain_replies() == b"\x1b[?1;0;1024S\x1b[?1;0;1024S\x1b[?1;3S\x1b[?2;3S" + ) + no_gfx = libvt.Terminal(rows=4, cols=10, policy=Policy(track_graphics=False)) + no_gfx.feed(b"\x1b[?1;3;512S\x1b[?1;1;0S\x1b[?2;1;0S") + assert no_gfx.drain_replies() == b"\x1b[?1;3S\x1b[?1;3S\x1b[?2;3S" + # Policy(allow_color_queries=False) suppresses OSC 4 and OSC 10-12 replies. no_color = libvt.Terminal(rows=2, cols=8, policy=Policy(allow_color_queries=False)) no_color.feed(b"\x1b]4;1;?\x07\x1b]10;?;?;?\x07")