//! Termion event conversion. //! //! Termion's parsed events are translated into typed `rustik-tui` events. The //! public entry point is [`TermionEvent`], which pairs the parsed event with //! its raw bytes so that SGR mouse sequences (carrying modifier state termion //! drops) can be recovered. use rustik_tui_core as tui_core; use tui_core::layout::Point; use tui_core::{Event, Key, Modifiers, Mouse, MouseButton}; /// CSI-u code point for the Enter key. const CSI_U_ENTER: u32 = 13; /// CSI-u code point for the Escape key. const CSI_U_ESCAPE: u32 = 27; /// CSI-u code point for the Tab key. const CSI_U_TAB: u32 = 9; /// CSI-u code point for the Backspace key. const CSI_U_BACKSPACE: u32 = 127; /// CSI-u code point for lowercase ASCII `a`. const CSI_U_LOWER_A: u32 = 0x61; /// CSI-u code point for lowercase ASCII `z`. const CSI_U_LOWER_Z: u32 = 0x7A; /// CSI-u modifier bit for Alt. const CSI_U_MOD_ALT: u32 = 0b010; /// CSI-u modifier bit for Control. const CSI_U_MOD_CONTROL: u32 = 0b100; /// Termion input event paired with its source bytes. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TermionEvent { /// Parsed termion event. event: termion::event::Event, /// Raw bytes that produced the event. raw: Vec, } impl From for Event<()> { fn from(event: TermionEvent) -> Self { if let Some(mouse) = sgr_mouse_event(&event.raw) { Event::Mouse(mouse) } else if let Some(key) = csi_u_key(&event.raw) { Event::Key(key) } else { convert_event(event.event) } } } impl From<(termion::event::Event, Vec)> for TermionEvent { fn from((event, raw): (termion::event::Event, Vec)) -> Self { Self { event, raw } } } /// Converts a termion event into a typed `rustik-tui` event. fn convert_event(event: termion::event::Event) -> Event<()> { match event { termion::event::Event::Key(key) => Event::Key(convert_key(key)), termion::event::Event::Mouse(mouse) => Event::Mouse(convert_mouse(mouse)), termion::event::Event::Unsupported(_) => Event::Unsupported, } } /// Converts a termion key into a typed `rustik-tui` key. fn convert_key(key: termion::event::Key) -> Key { match key { termion::event::Key::Backspace => Key::Backspace, termion::event::Key::Left => Key::Left, termion::event::Key::Right => Key::Right, termion::event::Key::Up => Key::Up, termion::event::Key::Down => Key::Down, termion::event::Key::Home => Key::Home, termion::event::Key::End => Key::End, termion::event::Key::PageUp => Key::PageUp, termion::event::Key::PageDown => Key::PageDown, termion::event::Key::BackTab => Key::BackTab, termion::event::Key::Delete => Key::Delete, termion::event::Key::Insert => Key::Insert, termion::event::Key::F(n) => Key::F(n), termion::event::Key::Char('\n') => Key::Enter, termion::event::Key::Char('\t') => Key::Tab, termion::event::Key::Char(ch) => Key::Char(ch), termion::event::Key::Alt(ch) => Key::Alt(ch), termion::event::Key::Ctrl(ch) => Key::Ctrl(ch), termion::event::Key::Null => Key::Null, termion::event::Key::Esc => Key::Esc, _ => Key::Unknown, } } /// Converts a termion mouse event into a typed `rustik-tui` mouse event. fn convert_mouse(event: termion::event::MouseEvent) -> Mouse { match event { termion::event::MouseEvent::Press(button, x, y) => Mouse::Press { button: convert_button(button), at: point(x, y), modifiers: Modifiers::NONE, }, termion::event::MouseEvent::Release(x, y) => Mouse::Release { at: point(x, y), modifiers: Modifiers::NONE, }, termion::event::MouseEvent::Hold(x, y) => Mouse::Hold { at: point(x, y), modifiers: Modifiers::NONE, }, } } /// Converts a termion mouse button into a typed `rustik-tui` mouse button. fn convert_button(button: termion::event::MouseButton) -> MouseButton { match button { termion::event::MouseButton::Left => MouseButton::Left, termion::event::MouseButton::Right => MouseButton::Right, termion::event::MouseButton::Middle => MouseButton::Middle, termion::event::MouseButton::WheelUp => MouseButton::WheelUp, termion::event::MouseButton::WheelDown => MouseButton::WheelDown, _ => MouseButton::Unknown, } } /// Decodes a CSI-u key sequence from the Kitty keyboard protocol. /// /// The disambiguate-escape-codes flag reports modified keys and the Escape key /// as `CSI [; ] u` sequences that termion treats as unsupported. /// This parser recovers the keys representable by [`Key`]. Unmapped codes /// return `None` so the caller falls back to termion's parse. fn csi_u_key(raw: &[u8]) -> Option { if !raw.starts_with(b"\x1B[") || raw.last() != Some(&b'u') { return None; } let body = &raw[2..raw.len() - 1]; let mut fields = body.split(|&byte| byte == b';'); let field = fields.next()?; let code = csi_u_number(field)?; // Modifiers are encoded as a one-based bitmask; absent means no modifiers. let mask = fields .next() .and_then(csi_u_number) .unwrap_or(1) .saturating_sub(1); let ctrl = mask & CSI_U_MOD_CONTROL != 0; let alt = mask & CSI_U_MOD_ALT != 0; match code { CSI_U_ENTER => Some(if ctrl { Key::Ctrl('\r') } else { Key::Enter }), CSI_U_ESCAPE => Some(Key::Esc), CSI_U_TAB => Some(Key::Tab), CSI_U_BACKSPACE => Some(Key::Backspace), CSI_U_LOWER_A..=CSI_U_LOWER_Z => { let ch = char::from(code as u8); Some(if ctrl { Key::Ctrl(ch) } else if alt { Key::Alt(ch) } else { Key::Char(ch) }) } _ => None, } } /// Parses the leading numeric value of a `CSI u` field, ignoring sub-parameters /// introduced by `:` and rejecting non-numeric fields such as `?1` responses. fn csi_u_number(field: &[u8]) -> Option { let head = field.split(|&byte| byte == b':').next()?; if head.is_empty() { return None; } std::str::from_utf8(head).ok()?.parse().ok() } /// Converts one-based terminal coordinates to a zero-based point. fn point(x: u16, y: u16) -> Point { Point::new(x.saturating_sub(1) as usize, y.saturating_sub(1) as usize) } /// Converts an SGR mouse byte sequence into a typed mouse event. fn sgr_mouse_event(raw: &[u8]) -> Option { if !raw.starts_with(b"\x1B[<") { return None; } let final_byte = *raw.last()?; if final_byte != b'M' && final_byte != b'm' { return None; } let body = std::str::from_utf8(&raw[3..raw.len().saturating_sub(1)]).ok()?; let mut parts = body.split(';'); let cb = parts.next()?.parse::().ok()?; let x = parts.next()?.parse::().ok()?; let y = parts.next()?.parse::().ok()?; let button_number = (cb & 0b0000_0011) | ((cb & 0b1100_0000) >> 4); let dragging = cb & 0b0010_0000 != 0; let mut modifiers = Modifiers::NONE; let at = point(x, y); if cb & 0b0000_0100 != 0 { modifiers |= Modifiers::SHIFT; } if cb & 0b0000_1000 != 0 { modifiers |= Modifiers::ALT; } if cb & 0b0001_0000 != 0 { modifiers |= Modifiers::CONTROL; } match (button_number, dragging, final_byte) { (0..=2, true, _) => Some(Mouse::Hold { at, modifiers }), (3, _, _) | (0..=5, false, b'm') => Some(Mouse::Release { at, modifiers }), (0, false, b'M') => Some(Mouse::Press { button: MouseButton::Left, at, modifiers, }), (1, false, b'M') => Some(Mouse::Press { button: MouseButton::Middle, at, modifiers, }), (2, false, b'M') => Some(Mouse::Press { button: MouseButton::Right, at, modifiers, }), (4, false, b'M') => Some(Mouse::Press { button: MouseButton::WheelUp, at, modifiers, }), (5, false, b'M') => Some(Mouse::Press { button: MouseButton::WheelDown, at, modifiers, }), _ => None, } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; #[test] fn termion_keys_are_typed() { assert_eq!(convert_key(termion::event::Key::Char('\n')), Key::Enter); assert_eq!(convert_key(termion::event::Key::Ctrl('c')), Key::Ctrl('c')); } #[test] fn csi_u_recovers_modified_and_special_keys() { let key = |bytes: &[u8]| { let event = TermionEvent::from(( termion::event::Event::Unsupported(bytes.to_vec()), bytes.to_vec(), )); Event::from(event) }; // Ctrl+Enter (keycode 13, Ctrl modifier 4 reported as 5). assert_eq!(key(b"\x1B[13;5u"), Event::Key(Key::Ctrl('\r'))); // Plain Enter reported through the protocol stays Enter. assert_eq!(key(b"\x1B[13u"), Event::Key(Key::Enter)); // Ctrl+D, which the diff viewer binds, survives disambiguation. assert_eq!(key(b"\x1B[100;5u"), Event::Key(Key::Ctrl('d'))); assert_eq!(key(b"\x1B[100;3u"), Event::Key(Key::Alt('d'))); assert_eq!(key(b"\x1B[27u"), Event::Key(Key::Esc)); assert_eq!(key(b"\x1B[57359u"), Event::Unsupported); // A protocol response is not mistaken for a key. assert_eq!(key(b"\x1B[?1u"), Event::Unsupported); } #[test] fn termion_events_are_mapped() { let key = termion::event::Event::Key(termion::event::Key::Char('x')); let mouse = termion::event::Event::Mouse(termion::event::MouseEvent::Release(2, 3)); let unsupported = termion::event::Event::Unsupported(vec![1, 2, 3]); assert_eq!(convert_event(key), Event::Key(Key::Char('x'))); assert_eq!( convert_event(mouse), Event::Mouse(Mouse::Release { at: Point::new(1, 2), modifiers: Modifiers::NONE, }) ); assert_eq!(convert_event(unsupported), Event::Unsupported); } #[test] fn termion_mouse_events_are_zero_based() { assert_eq!( convert_mouse(termion::event::MouseEvent::Press( termion::event::MouseButton::Left, 1, 2, )), Mouse::Press { button: MouseButton::Left, at: Point::new(0, 1), modifiers: Modifiers::NONE, } ); assert_eq!( convert_mouse(termion::event::MouseEvent::Hold(3, 4)), Mouse::Hold { at: Point::new(2, 3), modifiers: Modifiers::NONE, } ); } #[test] fn sgr_mouse_events_preserve_modifiers() { let press = |bytes: &[u8]| { let event = TermionEvent::from(( termion::event::Event::Unsupported(bytes.to_vec()), bytes.to_vec(), )); Event::from(event) }; assert_eq!( press(b"\x1B[<16;3;4M"), Event::Mouse(Mouse::Press { button: MouseButton::Left, at: Point::new(2, 3), modifiers: Modifiers::CONTROL, }) ); assert_eq!( press(b"\x1B[<0;1;2M"), Event::Mouse(Mouse::Press { button: MouseButton::Left, at: Point::new(0, 1), modifiers: Modifiers::NONE, }) ); assert_eq!( press(b"\x1B[<80;3;4M"), Event::Mouse(Mouse::Press { button: MouseButton::WheelUp, at: Point::new(2, 3), modifiers: Modifiers::CONTROL, }) ); } #[test] fn mouse_buttons_are_mapped() { assert_eq!( convert_button(termion::event::MouseButton::Left), MouseButton::Left ); assert_eq!( convert_button(termion::event::MouseButton::Right), MouseButton::Right ); assert_eq!( convert_button(termion::event::MouseButton::Middle), MouseButton::Middle ); assert_eq!( convert_button(termion::event::MouseButton::WheelUp), MouseButton::WheelUp ); assert_eq!( convert_button(termion::event::MouseButton::WheelDown), MouseButton::WheelDown ); } }