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
Render overview cards as offscreen textures
RoversX99b211d3b540
diff --git a/wezterm-gui/src/quad.rs b/wezterm-gui/src/quad.rsindex d8ec3d0d..0ef6e4e9 100644--- a/wezterm-gui/src/quad.rs+++ b/wezterm-gui/src/quad.rs@@ -832,6 +832,26 @@ impl HeapQuadAllocator {/// Copy every recorded quad into `other`, cropped to `clip` and scaled to/// `opacity`.+ /// Flatten the recorded quads into a plain vertex stream: sub-layer 0,+ /// then 1, then 2, in recorded order -- the order a replay would draw+ /// them. Used to render a card's picture into its own texture, where+ /// the render pass's projection does the placement and cropping, so the+ /// vertices go out untransformed and unclipped.+ pub fn extract_vertices(&self, out: &mut Vec<Vertex>) {+ for (_layer_num, quads) in self.layers() {+ for quad in quads {+ out.extend_from_slice(&quad.to_vertices());+ }+ }+ }++ pub fn quad_count(&self) -> usize {+ self.layers()+ .iter()+ .map(|(_, quads)| quads.len())+ .sum()+ }+/// Position, texture coordinates and per-corner colors are transformed/// together by the same primitive used by Space swipe composition.///diff --git a/wezterm-gui/src/renderstate.rs b/wezterm-gui/src/renderstate.rsindex 7dbb1167..e3166447 100644--- a/wezterm-gui/src/renderstate.rs+++ b/wezterm-gui/src/renderstate.rs@@ -267,10 +267,7 @@ impl MappedVertexBuffer {fn slice_mut(&mut self, range: std::ops::Range<usize>) -> &mut [Vertex] {match self {Self::Glium(g) => &mut g.mapping[range],- Self::WebGpu(g) => {- let mapping: &mut [Vertex] = bytemuck::cast_slice_mut(&mut g.mapping);- &mut mapping[range]- }+ Self::WebGpu(g) => &mut g.mapping[range],}}}@@ -282,13 +279,17 @@ pub struct MappedQuads<'a> {}pub struct WebGpuMappedVertexBuffer {- mapping: wgpu::BufferViewMut<'static>,- // Owner mapping, must be dropped after mapping- _slice: wgpu::BufferSlice<'static>,+ mapping: RefMut<'static, Vec<Vertex>>,}pub struct WebGpuVertexBuffer {buf: wgpu::Buffer,+ /// CPU-side quad staging. Quads are written here during layout and the+ /// used range is uploaded with `queue.write_buffer` at draw time. The+ /// GPU buffer is persistent: the old scheme allocated a fresh+ /// `mapped_at_creation` buffer every frame, and wgpu zero-fills those --+ /// megabytes of allocation and memset per layer per frame.+ staging: Vec<Vertex>,num_vertices: usize,state: Rc<WebGpuState>,}@@ -306,41 +307,30 @@ impl WebGpuVertexBuffer {buf: state.device.create_buffer(&wgpu::BufferDescriptor {label: Some("Vertex Buffer"),size: (num_vertices * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,- usage: wgpu::BufferUsages::VERTEX,- mapped_at_creation: true,+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,}),+ staging: vec![Vertex::default(); num_vertices],num_vertices,state: Rc::clone(state),}}- pub fn map(&self) -> WebGpuMappedVertexBuffer {- unsafe {- let slice = self.buf.slice(..).extend_lifetime();- let mapping = slice.get_mapped_range_mut();-- WebGpuMappedVertexBuffer {- mapping,- _slice: slice,- }- }- }-- /// Size of the buffer this recreates, which is the capacity high-water+ /// Size of the persistent buffer, 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"),- size: (self.num_vertices * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,- usage: wgpu::BufferUsages::VERTEX,- mapped_at_creation: true,- });- std::mem::swap(&mut new_buf, &mut self.buf);- new_buf+ /// Upload the used prefix of the staging quads into the persistent+ /// GPU buffer.+ pub fn upload(&self, vertex_count: usize) {+ let count = vertex_count.min(self.staging.len());+ if count > 0 {+ self.state+ .queue+ .write_buffer(&self.buf, 0, bytemuck::cast_slice(&self.staging[..count]));+ }}}@@ -509,21 +499,32 @@ impl TripleVertexBuffer {// we can then store in the same struct.// This is "safe" because we carry them around together and ensure// that the owner is dropped after the derived data.- let mapping = match &mut *bufs {- VertexBuffer::Glium(vb) => {- let buf_slice = unsafe {+ let mapping = if matches!(&*bufs, VertexBuffer::Glium(_)) {+ let buf_slice = {+ let vb = match &mut *bufs {+ VertexBuffer::Glium(vb) => vb,+ _ => unreachable!(),+ };+ unsafe {vb.slice_mut(..).expect("to map vertex buffer").extend_lifetime()- };- let mapping = buf_slice.map();+ }+ };+ let mapping = buf_slice.map();- MappedVertexBuffer::Glium(GliumMappedVertexBuffer {- _owner: bufs,- mapping,- })- }- VertexBuffer::WebGpu(vb) => MappedVertexBuffer::WebGpu(vb.map()),+ MappedVertexBuffer::Glium(GliumMappedVertexBuffer {+ _owner: bufs,+ mapping,+ })+ } else {+ // The WebGpu "mapping" is the CPU staging Vec; the RefMut keeps+ // the owning VertexBuffer borrowed for the mapping's lifetime.+ let staging = RefMut::map(bufs, |vb| match vb {+ VertexBuffer::WebGpu(vb) => &mut vb.staging,+ _ => unreachable!(),+ });+ MappedVertexBuffer::WebGpu(WebGpuMappedVertexBuffer { mapping: staging })};MappedQuads {@@ -555,6 +556,10 @@ pub struct RenderLayer {}impl RenderLayer {+ pub fn zindex(&self) -> i8 {+ self.zindex+ }+pub fn new(context: &RenderContext, num_quads: usize, zindex: i8) -> anyhow::Result<Self> {let vb = [Self::compute_vertices(context, 32)?,diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 1bb72ff8..29e494ce 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -3594,6 +3594,11 @@ impl SettingsWindow {corner_radius,window_border,usize::MAX, // settings window; no mux window behind it+ crate::termwindow::render::draw::CardDrawData {+ pending: Vec::new(),+ composites: Vec::new(),+ },+ &mut None,)?;Ok(true)}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex a83a9b55..b1262d7f 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -58,7 +58,7 @@ use mux::{Mux, MuxNotification};use mux_lua::MuxPane;use smol::channel::Sender;use smol::Timer;-use std::cell::{RefCell, RefMut};+use std::cell::{Cell, RefCell, RefMut};use std::collections::{HashMap, HashSet, LinkedList, VecDeque};use std::ops::{Add, Range};use std::path::{Path, PathBuf};@@ -1176,6 +1176,9 @@ pub struct PaneState {pub struct PaneFontEntry {pub fonts: Rc<FontConfiguration>,pub render_metrics: RenderMetrics,+ /// LRU stamp from `pane_font_cache_tick`; the cache holds whole+ /// FontConfigurations and would otherwise only ever grow.+ last_used: Cell<u64>,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]@@ -1493,12 +1496,24 @@ pub struct TermWindow {tab_state: RefCell<HashMap<TabId, TabState>>,pane_state: RefCell<HashMap<PaneId, PaneState>>,pane_font_cache: RefCell<HashMap<PaneFontKey, PaneFontEntry>>,+ pane_font_cache_tick: Cell<u64>,/// 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>>,+ /// Cards whose heap must be rendered into their texture this frame;+ /// queued by the paint pass, encoded by draw before the main pass.+ pending_card_renders: RefCell<Vec<crate::termwindow::render::paint::PendingCardRender>>,+ /// One textured quad per card standing in for its glyph quads.+ card_composites: RefCell<Vec<crate::termwindow::render::paint::CardComposite>>,+ /// The settled frame's composites, kept so a closing overview's ghost+ /// can fade the card pictures out with it (the ghost heap itself holds+ /// no thumbnail quads on the texture path).+ content_view_last_composites: RefCell<Vec<crate::termwindow::render::paint::CardComposite>>,+ /// Grow-only scratch GPU buffers for card render passes.+ card_scratch: RefCell<Option<crate::termwindow::render::draw::CardScratch>>,/// 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>>,@@ -2438,7 +2453,12 @@ impl TermWindow {tab_state: RefCell::new(HashMap::new()),pane_state: RefCell::new(HashMap::new()),pane_font_cache: RefCell::new(HashMap::new()),+ pane_font_cache_tick: Cell::new(0),preview_quad_cache: RefCell::new(HashMap::new()),+ pending_card_renders: RefCell::new(Vec::new()),+ card_composites: RefCell::new(Vec::new()),+ content_view_last_composites: RefCell::new(Vec::new()),+ card_scratch: RefCell::new(None),preview_scale_hold: RefCell::new(HashMap::new()),current_mouse_buttons: vec![],current_mouse_capture: None,@@ -7567,7 +7587,11 @@ impl TermWindow {config_generation: self.config.generation(),};+ let tick = self.pane_font_cache_tick.get().wrapping_add(1);+ self.pane_font_cache_tick.set(tick);+if let Some(entry) = self.pane_font_cache.borrow().get(&key) {+ entry.last_used.set(tick);return Ok((Rc::clone(&entry.fonts), entry.render_metrics));}@@ -7579,13 +7603,31 @@ impl TermWindow {fonts.change_scaling(font_scale, self.dimensions.dpi);let render_metrics = RenderMetrics::new(&fonts)?;- self.pane_font_cache.borrow_mut().insert(- key,- PaneFontEntry {- fonts: Rc::clone(&fonts),- render_metrics,- },- );+ {+ let mut cache = self.pane_font_cache.borrow_mut();+ // Each entry is a whole FontConfiguration (fonts, shaper state,+ // atlas-resident glyphs); unbounded, the map only ever grows as+ // scrolling and resizing walk new scale buckets.+ const PANE_FONT_CACHE_CAP: usize = 16;+ while cache.len() >= PANE_FONT_CACHE_CAP {+ let Some(oldest) = cache+ .iter()+ .min_by_key(|(_, entry)| entry.last_used.get())+ .map(|(key, _)| *key)+ else {+ break;+ };+ cache.remove(&oldest);+ }+ cache.insert(+ key,+ PaneFontEntry {+ fonts: Rc::clone(&fonts),+ render_metrics,+ last_used: Cell::new(tick),+ },+ );+ }crate::perf::accum("font_config_build", build_started);Ok((fonts, render_metrics))diff --git a/wezterm-gui/src/termwindow/render/draw.rs b/wezterm-gui/src/termwindow/render/draw.rsindex 5fa4fd4f..6c401ffa 100644--- a/wezterm-gui/src/termwindow/render/draw.rs+++ b/wezterm-gui/src/termwindow/render/draw.rs@@ -15,6 +15,129 @@ use config::FreeTypeLoadTarget;const LINUX_WINDOW_CORNER_RADIUS: f32 = 16.0;const LINUX_WINDOW_BORDER_WIDTH: f32 = 1.0;+/// Grow-only scratch GPU buffers shared by every card render and composite+/// draw of a frame: one vertex upload, sliced per draw with `base_vertex`.+pub(crate) struct CardScratch {+ vb: wgpu::Buffer,+ vb_capacity_verts: usize,+ index: wgpu::Buffer,+ index_capacity_quads: usize,+}++impl CardScratch {+ fn ensure(+ scratch: &mut Option<CardScratch>,+ state: &WebGpuState,+ verts_needed: usize,+ quads_needed: usize,+ ) {+ use crate::quad::{VERTICES_PER_CELL, V_BOT_LEFT, V_BOT_RIGHT, V_TOP_LEFT, V_TOP_RIGHT};+ const INDICES_PER_CELL: usize = 6;+ let need_vb = scratch+ .as_ref()+ .map_or(true, |s| s.vb_capacity_verts < verts_needed);+ let need_index = scratch+ .as_ref()+ .map_or(true, |s| s.index_capacity_quads < quads_needed);+ if !need_vb && !need_index {+ return;+ }+ let vb_capacity_verts = scratch+ .as_ref()+ .map(|s| s.vb_capacity_verts)+ .unwrap_or(0)+ .max(verts_needed)+ .next_power_of_two()+ .max(1024);+ let index_capacity_quads = scratch+ .as_ref()+ .map(|s| s.index_capacity_quads)+ .unwrap_or(0)+ .max(quads_needed)+ .next_power_of_two()+ .max(256);+ let vb = state.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("Card Scratch Vertices"),+ size: (vb_capacity_verts * std::mem::size_of::<crate::quad::Vertex>())+ as wgpu::BufferAddress,+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let mut indices: Vec<u32> = Vec::with_capacity(index_capacity_quads * INDICES_PER_CELL);+ for q in 0..index_capacity_quads {+ let idx = (q * VERTICES_PER_CELL) as u32;+ indices.push(idx + V_TOP_LEFT as u32);+ indices.push(idx + V_TOP_RIGHT as u32);+ indices.push(idx + V_BOT_LEFT as u32);+ indices.push(idx + V_TOP_RIGHT as u32);+ indices.push(idx + V_BOT_LEFT as u32);+ indices.push(idx + V_BOT_RIGHT as u32);+ }+ let index = wgpu::util::DeviceExt::create_buffer_init(+ &state.device,+ &wgpu::util::BufferInitDescriptor {+ label: Some("Card Scratch Indices"),+ usage: wgpu::BufferUsages::INDEX,+ contents: bytemuck::cast_slice(&indices),+ },+ );+ *scratch = Some(CardScratch {+ vb,+ vb_capacity_verts,+ index,+ index_capacity_quads,+ });+ }+}++/// The card texture work of one frame, handed from the paint pass to the+/// draw: heaps to render into card textures, and the textured quads that+/// stand in for the cards in the main pass.+pub(crate) struct CardDrawData {+ pub pending: Vec<crate::termwindow::render::paint::PendingCardRender>,+ pub composites: Vec<crate::termwindow::render::paint::CardComposite>,+}++/// Build the 4 vertices of one composite quad: `dest` cropped to `clip`,+/// UVs following the crop, positions converted to the window-centre-origin+/// space the shared projection expects.+fn composite_quad_verts(+ composite: &crate::termwindow::render::paint::CardComposite,+ dimensions: &Dimensions,+) -> Option<[crate::quad::Vertex; 4]> {+ use crate::quad::Vertex;+ let dest = composite.dest;+ let vis = dest.intersection(&composite.clip)?;+ if vis.size.width <= 0.0 || vis.size.height <= 0.0 {+ return None;+ }+ let half_w = dimensions.pixel_width as f32 / 2.0;+ let half_h = dimensions.pixel_height as f32 / 2.0;+ let u0 = (vis.min_x() - dest.min_x()) / dest.size.width;+ let u1 = (vis.max_x() - dest.min_x()) / dest.size.width;+ let v0 = (vis.min_y() - dest.min_y()) / dest.size.height;+ let v1 = (vis.max_y() - dest.min_y()) / dest.size.height;+ let (x0, x1) = (vis.min_x() - half_w, vis.max_x() - half_w);+ let (y0, y1) = (vis.min_y() - half_h, vis.max_y() - half_h);+ const IS_BG_IMAGE: f32 = 2.0;+ let vert = |x: f32, y: f32, u: f32, v: f32| Vertex {+ position: [x, y],+ tex: [u, v],+ fg_color: [1.0, 1.0, 1.0, composite.opacity],+ alt_color: [1.0, 1.0, 1.0, composite.opacity],+ hsv: [1.0, 1.0, 1.0],+ has_color: IS_BG_IMAGE,+ mix_value: 0.0,+ };+ // Corner order matches the shared index pattern: TL, TR, BL, BR.+ Some([+ vert(x0, y0, u0, v0),+ vert(x1, y0, u1, v0),+ vert(x0, y1, u0, v1),+ vert(x1, y1, u1, v1),+ ])+}+#[derive(Clone, Copy, Debug, PartialEq)]pub(crate) struct WindowBorder {pub width: f32,@@ -87,6 +210,8 @@ pub(crate) fn draw_webgpu_layers(corner_radius: f32,window_border: WindowBorder,window_label: usize,+ cards: CardDrawData,+ card_scratch: &mut Option<CardScratch>,) -> anyhow::Result<()> {let acquire_start = crate::perf::now();let output = webgpu.surface.get_current_texture()?;@@ -143,6 +268,109 @@ pub(crate) fn draw_webgpu_layers().to_arrays_transposed();+ // ---- Card texture work -------------------------------------------------+ // One combined vertex upload covers every card render pass and every+ // composite quad; each draw slices it with `base_vertex`. The uploads+ // must all happen before any pass is encoded because queued buffer+ // writes run at the head of the submit.+ let card_pass_start = crate::perf::now();+ let mut card_verts: Vec<crate::quad::Vertex> = Vec::new();+ let mut pending_ranges = Vec::with_capacity(cards.pending.len());+ for pending in &cards.pending {+ let base = card_verts.len();+ card_verts.extend_from_slice(&pending.verts);+ pending_ranges.push((base, pending.verts.len() / 4));+ }+ let mut composite_draws: Vec<(i8, i32, &crate::termwindow::render::paint::CardComposite)> =+ Vec::with_capacity(cards.composites.len());+ for composite in &cards.composites {+ if let Some(verts) = composite_quad_verts(composite, &dimensions) {+ let base = card_verts.len();+ card_verts.extend_from_slice(&verts);+ composite_draws.push((composite.zindex, base as i32, composite));+ }+ }+ if !card_verts.is_empty() {+ let max_quads = pending_ranges+ .iter()+ .map(|(_, quads)| *quads)+ .max()+ .unwrap_or(0)+ .max(1);+ CardScratch::ensure(card_scratch, webgpu, card_verts.len(), max_quads);+ let scratch = card_scratch.as_ref().expect("just ensured");+ webgpu+ .queue+ .write_buffer(&scratch.vb, 0, bytemuck::cast_slice(&card_verts));++ // Render each dirty card's quads into its texture. These passes are+ // encoded before the main pass, so the composites below sample the+ // fresh picture.+ for (pending, (base, quads)) in cards.pending.iter().zip(&pending_ranges) {+ if *quads == 0 {+ continue;+ }+ let half_w = dimensions.pixel_width as f32 / 2.0;+ let half_h = dimensions.pixel_height as f32 / 2.0;+ let area = pending.area;+ // `to_arrays()`, NOT `to_arrays_transposed()`: euclid's ortho+ // keeps its translation in the fourth row, and the shader+ // multiplies matrix * column-vector, so the plain row arrays are+ // already the WGSL column layout. The main pass gets away with+ // the transposed form only because its ortho is symmetric --+ // translation is zero there, and a transposed diagonal is+ // itself. This ortho is off-centre; transposing it puts the+ // translation into the w row and every card collapses into a+ // perspective wedge.+ let card_projection = euclid::Transform3D::<f32, f32, f32>::ortho(+ area.min_x() - half_w,+ area.max_x() - half_w,+ area.max_y() - half_h,+ area.min_y() - half_h,+ -1.0,+ 1.0,+ )+ .to_arrays();+ let card_uniforms = webgpu.create_uniform(ShaderUniform {+ foreground_text_hsb,+ milliseconds,+ viewport_and_corner: [+ pending.texture.width as f32,+ pending.texture.height as f32,+ 0.0,+ 0.0,+ ],+ window_border: [0.0; 4],+ projection: card_projection,+ });+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("Card Render Pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &pending.texture.view,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ occlusion_query_set: None,+ timestamp_writes: None,+ });+ pass.set_pipeline(&webgpu.render_pipeline);+ pass.set_bind_group(0, &card_uniforms, &[]);+ pass.set_bind_group(1, &texture_linear_bind_group, &[]);+ pass.set_bind_group(2, &texture_nearest_bind_group, &[]);+ pass.set_vertex_buffer(0, scratch.vb.slice(..));+ pass.set_index_buffer(scratch.index.slice(..), wgpu::IndexFormat::Uint32);+ pass.draw_indexed(0..(*quads * 6) as u32, *base as i32, 0..1);+ }+ }+ crate::perf::log_duration("card_texture_passes", card_pass_start);+ crate::perf::log_counter("card_texture_renders", cards.pending.len());+ crate::perf::log_counter("card_composites", composite_draws.len());+ // -----------------------------------------------------------------------+let mut cleared = false;let mut draw_calls = 0usize;let mut vertices_total = 0usize;@@ -151,10 +379,9 @@ pub(crate) fn draw_webgpu_layers(for idx in 0..3 {let vb = &layer.vb.borrow()[idx];let (vertex_count, index_count) = vb.vertex_index_count();- let vertex_buffer;let uniforms;if vertex_count > 0 {- let mut vertices = vb.current_vb_mut();+ let vertices = vb.current_vb_mut();let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {label: Some("Render Pass"),color_attachments: &[Some(wgpu::RenderPassColorAttachment {@@ -197,16 +424,16 @@ 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);+ // Upload only the quads this frame actually wrote into the+ // persistent vertex buffer. The old scheme allocated a fresh+ // `mapped_at_creation` buffer every frame, which wgpu+ // zero-fills -- megabytes of allocation and memset per layer+ // per frame, measured at ~10% of the main thread.+ let upload_start = crate::perf::now();+ vertices.webgpu().upload(vertex_count);+ crate::perf::log_duration("webgpu_vb_upload", upload_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.set_vertex_buffer(0, vertices.webgpu().slice(..));render_pass.set_index_buffer(vb.indices.webgpu().slice(..), wgpu::IndexFormat::Uint32);render_pass.draw_indexed(0..index_count as _, 0, 0..1);@@ -214,6 +441,68 @@ pub(crate) fn draw_webgpu_layers(vertices_total += vertex_count;}+ // Card pictures composite between this layer's base fills and+ // its glyph sub-buffers: above their own card background, below+ // every label drawn on top.+ if idx == 0+ && composite_draws+ .iter()+ .any(|(zindex, _, _)| *zindex == layer.zindex())+ {+ let scratch = card_scratch+ .as_ref()+ .expect("composite draws imply the scratch exists");+ let comp_uniforms = webgpu.create_uniform(ShaderUniform {+ foreground_text_hsb,+ milliseconds,+ viewport_and_corner: [+ dimensions.pixel_width as f32,+ dimensions.pixel_height as f32,+ corner_radius,+ 0.0,+ ],+ window_border: [+ window_border.color[0],+ window_border.color[1],+ window_border.color[2],+ window_border.width,+ ],+ projection,+ });+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("Card Composite Pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ resolve_target: None,+ ops: wgpu::Operations {+ load: if cleared {+ wgpu::LoadOp::Load+ } else {+ wgpu::LoadOp::Clear(clear_color)+ },+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ occlusion_query_set: None,+ timestamp_writes: None,+ });+ cleared = true;+ pass.set_pipeline(&webgpu.render_pipeline);+ pass.set_bind_group(0, &comp_uniforms, &[]);+ pass.set_vertex_buffer(0, scratch.vb.slice(..));+ pass.set_index_buffer(scratch.index.slice(..), wgpu::IndexFormat::Uint32);+ for (zindex, base, composite) in &composite_draws {+ if *zindex != layer.zindex() {+ continue;+ }+ pass.set_bind_group(1, &composite.texture.bind_group, &[]);+ pass.set_bind_group(2, &composite.texture.bind_group, &[]);+ pass.draw_indexed(0..6, *base, 0..1);+ draw_calls += 1;+ }+ }+vb.next_index();}}@@ -232,6 +521,18 @@ pub(crate) fn draw_webgpu_layers() {log::error!("framedump failed: {err:#}");}+ // Ground truth for the card texture path: dump each card texture+ // rendered this frame under a distinctive label.+ for (i, pending) in cards.pending.iter().enumerate() {+ if let Err(err) = crate::framedump::dump_texture(+ &webgpu.device,+ &webgpu.queue,+ &pending.texture.texture,+ 90000 + i,+ ) {+ log::error!("card framedump failed: {err:#}");+ }+ }}output.present();crate::perf::log_duration("webgpu_submit_present", submit_start);@@ -269,6 +570,11 @@ impl crate::TermWindow {self.dimensions.dpi,crate::native_settings::effective_appearance(),);+ let cards = CardDrawData {+ pending: std::mem::take(&mut *self.pending_card_renders.borrow_mut()),+ composites: std::mem::take(&mut *self.card_composites.borrow_mut()),+ };+ let mut card_scratch = self.card_scratch.borrow_mut();draw_webgpu_layers(webgpu,render_state,@@ -284,6 +590,8 @@ impl crate::TermWindow {corner_radius,window_border,self.mux_window_id as usize,+ cards,+ &mut card_scratch,)}diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex e9bddbbf..cc71634f 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -14,6 +14,7 @@ use smol::Timer;use std::collections::hash_map::DefaultHasher;use std::collections::HashSet;use std::hash::{Hash, Hasher};+use std::rc::Rc;use std::sync::Arc;use std::time::{Duration, Instant};use window::Dimensions;@@ -22,7 +23,12 @@ use wezterm_term::color::ColorAttribute;use wezterm_term::TerminalSize;const TERMINAL_PREVIEW_EXTENT_BUCKET_DESIGN_PX: f32 = 8.0;-const TERMINAL_PREVIEW_SCALE_BUCKETS_PER_UNIT: f64 = 128.0;+/// Coarse on purpose: every distinct bucket becomes a `FontConfiguration`+/// (a 4-8ms main-thread build plus its own glyph-atlas population and a new+/// shape-cache identity). At 128 buckets/unit a session of scrolling and+/// resizing built 96 of them in two minutes; at 16 the cell-size difference+/// between adjacent buckets is sub-pixel at thumbnail sizes.+const TERMINAL_PREVIEW_SCALE_BUCKETS_PER_UNIT: f64 = 16.0;/// How far the preview may walk down from its estimated font scale looking for/// one that fits. Each step costs a `FontConfiguration`, and the estimate is/// close enough that one is usually all it takes.@@ -101,7 +107,11 @@ pub(crate) struct PreviewQuadKey {pub(crate) struct PreviewGeometryKey {area_width: u32,area_height: u32,- hold_scale: bool,+ /// The *resolved* render scale (`preview_scale_estimate`), not the+ /// drag-time hold flag it replaced: the flag flipped at every gesture+ /// start and end, and each flip re-keyed all cards at once -- a full+ /// same-frame rebuild of the overview to draw the identical picture.+ scale_bits: u64,pixel_width: usize,pixel_height: usize,dpi: usize,@@ -118,12 +128,45 @@ pub(crate) struct CachedPreviewQuads {/// The card rectangle these quads were laid out in.area: RectF,heap: HeapQuadAllocator,+ /// The card's picture as a texture (WebGpu only). Rendered from `heap`+ /// when content changes; composited as a single quad on every other+ /// frame, which is what makes an unchanged card nearly free.+ texture: Option<Rc<crate::termwindow::webgpu::CardRenderTexture>>,+}++/// A card whose heap must be rendered into its texture this frame, queued by+/// the paint pass and encoded by `draw_webgpu_layers` before the main pass.+pub(crate) struct PendingCardRender {+ pub texture: Rc<crate::termwindow::webgpu::CardRenderTexture>,+ /// The card's quads, flattened; positions are window-centre-relative and+ /// the pass's projection maps `area` onto the texture.+ pub verts: Vec<crate::quad::Vertex>,+ /// The rect (top-left window pixels) the verts were recorded against.+ pub area: RectF,+}++/// One textured quad standing in for a card's thousands of glyph quads,+/// drawn between the base fills and the glyph sub-layers of the main pass.+#[derive(Clone)]+pub(crate) struct CardComposite {+ pub texture: Rc<crate::termwindow::webgpu::CardRenderTexture>,+ /// Where the card is being drawn this frame (top-left window pixels).+ pub dest: RectF,+ /// Visible region; the quad is shrunk to this and its UVs follow.+ pub clip: RectF,+ pub opacity: f32,+ /// Which render layer to composite after: drawn between that layer's+ /// base-fill sub-buffer and its glyph sub-buffers, so card pictures sit+ /// above their card's background and below every label. Settled frames+ /// use layer 0; a closing ghost's fading pictures use the fade layer.+ pub zindex: i8,}fn preview_quad_key(preview: &TerminalPreviewRequest,dimensions: &Dimensions,shape_generation: usize,+ scale: f64,) -> PreviewQuadKey {PreviewQuadKey {snapshot: Arc::as_ptr(&preview.snapshot) as usize,@@ -134,7 +177,7 @@ fn preview_quad_key(// 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,+ scale_bits: scale.to_bits(),// Quad positions are relative to the centre of the window.pixel_width: dimensions.pixel_width,pixel_height: dimensions.pixel_height,@@ -289,10 +332,8 @@ mod terminal_preview_tests {fn preview_scale_can_shrink_below_the_old_twelve_percent_floor() {let minimum = minimum_terminal_preview_scale(14.0, 144, 1.0);assert!(minimum < 0.12);- assert_eq!(- quantize_terminal_preview_scale_down(0.08, minimum),- 0.078125- );+ // 0.08 rounds down to the next 1/16 bucket, still below the old floor.+ assert_eq!(quantize_terminal_preview_scale_down(0.08, minimum), 0.0625);assert_eq!(quantize_terminal_preview_scale_down(0.001, minimum),minimum@@ -839,6 +880,7 @@ impl crate::TermWindow {// The departing picture has finished leaving; nothing else refers// to it, and an arriving one is now simply the foreground.self.content_view_last_frame = None;+ self.content_view_last_composites.borrow_mut().clear();if let Some(view) = self.active_content_view_mut() {view.set_terminal_in_flight(None);}@@ -1095,6 +1137,7 @@ impl crate::TermWindow {// window chrome it owns. Fading them separately -- or holding some of// them back -- is what makes an arrival look like several things// happening near each other rather than one thing happening.+ let composites_before = self.card_composites.borrow().len();let mut heap = HeapQuadAllocator::default();{let mut recorded = TripleLayerQuadAllocator::Heap(&mut heap);@@ -1106,12 +1149,27 @@ impl crate::TermWindow {}match self.content_view_fade_opacity(Instant::now()) {// Arriving: the terminal is underneath this frame, so the view has- // to be lifted clear of it.- Some(opacity) => self.composite_above_terminal(&heap, opacity)?,+ // to be lifted clear of it. Card textures are not in the heap;+ // lift their composites to the fade layer at the fade's opacity+ // so the pictures arrive as part of the view.+ Some(opacity) => {+ {+ let mut composites = self.card_composites.borrow_mut();+ for composite in composites[composites_before..].iter_mut() {+ composite.zindex = crate::termwindow::CONTENT_VIEW_FADE_ZINDEX;+ composite.opacity *= opacity;+ }+ }+ self.composite_above_terminal(&heap, opacity)?+ }// Settled: nothing else is on screen to be ordered against.None => heap.apply_to_clipped(layers, self.surface_clip(), 1.0)?,}self.content_view_last_frame = Some(heap);+ // The heap holds no thumbnail quads on the texture path, so a closing+ // ghost needs this frame's composites to fade the pictures out.+ *self.content_view_last_composites.borrow_mut() =+ self.card_composites.borrow()[composites_before..].to_vec();Ok(())}@@ -1132,7 +1190,19 @@ impl crate::TermWindow {.layer_for_zindex(crate::termwindow::CONTENT_VIEW_FADE_ZINDEX).context("departing content view layer")?;let mut layers = layer.quad_allocator();- ghost.apply_to_clipped(&mut layers, self.surface_clip(), opacity)+ ghost.apply_to_clipped(&mut layers, self.surface_clip(), opacity)?;+ // Card pictures live in textures, not in the ghost heap: fade them+ // with it. NOTE: these draw after the base fills of the main layer,+ // i.e. underneath the travelling ghost chrome above them.+ let mut composites = self.card_composites.borrow_mut();+ for saved in self.content_view_last_composites.borrow().iter() {+ composites.push(CardComposite {+ opacity,+ zindex: crate::termwindow::CONTENT_VIEW_FADE_ZINDEX,+ ..saved.clone()+ });+ }+ Ok(())}pub fn paint_content_view(@@ -1340,7 +1410,12 @@ impl crate::TermWindow {preview: &TerminalPreviewRequest,budget: &mut usize,) -> anyhow::Result<bool> {- let key = preview_quad_key(preview, &self.dimensions, self.shape_generation);+ let key = preview_quad_key(+ preview,+ &self.dimensions,+ self.shape_generation,+ self.preview_scale_estimate(preview),+ );let clip = quad_clip_rect(preview.clip, &self.dimensions);// A hit replays. A miss replays too -- but only when the miss is the@@ -1370,6 +1445,11 @@ impl crate::TermWindow {self.update_next_frame_time(Some(Instant::now()));}if let Some(recorded_area) = recorded_area {+ // Texture path: the card's picture already lives in its own+ // texture; a single textured quad replaces the whole replay.+ if self.card_texture_path_active() && self.composite_cached_card(preview)? {+ return Ok(false);+ }let cache = self.preview_quad_cache.borrow();let cached = cache.get(&preview.tab_id)@@ -1399,12 +1479,14 @@ impl crate::TermWindow {// 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+ let (mut heap, prior_texture) = match self.preview_quad_cache.borrow_mut().remove(&preview.tab_id)- .map(|cached| cached.heap)- .unwrap_or_default();+ {+ Some(cached) => (cached.heap, cached.texture),+ None => (HeapQuadAllocator::default(), None),+ };heap.recycle();{let card_started = crate::perf::now();@@ -1412,7 +1494,46 @@ impl crate::TermWindow {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);+ let mut texture = None;+ let result = if self.card_texture_path_active() {+ // Reuse the previous texture when the card size is unchanged --+ // content changes every refresh interval and reallocating a+ // texture for each one would churn.+ let wanted_w = (preview.area.size.width.ceil() as u32).max(1);+ let wanted_h = (preview.area.size.height.ceil() as u32).max(1);+ let tex = match prior_texture+ .filter(|t| t.width == wanted_w && t.height == wanted_h)+ {+ Some(prior) => Ok(prior),+ None => self.create_card_texture(preview.area),+ };+ match tex {+ Ok(tex) => {+ let mut verts = Vec::new();+ heap.extract_vertices(&mut verts);+ self.pending_card_renders.borrow_mut().push(PendingCardRender {+ texture: Rc::clone(&tex),+ verts,+ area: preview.area,+ });+ self.card_composites.borrow_mut().push(CardComposite {+ texture: Rc::clone(&tex),+ dest: preview.area,+ clip: preview.clip,+ opacity: 1.0,+ zindex: 0,+ });+ texture = Some(tex);+ Ok(true)+ }+ Err(err) => {+ log::warn!("card texture unavailable, replaying quads: {err:#}");+ heap.apply_to_clipped(layers, clip, 1.0).map(|()| true)+ }+ }+ } else {+ heap.apply_to_clipped(layers, clip, 1.0).map(|()| true)+ };self.preview_quad_cache.borrow_mut().insert(preview.tab_id,CachedPreviewQuads {@@ -1422,11 +1543,89 @@ impl crate::TermWindow {snapshot: Arc::clone(&preview.snapshot),area: preview.area,heap,+ texture,},);result}+ /// True while cards may draw as textures (WebGpu only). Transition+ /// frames also qualify: the card quads are not recorded into the fade+ /// heap; instead `paint_content_view_composited` lifts the composites to+ /// the fade layer and gives them the fade's opacity, so the pictures+ /// arrive and leave with the view while transition frames stay cheap.+ fn card_texture_path_active(&self) -> bool {+ self.webgpu.is_some()+ }++ fn create_card_texture(+ &self,+ area: RectF,+ ) -> anyhow::Result<Rc<crate::termwindow::webgpu::CardRenderTexture>> {+ let webgpu = self+ .webgpu+ .as_ref()+ .ok_or_else(|| anyhow::anyhow!("no webgpu state"))?;+ let width = (area.size.width.ceil() as u32).max(1);+ let height = (area.size.height.ceil() as u32).max(1);+ Ok(Rc::new(crate::termwindow::webgpu::CardRenderTexture::new(+ width, height, webgpu,+ )?))+ }++ /// Composite a cached card as one textured quad, first rendering the+ /// cached heap into a fresh texture if the entry does not have one yet+ /// (recorded during a transition, when the texture path is off). Returns+ /// false when there is nothing usable and the caller must replay quads.+ fn composite_cached_card(&self, preview: &TerminalPreviewRequest) -> anyhow::Result<bool> {+ let (needs_texture, recorded_area) = {+ let cache = self.preview_quad_cache.borrow();+ let Some(cached) = cache.get(&preview.tab_id) else {+ return Ok(false);+ };+ (cached.texture.is_none(), cached.area)+ };+ if needs_texture {+ let texture = match self.create_card_texture(recorded_area) {+ Ok(texture) => texture,+ Err(err) => {+ log::warn!("card texture unavailable, replaying quads: {err:#}");+ return Ok(false);+ }+ };+ let mut verts = Vec::new();+ {+ let mut cache = self.preview_quad_cache.borrow_mut();+ let Some(cached) = cache.get_mut(&preview.tab_id) else {+ return Ok(false);+ };+ cached.heap.extract_vertices(&mut verts);+ cached.texture = Some(Rc::clone(&texture));+ }+ self.pending_card_renders.borrow_mut().push(PendingCardRender {+ texture,+ verts,+ area: recorded_area,+ });+ }+ let Some(texture) = self+ .preview_quad_cache+ .borrow()+ .get(&preview.tab_id)+ .and_then(|cached| cached.texture.clone())+ else {+ return Ok(false);+ };+ self.card_composites.borrow_mut().push(CardComposite {+ texture,+ dest: preview.area,+ clip: preview.clip,+ opacity: 1.0,+ zindex: 0,+ });+ Ok(true)+ }+/// Build one card's thumbnail into `layers`, whole.////// Everything here is laid out against `preview.area` -- the card's full@@ -1435,6 +1634,51 @@ impl crate::TermWindow {/// 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.+ /// The scale a card's grid will be rendered at, before raster-metric+ /// correction: a pure function of the card's bucketed size, the+ /// terminal's shape and the drag-time hold. Cheap -- no font metrics --+ /// so the quad-cache key can carry the resolved value instead of the+ /// hold *flag*: a drag whose hold resolves to the scale already on+ /// screen then reads as the same geometry, where the flag flipping used+ /// to rebuild every card at gesture start and end.+ fn preview_scale_estimate(&self, preview: &TerminalPreviewRequest) -> f64 {+ let tab_size = preview.snapshot.tab_size;+ if tab_size.cols == 0 || tab_size.rows == 0 {+ return 1.0;+ }+ let bucketed_width =+ quantized_terminal_preview_extent(preview.area.size.width, self.dimensions.dpi);+ let bucketed_height =+ quantized_terminal_preview_extent(preview.area.size.height, self.dimensions.dpi);+ let width_ratio = bucketed_width+ / (tab_size.cols as f32 * self.render_metrics.cell_size.width.max(1) as f32);+ let height_ratio = bucketed_height+ / (tab_size.rows as f32 * self.render_metrics.cell_size.height.max(1) as f32);+ let global_scale = self.fonts.get_font_scale();+ let minimum_scale = minimum_terminal_preview_scale(+ self.config.font_size,+ self.dimensions.dpi,+ global_scale,+ );+ let maximum_scale = (global_scale * 0.84).max(minimum_scale);+ let desired_scale = (global_scale * f64::from(width_ratio.min(height_ratio)))+ .clamp(minimum_scale, maximum_scale);+ let mut quantized_scale = quantize_terminal_preview_scale_down(desired_scale, minimum_scale);+ // Mid-drag, keep the scale this grid was last drawn at. The search+ // in the render path would otherwise walk a new bucket every few+ // pixels of card width, and every bucket is a `FontConfiguration`.+ if preview.hold_scale {+ if let Some(held) = self+ .preview_scale_hold+ .borrow()+ .get(&(tab_size.cols, tab_size.rows))+ {+ quantized_scale = *held;+ }+ }+ quantized_scale+ }+fn paint_terminal_preview_unclipped(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,@@ -1468,31 +1712,17 @@ impl crate::TermWindow {quantized_terminal_preview_extent(preview.area.size.width, self.dimensions.dpi);let bucketed_height =quantized_terminal_preview_extent(preview.area.size.height, self.dimensions.dpi);- let width_ratio = bucketed_width- / (tab_size.cols as f32 * self.render_metrics.cell_size.width.max(1) as f32);- let height_ratio = bucketed_height- / (tab_size.rows as f32 * self.render_metrics.cell_size.height.max(1) as f32);let global_scale = self.fonts.get_font_scale();let minimum_scale = minimum_terminal_preview_scale(self.config.font_size,self.dimensions.dpi,global_scale,);- let maximum_scale = (global_scale * 0.84).max(minimum_scale);- let desired_scale = (global_scale * f64::from(width_ratio.min(height_ratio)))- .clamp(minimum_scale, maximum_scale);- let mut quantized_scale =- quantize_terminal_preview_scale_down(desired_scale, minimum_scale);- // Mid-drag, keep the scale this grid was last drawn at. The search- // below would otherwise walk a new bucket every few pixels of card- // width, and every bucket is a `FontConfiguration` that builds a font,- // rasterises glyphs and grows the atlas -- and is never evicted.+ // Shared with the quad-cache key: both must resolve the drag-time+ // hold the same way, or a gesture's start and end read as geometry+ // changes and rebuild every card in one frame.+ let mut quantized_scale = self.preview_scale_estimate(preview);let scale_key = (tab_size.cols, tab_size.rows);- if preview.hold_scale {- if let Some(held) = self.preview_scale_hold.borrow().get(&scale_key) {- quantized_scale = *held;- }- }let (mut font_config, mut metrics) = self.pane_font_resources(quantized_scale)?;// Font raster metrics are integer pixels and therefore do not scale@@ -2406,6 +2636,9 @@ impl crate::TermWindow {let frame_now = Instant::now();self.advance_workspace_space_swipe_push(frame_now);self.advance_content_view_fade(frame_now);+ // Card texture work is queued per pass; a retried pass re-queues it.+ self.pending_card_renders.borrow_mut().clear();+ self.card_composites.borrow_mut().clear();{let gl_state = self.render_state.as_ref().unwrap();for layer in gl_state.layers.borrow().iter() {@@ -2932,8 +3165,8 @@ mod tests {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)+ preview_quad_key(&preview, &test_dimensions(), 3, 1.0),+ preview_quad_key(&preview, &test_dimensions(), 3, 1.0));}@@ -2942,9 +3175,9 @@ mod tests {#[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);+ let key = preview_quad_key(&moved, &test_dimensions(), 3, 1.0);moved.area = moved.area.translate(euclid::vec2(0.0, -140.0));- assert_eq!(preview_quad_key(&moved, &test_dimensions(), 3), key);+ assert_eq!(preview_quad_key(&moved, &test_dimensions(), 3, 1.0), key);}/// Resizing a card rebuckets the font scale, so the recorded quads are the@@ -2955,8 +3188,8 @@ mod tests {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)+ preview_quad_key(&large, &test_dimensions(), 3, 1.0),+ preview_quad_key(&small, &test_dimensions(), 3, 1.0));}@@ -2966,8 +3199,8 @@ mod tests {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)+ preview_quad_key(&preview, &test_dimensions(), 4, 1.0),+ preview_quad_key(&preview, &test_dimensions(), 3, 1.0));}@@ -2986,16 +3219,16 @@ mod tests {let mut recaptured = first.clone();recaptured.snapshot = Arc::new((*first.snapshot).clone());- let old = preview_quad_key(&first, &test_dimensions(), 3);+ let old = preview_quad_key(&first, &test_dimensions(), 3, 1.0);- let new_content = preview_quad_key(&recaptured, &test_dimensions(), 3);+ let new_content = preview_quad_key(&recaptured, &test_dimensions(), 3, 1.0);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);+ let new_font = preview_quad_key(&first, &test_dimensions(), 4, 1.0);assert_ne!(new_font, old, "a loaded font must eventually be rebuilt");assert_eq!(new_font.geometry, old.geometry,@@ -3005,7 +3238,7 @@ mod tests {let mut resized = first.clone();resized.area.size.width = 480.0;assert_ne!(- preview_quad_key(&resized, &test_dimensions(), 3).geometry,+ preview_quad_key(&resized, &test_dimensions(), 3, 1.0).geometry,old.geometry,"a resized card must not be replayed, at any budget");@@ -3013,7 +3246,7 @@ mod tests {let mut wider = test_dimensions();wider.pixel_width += 200;assert_ne!(- preview_quad_key(&first, &wider, 3).geometry,+ preview_quad_key(&first, &wider, 3, 1.0).geometry,old.geometry,"a resized window must not be replayed, at any budget");@@ -3027,8 +3260,8 @@ mod tests {let mut wider = test_dimensions();wider.pixel_width += 200;assert_ne!(- preview_quad_key(&preview, &wider, 3),- preview_quad_key(&preview, &test_dimensions(), 3)+ preview_quad_key(&preview, &wider, 3, 1.0),+ preview_quad_key(&preview, &test_dimensions(), 3, 1.0));}@@ -3040,8 +3273,8 @@ mod tests {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)+ preview_quad_key(&recaptured, &test_dimensions(), 3, 1.0),+ preview_quad_key(&first, &test_dimensions(), 3, 1.0));}diff --git a/wezterm-gui/src/termwindow/webgpu.rs b/wezterm-gui/src/termwindow/webgpu.rsindex a8d4ea8f..2a216e97 100644--- a/wezterm-gui/src/termwindow/webgpu.rs+++ b/wezterm-gui/src/termwindow/webgpu.rs@@ -212,6 +212,77 @@ impl Drop for WebGpuTexture {}}+/// An overview card's private render target. The card's quads are rendered+/// into this once per content change; every other frame composites it as a+/// single textured quad, instead of re-emitting and re-uploading the card's+/// thousands of glyph quads.+pub struct CardRenderTexture {+ pub texture: wgpu::Texture,+ pub view: wgpu::TextureView,+ /// Card texture + linear sampler, bindable in either of the pipeline's+ /// two texture slots (their layouts are identical).+ pub bind_group: wgpu::BindGroup,+ pub width: u32,+ pub height: u32,+}++impl CardRenderTexture {+ pub fn new(width: u32, height: u32, state: &WebGpuState) -> anyhow::Result<Self> {+ let limit = state.device.limits().max_texture_dimension_2d;+ if width > limit || height > limit {+ anyhow::bail!(+ "card texture dimensions {width}x{height} exceed the \+ max dimension {limit} supported by your GPU"+ );+ }+ // Same format as the surface so the shared render pipeline can+ // target it.+ let format = state.config.borrow().format;+ let texture = state.device.create_texture(&wgpu::TextureDescriptor {+ size: wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: if crate::framedump::enabled() {+ wgpu::TextureUsages::RENDER_ATTACHMENT+ | wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::COPY_SRC+ } else {+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING+ },+ label: Some("Card Texture"),+ view_formats: &[],+ });+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ let bind_group = state.device.create_bind_group(&wgpu::BindGroupDescriptor {+ layout: &state.texture_bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(&view),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::Sampler(&state.texture_linear_sampler),+ },+ ],+ label: Some("card texture bind group"),+ });+ Ok(Self {+ texture,+ view,+ bind_group,+ width,+ height,+ })+ }+}+pub fn adapter_info_to_gpu_info(info: wgpu::AdapterInfo) -> GpuInfo {GpuInfo {name: info.name,