diff --git a/desktop/src-tauri/crates/buzz-terminal/src/damage.rs b/desktop/src-tauri/crates/buzz-terminal/src/damage.rs index f0e235b1ae..15097fbd49 100644 --- a/desktop/src-tauri/crates/buzz-terminal/src/damage.rs +++ b/desktop/src-tauri/crates/buzz-terminal/src/damage.rs @@ -8,6 +8,34 @@ //! 2. **Damage over-reports.** `Term::damage()` marks the cursor line every //! call, so an idle terminal reports damage nearly every frame. Per-line //! content hashing suppresses those, so the transport never sees a no-op. +//! +//! # Why a frame is the whole viewport +//! +//! Nearly every frame is a full repaint: `Term::scroll_up_relative` calls +//! `mark_fully_damaged()` unconditionally, so any output reaching the bottom +//! row damages the whole grid. Partial damage is effectively the idle cursor. +//! +//! That is fine, and the reason is worth having here rather than in a review +//! thread. A full frame is O(viewport) *by construction* -- the grid is itself +//! the coalescing buffer -- so its cost does not depend on how fast the child +//! writes. Measured on a 200x50 grid, bytes per frame across four orders of +//! magnitude of output rate: 11,390 at an unthrottled flood (45,759 lines +//! scrolled per frame), 11,390 at ~1 MB/s, 11,390 at ~100 KB/s, 11,305 on a +//! slow build log. Constant to three digits. +//! +//! A scroll-aware diff inverts that: its cost is O(lines scrolled), unbounded, +//! and at 45,759 lines/frame it would ship ~915x more data than the full grid +//! it was optimising. It wins where nobody is watching and loses under `cat`. +//! +//! **Revisit if the viewport grows.** 80x24 costs 2.6 KB/frame (0.2 MB/s at +//! 60 Hz), 200x50 costs 11.4 KB (0.7 MB/s), 400x100 costs 42.8 KB (2.6 MB/s). +//! 400x100 is roughly 4x a typical maximised window and is where this decision +//! should be re-measured -- as a serialization/IPC question, not a damage one. +//! +//! Dedup earns its place in the interactive case rather than the streaming one: +//! typing is ~0.9 rows per keystroke, and an idle terminal ships 0 rows across +//! 60 frames instead of a cursor-line frame 60x/second. Idle is the load-bearing +//! one -- it is what the substrate does while sitting behind the GUI untouched. use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -15,9 +43,7 @@ use std::hash::{Hash, Hasher}; use alacritty_terminal::grid::Dimensions; use alacritty_terminal::index::{Column, Line}; use alacritty_terminal::term::cell::{Cell, Flags}; -use alacritty_terminal::term::{Term, TermDamage}; - -use crate::listener::Listener; +use alacritty_terminal::term::TermDamage; /// A run of cells sharing one visual style. #[derive(Debug, Clone, PartialEq, Eq)] @@ -67,6 +93,16 @@ pub struct Frame { pub cursor: CursorFrame, /// Whether the renderer should discard what it has and repaint. pub full: bool, + /// The viewport this frame describes. A change means the grid was resized + /// and row indices refer to a different geometry than the previous frame's. + /// Carried so the consumer can detect that from the frame itself instead of + /// trusting that no resize overtook it in flight. + pub generation: u64, + /// Grid dimensions this frame was captured at, so a full frame is + /// self-describing rather than only meaningful against a size the consumer + /// happens to remember. + pub columns: usize, + pub screen_lines: usize, } impl Frame { @@ -81,11 +117,16 @@ pub struct RawFrame { rows: Vec<(usize, Vec)>, cursor: CursorFrame, full: bool, + generation: u64, + columns: usize, + screen_lines: usize, } /// Copy the damaged rows out of the terminal. **Runs under the lock; does no /// encoding.** Keep this function boring — everything added here is lock hold. -pub fn capture(term: &mut Term) -> RawFrame { +pub fn capture(terminal: &mut crate::Terminal) -> RawFrame { + let generation = terminal.generation(); + let term = terminal.term_mut(); let columns = term.columns(); let screen_lines = term.screen_lines(); let cursor_point = term.grid().cursor.point; @@ -116,7 +157,14 @@ pub fn capture(term: &mut Term) -> RawFrame { }; term.reset_damage(); - RawFrame { rows, cursor, full } + RawFrame { + rows, + cursor, + full, + generation, + columns, + screen_lines, + } } /// Suppresses rows whose content did not actually change. @@ -132,6 +180,9 @@ impl Encoder { /// Encode a captured frame. **Runs with the lock released.** pub fn encode(&mut self, raw: RawFrame) -> Frame { + // A full frame invalidates the dedup cache. Both routes that produce + // one matter: a `mark_fully_damaged` from scroll/alt-swap, and a resize, + // where the cached hashes describe rows of a different width entirely. if raw.full { self.hashes.clear(); } @@ -154,6 +205,9 @@ impl Encoder { rows, cursor: raw.cursor, full: raw.full, + generation: raw.generation, + columns: raw.columns, + screen_lines: raw.screen_lines, } } } diff --git a/desktop/src-tauri/crates/buzz-terminal/src/lib.rs b/desktop/src-tauri/crates/buzz-terminal/src/lib.rs index c20c136a58..4dc529b6c2 100644 --- a/desktop/src-tauri/crates/buzz-terminal/src/lib.rs +++ b/desktop/src-tauri/crates/buzz-terminal/src/lib.rs @@ -74,6 +74,7 @@ pub struct Terminal { term: Term, feeder: reader::Feeder, size: Size, + generation: u64, } impl Terminal { @@ -85,6 +86,7 @@ impl Terminal { term, feeder: reader::Feeder::new(fences), size, + generation: 0, }, actions, ) @@ -107,6 +109,36 @@ impl Terminal { self.size } + /// Which viewport the grid currently has, incremented on every applied + /// resize. Stamped onto each [`damage::Frame`] so a consumer can tell that + /// a frame describes a *different* grid than the one it last drew, without + /// having to infer it from message ordering. + pub fn generation(&self) -> u64 { + self.generation + } + + /// Apply a new viewport. + /// + /// Takes one target size, never a stream of them: resize is superlinear in + /// scrollback (2.5-4.7 ms per single column change at 10k history, and 40 + /// sequential 1-column steps cost 7.4x their coalesced equivalent), and it + /// runs while holding the terminal. Coalescing is the caller's job; this + /// function's job is to make the result observable. + /// + /// A resize forces a full damage frame -- upstream's `TermDamageState` + /// sets `full` in its own `resize` (`term/mod.rs:240`) -- which is what + /// keeps the encoder's per-line hashes from suppressing reflowed content. + /// The generation bump is belt-and-braces on top of that: it lets the + /// consumer *verify* it received the discontinuity rather than assume it. + pub fn resize(&mut self, size: Size) { + if size == self.size { + return; + } + self.term.resize(size); + self.size = size; + self.generation += 1; + } + pub fn term(&self) -> &Term { &self.term } diff --git a/desktop/src-tauri/crates/buzz-terminal/src/shared.rs b/desktop/src-tauri/crates/buzz-terminal/src/shared.rs index dba7de80da..918335eef4 100644 --- a/desktop/src-tauri/crates/buzz-terminal/src/shared.rs +++ b/desktop/src-tauri/crates/buzz-terminal/src/shared.rs @@ -163,13 +163,19 @@ impl SharedTerminal { pub fn render(&self, encoder: &mut Encoder) -> Frame { let raw = { let mut term = self.acquire(&self.renderer); - damage::capture(term.term_mut()) + damage::capture(&mut term) }; encoder.encode(raw) } - /// Take the lock for something the two methods above don't cover (resize, - /// input, reading stats). Metered on the renderer plane, since anything + /// Apply a coalesced resize. Renderer plane: this competes with the + /// renderer for the same lock and can hold it for milliseconds. + pub fn resize(&self, size: crate::Size) { + self.acquire(&self.renderer).resize(size); + } + + /// Take the lock for something the methods above don't cover (input, + /// reading stats). Metered on the renderer plane, since anything /// that isn't the read loop competes with the renderer for the same lock. pub fn lock(&self) -> MutexGuard<'_, Terminal> { self.acquire(&self.renderer) diff --git a/desktop/src-tauri/crates/buzz-terminal/tests/resize.rs b/desktop/src-tauri/crates/buzz-terminal/tests/resize.rs new file mode 100644 index 0000000000..f269e3d917 --- /dev/null +++ b/desktop/src-tauri/crates/buzz-terminal/tests/resize.rs @@ -0,0 +1,149 @@ +//! The resize seam: what a consumer is allowed to rely on across a reflow. +//! +//! The dedup encoder caches a hash per line. A resize reflows content into +//! rows of a different width, so those cached hashes describe a grid that no +//! longer exists -- if a resize did not force a full frame, dedup could +//! suppress a row whose content genuinely changed and leave the renderer +//! showing reflowed-away text. +//! +//! It does force one: upstream's `TermDamageState::resize` sets `full` +//! (`alacritty_terminal-0.26.0` term/mod.rs:240). These fixtures hold that +//! behaviour to the seam, because it is upstream's invariant and not ours. + +use buzz_terminal::damage::Encoder; +use buzz_terminal::fences::Fences; +use buzz_terminal::{Action, SharedTerminal, Size, Terminal}; +use std::sync::mpsc::Receiver; + +/// The receiver is returned rather than dropped: dropping it disconnects the +/// channel, and every subsequent listener send silently fails. These fixtures +/// don't assert on actions, but a fixture that quietly disables a code path is +/// how a future assertion gets written against a dead one. +fn shared(size: Size) -> (SharedTerminal, Receiver) { + let (term, actions) = Terminal::new(size, Fences::ALL); + (SharedTerminal::new(term), actions) +} + +fn size(columns: usize) -> Size { + Size { + columns, + screen_lines: 10, + scrollback: 1000, + } +} + +fn grid(columns: usize, screen_lines: usize) -> Size { + Size { + columns, + screen_lines, + scrollback: 1000, + } +} + +/// A resize invalidates dedup and republishes the whole grid at the new width. +#[test] +fn resize_forces_a_full_frame_at_the_new_width() { + let (shared, _actions) = shared(size(40)); + let mut encoder = Encoder::new(); + shared.feed(b"\x1b[2J\x1b[Hhello world\r\nsecond line\r\n"); + + let first = shared.render(&mut encoder); + assert!(first.full, "first frame after a fresh Term must be full"); + assert_eq!(first.columns, 40); + assert_eq!(first.generation, 0); + + // Nothing changed: dedup suppresses everything. Without this the next + // assertion could pass simply because every frame is full. + let idle = shared.render(&mut encoder); + assert!(!idle.full, "an unchanged grid must not republish"); + assert!( + idle.rows.is_empty(), + "dedup let {} unchanged rows through", + idle.rows.len() + ); + + shared.resize(size(20)); + let after = shared.render(&mut encoder); + assert!( + after.full, + "a resize must invalidate the renderer's cached rows" + ); + assert_eq!( + after.columns, 20, + "frame does not describe the new viewport" + ); + assert_eq!( + after.generation, 1, + "generation must advance across a resize" + ); + assert_eq!(after.rows.len(), 10, "full frame must carry every line"); + let row0: String = after.rows[0] + .spans + .iter() + .map(|s| s.text.as_str()) + .collect(); + assert_eq!(row0.chars().count(), 20, "row emitted at the old width"); + assert!( + row0.starts_with("hello world"), + "content lost across reflow: {row0:?}" + ); +} + +/// A no-op resize is not a resize: it must not burn a generation, or every +/// `ResizeObserver` tick would look like a discontinuity to the consumer. +#[test] +fn identical_resize_is_inert() { + let (shared, _actions) = shared(size(40)); + let mut encoder = Encoder::new(); + shared.feed(b"hello"); + shared.render(&mut encoder); + + shared.resize(size(40)); + let after = shared.render(&mut encoder); + assert_eq!( + after.generation, 0, + "a same-size resize advanced the generation" + ); + assert!( + !after.full, + "a same-size resize forced a needless full repaint" + ); +} + +/// A **full frame must carry every row**, including rows whose content is +/// byte-identical to what sat at that index before the resize. +/// +/// This is the arm that catches a dedup cache surviving a full frame, and the +/// width-changing fixture above does *not* catch it: changing the width changes +/// every row's cell contents, so the hashes differ and the rows are emitted for +/// the wrong reason. A **height-only** resize keeps the width, so reflowed rows +/// hash exactly as before -- and a stale cache suppresses them right after the +/// consumer was told to discard what it had. The result is a renderer holding +/// nothing where content should be. +/// +/// Verified concretely: growing 10 -> 20 lines moves "hello world" from row 0 +/// to row 1, so correctness here is not merely about frame bookkeeping. +#[test] +fn full_frame_after_height_resize_republishes_unchanged_rows() { + let (shared, _actions) = shared(grid(40, 10)); + let mut encoder = Encoder::new(); + shared.feed(b"\x1b[2J\x1b[Hhello world\r\nsecond line"); + let first = shared.render(&mut encoder); + assert!(first.full); + assert_eq!(first.rows.len(), 10); + + shared.resize(grid(40, 20)); + let after = shared.render(&mut encoder); + assert!( + after.full, + "a resize must invalidate the renderer's cached rows" + ); + assert_eq!(after.screen_lines, 20); + assert_eq!( + after.rows.len(), + 20, + "full frame carried {} of 20 rows -- dedup suppressed rows the consumer \ + was simultaneously told to discard, leaving them blank", + after.rows.len() + ); +}