Skip to content

Visual Studio Code, rebuilt in Rust

Rust
29.9 KB
Raw Blame
//! libghostty-vt, through the libghostty-vt crate's safe bindings, as the terminal screen the integrated terminal
//! draws, in the shape the port used from alacritty_terminal (lines relative to the active area's top, negative into
//! the scrollback).

#![forbid(unsafe_code)]

mod selection;

use std::cell::RefCell;
use std::ops::{Add, AddAssign, Index, Sub, SubAssign};

use libghostty_vt::effect::{self, ConformanceLevel, DeviceAttributeFeature, DeviceAttributes, DeviceType, PrimaryDeviceAttributes, SecondaryDeviceAttributes, TertiaryDeviceAttributes};
use libghostty_vt::grid_ref::{GridRef, TrackedGridRef};
use libghostty_vt::mode::{Kind, Mode};
use libghostty_vt::point::{Coordinate, Point as GhosttyPoint, Space};
use libghostty_vt::render::{CellIterator, RowIterator};
use libghostty_vt::report::SizeReportSize;
use libghostty_vt::screen::{self, CellContentTag, CellWide, Screen, cell};
use libghostty_vt::style::{Style, StyleColor, Underline};
use libghostty_vt::terminal::{CursorStyle as GhosttyCursorStyle, ScrollViewport};
use libghostty_vt::{RenderState, Terminal};

pub use libghostty_vt::color::Rgb;
pub use selection::{SelectionRange, SelectionType};

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Line(pub i32);

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Column(pub usize);

/// A cell: `line` 0 is the active area's first line, negative lines are in the scrollback.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Point {
    pub line: Line,
    pub column: Column,
}

impl Point {
    pub fn new(line: Line, column: Column) -> Point {
        Point { line, column }
    }
}

impl Add<i32> for Line {
    type Output = Line;
    fn add(self, rhs: i32) -> Line {
        Line(self.0 + rhs)
    }
}

impl Sub<i32> for Line {
    type Output = Line;
    fn sub(self, rhs: i32) -> Line {
        Line(self.0 - rhs)
    }
}

impl AddAssign<i32> for Line {
    fn add_assign(&mut self, rhs: i32) {
        self.0 += rhs;
    }
}

impl SubAssign<i32> for Line {
    fn sub_assign(&mut self, rhs: i32) {
        self.0 -= rhs;
    }
}

impl Add<usize> for Column {
    type Output = Column;
    fn add(self, rhs: usize) -> Column {
        Column(self.0 + rhs)
    }
}

impl Sub<usize> for Column {
    type Output = Column;
    fn sub(self, rhs: usize) -> Column {
        Column(self.0 - rhs)
    }
}

impl AddAssign<usize> for Column {
    fn add_assign(&mut self, rhs: usize) {
        self.0 += rhs;
    }
}

impl SubAssign<usize> for Column {
    fn sub_assign(&mut self, rhs: usize) {
        self.0 -= rhs;
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Side {
    Left,
    Right,
}

/// A cell's color as SGR set it: the default foreground or background, a palette index or a true color.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Color {
    Foreground,
    Background,
    Indexed(u8),
    Spec(Rgb),
}

/// A cell's attributes and its place in a wide character or a wrapped line.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Flags(u16);

impl Flags {
    pub const BOLD: Flags = Flags(1);
    pub const ITALIC: Flags = Flags(1 << 1);
    pub const DIM: Flags = Flags(1 << 2);
    pub const INVERSE: Flags = Flags(1 << 3);
    pub const HIDDEN: Flags = Flags(1 << 4);
    pub const STRIKEOUT: Flags = Flags(1 << 5);
    pub const UNDERLINE: Flags = Flags(1 << 6);
    pub const DOUBLE_UNDERLINE: Flags = Flags(1 << 7);
    pub const UNDERCURL: Flags = Flags(1 << 8);
    pub const DOTTED_UNDERLINE: Flags = Flags(1 << 9);
    pub const DASHED_UNDERLINE: Flags = Flags(1 << 10);
    pub const ALL_UNDERLINES: Flags = Flags(Self::UNDERLINE.0 | Self::DOUBLE_UNDERLINE.0 | Self::UNDERCURL.0 | Self::DOTTED_UNDERLINE.0 | Self::DASHED_UNDERLINE.0);
    /// The first cell of a double width character.
    pub const WIDE_CHAR: Flags = Flags(1 << 11);
    /// The second cell of a double width character.
    pub const WIDE_CHAR_SPACER: Flags = Flags(1 << 12);
    /// The last cell of a line whose double width character went to the next line.
    pub const LEADING_WIDE_CHAR_SPACER: Flags = Flags(1 << 13);
    /// The last cell of a line that continues on the next (a soft wrap).
    pub const WRAPLINE: Flags = Flags(1 << 14);

