Skip to content

Visual Studio Code, rebuilt in Rust

Rust
14.7 KB
Raw Blame
//! @xterm/addon-serialize `StringSerializeHandler`: the normal buffer as the escape sequences that redraw it, for
//! ptyService.ts `serializeNormalBuffer` (`excludeModes`, `excludeAltBuffer`).
use ghostty_vt::{Cell, Color, Column, Flags, Line, Point};

use super::TerminalInstance;

const UNDERLINES: Flags = Flags::ALL_UNDERLINES;

impl TerminalInstance {
    /// `serialize({ scrollback })` of the normal buffer: the last `scrollback` lines over the screen, then the cursor.
    // Ghostty's points address the active screen only, so a terminal on the alternate screen serializes that one.
    pub fn serialize_buffer(&self, scrollback: usize) -> String {
        let history = self.term.history_size();
        let rows = self.term.screen_lines();
        let total = history + rows;
        let first_row = total - (scrollback + rows).min(total);
        let mut handler = Handler::new(self, first_row);
        for row in first_row..total {
            handler.content_end = handler.content_end(row);
            for column in 0..self.term.columns() {
                handler.next_cell(row, column);
            }
            handler.row_end(row, row == total - 1);
        }
        handler.finish()
    }
}

struct Handler<'a> {
    instance: &'a TerminalInstance,
    rows: Vec<String>,
    separators: Vec<String>,
    current: String,
    null_cell_count: usize,
    /// The column after the row's last non-blank cell: only the blanks past it are xterm's empty cells.
    content_end: usize,
    cursor_style: Cell,
    background: Cell,
    cursor_style_at: (usize, usize),
    first_row: usize,
    last_cursor: (usize, usize),
    last_content_cursor: (usize, usize),
}

impl<'a> Handler<'a> {
    fn new(instance: &'a TerminalInstance, first_row: usize) -> Self {
        Handler {
            instance,
            rows: Vec::new(),
            separators: Vec::new(),
            current: String::new(),
            null_cell_count: 0,
            content_end: 0,
            cursor_style: Cell::default(),
            background: Cell::default(),
            cursor_style_at: (first_row, 0),
            first_row,
            last_cursor: (first_row, 0),
            last_content_cursor: (first_row, 0),
        }
    }

    /// Buffer row `row` counts from the top of the scrollback, as xterm's `buffer.getLine`.
    fn cell(&self, row: usize, column: usize) -> Cell {
        let line = row as i32 - self.instance.term.history_size() as i32;
        self.instance.term.cell(Point::new(Line(line), Column(column)))
    }

    fn content_end(&self, row: usize) -> usize {
        (0..self.instance.term.columns()).rev().find(|&column| !is_blank(&self.cell(row, column))).map_or(0, |column| column + 1)
    }

