Skip to main content

indigo_term/input/
physical.rs

1//! Splitting bytes from the terminal into sequences, without interpreting them
2
3use crate::input::{BRACKETED_PASTE_BEGIN, BRACKETED_PASTE_END};
4use std::cmp::min;
5use tinyvec::{ArrayVec, TinyVec};
6use winnow::{
7    Partial,
8    combinator::alt,
9    error::{ErrMode, Needed},
10    prelude::*,
11    token::{one_of, take_while},
12};
13
14#[derive(Debug, PartialEq)]
15pub enum Token {
16    /// Control Sequence Introducer
17    ///
18    /// <https://ghostty.org/docs/vt/concepts/sequences#csi>
19    Csi {
20        parameter_bytes: TinyVec<[u8; 32]>,
21        intermediate_bytes: TinyVec<[u8; 2]>,
22        final_byte: u8,
23    },
24    /// Operating System Command
25    ///
26    /// <https://ghostty.org/docs/vt/concepts/sequences#osc>
27    Osc { data_bytes: TinyVec<[u8; 32]> },
28    /// Start of pasted text, when bracketed paste is enabled
29    ///
30    /// <https://en.wikipedia.org/wiki/Bracketed-paste>
31    PasteBegin,
32    /// Some pasted text, between [`Token::PasteBegin`] and [`Token::PasteEnd`]
33    PasteChunk(ArrayVec<[u8; 32]>),
34    /// End of pasted text
35    PasteEnd,
36}
37
38#[derive(Default)]
39pub struct Tokenizer {
40    buffer: ArrayVec<[u8; 1024]>,
41    in_paste: bool,
42}
43
44impl Tokenizer {
45    #[must_use]
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// Add as many bytes as fit, returning how many were added. Take tokens with
51    /// [`Tokenizer::next_token`] to make room for more.
52    #[must_use]
53    pub fn feed(&mut self, bytes: &[u8]) -> usize {
54        let count = min(bytes.len(), self.buffer.capacity() - self.buffer.len());
55        self.buffer.extend_from_slice(&bytes[..count]);
56        count
57    }
58
59    /// Split off the next token, or return `None` if more bytes are needed.
60    pub fn next_token(&mut self) -> Option<Token> {
61        loop {
62            // Pasted text isn't garbage
63            if !self.in_paste {
64                self.skip_garbage();
65            }
66
67            if self.buffer.is_empty() {
68                return None;
69            }
70
71            let input = Partial::new(self.buffer.as_slice());
72
73            let mut parser = if self.in_paste { paste_token } else { token };
74
75            match parser.parse_peek(input) {
76                Ok((remaining, token)) => {
77                    let consumed = self.buffer.len() - remaining.len();
78                    self.buffer.drain(..consumed);
79                    match token {
80                        Token::PasteBegin => self.in_paste = true,
81                        Token::PasteEnd => self.in_paste = false,
82                        _ => {}
83                    }
84                    return Some(token);
85                }
86                Err(ErrMode::Incomplete(_)) => return None,
87                Err(_) => {
88                    // Malformed sequence, skip the leading 0x1b and retry
89                    self.buffer.drain(..1);
90                }
91            }
92        }
93    }
94
95    /// Skip any non-ESC bytes at the front of the buffer. These are garbage bytes that don't start
96    /// any recognized sequence.
97    fn skip_garbage(&mut self) {
98        let garbage_count = self
99            .buffer
100            .iter()
101            .position(|&byte| byte == /* ESC */ 0x1B)
102            .unwrap_or(self.buffer.len());
103        if garbage_count > 0 {
104            self.buffer.drain(..garbage_count);
105        }
106    }
107}
108
109fn token(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
110    alt((paste_begin, csi, osc)).parse_next(input)
111}
112
113fn paste_token(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
114    alt((paste_end, paste_chunk)).parse_next(input)
115}
116
117fn paste_begin(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
118    BRACKETED_PASTE_BEGIN.void().parse_next(input)?;
119    Ok(Token::PasteBegin)
120}
121
122fn paste_end(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
123    BRACKETED_PASTE_END.void().parse_next(input)?;
124    Ok(Token::PasteEnd)
125}
126
127fn paste_chunk(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
128    if input.is_empty() {
129        return Err(ErrMode::Incomplete(Needed::new(1)));
130    }
131    // Take whatever bytes are available, up to the chunk's capacity, but stop before the next ESC
132    // in case it begins the end marker. A leading ESC is pasted text, since `paste_end` didn't
133    // match it.
134    let mut chunk = ArrayVec::new();
135    let length = input
136        .iter()
137        .skip(1)
138        .position(|&byte| byte == 0x1B)
139        .map_or(input.len(), |position| position + 1);
140    let length = min(length, chunk.capacity());
141    chunk.extend_from_slice(input.next_slice(length));
142    Ok(Token::PasteChunk(chunk))
143}
144
145fn csi(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
146    "\x1b[".void().parse_next(input)?;
147    let parameter_bytes = take_while(0.., 0x30..=0x3F)
148        .map(TinyVec::from)
149        .parse_next(input)?;
150    if parameter_bytes.is_heap() {
151        tracing::debug!(
152            "got {} csi parameter bytes, overflowing to heap",
153            parameter_bytes.len()
154        );
155    }
156    let intermediate_bytes = take_while(0.., 0x20..=0x2F)
157        .map(TinyVec::from)
158        .parse_next(input)?;
159    if intermediate_bytes.is_heap() {
160        tracing::debug!(
161            "got {} csi intermediate bytes, overflowing to heap",
162            intermediate_bytes.len()
163        );
164    }
165    let final_byte = one_of(0x40..=0x7E).parse_next(input)?;
166    Ok(Token::Csi {
167        parameter_bytes,
168        intermediate_bytes,
169        final_byte,
170    })
171}
172
173fn osc(input: &mut Partial<&[u8]>) -> winnow::ModalResult<Token> {
174    "\x1b]".void().parse_next(input)?;
175    let data_bytes = take_while(0.., 0x20..=0xFF)
176        .map(TinyVec::from)
177        .parse_next(input)?;
178    if data_bytes.is_heap() {
179        tracing::debug!(
180            "found {} osc intermediate bytes, overflowing to heap",
181            data_bytes.len()
182        );
183    }
184    alt(("\x07", "\x1b\x5c")).void().parse_next(input)?;
185    Ok(Token::Osc { data_bytes })
186}