    pub fn empty() -> Flags {
        Flags(0)
    }

    pub fn is_empty(self) -> bool {
        self.0 == 0
    }

    pub fn contains(self, other: Flags) -> bool {
        self.0 & other.0 == other.0
    }

    pub fn intersects(self, other: Flags) -> bool {
        self.0 & other.0 != 0
    }

    pub fn insert(&mut self, other: Flags) {
        self.0 |= other.0;
    }
}

impl std::ops::BitOr for Flags {
    type Output = Flags;
    fn bitor(self, rhs: Flags) -> Flags {
        Flags(self.0 | rhs.0)
    }
}

impl std::ops::BitAnd for Flags {
    type Output = Flags;
    fn bitand(self, rhs: Flags) -> Flags {
        Flags(self.0 & rhs.0)
    }
}

impl std::ops::BitXor for Flags {
    type Output = Flags;
    fn bitxor(self, rhs: Flags) -> Flags {
        Flags(self.0 ^ rhs.0)
    }
}

impl std::ops::Not for Flags {
    type Output = Flags;
    fn not(self) -> Flags {
        Flags(!self.0)
    }
}

/// One cell's content and style. An empty cell reads as a space.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Cell {
    pub c: char,
    /// The combining characters after `c`.
    pub zerowidth: Vec<char>,
    pub fg: Color,
    pub bg: Color,
    pub underline_color: Option<Color>,
    pub flags: Flags,
}

impl Default for Cell {
    fn default() -> Cell {
        Cell { c: ' ', zerowidth: Vec::new(), fg: Color::Foreground, bg: Color::Background, underline_color: None, flags: Flags::empty() }
    }
}

impl Cell {
    pub fn zerowidth(&self) -> Option<&[char]> {
        (!self.zerowidth.is_empty()).then_some(self.zerowidth.as_slice())
    }

    pub fn underline_color(&self) -> Option<Color> {
        self.underline_color
    }
}

/// A line's cells, read from the terminal at one moment.
#[derive(Debug, PartialEq)]
pub struct Row(Vec<Cell>);

impl Row {
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn iter(&self) -> std::slice::Iter<'_, Cell> {
        self.0.iter()
    }

    /// The columns up to the last one with text; the whole row when it wraps.
    pub fn line_length(&self) -> Column {
        if self.0.last().is_some_and(|cell| cell.flags.contains(Flags::WRAPLINE)) {
            return Column(self.0.len());
        }
        Column(self.0.iter().rposition(|cell| cell.c != ' ' || !cell.zerowidth.is_empty()).map_or(0, |index| index + 1))
    }
}

impl Index<Column> for Row {
    type Output = Cell;
    fn index(&self, column: Column) -> &Cell {
        &self.0[column.0]
    }
}

/// The terminal modes the port reads, as xterm.js names them in `modes` and `buffer.active.type`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TermMode(u16);

