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
11 changes: 11 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,17 @@ prof = Profile(

### What's new

#### Kitty alternate keys and associated text (#30)

{class}`~libvt.input.KeyEvent` adds optional single-character
{attr}`~libvt.input.KeyEvent.shifted_key` and
{attr}`~libvt.input.KeyEvent.base_key` fields (with US-ASCII shifted keys
populated by {meth}`~libvt.input.KeyEvent.parse`), and
{func}`~libvt.input.encode_input` formats Kitty keyboard protocol flags
{attr}`~libvt.input.KittyKeyboardFlags.REPORT_ALTERNATE_KEYS` (`4`) and
{attr}`~libvt.input.KittyKeyboardFlags.REPORT_ASSOCIATED_TEXT` (`16`) into
`CSI key[:shifted[:base]] ; [mods[:event]] ; [text-codepoints] u` sequences.

#### `PyPy 3.12` CI certification and `TerminalTimeoutError` reduction fix (#32)

{exc}`~libvt.exc.TerminalTimeoutError` preserves `errno`, `strerror`, and
Expand Down
9 changes: 8 additions & 1 deletion docs/topics/protocols-and-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ consult `DECCKM`, mouse modes (`?9`, `?1000`, `?1002`, `?1003`, `?1006`,
`?1007` {attr}`~libvt.modes.Mode.ALTERNATE_SCROLL`, and `?1016` pixel SGR),
focus reporting (`?1004`), bracketed paste (`?2004`), `XTMODKEYS`
(`CSI > 4 ; pv m` via {attr}`~libvt.terminal.Terminal.modify_other_keys`), and
the active screen's {class}`~libvt.input.KittyKeyboardStack`:
the active screen's {class}`~libvt.input.KittyKeyboardStack` (including
{attr}`~libvt.input.KittyKeyboardFlags.REPORT_ALTERNATE_KEYS` shifted/base-layout
subparameters and
{attr}`~libvt.input.KittyKeyboardFlags.REPORT_ASSOCIATED_TEXT` UTF-32 text
codepoints):

```python
>>> from libvt.input import KeyEvent
Expand All @@ -100,6 +104,9 @@ b'\x1bOA'
>>> term.feed(b"\x1b[>4;2m")
>>> term.encode(KeyEvent.parse("ctrl+;"))
b'\x1b[27;5;59~'
>>> term.feed(b"\x1b[>5u")
>>> term.encode(KeyEvent.parse("ctrl+shift+1"))
b'\x1b[49:33;6u'
```

## Paste encoding
Expand Down
264 changes: 244 additions & 20 deletions src/libvt/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,32 @@ def reset(self) -> None:
}


_US_ASCII_SHIFT: dict[str, str] = {
"`": "~",
"1": "!",
"2": "@",
"3": "#",
"4": "$",
"5": "%",
"6": "^",
"7": "&",
"8": "*",
"9": "(",
"0": ")",
"-": "_",
"=": "+",
"[": "{",
"]": "}",
"\\": "|",
";": ":",
"'": '"',
",": "<",
".": ">",
"/": "?",
**{chr(c): chr(c - 32) for c in range(ord("a"), ord("z") + 1)},
}


@dataclass(frozen=True, slots=True)
class KeyEvent:
"""Structured keyboard event for outbound PTY encoding.
Expand All @@ -121,16 +147,86 @@ class KeyEvent:
Key action (``PRESS``, ``REPEAT``, or ``RELEASE``).
text : str
Optional associated text for Kitty flag ``REPORT_ASSOCIATED_TEXT``.
shifted_key : str
Optional single-character shifted alternate key for Kitty flag
``REPORT_ALTERNATE_KEYS`` (``4``).
base_key : str
Optional single-character PC-101 base-layout key for Kitty flag
``REPORT_ALTERNATE_KEYS`` (``4``).

Raises
------
ValueError
If ``shifted_key`` or ``base_key`` exceeds one character.

References
----------
- `Kitty Keyboard Protocol — Alternate Keys
<https://sw.kovidgoyal.net/kitty/keyboard-protocol/#alternate-keys>`__
- `ghostty-org/ghostty src/input/key_encode.zig (v1.4.0)
<https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/input/key_encode.zig#L1036-L1093>`__

Examples
--------
>>> from libvt.input import KeyEvent
>>> KeyEvent("a", shifted_key="A").shifted_key
'A'
"""

