diff --git a/src/ui/canvas_cache.rs b/src/ui/canvas_cache.rs new file mode 100644 index 00000000..18b67334 --- /dev/null +++ b/src/ui/canvas_cache.rs @@ -0,0 +1,485 @@ +//! Per-pane cache of the canvas base layer ([`crate::ui::canvas_layer`]) and the switch that turns +//! it on, off, or into a self-checking mode. +//! +//! A pane whose grid and layer inputs are unchanged since the last frame is not recomposed: the +//! stored cells are replayed into the frame buffer. The stored layer lives in the pane's +//! [`VtParser`] ([`crate::vt::derived::DerivedSlot`]), so it is dropped with the pane and is never +//! shared between two parsers. +//! +//! # What invalidates a stored layer +//! [`LayerKey`] lists every input. From the grid: `VtParser::generation` (bumped by every +//! `process`, resize and rebuild), the scrollback offset (scrolling does not bump the generation) +//! and the grid size. From the caller: every field of [`CanvasLayerInputs`]. State drawn *after* +//! the layer (graphics, search matches, selection, copy mode, hints, cursor and its blink, prompt, +//! status bar, focus chrome) is not cached at all and so cannot go stale. +//! +//! # Modes +//! `BILTERM_RENDER_CACHE=on|off|verify` picks the mode for the process; the default is `verify` +//! in debug builds (so every test that renders a pane checks the cache against the direct path) +//! and `on` in release builds. [`with_render_cache_mode`] overrides it for the current thread. + +use std::cell::Cell as StdCell; +use std::sync::{Arc, OnceLock}; + +use ratatui::buffer::{Buffer, Cell}; +use ratatui::layout::Rect; + +use crate::ui::canvas_layer::{CanvasLayerInputs, paint_canvas_layer}; +use crate::ui::theme::{ThemePalette, ThemePreset}; +use crate::vt::VtParser; + +/// How the canvas base layer is produced. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RenderCacheMode { + /// Replay the stored layer when its key matches; otherwise paint and (on the second sighting + /// of a key) store. + On, + /// Always paint directly. The reference behaviour. + Off, + /// Paint directly and also through the cache; panic if the two differ, or if a stored layer + /// differs from a fresh one with the same key (an under-invalidated key). + Verify, +} + +thread_local! { + static MODE_OVERRIDE: StdCell> = const { StdCell::new(None) }; +} + +fn process_default_mode() -> RenderCacheMode { + static DEFAULT: OnceLock = OnceLock::new(); + *DEFAULT.get_or_init(|| { + match std::env::var("BILTERM_RENDER_CACHE").ok().as_deref().map(str::trim) { + Some("on" | "1") => RenderCacheMode::On, + Some("off" | "0") => RenderCacheMode::Off, + Some("verify") => RenderCacheMode::Verify, + _ if cfg!(debug_assertions) => RenderCacheMode::Verify, + _ => RenderCacheMode::On, + } + }) +} + +/// The mode in effect on this thread. +pub fn render_cache_mode() -> RenderCacheMode { + MODE_OVERRIDE.with(StdCell::get).unwrap_or_else(process_default_mode) +} + +/// Runs `f` with the render cache in `mode` on the current thread, restoring the previous mode +/// afterwards (also when `f` panics). +pub fn with_render_cache_mode(mode: RenderCacheMode, f: impl FnOnce() -> R) -> R { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + MODE_OVERRIDE.with(|m| m.set(self.0)); + } + } + let _restore = Restore(MODE_OVERRIDE.with(|m| m.replace(Some(mode)))); + f() +} + +/// Stored layers kept per pane (the workspace view plus one other view of the same pane). +const MAX_LAYERS_PER_PANE: usize = 2; +/// Canvases larger than this many cells are painted directly and never stored. +const MAX_CACHED_CELLS: usize = 200_000; + +/// Every input of a stored layer. See the module documentation. +#[derive(Clone, Debug, PartialEq, Eq)] +struct LayerKey { + vt_generation: u64, + scrollback_offset: usize, + vt_size: (u16, u16), + canvas: Rect, + theme: ThemePreset, + palette: ThemePalette, + font_bold: bool, + font_italic: bool, + font_double_width: bool, + triggers: Vec, + crt_scanlines: bool, +} + +impl LayerKey { + fn capture(vt: &VtParser, inputs: &CanvasLayerInputs<'_>) -> Self { + // Exhaustive: adding a field to `CanvasLayerInputs` fails to compile here and in `matches`. + let CanvasLayerInputs { + canvas, + theme, + palette, + font_bold, + font_italic, + font_double_width, + triggers, + crt_scanlines, + } = *inputs; + Self { + vt_generation: vt.generation(), + scrollback_offset: vt.scrollback_offset(), + vt_size: vt.size(), + canvas, + theme, + palette: palette.clone(), + font_bold, + font_italic, + font_double_width, + triggers: triggers.to_vec(), + crt_scanlines, + } + } + + /// Allocation-free equivalent of `*self == LayerKey::capture(vt, inputs)`. + fn matches(&self, vt: &VtParser, inputs: &CanvasLayerInputs<'_>) -> bool { + let CanvasLayerInputs { + canvas, + theme, + palette, + font_bold, + font_italic, + font_double_width, + triggers, + crt_scanlines, + } = *inputs; + self.vt_generation == vt.generation() + && self.scrollback_offset == vt.scrollback_offset() + && self.vt_size == vt.size() + && self.canvas == canvas + && self.theme == theme + && self.font_bold == font_bold + && self.font_italic == font_italic + && self.font_double_width == font_double_width + && self.crt_scanlines == crt_scanlines + && self.triggers.as_slice() == triggers + && self.palette == *palette + } +} + +/// The value parked in the pane's `DerivedSlot`: at most [`MAX_LAYERS_PER_PANE`] stored layers and +/// as many keys that were painted once but not stored yet. +#[derive(Default)] +struct PaneLayerCache { + layers: Vec<(LayerKey, Arc>)>, + seen_once: Vec, +} + +enum Lookup { + Hit(Arc>), + /// Second consecutive sighting of this key: worth storing. + Store, + /// First sighting: paint directly. A pane that changes every frame stays on this path and + /// pays nothing for the cache. + PaintDirect, +} + +impl PaneLayerCache { + fn find(&self, vt: &VtParser, inputs: &CanvasLayerInputs<'_>) -> Option>> { + self.layers.iter().find(|(key, _)| key.matches(vt, inputs)).map(|(_, cells)| Arc::clone(cells)) + } + + fn lookup(&mut self, vt: &VtParser, inputs: &CanvasLayerInputs<'_>) -> Lookup { + if let Some(cells) = self.find(vt, inputs) { + return Lookup::Hit(cells); + } + if self.seen_once.iter().any(|key| key.matches(vt, inputs)) { + return Lookup::Store; + } + self.seen_once.insert(0, LayerKey::capture(vt, inputs)); + self.seen_once.truncate(MAX_LAYERS_PER_PANE); + Lookup::PaintDirect + } + + fn store(&mut self, key: LayerKey, cells: Arc>) { + self.seen_once.retain(|seen| *seen != key); + self.layers.retain(|(stored, _)| *stored != key); + self.layers.insert(0, (key, cells)); + self.layers.truncate(MAX_LAYERS_PER_PANE); + } +} + +fn cacheable(canvas: Rect) -> bool { + let cells = usize::from(canvas.width) * usize::from(canvas.height); + cells > 0 && cells <= MAX_CACHED_CELLS +} + +/// Paints the layer into a private buffer covering exactly `inputs.canvas`. +fn paint_to_cells(vt: &VtParser, inputs: &CanvasLayerInputs<'_>) -> Vec { + let mut scratch = Buffer::empty(inputs.canvas); + paint_canvas_layer(vt, inputs, &mut scratch); + scratch.content +} + +/// Replays stored layer `cells` (row-major over `canvas`) into `buf`, with the same effect on each +/// destination cell as [`paint_canvas_layer`]: symbol, foreground and background are replaced and +/// modifiers are added; `skip` and the underline colour are left alone. +fn replay(cells: &[Cell], canvas: Rect, buf: &mut Buffer) { + let clip = canvas.intersection(buf.area); + if clip.width == 0 || clip.height == 0 { + return; + } + let stride = usize::from(canvas.width); + let width = usize::from(clip.width); + for y in clip.y..clip.y + clip.height { + let src_start = usize::from(y - canvas.y) * stride + usize::from(clip.x - canvas.x); + let dst_start = buf.index_of(clip.x, y); + let src_row = &cells[src_start..src_start + width]; + let dst_row = &mut buf.content[dst_start..dst_start + width]; + for (dst, src) in dst_row.iter_mut().zip(src_row) { + dst.set_symbol(src.symbol()); + dst.fg = src.fg; + dst.bg = src.bg; + dst.modifier.insert(src.modifier); + } + } +} + +/// Paints the canvas base layer of `vt` into `buf`, through the per-pane cache when the current +/// [`RenderCacheMode`] allows it. The result is identical to [`paint_canvas_layer`] in every mode. +pub fn paint_canvas_layer_cached(vt: &VtParser, inputs: &CanvasLayerInputs<'_>, buf: &mut Buffer) { + let mode = render_cache_mode(); + if mode == RenderCacheMode::Off || !cacheable(inputs.canvas) { + paint_canvas_layer(vt, inputs, buf); + return; + } + if mode == RenderCacheMode::Verify { + paint_verified(vt, inputs, buf); + return; + } + match vt.derived().with(|cache: &mut PaneLayerCache| cache.lookup(vt, inputs)) { + Lookup::Hit(cells) => replay(&cells, inputs.canvas, buf), + Lookup::PaintDirect => paint_canvas_layer(vt, inputs, buf), + Lookup::Store => { + let cells = Arc::new(paint_to_cells(vt, inputs)); + replay(&cells, inputs.canvas, buf); + let key = LayerKey::capture(vt, inputs); + vt.derived().with(|cache: &mut PaneLayerCache| cache.store(key, cells)); + } + } +} + +fn region_cells(buf: &Buffer, region: Rect) -> Vec { + let mut out = Vec::with_capacity(usize::from(region.width) * usize::from(region.height)); + for y in region.y..region.y + region.height { + let start = buf.index_of(region.x, y); + out.extend_from_slice(&buf.content[start..start + usize::from(region.width)]); + } + out +} + +fn restore_region(buf: &mut Buffer, region: Rect, cells: &[Cell]) { + let width = usize::from(region.width); + for (row, y) in (region.y..region.y + region.height).enumerate() { + let start = buf.index_of(region.x, y); + buf.content[start..start + width].clone_from_slice(&cells[row * width..(row + 1) * width]); + } +} + +fn first_difference(a: &[Cell], b: &[Cell], region: Rect) -> Option { + let width = usize::from(region.width.max(1)); + a.iter().zip(b).position(|(x, y)| x != y).map(|i| { + format!( + "first difference at column {} row {} of the canvas: cached {:?}, direct {:?}", + i % width, + i / width, + a[i], + b[i] + ) + }) +} + +/// `Verify` mode: leaves `buf` exactly as the direct path paints it, after checking that +/// 1. a stored layer with a matching key equals a freshly painted one (the key covers every input); +/// 2. replaying a layer over the current buffer content equals painting directly over it. +fn paint_verified(vt: &VtParser, inputs: &CanvasLayerInputs<'_>, buf: &mut Buffer) { + let fresh = Arc::new(paint_to_cells(vt, inputs)); + let stored = vt.derived().with(|cache: &mut PaneLayerCache| cache.find(vt, inputs)); + if let Some(stored) = stored + && let Some(diff) = first_difference(&stored, &fresh, inputs.canvas) + { + panic!( + "render cache: a stored canvas layer is stale although its key matches (an input is \ + missing from the key). {diff}. Run with BILTERM_RENDER_CACHE=off to work around." + ); + } + let key = LayerKey::capture(vt, inputs); + vt.derived().with(|cache: &mut PaneLayerCache| cache.store(key, Arc::clone(&fresh))); + + let clip = inputs.canvas.intersection(buf.area); + if clip.width == 0 || clip.height == 0 { + return; + } + let before = region_cells(buf, clip); + replay(&fresh, inputs.canvas, buf); + let replayed = region_cells(buf, clip); + restore_region(buf, clip, &before); + paint_canvas_layer(vt, inputs, buf); + let direct = region_cells(buf, clip); + if let Some(diff) = first_difference(&replayed, &direct, clip) { + panic!( + "render cache: replaying the canvas layer differs from painting it directly. {diff}. \ + Run with BILTERM_RENDER_CACHE=off to work around." + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::BiltermConfig; + use crate::pane::CompositePane; + use ratatui::style::{Color, Modifier, Style}; + + fn pane_with_output() -> CompositePane { + let mut pane = CompositePane::new_headless(1, 12, 50); + pane.process_pty_output( + b"\x1b[1;32mgreen\x1b[0m plain \x1b[7minverse\x1b[0m https://example.org/x\r\n\ + \x1b[48;5;22m\x1b[38;5;120m+ added line\x1b[0m \xe6\x97\xa5\xe6\x9c\xac ERROR\r\n", + ); + pane + } + + fn paint(mode: RenderCacheMode, pane: &CompositePane, cfg: &BiltermConfig, canvas: Rect, buf: &mut Buffer) { + let palette = cfg.palette(); + let inputs = CanvasLayerInputs::gather(pane, canvas, cfg, &palette); + with_render_cache_mode(mode, || paint_canvas_layer_cached(pane.vt(), &inputs, buf)); + } + + /// A frame buffer whose cells already carry modifiers, colours and `skip`, as left behind by + /// whatever was drawn underneath the pane. + fn dirty_buffer(area: Rect) -> Buffer { + let mut buf = Buffer::empty(area); + for (i, cell) in buf.content.iter_mut().enumerate() { + cell.set_symbol("x"); + cell.set_style(Style::default().fg(Color::Red).bg(Color::Blue).add_modifier(Modifier::ITALIC | Modifier::DIM)); + cell.skip = i % 7 == 0; + } + buf + } + + #[test] + fn third_identical_render_is_a_cache_hit_and_equals_the_direct_path() { + let pane = pane_with_output(); + let cfg = BiltermConfig::default(); + let area = Rect::new(0, 0, 60, 14); + let canvas = Rect::new(3, 1, 50, 11); + + let mut reference = dirty_buffer(area); + paint(RenderCacheMode::Off, &pane, &cfg, canvas, &mut reference); + for round in 0..4 { + let mut buf = dirty_buffer(area); + paint(RenderCacheMode::On, &pane, &cfg, canvas, &mut buf); + assert_eq!(buf, reference, "round {round}"); + } + let stored = pane.vt().derived().with(|c: &mut PaneLayerCache| c.layers.len()); + assert_eq!(stored, 1, "first sighting paints directly, second stores, later ones hit"); + } + + #[test] + fn canvas_partly_outside_the_buffer_is_clipped_like_the_direct_path() { + let pane = pane_with_output(); + let cfg = BiltermConfig::default(); + let area = Rect::new(2, 2, 30, 6); + let canvas = Rect::new(0, 0, 50, 11); + let mut reference = dirty_buffer(area); + paint(RenderCacheMode::Off, &pane, &cfg, canvas, &mut reference); + for _ in 0..3 { + let mut buf = dirty_buffer(area); + paint(RenderCacheMode::On, &pane, &cfg, canvas, &mut buf); + assert_eq!(buf, reference); + } + let mut buf = dirty_buffer(area); + paint(RenderCacheMode::Verify, &pane, &cfg, canvas, &mut buf); + assert_eq!(buf, reference); + } + + #[test] + fn every_key_input_invalidates_the_stored_layer() { + let mut pane = pane_with_output(); + let mut cfg = BiltermConfig::default(); + let area = Rect::new(0, 0, 60, 14); + let mut canvas = Rect::new(0, 0, 50, 11); + + // After each change the cached render must equal a direct render of the new state and + // differ from the frame before the change. + let mut previous: Option = None; + let mut check = |label: &str, pane: &CompositePane, cfg: &BiltermConfig, canvas: Rect| { + let mut reference = Buffer::empty(area); + paint(RenderCacheMode::Off, pane, cfg, canvas, &mut reference); + for _ in 0..3 { + let mut buf = Buffer::empty(area); + paint(RenderCacheMode::On, pane, cfg, canvas, &mut buf); + assert_eq!(buf, reference, "{label}: cached frame differs from direct frame"); + } + if let Some(prev) = &previous { + assert_ne!(*prev, reference, "{label}: the change must be visible"); + } + previous = Some(reference); + }; + + check("initial", &pane, &cfg, canvas); + pane.process_pty_output(b"new output line\r\n"); + check("vt generation", &pane, &cfg, canvas); + for i in 0..40 { + pane.process_pty_output(format!("scroll filler {i}\r\n").as_bytes()); + } + check("more output", &pane, &cfg, canvas); + pane.vt_mut().scroll_up(5); + check("scrollback offset", &pane, &cfg, canvas); + pane.vt_mut().reset_scrollback(); + check("scrollback reset", &pane, &cfg, canvas); + cfg.theme = ThemePreset::Ibm3278Green; + check("theme", &pane, &cfg, canvas); + cfg.triggers = vec!["filler".to_string()]; + check("triggers", &pane, &cfg, canvas); + cfg.crt_scanlines = true; + check("crt scanlines", &pane, &cfg, canvas); + canvas = Rect::new(4, 2, 40, 9); + check("canvas rect", &pane, &cfg, canvas); + pane.vt_mut().set_size(9, 40); + check("vt size", &pane, &cfg, canvas); + } + + #[test] + fn a_pane_that_changes_every_frame_never_stores_a_layer() { + let mut pane = pane_with_output(); + let cfg = BiltermConfig::default(); + let area = Rect::new(0, 0, 50, 11); + for i in 0..6 { + pane.process_pty_output(format!("tick {i}\r\n").as_bytes()); + let mut buf = Buffer::empty(area); + paint(RenderCacheMode::On, &pane, &cfg, area, &mut buf); + } + let (layers, seen) = pane.vt().derived().with(|c: &mut PaneLayerCache| (c.layers.len(), c.seen_once.len())); + assert_eq!(layers, 0); + assert!(seen <= MAX_LAYERS_PER_PANE); + } + + #[test] + fn stored_layers_are_bounded_per_pane() { + let pane = pane_with_output(); + let cfg = BiltermConfig::default(); + let area = Rect::new(0, 0, 60, 14); + for w in 20..30 { + for _ in 0..3 { + let mut buf = Buffer::empty(area); + paint(RenderCacheMode::On, &pane, &cfg, Rect::new(0, 0, w, 10), &mut buf); + } + } + let (layers, seen) = pane.vt().derived().with(|c: &mut PaneLayerCache| (c.layers.len(), c.seen_once.len())); + assert!(layers <= MAX_LAYERS_PER_PANE && seen <= MAX_LAYERS_PER_PANE); + assert!(!cacheable(Rect::new(0, 0, 1000, 1000)), "oversized canvases are never stored"); + } + + #[test] + #[should_panic(expected = "stale although its key matches")] + fn verify_mode_catches_a_stale_stored_layer() { + let pane = pane_with_output(); + let cfg = BiltermConfig::default(); + let area = Rect::new(0, 0, 50, 11); + let mut buf = Buffer::empty(area); + paint(RenderCacheMode::Verify, &pane, &cfg, area, &mut buf); + // Corrupt the stored layer behind the key's back, as a missed invalidation would. + pane.vt().derived().with(|c: &mut PaneLayerCache| { + let mut cells = (*c.layers[0].1).clone(); + cells[0].set_symbol("!"); + c.layers[0].1 = Arc::new(cells); + }); + paint(RenderCacheMode::Verify, &pane, &cfg, area, &mut buf); + } +} diff --git a/src/ui/canvas_layer.rs b/src/ui/canvas_layer.rs new file mode 100644 index 00000000..209d1ccf --- /dev/null +++ b/src/ui/canvas_layer.rs @@ -0,0 +1,248 @@ +//! The cacheable base layer of a pane's `OutputCanvas`: background fill, VT cells with WCAG +//! contrast, URL and trigger highlights, CRT scanlines. +//! +//! [`paint_canvas_layer`] is a pure function of the [`VtParser`] grid and [`CanvasLayerInputs`]. +//! It deliberately takes neither the pane nor the config, so it cannot read an input that the +//! cache key in [`crate::ui::canvas_cache`] does not cover. A new input goes into +//! `CanvasLayerInputs`; the key destructures that struct exhaustively and stops compiling until +//! the field is handled. + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::{Color, Modifier, Style}; + +use crate::config::BiltermConfig; +use crate::pane::CompositePane; +use crate::ui::theme::{ThemePalette, ThemePreset}; +use crate::ui::typography::{self, LineSizeAttr}; +use crate::ui::{contrast, gui_font}; +use crate::vt::VtParser; + +/// Every input of the canvas base layer other than the VT grid itself (which is identified by +/// `VtParser::generation`, the scrollback offset and the grid size). +#[derive(Clone, Copy, Debug)] +pub struct CanvasLayerInputs<'a> { + /// Absolute canvas rectangle in the frame buffer. + pub canvas: Rect, + /// Theme preset: selects the ANSI 0..15 table and the fallback foreground. + pub theme: ThemePreset, + /// Resolved palette (global, per-window theme or per-window colour overrides). + pub palette: &'a ThemePalette, + /// Per-pane font option: force bold. + pub font_bold: bool, + /// Per-pane font option: force italic. + pub font_italic: bool, + /// Per-pane font option: render every row double-width. + pub font_double_width: bool, + /// Output triggers highlighted on the canvas. + pub triggers: &'a [String], + /// CRT scanline dimming on odd rows. + pub crt_scanlines: bool, +} + +impl<'a> CanvasLayerInputs<'a> { + /// Collects the layer inputs for `pane` drawn into `canvas` with `cfg` and `palette`. + pub fn gather( + pane: &CompositePane, + canvas: Rect, + cfg: &'a BiltermConfig, + palette: &'a ThemePalette, + ) -> Self { + let font = pane.font_options(); + Self { + canvas, + theme: cfg.theme, + palette, + font_bold: font.bold, + font_italic: font.italic, + font_double_width: font.double_width, + triggers: &cfg.triggers, + crt_scanlines: cfg.crt_scanlines, + } + } +} + +fn is_safe_terminal_cluster(s: &str, expected_width: usize, grapheme_mode_2027: bool) -> bool { + if s.is_empty() { + return false; + } + let w = unicode_width::UnicodeWidthStr::width(s); + if w != expected_width { + let first_ok = expected_width == 1 + && s.chars().next().is_some_and(|ch| { + gui_font::geometric::is_private_use_area(ch) + || gui_font::geometric::is_geometric_glyph(ch) + || unicode_width::UnicodeWidthChar::width(ch) == Some(1) + }); + if !first_ok { + return false; + } + } + for ch in s.chars() { + let code = ch as u32; + if matches!(code, 0xFE00..=0xFE0F) || (grapheme_mode_2027 && code == 0x200D) { + continue; + } + if ch.is_control() + || matches!( + code, + 0x200B..=0x200F | 0x2028..=0x202F | 0x2060..=0x206F | 0xFEFF | 0xFFF9..=0xFFFB + ) + { + return false; + } + } + true +} + +/// Paints the canvas base layer into `buf`. Every cell of `inputs.canvas` that lies inside `buf` +/// gets its symbol, foreground and background replaced and modifiers added (never removed), which +/// is what lets [`crate::ui::canvas_cache`] replay a stored layer over any prior buffer content. +pub fn paint_canvas_layer(vt: &VtParser, inputs: &CanvasLayerInputs<'_>, buf: &mut Buffer) { + let canvas = inputs.canvas; + let palette = inputs.palette; + let (vt_rows, vt_cols) = vt.size(); + let render_rows = canvas.height.min(vt_rows); + let render_cols = canvas.width.min(vt_cols); + let grapheme_2027 = vt.is_grapheme_cluster_2027(); + let fill_style = Style::default() + .fg(palette.text_fg.unwrap_or(palette.title_fg)) + .bg(palette.window_frame_bg); + for y in canvas.y..canvas.y + canvas.height { + for x in canvas.x..canvas.x + canvas.width { + if let Some(c) = buf.cell_mut((x, y)) { + c.set_symbol(" "); + c.set_style(fill_style); + } + } + } + + // Runs of cells with the same colours and attributes are the norm; reuse the last style + // instead of redoing the contrast maths (the style depends on nothing else in the cell). + let mut last_style: Option<(contrast::CellStyleKey, Style)> = None; + for r in 0..render_rows { + let mut line_attr = vt.line_size_attr(r); + if !line_attr.is_double_width() && inputs.font_double_width { + line_attr = LineSizeAttr::DoubleWidth; + } + if line_attr.is_double_width() { + typography::render_double_width_row(vt, r, canvas, render_cols, line_attr, buf); + continue; + } + let mut skip_next_wide_continuation = false; + for c in 0..render_cols { + let Some(vt_cell) = vt.cell_view(r, c) else { + skip_next_wide_continuation = false; + continue; + }; + let dst_x = canvas.x + c; + let dst_y = canvas.y + r; + let style_key = contrast::CellStyleKey::of(&vt_cell); + let mut style = match last_style { + Some((key, style)) if key == style_key => style, + _ => { + let style = contrast::readable_canvas_cell_style(&vt_cell, inputs.theme, palette); + last_style = Some((style_key, style)); + style + } + }; + if inputs.font_bold { + style = style.add_modifier(Modifier::BOLD); + } + if inputs.font_italic { + style = style.add_modifier(Modifier::ITALIC); + } + + if skip_next_wide_continuation { + skip_next_wide_continuation = false; + if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { + dst_cell.set_style(style); + } + continue; + } + + if vt_cell.is_wide_continuation() { + if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { + dst_cell.set_symbol(" "); + dst_cell.set_style(style); + } + continue; + } + + let contents = vt_cell.grapheme; + if vt_cell.is_wide() { + // Prevent a 2-column wide glyph at the rightmost column from overflowing/wrapping the host terminal + if c + 1 < render_cols && is_safe_terminal_cluster(contents, 2, grapheme_2027) { + if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { + dst_cell.set_symbol(contents); + dst_cell.set_style(style); + } + skip_next_wide_continuation = true; + } else if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { + dst_cell.set_symbol(" "); + dst_cell.set_style(style); + } + } else if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { + if contents.is_empty() { + dst_cell.set_symbol(" "); + } else if is_safe_terminal_cluster(contents, 1, grapheme_2027) { + if !grapheme_2027 && contents.contains(['\u{FE0E}', '\u{FE0F}']) + && let Some(base) = contents.chars().next() + { + let mut sym = [0u8; 4]; + dst_cell.set_symbol(base.encode_utf8(&mut sym)); + } else { + dst_cell.set_symbol(contents); + } + } else { + dst_cell.set_symbol("·"); + } + dst_cell.set_style(style); + } + } + } + + // Highlight detected URLs with underline + bright cyan tint (VAL-03) + for url in vt.detect_visible_urls() { + if url.row < render_rows { + for c in url.start_col..=url.end_col.min(render_cols.saturating_sub(1)) { + if let Some(cell) = buf.cell_mut((canvas.x + c, canvas.y + url.row)) { + cell.set_style( + cell.style() + .fg(Color::Rgb(85, 255, 255)) + .add_modifier(Modifier::UNDERLINED), + ); + } + } + } + } + + // Highlight custom output triggers (v0.7.0) + for trigger in inputs.triggers { + for m in vt.search_canvas(trigger) { + if m.row < render_rows { + for c in m.start_col..=m.end_col.min(render_cols.saturating_sub(1)) { + if let Some(cell) = buf.cell_mut((canvas.x + c, canvas.y + m.row)) { + cell.set_style( + Style::default() + .fg(Color::White) + .bg(Color::Rgb(200, 0, 80)) + .add_modifier(Modifier::BOLD), + ); + } + } + } + } + } + + // Apply CRT phosphor scanline effect on odd rows when enabled (v0.6.0) + if inputs.crt_scanlines { + for r in (1..render_rows).step_by(2) { + for c in 0..render_cols { + if let Some(cell) = buf.cell_mut((canvas.x + c, canvas.y + r)) { + cell.set_style(cell.style().add_modifier(Modifier::DIM)); + } + } + } + } +} diff --git a/src/ui/contrast.rs b/src/ui/contrast.rs index 2bd69349..51c3c936 100644 --- a/src/ui/contrast.rs +++ b/src/ui/contrast.rs @@ -122,18 +122,33 @@ pub fn resolve_ratatui_color_rgb(c: Color, theme: ThemePreset, default_rgb: (u8, } } +/// sRGB channel linearisation exactly as WCAG 2.1 defines it (one `powf` per call). +#[inline] +fn linear_channel(v: u8) -> f32 { + let s = f32::from(v) / 255.0; + if s <= 0.03928 { + s / 12.92 + } else { + ((s + 0.055) / 1.055).powf(2.4) + } +} + +/// [`linear_channel`] for every possible channel value, computed once at first use with the same +/// expression, so a lookup is bit-identical to the direct call. The canvas calls +/// [`rgb_luminance`] several times per cell; the table keeps `powf` out of that path. +static LINEAR_CHANNEL: std::sync::LazyLock<[f32; 256]> = std::sync::LazyLock::new(|| { + let mut table = [0.0f32; 256]; + for (v, slot) in table.iter_mut().enumerate() { + *slot = linear_channel(v as u8); + } + table +}); + /// WCAG 2.1 relative luminance (`0.0..=1.0`) for an `(r, g, b)` triplet. #[inline] pub fn rgb_luminance(rgb: (u8, u8, u8)) -> f32 { - fn chan(v: u8) -> f32 { - let s = f32::from(v) / 255.0; - if s <= 0.03928 { - s / 12.92 - } else { - ((s + 0.055) / 1.055).powf(2.4) - } - } - 0.2126 * chan(rgb.0) + 0.7152 * chan(rgb.1) + 0.0722 * chan(rgb.2) + let t = &*LINEAR_CHANNEL; + 0.2126 * t[usize::from(rgb.0)] + 0.7152 * t[usize::from(rgb.1)] + 0.0722 * t[usize::from(rgb.2)] } /// WCAG 2.1 contrast ratio (`1.0..=21.0`) between two `(r, g, b)` colors. @@ -179,6 +194,28 @@ pub fn boost_fg_contrast(fg: (u8, u8, u8), bg: (u8, u8, u8), min_ratio: f32) -> pole } +/// The cell attributes [`readable_canvas_cell_style`] reads. Two cells with equal keys get the +/// same style for a given theme and palette, so a renderer may reuse the previous result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CellStyleKey { + fg: CellColor, + bg: CellColor, + bold: bool, + italic: bool, + underlined: bool, + inverse: bool, +} + +impl CellStyleKey { + #[inline] + pub fn of(cell: &CellView<'_>) -> Self { + // Exhaustive on purpose: a new `CellView` field must be classified here as either part of + // the style key or irrelevant to the style (`grapheme`, `width`). + let CellView { grapheme: _, width: _, fg, bg, bold, italic, underline, inverse } = *cell; + Self { fg, bg, bold, italic, underlined: underline.is_underlined(), inverse } + } +} + /// Converts a [`CellView`] into a high-legibility `ratatui::style::Style` on the `OutputCanvas`: /// - Resolves `inverse` (`SGR 7`) explicitly into concrete `(fg, bg)` RGB colors so reversed blocks /// never rely on ambiguous `Color::Reset` host inversion. @@ -305,6 +342,17 @@ mod tests { } } + #[test] + fn luminance_table_is_bit_identical_to_the_direct_formula() { + for v in 0..=255u8 { + assert_eq!(LINEAR_CHANNEL[usize::from(v)].to_bits(), linear_channel(v).to_bits(), "channel {v}"); + } + for rgb in [(0, 0, 0), (255, 255, 255), (12, 16, 24), (248, 250, 252), (96, 165, 250), (1, 127, 254)] { + let direct = 0.2126 * linear_channel(rgb.0) + 0.7152 * linear_channel(rgb.1) + 0.0722 * linear_channel(rgb.2); + assert_eq!(rgb_luminance(rgb).to_bits(), direct.to_bits(), "{rgb:?}"); + } + } + #[test] fn light_highlight_background_with_default_or_light_fg_enforces_dark_text_contrast() { let palette = ThemePreset::TurboBlue.palette(); diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 3e0ef841..10b40d96 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -9,6 +9,8 @@ pub mod traffic_monitor_gui; pub mod traffic_monitor_ui; pub mod command_window_ui; pub mod bitmap_font; +pub mod canvas_cache; +pub mod canvas_layer; pub mod canvas_raster; pub mod contrast; pub mod copy_hints; @@ -232,39 +234,6 @@ impl Widget for CompositePaneWidget<'_> { } } -fn is_safe_terminal_cluster(s: &str, expected_width: usize, grapheme_mode_2027: bool) -> bool { - if s.is_empty() { - return false; - } - let w = unicode_width::UnicodeWidthStr::width(s); - if w != expected_width { - let first_ok = expected_width == 1 - && s.chars().next().is_some_and(|ch| { - gui_font::geometric::is_private_use_area(ch) - || gui_font::geometric::is_geometric_glyph(ch) - || unicode_width::UnicodeWidthChar::width(ch) == Some(1) - }); - if !first_ok { - return false; - } - } - for ch in s.chars() { - let code = ch as u32; - if matches!(code, 0xFE00..=0xFE0F) || (grapheme_mode_2027 && code == 0x200D) { - continue; - } - if ch.is_control() - || matches!( - code, - 0x200B..=0x200F | 0x2028..=0x202F | 0x2060..=0x206F | 0xFEFF | 0xFFF9..=0xFFFB - ) - { - return false; - } - } - true -} - /// Rasterizes an RGBA frame into `area` using TrueColor `▀` half-blocks (2 pixel rows per cell). fn rasterize_frame_halfblocks( buf: &mut Buffer, @@ -303,137 +272,11 @@ fn render_output_canvas( let (vt_rows, vt_cols) = vt.size(); let render_rows = canvas.height.min(vt_rows); let render_cols = canvas.width.min(vt_cols); - let grapheme_2027 = vt.is_grapheme_cluster_2027(); - let fill_style = Style::default() - .fg(palette.text_fg.unwrap_or(palette.title_fg)) - .bg(palette.window_frame_bg); - for y in canvas.y..canvas.y + canvas.height { - for x in canvas.x..canvas.x + canvas.width { - if let Some(c) = buf.cell_mut((x, y)) { - c.set_symbol(" "); - c.set_style(fill_style); - } - } - } - - let font_opts = pane.font_options(); - for r in 0..render_rows { - let mut line_attr = vt.line_size_attr(r); - if !line_attr.is_double_width() && font_opts.double_width { - line_attr = LineSizeAttr::DoubleWidth; - } - if line_attr.is_double_width() { - typography::render_double_width_row(vt, r, canvas, render_cols, line_attr, buf); - continue; - } - let mut skip_next_wide_continuation = false; - for c in 0..render_cols { - let Some(vt_cell) = vt.cell_view(r, c) else { - skip_next_wide_continuation = false; - continue; - }; - let dst_x = canvas.x + c; - let dst_y = canvas.y + r; - let mut style = contrast::readable_canvas_cell_style(&vt_cell, cfg.theme, palette); - if font_opts.bold { - style = style.add_modifier(Modifier::BOLD); - } - if font_opts.italic { - style = style.add_modifier(Modifier::ITALIC); - } - - if skip_next_wide_continuation { - skip_next_wide_continuation = false; - if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { - dst_cell.set_style(style); - } - continue; - } - - if vt_cell.is_wide_continuation() { - if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { - dst_cell.set_symbol(" "); - dst_cell.set_style(style); - } - continue; - } - - let contents = vt_cell.grapheme; - if vt_cell.is_wide() { - // Prevent a 2-column wide glyph at the rightmost column from overflowing/wrapping the host terminal - if c + 1 < render_cols && is_safe_terminal_cluster(contents, 2, grapheme_2027) { - if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { - dst_cell.set_symbol(contents); - dst_cell.set_style(style); - } - skip_next_wide_continuation = true; - } else if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { - dst_cell.set_symbol(" "); - dst_cell.set_style(style); - } - } else if let Some(dst_cell) = buf.cell_mut((dst_x, dst_y)) { - if contents.is_empty() { - dst_cell.set_symbol(" "); - } else if is_safe_terminal_cluster(contents, 1, grapheme_2027) { - if !grapheme_2027 && contents.contains(['\u{FE0E}', '\u{FE0F}']) - && let Some(base) = contents.chars().next() - { - let mut sym = [0u8; 4]; - dst_cell.set_symbol(base.encode_utf8(&mut sym)); - } else { - dst_cell.set_symbol(contents); - } - } else { - dst_cell.set_symbol("·"); - } - dst_cell.set_style(style); - } - } - } - - // Highlight detected URLs with underline + bright cyan tint (VAL-03) - for url in pane.vt().detect_visible_urls() { - if url.row < render_rows { - for c in url.start_col..=url.end_col.min(render_cols.saturating_sub(1)) { - if let Some(cell) = buf.cell_mut((canvas.x + c, canvas.y + url.row)) { - cell.set_style( - cell.style() - .fg(Color::Rgb(85, 255, 255)) - .add_modifier(Modifier::UNDERLINED), - ); - } - } - } - } - // Highlight custom output triggers (v0.7.0) - for trigger in &cfg.triggers { - for m in pane.vt().search_canvas(trigger) { - if m.row < render_rows { - for c in m.start_col..=m.end_col.min(render_cols.saturating_sub(1)) { - if let Some(cell) = buf.cell_mut((canvas.x + c, canvas.y + m.row)) { - cell.set_style( - Style::default() - .fg(Color::White) - .bg(Color::Rgb(200, 0, 80)) - .add_modifier(Modifier::BOLD), - ); - } - } - } - } - } - - // Apply CRT phosphor scanline effect on odd rows when enabled (v0.6.0) - if cfg.crt_scanlines { - for r in (1..render_rows).step_by(2) { - for c in 0..render_cols { - if let Some(cell) = buf.cell_mut((canvas.x + c, canvas.y + r)) { - cell.set_style(cell.style().add_modifier(Modifier::DIM)); - } - } - } - } + // Layer 1 (cached per pane): background fill, VT cells with contrast, URL and trigger + // highlights, CRT scanlines. Everything below is cheap or state-dependent and redrawn each frame. + let layer_inputs = canvas_layer::CanvasLayerInputs::gather(pane, canvas, cfg, palette); + canvas_cache::paint_canvas_layer_cached(vt, &layer_inputs, buf); // Render Kitty Graphics (APC G) and DEC Sixel (DCS q) placements using TrueColor half-blocks (GFX-01) for gfx in pane.vt().graphic_placements() { diff --git a/src/vt/derived.rs b/src/vt/derived.rs new file mode 100644 index 00000000..afab39cb --- /dev/null +++ b/src/vt/derived.rs @@ -0,0 +1,62 @@ +//! Reader-side cache slot attached to a [`super::VtParser`]. +//! +//! The renderer (`crate::ui`, a higher layer) parks data it derived from the grid here, so the +//! data lives and dies with the parser instead of in a global map keyed by pane id. The slot is +//! type-erased because `vt` must not name `ui` types; it holds at most one value, and the reader +//! bounds what that value contains. Validity is the reader's job: it keys its data on +//! [`super::VtParser::generation`] plus every other input it used. + +use std::any::Any; +use std::sync::Mutex; + +/// One interior-mutable, type-erased value. Never read by the parser itself. +#[derive(Default)] +pub struct DerivedSlot(Mutex>>); + +impl DerivedSlot { + /// Runs `f` on the stored `T`, creating `T::default()` first when the slot is empty or holds + /// another type. A poisoned lock (a reader panicked mid-update) drops the stored value. + pub fn with(&self, f: impl FnOnce(&mut T) -> R) -> R + where + T: Any + Send + Sync + Default, + { + let mut guard = match self.0.lock() { + Ok(guard) => guard, + Err(poisoned) => { + let mut guard = poisoned.into_inner(); + *guard = None; + guard + } + }; + if let Some(value) = guard.as_mut().and_then(|boxed| boxed.downcast_mut::()) { + return f(value); + } + let mut fresh = T::default(); + let out = f(&mut fresh); + *guard = Some(Box::new(fresh)); + out + } + + /// Drops the stored value. + pub fn clear(&self) { + if let Ok(mut guard) = self.0.lock() { + *guard = None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slot_keeps_one_value_and_replaces_it_on_type_change() { + let slot = DerivedSlot::default(); + assert_eq!(slot.with(|v: &mut Vec| { v.push(1); v.len() }), 1); + assert_eq!(slot.with(|v: &mut Vec| { v.push(2); v.len() }), 2); + assert_eq!(slot.with(|s: &mut String| s.len()), 0); + assert_eq!(slot.with(|v: &mut Vec| v.len()), 0, "the Vec was replaced by the String"); + slot.clear(); + assert_eq!(slot.with(|s: &mut String| s.len()), 0); + } +} diff --git a/src/vt/mod.rs b/src/vt/mod.rs index 0dabae9a..d224aaa7 100644 --- a/src/vt/mod.rs +++ b/src/vt/mod.rs @@ -1,5 +1,6 @@ pub mod backend; pub mod codec; +pub mod derived; pub mod detect; mod framer; pub mod ghostty_backend; @@ -148,6 +149,7 @@ pub struct VtParser { /// `false` once `primary_stream_log` has been truncated or invalidated by a rebuild, after /// which column changes reflow via [`VtParser::rebuild`] instead of replaying the log. primary_log_complete: bool, + derived: derived::DerivedSlot, } /// Smallest grid dimension handed to `vt100-ctt` (1-row grids panic on soft-wrap). @@ -225,6 +227,7 @@ impl VtParser { pending_canvas_osc: Vec::new(), primary_stream_log: Vec::new(), primary_log_complete: true, + derived: derived::DerivedSlot::default(), } } @@ -652,6 +655,7 @@ impl VtParser { pub fn size(&self) -> (u16, u16) { (self.rows, self.cols) } pub fn generation(&self) -> u64 { self.generation } + pub fn derived(&self) -> &derived::DerivedSlot { &self.derived } pub fn line_size_attr(&self, row: u16) -> LineSizeAttr { self.line_size_attrs.get(&row).copied().unwrap_or_default() } diff --git a/tests/full_suite_battle_and_perf.rs b/tests/full_suite_battle_and_perf.rs index f9beb72b..71be64b9 100644 --- a/tests/full_suite_battle_and_perf.rs +++ b/tests/full_suite_battle_and_perf.rs @@ -783,9 +783,13 @@ fn performance_and_stress_benchmark_verifies_sub_millisecond_frame_and_rpc_budge let mut ratatui_renderer = RatatuiWorkspaceRenderer; let mut buf = Buffer::empty(viewport); let render_start = Instant::now(); - for _ in 0..100 { - ratatui_renderer.render_workspace(&plane.wm, viewport, &mut buf); - } + // Time the shipping path: debug builds default the render cache to `Verify`, which paints + // every canvas twice and compares, and would be measured against the budget instead. + bilterm::ui::canvas_cache::with_render_cache_mode(bilterm::ui::canvas_cache::RenderCacheMode::On, || { + for _ in 0..100 { + ratatui_renderer.render_workspace(&plane.wm, viewport, &mut buf); + } + }); let avg_frame_us = render_start.elapsed().as_micros() as f64 / 100.0; assert!( avg_frame_us < 16_000.0, diff --git a/tests/perf_render_frame.rs b/tests/perf_render_frame.rs new file mode 100644 index 00000000..b8732cba --- /dev/null +++ b/tests/perf_render_frame.rs @@ -0,0 +1,169 @@ +//! Frame-time measurement harness for the workspace renderer (responsiveness 3b). +//! +//! Not part of the normal suite: every test here is `#[ignore]` and makes no wall-clock +//! assertion. Run (release, numbers in debug are dominated by unoptimised float maths): +//! +//! ```text +//! cargo test --release --test perf_render_frame -- --ignored --nocapture +//! BILTERM_PERF_ITERS=400 cargo test --release --test perf_render_frame -- --ignored --nocapture +//! ``` +mod render_fixture; + +use std::hint::black_box; +use std::time::{Duration, Instant}; + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::widgets::Widget; + +use bilterm::config::BiltermConfig; +use bilterm::ui::contrast::readable_canvas_cell_style; +use bilterm::ui::{CompositePaneWidget, WorkspaceWidget}; +use bilterm::wm::WindowManager; + +fn iters() -> usize { + std::env::var("BILTERM_PERF_ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(200) +} + +/// Median wall time of `f` over `n` runs (after 5 warm-up runs). +fn median(n: usize, mut f: impl FnMut()) -> Duration { + for _ in 0..5 { + f(); + } + let mut samples: Vec = (0..n) + .map(|_| { + let t = Instant::now(); + f(); + t.elapsed() + }) + .collect(); + samples.sort(); + samples[samples.len() / 2] +} + +fn us(d: Duration) -> f64 { + d.as_secs_f64() * 1e6 +} + +fn frame(wm: &WindowManager, area: Rect, buf: &mut Buffer) { + buf.reset(); + WorkspaceWidget::new(wm).render(area, buf); +} + +#[test] +#[ignore = "measurement harness; run explicitly with --ignored --nocapture"] +fn frame_time_and_breakdown_6_panes_200x60() { + let n = iters(); + let (mut wm, area) = render_fixture::build_workspace(200, 60, 6); + let mut buf = Buffer::empty(area); + let ids: Vec<_> = wm.compute_workspace_rects(area).into_iter().map(|(id, _)| id).collect(); + + // --- whole frame ------------------------------------------------------------------------- + let idle = median(n, || frame(&wm, area, &mut buf)); + wm.toggle_help(); + assert!(wm.is_help_visible()); + let idle_overlay = median(n, || frame(&wm, area, &mut buf)); + wm.toggle_help(); + + // One pane receives output before every frame (the common "one busy pane" case). + let busy_id = ids[0]; + let mut tick = 0usize; + let busy = median(n, || { + tick += 1; + let line = format!("\x1b[32mtick\x1b[0m {tick} https://example.org/t/{tick}\r\n"); + wm.pane_mut(busy_id).unwrap().process_pty_output(line.as_bytes()); + frame(&wm, area, &mut buf); + }); + let busy_feed_only = median(n, || { + tick += 1; + let line = format!("\x1b[32mtick\x1b[0m {tick} https://example.org/t/{tick}\r\n"); + wm.pane_mut(busy_id).unwrap().process_pty_output(line.as_bytes()); + }); + + // --- breakdown (same data, component cost in isolation) --------------------------------- + // Claim 2: per-cell contrast maths over every visible cell of every pane. + let cfg = wm.config().clone(); + let palette = cfg.palette(); + let mut cells = 0usize; + let contrast = median(n, || { + cells = 0; + for id in &ids { + let vt = wm.pane(*id).unwrap().vt(); + let (rows, cols) = vt.size(); + for r in 0..rows { + for c in 0..cols { + if let Some(cell) = vt.cell_view(r, c) { + black_box(readable_canvas_cell_style(&cell, cfg.theme, &palette)); + cells += 1; + } + } + } + } + }); + // Cell iteration alone, to subtract from the contrast figure. + let cell_walk = median(n, || { + for id in &ids { + let vt = wm.pane(*id).unwrap().vt(); + let (rows, cols) = vt.size(); + for r in 0..rows { + for c in 0..cols { + black_box(vt.cell_view(r, c)); + } + } + } + }); + + // Claim 3: URL detection and trigger scans, every pane. + let urls = median(n, || { + for id in &ids { + black_box(wm.pane(*id).unwrap().vt().detect_visible_urls()); + } + }); + let triggers = ["ERROR", "warning", "TODO"]; + let trig = median(n, || { + for id in &ids { + for t in triggers { + black_box(wm.pane(*id).unwrap().vt().search_canvas(t)); + } + } + }); + + // Claim 4: per-pane config clone + palette resolve, and BiltermConfig::default(). + let cfg_clone = median(n, || { + for id in &ids { + black_box(wm.pane_chrome(*id).resolve_config_and_palette(wm.config())); + } + }); + let cfg_default = median(n, || { + for _ in &ids { + black_box(BiltermConfig::default()); + } + }); + + // Claim 1: pane composition (all passes) vs. the rest of the frame (chrome + overlays). + let rects = wm.compute_workspace_rects(area); + let panes_only = median(n, || { + for (id, rect) in &rects { + let pane = wm.pane(*id).unwrap(); + CompositePaneWidget::with_config(pane, false, wm.config()).render(*rect, &mut buf); + } + }); + + // Same frame with three output triggers configured. + wm.config_mut().triggers = triggers.iter().map(|s| s.to_string()).collect(); + let idle_triggers = median(n, || frame(&wm, area, &mut buf)); + + eprintln!("== perf_render_frame: 6 panes, 200x60, {n} iterations, median, {} ==", + if cfg!(debug_assertions) { "DEBUG build" } else { "release build" }); + eprintln!("frame idle (nothing changed) {:>9.1} us", us(idle)); + eprintln!("frame idle + help overlay {:>9.1} us", us(idle_overlay)); + eprintln!("frame idle + 3 triggers {:>9.1} us", us(idle_triggers)); + eprintln!("frame, one busy pane (feed + render) {:>9.1} us (feed alone {:.1} us)", us(busy), us(busy_feed_only)); + eprintln!("-- breakdown, all 6 panes --"); + eprintln!("pane composition (6 pane widgets) {:>9.1} us", us(panes_only)); + eprintln!("contrast per cell ({cells} cells) {:>9.1} us (cell walk alone {:.1} us)", us(contrast), us(cell_walk)); + eprintln!("URL detection {:>9.1} us", us(urls)); + eprintln!("trigger scan (3 triggers) {:>9.1} us", us(trig)); + eprintln!("config clone + palette resolve {:>9.1} us", us(cfg_clone)); + eprintln!("BiltermConfig::default() x6 {:>9.1} us", us(cfg_default)); +} diff --git a/tests/render_cache_equivalence.rs b/tests/render_cache_equivalence.rs new file mode 100644 index 00000000..67624081 --- /dev/null +++ b/tests/render_cache_equivalence.rs @@ -0,0 +1,172 @@ +//! The render cache must never change a frame: for a sequence of workspace states, a frame drawn +//! with the cache on (cold, warming and hot) and in self-checking `Verify` mode equals the frame +//! drawn with the cache off. The states are applied to one long-lived workspace so that stored +//! layers survive from one state to the next; a missing cache-key input shows up as a stale frame. +mod render_fixture; + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::widgets::Widget; + +use bilterm::colon_command::{execute_wm_colon_command, parse_colon_command}; +use bilterm::ui::canvas_cache::{RenderCacheMode, with_render_cache_mode}; +use bilterm::ui::{CompositePaneWidget, WorkspaceWidget}; +use bilterm::wm::{WindowManager, WorkspaceLayoutMode}; + +fn render(mode: RenderCacheMode, wm: &WindowManager, area: Rect) -> Buffer { + let mut buf = Buffer::empty(area); + with_render_cache_mode(mode, || WorkspaceWidget::new(wm).render(area, &mut buf)); + buf +} + +/// Asserts cache-on (three frames: direct, store, hit) and `Verify` equal cache-off for the +/// current state, and returns the cache-off frame. +fn assert_cache_transparent(label: &str, wm: &WindowManager, area: Rect) -> Buffer { + let reference = render(RenderCacheMode::Off, wm, area); + for round in 0..3 { + let cached = render(RenderCacheMode::On, wm, area); + assert!(cached == reference, "{label}: cache-on frame {round} differs from cache-off frame"); + } + let verified = render(RenderCacheMode::Verify, wm, area); + assert!(verified == reference, "{label}: verify-mode frame differs from cache-off frame"); + reference +} + +fn colon(wm: &mut WindowManager, cmd: &str) { + let parsed = parse_colon_command(cmd) + .unwrap_or_else(|| panic!("{cmd}: not a command")) + .unwrap_or_else(|e| panic!("{cmd}: {e:?}")); + execute_wm_colon_command(wm, parsed); +} + +#[test] +fn workspace_frames_are_identical_with_cache_on_off_and_verify_across_state_changes() { + let (mut wm, area) = render_fixture::build_workspace(160, 48, 6); + let ids: Vec<_> = wm.compute_workspace_rects(area).into_iter().map(|(id, _)| id).collect(); + let mut frames: Vec<(String, Buffer)> = Vec::new(); + let mut step = |label: &str, wm: &WindowManager, must_change: bool| { + let frame = assert_cache_transparent(label, wm, area); + if must_change && let Some((prev_label, prev)) = frames.last() { + assert!(*prev != frame, "{label}: expected a visible change after {prev_label}"); + } + frames.push((label.to_string(), frame)); + }; + + step("initial tiled", &wm, false); + + // Grid content: one pane gets output; the others must keep their (cached) content. + wm.pane_mut(ids[1]).unwrap().process_pty_output(b"\x1b[1;31mNEW OUTPUT\x1b[0m https://example.org/new\r\n"); + step("output in one pane", &wm, true); + + // Scrollback: the generation does not change, only the offset. + wm.pane_mut(ids[0]).unwrap().vt_mut().scroll_up(7); + step("scrolled back", &wm, true); + wm.pane_mut(ids[0]).unwrap().vt_mut().reset_scrollback(); + step("scroll reset", &wm, true); + + // Global theme, then triggers and scanlines. + colon(&mut wm, ":theme 3279"); + step("global theme", &wm, true); + wm.config_mut().triggers = vec!["ERROR".to_string(), "warning".to_string()]; + step("triggers", &wm, true); + wm.config_mut().crt_scanlines = true; + step("crt scanlines", &wm, true); + wm.config_mut().crt_scanlines = false; + wm.config_mut().triggers.clear(); + step("triggers and scanlines off", &wm, true); + + // Per-window colour override on the focused pane only. + wm.active_pane_chrome_mut().colors.insert("bg".to_string(), "#202040".to_string()); + step("per-window bg", &wm, true); + wm.active_pane_chrome_mut().colors.insert("font-color".to_string(), "#ffcc00".to_string()); + step("per-window font colour", &wm, true); + + // State drawn above the cached layer: search, copy mode, hints. + wm.active_pane_mut().process_pty_output(b"needle in https://example.org/haystack at 10.0.0.1\r\n"); + wm.active_pane_mut().set_canvas_search("needle"); + step("canvas search", &wm, true); + wm.active_pane_mut().clear_canvas_search(); + wm.active_pane_mut().enter_copy_mode(); + step("copy mode", &wm, true); + wm.active_pane_mut().exit_copy_mode(); + wm.active_pane_mut().enter_hints_mode(); + step("hints mode", &wm, true); + wm.active_pane_mut().exit_hints_mode(); + step("hints off", &wm, true); + + // Overlays and layout. + wm.toggle_help(); + step("help modal", &wm, true); + wm.toggle_help(); + wm.toggle_palette(); + step("command palette", &wm, true); + wm.toggle_palette(); + wm.toggle_quick_terminal(); + step("quick terminal", &wm, true); + wm.toggle_quick_terminal(); + wm.set_layout_mode(WorkspaceLayoutMode::Stacked); + wm.resize_all(area).unwrap(); + step("stacked layout", &wm, true); + wm.shuffle_deck_next(); + step("stack shuffled", &wm, true); + wm.set_layout_mode(WorkspaceLayoutMode::Tiled); + wm.resize_all(area).unwrap(); + wm.toggle_zoom(); + step("zoomed pane", &wm, true); + wm.toggle_zoom(); + step("unzoomed", &wm, true); + + // Viewport resize: every pane gets a new canvas and grid size. + let small = Rect::new(0, 0, 120, 36); + wm.resize_all(small).unwrap(); + let reference = render(RenderCacheMode::Off, &wm, small); + for _ in 0..3 { + assert!(render(RenderCacheMode::On, &wm, small) == reference, "resized: cache-on differs"); + } + assert!(render(RenderCacheMode::Verify, &wm, small) == reference, "resized: verify differs"); +} + +#[test] +fn a_busy_pane_interleaved_with_idle_frames_never_shows_a_stale_frame() { + let (mut wm, area) = render_fixture::build_workspace(120, 40, 4); + let ids: Vec<_> = wm.compute_workspace_rects(area).into_iter().map(|(id, _)| id).collect(); + for i in 0..40usize { + // Output arrives on some frames only, so layers are stored, hit and invalidated. + if i % 3 != 1 { + let id = ids[i % ids.len()]; + let line = format!("\x1b[3{}mframe {i}\x1b[0m \x1b[7m inv \x1b[0m http://localhost/{i}\r\n", i % 8); + wm.pane_mut(id).unwrap().process_pty_output(line.as_bytes()); + } + if i % 7 == 0 { + wm.pane_mut(ids[0]).unwrap().vt_mut().scroll_up(2); + } + if i % 11 == 0 { + wm.pane_mut(ids[0]).unwrap().vt_mut().reset_scrollback(); + } + let cached = render(RenderCacheMode::On, &wm, area); + let reference = render(RenderCacheMode::Off, &wm, area); + assert!(cached == reference, "frame {i}: cache-on differs from cache-off"); + } +} + +#[test] +fn a_pane_drawn_at_two_sizes_in_one_frame_stays_correct() { + // The same pane rendered into two different rectangles (workspace view + a thumbnail) on + // alternating calls: both views must stay correct while they compete for the pane's cache. + let (wm, area) = render_fixture::build_workspace(100, 30, 2); + let pane = wm.active_pane(); + let rects = [Rect::new(0, 0, 100, 30), Rect::new(10, 5, 40, 12), Rect::new(3, 3, 61, 17)]; + let draw = |mode, rect: Rect| { + let mut buf = Buffer::empty(area); + with_render_cache_mode(mode, || CompositePaneWidget::with_config(pane, true, wm.config()).render(rect, &mut buf)); + buf + }; + for round in 0..5 { + for rect in rects { + assert!( + draw(RenderCacheMode::On, rect) == draw(RenderCacheMode::Off, rect), + "round {round} rect {rect:?}" + ); + } + } +} diff --git a/tests/render_fixture/mod.rs b/tests/render_fixture/mod.rs new file mode 100644 index 00000000..51bb6947 --- /dev/null +++ b/tests/render_fixture/mod.rs @@ -0,0 +1,76 @@ +//! Shared headless render fixture: a realistic multi-pane workspace with coloured output. +//! Used by the render-cache equivalence tests and by the `#[ignore]`d frame-time harness. +#![allow(dead_code)] + +use ratatui::layout::Rect; + +use bilterm::wm::split_tree::SplitDirection; +use bilterm::wm::WindowManager; + +/// Deterministic coloured terminal output for pane `seed`: SGR 16/256/TrueColor foregrounds, +/// highlighted backgrounds, inverse runs, bold/underline, a URL per few lines and wide glyphs. +pub fn coloured_output(seed: usize, lines: usize) -> Vec { + let mut out = String::new(); + for i in 0..lines { + let n = seed * 131 + i; + match n % 8 { + 0 => out.push_str(&format!( + "\x1b[1;32m Compiling\x1b[0m crate-{n} v0.{}.{} (\x1b[4;34mhttps://example.org/crates/{n}\x1b[0m)\r\n", + n % 9, + n % 13 + )), + 1 => out.push_str(&format!( + "\x1b[38;5;{}mwarning\x1b[0m: unused variable `\x1b[1mvalue_{n}\x1b[0m` \x1b[38;5;244m--> src/lib.rs:{}:{}\x1b[0m\r\n", + (n % 200) + 20, + n % 900, + n % 80 + )), + 2 => out.push_str(&format!( + "\x1b[48;5;22m\x1b[38;5;120m+ let total_{n} = items.iter().map(|i| i.cost).sum::();\x1b[0m\r\n" + )), + 3 => out.push_str(&format!( + "\x1b[48;5;52m\x1b[38;5;217m- let total_{n} = 0; // TODO ERROR remove\x1b[0m\r\n" + )), + 4 => { + for k in 0..40usize { + let r = (k * 6 + n) % 256; + let g = (k * 3 + n * 7) % 256; + let b = (255 + n - k * 5) % 256; + out.push_str(&format!("\x1b[38;2;{r};{g};{b}m#\x1b[48;2;{b};{r};{g}m \x1b[0m")); + } + out.push_str("\r\n"); + } + 5 => out.push_str(&format!( + "\x1b[7m STATUS \x1b[0m \x1b[33mjob {n}\x1b[0m \x1b[2mdim text\x1b[0m \x1b[3;35mitalic\x1b[0m see http://localhost:{}/job/{n}\r\n", + 3000 + n % 100 + )), + 6 => out.push_str(&format!( + "\x1b[36m{:>6}\x1b[0m │ \x1b[31mERROR\x1b[0m 日本語 wide ✓ plain text row number {n} with some trailing words\r\n", + n + )), + _ => out.push_str(&format!( + "plain default-colour output line {n} lorem ipsum dolor sit amet consectetur\r\n" + )), + } + } + out.into_bytes() +} + +/// Builds a tiled headless workspace of `panes` panes at `cols`x`rows`, every pane filled with +/// [`coloured_output`]. +pub fn build_workspace(cols: u16, rows: u16, panes: usize) -> (WindowManager, Rect) { + let area = Rect::new(0, 0, cols, rows); + let mut wm = WindowManager::new_headless(rows, cols); + for i in 1..panes { + let dir = if i % 2 == 1 { SplitDirection::Vertical } else { SplitDirection::Horizontal }; + wm.split_focused(dir).expect("split"); + } + wm.resize_all(area).expect("resize"); + let ids: Vec<_> = wm.compute_workspace_rects(area).into_iter().map(|(id, _)| id).collect(); + for (k, id) in ids.into_iter().enumerate() { + if let Some(p) = wm.pane_mut(id) { + p.process_pty_output(&coloured_output(k + 1, usize::from(rows) + 20)); + } + } + (wm, area) +}