impl TermMode {
    /// DECCKM (`?1`): cursor keys send application sequences.
    pub const APP_CURSOR: TermMode = TermMode(1);
    pub const BRACKETED_PASTE: TermMode = TermMode(1 << 1);
    /// The alternate screen is active.
    pub const ALT_SCREEN: TermMode = TermMode(1 << 2);
    /// `?1007`: the wheel sends arrow keys on the alternate screen.
    pub const ALTERNATE_SCROLL: TermMode = TermMode(1 << 3);
    /// `?1000`
    pub const MOUSE_REPORT_CLICK: TermMode = TermMode(1 << 4);
    /// `?1002`
    pub const MOUSE_DRAG: TermMode = TermMode(1 << 5);
    /// `?1003`
    pub const MOUSE_MOTION: TermMode = TermMode(1 << 6);
    pub const MOUSE_MODE: TermMode = TermMode(Self::MOUSE_REPORT_CLICK.0 | Self::MOUSE_DRAG.0 | Self::MOUSE_MOTION.0);
    /// `?1006`
    pub const SGR_MOUSE: TermMode = TermMode(1 << 7);
    /// `?1005`
    pub const UTF8_MOUSE: TermMode = TermMode(1 << 8);
    /// `?1004`
    pub const FOCUS_IN_OUT: TermMode = TermMode(1 << 9);
    /// DECTCEM (`?25`)
    pub const SHOW_CURSOR: TermMode = TermMode(1 << 10);

    pub fn contains(self, other: TermMode) -> bool {
        self.0 & other.0 == other.0
    }

    pub fn intersects(self, other: TermMode) -> bool {
        self.0 & other.0 != 0
    }
}

impl std::ops::BitOr for TermMode {
    type Output = TermMode;
    fn bitor(self, rhs: TermMode) -> TermMode {
        TermMode(self.0 | rhs.0)
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CursorShape {
    #[default]
    Block,
    Underline,
    Beam,
    HollowBlock,
    Hidden,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct CursorStyle {
    pub shape: CursorShape,
    pub blinking: bool,
}

pub struct Cursor {
    pub point: Point,
    /// The cursor sits past the last column, so the next character wraps first.
    pub input_needs_wrap: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Scroll {
    /// Lines up into the scrollback (positive) or down (negative).
    Delta(i32),
    PageUp,
    PageDown,
    Top,
    Bottom,
}

/// What xterm.js reads from its options: `scrollback`, `wordSeparators`, `cursorStyle` and `cursorBlink`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Config {
    pub scrolling_history: usize,
    pub semantic_escape_chars: String,
    pub default_cursor_style: CursorStyle,
}

impl Default for Config {
    fn default() -> Config {
        Config { scrolling_history: 10_000, semantic_escape_chars: ",│`|:\"' ()[]{}<>\t".into(), default_cursor_style: CursorStyle::default() }
    }
}

/// The colors a program set with OSC 4, 10, 11 and 12 over the defaults the terminal was given; index 256 is the
/// foreground, 257 the background, 258 the cursor.
pub struct ColorOverrides(Vec<Option<Rgb>>);

impl Index<usize> for ColorOverrides {
    type Output = Option<Rgb>;
    fn index(&self, index: usize) -> &Option<Rgb> {
        &self.0[index]
    }
}

/// The colors the terminal answers OSC 4, 10, 11 and 12 queries with: the theme's.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DefaultColors {
    pub palette: [Rgb; 256],
    pub foreground: Rgb,
    pub background: Rgb,
    pub cursor: Rgb,
}

/// What the terminal reported while it parsed, taken with `Term::take_effects`.
#[derive(Default)]
pub struct Effects {
    /// Replies for the program: device attributes, cursor and mode reports, color and size queries.
    pub pty_write: Vec<u8>,
    pub bell: bool,
    /// The title changed: `Some(title)`, `Some("")` after a reset.
    pub title: Option<String>,
}

/// The effect callbacks' state, the userdata the terminal hands them.
struct Handler {
    effects: Effects,
    size: SizeReportSize,
}

impl effect::OnPtyWrite for Handler {
    fn on_pty_write<'t>(&mut self, _: &'t Terminal<'_>, data: &'t [u8]) {
        self.effects.pty_write.extend_from_slice(data);
    }
}

impl effect::OnBell for Handler {
    fn on_bell(&mut self, _: &Terminal<'_>) {
        self.effects.bell = true;
    }
}

impl effect::OnTitleChanged for Handler {
    fn on_title_changed(&mut self, terminal: &Terminal<'_>) {
        // A panic here would unwind into Zig, so a failed read leaves the title as it was.
        if let Ok(title) = terminal.title() {
            self.effects.title = Some(String::from_utf8_lossy(title).into_owned());
        }
    }
}

impl effect::OnSize for Handler {
    fn on_size(&mut self, _: &Terminal<'_>) -> Option<SizeReportSize> {
        Some(self.size)
    }
}

/// xterm.js `CSI c` (`?1;2c`) and `CSI > c` (`>0;276;0c`).
impl effect::OnDeviceAttributes for Handler {
    fn on_device_attributes(&mut self, _: &Terminal<'_>) -> Option<DeviceAttributes> {
        Some(DeviceAttributes {
            primary: PrimaryDeviceAttributes::new(ConformanceLevel(1), &[DeviceAttributeFeature(2)]),
            secondary: SecondaryDeviceAttributes { device_type: DeviceType(0), firmware_version: 276, rom_cartridge: 0 },
            tertiary: TertiaryDeviceAttributes { unit_id: 0 },
        })
    }
}

impl effect::OnXtversion for Handler {
    fn on_xtversion<'t>(&mut self, _: &'t Terminal<'_>) -> Option<&'t [u8]> {
        Some(XTVERSION.as_bytes())
    }
}

/// xterm.js 6.1's replies (`CSI c`, `CSI > c`, `CSI > q`), the ones VS Code's terminal gives.
const XTVERSION: &str = "xterm.js(6.1.0-beta.337)";

/// The viewport copy the paint path and the cursor style read, with the iterators reused across frames.
struct Render {
    state: RenderState<'static>,
    rows: RowIterator<'static>,
    cells: CellIterator<'static>,
}

pub struct Term {
    selection: Option<selection::Selection>,
    render: RefCell<Render>,
    raw: Terminal<'static>,
    config: Config,
    default_colors: Option<DefaultColors>,
}

impl Term {
    pub fn new(cols: u16, rows: u16, config: Config) -> Term {
        let mut raw = Terminal::new(cols.max(1), rows.max(1)).unwrap();
        let size = SizeReportSize { rows, columns: cols, cell_width: 0, cell_height: 0 };
        raw.register_effects(Handler { effects: Effects::default(), size })
            .and_then(|effects| effects.with_on_pty_write())
            .and_then(|effects| effects.with_on_bell())
            .and_then(|effects| effects.with_on_title_changed())
            .and_then(|effects| effects.with_on_size())
            .and_then(|effects| effects.with_on_device_attributes())
            .and_then(|effects| effects.with_on_xtversion())
            .unwrap();
        raw.set_scrollback_max_bytes(Some(usize::MAX)).unwrap();
        let render = Render { state: RenderState::new().unwrap(), rows: RowIterator::new().unwrap(), cells: CellIterator::new().unwrap() };
        let mut term = Term { selection: None, render: RefCell::new(render), raw, config: Config::default(), default_colors: None };
        term.apply_config(&config);
        term.config = config;
        term
    }

