Skip to main content

indigo_term/
input.rs

1//! Decoding what the terminal sends
2
3pub mod logical;
4pub mod physical;
5
6use crate::{
7    input::physical::{Token, Tokenizer},
8    output::KeyboardEnhancementFlags,
9};
10use bitflags::bitflags;
11use std::mem;
12
13// Decoder
14
15#[derive(Default)]
16pub struct Decoder {
17    tokenizer: Tokenizer,
18    paste: Vec<u8>,
19}
20
21impl Decoder {
22    #[must_use]
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Add as many bytes as fit, returning how many were added. Take events with
28    /// [`Decoder::next_event`] to make room for more.
29    #[must_use]
30    pub fn feed(&mut self, bytes: &[u8]) -> usize {
31        self.tokenizer.feed(bytes)
32    }
33
34    /// Decode the next event, or return `None` if more bytes are needed.
35    pub fn next_event(&mut self) -> Option<Event> {
36        while let Some(token) = self.tokenizer.next_token() {
37            match token {
38                Token::PasteBegin => {}
39                Token::PasteChunk(chunk) => self.paste.extend_from_slice(&chunk),
40                Token::PasteEnd => {
41                    let paste = mem::take(&mut self.paste);
42                    return Some(Event::Paste(String::from_utf8_lossy_owned(paste)));
43                }
44                token => return Some(logical::decode(token)),
45            }
46        }
47        None
48    }
49}
50
51// Events
52
53#[derive(Debug, PartialEq)]
54pub enum Event {
55    KeyPress(Key),
56    KeyRepeat(Key),
57    KeyRelease(Key),
58    Resize {
59        height: u16,
60        width: u16,
61    },
62    /// Text pasted while bracketed paste is enabled, with any invalid UTF-8 replaced. Use a
63    /// [`Tokenizer`] to get the raw bytes instead, as they arrive.
64    ///
65    /// <https://en.wikipedia.org/wiki/Bracketed-paste>
66    Paste(String),
67    /// Kitty keyboard protocol progressive enhancement flags
68    ///
69    /// <https://sw.kovidgoyal.net/kitty/keyboard-protocol/#progressive-enhancement>
70    KeyboardEnhancementFlags(KeyboardEnhancementFlags),
71    /// Primary device attributes
72    ///
73    /// <https://vt100.net/docs/vt510-rm/DA1.html>
74    Da1,
75    /// Report mode
76    ///
77    /// <https://vt100.net/docs/vt510-rm/DECRPM.html>
78    Decrpm {
79        mode: u16,
80        setting: ModeSetting,
81    },
82    /// Color scheme report, sent in response to a query or when the color scheme changes
83    ///
84    /// <https://github.com/contour-terminal/contour/blob/master/docs/vt-extensions/color-palette-update-notifications.md>
85    ColorScheme(ColorScheme),
86    /// Cursor position report, sent in response to a query. The row and column start at 1.
87    ///
88    /// <https://vt100.net/docs/vt510-rm/CPR.html>
89    CursorPosition {
90        row: u16,
91        column: u16,
92    },
93    /// A sequence that isn't recognized
94    Unknown(Token),
95}
96
97// Keys
98
99#[derive(Debug, PartialEq)]
100pub struct Key {
101    pub code: KeyCode,
102    pub modifiers: KeyModifiers,
103}
104
105#[derive(Debug, PartialEq)]
106pub enum KeyCode {
107    Esc,
108    Backspace,
109    Tab,
110    Enter,
111    Left,
112    Right,
113    Up,
114    Down,
115    Char(char),
116}
117
118bitflags! {
119    #[derive(Debug, PartialEq)]
120    pub struct KeyModifiers: u8 {
121        const SHIFT = 1;
122        const ALT = 2;
123        const CTRL = 4;
124    }
125}
126
127// Modes
128
129#[derive(Debug, PartialEq)]
130pub enum ModeSetting {
131    NotRecognized,
132    Set,
133    Reset,
134    PermanentlySet,
135    PermanentlyReset,
136}
137
138impl ModeSetting {
139    #[must_use]
140    pub fn is_recognized(&self) -> bool {
141        !matches!(self, Self::NotRecognized)
142    }
143
144    #[must_use]
145    pub fn is_enabled(&self) -> bool {
146        matches!(self, Self::Set | Self::PermanentlySet)
147    }
148
149    #[must_use]
150    pub fn is_disabled(&self) -> bool {
151        matches!(
152            self,
153            Self::NotRecognized | Self::Reset | Self::PermanentlyReset
154        )
155    }
156
157    #[must_use]
158    pub fn is_configurable(&self) -> bool {
159        matches!(self, Self::Set | Self::Reset)
160    }
161}
162
163// Color scheme
164// https://github.com/contour-terminal/contour/blob/master/docs/vt-extensions/color-palette-update-notifications.md
165
166#[derive(Debug, PartialEq)]
167pub enum ColorScheme {
168    Dark,
169    Light,
170}
171
172// Bracketed paste
173// https://en.wikipedia.org/wiki/Bracketed-paste
174
175pub const BRACKETED_PASTE_BEGIN: &str = "\x1b[200~";
176pub const BRACKETED_PASTE_END: &str = "\x1b[201~";
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use hegel::generators as gs;
182
183    /// Feed `input` to a decoder in chunks split at `splits`, taking events after each chunk.
184    fn decode_chunked(input: &[u8], splits: &[usize]) -> Vec<Event> {
185        let mut decoder = Decoder::new();
186        let mut events = Vec::new();
187        let mut start = 0;
188        for end in splits.iter().copied().chain([input.len()]) {
189            let mut chunk = &input[start..end];
190            start = end;
191            while !chunk.is_empty() {
192                let fed = decoder.feed(chunk);
193                assert!(fed > 0, "decoder buffer full");
194                chunk = &chunk[fed..];
195                while let Some(event) = decoder.next_event() {
196                    events.push(event);
197                }
198            }
199        }
200        events
201    }
202
203    #[hegel::test(test_cases = 1_000)]
204    fn paste_is_decoded_regardless_of_chunking(tc: hegel::TestCase) {
205        // A partial end marker, an escape sequence, a run long enough to fill a chunk, multi-byte
206        // UTF-8, and invalid UTF-8. None of these combine to form the end marker.
207        let piece = gs::sampled_from(vec![
208            &b"\x1b[20"[..],
209            b"\x1b[A",
210            b"a run of pasted text that fills a whole chunk",
211            "é".as_bytes(),
212            b"\xff",
213        ]);
214        let text = tc.draw(gs::vecs(piece)).concat();
215        let input = [
216            BRACKETED_PASTE_BEGIN.as_bytes(),
217            &text,
218            BRACKETED_PASTE_END.as_bytes(),
219            b"\x1b[97u",
220        ]
221        .concat();
222        let mut splits = tc.draw(gs::vecs(gs::integers::<usize>().max_value(input.len())));
223        splits.sort_unstable();
224        assert_eq!(
225            decode_chunked(&input, &splits),
226            vec![
227                Event::Paste(String::from_utf8_lossy(&text).into_owned()),
228                Event::KeyPress(Key {
229                    code: KeyCode::Char('a'),
230                    modifiers: KeyModifiers::empty(),
231                }),
232            ]
233        );
234    }
235
236    #[test]
237    fn paste_can_be_larger_than_the_buffer() {
238        let text = "a run of pasted text that fills a whole chunk\n".repeat(100);
239        let input = [BRACKETED_PASTE_BEGIN, &text, BRACKETED_PASTE_END].concat();
240        assert_eq!(
241            decode_chunked(input.as_bytes(), &[]),
242            vec![Event::Paste(text)]
243        );
244    }
245}