rustom 0.1.0

A library for building rich, stateful terminal user interfaces and dashboards.
Documentation
//! The `Buffer` is an in-memory grid of `Cell`s representing everything
//! that should be drawn on screen for a single frame. Widgets never touch
//! the terminal directly, they only ever write into a `Buffer`.

use crate::layout::Rect;
use crate::style::{Color, Modifier, Style};
use unicode_width::UnicodeWidthStr;

/// A single character cell in the terminal grid, along with its style.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cell {
    pub symbol: String,
    pub fg: Color,
    pub bg: Color,
    pub modifier: Modifier,
}

impl Default for Cell {
    fn default() -> Cell {
        Cell {
            symbol: " ".to_string(),
            fg: Color::Reset,
            bg: Color::Reset,
            modifier: Modifier::empty(),
        }
    }
}

impl Cell {
    pub fn set_symbol(&mut self, symbol: &str) -> &mut Cell {
        self.symbol.clear();
        self.symbol.push_str(symbol);
        self
    }

    pub fn set_char(&mut self, ch: char) -> &mut Cell {
        self.symbol.clear();
        self.symbol.push(ch);
        self
    }

    pub fn set_fg(&mut self, color: Color) -> &mut Cell {
        self.fg = color;
        self
    }

    pub fn set_bg(&mut self, color: Color) -> &mut Cell {
        self.bg = color;
        self
    }

    pub fn set_style(&mut self, style: Style) -> &mut Cell {
        if let Some(c) = style.fg {
            self.fg = c;
        }
        if let Some(c) = style.bg {
            self.bg = c;
        }
        self.modifier.remove(style.sub_modifier);
        self.modifier.insert(style.add_modifier);
        self
    }

    pub fn reset(&mut self) {
        *self = Cell::default();
    }
}

/// The full grid of cells for a given `area` of the terminal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Buffer {
    pub area: Rect,
    pub content: Vec<Cell>,
}

impl Buffer {
    pub fn empty(area: Rect) -> Buffer {
        let size = (area.width as usize) * (area.height as usize);
        Buffer {
            area,
            content: vec![Cell::default(); size],
        }
    }

    pub fn filled(area: Rect, cell: &Cell) -> Buffer {
        let size = (area.width as usize) * (area.height as usize);
        Buffer {
            area,
            content: vec![cell.clone(); size],
        }
    }

    /// Converts absolute grid coordinates into an index into `content`.
    pub fn index_of(&self, x: u16, y: u16) -> usize {
        debug_assert!(
            self.area.contains(x, y),
            "position out of bounds: ({x},{y}) in {:?}",
            self.area
        );
        ((y - self.area.y) as usize) * (self.area.width as usize) + ((x - self.area.x) as usize)
    }

    /// Converts an index in `content` back into absolute grid coordinates.
    pub fn pos_of(&self, i: usize) -> (u16, u16) {
        (
            self.area.x + (i as u16 % self.area.width),
            self.area.y + (i as u16 / self.area.width),
        )
    }

    pub fn get(&self, x: u16, y: u16) -> &Cell {
        &self.content[self.index_of(x, y)]
    }

    pub fn get_mut(&mut self, x: u16, y: u16) -> &mut Cell {
        let i = self.index_of(x, y);
        &mut self.content[i]
    }

    pub fn reset(&mut self) {
        for c in &mut self.content {
            c.reset();
        }
    }

    pub fn resize(&mut self, area: Rect) {
        let size = (area.width as usize) * (area.height as usize);
        self.content.resize(size, Cell::default());
        self.area = area;
    }

    /// Writes `string` starting at `(x, y)`, applying `style` to every cell,
    /// and stopping once `width` columns have been written or the string
    /// runs out. Returns the x coordinate just past the last cell written.
    pub fn set_stringn(
        &mut self,
        x: u16,
        y: u16,
        string: &str,
        max_width: usize,
        style: Style,
    ) -> u16 {
        let mut cx = x;
        let mut remaining = max_width;
        for g in unicode_segmentation_graphemes(string) {
            let w = UnicodeWidthStr::width(g);
            if w == 0 {
                continue;
            }
            if remaining < w || cx >= self.area.right() {
                break;
            }
            if self.area.contains(cx, y) {
                let cell = self.get_mut(cx, y);
                cell.set_symbol(g);
                cell.set_style(style);
            }
            cx += w as u16;
            remaining -= w;
        }
        cx
    }

    pub fn set_string(&mut self, x: u16, y: u16, string: &str, style: Style) {
        self.set_stringn(x, y, string, usize::MAX, style);
    }

    pub fn set_style(&mut self, area: Rect, style: Style) {
        let area = area.intersection(self.area);
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                self.get_mut(x, y).set_style(style);
            }
        }
    }

    /// Returns every `(x, y, cell)` triple that differs between `self` and
    /// `other`, in row major order. This is what the terminal backend uses
    /// to draw only the cells that actually changed between frames.
    pub fn diff<'a>(&self, other: &'a Buffer) -> Vec<(u16, u16, &'a Cell)> {
        let mut updates = Vec::new();
        for i in 0..self.content.len().min(other.content.len()) {
            if self.content[i] != other.content[i] {
                let (x, y) = other.pos_of(i);
                updates.push((x, y, &other.content[i]));
            }
        }
        updates
    }
}

/// Minimal grapheme splitting wrapper kept local so the rest of the crate
/// depends on a single import site.
fn unicode_segmentation_graphemes(s: &str) -> unicode_segmentation::Graphemes<'_> {
    unicode_segmentation::UnicodeSegmentation::graphemes(s, true)
}

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

    #[test]
    fn set_string_writes_cells() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 1));
        buf.set_string(0, 0, "hi", Style::default());
        assert_eq!(buf.get(0, 0).symbol, "h");
        assert_eq!(buf.get(1, 0).symbol, "i");
        assert_eq!(buf.get(2, 0).symbol, " ");
    }

    #[test]
    fn set_string_truncates_at_width() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 3, 1));
        buf.set_string(0, 0, "hello", Style::default());
        assert_eq!(buf.get(0, 0).symbol, "h");
        assert_eq!(buf.get(2, 0).symbol, "l");
    }

    #[test]
    fn diff_reports_only_changed_cells() {
        let area = Rect::new(0, 0, 3, 1);
        let a = Buffer::empty(area);
        let mut b = Buffer::empty(area);
        b.set_string(1, 0, "x", Style::default());
        let updates = a.diff(&b);
        assert_eq!(updates.len(), 1);
        assert_eq!((updates[0].0, updates[0].1), (1, 0));
    }

    #[test]
    fn index_and_pos_roundtrip() {
        let buf = Buffer::empty(Rect::new(2, 3, 4, 4));
        for y in 3..7 {
            for x in 2..6 {
                let i = buf.index_of(x, y);
                assert_eq!(buf.pos_of(i), (x, y));
            }
        }
    }
}