    fn handler(&mut self) -> &mut Handler {
        self.raw.effect_handler_mut::<Handler>().unwrap()
    }

    /// Applies changed options: the scrollback limit, the word separators and the default cursor.
    pub fn set_options(&mut self, config: Config) {
        if config != self.config {
            self.apply_config(&config);
            self.config = config;
        }
    }

    fn apply_config(&mut self, config: &Config) {
        // Ghostty prunes whole pages, so it keeps more lines than this; `history_size` hides the rest.
        self.raw.set_scrollback_max_lines(Some(config.scrolling_history)).unwrap();
        let style = match config.default_cursor_style.shape {
            CursorShape::Beam => GhosttyCursorStyle::Bar,
            CursorShape::Underline => GhosttyCursorStyle::Underline,
            CursorShape::HollowBlock => GhosttyCursorStyle::BlockHollow,
            CursorShape::Block | CursorShape::Hidden => GhosttyCursorStyle::Block,
        };
        self.raw.set_default_cursor_style(Some(style)).unwrap();
        self.raw.set_default_cursor_blink(Some(config.default_cursor_style.blinking)).unwrap();
    }

    pub fn semantic_escape_chars(&self) -> &str {
        &self.config.semantic_escape_chars
    }

    /// The theme's colors, as the terminal's defaults: OSC queries answer with them and OSC sets override them.
    pub fn set_default_colors(&mut self, colors: DefaultColors) {
        if self.default_colors.as_ref() == Some(&colors) {
            return;
        }
        self.raw.set_default_color_palette(Some(libghostty_vt::color::Palette(colors.palette))).unwrap();
        self.raw.set_default_fg_color(Some(colors.foreground)).unwrap();
        self.raw.set_default_bg_color(Some(colors.background)).unwrap();
        self.raw.set_default_cursor_color(Some(colors.cursor)).unwrap();
        self.default_colors = Some(colors);
    }

