use crate::buffer::Cell;
use crate::runtime::{
CrosstermInput, FrameContext, InputEvent, InputSource, InputState, Key,
KeyPhase,
};
use crate::session::SessionColors;
use crossterm::{QueueableCommand, cursor, style, terminal};
use std::{
io::{BufWriter, Result, Write},
time::{Duration, Instant},
};
pub const MIN_EFFECT_SIZE: u16 = 6;
pub const MIN_SPEED: f32 = 0.05;
pub const MAX_SPEED: f32 = 8.0;
pub const SPEED_STEP: f32 = 0.1;
pub const MIN_IDLE_FPS: f32 = 1.0;
pub const MAX_IDLE_FPS: f32 = 30.0;
pub const DEFAULT_IDLE_FPS: f32 = 20.0;
pub fn bounded_f32(value: f32, default: f32, min: f32, max: f32) -> f32 {
if value.is_finite() {
value.clamp(min, max)
} else {
default
}
}
const MAX_FRAME_DELTA: Duration = Duration::from_millis(50);
const CHECK_MODE_POLL: Duration = Duration::from_millis(10);
pub type EffectRng = rand::rngs::StdRng;
pub const DEFAULT_SEED: u64 = 42;
pub fn seeded_rng(seed: u64, salt: &str) -> EffectRng {
use rand::SeedableRng;
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in salt.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
EffectRng::seed_from_u64(seed ^ hash)
}
pub fn normalize_effect_size(size: (u16, u16)) -> (u16, u16) {
(size.0.max(MIN_EFFECT_SIZE), size.1.max(MIN_EFFECT_SIZE))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RuntimeOptions {
pub speed: f32,
pub throttle_when_unfocused: bool,
pub idle_fps: f32,
pub colors: SessionColors,
}
impl Default for RuntimeOptions {
fn default() -> Self {
Self {
speed: 1.0,
throttle_when_unfocused: true,
idle_fps: DEFAULT_IDLE_FPS,
colors: SessionColors::default(),
}
}
}
impl RuntimeOptions {
pub fn new(speed: f32) -> Self {
Self {
speed: bounded_f32(speed, 1.0, MIN_SPEED, MAX_SPEED),
..Self::default()
}
}
pub fn with_focus_policy(
mut self,
throttle_when_unfocused: bool,
idle_fps: f32,
) -> Self {
self.throttle_when_unfocused = throttle_when_unfocused;
self.idle_fps =
bounded_f32(idle_fps, DEFAULT_IDLE_FPS, MIN_IDLE_FPS, MAX_IDLE_FPS);
self
}
pub fn with_colors(mut self, colors: SessionColors) -> Self {
self.colors = colors;
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct TickClock {
accumulator: f32,
}
impl TickClock {
pub const QUANTUM: f32 = 1.0 / 60.0;
pub const MAX_STEPS: usize = 4;
pub fn advance(&mut self, delta: Duration, speed: f32) -> usize {
self.accumulator +=
delta.as_secs_f32() * bounded_f32(speed, 1.0, MIN_SPEED, MAX_SPEED);
let mut steps = 0;
while self.accumulator + f32::EPSILON >= Self::QUANTUM
&& steps < Self::MAX_STEPS
{
self.accumulator -= Self::QUANTUM;
steps += 1;
}
if steps == Self::MAX_STEPS {
self.accumulator = 0.0;
}
steps
}
}
pub trait FrameTarget {
fn effect(&mut self) -> &mut dyn TerminalEffect;
fn on_global_key(&mut self, _key: Key, _phase: KeyPhase) -> bool {
false
}
fn on_frame(&mut self, _delta: Duration, _cells: &mut [(usize, usize, Cell)]) {}
fn on_resize(&mut self, _width: u16, _height: u16) {}
}
pub struct SingleEffect<'a> {
effect: &'a mut dyn TerminalEffect,
}
impl<'a> SingleEffect<'a> {
pub fn new(effect: &'a mut dyn TerminalEffect) -> Self {
Self { effect }
}
}
impl FrameTarget for SingleEffect<'_> {
fn effect(&mut self) -> &mut dyn TerminalEffect {
self.effect
}
fn on_resize(&mut self, width: u16, height: u16) {
self.effect.update_size(width, height);
}
}
pub trait TerminalEffect {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)>;
fn update(&mut self);
fn update_size(&mut self, width: u16, height: u16);
fn reset(&mut self);
fn handle_input(&mut self, _event: &InputEvent) {}
fn get_diff_with_context(
&mut self,
_context: &FrameContext,
) -> Vec<(usize, usize, Cell)> {
self.get_diff()
}
fn update_with_context(&mut self, _context: &FrameContext) {
self.update();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct AttributesOn {
bold: bool,
}
impl AttributesOn {
fn of(attr: style::Attribute) -> Self {
Self {
bold: matches!(attr, style::Attribute::Bold),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ActiveStyle {
fg: style::Color,
bg: style::Color,
attributes: AttributesOn,
}
impl Default for ActiveStyle {
fn default() -> Self {
Self {
fg: style::Color::Reset,
bg: style::Color::Reset,
attributes: AttributesOn::default(),
}
}
}
fn session_style(colors: SessionColors) -> ActiveStyle {
ActiveStyle {
fg: colors.foreground,
bg: colors.background,
attributes: AttributesOn::default(),
}
}
fn resolve(cell: style::Color, session: style::Color) -> style::Color {
if cell == style::Color::Reset {
session
} else {
cell
}
}
fn reassert_session_colors<W: Write>(
out: &mut W,
colors: SessionColors,
) -> Result<()> {
if colors.is_default() {
return Ok(());
}
out.queue(style::SetForegroundColor(colors.foreground))?;
out.queue(style::SetBackgroundColor(colors.background))?;
Ok(())
}
pub fn write_cells<W: Write>(
out: &mut W,
size: (u16, u16),
cells: &[(usize, usize, Cell)],
colors: SessionColors,
) -> Result<()> {
let (max_x, max_y) = (size.0 as usize, size.1 as usize);
let mut cursor: Option<(u16, u16)> = None;
let mut active: Option<ActiveStyle> = None;
for &(x, y, cell) in cells {
if x >= max_x || y >= max_y {
continue;
}
let column = x as u16;
let row = y as u16;
if cursor != Some((column, row)) {
out.queue(cursor::MoveTo(column, row))?;
}
let wanted = ActiveStyle {
fg: resolve(cell.color, colors.foreground),
bg: resolve(cell.bg, colors.background),
attributes: AttributesOn::of(cell.attr),
};
if active.is_none() {
out.queue(style::ResetColor)?;
reassert_session_colors(out, colors)?;
}
if active != Some(wanted) {
let mut previous = active.unwrap_or_else(|| session_style(colors));
if previous.attributes != wanted.attributes {
out.queue(style::ResetColor)?;
if wanted.attributes.bold {
out.queue(style::SetAttribute(style::Attribute::Bold))?;
}
previous = session_style(colors);
reassert_session_colors(out, colors)?;
}
if previous.fg != wanted.fg {
out.queue(style::SetForegroundColor(wanted.fg))?;
}
if previous.bg != wanted.bg {
out.queue(style::SetBackgroundColor(wanted.bg))?;
}
active = Some(wanted);
}
out.queue(style::Print(cell.symbol))?;
cursor = Some((column + 1, row));
}
if active.is_some() {
out.queue(style::ResetColor)?;
reassert_session_colors(out, colors)?;
}
Ok(())
}
pub fn run_loop_with_source_and_size_and_target<W, S, T>(
stdout: &mut W,
target: &mut T,
iterations: Option<usize>,
source: &mut S,
initial_size: (u16, u16),
options: RuntimeOptions,
) -> Result<f64>
where
W: Write,
S: InputSource,
T: FrameTarget + ?Sized,
{
run_loop_with_source_and_size_and_options(
stdout,
target,
iterations,
source,
initial_size,
options,
)
}
pub fn process_input<TE>(effect: &mut TE) -> Result<bool>
where
TE: TerminalEffect,
{
let mut size = terminal::size()?;
let mut input = InputState::default();
input.set_size(size);
let mut source = CrosstermInput;
let mut speed = 1.0;
let mut target = SingleEffect::new(effect);
process_runtime_events(
&mut target,
&mut source,
&mut input,
&mut size,
&mut speed,
CHECK_MODE_POLL,
)
}
pub fn run_loop<W>(
stdout: &mut W,
effect: &mut dyn TerminalEffect,
iterations: Option<usize>,
) -> Result<f64>
where
W: Write,
{
let mut source = CrosstermInput;
let size = terminal::size()?;
run_loop_with_source_and_size(stdout, effect, iterations, &mut source, size)
}
pub fn run_loop_with_options<W>(
stdout: &mut W,
effect: &mut dyn TerminalEffect,
iterations: Option<usize>,
options: RuntimeOptions,
) -> Result<f64>
where
W: Write,
{
let mut source = CrosstermInput;
let size = terminal::size()?;
let mut target = SingleEffect::new(effect);
run_loop_with_source_and_size_and_options(
stdout,
&mut target,
iterations,
&mut source,
size,
options,
)
}
pub fn run_loop_with_source<W, S>(
stdout: &mut W,
effect: &mut dyn TerminalEffect,
iterations: Option<usize>,
source: &mut S,
) -> Result<f64>
where
W: Write,
S: InputSource,
{
let size = terminal::size()?;
run_loop_with_source_and_size(stdout, effect, iterations, source, size)
}
pub fn run_loop_with_source_and_size<W, S>(
stdout: &mut W,
effect: &mut dyn TerminalEffect,
iterations: Option<usize>,
source: &mut S,
initial_size: (u16, u16),
) -> Result<f64>
where
W: Write,
S: InputSource,
{
let mut target = SingleEffect::new(effect);
run_loop_with_source_and_size_and_options(
stdout,
&mut target,
iterations,
source,
initial_size,
RuntimeOptions::default(),
)
}
pub fn run_loop_with_target<W, T>(
stdout: &mut W,
target: &mut T,
iterations: Option<usize>,
options: RuntimeOptions,
) -> Result<f64>
where
W: Write,
T: FrameTarget + ?Sized,
{
let mut source = CrosstermInput;
let size = terminal::size()?;
run_loop_with_source_and_size_and_options(
stdout,
target,
iterations,
&mut source,
size,
options,
)
}
pub fn run_loop_with_source_and_size_and_options<W, S, T>(
stdout: &mut W,
target: &mut T,
iterations: Option<usize>,
source: &mut S,
initial_size: (u16, u16),
options: RuntimeOptions,
) -> Result<f64>
where
W: Write,
S: InputSource,
T: FrameTarget + ?Sized,
{
if iterations == Some(0) {
return Ok(0.0);
}
let mut size = (initial_size.0.max(1), initial_size.1.max(1));
let mut input = InputState::default();
input.set_size(size);
let effect_size = normalize_effect_size(size);
if effect_size != size {
target.on_resize(effect_size.0, effect_size.1);
target.effect().reset();
}
let started_at = Instant::now();
let mut previous_frame = started_at;
let mut frame = 0u64;
let mut is_running = true;
let mut frames_per_second = 0.0;
let mut speed = bounded_f32(options.speed, 1.0, MIN_SPEED, MAX_SPEED);
let mut tick_clock = TickClock::default();
let active_frame_duration = Duration::from_secs_f64(1.0 / 60.0);
let idle_frame_duration = Duration::from_secs_f64(
1.0 / f64::from(bounded_f32(
options.idle_fps,
DEFAULT_IDLE_FPS,
MIN_IDLE_FPS,
MAX_IDLE_FPS,
)),
);
let mut next_frame_at = started_at;
let mut buffered_stdout = BufWriter::new(stdout);
while is_running {
let frame_started_at = Instant::now();
let delta = frame_started_at
.saturating_duration_since(previous_frame)
.min(MAX_FRAME_DELTA);
let elapsed = frame_started_at.duration_since(started_at);
previous_frame = frame_started_at;
input.begin_frame();
if !process_runtime_events(
target,
source,
&mut input,
&mut size,
&mut speed,
Duration::ZERO,
)? {
break;
}
let focused = !options.throttle_when_unfocused || input.is_focused();
let context = FrameContext::new(size, frame, elapsed, delta, input.clone());
let mut diff = target.effect().get_diff_with_context(&context);
target.on_frame(delta, &mut diff);
write_cells(&mut buffered_stdout, size, &diff, options.colors)?;
buffered_stdout.flush()?;
if (speed - 1.0).abs() < f32::EPSILON {
target.effect().update_with_context(&context);
} else {
let steps = tick_clock.advance(delta, speed);
let mut tick_context = context.clone();
tick_context.delta = Duration::from_secs_f64(TickClock::QUANTUM as f64);
for _ in 0..steps {
target.effect().update_with_context(&tick_context);
}
}
next_frame_at += if focused {
active_frame_duration
} else {
idle_frame_duration
};
let now = Instant::now();
if next_frame_at <= now {
next_frame_at = now;
} else {
std::thread::sleep(next_frame_at - now);
}
let measured_duration =
frame_started_at.elapsed().as_secs_f64().max(f64::EPSILON);
frames_per_second = (frames_per_second + 1.0 / measured_duration) / 2.0;
frame += 1;
if iterations.is_some_and(|limit| frame as usize >= limit) {
is_running = false;
}
}
Ok(frames_per_second)
}
fn process_runtime_events<S, T>(
target: &mut T,
source: &mut S,
input: &mut InputState,
size: &mut (u16, u16),
speed: &mut f32,
poll_timeout: Duration,
) -> Result<bool>
where
S: InputSource,
T: FrameTarget + ?Sized,
{
let events = source.poll(poll_timeout)?;
if events.iter().any(is_quit_event) {
return Ok(false);
}
let last_resize = events.iter().rev().find_map(|event| match event {
InputEvent::Resize { size } => Some(*size),
_ => None,
});
if let Some(new_size) = last_resize {
*size = (new_size.0.max(1), new_size.1.max(1));
input.set_size(*size);
let effect_size = normalize_effect_size(*size);
target.on_resize(effect_size.0, effect_size.1);
target.effect().reset();
}
for event in events {
if matches!(event, InputEvent::Resize { .. }) {
continue;
}
input.apply(event);
if let InputEvent::Key { key, phase } = event
&& matches!(phase, KeyPhase::Pressed | KeyPhase::Repeated)
{
match key {
Key::Char('+') | Key::Char('=') => {
*speed = (*speed + SPEED_STEP).min(MAX_SPEED);
continue;
}
Key::Char('-') => {
*speed = (*speed - SPEED_STEP).max(MIN_SPEED);
continue;
}
key if target.on_global_key(key, phase) => continue,
_ => {}
}
}
if !matches!(event, InputEvent::Ignored) {
target.effect().handle_input(&event);
}
}
Ok(true)
}
fn is_quit_event(event: &InputEvent) -> bool {
match event {
InputEvent::Quit => true,
InputEvent::Key { key, phase } => {
matches!(phase, KeyPhase::Pressed | KeyPhase::Repeated)
&& matches!(key, Key::Char('q') | Key::Escape | Key::CtrlC)
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::style::Color;
fn cell(symbol: char) -> Cell {
Cell::new(symbol, Color::Red, style::Attribute::Bold)
}
fn count_moves(out: &str) -> usize {
out.split("\u{1b}[").filter(|seq| seq.contains('H')).count()
}
fn count_resets(out: &str) -> usize {
out.matches("\u{1b}[0m").count()
}
fn encoded(size: (u16, u16), cells: &[(usize, usize, Cell)]) -> String {
encoded_with(size, cells, SessionColors::default())
}
fn encoded_with(
size: (u16, u16),
cells: &[(usize, usize, Cell)],
colors: SessionColors,
) -> String {
let mut out: Vec<u8> = Vec::new();
write_cells(&mut out, size, cells, colors)
.expect("writing to a Vec cannot fail");
String::from_utf8(out).expect("crossterm emits utf8")
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Painted {
symbol: char,
fg: Color,
bg: Color,
bold: bool,
}
struct Terminal {
width: usize,
height: usize,
painted: Vec<Painted>,
cursor: (usize, usize),
fg: Color,
bg: Color,
bold: bool,
}
impl Terminal {
fn new(width: usize, height: usize) -> Self {
let blank = Painted {
symbol: ' ',
fg: Color::Reset,
bg: Color::Reset,
bold: false,
};
Self {
width,
height,
painted: vec![blank; width * height],
cursor: (0, 0),
fg: Color::Reset,
bg: Color::Reset,
bold: false,
}
}
fn replay(&mut self, out: &str) {
let mut chars = out.chars().peekable();
while let Some(c) = chars.next() {
if c != '\u{1b}' {
self.draw(c);
continue;
}
assert_eq!(chars.next(), Some('['), "expected a CSI sequence");
let mut sequence = String::new();
for c in chars.by_ref() {
if c.is_ascii_alphabetic() {
self.control(&sequence, c);
break;
}
sequence.push(c);
}
}
}
fn control(&mut self, sequence: &str, final_byte: char) {
let parts: Vec<&str> = sequence.split(';').collect();
let numbers: Vec<u8> = parts
.iter()
.map(|part| part.parse::<u8>().unwrap_or(0))
.collect();
match final_byte {
'H' => {
let row =
numbers.first().copied().unwrap_or(1).max(1) as usize - 1;
let column =
numbers.get(1).copied().unwrap_or(1).max(1) as usize - 1;
self.cursor = (row, column);
}
'm' => self.select_graphic_rendition(&numbers),
other => panic!("the encoder emitted an unhandled escape: {other}"),
}
}
fn select_graphic_rendition(&mut self, numbers: &[u8]) {
let mut index = 0;
while index < numbers.len() {
match numbers[index] {
0 => {
self.fg = Color::Reset;
self.bg = Color::Reset;
self.bold = false;
index += 1;
}
1 => {
self.bold = true;
index += 1;
}
22 => {
self.bold = false;
index += 1;
}
39 => {
self.fg = Color::Reset;
index += 1;
}
49 => {
self.bg = Color::Reset;
index += 1;
}
38 | 48 => {
let target = numbers[index];
let color = match numbers.get(index + 1).copied() {
Some(2) => Color::Rgb {
r: numbers[index + 2],
g: numbers[index + 3],
b: numbers[index + 4],
},
Some(5) => from_ansi_index(numbers[index + 2]),
other => panic!(
"unexpected colour encoding {other:?} in {numbers:?}"
),
};
if target == 38 {
self.fg = color;
} else {
self.bg = color;
}
index += if numbers[index + 1] == 2 { 5 } else { 3 };
}
other => panic!("unhandled SGR parameter {other}"),
}
}
}
fn draw(&mut self, symbol: char) {
let (row, column) = self.cursor;
if row < self.height && column < self.width {
self.painted[row * self.width + column] = Painted {
symbol,
fg: self.fg,
bg: self.bg,
bold: self.bold,
};
}
self.cursor = (row, column + 1);
}
fn at(&self, x: usize, y: usize) -> Painted {
self.painted[y * self.width + x]
}
fn in_session(width: usize, height: usize, colors: SessionColors) -> Self {
let mut terminal = Self::new(width, height);
terminal.fg = colors.foreground;
terminal.bg = colors.background;
terminal
}
}
fn from_ansi_index(index: u8) -> Color {
const TABLE: [Color; 16] = [
Color::Black, Color::DarkRed, Color::DarkGreen, Color::DarkYellow, Color::DarkBlue, Color::DarkMagenta, Color::DarkCyan, Color::Grey, Color::DarkGrey, Color::Red, Color::Green, Color::Yellow, Color::Blue, Color::Magenta, Color::Cyan, Color::White, ];
TABLE
.get(index as usize)
.copied()
.unwrap_or(Color::AnsiValue(index))
}
fn painted(size: (u16, u16), cells: &[(usize, usize, Cell)]) -> Terminal {
let out = encoded(size, cells);
let mut terminal = Terminal::new(size.0 as usize, size.1 as usize);
terminal.replay(&out);
terminal
}
fn rgb(r: u8, g: u8, b: u8) -> Color {
Color::Rgb { r, g, b }
}
#[test]
fn every_cell_of_a_uniform_run_lands_in_its_own_colour() {
let run: Vec<(usize, usize, Cell)> = (0..8)
.map(|x| {
(
x,
0,
Cell::new('#', rgb(200, 30, 30), style::Attribute::Bold),
)
})
.collect();
let terminal = painted((20, 4), &run);
for x in 0..8 {
let cell = terminal.at(x, 0);
assert_eq!(cell.symbol, '#', "cell {x} has no glyph");
assert_eq!(
cell.fg,
rgb(200, 30, 30),
"cell {x} was painted {:?}, not the colour it asked for -- the \
style did not survive from the previous cell",
cell.fg
);
assert!(cell.bold, "cell {x} lost its bold");
}
}
#[test]
fn a_run_of_attribute_reset_cells_keeps_its_colour() {
let run: Vec<(usize, usize, Cell)> = (0..8)
.map(|x| {
(
x,
0,
Cell::new('x', rgb(10, 90, 200), style::Attribute::Reset),
)
})
.collect();
let terminal = painted((20, 4), &run);
for x in 0..8 {
assert_eq!(
terminal.at(x, 0).fg,
rgb(10, 90, 200),
"cell {x} lost its colour: `Attribute::Reset` is SGR 0, which \
clears the colours too, so it has to be applied before the \
colour rather than instead of it"
);
}
}
#[test]
fn leaving_bold_does_not_take_the_colour_with_it() {
let cells = [
(
0usize,
0usize,
Cell::new('a', rgb(1, 2, 3), style::Attribute::Bold),
),
(1, 0, Cell::new('b', rgb(4, 5, 6), style::Attribute::Reset)),
(2, 0, Cell::new('c', rgb(7, 8, 9), style::Attribute::Reset)),
];
let terminal = painted((10, 3), &cells);
assert!(terminal.at(0, 0).bold, "the bold cell lost its bold");
assert!(!terminal.at(1, 0).bold, "bold survived into a plain cell");
assert_eq!(terminal.at(1, 0).fg, rgb(4, 5, 6));
assert_eq!(terminal.at(2, 0).fg, rgb(7, 8, 9));
}
#[test]
fn the_background_colour_reaches_the_terminal() {
let cells = [
(
0usize,
0usize,
Cell::with_bg(
crate::render::halfblock::UPPER,
rgb(255, 0, 0),
rgb(0, 0, 255),
style::Attribute::Reset,
),
),
(
1,
0,
Cell::with_bg(
crate::render::halfblock::UPPER,
rgb(255, 0, 0),
rgb(0, 255, 0),
style::Attribute::Reset,
),
),
(
2,
0,
Cell::with_bg(
crate::render::halfblock::UPPER,
rgb(255, 0, 0),
rgb(0, 255, 0),
style::Attribute::Reset,
),
),
];
let terminal = painted((10, 3), &cells);
assert_eq!(terminal.at(0, 0).fg, rgb(255, 0, 0));
assert_eq!(terminal.at(0, 0).bg, rgb(0, 0, 255));
assert_eq!(
terminal.at(1, 0).bg,
rgb(0, 255, 0),
"a changed background was dropped"
);
assert_eq!(terminal.at(2, 0).bg, rgb(0, 255, 0));
}
#[test]
fn a_cell_with_no_background_clears_one_that_was_set() {
let cells = [
(
0usize,
0usize,
Cell::with_bg(
'a',
rgb(9, 9, 9),
rgb(1, 1, 1),
style::Attribute::Reset,
),
),
(1, 0, Cell::new('b', rgb(9, 9, 9), style::Attribute::Reset)),
];
let terminal = painted((10, 3), &cells);
assert_eq!(terminal.at(1, 0).bg, Color::Reset, "a background leaked");
}
#[test]
fn a_pinned_background_survives_a_frame() {
let pinned = SessionColors {
background: Color::Rgb { r: 0, g: 0, b: 0 },
foreground: Color::Rgb {
r: 0xcc,
g: 0xcc,
b: 0xdd,
},
};
let cells = [
(
0usize,
0usize,
Cell::new('*', rgb(255, 255, 255), style::Attribute::Reset),
),
(
1,
0,
Cell::new('*', rgb(255, 255, 255), style::Attribute::Bold),
),
(
2,
0,
Cell::new('*', rgb(255, 255, 255), style::Attribute::Reset),
),
(
3,
0,
Cell::with_bg(
'x',
rgb(1, 2, 3),
rgb(200, 30, 30),
style::Attribute::Reset,
),
),
];
let mut out: Vec<u8> = Vec::new();
write_cells(&mut out, (4, 1), &cells, pinned)
.expect("writing to a Vec cannot fail");
let encoded = String::from_utf8(out).expect("crossterm emits utf8");
let mut terminal = Terminal::in_session(4, 1, pinned);
terminal.replay(&encoded);
for x in 0..3 {
assert_eq!(
terminal.at(x, 0).bg,
pinned.background,
"the pinned background was gone at ({x}, 0), so a cell that asked \
for no background of its own was drawn in the terminal's default"
);
}
assert_eq!(
terminal.at(3, 0).bg,
rgb(200, 30, 30),
"a cell's own background was overridden by the session pin"
);
}
#[test]
fn the_default_session_costs_nothing_extra() {
let cells = [
(
0usize,
0usize,
Cell::new('a', Color::Red, style::Attribute::Bold),
),
(1, 0, Cell::new('b', Color::Red, style::Attribute::Reset)),
(2, 0, Cell::new('c', Color::Blue, style::Attribute::Reset)),
];
let mut out: Vec<u8> = Vec::new();
write_cells(&mut out, (3, 1), &cells, SessionColors::default())
.expect("writing to a Vec cannot fail");
let encoded = String::from_utf8(out).expect("crossterm emits utf8");
assert!(
!encoded.contains("39m") && !encoded.contains("49m"),
"a default session emitted a colour reset, so the re-assert is not a \
no-op: {encoded:?}"
);
assert_eq!(
count_resets(&encoded),
4,
"expected the baseline, both attribute changes and the end-of-frame \
reset and nothing else: {encoded:?}"
);
}
#[test]
fn a_colour_is_not_dropped_when_only_the_attribute_changes() {
let ink = Color::Rgb { r: 1, g: 2, b: 3 };
let cells = [
(0usize, 0usize, Cell::new('x', ink, style::Attribute::Bold)),
(1, 0, Cell::new('y', ink, style::Attribute::Reset)),
(2, 0, Cell::new('z', ink, style::Attribute::Reset)),
];
let mut out: Vec<u8> = Vec::new();
write_cells(&mut out, (3, 1), &cells, SessionColors::default())
.expect("writing to a Vec cannot fail");
let encoded = String::from_utf8(out).expect("crossterm emits utf8");
let mut terminal = Terminal::new(3, 1);
terminal.replay(&encoded);
for x in 0..3 {
assert_eq!(
terminal.at(x, 0).fg,
ink,
"cell {x} lost its colour across the attribute change, so it was \
drawn in the terminal's default foreground"
);
}
}
#[test]
fn every_cell_of_a_mixed_frame_lands_exactly_as_specified() {
let styles = [
style::Attribute::Reset,
style::Attribute::Bold,
style::Attribute::NormalIntensity,
];
let colors = [
Color::Reset,
Color::Red,
Color::White,
Color::DarkGreen,
rgb(1, 2, 3),
rgb(250, 240, 230),
];
let cells: Vec<(usize, usize, Cell)> = (0..60)
.map(|i| {
let x = i % 10;
let y = i / 10;
let attr = styles[i % styles.len()];
let color = colors[i % colors.len()];
let cell = if i % 3 == 0 {
Cell::with_bg(
crate::render::halfblock::UPPER,
color,
colors[(i + 2) % colors.len()],
attr,
)
} else {
Cell::new('#', color, attr)
};
(x, y, cell)
})
.collect();
let terminal = painted((10, 6), &cells);
for (x, y, cell) in &cells {
let painted_cell = terminal.at(*x, *y);
assert_eq!(painted_cell.symbol, cell.symbol, "glyph at ({x},{y})");
assert_eq!(painted_cell.fg, cell.color, "foreground at ({x},{y})");
assert_eq!(painted_cell.bg, cell.bg, "background at ({x},{y})");
assert_eq!(
painted_cell.bold,
matches!(cell.attr, style::Attribute::Bold),
"bold at ({x},{y})"
);
}
}
#[test]
fn untouched_cells_keep_the_style_they_were_drawn_with() {
let first: Vec<(usize, usize, Cell)> = (0..10)
.map(|x| (x, 0, Cell::new('#', rgb(3, 4, 5), style::Attribute::Bold)))
.collect();
let second: Vec<(usize, usize, Cell)> =
vec![(4, 0, Cell::new('@', rgb(9, 9, 9), style::Attribute::Bold))];
let mut out = Vec::new();
write_cells(&mut out, (20, 3), &first, SessionColors::default())
.expect("vec write");
write_cells(&mut out, (20, 3), &second, SessionColors::default())
.expect("vec write");
let mut terminal = Terminal::new(20, 3);
terminal.replay(&String::from_utf8(out).expect("utf8"));
for x in 0..10 {
if x == 4 {
continue;
}
assert_eq!(terminal.at(x, 0).symbol, '#', "cell {x} was disturbed");
assert_eq!(
terminal.at(x, 0).fg,
rgb(3, 4, 5),
"cell {x} was disturbed"
);
}
assert_eq!(terminal.at(4, 0).symbol, '@');
assert_eq!(terminal.at(4, 0).fg, rgb(9, 9, 9));
}
#[test]
fn each_frame_ends_by_resetting_so_the_next_one_can_assume_it() {
let out = encoded((10, 3), &[(0, 0, cell('x'))]);
assert!(
out.ends_with("\u{1b}[0m"),
"the frame did not leave the terminal reset, got {out:?}"
);
}
#[test]
fn an_empty_diff_emits_nothing_at_all() {
assert_eq!(encoded((10, 10), &[]), "");
}
#[test]
fn writes_nothing_for_an_empty_diff() {
assert_eq!(encoded((10, 10), &[]), "");
}
#[test]
fn encodes_a_cursor_move_and_the_styled_glyph() {
let out = encoded((10, 10), &[(3, 4, cell('x'))]);
assert!(
out.contains("\u{1b}[5;4H"),
"expected a move to row 5 column 4, got {out:?}"
);
assert!(out.contains('x'), "expected the glyph, got {out:?}");
}
#[test]
fn drops_cells_outside_the_terminal() {
let cells = [
(0usize, 0usize, cell('a')),
(99, 0, cell('b')),
(0, 99, cell('c')),
];
let out = encoded((10, 10), &cells);
assert!(out.contains('a'), "the in-bounds cell was dropped");
assert!(!out.contains('b'), "a cell past the right edge was written");
assert!(
!out.contains('c'),
"a cell past the bottom edge was written"
);
}
#[test]
fn the_last_row_and_column_are_inside_the_terminal() {
let cells = [(9usize, 9usize, cell('z'))];
let out = encoded((10, 10), &cells);
assert!(
out.contains('z'),
"the last cell was treated as out of bounds"
);
}
#[test]
fn encodes_every_cell_in_a_dense_diff() {
let cells: Vec<(usize, usize, Cell)> =
(0..100).map(|i| (i % 10, i / 10, cell('#'))).collect();
let out = encoded((10, 10), &cells);
assert_eq!(out.matches('#').count(), 100);
}
#[test]
fn a_full_screen_diff_of_one_style_stays_within_budget() {
let cells: Vec<(usize, usize, Cell)> = (0..200 * 50)
.map(|i| (i % 200, i / 200, cell('#')))
.collect();
let out = encoded((200, 50), &cells);
assert_eq!(out.matches('#').count(), 200 * 50);
assert!(
out.len() < 200 * 50 * 2,
"a full-screen repaint of uniformly styled cells encoded to {} bytes, \
which is more than the two bytes per glyph it needs",
out.len()
);
assert_eq!(
count_moves(&out),
50,
"expected one cursor move per row, got {}",
count_moves(&out)
);
}
#[test]
fn a_colour_change_alone_does_not_cost_a_reset() {
let cells: Vec<(usize, usize, Cell)> = (0..10)
.map(|x| {
(
x,
0,
Cell::new('#', rgb(x as u8, 0, 0), style::Attribute::Reset),
)
})
.collect();
let out = encoded((20, 5), &cells);
assert_eq!(
count_resets(&out),
2,
"colour changes are paying for an SGR reset each, got {out:?}"
);
}
#[test]
fn the_first_cell_of_a_frame_does_not_assume_the_terminals_style() {
let out = encoded(
(10, 3),
&[(2, 1, Cell::new('x', Color::Reset, style::Attribute::Reset))],
);
let mut terminal = Terminal::new(10, 3);
terminal.replay(&out);
let painted_cell = terminal.at(2, 1);
assert_eq!(painted_cell.symbol, 'x');
assert_eq!(painted_cell.fg, Color::Reset);
assert_eq!(painted_cell.bg, Color::Reset);
let reset = out
.find("\u{1b}[0m")
.expect("the frame emitted no baseline");
let glyph = out.find('x').expect("the frame emitted no glyph");
assert!(
reset < glyph,
"the baseline reset came after the glyph, so the glyph was drawn in \
whatever style the terminal already had: {out:?}"
);
}
#[test]
fn a_row_of_adjacent_cells_costs_one_cursor_move() {
let cells: Vec<(usize, usize, Cell)> =
(0..10).map(|x| (x, 0, cell('#'))).collect();
let out = encoded((20, 5), &cells);
assert_eq!(
count_moves(&out),
1,
"expected a single cursor move for ten adjacent cells, got {out:?}"
);
}
#[test]
fn a_gap_in_a_row_forces_a_new_cursor_move() {
let cells = [(0usize, 0usize, cell('#')), (5, 0, cell('#'))];
let out = encoded((20, 5), &cells);
assert_eq!(
count_moves(&out),
2,
"expected a cursor move per cell across the gap, got {out:?}"
);
}
#[test]
fn wrapping_to_the_next_row_forces_a_new_cursor_move() {
let cells = [(4usize, 0usize, cell('#')), (0, 1, cell('#'))];
let out = encoded((5, 5), &cells);
assert_eq!(
count_moves(&out),
2,
"expected a cursor move per row, got {out:?}"
);
}
#[test]
fn a_style_change_is_emitted_even_mid_row() {
let plain = Cell::new('#', Color::Red, style::Attribute::Bold);
let other = Cell::new('#', Color::Blue, style::Attribute::Bold);
let cells = [(0usize, 0usize, plain), (1, 0, other), (2, 0, plain)];
let out = encoded((10, 5), &cells);
assert_eq!(count_moves(&out), 1, "got {out:?}");
assert_eq!(out.matches('#').count(), 3, "got {out:?}");
}
}