tui-termion: Support Kitty keyboard protocol

1309b6a75273e9cc0451529ff4531bec57f4d31c
Alexis Sellier committed ago 1 parent 6438963b
crates/tui-termion/src/event.rs +89 -18
7 7
8 8
use rustik_tui_core as tui_core;
9 9
use tui_core::layout::Point;
10 10
use tui_core::{Event, Key, Modifiers, Mouse, MouseButton};
11 11
12 +
/// CSI-u code point for the Enter key.
13 +
const CSI_U_ENTER: u32 = 13;
14 +
/// CSI-u code point for the Escape key.
15 +
const CSI_U_ESCAPE: u32 = 27;
16 +
/// CSI-u code point for the Tab key.
17 +
const CSI_U_TAB: u32 = 9;
18 +
/// CSI-u code point for the Backspace key.
19 +
const CSI_U_BACKSPACE: u32 = 127;
20 +
/// CSI-u code point for lowercase ASCII `a`.
21 +
const CSI_U_LOWER_A: u32 = 0x61;
22 +
/// CSI-u code point for lowercase ASCII `z`.
23 +
const CSI_U_LOWER_Z: u32 = 0x7A;
24 +
/// CSI-u modifier bit for Alt.
25 +
const CSI_U_MOD_ALT: u32 = 0b010;
26 +
/// CSI-u modifier bit for Control.
27 +
const CSI_U_MOD_CONTROL: u32 = 0b100;
28 +
12 29
/// Termion input event paired with its source bytes.
13 30
#[derive(Debug, Clone, PartialEq, Eq)]
14 31
pub struct TermionEvent {
15 32
    /// Parsed termion event.
16 33
    event: termion::event::Event,
20 37
21 38
impl From<TermionEvent> for Event<()> {
22 39
    fn from(event: TermionEvent) -> Self {
23 40
        if let Some(mouse) = sgr_mouse_event(&event.raw) {
24 41
            Event::Mouse(mouse)
42 +
        } else if let Some(key) = csi_u_key(&event.raw) {
43 +
            Event::Key(key)
25 44
        } else {
26 45
            convert_event(event.event)
27 46
        }
28 47
    }
29 48
}
99 118
        termion::event::MouseButton::WheelDown => MouseButton::WheelDown,
100 119
        _ => MouseButton::Unknown,
101 120
    }
102 121
}
103 122
123 +
/// Decodes a CSI-u key sequence from the Kitty keyboard protocol.
124 +
///
125 +
/// The disambiguate-escape-codes flag reports modified keys and the Escape key
126 +
/// as `CSI <code> [; <mods>] u` sequences that termion treats as unsupported.
127 +
/// This parser recovers the keys representable by [`Key`]. Unmapped codes
128 +
/// return `None` so the caller falls back to termion's parse.
129 +
fn csi_u_key(raw: &[u8]) -> Option<Key> {
130 +
    if !raw.starts_with(b"\x1B[") || raw.last() != Some(&b'u') {
131 +
        return None;
132 +
    }
133 +
    let body = &raw[2..raw.len() - 1];
134 +
    let mut fields = body.split(|&byte| byte == b';');
135 +
    let code = csi_u_number(fields.next()?)?;
136 +
    // Modifiers are encoded as a one-based bitmask; absent means no modifiers.
137 +
    let mask = fields
138 +
        .next()
139 +
        .and_then(csi_u_number)
140 +
        .unwrap_or(1)
141 +
        .saturating_sub(1);
142 +
    let ctrl = mask & CSI_U_MOD_CONTROL != 0;
143 +
    let alt = mask & CSI_U_MOD_ALT != 0;
144 +
145 +
    match code {
146 +
        CSI_U_ENTER => Some(if ctrl { Key::Ctrl('\r') } else { Key::Enter }),
147 +
        CSI_U_ESCAPE => Some(Key::Esc),
148 +
        CSI_U_TAB => Some(Key::Tab),
149 +
        CSI_U_BACKSPACE => Some(Key::Backspace),
150 +
        CSI_U_LOWER_A..=CSI_U_LOWER_Z => {
151 +
            let ch = char::from(code as u8);
152 +
            Some(if ctrl {
153 +
                Key::Ctrl(ch)
154 +
            } else if alt {
155 +
                Key::Alt(ch)
156 +
            } else {
157 +
                Key::Char(ch)
158 +
            })
159 +
        }
160 +
        _ => None,
161 +
    }
162 +
}
163 +
164 +
/// Parses the leading numeric value of a `CSI u` field, ignoring sub-parameters
165 +
/// introduced by `:` and rejecting non-numeric fields such as `?1` responses.
166 +
fn csi_u_number(field: &[u8]) -> Option<u32> {
167 +
    let head = field.split(|&byte| byte == b':').next()?;
168 +
    if head.is_empty() {
169 +
        return None;
170 +
    }
171 +
    std::str::from_utf8(head).ok()?.parse().ok()
172 +
}
173 +
104 174
/// Converts one-based terminal coordinates to a zero-based point.
105 175
fn point(x: u16, y: u16) -> Point {
106 176
    Point::new(x.saturating_sub(1) as usize, y.saturating_sub(1) as usize)
107 177
}
108 178
177 247
        assert_eq!(convert_key(termion::event::Key::Char('\n')), Key::Enter);