    /// The colors OSC 4, 10, 11 and 12 changed from the defaults `set_default_colors` gave.
    pub fn color_overrides(&self) -> ColorOverrides {
        let mut overrides = vec![None; 259];
        let (palette, defaults) = (self.raw.color_palette().unwrap(), self.raw.default_color_palette().unwrap());
        for index in 0..256 {
            if palette.0[index] != defaults.0[index] {
                overrides[index] = Some(palette.0[index]);
            }
        }
        let pairs = [
            (self.raw.fg_color(), self.raw.default_fg_color()),
            (self.raw.bg_color(), self.raw.default_bg_color()),
            (self.raw.cursor_color(), self.raw.default_cursor_color()),
        ];
        for (offset, (current, default)) in pairs.into_iter().enumerate() {
            if let Some(value) = current.unwrap()
                && default.unwrap() != Some(value)
            {
                overrides[256 + offset] = Some(value);
            }
        }
        ColorOverrides(overrides)
    }

    /// Parses the program's output.
    pub fn advance(&mut self, bytes: &[u8]) {
        let screen = self.active_screen();
        self.raw.vt_write(bytes);
        // xterm.js clears the selection when the other buffer activates.
        if self.active_screen() != screen {
            self.selection = None;
        }
    }

    fn active_screen(&self) -> Screen {
        self.raw.active_screen().unwrap()
    }

    pub fn take_effects(&mut self) -> Effects {
        std::mem::take(&mut self.handler().effects)
    }

    /// RIS: the screens, modes and colors back to their defaults.
    pub fn reset(&mut self) {
        self.raw.reset();
    }

    pub fn resize(&mut self, cols: u16, rows: u16) {
        self.selection = None;
        let size = self.handler().size;
        self.raw.resize(cols.max(1), rows.max(1), size.cell_width, size.cell_height).unwrap();
        let size = &mut self.handler().size;
        size.rows = rows;
        size.columns = cols;
    }

    /// The cell size in pixels, for `CSI 14 t` and `CSI 16 t`.
    pub fn set_cell_size(&mut self, width: u32, height: u32) {
        let size = &mut self.handler().size;
        size.cell_width = width;
        size.cell_height = height;
    }

    pub fn columns(&self) -> usize {
        self.raw.cols().unwrap() as usize
    }

    pub fn screen_lines(&self) -> usize {
        self.raw.rows().unwrap() as usize
    }

    fn scrollback_rows(&self) -> usize {
        self.raw.scrollback_rows().unwrap()
    }

    /// The scrollback's lines, at most `scrolling_history` as xterm.js's `scrollback`.
    pub fn history_size(&self) -> usize {
        self.scrollback_rows().min(self.config.scrolling_history)
    }

    /// The rows Ghostty keeps above the scrollback xterm.js would keep.
    fn hidden_rows(&self) -> usize {
        self.scrollback_rows().saturating_sub(self.config.scrolling_history)
    }

    pub fn topmost_line(&self) -> Line {
        Line(-(self.history_size() as i32))
    }

    pub fn bottommost_line(&self) -> Line {
        Line(self.screen_lines() as i32 - 1)
    }

    pub fn last_column(&self) -> Column {
        Column(self.columns() - 1)
    }

    pub fn mode(&self) -> TermMode {
        let modes = [
            (1, TermMode::APP_CURSOR),
            (2004, TermMode::BRACKETED_PASTE),
            (1007, TermMode::ALTERNATE_SCROLL),
            (1000, TermMode::MOUSE_REPORT_CLICK),
            (1002, TermMode::MOUSE_DRAG),
            (1003, TermMode::MOUSE_MOTION),
            (1006, TermMode::SGR_MOUSE),
            (1005, TermMode::UTF8_MOUSE),
            (1004, TermMode::FOCUS_IN_OUT),
            (25, TermMode::SHOW_CURSOR),
        ];
        let mut mode = TermMode::default();
        for (number, flag) in modes {
            if self.raw.mode(Mode::new(number, Kind::Dec)).unwrap() {
                mode = mode | flag;
            }
        }
        if self.active_screen() == Screen::Alternate {
            mode = mode | TermMode::ALT_SCREEN;
        }
        mode
    }

    pub fn cursor(&self) -> Cursor {
        let (x, y) = (self.raw.cursor_x().unwrap(), self.raw.cursor_y().unwrap());
        Cursor { point: Point::new(Line(y as i32), Column(x as usize)), input_needs_wrap: self.raw.is_cursor_pending_wrap().unwrap() }
    }

    /// The pen the next printed character takes (SGR state), as a blank cell.
    pub fn cursor_template(&self) -> Cell {
        let mut cell = Cell::default();
        apply_style(&mut cell, &self.raw.cursor_style().unwrap());
        cell
    }

    /// The cursor's shape and blinking as DECSCUSR and the defaults set it; `Hidden` while DECTCEM hides it.
    pub fn cursor_style(&self) -> CursorStyle {
        let mut render = self.render.borrow_mut();
        let snapshot = render.state.update(&self.raw).unwrap();
        let blinking = snapshot.cursor_blinking().unwrap();
        let shape = match snapshot.cursor_visual_style().unwrap() {
            _ if !snapshot.cursor_visible().unwrap() => CursorShape::Hidden,
            GhosttyCursorStyle::Bar => CursorShape::Beam,
            GhosttyCursorStyle::Underline => CursorShape::Underline,
            GhosttyCursorStyle::BlockHollow => CursorShape::HollowBlock,
            _ => CursorShape::Block,
        };
        CursorStyle { shape, blinking }
    }

    /// The viewport's distance from the bottom, in lines.
    pub fn display_offset(&self) -> usize {
        let scrollbar = self.raw.scrollbar().unwrap();
        (scrollbar.total - scrollbar.offset - scrollbar.len) as usize
    }

    pub fn scroll_display(&mut self, scroll: Scroll) {
        let page = self.screen_lines() as isize;
        let viewport = match scroll {
            Scroll::Delta(lines) => ScrollViewport::Delta(-(lines as isize)),
            Scroll::PageUp => ScrollViewport::Delta(-page),
            Scroll::PageDown => ScrollViewport::Delta(page),
            Scroll::Top => ScrollViewport::Row(self.hidden_rows()),
            Scroll::Bottom => ScrollViewport::Bottom,
        };
        self.raw.scroll_viewport(viewport).unwrap();
        let hidden = self.hidden_rows();
        if hidden > 0 && self.display_offset() > self.history_size() {
            self.raw.scroll_viewport(ScrollViewport::Row(hidden)).unwrap();
        }
    }

    /// Scrolls so `point` is in the viewport, as little as needed.
    pub fn scroll_to_point(&mut self, point: Point) {
        let offset = self.display_offset() as i32;
        let rows = self.screen_lines() as i32;
        if point.line.0 < -offset {
            self.scroll_display(Scroll::Delta(-offset - point.line.0));
        } else if point.line.0 >= rows - offset {
            self.scroll_display(Scroll::Delta(rows - offset - 1 - point.line.0));
        }
    }

    /// The point as Ghostty addresses it. Active lines use the active tag, which Ghostty resolves from the bottom;
    /// scrollback lines count from the oldest row it keeps.
    fn screen_point(&self, point: Point) -> GhosttyPoint {
        assert!(point.line >= self.topmost_line() && point.line <= self.bottommost_line(), "line {} is outside the terminal", point.line.0);
        let x = point.column.0 as u16;
        match point.line.0 {
            line if line >= 0 => GhosttyPoint::Active(Coordinate { x, y: line as u32 }),
            line => GhosttyPoint::Screen(Coordinate { x, y: (self.scrollback_rows() as i64 + line as i64) as u32 }),
        }
    }

    fn grid_ref(&self, point: Point) -> GridRef<'_> {
        self.raw.grid_ref(self.screen_point(point)).unwrap()
    }

    /// Whether `line` continues on the next one.
    pub fn wraps(&self, line: Line) -> bool {
        self.grid_ref(Point::new(line, Column(0))).row().unwrap().is_wrapped().unwrap()
    }

    pub fn cell(&self, point: Point) -> Cell {
        let mut cell = read_cell(&self.grid_ref(point));
        if point.column.0 + 1 == self.columns() && self.wraps(point.line) {
            cell.flags.insert(Flags::WRAPLINE);
        }
        cell
    }

    /// Any line's cells, one grid reference per cell; `viewport_rows` reads the visible lines faster.
    pub fn row(&self, line: Line) -> Row {
        let columns = self.columns();
        let mut cells: Vec<Cell> = (0..columns).map(|column| read_cell(&self.grid_ref(Point::new(line, Column(column))))).collect();
        if self.wraps(line) {
            cells[columns - 1].flags.insert(Flags::WRAPLINE);
        }
        Row(cells)
    }

    /// The viewport's rows, top to bottom, from the render state: one call reads a row's raw cells, where `row`
    /// resolves a grid reference per cell.
    pub fn viewport_rows(&self) -> Vec<Row> {
        let mut render = self.render.borrow_mut();
        let Render { state, rows, cells } = &mut *render;
        let snapshot = state.update(&self.raw).unwrap();
        let mut iteration = rows.update(&snapshot).unwrap();
        let mut viewport = Vec::with_capacity(self.screen_lines());
        while let Some(row) = iteration.next() {
            let mut cell_iteration = cells.update(row).unwrap();
            // Style ids index the row's page, so they are cached per row.
            let mut styles: Vec<(libghostty_vt::style::Id, Style)> = Vec::new();
            let mut line = Vec::with_capacity(self.columns());
            for (x, raw) in row.cells_raw().unwrap().enumerate() {
                let fields = cell_fields(raw);
                let style = match fields.style {
                    Some(id) => match styles.iter().find(|(cached, _)| *cached == id) {
                        Some((_, style)) => *style,
                        None => {
                            cell_iteration.select(x as u16).unwrap();
                            let style = cell_iteration.style().unwrap();
                            styles.push((id, style));
                            style
                        }
                    },
                    None => Style::default(),
                };
                let graphemes = match fields.tag {
                    CellContentTag::CodepointGrapheme => {
                        cell_iteration.select(x as u16).unwrap();
                        cell_iteration.graphemes().unwrap()
                    }
                    _ => Vec::new(),
                };
                line.push(make_cell(raw, &fields, &style, graphemes));
            }
            if row.raw_row().unwrap().is_wrapped().unwrap()
                && let Some(last) = line.last_mut()
            {
                last.flags.insert(Flags::WRAPLINE);
            }
            viewport.push(Row(line));
        }
        viewport
    }

    /// A ref that follows `point`'s cell as output scrolls it up; `None` once the scrollback drops the cell.
    fn track(&self, point: Point) -> TrackedPoint {
        self.raw.track_grid_ref(self.screen_point(point)).unwrap()
    }

    fn tracked_point(&self, tracked: &TrackedPoint) -> Option<Point> {
        if !tracked.has_value() {
            return None;
        }
        let coordinate = tracked.point(Space::Screen).unwrap()?;
        let line = coordinate.y as i64 - self.scrollback_rows() as i64;
        (line >= -(self.history_size() as i64)).then(|| Point::new(Line(line as i32), Column(coordinate.x as usize)))
    }

    pub fn title(&self) -> String {
        String::from_utf8_lossy(self.raw.title().unwrap()).into_owned()
    }
}

use TrackedGridRef as TrackedPoint;

