Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

perf(term): batch single-width erase and repeat writes

RoversXcec8d0abdb25
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index 5ebdf1d1..5e349b59 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -32,6 +32,8 @@ mod keyboard;
pub(crate) mod kitty;
mod mouse;
pub(crate) mod performer;
+#[cfg(all(test, feature = "use_serde"))]
+mod repeat_tests;
mod sixel;
#[cfg(feature = "use_serde")]
mod snapshot;
@@ -2479,15 +2481,24 @@ impl TerminalState {
n
};
- for _ in 0..n {
+ let mut remaining = n;
+ while remaining > 0 {
+ // Batch only within a row. Wrapping and scrolling must
+ // still happen at precisely the same cell as scalar REP.
+ let count = if cell.width() == 1 && left_and_right_margins.contains(&x) {
+ remaining.min(left_and_right_margins.end - x)
+ } else {
+ 1
+ };
{
let screen = self.screen_mut();
let line_idx = screen.phys_row(y);
let line = screen.line_mut(line_idx);
- line.set_cell(x, cell.clone(), seqno);
+ line.set_cell_range(x..x + count, &cell, seqno);
}
- x += 1;
+ remaining -= count;
+ x += count;
if x > left_and_right_margins.end - 1 {
x = left_and_right_margins.start;
if y == top_and_bottom_margins.end - 1 {
diff --git a/term/src/terminalstate/repeat_tests.rs b/term/src/terminalstate/repeat_tests.rs
new file mode 100644
index 00000000..f77607b8
--- /dev/null
+++ b/term/src/terminalstate/repeat_tests.rs
@@ -0,0 +1,143 @@
+//! Differential coverage against the scalar REP implementation.
+use super::*;
+
+#[derive(Debug)]
+struct TestConfig {
+ scrollback: usize,
+}
+impl TerminalConfiguration for TestConfig {
+ fn scrollback_size(&self) -> usize {
+ self.scrollback
+ }
+ fn color_palette(&self) -> ColorPalette {
+ ColorPalette::default()
+ }
+}
+
+impl TerminalState {
+ // Reference from before row batching. Keep the per-cell loop independent
+ // of set_cell_range so a regression cannot change both sides of the test.
+ fn scalar_repeat_for_test(&mut self, n: u32) {
+ let seqno = self.seqno;
+
+ let mut y = self.cursor.y;
+ let mut x = self.cursor.x;
+ let left_and_right_margins = self.left_and_right_margins.clone();
+ let top_and_bottom_margins = self.top_and_bottom_margins.clone();
+
+ // Resolve the source cell. It may be a double-wide character.
+ let cell = {
+ let screen = self.screen_mut();
+ let to_copy = x.saturating_sub(1);
+ let line_idx = screen.phys_row(y);
+ let line = screen.line_mut(line_idx);
+
+ match line.cells_mut().get(to_copy).cloned() {
+ None => Cell::blank(),
+ Some(candidate) => {
+ if candidate.str() == " " && to_copy > 0 {
+ // It's a blank. It may be the second part of
+ // a double-wide pair; look ahead of it.
+ let prior = &line.cells_mut()[to_copy - 1];
+ if prior.width() > 1 {
+ prior.clone()
+ } else {
+ candidate
+ }
+ } else {
+ candidate
+ }
+ }
+ }
+ };
+
+ // Repeats wrap and scroll, so unlike ICH the screen keeps
+ // changing -- but only until the viewport and the scrollback
+ // hold nothing but the repeated cell. Past that only the cursor
+ // column still depends on n, and it cycles with the margin
+ // width, so keeping the remainder leaves the cursor exactly
+ // where it would have landed and drops the rest. Otherwise n
+ // reaches u32::MAX and this loop runs for a minute.
+ let width = (left_and_right_margins.end - left_and_right_margins.start).max(1);
+ let saturated =
+ width.saturating_mul(self.screen().physical_rows + self.config.scrollback_size());
+ let n = n as usize;
+ let n = if n > saturated {
+ saturated + (n % width)
+ } else {
+ n
+ };
+
+ for _ in 0..n {
+ {
+ let screen = self.screen_mut();
+ let line_idx = screen.phys_row(y);
+ let line = screen.line_mut(line_idx);
+
+ line.set_cell(x, cell.clone(), seqno);
+ }
+ x += 1;
+ if x > left_and_right_margins.end - 1 {
+ x = left_and_right_margins.start;
+ if y == top_and_bottom_margins.end - 1 {
+ self.scroll_up(1);
+ } else {
+ y += 1;
+ if y > top_and_bottom_margins.end - 1 {
+ y = top_and_bottom_margins.end;
+ }
+ }
+ }
+ }
+ self.cursor.x = x;
+ self.cursor.y = y;
+ }
+}
+
+#[test]
+fn batched_repeat_matches_scalar_screen_cursor_and_scrollback() {
+ for (rows, cols, scrollback) in [(1, 2, 0), (3, 7, 0), (3, 7, 4)] {
+ for setup in [
+ "abc",
+ "a界",
+ "e\u{301}",
+ "🙂",
+ "\x1b[44m ",
+ "\x1b[?1049habc",
+ "\x1b[?7labc",
+ "\x1b[2;3r\x1b[3;6Hq",
+ "\x1b[?69h\x1b[2;6s\x1b[3;6Hq",
+ "\x1b]8;;https://example.com\x1b\\q",
+ ] {
+ for n in [0, 1, 2, 7, 8, 19, 50, u32::MAX] {
+ let make = || {
+ let mut term = Terminal::new(
+ TerminalSize {
+ rows,
+ cols,
+ pixel_width: cols * 8,
+ pixel_height: rows * 16,
+ dpi: 96,
+ },
+ Arc::new(TestConfig { scrollback }),
+ "test",
+ "test",
+ Box::new(Vec::new()),
+ );
+ term.advance_bytes(setup);
+ term.increment_seqno();
+ term
+ };
+ let mut expected = make();
+ expected.scalar_repeat_for_test(n);
+ let mut actual = make();
+ actual.perform_csi_edit(Edit::Repeat(n));
+ assert_eq!(
+ actual.snapshot(),
+ expected.snapshot(),
+ "rows={rows}, cols={cols}, scrollback={scrollback}, setup={setup:?}, n={n}"
+ );
+ }
+ }
+ }
+}
diff --git a/wezterm-surface/src/line/line.rs b/wezterm-surface/src/line/line.rs
index b4d5780b..655a48ab 100644
--- a/wezterm-surface/src/line/line.rs
+++ b/wezterm-surface/src/line/line.rs
@@ -1002,11 +1002,51 @@ impl Line {
// them all away again before we return; NOP
return;
}
+ self.set_cell_range_impl(cols, cell, true, seqno);
+ self.prune_trailing_blanks(seqno);
+ }
+
+ /// Equivalent to calling `set_cell` at each column, including preservation
+ /// of Kitty image placements. Unlike `fill_range`, this does not prune
+ /// trailing blanks or erase image placements.
+ pub fn set_cell_range(&mut self, cols: Range<usize>, cell: &Cell, seqno: SequenceNo) {
+ self.set_cell_range_impl(cols, cell, false, seqno);
+ }
+
+ fn set_cell_range_impl(
+ &mut self,
+ mut cols: Range<usize>,
+ cell: &Cell,
+ clear_image_placements: bool,
+ seqno: SequenceNo,
+ ) {
+ let Some(first) = cols.next() else {
+ return;
+ };
+ // The first write handles an overlapping wide cell, invalidates links
+ // and zones, and updates the sequence number exactly as a scalar write.
+ self.set_cell_impl(first, cell.clone(), clear_image_placements, seqno);
+
+ if cell.width() == 1 && !cols.is_empty() {
+ if let CellStorage::V(cells) = &mut self.cells {
+ if cols.end > cells.len() {
+ cells.resize_with(cols.end, Cell::blank);
+ }
+ // Every preceding cell in this run has just been written with
+ // width one, so subsequent writes cannot overlap a wide cell
+ // on their left. Keep VecStorage's image-placement semantics.
+ for x in cols {
+ cells.set_cell(x, cell.clone(), clear_image_placements);
+ }
+ return;
+ }
+ }
+
+ // Preserve compact append storage and the scalar semantics of wide or
+ // zero-width cells. Never expand a compact line just for this fast path.
for x in cols {
- // FIXME: we can skip the look-back for second and subsequent iterations
- self.set_cell_impl(x, cell.clone(), true, seqno);
+ self.set_cell_impl(x, cell.clone(), clear_image_placements, seqno);
}
- self.prune_trailing_blanks(seqno);
}
pub fn len(&self) -> usize {
diff --git a/wezterm-surface/src/line/test.rs b/wezterm-surface/src/line/test.rs
index 657e8a7b..798cb96b 100644
--- a/wezterm-surface/src/line/test.rs
+++ b/wezterm-surface/src/line/test.rs
@@ -8,6 +8,153 @@ use alloc::sync::Arc;
use k9::assert_equal as assert_eq;
use wezterm_cell::{Cell, CellAttributes};
+// Keep a scalar reference so the fast path is checked against the old behavior,
+// including less visible state such as hyperlinks, sequence numbers and zones.
+fn scalar_range(line: &mut Line, range: core::ops::Range<usize>, cell: &Cell, clear: bool) {
+ if clear && line.len() == 0 && *cell == Cell::blank() {
+ return;
+ }
+ for x in range {
+ if clear {
+ line.set_cell_clearing_image_placements(x, cell.clone(), 42);
+ } else {
+ line.set_cell(x, cell.clone(), 42);
+ }
+ }
+ if clear {
+ line.prune_trailing_blanks(42);
+ }
+}
+
+fn check_range_against_scalar(
+ base: &Line,
+ range: core::ops::Range<usize>,
+ cell: &Cell,
+ clear: bool,
+) {
+ let mut expected = base.clone();
+ scalar_range(&mut expected, range.clone(), cell, clear);
+ let mut actual = base.clone();
+ if clear {
+ actual.fill_range(range.clone(), cell, 42);
+ } else {
+ actual.set_cell_range(range.clone(), cell, 42);
+ }
+ assert_eq!(
+ actual, expected,
+ "range={range:?}, cell={cell:?}, clear={clear}"
+ );
+ assert_eq!(
+ actual.semantic_zone_ranges(),
+ expected.semantic_zone_ranges()
+ );
+ assert_eq!(actual.compute_shape_hash(), expected.compute_shape_hash());
+}
+
+#[test]
+fn cell_ranges_match_scalar_writes_at_wide_boundaries_and_beyond_end() {
+ let mut colored = CellAttributes::default();
+ colored.set_background(wezterm_cell::color::ColorAttribute::PaletteIndex(4));
+ let cells = [
+ Cell::blank(),
+ Cell::blank_with_attrs(colored.clone()),
+ Cell::new('x', colored),
+ Cell::new_grapheme("界", CellAttributes::default(), None),
+ Cell::new_grapheme("e\u{301}", CellAttributes::default(), None),
+ ];
+ for text in ["", "abc ", "a界b🙂c", "界界", "e\u{301}x", " "] {
+ for compressed in [false, true] {
+ let mut base: Line = text.into();
+ if compressed {
+ base.compress_for_scrollback();
+ } else {
+ base.coerce_vec_storage();
+ }
+ for start in 0..base.len() + 3 {
+ for end in start..base.len() + 5 {
+ for cell in &cells {
+ for clear in [false, true] {
+ check_range_against_scalar(&base, start..end, cell, clear);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn cell_ranges_invalidate_implicit_links_and_preserve_explicit_links() {
+ let mut base: Line = "https://example.com abc".into();
+ base.scan_and_create_hyperlinks(&[Rule::new(r"https://\S+", "$0").unwrap()]);
+ let mut attrs = CellAttributes::default();
+ attrs.set_hyperlink(Some(Arc::new(Hyperlink::new("https://example.org"))));
+ attrs.set_semantic_type(wezterm_cell::SemanticType::Prompt);
+ base.semantic_zone_ranges();
+ for cell in [Cell::blank(), Cell::new('x', attrs)] {
+ for clear in [false, true] {
+ check_range_against_scalar(&base, 2..15, &cell, clear);
+ check_range_against_scalar(&base, 2..2, &cell, clear);
+ }
+ }
+}
+
+#[test]
+fn appending_ranges_keeps_compact_storage() {
+ let mut line = Line::new(0);
+ line.set_cell_range(0..4096, &Cell::new('x', CellAttributes::default()), 1);
+ assert!(line.is_compressed_for_scrollback());
+ assert_eq!(line.len(), 4096);
+ let mut empty = Line::new(0);
+ empty.fill_range(0..usize::MAX, &Cell::blank(), 1);
+ assert_eq!(empty.len(), 0);
+ assert!(empty.is_compressed_for_scrollback());
+}
+
+#[cfg(feature = "use_image")]
+#[test]
+fn cell_ranges_preserve_or_clear_image_placements_like_scalar_writes() {
+ use wezterm_cell::image::{ImageCell, ImageData, ImageDataType, TextureCoordinate};
+ let data = Arc::new(ImageData::with_data(ImageDataType::new_single_frame(
+ 1,
+ 1,
+ vec![255; 4],
+ )));
+ let mut base: Line = "a界b cdef".into();
+ for x in 0..base.len() {
+ for placement in [None, Some(7)] {
+ base.cells_mut()[x]
+ .attrs_mut()
+ .attach_image(Box::new(ImageCell::with_z_index(
+ TextureCoordinate::new_f32(0.0, 0.0),
+ TextureCoordinate::new_f32(1.0, 1.0),
+ Arc::clone(&data),
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ Some(3),
+ placement,
+ )));
+ }
+ }
+ let image_cell = base.cells_mut()[4].clone();
+ for cell in [
+ Cell::blank(),
+ Cell::new('x', CellAttributes::default()),
+ image_cell,
+ ] {
+ for start in 0..base.len() {
+ for end in start..base.len() + 2 {
+ for clear in [false, true] {
+ check_range_against_scalar(&base, start..end, &cell, clear);
+ }
+ }
+ }
+ }
+}
+
/// There are 4 double-wide graphemes that occupy 2 cells each.
/// When we join the lines, we must preserve the invisible blank
/// that is part of the grapheme otherwise our metrics will be