Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions docs/topics/protocols-and-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 <libvt.screen.Cell.hyperlink>`.
to {attr}`Cell.hyperlink <libvt.screen.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

Expand Down
3 changes: 3 additions & 0 deletions src/libvt/codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")

Expand Down
52 changes: 52 additions & 0 deletions src/libvt/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__

Examples
--------
>>> from libvt.config import QueryBehavior
>>> QueryBehavior().sixel_color_registers
256
"""

decrqss_enabled: bool = True
Expand All @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions src/libvt/contrib/tmux/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
9 changes: 8 additions & 1 deletion src/libvt/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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,
),
Expand All @@ -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="",
Expand Down Expand Up @@ -104,6 +110,7 @@
decrqss_enabled=False,
xtgettcap_enabled=False,
kitty_keyboard_query_enabled=False,
xtsmgraphics_enabled=False,
),
screen=ScreenBehavior(
reflow_on_resize=False,
Expand Down
135 changes: 133 additions & 2 deletions src/libvt/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html>`__
- `tmux/tmux input.c — input_csi_dispatch_sm_graphics (3.8)
<https://github.com/tmux/tmux/blob/3.8/input.c#L2103-L2120>`__

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``).

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading