paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
//! vte Perform bridge: feed ANSI/VT bytes, mutate a TermGrid.
//!
//! Implements the `vte` crate's `Perform` trait over a TermGrid. The
//! parser is created per feed batch; SGR state (colors/attributes)
//! carries across `print` calls within the batch.

use super::grid::TermGrid;
use ratatui::style::{Color, Modifier, Style};
use vte::{Params, Perform};

/// Feeds bytes into a grid via vte's state machine.
pub struct TermParser<'a> {
    grid: &'a mut TermGrid,
    sgr_style: Style,
}

impl<'a> TermParser<'a> {
    pub fn new(grid: &'a mut TermGrid) -> Self {
        TermParser {
            grid,
            sgr_style: Style::default(),
        }
    }

    /// Feed a byte batch through the internal vte state machine.
    pub fn feed(&mut self, bytes: &[u8]) {
        let mut parser = vte::Parser::new();
        parser.advance(&mut *self, bytes);
    }
}

/// First parameter, or `default` when absent/empty.
fn param_or(params: &Params, idx: usize, default: u16) -> u16 {
    params
        .iter()
        .nth(idx)
        .and_then(|p| p.first())
        .copied()
        .filter(|p| *p != 0)
        .unwrap_or(default)
}

impl Perform for TermParser<'_> {
    fn print(&mut self, ch: char) {
        self.grid.put(ch, self.sgr_style);
    }

    fn execute(&mut self, byte: u8) {
        match byte {
            b'\r' => self.grid.carriage_return(),
            b'\n' | 0x0b | 0x0c => self.grid.newline(),
            b'\t' => self.grid.tab(),
            0x08 => self.grid.backspace(),
            _ => {}
        }
    }

    fn csi_dispatch(
        &mut self,
        params: &Params,
        _intermediates: &[u8],
        _ignore: bool,
        action: char,
    ) {
        match action {
            'A' => self.grid.move_cursor(-(param_or(params, 0, 1) as i64), 0),
            'B' => self.grid.move_cursor(param_or(params, 0, 1) as i64, 0),
            'C' => self.grid.move_cursor(0, param_or(params, 0, 1) as i64),
            'D' => self.grid.move_cursor(0, -(param_or(params, 0, 1) as i64)),
            'J' => self.grid.erase_in_display(param_or(params, 0, 0)),
            'K' => self.grid.erase_in_line(param_or(params, 0, 0)),
            'H' | 'f' => {
                let row = param_or(params, 0, 1).saturating_sub(1);
                let col = param_or(params, 1, 1).saturating_sub(1);
                self.grid.move_to(row as usize, col as usize);
            }
            'm' => self.apply_sgr(params),
            _ => {}
        }
    }
}

impl TermParser<'_> {
    /// SGR (Select Graphic Rendition): colors, bold, reset.
    fn apply_sgr(&mut self, params: &Params) {
        if params.is_empty() {
            self.sgr_style = Style::default();
            return;
        }
        let mut it = params.iter();
        while let Some(sub) = it.next() {
            let code = sub.first().copied().unwrap_or(0);
            match code {
                0 => self.sgr_style = Style::default(),
                1 => self.sgr_style.add_modifier |= Modifier::BOLD,
                3 => self.sgr_style.add_modifier |= Modifier::ITALIC,
                4 => self.sgr_style.add_modifier |= Modifier::UNDERLINED,
                22 => self.sgr_style.add_modifier &= !Modifier::BOLD,
                23 => self.sgr_style.add_modifier &= !Modifier::ITALIC,
                24 => self.sgr_style.add_modifier &= !Modifier::UNDERLINED,
                30..=37 => {
                    self.sgr_style.fg = Some(sgr_color(code - 30));
                }
                39 => self.sgr_style.fg = None,
                40..=47 => {
                    self.sgr_style.bg = Some(sgr_color(code - 40));
                }
                49 => self.sgr_style.bg = None,
                90..=97 => {
                    self.sgr_style.fg = Some(bright_sgr_color(code - 90));
                }
                100..=107 => {
                    self.sgr_style.bg = Some(bright_sgr_color(code - 100));
                }
                38 | 48 => {
                    // Extended color: 38;5;n (256) or 38;2;r;g;b (RGB).
                    // `;`-separated params arrive as separate iterator items;
                    // subparams (`:`) arrive inside `sub`.
                    let target_fg = code == 38;
                    let (consumed, color) = extended_color(&mut it, sub);
                    // Skip any params extended_color already consumed so they
                    // are not re-interpreted as SGR codes.
                    for _ in 1..consumed {
                        it.next();
                    }
                    if let Some(c) = color {
                        if target_fg {
                            self.sgr_style.fg = Some(c);
                        } else {
                            self.sgr_style.bg = Some(c);
                        }
                    }
                }
                _ => {}
            }
        }
    }
}

