diff --git a/CHANGES b/CHANGES index e855afb..ad4b7de 100644 --- a/CHANGES +++ b/CHANGES @@ -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 diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md index 38d0fd7..965945e 100644 --- a/docs/topics/protocols-and-input.md +++ b/docs/topics/protocols-and-input.md @@ -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 @@ -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 diff --git a/src/libvt/input.py b/src/libvt/input.py index 38d1de2..ecb16f6 100644 --- a/src/libvt/input.py +++ b/src/libvt/input.py @@ -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. @@ -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 + `__ + - `ghostty-org/ghostty src/input/key_encode.zig (v1.4.0) + `__ + + 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 + `__ + + 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("+") @@ -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): @@ -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 + `__ + - `ghostty-org/ghostty src/input/key_encode.zig (v1.4.0) + `__ + + 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, *, @@ -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 @@ -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") @@ -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 ( @@ -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~" @@ -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]) diff --git a/tests/test_input.py b/tests/test_input.py index f7ee4ba..a21da22 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -359,3 +359,74 @@ def test_xtsave_xtrestore_decarm_8_decnkm_66_decbkm_67_and_mouse_tracker() -> No term.feed(b"\x1b[?1003h") assert tracker.filter_event(drag_next, modes=term.modes) == drag_next assert tracker.filter_event(drag_next, modes=term.modes) == drag_next + + +def test_kitty_report_alternate_keys_and_associated_text() -> None: + """``REPORT_ALTERNATE_KEYS`` (``4``) and ``REPORT_ASSOCIATED_TEXT`` (``16``).""" + assert ( + int(KittyKeyboardFlags.DISAMBIGUATE), + int(KittyKeyboardFlags.REPORT_EVENT_TYPES), + int(KittyKeyboardFlags.REPORT_ALTERNATE_KEYS), + int(KittyKeyboardFlags.REPORT_ALL_KEYS), + int(KittyKeyboardFlags.REPORT_ASSOCIATED_TEXT), + ) == (1, 2, 4, 8, 16) + + term = libvt.Terminal(rows=4, cols=20) + # Standalone >4u or >16u never promotes legacy keys to CSI u without 1 or 8: + for standalone_flag in (b"\x1b[>4u", b"\x1b[>16u"): + term.feed(standalone_flag) + assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x01" + assert term.encode(KeyEvent.parse("a")) == b"a" + assert term.encode(KeyEvent.parse("shift+1")) == b"!" + term.feed(b"\x1b[<1u") + + # DISAMBIGUATE | REPORT_ALTERNATE_KEYS (1 | 4 = 5): + term.feed(b"\x1b[>5u") + assert term.encode(KeyEvent.parse("ctrl+shift+a")) == b"\x1b[97:65;6u" + assert term.encode(KeyEvent.parse("ctrl+shift+1")) == b"\x1b[49:33;6u" + assert term.encode(KeyEvent.parse("shift+1")) == b"!" + assert ( + term.encode(KeyEvent("a", modifiers=KeyMod.CTRL, shifted_key="A")) + == b"\x1b[97;5u" + ) + # Non-Latin layout key with base_key only (::base) and shifted+base (:shifted:base): + cyr_ctrl = KeyEvent(key="\u0441", modifiers=KeyMod.CTRL, base_key="c") + assert term.encode(cyr_ctrl) == b"\x1b[1089::99;5u" + cyr_cs = KeyEvent( + key="\u0441", + modifiers=KeyMod.CTRL | KeyMod.SHIFT, + shifted_key="\u0421", + base_key="c", + ) + assert term.encode(cyr_cs) == b"\x1b[1089:1057:99;6u" + term.feed(b"\x1b[<1u") + + # All 5 flags (31): associated text on PRESS/REPEAT, omitted on RELEASE & controls. + term.feed(b"\x1b[>31u") + assert term.encode(KeyEvent.parse("a")) == b"\x1b[97;;97u" + assert term.encode(KeyEvent.parse("shift+j")) == b"\x1b[106:74;2;74u" + assert term.encode(KeyEvent.parse("shift+1")) == b"\x1b[49:33;2;33u" + assert ( + term.encode(KeyEvent.parse("shift+j", action=KeyAction.RELEASE)) + == b"\x1b[106:74;2:3u" + ) + assert ( + term.encode(KeyEvent.parse("a", action=KeyAction.REPEAT)) == b"\x1b[97;1:2;97u" + ) + assert term.encode(KeyEvent(key="kp_1")) == b"\x1b[57400;;49u" + assert term.encode(KeyEvent.parse("enter")) == b"\x1b[13u" + assert term.encode(KeyEvent.parse("up")) == b"\x1b[A" + assert term.encode(KeyEvent.parse("up", action=KeyAction.RELEASE)) == b"\x1b[1;1:3A" + assert term.encode(KeyEvent.parse("delete")) == b"\x1b[3~" + assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[97;5u" + # Multi-codepoint IME/composed text strips C0, DEL, C1, and lone surrogates: + composed = KeyEvent( + key="e", + modifiers=KeyMod.ALT, + text="é\x07\x7f\x9b\ud800!", + shifted_key="\ud800", + ) + assert term.encode(composed) == b"\x1b[101;3;233:33u" + + with pytest.raises(ValueError, match="single character"): + KeyEvent(key="a", shifted_key="ab")