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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Tune overview rendering and frame throttling
RoversXaea785209af6
diff --git a/.gitignore b/.gitignoreindex 6d245d8c..5302d77a 100644--- a/.gitignore+++ b/.gitignore@@ -77,3 +77,6 @@ ThinkTerm-macos-v0.1.0.zip/docs/*!/docs/thinkterm/!/docs/thinkterm/*.md++# well...+/.claudediff --git a/config/src/config.rs b/config/src/config.rsindex 16381a84..0acfb921 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -849,6 +849,20 @@ pub struct Config {#[dynamic(default = "default_max_fps")]pub max_fps: u64,+ /// How often, in milliseconds, a live overview card re-reads the terminal+ /// it is showing.+ ///+ /// A card that re-reads has to rebuild its thumbnail, and that is by far+ /// the most expensive thing the overview does: with several cards visible,+ /// a frame that rebuilds one takes around 12ms against a 8.3ms budget while+ /// a frame that rebuilds none takes 5ms. This number decides how many+ /// frames land in which group, so it is the main handle on how smooth the+ /// overview feels against how live the thumbnails look.+ ///+ /// Dynamic, so it can be tuned without a restart.+ #[dynamic(default = "default_live_overview_preview_refresh_ms")]+ pub live_overview_preview_refresh_ms: u64,+#[dynamic(default = "default_shape_cache_size")]pub shape_cache_size: usize,#[dynamic(default = "default_line_state_cache_size")]@@ -2302,20 +2316,33 @@ fn default_note_reading_max_width() -> usize {820}+fn default_live_overview_preview_refresh_ms() -> u64 {+ 300+}++/// These four sizes were set when a window showed one terminal. ThinkTerm's+/// live overview draws six at once, each at its own font size -- and the caches+/// are keyed by size, so six thumbnails of the same text are six sets of+/// entries. At 1024 that thrashed: a profile of the overview over busy+/// terminals put 87% of a thumbnail's cost in HarfBuzz, re-shaping text the+/// cache had just evicted.+///+/// An entry is a shaped cluster -- glyph indices and offsets, no pixels -- so+/// the memory is small next to the atlas it saves work against.fn default_shape_cache_size() -> usize {- 1024+ 16384}fn default_line_state_cache_size() -> usize {- 1024+ 4096}fn default_line_quad_cache_size() -> usize {- 1024+ 4096}fn default_line_to_ele_shape_cache_size() -> usize {- 1024+ 8192}#[derive(Debug, ToDynamic, Clone, Copy, PartialEq, Eq, Default)]diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 185c2b15..cbdc728e 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -1094,19 +1094,33 @@ impl Mux {}pub fn current_identity_owns_frontend_lease(&self, tab_id: TabId) -> bool {+ // An UNCLAIMED lease belongs to whoever is asking. The lease exists to+ // stop two frontends fighting over one tab's geometry; when nobody+ // holds it there is nothing to protect, and answering "not yours"+ // paralyzes the only frontend present: the GUI's local viewport+ // publish can fail its compose validation ("frontend frames do not+ // compose"), the lease then never gets claimed, and every pane-size+ // sync behind `owns_frontend_viewport` is silently skipped -- measured+ // as split-divider drags leaving TUIs at their old PTY size until the+ // drag ends. The identity-less arm below already treated unclaimed as+ // permitted; this makes the identified arm consistent.+ let unclaimed = {+ let lease = self.frontend_lease.lock();+ match lease.access_mode {+ FrontendAccessMode::Handoff => lease.handoff_owner.is_none(),+ FrontendAccessMode::TmuxLatest => lease+ .tabs+ .get(&tab_id)+ .and_then(|state| state.owner.as_ref())+ .is_none(),+ }+ };+ if unclaimed {+ return true;+ }match self.active_identity() {Some(identity) => self.client_owns_frontend_lease(&identity, tab_id),- None => {- let lease = self.frontend_lease.lock();- match lease.access_mode {- FrontendAccessMode::Handoff => lease.handoff_owner.is_none(),- FrontendAccessMode::TmuxLatest => lease- .tabs- .get(&tab_id)- .and_then(|state| state.owner.as_ref())- .is_none(),- }- }+ None => false,}}diff --git a/wezterm-gui/src/framedump.rs b/wezterm-gui/src/framedump.rsnew file mode 100644index 00000000..69f6d328--- /dev/null+++ b/wezterm-gui/src/framedump.rs@@ -0,0 +1,184 @@+//! Dump rendered frames to PNG on request, so the picture the user sees can+//! be inspected without screen-recording permissions.+//!+//! Enable by launching with `THINKTERM_FRAME_DUMP=<dir>`. Nothing is captured+//! until a file named `trigger` appears in that directory:+//! - an empty (or any) `trigger` file: the next frame is written and the+//! trigger is consumed;+//! - a `trigger` containing the word `all`: every frame is written, at most+//! four per second, until the file is removed.+//!+//! Frames land as `<dir>/frame-<pid>-<seq>.png`. Capture happens on the paint+//! path with a blocking map, costing a few milliseconds -- this is a debugging+//! tool, not something to leave triggered while measuring.++use std::cell::RefCell;+use std::path::PathBuf;+use std::sync::OnceLock;+use std::time::{Duration, Instant};++static DUMP_DIR: OnceLock<Option<PathBuf>> = OnceLock::new();++thread_local! {+ static LAST_DUMP: RefCell<Vec<(usize, Instant)>> = const { RefCell::new(Vec::new()) };+ static SEQ: RefCell<u64> = const { RefCell::new(0) };+}++const CONTINUOUS_MIN_INTERVAL: Duration = Duration::from_millis(250);++fn dump_dir() -> Option<&'static PathBuf> {+ DUMP_DIR+ .get_or_init(|| {+ let dir = std::env::var_os("THINKTERM_FRAME_DUMP").map(PathBuf::from);+ match &dir {+ Some(dir) => log::info!("framedump: enabled, dir={}", dir.display()),+ None => log::info!("framedump: THINKTERM_FRAME_DUMP not set"),+ }+ dir+ })+ .as_ref()+}++pub fn enabled() -> bool {+ dump_dir().is_some()+}++/// Whether this frame should be captured; consumes a one-shot trigger.+/// The continuous mode throttles per window, so a quiet window's frames are+/// not starved out by a busy one.+pub fn should_dump(window_label: usize) -> bool {+ let Some(dir) = dump_dir() else {+ return false;+ };+ let trigger = dir.join("trigger");+ let Ok(contents) = std::fs::read_to_string(&trigger) else {+ return false;+ };+ let contents = contents.trim();+ log::info!("framedump: trigger seen ({contents}) for win={window_label}");+ if contents == "burst" {+ // Every painted frame, no throttle: the only way to catch a+ // single-frame flicker. PNG encoding runs on the paint thread, so+ // this deliberately slows the app while active.+ true+ } else if contents == "all" {+ LAST_DUMP.with(|last| {+ let mut last = last.borrow_mut();+ let now = Instant::now();+ match last.iter_mut().find(|(label, _)| *label == window_label) {+ Some((_, prev)) if now.duration_since(*prev) < CONTINUOUS_MIN_INTERVAL => false,+ Some((_, prev)) => {+ *prev = now;+ true+ }+ None => {+ last.push((window_label, now));+ true+ }+ }+ })+ } else {+ let _ = std::fs::remove_file(&trigger);+ true+ }+}++/// Copy `texture` (the frame about to be presented) into a PNG on disk.+/// Blocks on the GPU for the copy; returns the path it wrote.+pub fn dump_texture(+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ texture: &wgpu::Texture,+ window_label: usize,+) -> anyhow::Result<PathBuf> {+ let dir = dump_dir().ok_or_else(|| anyhow::anyhow!("frame dump not enabled"))?;+ std::fs::create_dir_all(dir)?;++ let width = texture.width();+ let height = texture.height();+ let format = texture.format();+ let bytes_per_pixel = 4u32;+ let unpadded = width * bytes_per_pixel;+ let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;+ let padded = unpadded.div_ceil(align) * align;++ let buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("frame dump readback"),+ size: (padded * height) as u64,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("frame dump encoder"),+ });+ encoder.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo {+ texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::TexelCopyBufferInfo {+ buffer: &buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(padded),+ rows_per_image: Some(height),+ },+ },+ wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ );+ queue.submit(std::iter::once(encoder.finish()));++ let slice = buffer.slice(..);+ let (tx, rx) = std::sync::mpsc::channel();+ slice.map_async(wgpu::MapMode::Read, move |result| {+ let _ = tx.send(result);+ });+ device.poll(wgpu::PollType::Wait)?;+ rx.recv()??;++ let data = slice.get_mapped_range();+ let mut pixels = Vec::with_capacity((unpadded * height) as usize);+ for row in 0..height {+ let start = (row * padded) as usize;+ pixels.extend_from_slice(&data[start..start + unpadded as usize]);+ }+ drop(data);+ buffer.unmap();++ // The surface is BGRA on Metal; PNG wants RGBA.+ let is_bgra = matches!(+ format,+ wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb+ );+ if is_bgra {+ for px in pixels.chunks_exact_mut(4) {+ px.swap(0, 2);+ }+ }+ // The compositor owns real transparency; an opaque PNG is easier to read.+ for px in pixels.chunks_exact_mut(4) {+ px[3] = 0xff;+ }++ let seq = SEQ.with(|seq| {+ let mut seq = seq.borrow_mut();+ *seq += 1;+ *seq+ });+ let path = dir.join(format!(+ "frame-{}-win{window_label}-{seq:04}.png",+ std::process::id()+ ));+ let img = image::RgbaImage::from_raw(width, height, pixels)+ .ok_or_else(|| anyhow::anyhow!("pixel buffer size mismatch"))?;+ img.save(&path)?;+ log::info!("framedump: wrote {}", path.display());+ Ok(path)+}diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 0799d730..44faa582 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -39,6 +39,7 @@ mod colorease;mod commands;mod customglyph;mod download;+mod framedump;mod frontend;mod glyphcache;mod i18n;diff --git a/wezterm-gui/src/perf.rs b/wezterm-gui/src/perf.rsindex 528eef38..ecd4cdbe 100644--- a/wezterm-gui/src/perf.rs+++ b/wezterm-gui/src/perf.rs@@ -26,3 +26,56 @@ pub(crate) fn log_counter(label: &str, value: impl std::fmt::Display) {log::info!("thinkterm_perf {label}={value}");}}++thread_local! {+ static ACCUM: std::cell::RefCell<Vec<(&'static str, std::time::Duration, u64)>> =+ const { std::cell::RefCell::new(Vec::new()) };+}++/// Add `started.elapsed()` to a named accumulator. Costless when perf is off+/// (`now()` returned None). Accumulators live until `log_accums` drains them.+pub(crate) fn accum(label: &'static str, started: Option<Instant>) {+ let Some(started) = started else { return };+ let elapsed = started.elapsed();+ ACCUM.with(|accum| {+ let mut accum = accum.borrow_mut();+ if let Some(entry) = accum.iter_mut().find(|entry| entry.0 == label) {+ entry.1 += elapsed;+ entry.2 += 1;+ } else {+ accum.push((label, elapsed, 1));+ }+ });+}++/// Count an event without timing it.+pub(crate) fn accum_count(label: &'static str) {+ if !enabled() {+ return;+ }+ ACCUM.with(|accum| {+ let mut accum = accum.borrow_mut();+ if let Some(entry) = accum.iter_mut().find(|entry| entry.0 == label) {+ entry.2 += 1;+ } else {+ accum.push((label, std::time::Duration::ZERO, 1));+ }+ });+}++/// Drop whatever has accumulated so a section can measure only itself.+pub(crate) fn reset_accums() {+ ACCUM.with(|accum| accum.borrow_mut().clear());+}++/// Emit and clear every accumulator, prefixing each label.+pub(crate) fn log_accums(prefix: &str) {+ if !enabled() {+ return;+ }+ ACCUM.with(|accum| {+ for (label, total, count) in accum.borrow_mut().drain(..) {+ log::info!("thinkterm_perf {prefix}{label}={total:.2?} {prefix}{label}_n={count}");+ }+ });+}diff --git a/wezterm-gui/src/renderstate.rs b/wezterm-gui/src/renderstate.rsindex 3fdcf943..7dbb1167 100644--- a/wezterm-gui/src/renderstate.rs+++ b/wezterm-gui/src/renderstate.rs@@ -326,6 +326,12 @@ impl WebGpuVertexBuffer {}}+ /// Size of the buffer this recreates, which is the capacity high-water+ /// mark rather than what the frame actually uses.+ pub fn capacity_bytes(&self) -> usize {+ self.num_vertices * std::mem::size_of::<Vertex>()+ }+pub fn recreate(&mut self) -> wgpu::Buffer {let mut new_buf = self.state.device.create_buffer(&wgpu::BufferDescriptor {label: Some("Vertex Buffer"),diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 76b2a2a1..1bb72ff8 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -3593,6 +3593,7 @@ impl SettingsWindow {clear_color,corner_radius,window_border,+ usize::MAX, // settings window; no mux window behind it)?;Ok(true)}diff --git a/wezterm-gui/src/termwindow/content_view.rs b/wezterm-gui/src/termwindow/content_view.rsindex 1f019599..4a624a1d 100644--- a/wezterm-gui/src/termwindow/content_view.rs+++ b/wezterm-gui/src/termwindow/content_view.rs@@ -321,6 +321,9 @@ pub(crate) struct TerminalPreviewPaneSnapshot {#[derive(Clone, Debug)]pub(crate) struct TerminalPreviewRequest {+ /// Which card this thumbnail belongs to. The renderer keeps one cached+ /// quad heap per card and needs a stable identity to find it again.+ pub tab_id: TabId,pub snapshot: Arc<TerminalPreviewSnapshot>,pub area: RectF,pub clip: RectF,@@ -465,6 +468,11 @@ pub(crate) trait ContentView {/// same thing rather than one thing moving.fn set_terminal_in_flight(&mut self, _tab_id: Option<TabId>) {}+ /// The opening frame of a full-window transition records the terminal and+ /// grows the atlas; defer thumbnail capture until the next frame so that+ /// work is not stacked onto the click that triggered the transition.+ fn set_defer_preview_captures(&mut self, _defer: bool) {}+/// Paint masks and chrome that must sit above terminal preview glyphs./// Most ContentViews do not embed terminal snapshots and need no second/// pass.diff --git a/wezterm-gui/src/termwindow/live_overview.rs b/wezterm-gui/src/termwindow/live_overview.rsindex 2fe23485..880c3c81 100644--- a/wezterm-gui/src/termwindow/live_overview.rs+++ b/wezterm-gui/src/termwindow/live_overview.rs@@ -77,6 +77,57 @@ const MAX_COLUMNS: usize = 5;const MAX_COLUMNS_BELOW_WIDE_BREAKPOINT: usize = 4;const FIVE_COLUMN_WINDOW_WIDTH: f32 = 3000.0;const LIVE_RESIZE_PREVIEW_INTERVAL: Duration = Duration::from_millis(33);+/// How long a card holds its picture while the list is being scrolled.+///+/// Long enough that no single flick contains a refresh, which is the point:+/// the cost of a refresh lands as dropped frames in the scroll itself. It is+/// an interval rather than a flag so a card that has never been captured still+/// gets its first picture while the list is moving.+const SCROLLING_PREVIEW_INTERVAL: Duration = Duration::from_secs(5);+/// How often a card re-reads the terminal it is showing, when nothing is being+/// dragged.+///+/// Capturing had no interval at all outside a resize: any frame whose+/// fingerprint had moved re-read the screen and, downstream, rebuilt every quad+/// in the thumbnail. Against terminals that are genuinely busy -- agents+/// printing continuously, which is what this overview is for -- that meant+/// rebuilding all of them at the display's refresh rate, and no cache below+/// could ever hit. This is the gate that bounds that work; the quad cache is+/// what collects on it.+///+/// A thumbnail is a few pixels per cell, so it does not need to be as current+/// as the terminal it depicts. The value lives in the config+/// (`live_overview_preview_refresh_ms`) because it is the one number that+/// trades the overview's smoothness against how live the cards look, and+/// finding the right point takes trying it -- which a constant would make cost+/// a rebuild each time.+fn preview_refresh_interval() -> Duration {+ Duration::from_millis(+ config::configuration()+ .live_overview_preview_refresh_ms+ .max(1),+ )+}+/// How many cards may re-read their terminal in any one frame.+///+/// Every visible card is first captured in the same frame, so their refresh+/// deadlines start life aligned and stay that way: without a cap, each interval+/// would land one frame in which every card rebuilds -- a periodic hitch ten+/// times a second, which reads worse than being uniformly slow. Spending the+/// budget staggers the phases apart on the first collision and keeps them apart.+///+/// One, because a rebuild is not cheap enough to fit two in a frame. Measured+/// against six cards of continuously redrawing terminals: a frame that rebuilds+/// one card takes 11.4ms, two takes 17.5ms, and six -- which is what opening the+/// overview used to do in a single frame -- takes 397ms. The budget covers a+/// card's *first* capture as well as its refreshes for that last reason.+const MAX_PREVIEW_CAPTURES_PER_FRAME: usize = 1;+/// How long after the last observed stale preview the repaint chain stays+/// armed. A little longer than the default refresh interval, so that with a+/// continuously updating terminal the next staleness lands before the hold+/// expires and the chain never flaps; once output stops, the overview+/// settles back to event-driven repaints within one interval.+const PREVIEW_STALE_CHAIN_HOLD: Duration = Duration::from_millis(400);/// How often a card re-asks what its terminal is running.////// `CachePolicy::AllowStale` is not the cheap read its name suggests: it takes@@ -285,6 +336,17 @@ pub(crate) struct LiveOverviewView {scroll_animating: bool,next_preview_refresh: Option<Instant>,scrollbar_visible_until: Option<Instant>,+ /// The last time a warm card reported content newer than what is on+ /// screen (a changed fingerprint that the refresh throttle has not+ /// let us capture yet, or a capture we owe). Drives the repaint+ /// chain: while previews are live, every frame asks for the next one+ /// and the display paces us; when they go quiet we stop asking and+ /// the overview costs nothing.+ last_preview_stale: Option<Instant>,+ /// Opening a full-window view records the terminal on the same frame as+ /// the overview's first layout. Skip thumbnail capture that frame so the+ /// click is not charged for both at once.+ defer_preview_captures: bool,}impl LiveOverviewView {@@ -327,6 +389,8 @@ impl LiveOverviewView {scroll_animating: false,next_preview_refresh: None,scrollbar_visible_until: None,+ last_preview_stale: None,+ defer_preview_captures: false,}}@@ -559,7 +623,6 @@ impl LiveOverviewView {let now = Instant::now();let groups = self.collect_groups(now);- let refresh_interval = self.live_resizing.then_some(LIVE_RESIZE_PREVIEW_INTERVAL);// Advance every card's travel once, before anything samples it.for motion in self.card_motion.values_mut() {motion.travel.advance(now);@@ -570,6 +633,23 @@ impl LiveOverviewView {if self.scroll_animating {self.reveal_scrollbar(now);}+ // The list is moving if a finger is down on it or a flick is still+ // gliding. A card that recaptures has to rebuild its thumbnail, and+ // that is ~10ms against a 8.3ms frame -- so a refresh landing mid-flick+ // drops frames out of the one animation the eye is following. Held for+ // the length of the gesture, no thumbnail can be read anyway; released+ // the moment it ends, so the cards are current by the time the list+ // settles. The interval is a hold rather than a skip so that a card+ // being seen for the first time still gets its picture.+ let scrolling = self.scroll.active_phase.is_some() || self.scroll_animating;+ let refresh_interval = Some(if self.live_resizing {+ LIVE_RESIZE_PREVIEW_INTERVAL+ } else if scrolling {+ SCROLLING_PREVIEW_INTERVAL+ } else {+ preview_refresh_interval()+ });+ let mut capture_budget = MAX_PREVIEW_CAPTURES_PER_FRAME;let mut warm_keys = HashSet::new();let mut seen_keys = HashSet::new();if groups.is_empty() {@@ -678,22 +758,37 @@ impl LiveOverviewView {let overscan = layout.grid.card_height + gap;let snapshot = if card_is_warm(rect, self.viewport, overscan) {warm_keys.insert(card.key.clone());- let fingerprint = terminal_preview_fingerprint(card.tab_id);- let (snapshot, refresh_due) = resolve_snapshot(- &mut self.snapshot_cache,- &card.key,- fingerprint,- now,- refresh_interval,- || capture_terminal_snapshot(card.tab_id),- );- if let Some(refresh_due) = refresh_due {- self.next_preview_refresh = Some(- self.next_preview_refresh- .map_or(refresh_due, |current| current.min(refresh_due)),+ if self.defer_preview_captures {+ self.snapshot_cache+ .get(&card.key)+ .map(|cached| Arc::clone(&cached.snapshot))+ } else {+ let fingerprint = terminal_preview_fingerprint(card.tab_id);+ let (snapshot, refresh_due) = resolve_snapshot(+ &mut self.snapshot_cache,+ &card.key,+ fingerprint,+ now,+ refresh_interval,+ &mut capture_budget,+ || capture_terminal_snapshot(card.tab_id),);+ if let Some(refresh_due) = refresh_due {+ // A `Some` here means the card's fingerprint no+ // longer matches what was captured: there is newer+ // content than what is on screen (or no capture+ // yet). That -- not the refresh timer on its own+ // -- is what justifies asking for a steady stream+ // of frames. Cursor blink does not move the+ // fingerprint, so idle cursors stay idle.+ self.last_preview_stale = Some(now);+ self.next_preview_refresh = Some(+ self.next_preview_refresh+ .map_or(refresh_due, |current| current.min(refresh_due)),+ );+ }+ snapshot}- snapshot} else {None};@@ -829,6 +924,7 @@ impl LiveOverviewView {)?;if let Some(snapshot) = snapshot.as_ref().filter(|_| !in_flight) {self.previews.push(TerminalPreviewRequest {+ tab_id,snapshot: Arc::clone(snapshot),area: preview,clip,@@ -1054,6 +1150,15 @@ impl LiveOverviewView {// the repaint scheduler and the backend, which already throttle to// this panel's refresh rate.let motion_deadline = (self.card_motion_running || self.scroll_animating).then_some(now);+ // While any card is showing stale content, chain frames at the+ // display's pace instead of waking once per refresh timer: six cards+ // on a 300ms throttle wake 20 times a second otherwise, which paints+ // a busy overview at a juddery ~20fps. The hold-out spans a little+ // more than one refresh interval so the chain does not flap in the+ // gap between a capture and the next burst of output.+ let stale_deadline = self.last_preview_stale.and_then(|stale| {+ (now.duration_since(stale) < PREVIEW_STALE_CHAIN_HOLD).then_some(now)+ });// Before the fade begins one frame is enough -- the one that starts// it. Inside the fade every frame counts.let scrollbar_deadline = self.scrollbar_visible_until.and_then(|until| {@@ -1068,6 +1173,7 @@ impl LiveOverviewView {});[motion_deadline,+ stale_deadline,self.next_preview_refresh,scrollbar_deadline,]@@ -1465,6 +1571,10 @@ impl ContentView for LiveOverviewView {self.terminal_in_flight = tab_id;}+ fn set_defer_preview_captures(&mut self, defer: bool) {+ self.defer_preview_captures = defer;+ }+fn set_host_preview_aspect(&mut self, aspect: f32) {if aspect.is_finite() && aspect > 0.0 {self.host_preview_aspect = aspect.clamp(HOST_PREVIEW_ASPECT_MIN, HOST_PREVIEW_ASPECT_MAX);@@ -1828,6 +1938,7 @@ fn resolve_snapshot<T, F>(fingerprint: Option<TerminalPreviewFingerprint>,now: Instant,refresh_interval: Option<Duration>,+ capture_budget: &mut usize,capture: F,) -> (Option<Arc<T>>, Option<Instant>)where@@ -1850,7 +1961,25 @@ wherereturn (Some(Arc::clone(&cached.snapshot)), Some(refresh_due));}}- }+ // Due, but this frame has already paid for as many cards as it will.+ // Ask for another frame immediately rather than naming a time: this+ // card is owed a capture and should get it as soon as there is room.+ if *capture_budget == 0 {+ return (Some(Arc::clone(&cached.snapshot)), Some(now));+ }+ } else if *capture_budget == 0 {+ // Nothing to show for this card yet, and it will have to wait a frame+ // for its first picture.+ //+ // This used to be exempt, on the theory that an empty panel is a more+ // visible defect than a stale one. Measurement said otherwise: opening+ // an overview of six cards captured all six in one frame and cost+ // 397ms -- a fifth of a second of frozen window, at the exact moment+ // the user is looking at it. Spread one per frame the same six take+ // 25ms and no card is empty for longer than a frame or two.+ return (None, Some(now));+ }+ *capture_budget -= 1;if let Some(snapshot) = capture() {cache.insert(@@ -2658,6 +2787,27 @@ mod tests {assert_eq!(view.next_frame_deadline(deadline), None);}+ #[test]+ fn stale_previews_chain_frames_at_display_pace_then_settle() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ let now = Instant::now();++ // Nothing has ever been stale: no chain, no deadline, zero cost.+ assert_eq!(view.next_frame_deadline(now), None);++ // A card just reported newer content than what is on screen: ask for+ // the next frame immediately and let the display pace us.+ view.last_preview_stale = Some(now);+ assert_eq!(view.next_frame_deadline(now), Some(now));+ // The hold spans the gap between a capture and the next output burst.+ let within_hold = now + PREVIEW_STALE_CHAIN_HOLD - Duration::from_millis(1);+ assert_eq!(view.next_frame_deadline(within_hold), Some(within_hold));++ // Once previews have stayed quiet past the hold, the chain lets go.+ let past_hold = now + PREVIEW_STALE_CHAIN_HOLD;+ assert_eq!(view.next_frame_deadline(past_hold), None);+ }+#[test]fn snapshot_cache_reuses_unchanged_content_and_throttles_live_resize() {let key = LiveThreadKey {@@ -2666,6 +2816,7 @@ mod tests {};let mut cache = HashMap::new();let now = Instant::now();+ let mut budget = usize::MAX;let first_fingerprint = test_fingerprint(1);let (snapshot, due) = resolve_snapshot(&mut cache,@@ -2673,6 +2824,7 @@ mod tests {Some(first_fingerprint.clone()),now,None,+ &mut budget,|| Some(7_u8),);assert_eq!(*snapshot.unwrap(), 7);@@ -2684,6 +2836,7 @@ mod tests {Some(first_fingerprint),now + Duration::from_millis(1),None,+ &mut budget,|| panic!("unchanged fingerprint must not recapture"),);assert_eq!(*snapshot.unwrap(), 7);@@ -2696,6 +2849,7 @@ mod tests {Some(changed_fingerprint.clone()),now + Duration::from_millis(10),Some(LIVE_RESIZE_PREVIEW_INTERVAL),+ &mut budget,|| panic!("live resize must reuse until the refresh deadline"),);assert_eq!(*snapshot.unwrap(), 7);@@ -2707,6 +2861,7 @@ mod tests {Some(changed_fingerprint),now + Duration::from_millis(34),Some(LIVE_RESIZE_PREVIEW_INTERVAL),+ &mut budget,|| Some(8_u8),);assert_eq!(*snapshot.unwrap(), 8);@@ -2718,6 +2873,7 @@ mod tests {None,now + Duration::from_millis(35),None,+ &mut budget,|| panic!("missing live tab keeps the last successful snapshot"),);assert_eq!(*snapshot.unwrap(), 8);@@ -2726,6 +2882,166 @@ mod tests {assert!(cache.is_empty());}+ /// A busy terminal changes its fingerprint on every frame. Without an+ /// interval outside a resize, that recaptured -- and rebuilt every quad in+ /// the thumbnail -- at the display's refresh rate.+ #[test]+ fn a_busy_terminal_is_recaptured_at_the_steady_state_interval() {+ let key = LiveThreadKey {+ space_id: "local".to_string(),+ thread_id: "thread".to_string(),+ };+ let mut cache = HashMap::new();+ let now = Instant::now();+ let mut budget = usize::MAX;+ let mut captures = 0;+ let mut capture = |cache: &mut HashMap<_, _>, at: Instant, seq: usize, budget: &mut usize| {+ resolve_snapshot(+ cache,+ &key,+ Some(test_fingerprint(seq)),+ at,+ Some(preview_refresh_interval()),+ budget,+ || {+ captures += 1;+ Some(seq as u8)+ },+ )+ };++ // A frame every 8ms for a second, with the content different every+ // time. What comes out is one capture per refresh interval, not the+ // 121 the fingerprints alone would ask for.+ const FRAMES: u64 = 120;+ const FRAME_MS: u64 = 8;+ capture(&mut cache, now, 1, &mut budget);+ for frame in 1..=FRAMES {+ capture(+ &mut cache,+ now + Duration::from_millis(FRAME_MS * frame),+ 1 + frame as usize,+ &mut budget,+ );+ }+ let interval_ms = preview_refresh_interval().as_millis() as u64;+ assert_eq!(captures, 1 + (FRAMES * FRAME_MS / interval_ms) as usize);+ assert!(captures < 12, "{captures} captures in a second is not a throttle");+ }++ /// Opening the overview used to capture every card in the frame that+ /// revealed them -- 397ms with six cards, all of it inside the gesture the+ /// user is watching.+ #[test]+ fn opening_does_not_capture_every_card_in_one_frame() {+ let keys: Vec<LiveThreadKey> = (0..6)+ .map(|index| LiveThreadKey {+ space_id: "local".to_string(),+ thread_id: format!("thread-{index}"),+ })+ .collect();+ let mut cache = HashMap::new();+ let now = Instant::now();+ let mut budget = MAX_PREVIEW_CAPTURES_PER_FRAME;+ let mut captured = 0;+ let mut empty = 0;+ for key in &keys {+ let (snapshot, due) = resolve_snapshot(+ &mut cache,+ key,+ Some(test_fingerprint(1)),+ now,+ Some(preview_refresh_interval()),+ &mut budget,+ || {+ captured += 1;+ Some(1_u8)+ },+ );+ if snapshot.is_none() {+ // Nothing to draw yet, and owed the very next frame for it.+ assert_eq!(due, Some(now));+ empty += 1;+ }+ }+ assert_eq!(captured, MAX_PREVIEW_CAPTURES_PER_FRAME);+ assert_eq!(empty, keys.len() - MAX_PREVIEW_CAPTURES_PER_FRAME);++ // The next frame picks up where this one stopped.+ let mut budget = MAX_PREVIEW_CAPTURES_PER_FRAME;+ resolve_snapshot(+ &mut cache,+ &keys[1],+ Some(test_fingerprint(1)),+ now,+ Some(preview_refresh_interval()),+ &mut budget,+ || {+ captured += 1;+ Some(1_u8)+ },+ );+ assert_eq!(captured, 2 * MAX_PREVIEW_CAPTURES_PER_FRAME);+ }++ /// Cards are all first captured in the same frame, so their deadlines start+ /// aligned. Rationing captures is what stops one frame in every interval+ /// from rebuilding all of them at once.+ #[test]+ fn only_a_couple_of_cards_may_recapture_in_one_frame() {+ let keys: Vec<LiveThreadKey> = (0..5)+ .map(|index| LiveThreadKey {+ space_id: "local".to_string(),+ thread_id: format!("thread-{index}"),+ })+ .collect();+ let mut cache = HashMap::new();+ let now = Instant::now();++ let mut budget = usize::MAX;+ for key in &keys {+ resolve_snapshot(+ &mut cache,+ key,+ Some(test_fingerprint(1)),+ now,+ Some(preview_refresh_interval()),+ &mut budget,+ || Some(1_u8),+ );+ }++ // Every card is now due at the same instant, and every one has changed.+ let due_at = now + preview_refresh_interval();+ let mut budget = MAX_PREVIEW_CAPTURES_PER_FRAME;+ let mut captured = 0;+ let mut asked_for_another_frame = 0;+ for key in &keys {+ let (snapshot, due) = resolve_snapshot(+ &mut cache,+ key,+ Some(test_fingerprint(2)),+ due_at,+ Some(preview_refresh_interval()),+ &mut budget,+ || {+ captured += 1;+ Some(2_u8)+ },+ );+ if *snapshot.unwrap() == 1 {+ // Still on the old picture, and owed a frame to fix that.+ assert_eq!(due, Some(due_at));+ asked_for_another_frame += 1;+ }+ }+ assert_eq!(captured, MAX_PREVIEW_CAPTURES_PER_FRAME);+ assert_eq!(+ asked_for_another_frame,+ keys.len() - MAX_PREVIEW_CAPTURES_PER_FRAME+ );+ }+#[test]fn overview_warms_only_visible_and_adjacent_rows() {let viewport = euclid::rect(0.0, 110.0, 1000.0, 100.0);diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 0bedb272..a83a9b55 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -1493,9 +1493,12 @@ pub struct TermWindow {tab_state: RefCell<HashMap<TabId, TabState>>,pane_state: RefCell<HashMap<PaneId, PaneState>>,pane_font_cache: RefCell<HashMap<PaneFontKey, PaneFontEntry>>,- /// Scratch space for recording terminal thumbnails, kept across frames so- /// its pool of quad boxes is not rebuilt for every card.- preview_quad_heap: RefCell<crate::quad::HeapQuadAllocator>,+ /// One recorded thumbnail per card, kept across frames so an unchanged+ /// terminal is replayed rather than re-shaped and re-quadded. Entries are+ /// dropped for cards that stop asking for a preview, and invalidated+ /// wholesale when the glyph atlas is repacked -- the quads hold atlas+ /// coordinates.+ preview_quad_cache: RefCell<HashMap<TabId, crate::termwindow::render::paint::CachedPreviewQuads>>,/// Font scale last chosen for a thumbnail of a grid this size, so a drag/// can hold it steady instead of rebucketing every few pixels.preview_scale_hold: RefCell<HashMap<(usize, usize), f64>>,@@ -2085,6 +2088,13 @@ impl TermWindow {fn discard_content_view_captures_after_atlas_recreation(&mut self) {// Repopulated by the paint pass the retry loop is about to run.self.content_view_last_frame = None;+ // Same reason, one level down: a card's recorded thumbnail is quads+ // carrying atlas coordinates, and a repack moves every glyph. Keeping+ // them would draw the overview in whatever now occupies those texels.+ // `PreviewQuadKey` also carries `shape_generation`, so this is belt and+ // braces -- but the two live in different files and the invariant+ // belongs with the rest of the captures.+ self.preview_quad_cache.borrow_mut().clear();let Some(fade) = self.content_view_fade.as_mut() else {return;};@@ -2428,7 +2438,7 @@ impl TermWindow {tab_state: RefCell::new(HashMap::new()),pane_state: RefCell::new(HashMap::new()),pane_font_cache: RefCell::new(HashMap::new()),- preview_quad_heap: RefCell::new(Default::default()),+ preview_quad_cache: RefCell::new(HashMap::new()),preview_scale_hold: RefCell::new(HashMap::new()),current_mouse_buttons: vec![],current_mouse_capture: None,@@ -7345,14 +7355,57 @@ impl TermWindow {/// converged. Background tabs retain the server's canonical split tree/// until they are activated or explicitly claimed.pub(crate) fn reapply_collapsed_panes_for_tab(&mut self, tab_id: TabId) {- if self.collapsed_pane_layouts.is_empty() {- return;- }-let Some(tab) = Mux::get().get_tab(tab_id) else {return;};let min_cells = self.collapsed_pane_min_cells();++ // Adopt orphans first. `collapsed_pane_layouts` keys on stack ids+ // that are allocated per process and lives only in this window's+ // memory, so a pane that *arrives* at collapsed width -- session+ // restore, window adoption, workspace reconcile -- has no record+ // here. Without one it is painted as an ordinary terminal squeezed+ // to a few columns: the "strip of vertically wrapped prompt text on+ // the right edge" bug. A pane this narrow is not something anyone+ // can read or use, so claiming it as collapsed is strictly better+ // than drawing it raw.+ //+ // The threshold is deliberately looser than `min_cells` (2-3): the+ // orphan was squeezed by proportional resizes, not by the collapse+ // code, so it drifts -- observed at 6 cells. Ten columns is still+ // far below anything a terminal is usable at, and legitimate narrow+ // threads (~20 cells) stay untouched.+ let threshold = (min_cells * 3).max(10);+ let orphans: Vec<usize> = tab+ .iter_panes_ignoring_zoom()+ .into_iter()+ .filter(|pos| {+ // No direction test: side-by-side panes report their split as+ // Horizontal and collapse into a vertical strip. Whether a+ // given pane can collapse at all is `collapse_pane_by_index`'s+ // call -- it returns None when it cannot.+ !pos.is_active+ && pos.width <= threshold+ && !self+ .collapsed_pane_layouts+ .contains_key(&pos.pane_stack_id)+ })+ .map(|pos| pos.index)+ .collect();+ for index in orphans {+ if let Some(layout) = tab.collapse_pane_by_index(index, min_cells) {+ log::info!(+ "adopted orphan collapsed pane stack {:?} (index {index})",+ layout.pane_stack_id+ );+ self.collapsed_pane_layouts+ .insert(layout.pane_stack_id, layout);+ }+ }++ if self.collapsed_pane_layouts.is_empty() {+ return;+ }let layouts: Vec<_> = self.collapsed_pane_layouts.values().copied().collect();for layout in layouts {let contains_stack = tab@@ -7518,6 +7571,7 @@ impl TermWindow {return Ok((Rc::clone(&entry.fonts), entry.render_metrics));}+ let build_started = crate::perf::now();let fonts = Rc::new(FontConfiguration::new(Some(self.config.clone()),self.dimensions.dpi,@@ -7532,6 +7586,7 @@ impl TermWindow {render_metrics,},);+ crate::perf::accum("font_config_build", build_started);Ok((fonts, render_metrics))}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex e65e3700..e2c5ce56 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -2058,12 +2058,22 @@ impl super::TermWindow {};if delta != 0 {+ // Split of the per-event drag cost: the pre-c9e3300 path was+ // resize_split_by alone; preview_active_tab_geometry_now is the+ // frontend-geometry machinery added since. Which of the two the+ // time goes to decides where the fast-path cut lands.+ let event_started = crate::perf::now();+ let split_started = crate::perf::now();tab.resize_split_by(split.index, delta);+ crate::perf::log_duration("drag_resize_split_by", split_started);+ let preview_started = crate::perf::now();self.preview_active_tab_geometry_now();+ crate::perf::log_duration("drag_preview_geometry", preview_started);if let Some(split) = tab.iter_splits().into_iter().nth(split.index) {item.item_type = UIItemType::Split(split);context.invalidate();}+ crate::perf::log_duration("drag_split_event", event_started);}self.dragging.replace((item, start_event));}diff --git a/wezterm-gui/src/termwindow/render/draw.rs b/wezterm-gui/src/termwindow/render/draw.rsindex 3e4ee63d..5fa4fd4f 100644--- a/wezterm-gui/src/termwindow/render/draw.rs+++ b/wezterm-gui/src/termwindow/render/draw.rs@@ -86,6 +86,7 @@ pub(crate) fn draw_webgpu_layers(clear_color: wgpu::Color,corner_radius: f32,window_border: WindowBorder,+ window_label: usize,) -> anyhow::Result<()> {let acquire_start = crate::perf::now();let output = webgpu.surface.get_current_texture()?;@@ -196,7 +197,14 @@ pub(crate) fn draw_webgpu_layers(render_pass.set_bind_group(0, &uniforms, &[]);render_pass.set_bind_group(1, &texture_linear_bind_group, &[]);render_pass.set_bind_group(2, &texture_nearest_bind_group, &[]);+ // Timed on its own because it is not the small bookkeeping step+ // it reads as: `recreate` allocates a whole new vertex buffer+ // with `mapped_at_creation`, which wgpu zero-fills. At overview+ // sizes that is megabytes per layer per frame.+ let recreate_start = crate::perf::now();vertex_buffer = vertices.webgpu_mut().recreate();+ crate::perf::log_duration("webgpu_vb_recreate", recreate_start);+ crate::perf::log_counter("webgpu_vb_bytes", vertices.webgpu().capacity_bytes());vertex_buffer.unmap();render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));render_pass@@ -215,6 +223,16 @@ pub(crate) fn draw_webgpu_layers(crate::perf::log_counter("webgpu_vertices", vertices_total);let submit_start = crate::perf::now();webgpu.queue.submit(std::iter::once(encoder.finish()));+ if crate::framedump::should_dump(window_label) {+ if let Err(err) = crate::framedump::dump_texture(+ &webgpu.device,+ &webgpu.queue,+ &output.texture,+ window_label,+ ) {+ log::error!("framedump failed: {err:#}");+ }+ }output.present();crate::perf::log_duration("webgpu_submit_present", submit_start);@@ -265,6 +283,7 @@ impl crate::TermWindow {},corner_radius,window_border,+ self.mux_window_id as usize,)}diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rsindex 03a2009a..c799dc54 100644--- a/wezterm-gui/src/termwindow/render/mod.rs+++ b/wezterm-gui/src/termwindow/render/mod.rs@@ -103,6 +103,7 @@ pub struct LineToElementParams<'a> {pub font_config: Option<&'a Rc<FontConfiguration>>,pub render_metrics: RenderMetrics,pub font_identity: u64,+ pub simple_shaping: bool,}#[derive(Debug, Hash, PartialEq, Eq, Clone)]@@ -189,6 +190,14 @@ pub struct RenderScreenLineParams<'a> {/// Live Overview keeps the source line untouched and suppresses only the/// image quads; regular terminal painting enables them.pub allow_images: bool,++ /// Shape one cell at a time through the per-grapheme shape cache instead+ /// of handing whole same-attribute runs to the shaper. Ligatures and+ /// kerning are given up, which is invisible at thumbnail cell sizes; what+ /// is bought is a cache that actually hits on content like btop, whose+ /// full-run strings never repeat but whose individual characters always+ /// do. Live Overview previews only.+ pub simple_shaping: bool,}#[derive(Debug, Hash, PartialEq, Eq, Clone)]@@ -862,7 +871,10 @@ impl crate::TermWindow {text: &cluster.text,};let glyph_info = match self.lookup_cached_shape(&key) {- Some(Ok(info)) => info,+ Some(Ok(info)) => {+ crate::perf::accum_count("cluster_shape_hit");+ info+ }Some(Err(err)) => return Err(err),None => {let font = match font {@@ -873,6 +885,7 @@ impl crate::TermWindow {let presentation_width = PresentationWidth::with_cluster(&cluster);+ let hb_started = crate::perf::now();match font.shape(&cluster.text,move || window.notify(TermWindowNotif::InvalidateShapeCache),@@ -883,6 +896,8 @@ impl crate::TermWindow {Some(&presentation_width),) {Ok(info) => {+ crate::perf::accum("cluster_hb_shape", hb_started);+ let raster_started = crate::perf::now();let glyphs = self.glyph_infos_to_glyphs(&style,&mut gl_state.glyph_cache.borrow_mut(),@@ -890,6 +905,7 @@ impl crate::TermWindow {&font,metrics,)?;+ crate::perf::accum("glyph_raster", raster_started);let shaped = Rc::new(ShapedInfo::process(&info, &glyphs));self.shape_cache@@ -918,6 +934,135 @@ impl crate::TermWindow {Ok(glyph_info)}+ /// Shape a cluster one cell at a time, each cell's grapheme going through+ /// the shape cache on its own.+ ///+ /// The whole-run `cached_cluster_shape` above keys its cache on the entire+ /// same-attribute string, and against content like btop -- whose braille+ /// graphs mint a new string every refresh -- that cache can never hit:+ /// measured on a Live Overview rebuild, 85% of the cost was HarfBuzz+ /// re-shaping runs it had shaped 100ms earlier. The individual characters,+ /// though, repeat endlessly (braille is 256 codepoints), so per-cell+ /// entries converge on a hit rate of ~1 after the first screen.+ ///+ /// The price is shaping without cross-cell context: no ligatures, no+ /// kerning, and ambiguous-width characters resolved without the cluster's+ /// `PresentationWidth`. At the 2-6px cell sizes previews render at, none+ /// of that is visible, which is why only they take this path.+ fn cached_cluster_shape_by_cell(+ &self,+ style: &TextStyle,+ cluster: &CellCluster,+ gl_state: &RenderState,+ font: Option<&Rc<LoadedFont>>,+ font_config: Option<&Rc<FontConfiguration>>,+ metrics: &RenderMetrics,+ font_identity: u64,+ ) -> anyhow::Result<Rc<Vec<ShapedInfo>>> {+ let text = &cluster.text;+ if text.is_empty() {+ return Ok(Rc::new(vec![]));+ }++ // Cell boundaries in byte offsets. A cell holds one grapheme, so+ // splitting where the byte->cell mapping steps keeps combining+ // sequences intact without a segmentation pass.+ let mut segments: Vec<(usize, usize)> = Vec::new();+ let mut seg_start = 0usize;+ let mut seg_cell = cluster.byte_to_cell_idx(0);+ for (byte_idx, _) in text.char_indices().skip(1) {+ let cell = cluster.byte_to_cell_idx(byte_idx);+ if cell != seg_cell {+ segments.push((seg_start, byte_idx));+ seg_start = byte_idx;+ seg_cell = cell;+ }+ }+ segments.push((seg_start, text.len()));++ let mut resolved_font: Option<Rc<LoadedFont>> = font.cloned();+ let mut merged: Vec<ShapedInfo> = Vec::with_capacity(segments.len());+ for (start, end) in segments {+ let seg = &text[start..end];+ let key = BorrowedShapeCacheKey {+ font_identity,+ style,+ text: seg,+ };+ let infos = match self.lookup_cached_shape(&key) {+ Some(Ok(info)) => {+ crate::perf::accum_count("cluster_shape_hit");+ info+ }+ Some(Err(err)) => return Err(err),+ None => {+ let font = match &resolved_font {+ Some(font) => Rc::clone(font),+ None => {+ let font = font_config.unwrap_or(&self.fonts).resolve_font(style)?;+ resolved_font = Some(Rc::clone(&font));+ font+ }+ };+ let window = self.window.as_ref().unwrap().clone();+ let hb_started = crate::perf::now();+ match font.shape(+ seg,+ move || window.notify(TermWindowNotif::InvalidateShapeCache),+ BlockKey::filter_out_synthetic,+ Some(cluster.presentation),+ cluster.direction,+ None,+ None,+ ) {+ Ok(info) => {+ crate::perf::accum("cluster_hb_shape", hb_started);+ let raster_started = crate::perf::now();+ let glyphs = self.glyph_infos_to_glyphs(+ &style,+ &mut gl_state.glyph_cache.borrow_mut(),+ &info,+ &font,+ metrics,+ )?;+ crate::perf::accum("glyph_raster", raster_started);+ let shaped = Rc::new(ShapedInfo::process(&info, &glyphs));+ self.shape_cache+ .borrow_mut()+ .put(key.to_owned(), Ok(Rc::clone(&shaped)));+ shaped+ }+ Err(err) => {+ if err.root_cause().downcast_ref::<ClearShapeCache>().is_some() {+ return Err(err);+ }+ let res = anyhow!("shaper error: {}", err);+ self.shape_cache.borrow_mut().put(key.to_owned(), Err(err));+ return Err(res);+ }+ }+ }+ };+ for info in infos.iter() {+ merged.push(ShapedInfo {+ glyph: Rc::clone(&info.glyph),+ pos: GlyphPosition {+ glyph_idx: info.pos.glyph_idx,+ num_cells: info.pos.num_cells,+ x_offset: info.pos.x_offset,+ bearing_x: info.pos.bearing_x,+ bitmap_pixel_width: info.pos.bitmap_pixel_width,+ },+ // Re-anchor from segment-relative to cluster-relative so+ // the consumer's byte->cell mapping still lands.+ cluster: start + info.cluster,+ block_key: info.block_key,+ });+ }+ }+ Ok(Rc::new(merged))+ }+fn lookup_cached_shape(&self,key: &dyn ShapeCacheKeyTrait,diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex ffbd0f3d..e9bddbbf 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -9,11 +9,14 @@ use ::window::RectF;use ::window::WindowOps;use anyhow::Context;use mux::renderable::{RenderableDimensions, StableCursorPosition};-use mux::tab::SplitDirection;+use mux::tab::{SplitDirection, TabId};use smol::Timer;use std::collections::hash_map::DefaultHasher;+use std::collections::HashSet;use std::hash::{Hash, Hasher};+use std::sync::Arc;use std::time::{Duration, Instant};+use window::Dimensions;use wezterm_font::ClearShapeCache;use wezterm_term::color::ColorAttribute;use wezterm_term::TerminalSize;@@ -37,6 +40,119 @@ const MAX_PREVIEW_FILL: f32 = 1.5;/// device pixels the divider quad uses. Kept in step with `fancy_tab_bar`.const TAB_BAR_SEAM_HEIGHT: f32 = 1.0;+/// How many cards may rebuild their recorded quads in one frame.+///+/// Measured with five cards open: replaying a card costs ~0.3ms and rebuilding+/// one costs ~10ms, so this is the difference between a frame that fits a+/// 120Hz deadline and one that misses two. Five at once -- which is what+/// reopening the overview used to do -- froze the window for 100-170ms.+///+/// One, because two already overruns. Cards over the budget replay their last+/// picture and ask for another frame, so no card goes blank and the queue+/// drains at one per frame.+const MAX_PREVIEW_QUAD_REBUILDS_PER_FRAME: usize = 1;++/// Everything a card's recorded quads depend on.+///+/// Equal keys mean the recorded heap still draws the right picture and can be+/// replayed instead of rebuilt. Note what is *not* here: where the card is.+/// Position is recovered at replay time, so scrolling the overview costs a+/// remap rather than a rebuild.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct PreviewQuadKey {+ /// Address of the snapshot these quads were built from.+ ///+ /// `resolve_snapshot` hands back the very same `Arc` while a terminal's+ /// content is unchanged and a freshly allocated one when it is not, so+ /// pointer equality answers "is this the same picture?" exactly, for free.+ /// [`CachedPreviewQuads`] keeps the `Arc` alive so a dead snapshot's+ /// address cannot be reissued to a different one.+ snapshot: usize,+ /// Bumped when a font finishes loading and every shape cache is thrown+ /// away. That makes the recorded quads *out of date* -- a character the+ /// shaper had no glyph for may now have one -- but not wrong: the atlas is+ /// untouched, so every texel they address still holds the glyph they were+ /// built with. It belongs on this side of the split for that reason.+ ///+ /// It matters that it is here and not in the geometry. A font fallback+ /// landed roughly once a second against busy terminals, and while this was+ /// geometry every one of them forced all five cards to rebuild inside the+ /// frame that noticed -- a ~100ms freeze, once a second, for a difference+ /// nobody could see. The atlas repack that *does* invalidate these quads+ /// clears the cache outright, in the same breath as the rest of the+ /// captures (`discard_content_view_captures_after_atlas_recreation`), so+ /// nothing here has to stand in for it.+ shape_generation: usize,+ geometry: PreviewGeometryKey,+}++/// Everything a card's quads depend on *except* what the terminal was showing.+///+/// The split is the difference between two kinds of staleness. Quads whose+/// geometry still matches but whose snapshot has moved on draw the right+/// pixels in the right places, just a refresh behind -- safe to put on screen+/// for a frame while the rebuild waits its turn. Quads whose geometry has moved+/// on are not stale, they are *wrong*: the quads carry positions relative to+/// the centre of the window and a font scale chosen from the card's size, so+/// showing them under a different window or a different card draws the picture+/// somewhere it does not belong. Replaying across that is what made the+/// overview flicker while opening.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct PreviewGeometryKey {+ area_width: u32,+ area_height: u32,+ hold_scale: bool,+ pixel_width: usize,+ pixel_height: usize,+ dpi: usize,+}++/// One card's thumbnail, kept between frames.+pub(crate) struct CachedPreviewQuads {+ key: PreviewQuadKey,+ /// Never read. Held so that the address recorded in `key.snapshot` belongs+ /// to a live allocation for as long as this entry does, which is what makes+ /// comparing addresses a sound test for "same snapshot".+ #[allow(dead_code)]+ snapshot: Arc<crate::termwindow::content_view::TerminalPreviewSnapshot>,+ /// The card rectangle these quads were laid out in.+ area: RectF,+ heap: HeapQuadAllocator,+}++fn preview_quad_key(+ preview: &TerminalPreviewRequest,+ dimensions: &Dimensions,+ shape_generation: usize,+) -> PreviewQuadKey {+ PreviewQuadKey {+ snapshot: Arc::as_ptr(&preview.snapshot) as usize,+ shape_generation,+ geometry: PreviewGeometryKey {+ // The font scale is chosen from the card's size, so a resized card+ // is a different picture even from the same snapshot. Position is+ // deliberately absent: a moved card is replayed, not rebuilt.+ area_width: preview.area.size.width.to_bits(),+ area_height: preview.area.size.height.to_bits(),+ hold_scale: preview.hold_scale,+ // Quad positions are relative to the centre of the window.+ pixel_width: dimensions.pixel_width,+ pixel_height: dimensions.pixel_height,+ dpi: dimensions.dpi,+ },+ }+}++fn quad_clip_rect(rect: RectF, dimensions: &Dimensions) -> QuadClipRect {+ QuadClipRect::from_top_left_pixels(+ rect.min_x(),+ rect.min_y(),+ rect.max_x(),+ rect.max_y(),+ dimensions,+ )+}+fn quantized_terminal_preview_extent(extent: f32, dpi: usize) -> f32 {let bucket = crate::ui::scale_ui_f32(TERMINAL_PREVIEW_EXTENT_BUCKET_DESIGN_PX, dpi).max(1.0);if extent <= bucket {@@ -438,13 +554,42 @@ impl crate::TermWindow {}}+ // How many times one frame may be thrown away and started again because+ // a font finished loading underneath it.+ //+ // `ClearShapeCache` means "a font you asked for has only just arrived;+ // the shapes you cached are stale". The handler answers by clearing+ // every shape cache and repainting the whole window -- and each repaint+ // can pull in the next not-yet-loaded font and ask for the same thing+ // again. Opening the live overview introduces a font size per card at+ // once, so the frame that opens it was chaining eight and nine of these+ // rounds, re-shaping five thumbnails from scratch in every one: 680ms+ // of frozen window, measured.+ //+ // One retry is enough to present a correct frame in the common case.+ // Past that, stop chasing the fonts inside this frame and ask for+ // another one: the caches have been cleared either way, so the next+ // frame starts warm and the cost lands as one more frame rather than as+ // half a second of nothing.+ const MAX_SHAPE_CACHE_RETRIES: usize = 1;+ let mut shape_retries = 0usize;+'pass: for pass in 0.. {match self.paint_pass() {Ok(_) => match self.render_state.as_mut().unwrap().allocated_more_quads() {Ok(allocated) => {if !allocated {+ // Recorded even for the ordinary single-pass frame,+ // so the counter can be read as a distribution+ // rather than as "something went wrong once".+ crate::perf::log_counter("paint_passes", pass + 1);break 'pass;}+ // Each retry repaints the *whole* window, thumbnails+ // included. Opening the overview was costing five of+ // them inside one frame -- 580ms -- so which resource+ // ran out, and how often, decides where the fix goes.+ crate::perf::log_counter("paint_retry_quads", pass);self.invalidate_fancy_tab_bar();self.invalidate_modal();}@@ -459,6 +604,10 @@ impl crate::TermWindow {current_size,}) = err.root_cause().downcast_ref::<OutOfTextureSpace>(){+ crate::perf::log_counter(+ "paint_retry_atlas",+ format!("pass={pass} have={current_size} want={size}"),+ );let result = if pass == 0 {// Grow while there is headroom, rather than// clearing in place.@@ -523,6 +672,11 @@ impl crate::TermWindow {);}} else if err.root_cause().downcast_ref::<ClearShapeCache>().is_some() {+ // The shaper asked for the frame to be redone because a+ // font it needed had only just finished loading. Each+ // one of these throws away every shape cache and starts+ // the whole window again, thumbnails included.+ crate::perf::log_counter("paint_retry_shape", pass);self.invalidate_fancy_tab_bar();self.invalidate_modal();self.shape_generation += 1;@@ -530,6 +684,14 @@ impl crate::TermWindow {self.ui_shape_caches.borrow_mut().clear_all();self.publish_ui_shape_cache_diagnostics();self.line_to_ele_shape_cache.borrow_mut().clear();+ shape_retries += 1;+ if shape_retries > MAX_SHAPE_CACHE_RETRIES {+ crate::perf::log_counter("paint_shape_retry_capped", shape_retries);+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ break 'pass;+ }} else {log::error!("paint_pass failed: {:#}", err);break 'pass;@@ -553,12 +715,56 @@ impl crate::TermWindow {// If self.has_animation is some, then the last render detected// image attachments with multiple frames, so we also need to// invalidate the viewport when the next frame is due- if self.focused.is_some() {+ //+ // The focus gate exists so an unfocused terminal does not burn frames+ // animating gifs nobody is looking at. But a content-view transition+ // or an open overview owes frames regardless of focus: toggling the+ // overview can switch macOS Spaces, and during that switch the window+ // is briefly unfocused -- dropping the schedule right there strands+ // the animation, which then only advances when some terminal happens+ // to emit output. Measured: 150-210ms between transition frames, with+ // the main thread idle the whole time.+ let owes_frames_regardless_of_focus =+ self.content_view_fade.is_some() || self.active_content_view_index().is_some();+ if self.focused.is_some() || owes_frames_regardless_of_focus {if let Some(next_due) = *self.has_animation.borrow() {+ // "The next frame the display will give me" is the common+ // request: every frame of a scroll, of a card travelling, of a+ // transition, and of a preview that is owed a capture asks for+ // it.+ //+ // Answering it through the timer answers it the slowest way+ // available -- spawn a task, await a `Timer` that is already+ // due, notify the window across a channel, spend a turn of the+ // run loop applying that notification, invalidate, and only+ // then wait for the display refresh that was the entire point.+ // Those hops cost more than the frame does: measured with the+ // overview open, 14.7ms of painting delivered a frame every+ // 33.6ms, the difference spent idle in the run loop waiting for+ // the app's own message to come back.+ //+ // So ask the window directly and let the backend pace it; it+ // already throttles to min(max_fps, the display's rate).+ if next_due <= Instant::now() {+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ return;+ }let prior = self.scheduled_animation.borrow_mut().take();match prior {- Some(prior) if prior <= next_due => {- // Already due before that time+ // A timer for an earlier-or-equal deadline is already in+ // flight -- but only trust it while the deadline is+ // current. Display sleep can swallow the spawned task+ // whole, and a swallowed timer whose deadline is trusted+ // forever strands the animation. Put the deadline back so+ // the next frame doesn't spawn a duplicate timer for it.+ Some(prior)+ if prior <= next_due+ && Instant::now().saturating_duration_since(prior)+ < Duration::from_millis(250) =>+ {+ self.scheduled_animation.borrow_mut().replace(prior);}_ => {self.scheduled_animation.borrow_mut().replace(next_due);@@ -1006,11 +1212,15 @@ impl crate::TermWindow {}};+ let defer_preview_captures = self.content_view_fade.as_ref().is_some_and(|fade| {+ fade.flight.is_none()+ });let (next_frame, previews) = {let gl_state = self.render_state.as_ref().unwrap();let ctx = DrawContext::new(gl_state, dimensions, &render_metrics);if let Some(idx) = active_content_view_idx {let view = self.content_views[idx].view.as_mut();+ view.set_defer_preview_captures(defer_preview_captures);view.set_host_preview_aspect(host_preview_aspect);view.paint_surface_background(&ctx, layers, surface, palette)?;view.paint(@@ -1056,45 +1266,175 @@ impl crate::TermWindow {layers: &mut TripleLayerQuadAllocator<'_>,previews: &[TerminalPreviewRequest],) -> anyhow::Result<()> {- // One allocator for every card, borrowed out of the window and put- // back, so its pool of quad boxes outlives both the loop and the frame.- // Each card's thumbnail is thousands of quads and there are as many- // cards as fit the viewport; building and dropping that from scratch- // per card per frame is millions of allocations a second, spent on- // memory that was about to be asked for again.- let mut heap = std::mem::take(&mut *self.preview_quad_heap.borrow_mut());- let result = (|| {- for preview in previews {- self.paint_terminal_preview(layers, preview, &mut heap)?;+ // Drop the cards that are no longer asked for -- but only while there+ // are cards to compare against. Closing the overview asks for none, and+ // pruning on that frame threw away every recorded thumbnail; reopening+ // then rebuilt all of them in the single frame that revealed them,+ // which is the 100-170ms freeze the gesture was landing in. Nothing+ // about a closed overview says the cards are gone, and a stale entry+ // costs one key comparison to reject.+ if !previews.is_empty() {+ let live: HashSet<TabId> = previews.iter().map(|preview| preview.tab_id).collect();+ self.preview_quad_cache+ .borrow_mut()+ .retain(|tab_id, _| live.contains(tab_id));+ }+ let started = crate::perf::now();+ crate::perf::reset_accums();+ let mut rebuilt = 0usize;+ // How many cards may rebuild their quads in this frame.+ //+ // A rebuild is ~10ms and a replay is ~0.3ms, so a frame that rebuilds+ // two cards has already missed a 120Hz deadline and a frame that+ // rebuilds five has frozen the window for a fifth of a second. Cards+ // over the budget replay what they last showed and ask for another+ // frame, so the picture is at worst one frame out of date and the cost+ // is spread instead of spiked.+ let mut budget = MAX_PREVIEW_QUAD_REBUILDS_PER_FRAME;+ for preview in previews {+ if self.paint_terminal_preview(layers, preview, &mut budget)? {+ rebuilt += 1;}- Ok(())- })();- heap.recycle();- *self.preview_quad_heap.borrow_mut() = heap;- result+ }+ // What a frame spent on thumbnails, and how much of that was a card+ // whose quads could not be replayed. Without the split, a slow frame+ // says nothing about whether the cache missed or whether the cost is+ // somewhere else entirely.+ crate::perf::log_duration("preview_paint", started);+ crate::perf::log_counter("preview_cards", previews.len());+ crate::perf::log_counter("preview_rebuilds", rebuilt);+ if rebuilt > 0 {+ crate::perf::log_accums("pv_");+ } else {+ crate::perf::reset_accums();+ }+ // A shaping cache sitting at its capacity is a cache that is evicting+ // entries it is about to be asked for again. Reading the occupancy is+ // the difference between knowing that and inferring it from timings.+ if crate::perf::enabled() {+ crate::perf::log_counter("shape_cache_len", self.shape_cache.borrow().len());+ crate::perf::log_counter(+ "line_shape_cache_len",+ self.line_to_ele_shape_cache.borrow().len(),+ );+ crate::perf::log_counter("line_quad_cache_len", self.line_quad_cache.borrow().len());+ }+ Ok(())}+ /// Draw one card's thumbnail, building its quads only when they cannot be+ /// replayed.+ ///+ /// A thumbnail is thousands of quads and rebuilding one means re-shaping+ /// every line of the terminal it depicts. Doing that per card per frame+ /// was the whole cost of the overview: measured over 4621 frames it put+ /// the median frame at 14.8ms against a 8.3ms budget, and the snapshots+ /// feeding it were mostly *unchanged* -- the work was being redone to+ /// arrive at the same picture. Keeping the quads is what turns a repaint+ /// into a copy.+ ///+ /// Returns whether the quads had to be rebuilt.fn paint_terminal_preview(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,preview: &TerminalPreviewRequest,- heap: &mut HeapQuadAllocator,- ) -> anyhow::Result<()> {+ budget: &mut usize,+ ) -> anyhow::Result<bool> {+ let key = preview_quad_key(preview, &self.dimensions, self.shape_generation);+ let clip = quad_clip_rect(preview.clip, &self.dimensions);++ // A hit replays. A miss replays too -- but only when the miss is the+ // snapshot alone and the budget is spent, because then the recorded+ // quads are merely a refresh out of date, which at thumbnail size is+ // not a difference anyone can see. A geometry miss is never replayed:+ // those quads are wrong, not old.+ let mut deferred = false;+ let recorded_area = self+ .preview_quad_cache+ .borrow()+ .get(&preview.tab_id)+ .filter(|cached| {+ if cached.key == key {+ return true;+ }+ if cached.key.geometry == key.geometry && *budget == 0 {+ deferred = true;+ return true;+ }+ false+ })+ .map(|cached| cached.area);+ if deferred {+ // Come straight back rather than naming a time: this card owes a+ // rebuild and should get it as soon as a frame has room.+ self.update_next_frame_time(Some(Instant::now()));+ }+ if let Some(recorded_area) = recorded_area {+ let cache = self.preview_quad_cache.borrow();+ let cached = cache+ .get(&preview.tab_id)+ .expect("entry was present a statement ago and nothing removes it");+ // Scrolling moves a card without changing what it shows. The quads+ // carry the position they were recorded at, so a card that has+ // moved is replayed through the same source->target mapping the+ // flight animation uses. The key carries the card's *size*, so a+ // matching key guarantees the two rects are the same shape and the+ // mapping degenerates to a translation -- none of the softening+ // that a genuinely rescaled replay costs. A card that has not moved+ // takes the plain path, which is bit-for-bit what this drew before+ // the cache existed.+ if recorded_area == preview.area {+ cached.heap.apply_to_clipped(layers, clip, 1.0)?;+ } else {+ let source = quad_clip_rect(recorded_area, &self.dimensions);+ let target = quad_clip_rect(preview.area, &self.dimensions);+ cached+ .heap+ .apply_to_scaled(layers, source, target, clip, 1.0)?;+ }+ return Ok(false);+ }++ *budget = budget.saturating_sub(1);+ // Reuse the stale entry's boxes rather than freeing thousands of them+ // and asking for the same number back on the next line of this+ // function. `recycle` empties the layers into the spare pool.+ let mut heap = self+ .preview_quad_cache+ .borrow_mut()+ .remove(&preview.tab_id)+ .map(|cached| cached.heap)+ .unwrap_or_default();heap.recycle();{- let mut clipped_layers = TripleLayerQuadAllocator::Heap(heap);- self.paint_terminal_preview_unclipped(&mut clipped_layers, preview)?;- }- let clip = QuadClipRect::from_top_left_pixels(- preview.clip.min_x(),- preview.clip.min_y(),- preview.clip.max_x(),- preview.clip.max_y(),- &self.dimensions,+ let card_started = crate::perf::now();+ let mut heap_layers = TripleLayerQuadAllocator::Heap(&mut heap);+ self.paint_terminal_preview_unclipped(&mut heap_layers, preview)?;+ crate::perf::log_duration("preview_rebuild_card", card_started);+ }+ let result = heap.apply_to_clipped(layers, clip, 1.0).map(|()| true);+ self.preview_quad_cache.borrow_mut().insert(+ preview.tab_id,+ CachedPreviewQuads {+ key,+ // Held so the address in `key` cannot be handed to a different+ // snapshot while this entry is alive.+ snapshot: Arc::clone(&preview.snapshot),+ area: preview.area,+ heap,+ },);- heap.apply_to_clipped(layers, clip, 1.0)+ result}+ /// Build one card's thumbnail into `layers`, whole.+ ///+ /// Everything here is laid out against `preview.area` -- the card's full+ /// rectangle -- and nothing against `preview.clip`. That is what lets the+ /// result be kept: a heap built against the visible slice would hold only+ /// the rows that happened to be on screen when it was recorded, and the+ /// first scroll would reveal the gap. Cropping is the replaying caller's+ /// job, and it already does it.fn paint_terminal_preview_unclipped(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,@@ -1119,7 +1459,7 @@ impl crate::TermWindow {.or_else(|| snapshot.panes.first()).map(|pane| pane.palette.resolve_bg(ColorAttribute::Default).to_linear()).expect("checked that the tab has panes");- self.filled_rectangle(layers, 0, preview.clip, preview_background)?;+ self.filled_rectangle(layers, 0, preview.area, preview_background)?;// Quantization bounds the number of cached FontConfigurations even// when cards continuously resize. Flooring guarantees the terminal@@ -1261,13 +1601,13 @@ impl crate::TermWindow {let pane_width = pane.width as f32 * cell_width;let pane_height = pane.height as f32 * cell_height;let pane_rect = euclid::rect(pane_x, pane_y, pane_width, pane_height);- let Some(pane_clip) = pane_rect.intersection(&preview.clip) else {+ let Some(pane_bounds) = pane_rect.intersection(&preview.area) else {continue;};self.filled_rectangle(layers,0,- pane_clip,+ pane_bounds,palette.resolve_bg(ColorAttribute::Default).to_linear(),)?;@@ -1330,7 +1670,6 @@ impl crate::TermWindow {render_dims.viewport_rows = rows;render_dims.pixel_width = rendered_width.round() as usize;render_dims.pixel_height = rendered_height.round() as usize;- let rendered_y = grid_top;let foreground = palette.foreground.to_linear();let default_bg = palette.background.to_linear();// LineToElementShape caches resolved colors as well as glyph@@ -1355,11 +1694,23 @@ impl crate::TermWindow {// scale can fill both axes exactly. Applying this tiny correction// during allocation keeps exact pane geometry without a second// CPU walk over every htop glyph each frame.+ //+ // The source space starts at the origin rather than at the card's+ // corner, so everything drawn through this transform is expressed+ // relative to the pane itself. That is what makes the line quads+ // below cacheable: `LineQuadCacheKey` carries `top_pixel_y` and+ // `left_pixel_x`, and while those were the card's position on+ // screen, scrolling the overview minted a fresh key for every line+ // at every scroll offset -- thousands of entries that would never+ // be asked for again, evicting the ones that would. Measured with+ // four cards open, the cache sat pegged at its 4096 capacity and a+ // card that had to rebuild cost 7.9ms against 1.7ms for one that+ // did not.let source_rect = QuadClipRect::from_top_left_pixels(- pane_x,- rendered_y,- pane_x + rendered_width,- rendered_y + rendered_height,+ 0.0,+ 0.0,+ rendered_width,+ rendered_height,&self.dimensions,);let target_rect = QuadClipRect::from_top_left_pixels(@@ -1378,21 +1729,62 @@ impl crate::TermWindow {let transformed =layers.set_heap_position_transform(Some((source_rect, target_rect)));debug_assert!(transformed);- let source_visible_top = rendered_y- + (pane_clip.min_y() - grid_top) * rendered_height / grid_height.max(1.0);- let source_visible_bottom = rendered_y- + (pane_clip.max_y() - grid_top) * rendered_height / grid_height.max(1.0);+ // In the same pane-relative space as `source_rect`.+ let source_visible_top =+ (pane_bounds.min_y() - grid_top) * rendered_height / grid_height.max(1.0);+ let source_visible_bottom =+ (pane_bounds.max_y() - grid_top) * rendered_height / grid_height.max(1.0);for (line_idx, line) in pane.lines.iter().take(rows).enumerate() {- let y = rendered_y + line_idx as f32 * pane_cell_height;+ let y = line_idx as f32 * pane_cell_height;if y + pane_cell_height <= source_visible_top || y >= source_visible_bottom {continue;}+ let hash_started = crate::perf::now();let shape_hash = self.shape_hash_for_line(line);+ crate::perf::accum("line_hash", hash_started);++ // Deliberately *not* going through `line_quad_cache` here, the+ // way the real pane renderer does.+ //+ // It was tried, on the theory that a card whose snapshot moved+ // should only pay for the rows that actually changed. Measured,+ // it made a card rebuild 4.5x more expensive: 2.3ms per card+ // without it, 9.96ms with. Two reasons, both structural.+ //+ // The cache cannot hold a thumbnail's working set. Its key+ // carries the row a line was drawn at, so a terminal that+ // scrolls mints a fresh entry for every row it shifts text+ // through -- five cards of scrolling output filled all 4096+ // slots and stayed there, evicting entries as fast as they were+ // put in. Growing it is not the answer either: an entry is the+ // line's quads, so the capacity that would hold the working set+ // is measured in hundreds of megabytes.+ //+ // And a miss is not free. It allocates a heap, renders into it,+ // copies every quad a second time into `layers`, then evicts+ // someone else's entry to store it. At the hit rate a full+ // cache gives, that is pure overhead on top of the work it was+ // supposed to avoid -- and the work it was supposed to avoid is+ // already cheap, because `shape_cache` and+ // `line_to_ele_shape_cache` catch the re-shaping. Those two sit+ // at a few hundred entries of their thousands while this one is+ // pegged, which is the whole argument in two numbers.+ //+ // What does pay is the layer above: `preview_quad_cache` keeps+ // the finished card, so an unchanged terminal costs a replay+ // (1.41ms for four cards) and never reaches this loop at all.+ // Whatever else changes here, keep this path a straight render.+ //+ // Whatever the terminal itself was waiting to redraw for, put+ // back afterwards: a thumbnail must not claim the window's+ // animation deadline, and must not silently inherit one.+ let next_due = self.has_animation.borrow_mut().take();+ let line_started = crate::perf::now();self.render_screen_line(RenderScreenLineParams {top_pixel_y: y,- left_pixel_x: pane_x,+ left_pixel_x: 0.0,pixel_width: rendered_width,stable_line_idx: Some(pane.resolved_top + line_idx as isize),line,@@ -1428,9 +1820,15 @@ impl crate::TermWindow {}),password_input: false,allow_images: false,+ simple_shaping: true,},layers,)?;+ crate::perf::accum("line_render", line_started);+ // Restore by assignment, not min-merge: the line render above+ // may have claimed a blink/expiry deadline of its own, and a+ // merge would let the thumbnail keep it.+ *self.has_animation.borrow_mut() = next_due;}// Draw a non-blinking cursor for the active split. The regular@@ -1444,9 +1842,11 @@ impl crate::TermWindow {&& (cursor_row as usize) < rows&& cursor.x < cols{+ // Still inside the position transform, so pane-relative+ // like everything else drawn through it.let cursor_rect: ::window::RectF = euclid::rect(- pane_x + cursor.x as f32 * pane_cell_width,- rendered_y + cursor_row as f32 * pane_cell_height,+ cursor.x as f32 * pane_cell_width,+ cursor_row as f32 * pane_cell_height,pane_cell_width,pane_cell_height,);@@ -1506,7 +1906,7 @@ impl crate::TermWindow {split_stroke,)};- if let Some(visible) = rect.intersection(&preview.clip) {+ if let Some(visible) = rect.intersection(&preview.area) {self.filled_rectangle(layers, 2, visible, split_color)?;}}@@ -2504,6 +2904,147 @@ impl crate::TermWindow {mod tests {use super::*;+ fn test_preview(area: RectF) -> TerminalPreviewRequest {+ TerminalPreviewRequest {+ tab_id: 1,+ snapshot: Arc::new(crate::termwindow::content_view::TerminalPreviewSnapshot {+ tab_size: TerminalSize::default(),+ panes: vec![],+ splits: vec![],+ }),+ area,+ clip: area,+ hold_scale: false,+ }+ }++ fn test_dimensions() -> Dimensions {+ Dimensions {+ pixel_width: 1600,+ pixel_height: 1000,+ dpi: 144,+ }+ }++ /// The whole point of the cache: an unchanged snapshot in an unchanged card+ /// replays instead of being rebuilt.+ #[test]+ fn the_same_snapshot_in_the_same_card_keeps_its_quads() {+ let preview = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ assert_eq!(+ preview_quad_key(&preview, &test_dimensions(), 3),+ preview_quad_key(&preview, &test_dimensions(), 3)+ );+ }++ /// A card that has only scrolled shows the same picture somewhere else, so+ /// it stays a cache hit and is replayed through a translation.+ #[test]+ fn a_card_that_only_moved_keeps_its_quads() {+ let mut moved = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ let key = preview_quad_key(&moved, &test_dimensions(), 3);+ moved.area = moved.area.translate(euclid::vec2(0.0, -140.0));+ assert_eq!(preview_quad_key(&moved, &test_dimensions(), 3), key);+ }++ /// Resizing a card rebuckets the font scale, so the recorded quads are the+ /// wrong picture even though the terminal has not changed.+ #[test]+ fn a_resized_card_rebuilds() {+ let small = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ let mut large = small.clone();+ large.area.size.width = 480.0;+ assert_ne!(+ preview_quad_key(&large, &test_dimensions(), 3),+ preview_quad_key(&small, &test_dimensions(), 3)+ );+ }++ /// A font finishing its load means the card should be re-shaped, so the+ /// key stops matching and the card rebuilds.+ #[test]+ fn a_newly_loaded_font_rebuilds() {+ let preview = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ assert_ne!(+ preview_quad_key(&preview, &test_dimensions(), 4),+ preview_quad_key(&preview, &test_dimensions(), 3)+ );+ }++ /// The distinction the rebuild budget rests on: which misses may be shown+ /// one frame late, and which may not be shown at all.+ ///+ /// New content and a newly loaded font both leave quads that draw valid+ /// pixels in the right places -- only what they depict is behind. A card+ /// that has changed size or moved to another window does not: its quads+ /// carry positions relative to the window's centre and glyphs sized for the+ /// old card, so replaying them puts the picture in the wrong place. That is+ /// the flicker.+ #[test]+ fn only_a_stale_picture_may_be_shown_late() {+ let first = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ let mut recaptured = first.clone();+ recaptured.snapshot = Arc::new((*first.snapshot).clone());++ let old = preview_quad_key(&first, &test_dimensions(), 3);++ let new_content = preview_quad_key(&recaptured, &test_dimensions(), 3);+ assert_ne!(new_content, old, "a recapture must eventually be rebuilt");+ assert_eq!(+ new_content.geometry, old.geometry,+ "but the recorded quads still draw the right pixels meanwhile"+ );++ let new_font = preview_quad_key(&first, &test_dimensions(), 4);+ assert_ne!(new_font, old, "a loaded font must eventually be rebuilt");+ assert_eq!(+ new_font.geometry, old.geometry,+ "shaping does not move the atlas, so the quads stay showable"+ );++ let mut resized = first.clone();+ resized.area.size.width = 480.0;+ assert_ne!(+ preview_quad_key(&resized, &test_dimensions(), 3).geometry,+ old.geometry,+ "a resized card must not be replayed, at any budget"+ );++ let mut wider = test_dimensions();+ wider.pixel_width += 200;+ assert_ne!(+ preview_quad_key(&first, &wider, 3).geometry,+ old.geometry,+ "a resized window must not be replayed, at any budget"+ );+ }++ /// Quad positions are relative to the centre of the window, so every+ /// recorded position moves when the window does.+ #[test]+ fn a_resized_window_rebuilds() {+ let preview = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ let mut wider = test_dimensions();+ wider.pixel_width += 200;+ assert_ne!(+ preview_quad_key(&preview, &wider, 3),+ preview_quad_key(&preview, &test_dimensions(), 3)+ );+ }++ /// Two cards holding equal-looking snapshots are still two pictures: the+ /// key is the snapshot's identity, not its value.+ #[test]+ fn a_fresh_capture_rebuilds_even_when_it_looks_the_same() {+ let first = test_preview(euclid::rect(10.0, 20.0, 400.0, 260.0));+ let mut recaptured = first.clone();+ recaptured.snapshot = Arc::new((*first.snapshot).clone());+ assert_ne!(+ preview_quad_key(&recaptured, &test_dimensions(), 3),+ preview_quad_key(&first, &test_dimensions(), 3)+ );+ }+/// A card exactly the size of the grid it holds is left alone. This is the/// case the fill exists to *not* disturb.#[test]diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rsindex 5a3bf7fa..fe505e61 100644--- a/wezterm-gui/src/termwindow/render/pane.rs+++ b/wezterm-gui/src/termwindow/render/pane.rs@@ -1623,6 +1623,7 @@ impl crate::TermWindow {shape_key: Some(shape_key),password_input,allow_images: true,+ simple_shaping: false,},&mut TripleLayerQuadAllocator::Heap(&mut buf),)diff --git a/wezterm-gui/src/termwindow/render/screen_line.rs b/wezterm-gui/src/termwindow/render/screen_line.rsindex eecc9941..3d5efb7b 100644--- a/wezterm-gui/src/termwindow/render/screen_line.rs+++ b/wezterm-gui/src/termwindow/render/screen_line.rs@@ -132,6 +132,7 @@ impl crate::TermWindow {if !expired && !hover_changed {self.update_next_frame_time(entry.expires);shaped.replace(Rc::clone(&entry.shaped));+ crate::perf::accum_count("line_shape_hit");}invalidate_on_hover_change = entry.invalidate_on_hover_change;@@ -153,12 +154,16 @@ impl crate::TermWindow {font_config: params.font_config.as_ref(),render_metrics: params.render_metrics,font_identity: params.font_identity,+ simple_shaping: params.simple_shaping,};+ let build_started = crate::perf::now();let (shaped, invalidate_on_hover) = self.build_line_element_shape(params)?;+ crate::perf::accum("line_shape_build", build_started);invalidate_on_hover_change = invalidate_on_hover;shaped};+ let emit_started = crate::perf::now();let bounding_rect = euclid::rect(params.left_pixel_x,@@ -717,6 +722,7 @@ impl crate::TermWindow {}metrics::histogram!("render_screen_line").record(start.elapsed());+ crate::perf::accum("line_quad_emit", emit_started);Ok(RenderScreenLineResult {invalidate_on_hover_change,@@ -866,15 +872,27 @@ impl crate::TermWindow {let style_params = last_style.as_ref().expect("we just set it up").clone();- let glyph_info = self.cached_cluster_shape(- style_params.style,- &cluster,- &gl_state,- params.font,- params.font_config,- ¶ms.render_metrics,- params.font_identity,- )?;+ let glyph_info = if params.simple_shaping {+ self.cached_cluster_shape_by_cell(+ style_params.style,+ &cluster,+ &gl_state,+ params.font,+ params.font_config,+ ¶ms.render_metrics,+ params.font_identity,+ )?+ } else {+ self.cached_cluster_shape(+ style_params.style,+ &cluster,+ &gl_state,+ params.font,+ params.font_config,+ ¶ms.render_metrics,+ params.font_identity,+ )?+ };let pixel_width = glyph_info.iter().map(|info| info.glyph.x_advance.get() as f32)diff --git a/wezterm-gui/src/termwindow/render/tab_bar.rs b/wezterm-gui/src/termwindow/render/tab_bar.rsindex 9ebb7014..1f618b93 100644--- a/wezterm-gui/src/termwindow/render/tab_bar.rs+++ b/wezterm-gui/src/termwindow/render/tab_bar.rs@@ -148,6 +148,7 @@ impl crate::TermWindow {shape_key: None,password_input: false,allow_images: true,+ simple_shaping: false,},layers,)?;diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex 3b860f35..5a18558f 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -1977,6 +1977,11 @@ impl super::TermWindow {fn sync_active_mux_tab_pane_sizes(&self) {if !self.owns_frontend_viewport() {+ // Another frontend holds this tab's lease; resizing its PTYs from+ // here would fight it. Logged because a *wrongly* closed gate is+ // invisible otherwise: it silently strands every pane at its old+ // size during divider drags.+ log::debug!("skipping pane size sync: frontend viewport not owned");return;}let Some(tab) = Mux::get().get_active_tab_for_window(self.mux_window_id) else {diff --git a/wezterm-gui/src/termwindow/webgpu.rs b/wezterm-gui/src/termwindow/webgpu.rsindex b0acba67..a8d4ea8f 100644--- a/wezterm-gui/src/termwindow/webgpu.rs+++ b/wezterm-gui/src/termwindow/webgpu.rs@@ -404,7 +404,11 @@ impl WebGpuState {};let config = wgpu::SurfaceConfiguration {- usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ usage: if crate::framedump::enabled() {+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC+ } else {+ wgpu::TextureUsages::RENDER_ATTACHMENT+ },format,width: dimensions.pixel_width as u32,height: dimensions.pixel_height as u32,diff --git a/wezterm-toast-notification/build.rs b/wezterm-toast-notification/build.rsindex 5ecc6da6..3899f734 100644--- a/wezterm-toast-notification/build.rs+++ b/wezterm-toast-notification/build.rs@@ -1,5 +1,7 @@fn main() {- if cfg!(target_os = "macos") {+ // cfg!() in a build script tests the HOST, not the TARGET; use the+ // cargo-provided target var so cross builds don't link Apple frameworks.+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {println!("cargo:rustc-link-lib=framework=UserNotifications");}}diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rsindex 8c0cc386..b0b92d78 100644--- a/window/src/os/macos/window.rs+++ b/window/src/os/macos/window.rs@@ -158,6 +158,30 @@ fn target_frame_fps(configured_max_fps: u64) -> f64 {configured.min(screen).max(1.0)}+/// How long to hold the next frame back, or `None` to let the display decide.+///+/// The throttle exists to honour a `max_fps` set *below* the panel's rate. When+/// it is not below it -- and the default 120 is not below a 120Hz panel -- there+/// is nothing left to enforce, because CoreAnimation already delivers `drawRect`+/// once per refresh. Running the timer anyway is not merely redundant, it costs+/// a refresh: the delay was measured from the *end* of the paint, so a 7ms frame+/// was followed by a full 8.3ms of enforced idleness and only then by the wait+/// for the next vsync, and every `drawRect` AppKit delivered in between was+/// dropped by the throttle check. Measured: delivered frames every 33ms on a+/// 120Hz panel while painting took 7ms.+fn frame_throttle_delay(+ configured_max_fps: u64,+ spent: std::time::Duration,+) -> Option<std::time::Duration> {+ let screen = macos_current_screen_max_fps().unwrap_or(60).max(1) as f64;+ if configured_max_fps.max(1) as f64 >= screen {+ return None;+ }+ let period = std::time::Duration::from_secs_f64(1.0 / target_frame_fps(configured_max_fps));+ let remaining = period.saturating_sub(spent);+ (!remaining.is_zero()).then_some(remaining)+}+fn ns_event_phase_to_scroll_phase(phase: NSEventPhase) -> Option<ScrollPhase> {if phase.contains(NSEventPhase::NSEventPhaseBegan) {Some(ScrollPhase::Began)@@ -1668,10 +1692,24 @@ impl WindowInner {// Avoid borrowing the view's `Inner` here: `set_cursor` can be// reached synchronously from inside an event dispatch that already// holds that borrow, so we stash the value in an ivar instead.- (**self.view).set_ivar::<i64>(CURSOR_IVAR, cursor_to_code(cursor));- // Ask AppKit to rebuild the cursor rects so the change above takes- // effect for its own cursor management on the next event.- let () = msg_send![*self.window, invalidateCursorRectsForView: *self.view];+ // Only rebuild the cursor rects when the cursor actually changes.+ // `set_cursor` runs on every mouse move, and+ // `invalidateCursorRectsForView:` makes AppKit re-route the rects+ // through the window server (`routeCursorRect` ->+ // `_NSFindWindowUnderMouse` -> SLS* IPC) synchronously on the main+ // thread. Sampled during a divider drag, that routing ate 30-45%+ // of the drag's wall time and serialized mouse-event delivery --+ // the whole app felt like a remote session. The registered rect+ // stays valid while the cursor kind is unchanged, so skipping the+ // invalidation loses nothing.+ let code = cursor_to_code(cursor);+ let prev: i64 = *(**self.view).get_ivar::<i64>(CURSOR_IVAR);+ if prev != code {+ (**self.view).set_ivar::<i64>(CURSOR_IVAR, code);+ // Ask AppKit to rebuild the cursor rects so the change above+ // takes effect for its own cursor management on the next event.+ let () = msg_send![*self.window, invalidateCursorRectsForView: *self.view];+ }if let Some(cursor) = cursor {// Unconditionally apply the requested cursor, as there are@@ -2725,6 +2763,14 @@ struct WindowView {// the frame throttle timer, invalidate()), and losing an update here is// what makes the window stop refreshing until the next user interaction.paint_throttled: Cell<bool>,+ // When the throttle was engaged. The async timer that clears the flag is+ // a single point of failure -- display sleep coalesces timers hard enough+ // to lose it outright, and once it is gone every drawRect short-circuits+ // on the flag forever (observed: a window frozen from the 50th minute of+ // a display-off stretch until relaunch). This timestamp is what lets+ // drawRect notice that the throttle has outlived any legal frame period+ // and break the latch itself.+ paint_throttled_since: Cell<Option<Instant>>,invalidated: Cell<bool>,}@@ -4338,29 +4384,64 @@ impl WindowView {return;}- if this.paint_throttled.get() {+ // The throttle is only honored while its clearing timer can still+ // plausibly be pending. No legal frame period reaches anywhere+ // near this bound, so blowing past it means the timer is lost and+ // waiting on it would freeze the window permanently.+ const PAINT_THROTTLE_WATCHDOG: std::time::Duration =+ std::time::Duration::from_millis(250);+ let throttle_holds = this.paint_throttled.get()+ && this+ .paint_throttled_since+ .get()+ .is_some_and(|since| since.elapsed() < PAINT_THROTTLE_WATCHDOG);+ if this.paint_throttled.get() && !throttle_holds {+ log::warn!("paint throttle outlived its clearing timer; breaking the latch");+ }+ if throttle_holds {this.invalidated.set(true);} else {let now = Instant::now();if let Some(last) = inner.last_repaint_time.replace(now) {if thinkterm_perf_enabled() {log::info!(- "thinkterm_perf macos_frame_interval_ms={:.2}",- now.saturating_duration_since(last).as_secs_f64() * 1000.0+ "thinkterm_perf macos_frame_interval_ms={:.2} win={}",+ now.saturating_duration_since(last).as_secs_f64() * 1000.0,+ inner.window_id,);}}inner.events.dispatch(WindowEvent::NeedRepaint);this.invalidated.set(false);this.paint_throttled.set(true);+ this.paint_throttled_since.set(Some(now));let window_id = inner.window_id;let max_fps = target_frame_fps(inner.config.max_fps);if thinkterm_perf_enabled() {log::info!("thinkterm_perf macos_target_fps={max_fps:.0}");}+ let Some(remaining) = frame_throttle_delay(inner.config.max_fps, now.elapsed())+ else {+ // Nothing left to enforce; hand the pacing back to the+ // display, which is the only clock that matters here.+ this.paint_throttled.set(false);+ if this.invalidated.get() {+ // Through `performSelector` rather than setting the flag+ // inline: AppKit clears `needsDisplay` around this pass,+ // so a request made from inside it can be lost.+ if let Some(view_id) = inner.view_id.as_ref().map(|view| view.load()) {+ unsafe {+ let () = msg_send![*view_id, performSelector: sel!(thinktermRearmNeedsDisplay)+ withObject: nil+ afterDelay: 0.0];+ }+ }+ }+ return;+ };promise::spawn::spawn(async move {- async_io::Timer::after(std::time::Duration::from_secs_f64(1.0 / max_fps)).await;+ async_io::Timer::after(remaining).await;Connection::with_window_inner(window_id, move |inner| {if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {window_view.paint_throttled.set(false);@@ -4496,6 +4577,7 @@ impl WindowView {let view = Box::into_raw(Box::new(Self {inner: Rc::clone(&inner),paint_throttled: Cell::new(false),+ paint_throttled_since: Cell::new(None),invalidated: Cell::new(true),}));