/// Standard SGR palette 0-7.
fn sgr_color(i: u16) -> Color {
    match i {
        0 => Color::Black,
        1 => Color::Red,
        2 => Color::Green,
        3 => Color::Yellow,
        4 => Color::Blue,
        5 => Color::Magenta,
        6 => Color::Cyan,
        _ => Color::Gray,
    }
}

/// Bright SGR palette 8-15.
fn bright_sgr_color(i: u16) -> Color {
    match i {
        0 => Color::DarkGray,
        1 => Color::LightRed,
        2 => Color::LightGreen,
        3 => Color::LightYellow,
        4 => Color::LightBlue,
        5 => Color::LightMagenta,
        6 => Color::LightCyan,
        _ => Color::White,
    }
}

/// Consume a 38/5/n or 38/2/r/g/b sequence. Returns
/// (params_consumed_after_first, color). Handles both `;`-separated
/// params (separate iterator items) and `:`-separated subparams
/// (packed into `sub`).
fn extended_color<'p, I>(it: &mut I, sub: &'p [u16]) -> (usize, Option<Color>)
where
    I: Iterator<Item = &'p [u16]>,
{
    // Subparam form: 38:5:n or 38:2:r:g:b all inside `sub`.
    match sub.get(1).copied() {
        Some(5) => {
            return (0, sub.get(2).copied().map(|n| Color::Indexed(n as u8)));
        }
        Some(2) => {
            if let (Some(r), Some(g), Some(b)) = (
                sub.get(2).copied(),
                sub.get(3).copied(),
                sub.get(4).copied(),
            ) {
                return (0, Some(Color::Rgb(r as u8, g as u8, b as u8)));
            }
            return (0, None);
        }
        _ => {}
    }
    // `;`-separated form: the mode (5 or 2) is the NEXT param.
    match it.next().and_then(|p| p.first().copied()) {
        Some(5) => match it.next().and_then(|p| p.first().copied()) {
            Some(n) => (2, Some(Color::Indexed(n as u8))),
            None => (1, None),
        },
        Some(2) => {
            let r = it.next().and_then(|p| p.first().copied());
            let g = it.next().and_then(|p| p.first().copied());
            let b = it.next().and_then(|p| p.first().copied());
            match (r, g, b) {
                (Some(r), Some(g), Some(b)) => (4, Some(Color::Rgb(r as u8, g as u8, b as u8))),
                _ => (4, None),
            }
        }
        _ => (0, None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn feed(grid: &mut TermGrid, s: &str) {
        TermParser::new(grid).feed(s.as_bytes());
    }

    fn fg(grid: &TermGrid, row: usize, col: usize) -> Option<Color> {
        grid.cell(row, col).and_then(|c| c.style.fg)
    }

    #[test]
    fn plain_text_lands_in_grid() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "hi");
        assert_eq!(
            g.text_projection(),
            vec!["hi".to_string(), String::new(), String::new()]
        );
        assert_eq!(g.cursor(), (0, 2));
    }

    #[test]
    fn cr_lf_combo_moves_to_next_line_start() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "one\r\ntwo");
        assert_eq!(g.text_projection()[0], "one");
        assert_eq!(g.text_projection()[1], "two");
        assert_eq!(g.cursor(), (1, 3));
    }

    #[test]
    fn sgr_red_then_reset() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "\x1b[31mred\x1b[0mplain");
        assert_eq!(fg(&g, 0, 0), Some(Color::Red));
        assert_eq!(fg(&g, 0, 2), Some(Color::Red));
        assert_eq!(fg(&g, 0, 3), None, "reset must clear fg");
        assert_eq!(fg(&g, 0, 7), None);
    }

    #[test]
    fn sgr_bold_underline() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "\x1b[1;4mbu\x1b[m");
        assert!(g
            .cell(0, 0)
            .unwrap()
            .style
            .add_modifier
            .contains(Modifier::BOLD));
        assert!(g
            .cell(0, 0)
            .unwrap()
            .style
            .add_modifier
            .contains(Modifier::UNDERLINED));
    }

    #[test]
    fn sgr_256_color() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "\x1b[38;5;208mx");
        assert_eq!(fg(&g, 0, 0), Some(Color::Indexed(208)));
    }

    #[test]
    fn sgr_rgb_color() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "\x1b[38;2;10;20;30mx");
        assert_eq!(fg(&g, 0, 0), Some(Color::Rgb(10, 20, 30)));
    }

    #[test]
    fn sgr_bg_color() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "\x1b[41mX");
        assert_eq!(g.cell(0, 0).unwrap().style.bg, Some(Color::Red));
    }

    #[test]
    fn cursor_movement_cub_cuf() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "abc\x1b[2D\x1b[DX");
        // 'abc' -> cursor col 3; ESC[2D -> col 1; ESC[D (default 1) -> col 0; X overwrites 'a'
        assert_eq!(g.text_projection()[0], "Xbc");
    }

    #[test]
    fn cursor_movement_cuu_cud() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "a\r\nb\r\n\x1b[AX");
        // rows: 'a','b'; the trailing \r\n put the cursor on row 2 col 0;
        // ESC[A moves up to (1,0); X overwrites 'b'.
        assert_eq!(g.text_projection()[0], "a");
        assert_eq!(g.text_projection()[1], "X");
    }

    #[test]
    fn cursor_home_cup() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "hello\r\nworld\x1b[2;3H*");
        assert_eq!(g.text_projection()[1], "wo*ld");
    }

    #[test]
    fn erase_in_line_el() {
        let mut g = TermGrid::new(10, 1);
        feed(&mut g, "0123456789\x1b[1;5H\x1b[K");
        // cursor to (0,4); EL default 0 clears to end of line
        assert_eq!(g.text_projection()[0], "0123");
    }

    #[test]
    fn clear_screen_ed() {
        let mut g = TermGrid::new(10, 3);
        feed(&mut g, "one\r\ntwo\r\nthree\x1b[H\x1b[2Jx");
        assert_eq!(
            g.text_projection(),
            vec!["x".to_string(), String::new(), String::new()]
        );
    }

    #[test]
    fn backspace_and_tab() {
        let mut g = TermGrid::new(20, 2);
        // BS moves the cursor left; it does not erase. "ab" + BS BS + "c"
        // overwrites 'a' -> "cb".
        feed(&mut g, "ab\x08\x08c");
        assert_eq!(g.text_projection()[0], "cb");
        feed(&mut g, "\t");
        assert_eq!(g.cursor(), (0, 8));
    }

    #[test]
    fn feed_is_batchable_sgr_carries() {
        let mut g = TermGrid::new(10, 3);
        let mut p = TermParser::new(&mut g);
        p.feed(b"\x1b[32m");
        p.feed(b"green");
        assert_eq!(fg(&g, 0, 0), Some(Color::Green));
        assert_eq!(fg(&g, 0, 4), Some(Color::Green));
    }
}