crates/tui-termion/src/event.rs 12.5 KiB raw
1
//! Termion event conversion.
2
//!
3
//! Termion's parsed events are translated into typed `rustik-tui` events. The
4
//! public entry point is [`TermionEvent`], which pairs the parsed event with
5
//! its raw bytes so that SGR mouse sequences (carrying modifier state termion
6
//! drops) can be recovered.
7
8
use rustik_tui_core as tui_core;
9
use tui_core::layout::Point;
10
use tui_core::{Event, Key, Modifiers, Mouse, MouseButton};
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
29
/// Termion input event paired with its source bytes.
30
#[derive(Debug, Clone, PartialEq, Eq)]
31
pub struct TermionEvent {
32
    /// Parsed termion event.
33
    event: termion::event::Event,
34
    /// Raw bytes that produced the event.
35
    raw: Vec<u8>,
36
}
37
38
impl From<TermionEvent> for Event<()> {
39
    fn from(event: TermionEvent) -> Self {
40
        if let Some(mouse) = sgr_mouse_event(&event.raw) {
41
            Event::Mouse(mouse)
42
        } else if let Some(key) = csi_u_key(&event.raw) {
43
            Event::Key(key)
44
        } else {
45
            convert_event(event.event)
46
        }
47
    }
48
}
49
50
impl From<(termion::event::Event, Vec<u8>)> for TermionEvent {
51
    fn from((event, raw): (termion::event::Event, Vec<u8>)) -> Self {
52
        Self { event, raw }
53
    }
54
}
55
56
/// Converts a termion event into a typed `rustik-tui` event.
57
fn convert_event(event: termion::event::Event) -> Event<()> {
58
    match event {
59
        termion::event::Event::Key(key) => Event::Key(convert_key(key)),
60
        termion::event::Event::Mouse(mouse) => Event::Mouse(convert_mouse(mouse)),
61
        termion::event::Event::Unsupported(_) => Event::Unsupported,
62
    }
63
}
64
65
/// Converts a termion key into a typed `rustik-tui` key.
66
fn convert_key(key: termion::event::Key) -> Key {
67
    match key {
68
        termion::event::Key::Backspace => Key::Backspace,
69
        termion::event::Key::Left => Key::Left,
70
        termion::event::Key::Right => Key::Right,
71
        termion::event::Key::Up => Key::Up,
72
        termion::event::Key::Down => Key::Down,
73
        termion::event::Key::Home => Key::Home,
74
        termion::event::Key::End => Key::End,
75
        termion::event::Key::PageUp => Key::PageUp,
76
        termion::event::Key::PageDown => Key::PageDown,
77
        termion::event::Key::BackTab => Key::BackTab,
78
        termion::event::Key::Delete => Key::Delete,
79
        termion::event::Key::Insert => Key::Insert,
80
        termion::event::Key::F(n) => Key::F(n),
81
        termion::event::Key::Char('\n') => Key::Enter,
82
        termion::event::Key::Char('\t') => Key::Tab,
83
        termion::event::Key::Char(ch) => Key::Char(ch),
84
        termion::event::Key::Alt(ch) => Key::Alt(ch),
85
        termion::event::Key::Ctrl(ch) => Key::Ctrl(ch),
86
        termion::event::Key::Null => Key::Null,
87
        termion::event::Key::Esc => Key::Esc,
88
        _ => Key::Unknown,
89
    }
90
}
91
92
/// Converts a termion mouse event into a typed `rustik-tui` mouse event.
93
fn convert_mouse(event: termion::event::MouseEvent) -> Mouse {
94
    match event {
95
        termion::event::MouseEvent::Press(button, x, y) => Mouse::Press {
96
            button: convert_button(button),
97
            at: point(x, y),
98
            modifiers: Modifiers::NONE,
99
        },
100
        termion::event::MouseEvent::Release(x, y) => Mouse::Release {
101
            at: point(x, y),
102
            modifiers: Modifiers::NONE,
103
        },
104
        termion::event::MouseEvent::Hold(x, y) => Mouse::Hold {
105
            at: point(x, y),
106
            modifiers: Modifiers::NONE,
107
        },
108
    }
109
}
110
111
/// Converts a termion mouse button into a typed `rustik-tui` mouse button.
112
fn convert_button(button: termion::event::MouseButton) -> MouseButton {
113
    match button {
114
        termion::event::MouseButton::Left => MouseButton::Left,
115
        termion::event::MouseButton::Right => MouseButton::Right,
116
        termion::event::MouseButton::Middle => MouseButton::Middle,
117
        termion::event::MouseButton::WheelUp => MouseButton::WheelUp,
118
        termion::event::MouseButton::WheelDown => MouseButton::WheelDown,
119
        _ => MouseButton::Unknown,
120
    }
121
}
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 field = fields.next()?;
136
    let code = csi_u_number(field)?;
