use crossterm::style::Color;
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub enum Intensity {
#[default]
Normal,
Bold,
Dim,
}
#[derive(Clone, Copy, PartialEq, Debug, Default)]
pub struct CellStyle {
pub intensity: Intensity,
pub underline: bool,
pub italic: bool,
pub reverse: bool,
pub strikethrough: bool,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Cell {
pub symbol: char,
pub fg: Color,
pub bg: Color,
pub style: CellStyle,
pub alpha: f32,
}
impl Default for Cell {
fn default() -> Self {
Cell {
symbol: ' ',
fg: Color::Reset,
bg: Color::Reset,
style: CellStyle::default(),
alpha: 0.0,
}
}
}
#[derive(Clone, Debug)]
pub struct Buffer {
pub width: u16,
pub height: u16,
cells: Vec<Cell>,
}
impl Buffer {
pub fn new(width: u16, height: u16) -> Self {
Buffer {
width,
height,
cells: vec![Cell::default(); width as usize * height as usize],
}
}
pub fn get(&self, x: u16, y: u16) -> &Cell {
&self.cells[self.index(x, y)]
}
pub fn set(&mut self, x: u16, y: u16, cell: Cell) {
let idx = self.index(x, y);
self.cells[idx] = cell;
}
pub fn blit(&self, dest: &mut Buffer, x: u16, y: u16) {
for row in 0..self.height {
let Some(dy) = y.checked_add(row) else { break };
if dy >= dest.height {
break;
}
for col in 0..self.width {
let Some(dx) = x.checked_add(col) else { break };
if dx >= dest.width {
break;
}
dest.set(dx, dy, self.get(col, row).clone());
}
}
}
fn index(&self, x: u16, y: u16) -> usize {
debug_assert!(
x < self.width && y < self.height,
"index ({x}, {y}) out of bounds for a {}x{} buffer",
self.width,
self.height
);
y as usize * self.width as usize + x as usize
}
}
#[derive(Debug, PartialEq)]
pub struct CellDiff {
pub x: u16,
pub y: u16,
pub cell: Cell,
}
pub fn diff(prev: &Buffer, next: &Buffer) -> Vec<CellDiff> {
let mut out = Vec::new();
for y in 0..next.height {
for x in 0..next.width {
let n = next.get(x, y);
if n != prev.get(x, y) {
out.push(CellDiff {
x,
y,
cell: n.clone(),
});
}
}
}
out
}
#[derive(Clone, Debug)]
pub struct LayerStack {
layers: Vec<Buffer>,
}
impl LayerStack {
pub fn new(width: u16, height: u16) -> Self {
LayerStack {
layers: vec![Buffer::new(width, height)],
}
}
pub fn push_layer(&mut self) -> &mut Buffer {
let width = self.layers[0].width;
let height = self.layers[0].height;
self.layers.push(Buffer::new(width, height));
self.layers.last_mut().unwrap()
}
pub fn layer_mut(&mut self, index: usize) -> &mut Buffer {
&mut self.layers[index]
}
pub fn layer(&self, index: usize) -> &Buffer {
&self.layers[index]
}
pub fn layer_count(&self) -> usize {
self.layers.len()
}
pub fn composite(&self) -> Buffer {
if self.layers.len() == 1 {
let mut out = self.layers[0].clone();
let width = out.width;
let height = out.height;
for y in 0..height {
for x in 0..width {
out.set(x, y, normalize_alpha(out.get(x, y).clone()));
}
}
return out;
}
let width = self.layers[0].width;
let height = self.layers[0].height;
let mut out = Buffer::new(width, height);
for y in 0..height {
for x in 0..width {
out.set(x, y, composite_cell(&self.layers, x, y));
}
}
out
}
}
fn normalize_alpha(cell: Cell) -> Cell {
if cell.alpha <= 0.0 {
Cell::default()
} else {
Cell { alpha: 1.0, ..cell }
}
}
fn composite_cell(layers: &[Buffer], x: u16, y: u16) -> Cell {
let mut remaining = 1.0_f32;
let mut acc_weight = 0.0_f32;
let mut acc_fg = Color::Reset;
let mut acc_bg = Color::Reset;
let mut winner: Option<(char, CellStyle)> = None;
let mut first: Option<(char, CellStyle)> = None;
for layer in layers.iter().rev() {
if remaining <= 0.0 {
break;
}
let cell = layer.get(x, y);
if cell.alpha <= 0.0 {
continue;
}
let contribution = cell.alpha * remaining;
if first.is_none() {
first = Some((cell.symbol, cell.style));
}
if winner.is_none() && contribution >= 0.5 {
winner = Some((cell.symbol, cell.style));
}
acc_fg = if acc_weight <= 0.0 {
cell.fg
} else {
crate::easing::lerp_color(acc_fg, cell.fg, contribution / (acc_weight + contribution))
};
acc_bg = if acc_weight <= 0.0 {
cell.bg
} else {
crate::easing::lerp_color(acc_bg, cell.bg, contribution / (acc_weight + contribution))
};
acc_weight += contribution;
remaining *= 1.0 - cell.alpha;
}
match winner.or(first) {
None => Cell::default(),
Some((symbol, style)) => Cell {
symbol,
fg: acc_fg,
bg: acc_bg,
style,
alpha: 1.0,
},
}
}
impl std::ops::Deref for LayerStack {
type Target = Buffer;
fn deref(&self) -> &Buffer {
&self.layers[0]
}
}
impl std::ops::DerefMut for LayerStack {
fn deref_mut(&mut self) -> &mut Buffer {
&mut self.layers[0]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn intensity_default_is_normal() {
assert_eq!(Intensity::default(), Intensity::Normal);
}
#[test]
fn cell_style_default_intensity_is_normal() {
assert_eq!(CellStyle::default().intensity, Intensity::Normal);
}
#[test]
fn cell_default_style_equals_cell_style_default() {
assert_eq!(Cell::default().style, CellStyle::default());
}
#[test]
fn cells_identical_except_intensity_are_unequal() {
let cell1 = Cell::default();
let mut cell2 = Cell::default();
cell2.style.intensity = Intensity::Bold;
assert_ne!(cell1, cell2);
}
#[test]
fn bold_dim_and_normal_are_pairwise_distinct() {
assert_ne!(Intensity::Normal, Intensity::Bold);
assert_ne!(Intensity::Bold, Intensity::Dim);
assert_ne!(Intensity::Normal, Intensity::Dim);
}
#[test]
fn cell_default_alpha_is_zero() {
assert_eq!(Cell::default().alpha, 0.0);
}
#[test]
fn composite_blends_partial_alpha_between_two_layers() {
let mut stack = LayerStack::new(1, 1);
let base = Cell {
symbol: 'a',
fg: Color::Rgb { r: 0, g: 0, b: 0 },
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
stack.set(0, 0, base);
let top = Cell {
symbol: 'b',
fg: Color::Rgb {
r: 200,
g: 100,
b: 50,
},
bg: Color::Reset,
alpha: 0.5,
..Default::default()
};
stack.push_layer().set(0, 0, top);
let out = stack.composite();
assert_eq!(
out.get(0, 0).fg,
Color::Rgb {
r: 100,
g: 50,
b: 25
}
);
assert_eq!(out.get(0, 0).symbol, 'b'); assert_eq!(out.get(0, 0).alpha, 1.0);
}
#[test]
fn composite_blends_bg_partial_alpha_between_two_layers() {
let mut stack = LayerStack::new(1, 1);
let base = Cell {
symbol: 'a',
fg: Color::Reset,
bg: Color::Rgb { r: 0, g: 0, b: 0 },
alpha: 1.0,
..Default::default()
};
stack.set(0, 0, base);
let top = Cell {
symbol: 'b',
fg: Color::Reset,
bg: Color::Rgb {
r: 200,
g: 100,
b: 50,
},
alpha: 0.5,
..Default::default()
};
stack.push_layer().set(0, 0, top);
let out = stack.composite();
assert_eq!(
out.get(0, 0).bg,
Color::Rgb {
r: 100,
g: 50,
b: 25
}
);
assert_eq!(out.get(0, 0).symbol, 'b'); assert_eq!(out.get(0, 0).alpha, 1.0);
}
#[test]
fn composite_accumulates_correctly_across_three_partially_transparent_layers() {
let mut stack = LayerStack::new(1, 1);
let bottom_fg = Color::Rgb { r: 0, g: 0, b: 0 };
let mid_fg = Color::Rgb {
r: 100,
g: 100,
b: 100,
};
let top_fg = Color::Rgb {
r: 200,
g: 200,
b: 200,
};
stack.set(
0,
0,
Cell {
symbol: 'a',
fg: bottom_fg,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: 'b',
fg: mid_fg,
bg: Color::Reset,
alpha: 0.5,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: 'c',
fg: top_fg,
bg: Color::Reset,
alpha: 0.5,
..Default::default()
},
);
let out = stack.composite();
let expected_fg = {
let after_mid = crate::easing::lerp_color(top_fg, mid_fg, 0.25 / 0.75); crate::easing::lerp_color(after_mid, bottom_fg, 0.25 / 1.0) };
assert_eq!(out.get(0, 0).fg, expected_fg);
assert_eq!(out.get(0, 0).symbol, 'c'); }
#[test]
fn a_fully_opaque_layer_occludes_everything_beneath_it() {
let mut stack = LayerStack::new(1, 1);
stack.set(
0,
0,
Cell {
symbol: 'z',
fg: Color::Rgb { r: 255, g: 0, b: 0 },
bg: Color::Reset,
alpha: 1.0,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: 'y',
fg: Color::Rgb { r: 0, g: 255, b: 0 },
bg: Color::Reset,
alpha: 1.0,
..Default::default()
},
);
let out = stack.composite();
assert_eq!(out.get(0, 0).symbol, 'y');
assert_eq!(out.get(0, 0).fg, Color::Rgb { r: 0, g: 255, b: 0 });
}
#[test]
fn non_rgb_colors_fall_back_to_the_lerp_color_target_not_a_true_blend() {
let mut stack = LayerStack::new(1, 1);
stack.set(
0,
0,
Cell {
symbol: 'a',
fg: Color::Green,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: 'b',
fg: Color::Yellow,
bg: Color::Reset,
alpha: 0.5,
..Default::default()
},
);
let out = stack.composite();
assert_eq!(out.get(0, 0).fg, Color::Green);
}
#[test]
fn glyph_selection_uses_the_first_layer_to_reach_half_contribution() {
let mut stack = LayerStack::new(1, 1);
stack.set(
0,
0,
Cell {
symbol: 'a',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: 'b',
fg: Color::Reset,
bg: Color::Reset,
alpha: 0.5,
..Default::default()
},
);
let out = stack.composite();
assert_eq!(out.get(0, 0).symbol, 'b');
}
#[test]
fn glyph_selection_falls_back_to_the_topmost_contributor_when_none_reach_half() {
let mut stack = LayerStack::new(1, 1);
stack.set(
0,
0,
Cell {
symbol: 'a',
fg: Color::Reset,
bg: Color::Reset,
alpha: 0.3,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: 'b',
fg: Color::Reset,
bg: Color::Reset,
alpha: 0.3,
..Default::default()
},
);
let out = stack.composite();
assert_eq!(out.get(0, 0).symbol, 'b');
}
#[test]
fn new_buffer_is_filled_with_default_cells() {
let buf = Buffer::new(3, 2);
assert_eq!(buf.width, 3);
assert_eq!(buf.height, 2);
assert_eq!(*buf.get(0, 0), Cell::default());
assert_eq!(*buf.get(2, 1), Cell::default());
}
#[test]
fn set_then_get_returns_the_cell() {
let mut buf = Buffer::new(3, 2);
let cell = Cell {
symbol: 'x',
fg: crossterm::style::Color::Red,
bg: crossterm::style::Color::Reset,
alpha: 1.0,
..Default::default()
};
buf.set(1, 1, cell.clone());
assert_eq!(*buf.get(1, 1), cell);
}
#[test]
fn diff_returns_only_changed_cells() {
let prev = Buffer::new(2, 1);
let mut next = Buffer::new(2, 1);
let cell = Cell {
symbol: 'x',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
next.set(1, 0, cell.clone());
let diffs = diff(&prev, &next);
assert_eq!(diffs, vec![CellDiff { x: 1, y: 0, cell }]);
}
#[test]
fn diff_of_identical_buffers_is_empty() {
let a = Buffer::new(2, 2);
let b = Buffer::new(2, 2);
assert!(diff(&a, &b).is_empty());
}
#[test]
fn new_layer_stack_has_one_default_filled_base_layer() {
let mut stack = LayerStack::new(3, 2);
assert_eq!(*stack.layer_mut(0).get(0, 0), Cell::default());
assert_eq!(*stack.layer_mut(0).get(2, 1), Cell::default());
}
#[test]
fn push_layer_appends_a_same_dimension_default_filled_layer() {
let mut stack = LayerStack::new(3, 2);
let cell = Cell {
symbol: 'x',
fg: Color::Red,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
stack.push_layer().set(1, 1, cell.clone());
assert_eq!(*stack.layer_mut(1).get(1, 1), cell);
assert_eq!(*stack.layer_mut(0).get(1, 1), Cell::default());
}
#[test]
fn layer_stack_derefs_to_the_base_layer() {
let mut stack = LayerStack::new(3, 2);
let cell = Cell {
symbol: 'y',
fg: Color::Reset,
bg: Color::Red,
alpha: 1.0,
..Default::default()
};
stack.set(0, 1, cell.clone());
assert_eq!(*stack.get(0, 1), cell); assert_eq!(*stack.layer_mut(0).get(0, 1), cell); }
#[test]
fn composite_of_a_single_layer_stack_matches_that_layer() {
let mut stack = LayerStack::new(2, 2);
let cell = Cell {
symbol: 'z',
fg: Color::Green,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
stack.set(1, 0, cell.clone());
let out = stack.composite();
assert_eq!(*out.get(1, 0), cell);
assert_eq!(*out.get(0, 0), Cell::default());
assert_eq!(*out.get(0, 1), Cell::default());
assert_eq!(*out.get(1, 1), Cell::default());
}
#[test]
fn composite_of_a_single_layer_stack_normalizes_zero_alpha_to_default() {
let mut stack = LayerStack::new(1, 1);
stack.set(
0,
0,
Cell {
symbol: 'x',
fg: Color::Rgb { r: 1, g: 2, b: 3 },
bg: Color::Reset,
alpha: 0.0,
..Default::default()
},
);
let out = stack.composite();
assert_eq!(*out.get(0, 0), Cell::default());
}
#[test]
fn composite_of_a_single_layer_stack_forces_fractional_alpha_to_one() {
let mut stack = LayerStack::new(1, 1);
let cell = Cell {
symbol: 'x',
fg: Color::Rgb {
r: 10,
g: 20,
b: 30,
},
bg: Color::Reset,
alpha: 0.3,
..Default::default()
};
stack.set(0, 0, cell.clone());
let out = stack.composite();
assert_eq!(out.get(0, 0).symbol, cell.symbol);
assert_eq!(out.get(0, 0).fg, cell.fg);
assert_eq!(out.get(0, 0).bg, cell.bg);
assert_eq!(out.get(0, 0).style, cell.style);
assert_eq!(out.get(0, 0).alpha, 1.0);
}
#[test]
fn a_visually_blank_but_alpha_1_cell_occludes_what_is_beneath_it() {
let mut stack = LayerStack::new(1, 1);
stack.set(
0,
0,
Cell {
symbol: 'x',
fg: Color::Rgb {
r: 10,
g: 20,
b: 30,
},
bg: Color::Rgb {
r: 40,
g: 50,
b: 60,
},
alpha: 1.0,
..Default::default()
},
);
stack.push_layer().set(
0,
0,
Cell {
symbol: ' ',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
},
);
let out = stack.composite();
assert_eq!(out.get(0, 0).symbol, ' ');
assert_eq!(out.get(0, 0).fg, Color::Reset);
assert_eq!(out.get(0, 0).bg, Color::Reset);
}
#[test]
fn composite_early_exits_once_a_layer_reaches_full_opacity() {
let mut stack = LayerStack::new(3, 1);
let a = Cell {
symbol: 'a',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
let b = Cell {
symbol: 'b',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
let c = Cell {
symbol: 'c',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
stack.set(0, 0, a.clone()); stack.push_layer().set(1, 0, b.clone()); stack.push_layer().set(0, 0, c.clone());
let out = stack.composite();
assert_eq!(*out.get(0, 0), c); assert_eq!(*out.get(1, 0), b); assert_eq!(*out.get(2, 0), Cell::default()); }
#[test]
fn cloning_a_layer_stack_preserves_all_layers_not_just_the_base() {
let mut stack = LayerStack::new(2, 1);
let base_cell = Cell {
symbol: 'a',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
let top_cell = Cell {
symbol: 'b',
fg: Color::Blue,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
stack.set(0, 0, base_cell.clone()); stack.push_layer().set(1, 0, top_cell.clone()); stack.push_layer();
let mut cloned = stack.clone();
assert_eq!(cloned.layers.len(), 3);
assert_eq!(*cloned.layer_mut(0).get(0, 0), base_cell);
assert_eq!(*cloned.layer_mut(1).get(1, 0), top_cell);
let out = cloned.composite();
assert_eq!(*out.get(1, 0), top_cell);
assert_eq!(*out.get(0, 0), base_cell);
}
#[test]
fn layer_count_reflects_pushed_layers() {
let mut stack = LayerStack::new(2, 2);
assert_eq!(stack.layer_count(), 1);
stack.push_layer();
stack.push_layer();
assert_eq!(stack.layer_count(), 3);
}
#[test]
fn layer_gives_read_only_access_to_a_pushed_layer() {
let mut stack = LayerStack::new(2, 2);
let cell = Cell {
symbol: 'q',
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
};
stack.push_layer().set(0, 0, cell.clone());
assert_eq!(*stack.layer(1).get(0, 0), cell);
}
fn marked(symbol: char) -> Cell {
Cell {
symbol,
fg: Color::Reset,
bg: Color::Reset,
alpha: 1.0,
..Default::default()
}
}
fn filled(width: u16, height: u16, symbol: char) -> Buffer {
let mut buf = Buffer::new(width, height);
for y in 0..height {
for x in 0..width {
buf.set(x, y, marked(symbol));
}
}
buf
}
#[test]
fn blit_at_the_origin_copies_every_cell() {
let src = filled(2, 2, 'x');
let mut dest = Buffer::new(2, 2);
src.blit(&mut dest, 0, 0);
for y in 0..2 {
for x in 0..2 {
assert_eq!(*dest.get(x, y), marked('x'), "({x}, {y})");
}
}
}
#[test]
fn blit_places_the_sources_top_left_at_the_offset() {
let src = filled(2, 1, 'x');
let mut dest = Buffer::new(4, 3);
src.blit(&mut dest, 1, 2);
assert_eq!(*dest.get(1, 2), marked('x'));
assert_eq!(*dest.get(2, 2), marked('x'));
assert_eq!(*dest.get(0, 2), Cell::default());
assert_eq!(*dest.get(3, 2), Cell::default());
assert_eq!(*dest.get(1, 1), Cell::default());
}
#[test]
fn blit_writes_only_what_fits_when_the_source_overhangs() {
let src = filled(4, 4, 'x');
let mut dest = Buffer::new(3, 2);
src.blit(&mut dest, 1, 1);
assert_eq!(*dest.get(1, 1), marked('x'));
assert_eq!(*dest.get(2, 1), marked('x'));
assert_eq!(*dest.get(0, 0), Cell::default());
assert_eq!(*dest.get(0, 1), Cell::default());
}
#[test]
fn blit_past_the_right_edge_does_not_wrap_onto_the_next_row() {
let src = filled(2, 1, 'x');
let mut dest = Buffer::new(4, 3);
src.blit(&mut dest, 4, 0);
for y in 0..3 {
for x in 0..4 {
assert_eq!(
*dest.get(x, y),
Cell::default(),
"({x}, {y}) was written by an out-of-bounds blit"
);
}
}
}
#[test]
fn blit_partly_past_the_right_edge_clips_the_overhanging_columns() {
let src = filled(3, 1, 'x');
let mut dest = Buffer::new(4, 3);
src.blit(&mut dest, 3, 0);
assert_eq!(*dest.get(3, 0), marked('x'));
for x in 0..4 {
assert_eq!(*dest.get(x, 1), Cell::default(), "(({x}, 1))");
}
}
#[test]
fn blit_past_the_bottom_edge_writes_nothing() {
let src = filled(2, 2, 'x');
let mut dest = Buffer::new(4, 2);
src.blit(&mut dest, 0, 2);
for y in 0..2 {
for x in 0..4 {
assert_eq!(*dest.get(x, y), Cell::default(), "({x}, {y})");
}
}
}
#[test]
fn blit_near_u16_max_does_not_overflow_the_offset_arithmetic() {
let src = filled(4, 4, 'x');
let mut dest = Buffer::new(4, 4);
src.blit(&mut dest, u16::MAX - 1, u16::MAX - 1);
assert_eq!(*dest.get(0, 0), Cell::default());
}
#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "out of bounds")]
fn set_with_an_x_past_the_width_panics_instead_of_wrapping() {
let mut buf = Buffer::new(4, 3);
let mut cell = buf.get(0, 0).clone();
cell.symbol = 'X';
buf.set(5, 0, cell);
}
#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "out of bounds")]
fn get_with_an_x_past_the_width_panics_instead_of_reading_a_neighbour() {
let buf = Buffer::new(4, 3);
let _ = buf.get(5, 0);
}
#[test]
fn set_at_the_last_valid_cell_still_works() {
let mut buf = Buffer::new(4, 3);
let mut cell = buf.get(0, 0).clone();
cell.symbol = 'Z';
buf.set(3, 2, cell);
assert_eq!(buf.get(3, 2).symbol, 'Z');
}
}