key: str
modifiers: KeyMod = KeyMod.NONE
action: KeyAction = KeyAction.PRESS
text: str = ""
shifted_key: str = ""
base_key: str = ""

def __post_init__(self) -> None:
"""Validate optional alternate-key fields."""
if len(self.shifted_key) > 1:
msg = (
"shifted_key must be '' or a single character, "
f"got {self.shifted_key!r}"
)
raise ValueError(msg)
if len(self.base_key) > 1:
msg = f"base_key must be '' or a single character, got {self.base_key!r}"
raise ValueError(msg)

@classmethod
def parse(cls, chord: str, *, action: KeyAction = KeyAction.PRESS) -> KeyEvent:
"""Parse a human-readable chord such as ``"ctrl+shift+p"`` or ``"up"``."""
"""Parse a human-readable chord such as ``"ctrl+shift+p"`` or ``"up"``.

Parameters
----------
chord : str
``+``-separated modifier and key specification (e.g. ``"ctrl+c"``,
``"ctrl+shift+1"``, ``"up"``).
action : KeyAction, default KeyAction.PRESS
Key press, repeat, or release action.

Returns
-------
KeyEvent
Parsed key event with US-ASCII ``shifted_key`` populated when
``shift`` is present on a single-character key.

Raises
------
ValueError
If *chord* contains an unrecognized modifier token.

References
----------
- `Kitty Keyboard Protocol — Progressive Enhancement
<https://sw.kovidgoyal.net/kitty/keyboard-protocol/#progressive-enhancement>`__

Examples
--------
>>> from libvt.input import KeyEvent
>>> ev = KeyEvent.parse("ctrl+shift+1")
>>> (ev.key, ev.shifted_key)
('1', '!')
"""
if chord == "+":
return cls(key="+", action=action)
parts = chord.split("+")
Expand All @@ -143,7 +239,12 @@ def parse(cls, chord: str, *, action: KeyAction = KeyAction.PRESS) -> KeyEvent:
mods |= m
raw_key = parts[-1]
key = raw_key if len(raw_key) == 1 else raw_key.strip().lower()
return cls(key=key, modifiers=mods, action=action)
shifted = (
_US_ASCII_SHIFT.get(key, "")
if (mods & KeyMod.SHIFT) and len(key) == 1
else ""
)
return cls(key=key, modifiers=mods, action=action, shifted_key=shifted)


class MouseButton(enum.IntEnum):
Expand Down Expand Up @@ -545,6 +646,66 @@ def _has_legacy_c0_mapping(k: str) -> bool:
return _is_ascii_alpha(k) or k in (" ", "@", "[", "\\", "]", "^", "_", "/")


def _is_printable_cp(cp: int) -> bool:
"""Return ``True`` when *cp* is a printable scalar (no ``C0``/``C1``/surrogates).

Examples
--------
>>> from libvt.input import _is_printable_cp
>>> (_is_printable_cp(97), _is_printable_cp(127), _is_printable_cp(0xD800))
(True, False, False)
"""
return cp >= 0x20 and not (0x7F <= cp <= 0x9F) and not (0xD800 <= cp <= 0xDFFF)