137
    // Modifiers are encoded as a one-based bitmask; absent means no modifiers.
138
    let mask = fields
139
        .next()
140
        .and_then(csi_u_number)
141
        .unwrap_or(1)
142
        .saturating_sub(1);
143
    let ctrl = mask & CSI_U_MOD_CONTROL != 0;
144
    let alt = mask & CSI_U_MOD_ALT != 0;
145
146
    match code {
147
        CSI_U_ENTER => Some(if ctrl { Key::Ctrl('\r') } else { Key::Enter }),
148
        CSI_U_ESCAPE => Some(Key::Esc),
149
        CSI_U_TAB => Some(Key::Tab),
150
        CSI_U_BACKSPACE => Some(Key::Backspace),
151
        CSI_U_LOWER_A..=CSI_U_LOWER_Z => {
152
            let ch = char::from(code as u8);
153
            Some(if ctrl {
154
                Key::Ctrl(ch)
155
            } else if alt {
156
                Key::Alt(ch)
157
            } else {
158
                Key::Char(ch)
159
            })
160
        }
161
        _ => None,
162
    }
163
}
164
165
/// Parses the leading numeric value of a `CSI u` field, ignoring sub-parameters
166
/// introduced by `:` and rejecting non-numeric fields such as `?1` responses.
167
fn csi_u_number(field: &[u8]) -> Option<u32> {
168
    let head = field.split(|&byte| byte == b':').next()?;
169
    if head.is_empty() {
170
        return None;
171
    }
172
    std::str::from_utf8(head).ok()?.parse().ok()
173
}
174
175
/// Converts one-based terminal coordinates to a zero-based point.
176
fn point(x: u16, y: u16) -> Point {
177
    Point::new(x.saturating_sub(1) as usize, y.saturating_sub(1) as usize)
178
}
179
180
/// Converts an SGR mouse byte sequence into a typed mouse event.
181
fn sgr_mouse_event(raw: &[u8]) -> Option<Mouse> {
182
    if !raw.starts_with(b"\x1B[<") {
183
        return None;
184
    }
185
    let final_byte = *raw.last()?;
186
    if final_byte != b'M' && final_byte != b'm' {
187
        return None;
188
    }
189
    let body = std::str::from_utf8(&raw[3..raw.len().saturating_sub(1)]).ok()?;
190
    let mut parts = body.split(';');
191
    let cb = parts.next()?.parse::<u16>().ok()?;
192
    let x = parts.next()?.parse::<u16>().ok()?;
193
    let y = parts.next()?.parse::<u16>().ok()?;
194
    let button_number = (cb & 0b0000_0011) | ((cb & 0b1100_0000) >> 4);
195
    let dragging = cb & 0b0010_0000 != 0;
196
    let mut modifiers = Modifiers::NONE;
197
    let at = point(x, y);
198
199
    if cb & 0b0000_0100 != 0 {
200
        modifiers |= Modifiers::SHIFT;
201
    }
202
    if cb & 0b0000_1000 != 0 {
203
        modifiers |= Modifiers::ALT;
204
    }
205
    if cb & 0b0001_0000 != 0 {
206
        modifiers |= Modifiers::CONTROL;
207
    }
208
209
    match (button_number, dragging, final_byte) {
210
        (0..=2, true, _) => Some(Mouse::Hold { at, modifiers }),
211
        (3, _, _) | (0..=5, false, b'm') => Some(Mouse::Release { at, modifiers }),
212
        (0, false, b'M') => Some(Mouse::Press {
213
            button: MouseButton::Left,
214
            at,
215
            modifiers,
216
        }),
217
        (1, false, b'M') => Some(Mouse::Press {
218
            button: MouseButton::Middle,
219
            at,
220
            modifiers,
221
        }),
222
        (2, false, b'M') => Some(Mouse::Press {
223
            button: MouseButton::Right,
224
            at,
225
            modifiers,
226
        }),
227
        (4, false, b'M') => Some(Mouse::Press {
228
            button: MouseButton::WheelUp,
229
            at,
230
            modifiers,
231
        }),
232
        (5, false, b'M') => Some(Mouse::Press {
233
            button: MouseButton::WheelDown,
234
            at,
235
            modifiers,
236
        }),
237
        _ => None,
238
    }
239
}
240
241
#[cfg(test)]
242
#[allow(clippy::unwrap_used)]
243
mod tests {
244
    use super::*;
245
246
    #[test]
247
    fn termion_keys_are_typed() {
248
        assert_eq!(convert_key(termion::event::Key::Char('\n')), Key::Enter);
249
        assert_eq!(convert_key(termion::event::Key::Ctrl('c')), Key::Ctrl('c'));
250
    }
251
252
    #[test]
253
    fn csi_u_recovers_modified_and_special_keys() {
254
        let key = |bytes: &[u8]| {
255
            let event = TermionEvent::from((
256
                termion::event::Event::Unsupported(bytes.to_vec()),
257
                bytes.to_vec(),
258
            ));
259
            Event::from(event)
260
        };
261
        // Ctrl+Enter (keycode 13, Ctrl modifier 4 reported as 5).
262
        assert_eq!(key(b"\x1B[13;5u"), Event::Key(Key::Ctrl('\r')));
263
        // Plain Enter reported through the protocol stays Enter.
264
        assert_eq!(key(b"\x1B[13u"), Event::Key(Key::Enter));
265
        // Ctrl+D, which the diff viewer binds, survives disambiguation.
266
        assert_eq!(key(b"\x1B[100;5u"), Event::Key(Key::Ctrl('d')));
267
        assert_eq!(key(b"\x1B[100;3u"), Event::Key(Key::Alt('d')));
268
        assert_eq!(key(b"\x1B[27u"), Event::Key(Key::Esc));
269
        assert_eq!(key(b"\x1B[57359u"), Event::Unsupported);
270
        // A protocol response is not mistaken for a key.
271
        assert_eq!(key(b"\x1B[?1u"), Event::Unsupported);
272
    }
273
274
    #[test]
275
    fn termion_events_are_mapped() {
276
        let key = termion::event::Event::Key(termion::event::Key::Char('x'));
277
        let mouse = termion::event::Event::Mouse(termion::event::MouseEvent::Release(2, 3));
278
        let unsupported = termion::event::Event::Unsupported(vec![1, 2, 3]);
279
280
        assert_eq!(convert_event(key), Event::Key(Key::Char('x')));
281
        assert_eq!(
282
            convert_event(mouse),
283
            Event::Mouse(Mouse::Release {
284
                at: Point::new(1, 2),
285
                modifiers: Modifiers::NONE,
286
            })
287
        );
288
        assert_eq!(convert_event(unsupported), Event::Unsupported);
289
    }
290
291
    #[test]
292
    fn termion_mouse_events_are_zero_based() {
293
        assert_eq!(
294
            convert_mouse(termion::event::MouseEvent::Press(
295
                termion::event::MouseButton::Left,
296
                1,
297
                2,
298
            )),
299
            Mouse::Press {
300
                button: MouseButton::Left,
301
                at: Point::new(0, 1),
302
                modifiers: Modifiers::NONE,
303
            }
304
        );
305
        assert_eq!(
306
            convert_mouse(termion::event::MouseEvent::Hold(3, 4)),
307
            Mouse::Hold {
308
                at: Point::new(2, 3),
309
                modifiers: Modifiers::NONE,
310
            }
311
        );
312
    }
313
314
    #[test]
315
    fn sgr_mouse_events_preserve_modifiers() {
316
        let press = |bytes: &[u8]| {
317
            let event = TermionEvent::from((
318
                termion::event::Event::Unsupported(bytes.to_vec()),
319
                bytes.to_vec(),
320
            ));
321
            Event::from(event)
322
        };
323
324
        assert_eq!(
325
            press(b"\x1B[<16;3;4M"),
326
            Event::Mouse(Mouse::Press {
327
                button: MouseButton::Left,
328
                at: Point::new(2, 3),
329
                modifiers: Modifiers::CONTROL,
330
            })
331
        );
332
        assert_eq!(
333
            press(b"\x1B[<0;1;2M"),
334
            Event::Mouse(Mouse::Press {
335
                button: MouseButton::Left,
336
                at: Point::new(0, 1),
337
                modifiers: Modifiers::NONE,
338
            })
339
        );
340
        assert_eq!(
341
            press(b"\x1B[<80;3;4M"),
342
            Event::Mouse(Mouse::Press {
343
                button: MouseButton::WheelUp,
344
                at: Point::new(2, 3),
345
                modifiers: Modifiers::CONTROL,
346
            })
347
        );
348
    }
349
350
    #[test]
351
    fn mouse_buttons_are_mapped() {
352
        assert_eq!(
353
            convert_button(termion::event::MouseButton::Left),
354
            MouseButton::Left
355
        );
356
        assert_eq!(
357
            convert_button(termion::event::MouseButton::Right),
358
            MouseButton::Right
359
        );
360
        assert_eq!(
361
            convert_button(termion::event::MouseButton::Middle),
362
            MouseButton::Middle
363
        );
364
        assert_eq!(
365
            convert_button(termion::event::MouseButton::WheelUp),
366
            MouseButton::WheelUp
367
        );
368
        assert_eq!(
369
            convert_button(termion::event::MouseButton::WheelDown),
370
            MouseButton::WheelDown
371
        );
372
    }
373
}