Skip to main content

cellix_term/
replies.rs

1//! The terminal's answers to Cellix's questions, told from keys whenever they come.
2//!
3//! The questions (`detect.rs`) are answered on the input the keys come on, and an answer that
4//! comes after its wait has run out is read by the loop like anything else. crossterm makes keys
5//! of what it doesn't know: the background's answer became Alt+], a key for each character of
6//! `11;rgb:1010/1111/1414`, and Alt+\, and was typed into the open file. Device attributes, the
7//! cell size and the modes' reports it swallows whole, but where a read ends just after an
8//! answer's ESC it hands over an Esc and then the rest as keys. And where a wait ran out partway
9//! through an answer, the rest of it comes with nothing to say what it is.
10//!
11//! So everything read goes through `Replies`, which knows the shape of every answer Cellix's
12//! questions can bring and drops them wherever they arrive. What may be the start of one is held
13//! until it's clear, and given back as it was when it isn't one. A wait that ran out says how far
14//! it had read into an answer (`owed`), so the rest of it is known for what it is.
15
16use std::collections::VecDeque;
17use std::sync::Mutex;
18use std::time::{Duration, Instant};
19
20/// How long after a question's wait ran out its answers may still come. In that time an Esc,
21/// or an Alt+] or Alt+_ standing alone, is held a moment in case an answer's rest follows it.
22pub const LATE: Duration = Duration::from_secs(10);
23
24const ESC: u8 = 0x1b;
25const BEL: u8 = 0x07;
26/// The longest an OSC answer's body runs: `rgb:ffff/ffff/ffff` is 18 bytes.
27const OSC_BODY: u16 = 64;
28/// The longest a graphics answer's body runs, as an error that names a file.
29const APC_BODY: u16 = 1024;
30/// The most parameter bytes an answer's CSI has.
31const CSI_LONG: u8 = 48;
32/// How the answers past ESC begin: the background's, `ESC ] 11 ;`, and the graphics', `ESC _ G
33/// i =`, which always carries the id it was asked with.
34const OSC_START: &[u8] = b"11;";
35const APC_START: &[u8] = b"Gi=";
36
37/// How far into an answer the bytes so far are.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39enum State {
40    #[default]
41    Idle,
42    /// An ESC, which starts every answer.
43    Esc,
44    /// `ESC ]` and so many bytes of `11;`.
45    Osc(u8),
46    /// `ESC _` and so many bytes of `Gi=`.
47    Apc(u8),
48    /// `ESC [` and so many parameter bytes of an answer: device attributes (`? 62 ; 22 c`), a
49    /// mode's report (`? 1016 ; 2 $ y`), keyboard flags (`? 1 u`), or a size (`6 ; 37 ; 17 t`).
50    Csi {
51        private: bool,
52        dollar: bool,
53        len: u8,
54    },
55    /// The rest of a CSI whose start a wait read: up to its final byte, whatever it is.
56    CsiTail(u8),
57    /// An OSC's or APC's body, so long, up to `ESC \` or BEL, and whether an ESC just came.
58    Body { osc: bool, len: u16, esc: bool },
59}
60
61/// What a byte comes to.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63enum Step {
64    /// No answer under way: it's input.
65    Pass,
66    /// It may be an answer's start.
67    Hold,
68    /// It's an answer's, as is all that's held.
69    Drop,
70    /// What's held, and this, isn't an answer after all.
71    Miss,
72    /// The answer under way ended before this, which is taken again from the start.
73    Over,
74}
75
76impl State {
77    fn step(&mut self, byte: u8) -> Step {
78        let (next, step) = match *self {
79            State::Idle if byte == ESC => (State::Esc, Step::Hold),
80            State::Idle => (State::Idle, Step::Pass),
81            State::Esc => match byte {
82                b']' => (State::Osc(0), Step::Hold),
83                b'_' => (State::Apc(0), Step::Hold),
84                b'[' => (
85                    State::Csi {
86                        private: false,
87                        dollar: false,
88                        len: 0,
89                    },
90                    Step::Hold,
91                ),
92                _ => (State::Idle, Step::Miss),
93            },
94            State::Osc(n) => started(true, n, byte),
95            State::Apc(n) => started(false, n, byte),
96            State::Csi {
97                private,
98                dollar,
99                len,
100            } => csi(private, dollar, len, byte),
101            State::CsiTail(len) => match byte {
102                0x20..=0x3f if len < CSI_LONG => (State::CsiTail(len + 1), Step::Drop),
103                0x40..=0x7e => (State::Idle, Step::Drop),
104                _ => (State::Idle, Step::Over),
105            },
106            State::Body { esc: true, .. } if byte == b'\\' => (State::Idle, Step::Drop),
107            State::Body { esc: true, .. } => (State::Idle, Step::Over),
108            State::Body { osc, len, .. } => match byte {
109                ESC => (
110                    State::Body {
111                        osc,
112                        len,
113                        esc: true,
114                    },
115                    Step::Drop,
116                ),
117                BEL => (State::Idle, Step::Drop),
118                0x20..=0x7e if len < if osc { OSC_BODY } else { APC_BODY } => (
119                    State::Body {
120                        osc,
121                        len: len + 1,
122                        esc: false,
123                    },
124                    Step::Drop,
125                ),
126                _ => (State::Idle, Step::Over),
127            },
128        };
129        *self = next;
130        step
131    }
132
133    /// A unit that stands for no bytes, such as a click or a focus change: never an answer's.
134    fn interrupt(&mut self) -> Step {
135        let step = match self {
136            State::Idle => Step::Pass,
137            State::Body { .. } | State::CsiTail(_) => Step::Over,
138            _ => Step::Miss,
139        };
140        *self = State::Idle;
141        step
142    }
143}
144
145/// The next byte of an OSC's or APC's start: once it's all there, it's an answer's body.
146fn started(osc: bool, n: u8, byte: u8) -> (State, Step) {
147    let start = if osc { OSC_START } else { APC_START };
148    let at = usize::from(n);
149    if start.get(at) != Some(&byte) {
150        (State::Idle, Step::Miss)
151    } else if at + 1 == start.len() {
152        (
153            State::Body {
154                osc,
155                len: 0,
156                esc: false,
157            },
158            Step::Drop,
159        )
160    } else if osc {
161        (State::Osc(n + 1), Step::Hold)
162    } else {
163        (State::Apc(n + 1), Step::Hold)
164    }
165}
166
167/// The next byte of a CSI that may be an answer, held until its final byte says it is one.
168fn csi(private: bool, dollar: bool, len: u8, byte: u8) -> (State, Step) {
169    let more = |private, dollar| {
170        (
171            State::Csi {
172                private,
173                dollar,
174                len: len + 1,
175            },
176            Step::Hold,
177        )
178    };
179    let done = (State::Idle, Step::Drop);
180    match byte {
181        _ if len >= CSI_LONG => (State::Idle, Step::Miss),
182        b'?' if len == 0 => more(true, false),
183        b'0'..=b'9' if !dollar => more(private, false),
184        b';' if len > 0 && !dollar => more(private, false),
185        b'$' if private && len > 1 && !dollar => more(true, true),
186        b'y' if dollar => done,
187        b'c' | b'u' if private && len > 1 && !dollar => done,
188        b't' if !private && len > 0 && !dollar => done,
189        _ => (State::Idle, Step::Miss),
190    }
191}
192
193/// Drops the terminal's answers from what's read. A unit is what's read at once (a key event
194/// for the loop, a byte in a test) with the bytes it stands for: Alt+] is `ESC ]`, Ctrl+G is
195/// BEL. Units that stand for none, such as clicks, end any answer under way.
196pub struct Replies<T> {
197    state: State,
198    /// Units held while they may start an answer, with their bytes.
199    held: Vec<(T, Option<Vec<u8>>)>,
200    /// The answer under way started in a wait, which read its start: nothing of it is held to
201    /// give back if it turns out not to be one.
202    seeded: bool,
203    /// Until when answers may still come, after a wait that ran out.
204    owed: Option<Instant>,
205    /// The background's answer read so far, from its start.
206    colour: Option<Vec<u8>>,
207    /// The last background answer read whole, as `rgb:…`.
208    background: Option<Vec<u8>>,
209}
210
211impl<T> Default for Replies<T> {
212    fn default() -> Self {
213        Self {
214            state: State::Idle,
215            held: Vec::new(),
216            seeded: false,
217            owed: None,
218            colour: None,
219            background: None,
220        }
221    }
222}
223
224impl<T> Replies<T> {
225    /// Takes one unit, and gives back those that are input, in order: none while it may
226    /// still be an answer's start, and what was held with it once it isn't.
227    pub fn take(&mut self, unit: T, bytes: Option<&[u8]>) -> Vec<T> {
228        let mut out = Vec::new();
229        let mut queue = VecDeque::from([(unit, bytes.map(<[u8]>::to_vec))]);
230        while let Some((unit, bytes)) = queue.pop_front() {
231            let step = match &bytes {
232                Some(bytes) => self.feed(bytes),
233                None => {
234                    self.colour = None;
235                    self.state.interrupt()
236                }
237            };
238            match step {
239                Step::Pass => out.push(unit),
240                Step::Hold => self.held.push((unit, bytes)),
241                Step::Drop => {
242                    self.held.clear();
243                    if self.state == State::Idle {
244                        self.seeded = false;
245                    }
246                }
247                Step::Miss => {
248                    let mut again: VecDeque<_> = std::mem::take(&mut self.held).into();
249                    again.push_back((unit, bytes));
250                    // The first can't start an answer; what came after it is looked at again.
251                    // Where the start was read in a wait, none of what's held was the answer's.
252                    if !std::mem::take(&mut self.seeded) {
253                        out.extend(again.pop_front().map(|(unit, _)| unit));
254                    }
255                    while let Some(unit) = again.pop_back() {
256                        queue.push_front(unit);
257                    }
258                }
259                Step::Over => {
260                    self.seeded = false;
261                    queue.push_front((unit, bytes));
262                }
263            }
264        }
265        out
266    }
267
268    fn feed(&mut self, bytes: &[u8]) -> Step {
269        let mut step = Step::Pass;
270        for &byte in bytes {
271            let before = self.state;
272            step = self.state.step(byte);
273            match (before, self.state, step) {
274                (State::Osc(_), State::Body { .. }, _) => self.colour = Some(Vec::new()),
275                (State::Body { osc: true, .. }, State::Body { esc: false, .. }, Step::Drop) => {
276                    if let Some(colour) = &mut self.colour {
277                        colour.push(byte);
278                    }
279                }
280                (State::Body { osc: true, .. }, State::Idle, Step::Drop) => {
281                    self.background = self.colour.take().or(self.background.take());
282                }
283                (_, _, Step::Miss | Step::Over) => self.colour = None,
284                _ => {}
285            }
286            if matches!(step, Step::Miss | Step::Over) {
287                break;
288            }
289        }
290        step
291    }
292
293    /// No more input came: what's held wasn't an answer's start after all, and goes on as it
294    /// was. Not where a wait read the start: the rest of that answer is still to come.
295    pub fn release(&mut self) -> Vec<T> {
296        if self.seeded || self.held.is_empty() {
297            return Vec::new();
298        }
299        self.state = State::Idle;
300        self.held.drain(..).map(|(unit, _)| unit).collect()
301    }
302
303    /// Whether something is held that, with answers owed, may be an answer's start, so more is
304    /// worth waiting a moment for before what's held is given back.
305    pub fn waiting(&self, now: Instant) -> bool {
306        self.holding() && self.owed.is_some_and(|until| now < until)
307    }
308
309    /// Whether anything is held, owed or not.
310    pub fn holding(&self) -> bool {
311        !self.held.is_empty()
312    }
313
314    /// Takes what a wait left owing: answers that may still come, and how far into one it
315    /// read, so the rest of that one is dropped too.
316    pub fn owe(&mut self, owed: Owed) {
317        self.owed = Some(self.owed.map_or(owed.until, |was| was.max(owed.until)));
318        if let Some(seed) = owed.seed
319            && self.state == State::Idle
320            && self.held.is_empty()
321        {
322            self.state = seed;
323            self.seeded = true;
324        }
325    }
326
327    /// The background colour the last answer read whole said, as `rgb:…`, once.
328    pub fn take_background(&mut self) -> Option<Vec<u8>> {
329        self.background.take()
330    }
331}
332
333/// What a wait left owing: its answers may still come, and it may have read partway into one.
334#[derive(Clone, Copy, Debug)]
335pub struct Owed {
336    seed: Option<State>,
337    until: Instant,
338}
339
340/// What the waits have left owing, until the loop takes it, and until when answers may come.
341struct Owing {
342    until: Option<Instant>,
343    fresh: Option<Owed>,
344}
345
346static OWING: Mutex<Owing> = Mutex::new(Owing {
347    until: None,
348    fresh: None,
349});
350
351/// What the questions' waits have left owing since this was last asked, if anything.
352pub fn owed() -> Option<Owed> {
353    OWING.lock().ok()?.fresh.take()
354}
355
356/// Whether an earlier question's answers may still come, so a wait now may read them.
357#[cfg(unix)]
358pub(crate) fn owing(now: Instant) -> bool {
359    OWING
360        .lock()
361        .is_ok_and(|owing| owing.until.is_some_and(|until| now < until))
362}
363
364/// A wait that ran out, or that may have read an earlier question's answers for its own:
365/// answers may still come, and `read` says how far into one it got.
366#[cfg(unix)]
367pub(crate) fn owe(read: &Read) {
368    let Ok(mut owing) = OWING.lock() else {
369        return;
370    };
371    let until = Instant::now() + LATE;
372    owing.until = Some(until);
373    owing.fresh = Some(Owed {
374        seed: read.seed(),
375        until,
376    });
377}
378
379/// What a wait read, followed byte by byte, to know whether it ended partway into an answer.
380#[cfg(any(unix, test))]
381#[derive(Default)]
382pub(crate) struct Read(Replies<()>);
383
384#[cfg(any(unix, test))]
385impl Read {
386    pub(crate) fn feed(&mut self, bytes: &[u8]) {
387        for &byte in bytes {
388            self.0.take((), Some(&[byte]));
389        }
390    }
391
392    /// Where the bytes read so far end: inside an answer, and how far. A CSI read in a wait is
393    /// one, whatever it is, so its rest goes up to its final byte.
394    fn seed(&self) -> Option<State> {
395        match self.0.state {
396            State::Idle => None,
397            State::Csi { len, .. } => Some(State::CsiTail(len)),
398            state => Some(state),
399        }
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    /// Filters a byte stream read in `reads`, each byte a unit, as the loop would: nothing
408    /// given back between reads, which come before the loop's patience runs out.
409    fn filtered(replies: &mut Replies<u8>, reads: &[&[u8]]) -> Vec<u8> {
410        let mut out = Vec::new();
411        for read in reads {
412            for &byte in *read {
413                out.extend(replies.take(byte, Some(&[byte])));
414            }
415        }
416        out
417    }
418
419    /// The same once no more comes.
420    fn whole(reads: &[&[u8]]) -> Vec<u8> {
421        let mut replies = Replies::default();
422        let mut out = filtered(&mut replies, reads);
423        out.extend(replies.release());
424        out
425    }
426
427    /// Every answer Cellix's questions can bring, ended each way it can end, as terminals,
428    /// tmux and Zellij send them.
429    const ANSWERS: [&[u8]; 12] = [
430        b"\x1b]11;rgb:1010/1111/1414\x1b\\",
431        b"\x1b]11;rgb:ffff/fefe/fdfd\x07",
432        b"\x1b]11;rgba:0000/0000/0000/ffff\x1b\\",
433        b"\x1b[?62;22c",
434        b"\x1b[?1;2c",
435        b"\x1b[6;37;17t",
436        b"\x1b[4;888;1394t",
437        b"\x1b[?1016;2$y",
438        b"\x1b[?5522;0$y",
439        b"\x1b[?1u",
440        b"\x1b_Gi=31;OK\x1b\\",
441        b"\x1b_Gi=32;EINVAL:refused, no file at /tmp/x\x1b\\",
442    ];
443
444    #[test]
445    fn every_answer_is_dropped_and_the_keys_round_it_kept() {
446        for answer in ANSWERS {
447            let stream = [b"ab".as_slice(), answer, b"cd"].concat();
448            assert_eq!(
449                whole(&[&stream]),
450                b"abcd",
451                "{:?}",
452                String::from_utf8_lossy(answer)
453            );
454        }
455        // All of them at once, as a slow terminal sends the lot.
456        let all = ANSWERS.concat();
457        assert_eq!(whole(&[&all, b"x"]), b"x");
458    }
459
460    /// An answer can come in pieces, a read each, split anywhere: it's dropped all the same.
461    #[test]
462    fn an_answer_in_pieces_across_reads_is_dropped() {
463        for answer in ANSWERS {
464            let stream = [answer, b"x"].concat();
465            for cut in 1..stream.len() {
466                let (first, second) = stream.split_at(cut);
467                assert_eq!(
468                    whole(&[first, second]),
469                    b"x",
470                    "{:?} cut at {cut}",
471                    String::from_utf8_lossy(answer)
472                );
473            }
474            // A byte a read.
475            let bytes: Vec<&[u8]> = stream.chunks(1).collect();
476            assert_eq!(whole(&bytes), b"x", "{:?}", String::from_utf8_lossy(answer));
477        }
478    }
479
480    /// A wait that ran out partway through an answer says how far it read, and the rest that
481    /// comes later is dropped: from every point in every answer.
482    #[test]
483    fn the_rest_of_an_answer_a_wait_began_is_dropped() {
484        for answer in ANSWERS {
485            for cut in 1..answer.len() {
486                let (started, rest) = answer.split_at(cut);
487                let mut read = Read::default();
488                read.feed(started);
489                let mut replies = Replies::default();
490                replies.owe(Owed {
491                    seed: read.seed(),
492                    until: Instant::now() + LATE,
493                });
494                let mut out = filtered(&mut replies, &[rest, b"x"]);
495                out.extend(replies.release());
496                assert_eq!(
497                    out,
498                    b"x",
499                    "{:?} read up to {cut}",
500                    String::from_utf8_lossy(answer)
501                );
502            }
503        }
504        // A wait that ended between answers leaves nothing to drop.
505        let mut read = Read::default();
506        read.feed(b"\x1b[?62c");
507        assert_eq!(read.seed(), None);
508    }
509
510    /// What a person types is never an answer: Alt+] or Esc alone, text with `rgb:` in it,
511    /// and keys that start as an answer would and then don't go on as one.
512    #[test]
513    fn typing_that_looks_like_an_answer_still_arrives() {
514        for typed in [
515            b"\x1b]".as_slice(),
516            b"\x1b",
517            b"\x1b_",
518            b"11;rgb:1010/1111/1414",
519            b"colour = rgb:ff/ff/ff;",
520            b"\x1b]5522;type=read\x1b\\",
521            b"\x1b]1x",
522            b"\x1b_Gx",
523            b"\x1b[?62;22x",
524            b"\x1b[6;37;17A",
525            b"\x1b[?1016$c",
526            b"\x1bx\x1b\x1b]q",
527            b"\x1b\\",
528        ] {
529            assert_eq!(
530                whole(&[typed]),
531                typed,
532                "{:?}",
533                String::from_utf8_lossy(typed)
534            );
535        }
536        // Held while it may be an answer's start, and given back once no more comes.
537        let mut replies = Replies::default();
538        assert!(filtered(&mut replies, &[b"\x1b]1"]).is_empty());
539        assert_eq!(replies.release(), b"\x1b]1");
540        // An answer right after a key that looked like one's start: the key, then nothing.
541        assert_eq!(whole(&[b"\x1b\x1b]11;rgb:1/1/1\x07"]), b"\x1b");
542    }
543
544    /// Held starts wait a moment for their rest only while answers are owed.
545    #[test]
546    fn a_held_start_waits_only_while_answers_are_owed() {
547        let now = Instant::now();
548        let mut replies = Replies::default();
549        assert!(filtered(&mut replies, &[b"\x1b"]).is_empty());
550        assert!(!replies.waiting(now), "nothing owed");
551        replies.owe(Owed {
552            seed: None,
553            until: now + LATE,
554        });
555        assert!(replies.waiting(now));
556        assert!(!replies.waiting(now + LATE));
557        assert_eq!(replies.release(), b"\x1b");
558        assert!(!replies.waiting(now), "nothing held");
559    }
560
561    /// The colour a late answer says is kept for the loop, the latest whole one.
562    #[test]
563    fn a_late_background_answer_says_its_colour() {
564        let mut replies = Replies::default();
565        let out = filtered(
566            &mut replies,
567            &[b"\x1b]11;rgb:1010/1111/1414\x1b\\a\x1b]11;rgb:eeee/eeee/eeee\x07"],
568        );
569        assert_eq!(out, b"a");
570        assert_eq!(
571            replies.take_background().as_deref(),
572            Some(b"rgb:eeee/eeee/eeee".as_slice())
573        );
574        assert_eq!(replies.take_background(), None);
575        // One cut short says nothing.
576        filtered(&mut replies, &[b"\x1b]11;rgb:1010"]);
577        replies.take(0, None);
578        assert_eq!(replies.take_background(), None);
579    }
580}