//! Styled terminal cell buffer. //! //! `Buffer` is the render artifact for the core crate: widgets write styled //! [`Cell`] values into it, and the terminal flushes only the cells that changed //! since the previous frame. It also handles wide glyph continuation cells so //! higher-level widgets can write glyphs without manual cleanup. use std::borrow::Cow; use std::{slice, str}; use crate::cell::{Text as _, char_width}; use crate::layout::{Point, Rect}; use crate::{Label, Line, Paint, Size, Style}; /// A styled terminal cell. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Cell { /// Cell glyph. glyph: CellGlyph, /// Cell style. style: Style, } /// Renderable cell glyph. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] enum CellGlyph { /// A blank terminal cell. #[default] Blank, /// A single ASCII terminal glyph. Ascii(u8), /// A single non-ASCII terminal glyph. Unicode(char), /// A heap-backed multi-scalar terminal glyph. Grapheme(String), /// Continuation cell occupied by a wide leading glyph. Continuation, } impl Cell { /// Creates a cell from one character and style. pub fn new(ch: char, style: Style) -> Self { Self { glyph: normalize_char(ch), style, } } /// Creates a cell from a glyph string and style. pub(crate) fn from_glyph(glyph: impl AsRef, style: Style) -> Self { Self { glyph: normalize_glyph(glyph.as_ref()), style, } } /// Creates a blank cell. pub fn blank() -> Self { Self::default() } /// Returns the cell glyph. pub fn glyph(&self) -> Cow<'_, str> { match &self.glyph { CellGlyph::Blank => Cow::Borrowed(" "), CellGlyph::Ascii(glyph) => { Cow::Borrowed(str::from_utf8(slice::from_ref(glyph)).unwrap_or(" ")) } CellGlyph::Unicode(glyph) => Cow::Owned(glyph.to_string()), CellGlyph::Grapheme(glyph) => Cow::Borrowed(glyph), CellGlyph::Continuation => Cow::Borrowed(""), } } /// Returns the cell style. pub const fn style(&self) -> Style { self.style } /// Returns whether this cell is a wide-glyph continuation. pub fn is_continuation(&self) -> bool { matches!(self.glyph, CellGlyph::Continuation) } /// Returns this cell as styled display text. pub fn paint(&self) -> Paint> { Paint::new(self.glyph()).with_style(self.style) } /// Returns this cell with a different style. pub fn with_style(mut self, style: Style) -> Self { self.style = style; self } /// Creates a continuation cell. fn continuation(style: Style) -> Self { Self { glyph: CellGlyph::Continuation, style, } } /// Creates a cell from one printable ASCII byte. fn from_printable_ascii(byte: u8, style: Style) -> Self { Self { glyph: if byte == b' ' { CellGlyph::Blank } else { CellGlyph::Ascii(byte) }, style, } } /// Returns the terminal width of this cell's leading glyph. fn width(&self) -> usize { match &self.glyph { CellGlyph::Blank | CellGlyph::Ascii(_) => 1, CellGlyph::Unicode(glyph) => char_width(*glyph), CellGlyph::Grapheme(glyph) => glyph.width(), CellGlyph::Continuation => 0, } } } /// A contiguous run of dirty cells. #[derive(Debug, Clone, Copy)] pub struct DirtyRun<'a> { /// Start column. pub x: usize, /// Row. pub y: usize, /// Dirty cells. pub cells: &'a [Cell], } /// A rectangular styled cell buffer. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Buffer { area: Rect, cells: Vec, dirty: Vec, } impl Buffer { /// Creates an empty buffer for an area. pub fn empty(area: Rect) -> Self { let len = area.cols.saturating_mul(area.rows); Self { area, cells: vec![Cell::blank(); len], dirty: vec![true; len], } } /// Returns the covered area. pub const fn area(&self) -> Rect { self.area } /// Returns the buffer size. pub const fn size(&self) -> Size { self.area.size() } /// Returns whether the buffer has no cells. pub fn is_empty(&self) -> bool { self.cells.is_empty() } /// Resizes the buffer and marks all cells dirty. pub fn resize(&mut self, area: Rect) { if self.area == area { return; } *self = Self::empty(area); } /// Clears the buffer to blank cells. pub fn clear(&mut self) { for (cell, dirty) in self.cells.iter_mut().zip(&mut self.dirty) { if *cell != Cell::blank() { *cell = Cell::blank(); *dirty = true; } } } /// Marks all cells clean. pub fn reset_dirty(&mut self) { self.dirty.fill(false); } /// Returns a cell by absolute position. pub fn get(&self, x: usize, y: usize) -> Option<&Cell> { self.index(x, y).map(|index| &self.cells[index]) } /// Sets a cell by absolute position. pub fn set(&mut self, x: usize, y: usize, cell: Cell) { if cell.is_continuation() { self.set_exact(x, y, cell); return; } let width = cell.width().max(1); self.clear_glyph_at(x, y); if width > self.area.right().saturating_sub(x) { return; } let style = cell.style(); self.set_exact(x, y, cell); for dx in 1..width { self.set_exact(x + dx, y, Cell::continuation(style)); } } /// Sets a cell without adjusting neighboring wide cells. fn set_exact(&mut self, x: usize, y: usize, cell: Cell) { let Some(index) = self.index(x, y) else { return; }; if self.cells[index] != cell { self.cells[index] = cell; self.dirty[index] = true; } } /// Sets one styled glyph by absolute position. pub fn set_glyph(&mut self, x: usize, y: usize, glyph: impl AsRef, style: Style) { self.set(x, y, Cell::from_glyph(glyph, style)); } /// Sets one styled character by absolute position. pub(crate) fn set_char(&mut self, x: usize, y: usize, ch: char, style: Style) { self.set(x, y, Cell::new(ch, style)); } /// Writes styled text by absolute position. pub fn set_str(&mut self, x: usize, y: usize, text: &str, style: Style) { if text.is_ascii() && text.bytes().all(|byte| !byte.is_ascii_control()) && self.area.contains(Point::new(x, y)) { self.set_ascii_str(x, y, text, style); return; } let mut cursor = x; for ch in text.chars() { if cursor >= self.area.right() { break; } let width = char_width(ch); if width == 0 { continue; } if width > self.area.right().saturating_sub(cursor) { break; } self.set(cursor, y, Cell::new(ch, style)); cursor += width; } } /// Writes printable ASCII text by absolute position. fn set_ascii_str(&mut self, x: usize, y: usize, text: &str, style: Style) { let visible = text.len().min(self.area.right() - x); if visible == 0 { return; } self.clear_glyph_at(x, y); if x + visible < self.area.right() && self.get(x + visible, y).is_some_and(Cell::is_continuation) { self.clear_glyph_at(x + visible, y); } let start = (y - self.area.y) * self.area.cols + (x - self.area.x); for (offset, byte) in text.bytes().take(visible).enumerate() { let cell = Cell::from_printable_ascii(byte, style); let index = start + offset; if self.cells[index] != cell { self.cells[index] = cell; self.dirty[index] = true; } } } /// Writes a label by absolute position. pub fn set_label(&mut self, x: usize, y: usize, label: &Label) { if label.is_ascii() && self.area.contains(Point::new(x, y)) { self.set_ascii_str(x, y, label.content(), label.paint.style()); } else { self.set_str(x, y, label.content(), label.paint.style()); } } /// Writes a styled line by absolute position. pub fn set_line(&mut self, x: usize, y: usize, line: &Line) { let mut cursor = x; for label in line.labels() { self.set_label(cursor, y, label); cursor += label.width(); if cursor >= self.area.right() { break; } } } /// Fills an area with a cell. pub fn fill(&mut self, area: Rect, cell: Cell) { let area = self.area.intersection(area); for y in area.y..area.bottom() { let mut x = area.x; while x < area.right() { let width = cell.width().max(1); if width > area.right().saturating_sub(x) { break; } self.set(x, y, cell.clone()); x += width; } } } /// Returns dirty runs based on explicit dirty marks. pub fn dirty_runs(&self) -> Vec> { self.runs(|index, _| self.dirty[index]) } /// Returns dirty runs by diffing against `previous`. pub fn diff(&self, previous: &Self) -> Vec> { if self.area != previous.area { return self.runs(|_, _| true); } self.runs(|index, cell| previous.cells[index] != *cell) } /// Returns plain rendered lines. pub fn lines(&self) -> Vec { (0..self.area.rows).map(|row| self.line(row)).collect() } /// Returns one plain rendered line by local row index. pub fn line(&self, row: usize) -> String { if row >= self.area.rows { return String::new(); } let start = row * self.area.cols; let end = start + self.area.cols; self.cells[start..end] .iter() .map(|cell| cell.glyph()) .collect::() } /// Returns one styled rendered line by local row index. pub fn styled_line(&self, row: usize) -> Line { if row >= self.area.rows { return Line::blank(); } let start = row * self.area.cols; let end = start + self.area.cols; let mut line = Line::blank(); let mut content = String::new(); let mut style = None; for cell in &self.cells[start..end] { if cell.is_continuation() { continue; } let cell_style = cell.style(); if style.is_some_and(|style| style != cell_style) && !content.is_empty() { line.push(Label::raw(content, style.unwrap_or_default())); content = String::new(); } style = Some(cell_style); content.push_str(&cell.glyph()); } if !content.is_empty() { line.push(Label::raw(content, style.unwrap_or_default())); } line } /// Computes dirty runs using a cell predicate. fn runs(&self, mut dirty: impl FnMut(usize, &Cell) -> bool) -> Vec> { let mut runs = Vec::new(); for row in 0..self.area.rows { let start = row * self.area.cols; let end = start + self.area.cols; let mut index = start; while index < end { while index < end && !dirty(index, &self.cells[index]) { index += 1; } if index == end { break; } let run_start = index; while index < end && dirty(index, &self.cells[index]) { index += 1; } runs.push(DirtyRun { x: self.area.x + run_start - start, y: self.area.y + row, cells: &self.cells[run_start..index], }); } } runs } /// Returns an index for an absolute position. fn index(&self, x: usize, y: usize) -> Option { if !self.area.contains(Point::new(x, y)) { return None; } let local_x = x - self.area.x; let local_y = y - self.area.y; Some(local_y * self.area.cols + local_x) } /// Clears the leading glyph that covers a position. fn clear_glyph_at(&mut self, x: usize, y: usize) { if self.index(x, y).is_none() { return; } let mut lead = x; while lead > self.area.x { let Some(cell) = self.get(lead, y) else { break; }; if !cell.is_continuation() { break; } lead -= 1; } let width = self.get(lead, y).map_or(1, |cell| cell.width().max(1)); for dx in 0..width { self.set_exact(lead + dx, y, Cell::blank()); } } } /// Normalizes arbitrary input into one terminal glyph. fn normalize_glyph(input: &str) -> CellGlyph { let mut chars = input.chars(); let Some(first) = chars.next() else { return CellGlyph::Blank; }; if first.is_control() { return CellGlyph::Blank; } if first.is_ascii() { return ascii_glyph(first); } if !matches!(chars.clone().next(), Some('\u{fe0f}' | '\u{fe0e}')) { return normalize_char(first); } let mut glyph = String::from(first); if let Some(second @ ('\u{fe0f}' | '\u{fe0e}')) = chars.next() { glyph.push(second); for ch in chars { if !matches!(ch, '\u{fe0f}' | '\u{fe0e}') { break; } glyph.push(ch); } } if glyph.width() == 0 { CellGlyph::Blank } else { CellGlyph::Grapheme(glyph) } } /// Normalizes one character into one terminal glyph. fn normalize_char(ch: char) -> CellGlyph { if ch.is_control() || char_width(ch) == 0 { CellGlyph::Blank } else if ch.is_ascii() { ascii_glyph(ch) } else { CellGlyph::Unicode(ch) } } /// Normalizes one non-control ASCII character. fn ascii_glyph(ch: char) -> CellGlyph { if ch == ' ' { CellGlyph::Blank } else { CellGlyph::Ascii(ch as u8) } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; #[test] fn cell_normalizes_to_one_terminal_glyph() { let style = Style::new(crate::Color::Red); let cell = Cell::from_glyph("ab", style); let control = Cell::from_glyph("\n", style); assert_eq!(cell.glyph(), "a"); assert_eq!(cell.style(), style); assert_eq!(control.glyph(), " "); assert!(!cell.is_continuation()); } #[test] fn cell_uses_inline_storage_for_blank_and_ascii_glyphs() { let style = Style::new(crate::Color::Blue); assert!(matches!(Cell::blank().glyph, CellGlyph::Blank)); assert!(matches!( Cell::from_glyph(" ", style).glyph, CellGlyph::Blank )); assert!(matches!( Cell::from_glyph("x", style).glyph, CellGlyph::Ascii(b'x') )); assert!(matches!( Cell::from_glyph("╭", style).glyph, CellGlyph::Unicode('╭') )); assert!(matches!( Cell::from_glyph("❤️", style).glyph, CellGlyph::Grapheme(glyph) if glyph == "❤️" )); assert!(matches!( Cell::from_glyph("λ", style).glyph, CellGlyph::Unicode('λ') )); } #[test] fn buffer_writes_plain_and_styled_text() { let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 2)); buffer.set_str(1, 0, "hi", Style::default()); buffer.set_line(0, 1, &Line::new("ok")); assert_eq!(buffer.lines(), vec![" hi ", "ok "]); } #[test] fn styled_line_preserves_cell_styles() { let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 1)); buffer.set_str(0, 0, "r", Style::new(crate::Color::Red)); buffer.set_str(1, 0, "b", Style::new(crate::Color::Blue)); let line = buffer.styled_line(0); assert_eq!(line.to_string(), "rb "); assert_eq!(line.labels()[0].paint.style().fg_color(), crate::Color::Red); assert_eq!( line.labels()[1].paint.style().fg_color(), crate::Color::Blue ); } #[test] fn ascii_text_clears_wide_glyph_boundaries() { let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 1)); buffer.set_str(0, 0, "🍍🍍", Style::default()); buffer.set_str(1, 0, "ab", Style::default()); assert_eq!(buffer.line(0), " ab "); } #[test] fn new_buffer_starts_dirty_and_reset_clears_dirty_marks() { let mut buffer = Buffer::empty(Rect::new(2, 3, 4, 2)); let runs = buffer.dirty_runs(); assert_eq!(runs.len(), 2); assert_eq!(runs[0].x, 2); assert_eq!(runs[0].y, 3); assert_eq!(runs[0].cells.len(), 4); buffer.reset_dirty(); assert!(buffer.dirty_runs().is_empty()); } #[test] fn buffer_tracks_dirty_runs() { let mut previous = Buffer::empty(Rect::new(0, 0, 6, 1)); previous.reset_dirty(); let mut next = previous.clone(); next.set_str(1, 0, "abc", Style::default()); let runs = next.diff(&previous); assert_eq!(runs.len(), 1); assert_eq!(runs[0].x, 1); assert_eq!(runs[0].cells.len(), 3); } #[test] fn setting_same_cell_after_reset_does_not_mark_dirty() { let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 1)); buffer.reset_dirty(); buffer.set(0, 0, Cell::blank()); assert!(buffer.dirty_runs().is_empty()); } #[test] fn fill_clips_to_buffer_area_and_out_of_bounds_writes_are_ignored() { let mut buffer = Buffer::empty(Rect::new(1, 1, 4, 2)); buffer.reset_dirty(); buffer.fill( Rect::new(3, 0, 4, 4), Cell::new('x', Style::new(crate::Color::Blue)), ); buffer.set(0, 0, Cell::new('z', Style::default())); assert_eq!(buffer.lines(), vec![" xx", " xx"]); assert_eq!(buffer.dirty_runs().len(), 2); } #[test] fn resize_reallocates_cells_and_marks_new_area_dirty() { let mut buffer = Buffer::empty(Rect::new(0, 0, 2, 1)); buffer.reset_dirty(); buffer.resize(Rect::new(0, 0, 3, 2)); assert_eq!(buffer.size(), Size::new(3, 2)); assert_eq!(buffer.lines(), vec![" ", " "]); assert_eq!(buffer.dirty_runs().len(), 2); } #[test] fn wide_glyphs_occupy_continuation_cells_without_extra_text() { let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1)); buffer.reset_dirty(); buffer.set_str(0, 0, "🍍a", Style::default()); assert_eq!(buffer.line(0), "🍍a "); assert_eq!(buffer.get(0, 0).unwrap().glyph(), "🍍"); assert!(buffer.get(1, 0).unwrap().is_continuation()); assert_eq!(buffer.get(2, 0).unwrap().glyph(), "a"); assert_eq!(buffer.dirty_runs()[0].cells.len(), 3); } #[test] fn overwriting_inside_wide_glyph_clears_the_leading_cell() { let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1)); buffer.set_str(0, 0, "🍍x", Style::default()); buffer.reset_dirty(); buffer.set_str(1, 0, "a", Style::default()); assert_eq!(buffer.line(0), " ax "); assert_eq!(buffer.get(0, 0).unwrap().glyph(), " "); assert_eq!(buffer.get(1, 0).unwrap().glyph(), "a"); assert!(!buffer.get(1, 0).unwrap().is_continuation()); } #[test] fn wide_glyph_that_cannot_fit_is_not_written() { let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 1)); buffer.set_str(2, 0, "🍍", Style::default()); assert_eq!(buffer.line(0), " "); } #[test] fn wide_fill_tiles_by_visual_width() { let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1)); buffer.fill(buffer.area(), Cell::new('🍍', Style::default())); assert_eq!(buffer.line(0), "🍍🍍 "); assert!(buffer.get(1, 0).unwrap().is_continuation()); assert!(buffer.get(3, 0).unwrap().is_continuation()); } #[test] fn line_returns_empty_string_for_out_of_bounds_rows() { let buffer = Buffer::empty(Rect::new(0, 0, 2, 1)); assert_eq!(buffer.line(99), ""); } }