def _format_kitty_csi(
key_cp: int,
*,
shifted_cp: int | None = None,
base_layout_cp: int | None = None,
mod_param: int = 1,
ev_suffix: str = "",
assoc_text: str = "",
final: str = "u",
) -> bytes:
r"""Serialize a Kitty progressive-enhancement ``CSI ... u`` / ``~`` sequence.

References
----------
- `Kitty Keyboard Protocol Specification
<https://sw.kovidgoyal.net/kitty/keyboard-protocol/>`__
- `ghostty-org/ghostty src/input/key_encode.zig (v1.4.0)
<https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/input/key_encode.zig#L1036-L1093>`__

Examples
--------
>>> from libvt.input import _format_kitty_csi
>>> _format_kitty_csi(106, shifted_cp=74, mod_param=2, assoc_text="J")
b'\x1b[106:74;2;74u'
"""
parts: list[str] = [f"\x1b[{key_cp}"]
if shifted_cp is not None:
parts.append(f":{shifted_cp}")
if base_layout_cp is not None:
parts.append(
f"::{base_layout_cp}" if shifted_cp is None else f":{base_layout_cp}"
)
emit_prior = False
if ev_suffix:
parts.append(f";{mod_param}{ev_suffix}")
emit_prior = True
elif mod_param > 1:
parts.append(f";{mod_param}")
emit_prior = True
if assoc_text:
cps = [str(ord(ch)) for ch in assoc_text if _is_printable_cp(ord(ch))]
if cps:
parts.append(";" if emit_prior else ";;")
parts.append(":".join(cps))
parts.append(final)
return "".join(parts).encode("ascii")