/// The fields of a raw cell the port reads, in one call.
struct CellFields {
    codepoint: char,
    tag: CellContentTag,
    wide: CellWide,
    /// The cell's style id, `None` for the default style.
    style: Option<libghostty_vt::style::Id>,
}

fn cell_fields(raw: screen::Cell) -> CellFields {
    let (codepoint, tag, wide, styled, style) = raw.get_multi((cell::Codepoint, cell::ContentTag, cell::Wide, cell::HasStyling, cell::StyleId)).unwrap();
    CellFields { codepoint, tag, wide, style: styled.then_some(style) }
}

fn read_cell(grid_ref: &GridRef<'_>) -> Cell {
    let raw = grid_ref.cell().unwrap();
    let fields = cell_fields(raw);
    let style = grid_ref.style().unwrap();
    let graphemes = match fields.tag {
        CellContentTag::CodepointGrapheme => grid_ref_graphemes(grid_ref),
        _ => Vec::new(),
    };
    make_cell(raw, &fields, &style, graphemes)
}

/// The cell's grapheme cluster, its base codepoint first.
fn grid_ref_graphemes(grid_ref: &GridRef<'_>) -> Vec<char> {
    let mut buffer = vec!['\0'; 16];
    let written = match grid_ref.graphemes(&mut buffer) {
        Err(libghostty_vt::Error::OutOfSpace { required }) => {
            buffer.resize(required, '\0');
            grid_ref.graphemes(&mut buffer).unwrap()
        }
        written => written.unwrap(),
    };
    buffer.truncate(written);
    buffer
}

fn make_cell(raw: screen::Cell, fields: &CellFields, style: &Style, graphemes: Vec<char>) -> Cell {
    let mut cell = Cell { c: if fields.codepoint == '\0' { ' ' } else { fields.codepoint }, ..Cell::default() };
    apply_style(&mut cell, style);
    match fields.tag {
        CellContentTag::CodepointGrapheme => cell.zerowidth = graphemes.into_iter().skip(1).collect(),
        CellContentTag::BgColorPalette => cell.bg = Color::Indexed(raw.bg_color_palette().unwrap().0),
        CellContentTag::BgColorRgb => cell.bg = Color::Spec(raw.bg_color_rgb().unwrap()),
        CellContentTag::Codepoint => {}
    }
    match fields.wide {
        CellWide::Wide => cell.flags.insert(Flags::WIDE_CHAR),
        CellWide::SpacerTail => cell.flags.insert(Flags::WIDE_CHAR_SPACER),
        CellWide::SpacerHead => cell.flags.insert(Flags::LEADING_WIDE_CHAR_SPACER),
        CellWide::Narrow => {}
    }
    cell
}

fn style_color(color: StyleColor) -> Option<Color> {
    match color {
        StyleColor::None => None,
        StyleColor::Palette(index) => Some(Color::Indexed(index.0)),
        StyleColor::Rgb(rgb) => Some(Color::Spec(rgb)),
    }
}

fn apply_style(cell: &mut Cell, style: &Style) {
    cell.fg = style_color(style.fg_color).unwrap_or(Color::Foreground);
    cell.bg = style_color(style.bg_color).unwrap_or(Color::Background);
    cell.underline_color = style_color(style.underline_color);
    let attributes = [(style.bold, Flags::BOLD), (style.italic, Flags::ITALIC), (style.faint, Flags::DIM), (style.inverse, Flags::INVERSE), (style.invisible, Flags::HIDDEN), (style.strikethrough, Flags::STRIKEOUT)];
    for (set, flag) in attributes {
        if set {
            cell.flags.insert(flag);
        }
    }
    cell.flags.insert(match style.underline {
        Underline::Single => Flags::UNDERLINE,
        Underline::Double => Flags::DOUBLE_UNDERLINE,
        Underline::Curly => Flags::UNDERCURL,
        Underline::Dotted => Flags::DOTTED_UNDERLINE,
        Underline::Dashed => Flags::DASHED_UNDERLINE,
        _ => Flags::empty(),
    });
}

#[cfg(test)]
mod tests;