    fn next_cell(&mut self, row: usize, column: usize) {
        let cell = self.cell(row, column);
        if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
            return;
        }
        let empty = column >= self.content_end;
        let sgr = diff_style(&cell, &self.cursor_style);
        let style_changed = if empty { cell.bg != self.cursor_style.bg } else { !sgr.is_empty() };
        if style_changed {
            if self.null_cell_count > 0 {
                if self.cursor_style.bg != self.background.bg {
                    self.current += &format!("\x1b[{}X", self.null_cell_count);
                }
                self.current += &format!("\x1b[{}C", self.null_cell_count);
                self.null_cell_count = 0;
            }
            self.last_content_cursor = (row, column);
            self.last_cursor = (row, column);
            self.current += &format!("\x1b[{}m", sgr.join(";"));
            self.cursor_style = cell.clone();
            self.cursor_style_at = (row, column);
        }
        let width = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 };
        if empty {
            self.null_cell_count += width;
            return;
        }
        if self.null_cell_count > 0 {
            if self.cursor_style.bg != self.background.bg {
                self.current += &format!("\x1b[{}X", self.null_cell_count);
            }
            self.current += &format!("\x1b[{}C", self.null_cell_count);
            self.null_cell_count = 0;
        }
        self.current.push(cell.c);
        for c in cell.zerowidth().into_iter().flatten() {
            self.current.push(*c);
        }
        self.last_content_cursor = (row, column + width);
        self.last_cursor = (row, column + width);
    }

    fn row_end(&mut self, row: usize, is_last_row: bool) {
        if self.null_cell_count > 0 && self.cursor_style.bg != self.background.bg {
            self.current += &format!("\x1b[{}X", self.null_cell_count);
        }
        let mut separator = String::new();
        if !is_last_row {
            // Enable BCE
            if row - self.first_row >= self.instance.term.screen_lines() {
                self.background = self.cell(self.cursor_style_at.0, self.cursor_style_at.1).clone();
            }
            let cols = self.instance.term.columns();
            let last = self.cell(row, cols - 1);
            if !last.flags.contains(Flags::WRAPLINE) {
                separator = "\r\n".into();
                self.last_cursor = (row + 1, 0);
            } else if !self.wrap_is_valid(row) {
                // Force the wrap: enough characters to overflow, then erase the next line's head.
                separator = "-".repeat(self.null_cell_count + 1) + "\x1b[1D\x1b[1X";
                if self.null_cell_count > 0 {
                    let content_length = cols - self.null_cell_count;
                    separator += "\x1b[A";
                    if content_length > 0 {
                        separator += &format!("\x1b[{content_length}C");
                    }
                    separator += &format!("\x1b[{}X", self.null_cell_count);
                    if content_length > 0 {
                        separator += &format!("\x1b[{content_length}D");
                    }
                    separator += "\x1b[B";
                }
                self.last_content_cursor = (row + 1, 0);
                self.last_cursor = (row + 1, 0);
            }
        }
        self.rows.push(std::mem::take(&mut self.current));
        self.separators.push(separator);
        self.null_cell_count = 0;
    }

    /// Whether printing the row overflows into the next one by itself: its last cell (or the two before a wide
    /// first character) holds a character with the next row's first background.
    fn wrap_is_valid(&self, row: usize) -> bool {
        let cols = self.instance.term.columns();
        let last = self.cell(row, cols - 1);
        let next_first = self.cell(row + 1, 0);
        let next_wide = next_first.flags.contains(Flags::WIDE_CHAR);
        let allowed_nulls = if next_wide { 1 } else { 0 };
        if self.content_end(row + 1) == 0 || self.null_cell_count > allowed_nulls {
            return false;
        }
        let has_char = |cell: &Cell| !is_blank(cell) || cell.flags.contains(Flags::WIDE_CHAR_SPACER);
        if has_char(&last) && last.bg == next_first.bg {
            return true;
        }
        let second_last = self.cell(row, cols.saturating_sub(2));
        next_wide && has_char(&second_last) && last.bg == next_first.bg && second_last.bg == next_first.bg
    }

    fn finish(mut self) -> String {
        let term = &self.instance.term;
        let total = term.history_size() + term.screen_lines();
        let mut row_end = self.rows.len();
        // Without scrollback the cursor fixup lands on the last content.
        if total - self.first_row <= term.screen_lines() {
            row_end = self.last_content_cursor.0 + 1 - self.first_row;
            self.last_cursor = self.last_content_cursor;
        }
        let mut content = String::new();
        for index in 0..row_end {
            content += &self.rows[index];
            if index + 1 < row_end {
                content += &self.separators[index];
            }
        }
        let cursor = term.cursor().point;
        let real_row = (term.history_size() as i32 + cursor.line.0) as i64;
        let real_column = cursor.column.0 as i64;
        let down = real_row - self.last_cursor.0 as i64;
        let right = real_column - self.last_cursor.1 as i64;
        if down > 0 {
            content += &format!("\x1b[{down}B");
        } else if down < 0 {
            content += &format!("\x1b[{}A", -down);
        }
        if right > 0 {
            content += &format!("\x1b[{right}C");
        } else if right < 0 {
            content += &format!("\x1b[{}D", -right);
        }
        let sgr = diff_style(&term.cursor_template(), &self.cursor_style);
        if !sgr.is_empty() {
            content += &format!("\x1b[{}m", sgr.join(";"));
        }
        content
    }
}

/// Ghostty stores an erased cell and a typed space alike, so a blank is xterm's empty cell only past the row's content.
fn is_blank(cell: &Cell) -> bool {
    matches!(cell.c, ' ' | '\0') && cell.zerowidth().is_none()
}

fn is_default(cell: &Cell) -> bool {
    let style = cell.flags & !(Flags::WRAPLINE | Flags::WIDE_CHAR | Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER);
    cell.fg == Color::Foreground && cell.bg == Color::Background && style.is_empty() && cell.underline_color().is_none()
}

/// `_diffStyle`: the SGR parameters that turn `old`'s attributes into `cell`'s.
fn diff_style(cell: &Cell, old: &Cell) -> Vec<String> {
    let mut sgr = Vec::new();
    let flags_changed = (cell.flags ^ old.flags).intersects(Flags::INVERSE | Flags::BOLD | UNDERLINES | Flags::HIDDEN | Flags::ITALIC | Flags::DIM | Flags::STRIKEOUT) || (cell.flags.intersects(UNDERLINES) && cell.underline_color() != old.underline_color());
    if cell.fg == old.fg && cell.bg == old.bg && !flags_changed {
        return sgr;
    }
    if is_default(cell) {
        if !is_default(old) {
            sgr.push("0".into());
        }
        return sgr;
    }
    if cell.fg != old.fg {
        sgr.push(color_sgr(cell.fg, 30, 90, 38, 39));
    }
    if cell.bg != old.bg {
        sgr.push(color_sgr(cell.bg, 40, 100, 48, 49));
    }
    if flags_changed {
        let toggled = |flag: Flags| cell.flags.contains(flag) != old.flags.contains(flag);
        if toggled(Flags::INVERSE) {
            sgr.push(if cell.flags.contains(Flags::INVERSE) { "7" } else { "27" }.into());
        }
        if toggled(Flags::BOLD) {
            sgr.push(if cell.flags.contains(Flags::BOLD) { "1" } else { "22" }.into());
        }
        if (cell.flags & UNDERLINES) != (old.flags & UNDERLINES) || cell.underline_color() != old.underline_color() {
            let style = underline_style(cell.flags);
            match (style, cell.underline_color()) {
                (0, _) => sgr.push("24".into()),
                (1, None) => sgr.push("4".into()),
                (style, color) => {
                    sgr.push(format!("4:{style}"));
                    match color {
                        Some(Color::Spec(rgb)) => sgr.push(format!("58:2::{}:{}:{}", rgb.r, rgb.g, rgb.b)),
                        Some(Color::Indexed(index)) => sgr.push(format!("58:5:{index}")),
                        Some(Color::Foreground | Color::Background) | None => {}
                    }
                }
            }
        }
        if toggled(Flags::HIDDEN) {
            sgr.push(if cell.flags.contains(Flags::HIDDEN) { "8" } else { "28" }.into());
        }
        if toggled(Flags::ITALIC) {
            sgr.push(if cell.flags.contains(Flags::ITALIC) { "3" } else { "23" }.into());
        }
        if toggled(Flags::DIM) {
            sgr.push(if cell.flags.contains(Flags::DIM) { "2" } else { "22" }.into());
        }
        if toggled(Flags::STRIKEOUT) {
            sgr.push(if cell.flags.contains(Flags::STRIKEOUT) { "9" } else { "29" }.into());
        }
    }
    sgr
}

fn color_sgr(color: Color, normal: u8, bright: u8, extended: u8, default: u8) -> String {
    match color {
        Color::Spec(rgb) => format!("{extended};2;{};{};{}", rgb.r, rgb.g, rgb.b),
        Color::Indexed(index) if index >= 16 => format!("{extended};5;{index}"),
        Color::Indexed(index) => palette_sgr(index as usize, normal, bright),
        Color::Foreground | Color::Background => default.to_string(),
    }
}

fn palette_sgr(index: usize, normal: u8, bright: u8) -> String {
    if index & 8 != 0 { (bright as usize + (index & 7)).to_string() } else { (normal as usize + (index & 7)).to_string() }
}

/// UnderlineStyle: single 1, double 2, curly 3, dotted 4, dashed 5.
fn underline_style(flags: Flags) -> u8 {
    if flags.contains(Flags::UNDERLINE) {
        1
    } else if flags.contains(Flags::DOUBLE_UNDERLINE) {
        2
    } else if flags.contains(Flags::UNDERCURL) {
        3
    } else if flags.contains(Flags::DOTTED_UNDERLINE) {
        4
    } else if flags.contains(Flags::DASHED_UNDERLINE) {
        5
    } else {
        0
    }
}

#[cfg(test)]
mod tests {
    use ghostty_vt::Config;

    use super::super::{ShellLaunchConfig, TerminalInstance, colors};

    fn instance(cols: u16) -> (TerminalInstance, colors::TerminalColors) {
        let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let colors = colors::TerminalColors::new(&crate::theme::load_theme(&[themes], "Dark Modern").unwrap());
        let launch = ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), ..Default::default() };
        (TerminalInstance::new(1, launch, cols, 4, Config { scrolling_history: 100, ..Config::default() }).0, colors)
    }

    fn screen(instance: &TerminalInstance) -> Vec<String> {
        use ghostty_vt::{Column, Line, Point};
        (0..instance.term.screen_lines() as i32).map(|line| (0..instance.term.columns()).map(|column| instance.term.cell(Point::new(Line(line), Column(column))).c).collect::<String>().trim_end().to_owned()).collect()
    }

    #[test]
    fn rows_colors_and_the_cursor_serialize_to_the_sequences_that_redraw_them() {
        let (mut source, colors) = instance(10);
        source.process(b"$ echo a\r\n\x1b[31mred\x1b[0m  b\r\n$ ", &colors);
        let serialized = source.serialize_buffer(100);
        assert_eq!(serialized, "$ echo a\r\n\x1b[31mred\x1b[0m  b\r\n$\x1b[1C");
        let (mut revived, _) = instance(10);
        revived.process(serialized.as_bytes(), &colors);
        assert_eq!(screen(&revived), screen(&source));
        assert_eq!(revived.term.cursor().point, source.term.cursor().point);
    }

    #[test]
    fn a_wrapped_row_joins_the_next_without_a_line_break() {
        let (mut source, colors) = instance(5);
        source.process(b"0123456789ab\r\n$ ", &colors);
        let serialized = source.serialize_buffer(100);
        assert_eq!(serialized, "0123456789ab\r\n$\x1b[1C");
        let (mut revived, _) = instance(5);
        revived.process(serialized.as_bytes(), &colors);
        assert_eq!(screen(&revived), screen(&source));
    }
}