178 248
        assert_eq!(convert_key(termion::event::Key::Ctrl('c')), Key::Ctrl('c'));
179 249
    }
180 250
181 251
    #[test]
182 -
    fn all_common_termion_keys_are_mapped() {
183 -
        assert_eq!(convert_key(termion::event::Key::Backspace), Key::Backspace);
184 -
        assert_eq!(convert_key(termion::event::Key::Left), Key::Left);
185 -
        assert_eq!(convert_key(termion::event::Key::Right), Key::Right);
186 -
        assert_eq!(convert_key(termion::event::Key::Up), Key::Up);
187 -
        assert_eq!(convert_key(termion::event::Key::Down), Key::Down);
188 -
        assert_eq!(convert_key(termion::event::Key::Home), Key::Home);
189 -
        assert_eq!(convert_key(termion::event::Key::End), Key::End);
190 -
        assert_eq!(convert_key(termion::event::Key::PageUp), Key::PageUp);
191 -
        assert_eq!(convert_key(termion::event::Key::PageDown), Key::PageDown);
192 -
        assert_eq!(convert_key(termion::event::Key::BackTab), Key::BackTab);
193 -
        assert_eq!(convert_key(termion::event::Key::Delete), Key::Delete);
194 -
        assert_eq!(convert_key(termion::event::Key::Insert), Key::Insert);
195 -
        assert_eq!(convert_key(termion::event::Key::F(5)), Key::F(5));
196 -
        assert_eq!(convert_key(termion::event::Key::Char('\t')), Key::Tab);
197 -
        assert_eq!(convert_key(termion::event::Key::Alt('x')), Key::Alt('x'));
198 -
        assert_eq!(convert_key(termion::event::Key::Null), Key::Null);
199 -
        assert_eq!(convert_key(termion::event::Key::Esc), Key::Esc);
252 +
    fn csi_u_recovers_modified_and_special_keys() {
253 +
        let key = |bytes: &[u8]| {
254 +
            let event = TermionEvent::from((
255 +
                termion::event::Event::Unsupported(bytes.to_vec()),
256 +
                bytes.to_vec(),
257 +
            ));
258 +
            Event::from(event)
259 +
        };
260 +
        // Ctrl+Enter (keycode 13, Ctrl modifier 4 reported as 5).
261 +
        assert_eq!(key(b"\x1B[13;5u"), Event::Key(Key::Ctrl('\r')));
262 +
        // Plain Enter reported through the protocol stays Enter.
263 +
        assert_eq!(key(b"\x1B[13u"), Event::Key(Key::Enter));
264 +
        // Ctrl+D, which the diff viewer binds, survives disambiguation.
265 +
        assert_eq!(key(b"\x1B[100;5u"), Event::Key(Key::Ctrl('d')));
266 +
        assert_eq!(key(b"\x1B[100;3u"), Event::Key(Key::Alt('d')));
267 +
        assert_eq!(key(b"\x1B[27u"), Event::Key(Key::Esc));
268 +
        assert_eq!(key(b"\x1B[57359u"), Event::Unsupported);
269 +
        // A protocol response is not mistaken for a key.
270 +
        assert_eq!(key(b"\x1B[?1u"), Event::Unsupported);
200 271
    }
201 272
202 273
    #[test]
203 274
    fn termion_events_are_mapped() {
204 275
        let key = termion::event::Event::Key(termion::event::Key::Char('x'));
crates/tui-termion/src/term.rs +47 -4
4 4
//! run a `rustik-tui` app on a real terminal. Keeping it outside the core crate avoids
5 5
//! tying widget rendering to termion.
6 6
7 7
use std::fs::{File, OpenOptions};
8 8
use std::io;
9 -
use std::io::Write as _;
9 +
use std::io::Write;
10 10
use std::sync::mpsc;
11 11
use std::thread;
12 12
13 13
use termion::input::{MouseTerminal, TermReadEventsAndRaw};
14 14
use termion::raw::{IntoRawMode, RawTerminal};
26 26
27 27
/// Signals observed by terminal applications.
28 28
const SIGNALS: &[signals::Signal] = &[signals::Signal::WindowChanged];
29 29
/// Controlling terminal path used when standard input is application data.
30 30
const TTY_DEVICE: &str = "/dev/tty";
31 +
/// Sequence enabling the Kitty keyboard protocol's disambiguate-escape-codes
32 +
/// flag, so modified keys and the Escape key are reported as `CSI u` sequences.
33 +
const KEYBOARD_PUSH: &str = "\x1B[>1u";
34 +
/// Sequence restoring the terminal's previous keyboard protocol flags.
35 +
const KEYBOARD_POP: &str = "\x1B[<u";
31 36
/// Process stdout descriptor path used as a terminal fallback.
32 37
const STDOUT_DEVICE: &str = "/proc/self/fd/1";
33 38
/// Process stderr descriptor path used as a terminal fallback.
34 39
const STDERR_DEVICE: &str = "/proc/self/fd/2";
35 40
36 -
/// Raw alternate terminal-device screen.
37 -
pub type TerminalScreen = AlternateScreen<MouseTerminal<RawTerminal<File>>>;
41 +
/// Raw alternate terminal-device screen with the enhanced keyboard protocol.
42 +
pub type TerminalScreen = KeyboardProtocol<AlternateScreen<MouseTerminal<RawTerminal<File>>>>;
38 43
39 44
/// Creates a raw alternate-screen backend on the terminal device.
40 45
pub fn screen() -> io::Result<TermionBackend<TerminalScreen>> {
41 46
    let screen =
42 47
        MouseTerminal::from(terminal_screen()?.into_raw_mode()?).into_alternate_screen()?;
43 -
    Ok(TermionBackend::new(screen))
48 +
    Ok(TermionBackend::new(KeyboardProtocol::new(screen)?))
49 +
}
50 +
51 +
/// Output wrapper that enables the enhanced keyboard protocol for its lifetime.
52 +
///
53 +
/// The protocol lets the terminal report modified keys unambiguously; terminals that do not
54 +
/// implement it ignore the enabling sequence, so this degrades to the legacy keyboard encoding. The
55 +
/// restoring sequence is written when the wrapper is dropped, before the underlying
56 +
/// raw/alternate-screen guards tear down.
57 +
#[derive(Debug)]
58 +
pub struct KeyboardProtocol<W: Write> {
59 +
    /// Wrapped terminal writer.
60 +
    inner: W,
61 +
}
62 +
63 +
impl<W: Write> KeyboardProtocol<W> {
64 +
    /// Enables the protocol on `inner` and returns the guarding wrapper.
65 +
    fn new(mut inner: W) -> io::Result<Self> {
66 +
        inner.write_all(KEYBOARD_PUSH.as_bytes())?;
67 +
        inner.flush()?;
68 +
        Ok(Self { inner })
69 +
    }
70 +
}
71 +
72 +
impl<W: Write> Drop for KeyboardProtocol<W> {
73 +
    fn drop(&mut self) {
74 +
        let _ = self.inner.write_all(KEYBOARD_POP.as_bytes());
75 +
        let _ = self.inner.flush();
76 +
    }
77 +
}
78 +
79 +
impl<W: Write> Write for KeyboardProtocol<W> {
80 +
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
81 +
        self.inner.write(buf)
82 +
    }
83 +
84 +
    fn flush(&mut self) -> io::Result<()> {
85 +
        self.inner.flush()
86 +
    }
44 87
}
45 88
46 89
/// Returns typed events from the terminal.
47 90
pub fn events() -> impl Iterator<Item = io::Result<Event<()>>> {
48 91
    event_receiver().into_iter()