def _encode_key(
event: KeyEvent,
*,
Expand Down Expand Up @@ -624,11 +785,20 @@ def _encode_key(
return f"\x1b[1;{mod_param}{ev_suffix}{final}".encode("ascii")

# Tilde functional keys
report_alt = bool(kitty_flags & KittyKeyboardFlags.REPORT_ALTERNATE_KEYS)
report_assoc = bool(kitty_flags & KittyKeyboardFlags.REPORT_ASSOCIATED_TEXT)
if k_low in _TILDE_CSI:
num = _TILDE_CSI[k_low]
if mod_param == 1 and not ev_suffix:
return f"\x1b[{num}~".encode("ascii")
return f"\x1b[{num};{mod_param}{ev_suffix}~".encode("ascii")
assoc = (
event.text if (report_assoc and event.action != KeyAction.RELEASE) else ""
)
return _format_kitty_csi(
num,
mod_param=mod_param,
ev_suffix=ev_suffix,
assoc_text=assoc,
final="~",
)

disambig = bool(
kitty_flags
Expand All @@ -641,9 +811,20 @@ def _encode_key(
if k_low in _KEYPAD_MAP:
num_txt, ss3_fin, kp_cp = _KEYPAD_MAP[k_low]
if report_all or disambig or bool(ev_suffix):
if mod_param == 1 and not ev_suffix:
return f"\x1b[{kp_cp}u".encode("ascii")
return f"\x1b[{kp_cp};{mod_param}{ev_suffix}u".encode("ascii")
assoc = ""
if report_assoc and event.action != KeyAction.RELEASE:
if event.text:
assoc = event.text
elif (
event.modifiers & ~KeyMod.SHIFT
) == KeyMod.NONE and num_txt != "\r":
assoc = num_txt
return _format_kitty_csi(
kp_cp,
mod_param=mod_param,
ev_suffix=ev_suffix,
assoc_text=assoc,
)
if modes.is_set(Mode.APPLICATION_KEYPAD):
if mod_param == 1:
return f"\x1bO{ss3_fin}".encode("ascii")
Expand All @@ -669,9 +850,17 @@ def _encode_key(
and (k_low in ("escape", "esc") or event.modifiers != KeyMod.NONE)
)
):
if mod_param == 1 and not ev_suffix:
return f"\x1b[{cp}u".encode("ascii")
return f"\x1b[{cp};{mod_param}{ev_suffix}u".encode("ascii")
assoc = (
event.text
if (report_assoc and event.action != KeyAction.RELEASE)
else ""
)
return _format_kitty_csi(
cp,
mod_param=mod_param,
ev_suffix=ev_suffix,
assoc_text=assoc,
)
decbkm = modes.is_set(Mode.BACKARROW_IS_BS)
legacy_cp = (0x08 if decbkm else 0x7F) if k_low == "backspace" else cp
if (
Expand Down Expand Up @@ -704,16 +893,53 @@ def _encode_key(
or bool(ev_suffix)
or (disambig and (event.modifiers & ~KeyMod.SHIFT) != KeyMod.NONE)
):
base_cp = ord(k.lower()) if "A" <= k <= "Z" else cp
mods = event.modifiers | (KeyMod.SHIFT if "A" <= k <= "Z" else KeyMod.NONE)
is_upper_ascii = "A" <= k <= "Z"
base_cp = ord(k.lower()) if is_upper_ascii else cp
mods = event.modifiers | (KeyMod.SHIFT if is_upper_ascii else KeyMod.NONE)
mp = int(mods) + 1
if mp == 1 and not ev_suffix:
return f"\x1b[{base_cp}u".encode("ascii")
return f"\x1b[{base_cp};{mp}{ev_suffix}u".encode("ascii")
shifted_cp: int | None = None
base_layout_cp: int | None = None
if report_alt and _is_printable_cp(base_cp):
if event.shifted_key and _is_printable_cp(ord(event.shifted_key)):
cand_s = ord(event.shifted_key)
if cand_s != base_cp and (mods & KeyMod.SHIFT):
shifted_cp = cand_s
elif not event.shifted_key and (mods & KeyMod.SHIFT):
sh_ch = k if is_upper_ascii else _US_ASCII_SHIFT.get(k, "")
if sh_ch and ord(sh_ch) != base_cp:
shifted_cp = ord(sh_ch)
if event.base_key and _is_printable_cp(ord(event.base_key)):
cand_b = ord(event.base_key)
if cand_b != base_cp and cand_b != shifted_cp:
base_layout_cp = cand_b
assoc = ""
if report_assoc and event.action != KeyAction.RELEASE:
if event.text:
assoc = event.text
elif (mods & ~KeyMod.SHIFT) == KeyMod.NONE and _is_printable_cp(base_cp):
assoc = (
event.shifted_key
or (k if is_upper_ascii else _US_ASCII_SHIFT.get(k, k))
if (mods & KeyMod.SHIFT)
else chr(base_cp)
)
return _format_kitty_csi(
base_cp,
shifted_cp=shifted_cp,
base_layout_cp=base_layout_cp,
mod_param=mp,
ev_suffix=ev_suffix,
assoc_text=assoc,
)

shifted_plain = (
event.shifted_key
if (event.shifted_key and _is_printable_cp(ord(event.shifted_key)))
else (k.upper() if "a" <= k <= "z" else _US_ASCII_SHIFT.get(k, k))
)
if use_xtmod and event.modifiers != KeyMod.NONE:
mods = event.modifiers | (KeyMod.SHIFT if "A" <= k <= "Z" else KeyMod.NONE)
cp_out = ord(k.upper()) if ("a" <= k <= "z" and (mods & KeyMod.SHIFT)) else cp
cp_out = ord(shifted_plain) if (mods & KeyMod.SHIFT) else cp
if mods == KeyMod.SHIFT:
if cp_out == 0x20:
return b"\x1b[27;2;32~"
Expand All @@ -732,9 +958,7 @@ def _encode_key(
return f"\x1b[27;{int(mods) + 1};{cp_out}~".encode("ascii")

# Legacy xterm key encoding
out_char = (
k.upper() if ("a" <= k <= "z" and (event.modifiers & KeyMod.SHIFT)) else k
)
out_char = shifted_plain if (event.modifiers & KeyMod.SHIFT) else k
if event.modifiers & KeyMod.CTRL:
if _is_ascii_alpha(k):
raw = bytes([(ord(k) | 0x20) - 0x60])
Expand Down
Loading
Loading