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
Add content-view transitions and preview optimizations
RoversXb85de09a4bff
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex 16ef8a4d..1251f59a 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};use std::fs;use std::io;use std::path::PathBuf;-use std::sync::OnceLock;+use std::sync::{Arc, OnceLock};use window::{Appearance, Connection, ConnectionOps};// One point is one logical pixel on macOS but 4/3 px at 96dpi, so the@@ -456,10 +456,10 @@ pub(crate) fn settings_path() -> PathBuf {.join("settings.json")}-static SETTINGS_CACHE: OnceLock<Mutex<ThinkTermNativeSettings>> = OnceLock::new();+static SETTINGS_CACHE: OnceLock<Mutex<Arc<ThinkTermNativeSettings>>> = OnceLock::new();-fn settings_cache() -> &'static Mutex<ThinkTermNativeSettings> {- SETTINGS_CACHE.get_or_init(|| Mutex::new(load_from_disk()))+fn settings_cache() -> &'static Mutex<Arc<ThinkTermNativeSettings>> {+ SETTINGS_CACHE.get_or_init(|| Mutex::new(Arc::new(load_from_disk())))}fn load_from_disk() -> ThinkTermNativeSettings {@@ -487,7 +487,17 @@ fn load_from_disk() -> ThinkTermNativeSettings {}pub(crate) fn load() -> ThinkTermNativeSettings {- settings_cache().lock().clone()+ (**settings_cache().lock()).clone()+}++/// A shared handle to the settings, for callers that only read them.+///+/// [`load`] hands out a private copy, which is what a caller wanting to edit+/// and `save` needs. The paint path wants nothing of the sort and was taking+/// several copies a frame -- a lock and a deep clone each time, of a value+/// nobody was going to touch.+pub(crate) fn load_shared() -> Arc<ThinkTermNativeSettings> {+ Arc::clone(&settings_cache().lock())}pub(crate) fn should_show_onboarding(settings: &ThinkTermNativeSettings) -> bool {@@ -496,7 +506,7 @@ pub(crate) fn should_show_onboarding(settings: &ThinkTermNativeSettings) -> boolpub(crate) fn reload_from_disk() -> ThinkTermNativeSettings {let settings = load_from_disk();- *settings_cache().lock() = settings.clone();+ *settings_cache().lock() = Arc::new(settings.clone());settings}@@ -509,7 +519,7 @@ pub(crate) fn save(settings: &ThinkTermNativeSettings) -> anyhow::Result<()> {let tmp = path.with_extension("json.tmp");fs::write(&tmp, data)?;fs::rename(tmp, path)?;- *settings_cache().lock() = settings.clone();+ *settings_cache().lock() = Arc::new(settings.clone());Ok(())}diff --git a/wezterm-gui/src/quad.rs b/wezterm-gui/src/quad.rsindex 1aa622fc..d8ec3d0d 100644--- a/wezterm-gui/src/quad.rs+++ b/wezterm-gui/src/quad.rs@@ -126,14 +126,73 @@ pub trait QuadTrait {pub enum QuadImpl<'a> {Vert(Quad<'a>),Boxed(&'a mut BoxedQuad),+ TransformedBoxed(&'a mut BoxedQuad, QuadPositionTransform),Tee(Quad<'a>, &'a mut BoxedQuad),}+/// Maps quad positions from a naturally rendered source rect into an exact+/// destination rect while the quad is being authored. Live thumbnails use+/// this instead of walking every glyph a second time after paint.+#[derive(Clone, Copy, Debug)]+pub struct QuadPositionTransform {+ scale_x: f32,+ scale_y: f32,+ offset_x: f32,+ offset_y: f32,+}++impl QuadPositionTransform {+ fn new(source: QuadClipRect, target: QuadClipRect) -> Option<Self> {+ let source_width = source.width();+ let source_height = source.bottom() - source.top();+ let target_width = target.width();+ let target_height = target.bottom() - target.top();+ if !(source_width > 0.0+ && source_height > 0.0+ && target_width > 0.0+ && target_height > 0.0)+ {+ return None;+ }+ let scale_x = target_width / source_width;+ let scale_y = target_height / source_height;+ let offset_x = target.left() - source.left() * scale_x;+ let offset_y = target.top() - source.top() * scale_y;+ (scale_x.is_finite()+ && scale_y.is_finite()+ && offset_x.is_finite()+ && offset_y.is_finite())+ .then_some(Self {+ scale_x,+ scale_y,+ offset_x,+ offset_y,+ })+ }++ fn map_position(+ self,+ left: f32,+ top: f32,+ right: f32,+ bottom: f32,+ ) -> (f32, f32, f32, f32) {+ (+ left * self.scale_x + self.offset_x,+ top * self.scale_y + self.offset_y,+ right * self.scale_x + self.offset_x,+ bottom * self.scale_y + self.offset_y,+ )+ }+}+impl<'a> QuadTrait for QuadImpl<'a> {fn set_texture_discrete(&mut self, x1: f32, x2: f32, y1: f32, y2: f32) {match self {Self::Vert(q) => q.set_texture_discrete(x1, x2, y1, y2),- Self::Boxed(q) => q.set_texture_discrete(x1, x2, y1, y2),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => {+ q.set_texture_discrete(x1, x2, y1, y2)+ }Self::Tee(gpu, heap) => {gpu.set_texture_discrete(x1, x2, y1, y2);heap.set_texture_discrete(x1, x2, y1, y2);@@ -144,7 +203,7 @@ impl<'a> QuadTrait for QuadImpl<'a> {fn set_has_color_impl(&mut self, has_color: f32) {match self {Self::Vert(q) => q.set_has_color_impl(has_color),- Self::Boxed(q) => q.set_has_color_impl(has_color),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_has_color_impl(has_color),Self::Tee(gpu, heap) => {gpu.set_has_color_impl(has_color);heap.set_has_color_impl(has_color);@@ -155,7 +214,7 @@ impl<'a> QuadTrait for QuadImpl<'a> {fn set_fg_color(&mut self, color: LinearRgba) {match self {Self::Vert(q) => q.set_fg_color(color),- Self::Boxed(q) => q.set_fg_color(color),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_fg_color(color),Self::Tee(gpu, heap) => {gpu.set_fg_color(color);heap.set_fg_color(color);@@ -172,7 +231,9 @@ impl<'a> QuadTrait for QuadImpl<'a> {) {match self {Self::Vert(q) => q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right),- Self::Boxed(q) => q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => {+ q.set_corner_gradient(top_left, top_right, bottom_left, bottom_right)+ }Self::Tee(gpu, heap) => {gpu.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);heap.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);@@ -183,7 +244,7 @@ impl<'a> QuadTrait for QuadImpl<'a> {fn set_vertical_gradient(&mut self, top: LinearRgba, bottom: LinearRgba) {match self {Self::Vert(q) => q.set_vertical_gradient(top, bottom),- Self::Boxed(q) => q.set_vertical_gradient(top, bottom),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_vertical_gradient(top, bottom),Self::Tee(gpu, heap) => {gpu.set_vertical_gradient(top, bottom);heap.set_vertical_gradient(top, bottom);@@ -194,7 +255,9 @@ impl<'a> QuadTrait for QuadImpl<'a> {fn set_alt_color_and_mix_value(&mut self, color: LinearRgba, mix_value: f32) {match self {Self::Vert(q) => q.set_alt_color_and_mix_value(color, mix_value),- Self::Boxed(q) => q.set_alt_color_and_mix_value(color, mix_value),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => {+ q.set_alt_color_and_mix_value(color, mix_value)+ }Self::Tee(gpu, heap) => {gpu.set_alt_color_and_mix_value(color, mix_value);heap.set_alt_color_and_mix_value(color, mix_value);@@ -205,7 +268,7 @@ impl<'a> QuadTrait for QuadImpl<'a> {fn set_hsv(&mut self, hsv: Option<HsbTransform>) {match self {Self::Vert(q) => q.set_hsv(hsv),- Self::Boxed(q) => q.set_hsv(hsv),+ Self::Boxed(q) | Self::TransformedBoxed(q, _) => q.set_hsv(hsv),Self::Tee(gpu, heap) => {gpu.set_hsv(hsv);heap.set_hsv(hsv);@@ -217,6 +280,11 @@ impl<'a> QuadTrait for QuadImpl<'a> {match self {Self::Vert(q) => q.set_position(left, top, right, bottom),Self::Boxed(q) => q.set_position(left, top, right, bottom),+ Self::TransformedBoxed(q, transform) => {+ let (left, top, right, bottom) =+ transform.map_position(left, top, right, bottom);+ q.set_position(left, top, right, bottom);+ }Self::Tee(gpu, heap) => {gpu.set_position(left, top, right, bottom);heap.set_position(left, top, right, bottom);@@ -434,6 +502,25 @@ impl BoxedQuad {vert}+ /// Scale every colour's alpha, for compositing a recorded surface at+ /// partial opacity.+ ///+ /// Every shader branch multiplies by this, so a whole recorded surface --+ /// fills, gradients, UI text, terminal glyphs, colour emoji -- fades as+ /// one picture. `IS_GLYPH` and `IS_COLOR_EMOJI` used to take their alpha+ /// from the glyph texture alone and drop the vertex colour's, which left+ /// terminal text standing solid over everything else as it faded.+ fn with_opacity(mut self, opacity: f32) -> Self {+ self.fg_color[3] *= opacity;+ self.alt_color[3] *= opacity;+ if let Some(corners) = self.fg_color_corners.as_deref_mut() {+ for corner in corners.iter_mut() {+ corner[3] *= opacity;+ }+ }+ self+ }+/// Translate this quad and crop it to `clip`, preserving texture/// coordinates and per-corner colors for the visible portion.fn translated_clipped(&self, offset_x: f32, offset_y: f32, clip: QuadClipRect) -> Option<Self> {@@ -442,26 +529,65 @@ impl BoxedQuad {let translated_top = top + offset_y;let translated_right = right + offset_x;let translated_bottom = bottom + offset_y;- if !(translated_right > translated_left- && translated_bottom > translated_top+ self.positioned_clipped(+ translated_left,+ translated_top,+ translated_right,+ translated_bottom,+ clip,+ )+ }++ /// Scale and offset this quad into a destination rect, then crop it.+ ///+ /// Unlike [`TripleLayerQuadAllocator::set_heap_position_transform`], which+ /// maps positions as a surface is being authored, this remaps a surface+ /// that was already recorded. That is what lets one captured frame be+ /// replayed at a different size on every frame of a transition instead of+ /// the whole window being painted again each time -- at the cost of the+ /// glyph textures being sampled below their rasterised size, so the text+ /// softens as it shrinks.+ fn transformed_clipped(+ &self,+ transform: QuadPositionTransform,+ clip: QuadClipRect,+ ) -> Option<Self> {+ let (left, top, right, bottom) = self.position;+ let (left, top, right, bottom) = transform.map_position(left, top, right, bottom);+ self.positioned_clipped(left, top, right, bottom, clip)+ }++ /// Crop this quad after its four position edges have already been mapped.+ /// Keeping the mapping outside avoids cloning an intermediate quad for the+ /// scaled-preview path, which touches thousands of tiny glyph quads.+ fn positioned_clipped(+ &self,+ left: f32,+ top: f32,+ right: f32,+ bottom: f32,+ clip: QuadClipRect,+ ) -> Option<Self> {+ if !(right > left+ && bottom > top&& clip.right() > clip.left()&& clip.bottom() > clip.top()){return None;}- let visible_left = translated_left.max(clip.left());- let visible_top = translated_top.max(clip.top());- let visible_right = translated_right.min(clip.right());- let visible_bottom = translated_bottom.min(clip.bottom());+ let visible_left = left.max(clip.left());+ let visible_top = top.max(clip.top());+ let visible_right = right.min(clip.right());+ let visible_bottom = bottom.min(clip.bottom());if visible_right <= visible_left || visible_bottom <= visible_top {return None;}- let x0 = (visible_left - translated_left) / (translated_right - translated_left);- let x1 = (visible_right - translated_left) / (translated_right - translated_left);- let y0 = (visible_top - translated_top) / (translated_bottom - translated_top);- let y1 = (visible_bottom - translated_top) / (translated_bottom - translated_top);+ let x0 = (visible_left - left) / (right - left);+ let x1 = (visible_right - left) / (right - left);+ let y0 = (visible_top - top) / (bottom - top);+ let y1 = (visible_bottom - top) / (bottom - top);let (u0, u1, v0, v1) = self.tex;let source_colors = self.fg_color_corners@@ -508,6 +634,7 @@ impl BoxedQuad {}Some(clipped)}+}fn lerp(start: f32, end: f32, amount: f32) -> f32 {@@ -529,8 +656,20 @@ pub struct HeapQuadAllocator {layer0: Vec<Box<BoxedQuad>>,layer1: Vec<Box<BoxedQuad>>,layer2: Vec<Box<BoxedQuad>>,+ /// Boxes handed back by [`HeapQuadAllocator::recycle`], waiting to be+ /// filled again. Quads are boxed so their addresses survive the vector+ /// growing, which means one allocation each -- fine for a surface recorded+ /// once, ruinous for the overview, which builds a fresh allocator per card+ /// per frame and drops every box at the end of it.+ spare: Vec<Box<BoxedQuad>>,+ position_transform: Option<QuadPositionTransform>,}+/// Ceiling on the recycling pool. A pool the size of the largest single+/// surface is the whole point; one the size of the largest surface ever+/// painted, held forever, is a leak wearing a cache's clothes.+const MAX_SPARE_QUADS: usize = 65_536;+impl std::fmt::Debug for HeapQuadAllocator {fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {fmt.debug_struct("HeapQuadAllocator").finish()@@ -640,6 +779,23 @@ pub struct HeapQuadMark {}impl HeapQuadAllocator {+ /// Empty the allocator but keep its boxes for whatever is recorded next.+ ///+ /// For a caller that records many surfaces in a row -- the overview draws+ /// one per visible card, every frame -- this turns a quad's allocation into+ /// a `Vec::pop`. Dropping the allocator instead frees every box, and the+ /// next card immediately allocates them all back.+ pub fn recycle(&mut self) {+ for layer in [&mut self.layer0, &mut self.layer1, &mut self.layer2] {+ if self.spare.len() + layer.len() <= MAX_SPARE_QUADS {+ self.spare.append(layer);+ } else {+ layer.clear();+ }+ }+ self.position_transform = None;+ }+/// Where the next quad will land, for later use with [`Self::apply_before`],/// [`Self::apply_between`] and [`Self::apply_after`].pub fn mark(&self) -> HeapQuadMark {@@ -674,13 +830,18 @@ impl HeapQuadAllocator {Ok(())}- /// Copy every recorded quad into `other`, cropped to `clip`.+ /// Copy every recorded quad into `other`, cropped to `clip` and scaled to+ /// `opacity`./// Position, texture coordinates and per-corner colors are transformed/// together by the same primitive used by Space swipe composition.+ ///+ /// See [`BoxedQuad::with_opacity`] for which quads an opacity below 1+ /// actually reaches.pub fn apply_to_clipped(&self,other: &mut TripleLayerQuadAllocator,clip: QuadClipRect,+ opacity: f32,) -> anyhow::Result<()> {let started = std::time::Instant::now();for (layer_num, quads) in self.layers() {@@ -688,6 +849,11 @@ impl HeapQuadAllocator {let Some(clipped) = quad.translated_clipped(0.0, 0.0, clip) else {continue;};+ let clipped = if opacity < 1.0 {+ clipped.with_opacity(opacity)+ } else {+ clipped+ };other.extend_with(layer_num, &clipped.to_vertices());}}@@ -695,6 +861,41 @@ impl HeapQuadAllocator {Ok(())}+ /// Replay this whole surface scaled into `target`, cropped to `clip` and+ /// composited at `opacity`.+ ///+ /// `source` is the rect the surface was recorded in; the two together give+ /// the scale and offset. Used to fly a captured window into the card it+ /// becomes.+ pub fn apply_to_scaled(+ &self,+ other: &mut TripleLayerQuadAllocator,+ source: QuadClipRect,+ target: QuadClipRect,+ clip: QuadClipRect,+ opacity: f32,+ ) -> anyhow::Result<()> {+ let started = std::time::Instant::now();+ let Some(transform) = QuadPositionTransform::new(source, target) else {+ return Ok(());+ };+ for (layer_num, quads) in self.layers() {+ for quad in quads {+ let Some(mapped) = quad.transformed_clipped(transform, clip) else {+ continue;+ };+ let mapped = if opacity < 1.0 {+ mapped.with_opacity(opacity)+ } else {+ mapped+ };+ other.extend_with(layer_num, &mapped.to_vertices());+ }+ }+ metrics::histogram!("quad_buffer_apply_scaled").record(started.elapsed());+ Ok(())+ }+/// Replay everything recorded before `mark`, in place.pub fn apply_before(&self,@@ -754,10 +955,22 @@ impl HeapQuadAllocator {metrics::histogram!("quad_buffer_translated_rect_clip_apply").record(started.elapsed());Ok(())}++ fn set_position_transform(&mut self, transform: Option<QuadPositionTransform>) {+ self.position_transform = transform;+ }}impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>> {+ let position_transform = self.position_transform;+ let fresh = match self.spare.pop() {+ Some(mut quad) => {+ *quad = BoxedQuad::default();+ quad+ }+ None => Box::new(BoxedQuad::default()),+ };let quads = match layer_num {0 => &mut self.layer0,1 => &mut self.layer1,@@ -765,10 +978,13 @@ impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {_ => unreachable!(),};- quads.push(Box::new(BoxedQuad::default()));+ quads.push(fresh);let quad = quads.last_mut().unwrap();- Ok(QuadImpl::Boxed(quad))+ Ok(match position_transform {+ Some(transform) => QuadImpl::TransformedBoxed(quad, transform),+ None => QuadImpl::Boxed(quad),+ })}fn extend_with(&mut self, layer_num: usize, vertices: &[Vertex]) {@@ -776,6 +992,7 @@ impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {return;}+ let position_transform = self.position_transform;let dest_quads = match layer_num {0 => &mut self.layer0,1 => &mut self.layer1,@@ -791,7 +1008,12 @@ impl TripleLayerQuadAllocatorTrait for HeapQuadAllocator {unsafe { std::slice::from_raw_parts(vertices.as_ptr().cast(), vertices.len() / 4) };for quad in src_quads {- dest_quads.push(Box::new(BoxedQuad::from_vertices(quad)));+ let mut quad = BoxedQuad::from_vertices(quad);+ if let Some(transform) = position_transform {+ let (left, top, right, bottom) = quad.position;+ quad.position = transform.map_position(left, top, right, bottom);+ }+ dest_quads.push(Box::new(quad));}}}@@ -816,6 +1038,29 @@ impl<'a> TripleLayerQuadAllocator<'a> {Self::Tee { heap, .. } => Some(heap.mark()),}}++ /// Map subsequently recorded quad positions while backed by a heap. GPU+ /// vertices are immutable once allocated, so preview callers deliberately+ /// record their complete surface before the final upload.+ pub fn set_heap_position_transform(+ &mut self,+ transform: Option<(QuadClipRect, QuadClipRect)>,+ ) -> bool {+ let Self::Heap(heap) = self else {+ return false;+ };+ let transform = match transform {+ Some((source, target)) => {+ let Some(transform) = QuadPositionTransform::new(source, target) else {+ return false;+ };+ Some(transform)+ }+ None => None,+ };+ heap.set_position_transform(transform);+ true+ }}impl<'a> TripleLayerQuadAllocatorTrait for TripleLayerQuadAllocator<'a> {@@ -937,6 +1182,30 @@ fn boxed_quad_translation_and_clip_crop_position_texture_and_gradient_together()assert_eq!(colors[V_BOT_RIGHT], [0.75, 0.75, 0.0, 1.0]);}+#[cfg(test)]+#[test]+fn heap_position_transform_maps_new_and_cached_quads_in_one_pass() {+ let source = QuadClipRect::from_top_left_pixels(0.0, 0.0, 100.0, 100.0, &TEST_ORIGIN);+ let target = QuadClipRect::from_top_left_pixels(10.0, 20.0, 210.0, 70.0, &TEST_ORIGIN);+ let mut heap = HeapQuadAllocator::default();+ {+ let mut layers = TripleLayerQuadAllocator::Heap(&mut heap);+ assert!(layers.set_heap_position_transform(Some((source, target))));++ let mut authored = layers.allocate(0).unwrap();+ authored.set_position(20.0, 10.0, 40.0, 50.0);+ drop(authored);++ let mut cached = BoxedQuad::default();+ cached.set_position(20.0, 10.0, 40.0, 50.0);+ layers.extend_with(1, &cached.to_vertices());+ assert!(layers.set_heap_position_transform(None));+ }++ assert_eq!(heap.layer0[0].position, (50.0, 25.0, 90.0, 45.0));+ assert_eq!(heap.layer1[0].position, (50.0, 25.0, 90.0, 45.0));+}+#[cfg(test)]#[test]fn boxed_quad_clip_rejects_outside_and_preserves_inside() {diff --git a/wezterm-gui/src/shader.wgsl b/wezterm-gui/src/shader.wgslindex 524b04da..5b72338c 100644--- a/wezterm-gui/src/shader.wgsl+++ b/wezterm-gui/src/shader.wgsl@@ -140,6 +140,34 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {var linear_tex: vec4<f32> = textureSample(atlas_linear_tex, atlas_linear_sampler, in.tex);var nearest_tex: vec4<f32> = textureSample(atlas_nearest_tex, atlas_nearest_sampler, in.tex);+ // How far this quad is minified, in atlas texels per screen pixel.+ //+ // Glyphs are rasterised at the size they are meant to be drawn and sampled+ // nearest, which is correct at 1:1 and is what keeps terminal text crisp.+ // A quad that is being shrunk -- a terminal travelling into an overview+ // card -- breaks that assumption: nearest minification samples one texel in+ // every N, so strokes drop out entirely and the text shimmers as the scale+ // passes through. Both samples are taken anyway and the two bind groups are+ // the same atlas texture, so blending toward the linear one costs a mix and+ // leaves everything drawn at its rasterised size untouched.+ //+ // Derivatives must be taken in uniform control flow, hence up here rather+ // than inside the branches below.+ let atlas_size = vec2<f32>(textureDimensions(atlas_nearest_tex));+ let footprint = max(+ length(dpdx(in.tex) * atlas_size),+ length(dpdy(in.tex) * atlas_size),+ );+ // Nearest until the quad is unambiguously being shrunk, then ramp to linear.+ //+ // The dead zone matters more than the ramp. A glyph drawn at the size it was+ // rasterised does not land on exactly one texel per pixel -- cell metrics are+ // integer device pixels and the projection carries float error -- so a+ // threshold at 1.0 leaks a few percent of linear into every character on+ // screen and softens the whole terminal. Nothing below 1.25 is minified+ // enough to be worth filtering.+ let minified = smoothstep(1.25, 2.0, footprint);+var hsv = in.hsv;if in.has_color == IS_SOLID_COLOR {@@ -152,16 +180,24 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {color.a *= in.fg_color.a;} else if in.has_color == IS_COLOR_EMOJI {// the texture is full color info (eg: color emoji glyph)- color = nearest_tex;+ color = mix(nearest_tex, linear_tex, minified);+ // The vertex alpha still applies, so that a surface being composited at+ // partial opacity carries its emoji with it.+ color.a *= in.fg_color.a;} else if in.has_color == IS_GRAY_SCALE {// Grayscale poly quad for non-aa text render layerscolor = in.fg_color;- color.a *= nearest_tex.a;+ color.a *= mix(nearest_tex.a, linear_tex.a, minified);} else if in.has_color == IS_GLYPH {// the texture is the alpha channel/color mask// and we need to tint with the fg_colorcolor = in.fg_color;- color.a = nearest_tex.a;+ // Multiply rather than replace: the glyph mask decides the shape, the+ // vertex colour decides how present the whole thing is. Replacing it+ // discarded any opacity the caller asked for, which meant terminal text+ // could not take part in a surface being composited at partial opacity --+ // it stayed solid over everything else as it faded.+ color.a = mix(nearest_tex.a, linear_tex.a, minified) * in.fg_color.a;hsv *= uniforms.foreground_text_hsb;}diff --git a/wezterm-gui/src/termwindow/content_view.rs b/wezterm-gui/src/termwindow/content_view.rsindex 9a6647df..1f019599 100644--- a/wezterm-gui/src/termwindow/content_view.rs+++ b/wezterm-gui/src/termwindow/content_view.rs@@ -8,18 +8,270 @@ use crate::termwindow::TermWindow;use crate::ui::{DrawContext, UiPalette};use mux::pane::PaneId;use mux::renderable::{RenderableDimensions, StableCursorPosition};-use mux::tab::PositionedSplit;+use mux::tab::{PositionedSplit, TabId};use std::path::PathBuf;use std::rc::Rc;use std::sync::Arc;-use std::time::Instant;+use std::time::{Duration, Instant};use wezterm_font::LoadedFont;use wezterm_term::color::ColorPalette;use wezterm_term::{KeyCode, KeyModifiers, Line, StableRowIndex, TerminalSize};-use window::{MouseEventKind as WMEK, RectF};+use window::{MouseEvent, MouseEventKind as WMEK, RectF};pub(crate) type ContentViewId = u64;+/// A full-window ContentView arriving or leaving, composited over the terminal+/// while it travels.+///+/// The terminal keeps being painted for the duration -- normally a foreground+/// ContentView suppresses it entirely -- so the two are on screen together and+/// the view can be faded against something rather than against nothing.+pub(crate) struct ContentViewFade {+ /// How present the view is: rising as it arrives, falling as it leaves.+ pub(crate) opacity: crate::ui::anim::Timeline,+ /// How far the terminal has travelled towards the place the view keeps for+ /// it: 0 is the whole window, 1 is that place. Separate from `opacity`+ /// because movement decelerates into its target while opacity does not.+ pub(crate) travel: crate::ui::anim::Timeline,+ /// The outgoing view's last painted frame.+ ///+ /// A closing view is torn down immediately: deferring that would mean+ /// keeping something alive that still answers to input and to the mux+ /// while it is on its way out. Keeping its final quads instead lets the+ /// picture leave without the view having to.+ pub(crate) ghost: Option<crate::quad::HeapQuadAllocator>,+ /// The terminal, recorded once, and where it is going.+ pub(crate) flight: Option<ContentViewFlight>,+ /// How far the window frame has moved off its own edges: 0 in place, 1+ /// fully gone. Separate from the terminal's travel so the two can be+ /// staggered -- the frame is meant to be seen leaving before the terminal+ /// starts crossing, and to come back after it has landed.+ pub(crate) chrome_travel: crate::ui::anim::Timeline,+ /// The window frame, recorded once, in the three pieces that leave in+ /// three different directions.+ pub(crate) chrome: Option<ContentViewChrome>,+ /// Destination captured before the view was torn down.+ ///+ /// A closing view cannot be asked where the terminal belongs -- it is+ /// already gone by the time the flight is resolved -- so a close records+ /// the answer while it still can.+ pub(crate) pending_destination: Option<RectF>,+ /// The travelling terminal dissolving into the card's own thumbnail of it,+ /// started once the two are close enough in size to overlap. `None` until+ /// then, and for the whole of a closing transition -- growing back out of+ /// a card, there is nothing on the far side to dissolve into.+ pub(crate) landing: Option<crate::ui::anim::Timeline>,+ /// When this transition began, in wall-clock time.+ ///+ /// Only used to bound how long input may be held; the animation itself is+ /// paced by the timelines above, which run on a deferred clock.+ pub(crate) started_at: Instant,+}++/// How long a running transition may hold input before it is assumed stuck.+///+/// The longest piece of the animation is 260ms, and its clock does not start+/// until a frame has been presented. This ceiling is well clear of that while+/// still bounded, because the fade is only ever cleared by painting: a window+/// that stops painting mid-transition -- occluded, or on a display that has+/// gone to sleep -- would otherwise hold input forever.+const TRANSITION_INPUT_HOLD: Duration = Duration::from_millis(1000);++/// Whether a transition that began `elapsed` ago still owns the keyboard and+/// the pointer.+///+/// While a transition runs, what is on screen is a recording: the terminal on+/// its way behind an arriving view, or a view's last frame on its way out.+/// Both look interactive and neither is.+pub(crate) fn transition_holds_input(elapsed: Duration) -> bool {+ elapsed < TRANSITION_INPUT_HOLD+}++#[cfg(test)]+mod flight_rect_tests {+ use super::*;++ fn source() -> RectF {+ euclid::rect(0.0, 40.0, 1600.0, 900.0)+ }++ fn destination() -> RectF {+ euclid::rect(300.0, 600.0, 400.0, 225.0)+ }++ #[test]+ fn the_journey_starts_where_the_terminal_was_recorded() {+ assert_eq!(flight_rect_at(source(), destination(), 0.0), source());+ }++ #[test]+ fn the_journey_ends_in_the_card() {+ assert_eq!(flight_rect_at(source(), destination(), 1.0), destination());+ }++ #[test]+ fn travel_is_clamped_at_both_ends() {+ assert_eq!(flight_rect_at(source(), destination(), -0.5), source());+ assert_eq!(flight_rect_at(source(), destination(), 4.0), destination());+ }++ #[test]+ fn halfway_is_halfway_on_every_edge() {+ let mid = flight_rect_at(source(), destination(), 0.5);+ assert_eq!(mid.min_x(), 150.0);+ assert_eq!(mid.min_y(), 320.0);+ assert_eq!(mid.size.width, 1000.0);+ assert_eq!(mid.size.height, 562.5);+ }++ #[test]+ fn the_dissolve_waits_until_the_sizes_nearly_match() {+ // Shrinking 1600 wide into a 400 wide card: every 1% of journey left+ // is 3% of oversize, so the bound is reached at travel 0.96.+ let (src, dst) = (source(), destination());+ assert!(!flight_is_landing(src, dst, 0.0));+ assert!(!flight_is_landing(src, dst, 0.95));+ assert!(flight_is_landing(src, dst, 0.96));+ assert!(flight_is_landing(src, dst, 1.0));+ }++ #[test]+ fn a_smaller_card_has_to_be_approached_more_closely() {+ // Same journey into a card half the size: the journey left that was+ // 12% of oversize is 28% of this one, so 0.96 is no longer close+ // enough. The window stays roughly the same length in time because+ // the travel eases out.+ let src = source();+ let small = euclid::rect(300.0, 600.0, 200.0, 112.5);+ assert!(!flight_is_landing(src, small, 0.96));+ assert!(flight_is_landing(src, small, 0.99));+ }++ #[test]+ fn a_card_that_moved_mid_flight_retargets_from_the_same_source() {+ // The overview reflowed underneath the terminal: same recording, new+ // landing rectangle. The arriving picture has to follow it rather than+ // finish at the old one and jump.+ let moved = euclid::rect(900.0, 100.0, 400.0, 225.0);+ assert_eq!(flight_rect_at(source(), moved, 1.0), moved);+ assert_eq!(flight_rect_at(source(), moved, 0.0), source());+ }+}++#[cfg(test)]+mod transition_input_tests {+ use super::*;++ #[test]+ fn input_is_held_for_the_length_of_the_animation() {+ // The travel is 260ms and its clock waits for a presented frame.+ assert!(transition_holds_input(Duration::ZERO));+ assert!(transition_holds_input(Duration::from_millis(260)));+ assert!(transition_holds_input(Duration::from_millis(500)));+ }++ #[test]+ fn a_transition_that_stopped_painting_gives_input_back() {+ assert!(!transition_holds_input(TRANSITION_INPUT_HOLD));+ assert!(!transition_holds_input(Duration::from_secs(30)));+ }+}++/// The window frame recorded per edge, because each piece leaves towards the+/// edge it is anchored to rather than all of them fading in place.+#[derive(Default)]+pub(crate) struct ContentViewChrome {+ pub(crate) left: crate::quad::HeapQuadAllocator,+ pub(crate) right: crate::quad::HeapQuadAllocator,+ pub(crate) top: crate::quad::HeapQuadAllocator,+}++/// The terminal as it looked when a transition began, travelling to the place+/// the arriving view keeps for it.+///+/// Recorded once rather than repainted per frame: the terminal is not+/// interactive during the transition, so there is nothing for a live repaint+/// to show that a still frame cannot. The cost is that its glyphs are sampled+/// below the size they were rasterised at, so the text softens as it shrinks+/// -- which is what a window pulling away from you looks like anyway.+pub(crate) struct ContentViewFlight {+ pub(crate) surface: crate::quad::HeapQuadAllocator,+ /// Where the terminal was when `surface` was recorded.+ ///+ /// Frozen rather than re-read each frame. These quads carry the positions+ /// they were authored at, so remapping them from anywhere but the geometry+ /// they were authored under scales and offsets them wrongly -- a window+ /// resized, or a sidebar toggled, mid-flight used to stretch the picture.+ pub(crate) source: RectF,+ /// Destination in window pixels. Equal to the whole window when the view+ /// has no place for this terminal, which turns the flight into a plain+ /// hold and leaves the transition to the fade alone.+ ///+ /// A fallback rather than the answer: an arriving view is asked again on+ /// every frame, because its layout keeps moving while the terminal is on+ /// its way there. This value is what a *departing* view left behind, and+ /// there is nobody left to ask.+ pub(crate) destination: RectF,+ /// Which terminal is travelling, so the arriving view can be re-asked+ /// where it now keeps a place for it.+ pub(crate) tab_id: Option<TabId>,+}++/// How much larger than its card the travelling terminal may still be when the+/// two are first allowed to overlap.+///+/// Loose, because the overlap itself is cheap: the eased opacity is still flat+/// at 1.0 for the first quarter of the dissolve, and by the time the recording+/// is visibly translucent the mismatch is already under 1%. What made the+/// earlier attempt read as two pictures was not the mismatch on its own but+/// the flat panel colour showing between them -- the card drew no thumbnail+/// while its terminal was in flight, so there was nothing to dissolve into.+/// With an aligned copy of the same picture underneath, a few percent of size+/// difference is not what the eye is looking at.+///+/// Tightening this is what made the first version invisible: 3% left about two+/// usable frames, which is a cut with extra steps.+const FLIGHT_LANDING_OVERSIZE: f32 = 0.12;++/// Whether the travelling terminal has closed to within touching distance of+/// the card it is landing in.+///+/// Measured in size, not in time and not in distance already covered. The+/// travel eases out, so a window written in either of those spends most of+/// itself at a size that does not match the card -- a threshold at "the last+/// tenth of the distance" is nearly half of the duration, which is exactly how+/// the previous attempt ended up translucent for seven frames at a size 3-18%+/// off. Bounding the mismatch instead makes the window short as a+/// *consequence*: 40-65ms across the range of card sizes, and self-correcting,+/// because a smaller card has to be approached more closely to reach the same+/// proportional error.+pub(crate) fn flight_is_landing(source: RectF, destination: RectF, travel: f32) -> bool {+ let rect = flight_rect_at(source, destination, travel);+ let mismatch = |reached: f32, target: f32| {+ if target <= 0.0 {+ f32::INFINITY+ } else {+ (reached - target).abs() / target+ }+ };+ mismatch(rect.size.width, destination.size.width)+ .max(mismatch(rect.size.height, destination.size.height))+ <= FLIGHT_LANDING_OVERSIZE+}++/// Where the travelling terminal sits at `travel`, between the rectangle it+/// was recorded in and the one it is heading for.+pub(crate) fn flight_rect_at(source: RectF, destination: RectF, travel: f32) -> RectF {+ let travel = travel.clamp(0.0, 1.0);+ let lerp = |from: f32, to: f32| from + (to - from) * travel;+ euclid::rect(+ lerp(source.min_x(), destination.min_x()),+ lerp(source.min_y(), destination.min_y()),+ lerp(source.size.width, destination.size.width),+ lerp(source.size.height, destination.size.height),+ )+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub(crate) enum ContentViewPresentation {#[default]@@ -57,6 +309,11 @@ pub(crate) struct TerminalPreviewPaneSnapshot {pub rows: usize,pub resolved_top: StableRowIndex,pub lines: Vec<Line>,+ /// Height of the pane's whole box, nav bar included. `dimensions` covers+ /// the grid alone, so the difference is what the real terminal reserves+ /// above the first row -- which a thumbnail has to reserve too, or it+ /// draws the same rows into a taller space.+ pub box_pixel_height: usize,pub dimensions: RenderableDimensions,pub palette: ColorPalette,pub cursor: StableCursorPosition,@@ -67,6 +324,13 @@ pub(crate) struct TerminalPreviewRequest {pub snapshot: Arc<TerminalPreviewSnapshot>,pub area: RectF,pub clip: RectF,+ /// The card is being resized right now, so hold whatever font scale was+ /// already chosen rather than picking one for this exact size. Scales are+ /// bucketed to bound how many `FontConfiguration`s exist, but a drag sweeps+ /// the card through a bucket every few pixels, and each new bucket builds a+ /// font and rasterises a glyph set. Holding still for the duration costs a+ /// thumbnail that is briefly a little small.+ pub hold_scale: bool,}/// Progress of an SSH connection that a content view kicked off, pushed by the@@ -167,12 +431,40 @@ pub(crate) trait ContentView {false}+ /// Tell the view the shape of the terminal area it is standing in front+ /// of, so a thumbnail can hold the same proportions as the thing it is a+ /// picture of. Pushed every frame rather than fixed at construction: the+ /// window can be resized, a sidebar opened or the tab bar toggled while+ /// the view is up, and a card frozen at the shape the terminal happened to+ /// have when it opened stops matching the terminal it came from.+ fn set_host_preview_aspect(&mut self, _aspect: f32) {}+/// Terminal tabs to paint as read-only live thumbnails after the view's/// regular UI layers have been prepared.fn terminal_previews(&self) -> Vec<TerminalPreviewRequest> {Vec::new()}+ /// Where this view shows `tab_id`'s terminal, if it shows it at all.+ ///+ /// A view that gives a terminal a place of its own can have that terminal+ /// travel to it rather than being replaced by it. `None` means there is no+ /// destination and the view should simply arrive.+ ///+ /// Only meaningful after a paint: the answer comes from a layout, and the+ /// layout is computed while drawing.+ fn terminal_landing_rect(&self, _tab_id: TabId) -> Option<RectF> {+ None+ }++ /// A terminal that is currently travelling to or from its place here, and+ /// so must not also be drawn in it.+ ///+ /// Without this the view shows its own copy of the terminal underneath the+ /// one flying towards it, and the transition reads as two pictures of the+ /// same thing rather than one thing moving.+ fn set_terminal_in_flight(&mut self, _tab_id: Option<TabId>) {}+/// Paint masks and chrome that must sit above terminal preview glyphs./// Most ContentViews do not embed terminal snapshots and need no second/// pass.@@ -213,6 +505,21 @@ pub(crate) trait ContentView {fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse;+ /// Wheel events, with the parts of the event that [`WMEK`] cannot carry.+ ///+ /// A trackpad reports pixels: macOS sends `VertWheel(0)` alongside a+ /// precise delta whenever the gesture has not yet accumulated a whole+ /// line, so a view that reads only the kind either stands still or moves+ /// in whole notches. The momentum phase matters for the same reason --+ /// the system is already supplying the glide, and a view that adds its+ /// own would be integrating it twice.+ ///+ /// Views that do not scroll by pixels can ignore this and keep handling+ /// the coarse event.+ fn on_wheel(&mut self, x: f32, y: f32, event: &MouseEvent) -> ContentViewResponse {+ self.on_mouse(x, y, event.kind.clone())+ }+fn on_key(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse;/// Insert pasted text into the focused field, if any.diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rsindex 4c76222b..25bffe25 100644--- a/wezterm-gui/src/termwindow/keyevent.rs+++ b/wezterm-gui/src/termwindow/keyevent.rs@@ -985,6 +985,13 @@ impl super::TermWindow {}pub fn key_event_impl(&mut self, window_key: KeyEvent, context: &dyn WindowOps) {+ // A transition owns the window: what is on screen is a recording, not+ // anything that can answer. Swallowing here rather than routing to the+ // terminal is the difference between a keystroke landing in a pane the+ // user can no longer see and it landing nowhere.+ if self.content_view_transition_running() {+ return;+ }// Esc aborts an in-flight file-row drag without reaching the paneif window_key.key_is_down&& matches!(window_key.key, KeyCode::Char('\u{1b}'))diff --git a/wezterm-gui/src/termwindow/live_overview.rs b/wezterm-gui/src/termwindow/live_overview.rsindex 8cbc544d..2fe23485 100644--- a/wezterm-gui/src/termwindow/live_overview.rs+++ b/wezterm-gui/src/termwindow/live_overview.rs@@ -5,15 +5,16 @@ use crate::termwindow::content_view::{};use crate::termwindow::ui::icons::SvgIcon;use crate::termwindow::{TermWindow, TermWindowNotif};+use crate::ui::anim::{self, Easing, Timeline};use crate::ui::{draw_button_on_layer, draw_icon_button, draw_icon_button_on_layer, draw_scrollbar_on_layer,- wheel_delta_pixels, ButtonSpec, ControlState, DrawContext, InteractionState, ScrollState,- UiContext, UiPalette, UiTokens, WidgetKind,+ precise_wheel_delta_pixels, wheel_delta_pixels, ButtonSpec, ControlState, DrawContext,+ InteractionState, ScrollState, UiContext, UiPalette, UiTokens, WidgetKind,};use crate::workspace_threads;use fluent_bundle::FluentArgs;use mux::domain::DomainState;-use mux::pane::{CloseReason, PaneId};+use mux::pane::{CachePolicy, CloseReason, PaneId};use mux::renderable::{RenderableDimensions, StableCursorPosition};use mux::tab::{PositionedSplit, TabId};use mux::Mux;@@ -50,6 +51,11 @@ const CARD_INSET: f32 = 8.0;const CARD_CLOSE_BUTTON_SIZE: f32 = 32.0;const CARD_CLOSE_RIGHT_PAD: f32 = 8.0;const CARD_TITLE_CLOSE_GAP: f32 = 8.0;+/// Space between the thread name and the command it is running.+const RUNNING_LABEL_GAP: f32 = 14.0;+/// Below this there is no room to say anything useful, so say nothing rather+/// than showing two or three clipped letters.+const RUNNING_LABEL_MIN_WIDTH: f32 = 56.0;const PREVIEW_RADIUS: f32 = 12.0;const CLOSE_BUTTON_SIZE: f32 = 44.0;const CONFIRM_MIN_WIDTH: f32 = 640.0;@@ -59,11 +65,31 @@ const CONFIRM_PADDING: f32 = 36.0;const CONFIRM_RADIUS: f32 = 24.0;const CONFIRM_TEXT_GAP: f32 = 18.0;const CONFIRM_BUTTON_GAP: f32 = 12.0;+/// Bounds on the shape a card may take. A card is a picture of the terminal,+/// so the terminal's own proportions decide this and the clamp only guards+/// against a degenerate window. The lower bound used to sit at 1.2, which is+/// wider than a terminal gets as soon as a sidebar is open -- at 2704px wide+/// with both sidebars out the terminal is 1699x1622, or 1.05, and every card+/// was being stretched 15% wider than the thing it was a picture of.+const HOST_PREVIEW_ASPECT_MIN: f32 = 0.55;+const HOST_PREVIEW_ASPECT_MAX: f32 = 3.4;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 often a card re-asks what its terminal is running.+///+/// `CachePolicy::AllowStale` is not the cheap read its name suggests: it takes+/// a lock, clones a `CachedLeaderInfo` with its paths, and spawns a thread when+/// the entry has expired. Asking once per card per frame put that on the render+/// thread sixty times a second, for cards scrolled out of sight as much as+/// visible ones. A label naming the program at the prompt does not need to be+/// fresher than this.+const RUNNING_LABEL_REFRESH: Duration = Duration::from_millis(1000);const SCROLLBAR_VISIBLE_INTERVAL: Duration = Duration::from_millis(900);+/// The tail of that interval is spent fading rather than shown at full+/// strength and then cut.+const SCROLLBAR_FADE: Duration = anim::SHORT;const SCROLL_MASK_FADE_HEIGHT: f32 = 32.0;#[derive(Clone, Debug, PartialEq, Eq, Hash)]@@ -107,6 +133,11 @@ struct CachedPreview<T> {struct LiveCard {key: LiveThreadKey,title: String,+ /// What this terminal is running right now, if it is running anything.+ /// The thumbnail below says what the screen looks like; at card size that+ /// is texture rather than information, and this is the line that actually+ /// answers "what is happening here".+ running: Option<String>,tab_id: TabId,active: bool,}@@ -148,6 +179,53 @@ struct GroupLayout {grid: GroupGrid,}+/// Where a card is travelling from and to, so that a change of layout is+/// covered rather than jumped.+///+/// The rectangles are in content space -- the scroll offset and the viewport+/// origin are applied afterwards. Scrolling moves every card on every frame,+/// and diffing in screen space would read that as the whole grid reflowing.+#[derive(Clone, Debug)]+struct CardMotion {+ from: RectF,+ to: RectF,+ travel: Timeline,+}++impl CardMotion {+ fn settled(now: Instant, rect: RectF) -> Self {+ Self {+ from: rect,+ to: rect,+ travel: Timeline::settled(now, 1.0),+ }+ }++ fn current(&self, now: Instant) -> RectF {+ lerp_rect(self.from, self.to, self.travel.value(now))+ }+}++fn lerp_rect(from: RectF, to: RectF, t: f32) -> RectF {+ let lerp = |a: f32, b: f32| a + (b - a) * t;+ euclid::rect(+ lerp(from.origin.x, to.origin.x),+ lerp(from.origin.y, to.origin.y),+ lerp(from.size.width, to.size.width),+ lerp(from.size.height, to.size.height),+ )+}++/// Sub-pixel drift is not a reflow. Without a threshold, rounding in the grid+/// arithmetic would restart the travel on frames where nothing moved.+fn rect_moved(from: RectF, to: RectF) -> bool {+ let moved = |a: f32, b: f32| (a - b).abs() > 0.5;+ moved(from.origin.x, to.origin.x)+ || moved(from.origin.y, to.origin.y)+ || moved(from.size.width, to.size.width)+ || moved(from.size.height, to.size.height)+}+#[derive(Clone, Copy, Debug)]struct CardChrome {preview: RectF,@@ -177,6 +255,9 @@ pub(crate) struct LiveOverviewView {active: Option<LiveThreadKey>,host_preview_aspect: f32,scroll: ScrollState,+ /// Whether the active thread's card has been brought into view. Done once,+ /// on the first frame that has a layout to measure against.+ revealed_active: bool,last_ui_scale: f32,viewport: RectF,widgets: UiContext<OverviewAction>,@@ -184,11 +265,24 @@ pub(crate) struct LiveOverviewView {card_keys: HashMap<TabId, LiveThreadKey>,card_titles: HashMap<TabId, String>,pending_close: Option<PendingClose>,+ running_labels: HashMap<TabId, (Instant, Option<String>)>,snapshot_cache: HashMap<LiveThreadKey, CachedPreview<TerminalPreviewSnapshot>>,previews: Vec<TerminalPreviewRequest>,preview_chrome: Vec<CardChrome>,+ /// Where each visible card shows its terminal, so an opening overview can+ /// be told what a given terminal is about to become. Only cards that were+ /// actually laid out this frame appear here.+ card_preview_rects: HashMap<TabId, RectF>,+ /// Terminal currently travelling to or from its card. Its card is laid out+ /// and drawn as usual, but left empty: the travelling copy is the one the+ /// eye is following, and a second copy waiting in the slot is what made+ /// the transition look like two layers.+ terminal_in_flight: Option<TabId>,visible_panes: HashSet<PaneId>,live_resizing: bool,+ card_motion: HashMap<LiveThreadKey, CardMotion>,+ card_motion_running: bool,+ scroll_animating: bool,next_preview_refresh: Option<Instant>,scrollbar_visible_until: Option<Instant>,}@@ -210,8 +304,9 @@ impl LiveOverviewView {// Extremely narrow/tall terminals still need a useful overview;// within this safety range every card keeps the exact same host// aspect instead of inheriting a source mux tab's split geometry.- host_preview_aspect: host_preview_aspect.clamp(1.2, 3.4),+ host_preview_aspect: host_preview_aspect.clamp(HOST_PREVIEW_ASPECT_MIN, HOST_PREVIEW_ASPECT_MAX),scroll: ScrollState::new(),+ revealed_active: false,last_ui_scale: 1.0,viewport: euclid::rect(0.0, 0.0, 0.0, 0.0),widgets: UiContext::default(),@@ -219,17 +314,68 @@ impl LiveOverviewView {card_keys: HashMap::new(),card_titles: HashMap::new(),pending_close: None,+ running_labels: HashMap::new(),snapshot_cache: HashMap::new(),previews: Vec::new(),preview_chrome: Vec::new(),+ card_preview_rects: HashMap::new(),+ terminal_in_flight: None,visible_panes: HashSet::new(),live_resizing: false,+ card_motion: HashMap::new(),+ card_motion_running: false,+ scroll_animating: false,next_preview_refresh: None,scrollbar_visible_until: None,}}- fn collect_groups(&self) -> Vec<LiveGroup> {+ /// Where to draw a card this frame, given where the grid says it belongs.+ ///+ /// A card that has moved travels to its new home instead of appearing+ /// there. Cards seen for the first time -- and every card while the window+ /// is being dragged, where an animation would only ever lag behind the+ /// window edge -- are placed directly.+ fn settle_card_rect(&mut self, key: &LiveThreadKey, target: RectF, now: Instant) -> RectF {+ let snap = self.live_resizing;+ match self.card_motion.get_mut(key) {+ None => {+ self.card_motion+ .insert(key.clone(), CardMotion::settled(now, target));+ target+ }+ Some(motion) => {+ if snap {+ *motion = CardMotion::settled(now, target);+ return target;+ }+ if rect_moved(motion.to, target) {+ // Depart from where the card is right now, not from where+ // the previous travel was headed: closing a second card+ // while the first reflow is still moving must not send+ // everything backwards before it sets off again.+ motion.from = motion.current(now);+ motion.to = target;+ motion.travel = Timeline::progress(now, anim::SHORT, Easing::OutCubic);+ }+ motion.current(now)+ }+ }+ }++ /// What `tab_id` is running, from cache unless it has gone stale.+ fn running_label(&mut self, tab_id: TabId, now: Instant) -> Option<String> {+ if let Some((asked_at, label)) = self.running_labels.get(&tab_id) {+ if now.saturating_duration_since(*asked_at) < RUNNING_LABEL_REFRESH {+ return label.clone();+ }+ }+ let label = foreground_process_name(tab_id);+ self.running_labels.insert(tab_id, (now, label.clone()));+ label+ }++ fn collect_groups(&mut self, now: Instant) -> Vec<LiveGroup> {let mux = Mux::get();let live_workspaces = mux.iter_workspaces();let mut groups = Vec::new();@@ -266,6 +412,7 @@ impl LiveOverviewView {active: self.active.as_ref() == Some(&key),key,title: card_title(&state.project_name, &state.thread_name),+ running: self.running_label(tab_id, now),tab_id,});}@@ -284,9 +431,69 @@ impl LiveOverviewView {}}+ retain_running_labels(&mut self.running_labels, &groups);+groups}+ /// Where the list has to sit for the active thread's card to be on screen,+ /// or `None` if it already is -- or if there is no active card to find.+ ///+ /// This is not only about orientation. A card outside the viewport is+ /// skipped before it registers a landing rectangle, and a terminal with no+ /// landing rectangle has nowhere to go: `terminal_landing_rect` returns+ /// `None`, the flight falls back to the whole window, and the shrink+ /// degenerates into a fade in place. Revealing the card is what gives the+ /// transition a destination.+ ///+ /// Centres the card rather than scrolling the least possible distance. This+ /// runs before the first row is drawn, so there is no motion to keep small+ /// -- only the question of where the eye should land.+ fn offset_revealing_active(+ &self,+ groups: &[LiveGroup],+ layouts: &[GroupLayout],+ content_x: f32,+ content_width: f32,+ gap: f32,+ ) -> Option<f32> {+ let viewport_height = self.viewport.size.height;+ let max_offset = self.scroll.max_offset();+ if viewport_height <= 0.0 || max_offset <= 0.0 {+ return None;+ }+ let (layout, index, count) = groups.iter().zip(layouts).find_map(|(group, layout)| {+ group+ .cards+ .iter()+ .position(|card| card.active)+ .map(|index| (layout, index, group.cards.len()))+ })?;+ let rect = card_rect(+ index,+ count,+ layout.grid,+ content_x,+ content_width,+ layout.cards_y,+ gap,+ );+ // Card rectangles are in content space, so the band on screen right now+ // is `[offset, offset + viewport_height]`.+ let offset = self.scroll.offset;+ if rect.min_y() >= offset && rect.max_y() <= offset + viewport_height {+ return None;+ }+ let desired = if rect.size.height >= viewport_height {+ // Taller than the viewport: showing its top beats centring a card+ // whose header would then be cut off.+ rect.min_y()+ } else {+ rect.min_y() - (viewport_height - rect.size.height) / 2.0+ };+ Some(desired.clamp(0.0, max_offset))+ }+#[allow(clippy::too_many_arguments)]fn paint_impl(&mut self,@@ -304,6 +511,7 @@ impl LiveOverviewView {self.card_titles.clear();self.previews.clear();self.preview_chrome.clear();+ self.card_preview_rects.clear();self.visible_panes.clear();self.next_preview_refresh = None;@@ -349,10 +557,21 @@ impl LiveOverviewView {ctx.px(FIVE_COLUMN_WINDOW_WIDTH),);- let groups = self.collect_groups();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);+ }+ // The glide a notched wheel was given, and any smoothing towards a+ // programmatic target, both live in the scroll state.+ self.scroll_animating = self.scroll.advance_animation(now);+ if self.scroll_animating {+ self.reveal_scrollbar(now);+ }let mut warm_keys = HashSet::new();+ let mut seen_keys = HashSet::new();if groups.is_empty() {self.scroll.set_extents(self.viewport.size.height, 0.0);self.paint_empty(ctx, layers, palette, settings_font)?;@@ -378,6 +597,20 @@ impl LiveOverviewView {);self.scroll.set_extents(self.viewport.size.height, content_height);+ // A brand-new overview starts at the top of the list, which leaves+ // the active thread's card off screen as soon as the grid is taller+ // than the viewport. Reveal it here, before the first row is drawn,+ // so that this frame's `card_preview_rects` already carries its+ // landing rectangle and the arriving terminal has somewhere to+ // shrink into.+ if !self.revealed_active {+ self.revealed_active = true;+ if let Some(offset) =+ self.offset_revealing_active(&groups, &layouts, content_x, content_width, gap)+ {+ self.scroll.scroll_by(offset - self.scroll.offset);+ }+ }for (group, layout) in groups.iter().zip(layouts) {let heading_y = self.viewport.origin.y + layout.header_y - self.scroll.offset;@@ -419,15 +652,25 @@ impl LiveOverviewView {}for (index, card) in group.cards.iter().enumerate() {- let rect = card_rect(+ // Content space: `cards_y` is measured from the top of the+ // scrollable content, so the same card keeps the same+ // rectangle no matter where the list is scrolled to.+ let target = card_rect(index,group.cards.len(),layout.grid,content_x,content_width,- self.viewport.origin.y + layout.cards_y - self.scroll.offset,+ layout.cards_y,gap,);+ seen_keys.insert(card.key.clone());+ let rect = self+ .settle_card_rect(&card.key, target, now)+ .translate(euclid::vec2(+ 0.0,+ self.viewport.origin.y - self.scroll.offset,+ ));// Keep one complete row warm above and below the viewport// so a scroll does not reveal an uncaptured thumbnail. All@@ -517,6 +760,7 @@ impl LiveOverviewView {palette.secondary_text,)?;let text_x = icon_x + icon_size + ctx.px(10.0);+ let text_limit = (close_x - ctx.px(CARD_TITLE_CLOSE_GAP) - text_x).max(1.0);ctx.draw_text(layers,card_font,@@ -524,8 +768,28 @@ impl LiveOverviewView {title_y,&card.title,palette.text,- (close_x - ctx.px(CARD_TITLE_CLOSE_GAP) - text_x).max(1.0),+ text_limit,)?;+ if let Some(running) = card.running.as_ref() {+ // Only once the name of the thread has been given+ // its space: which terminal this is comes first,+ // what it is doing second.+ let title_width =+ ctx.measure_text_width(card_font, &card.title).min(text_limit);+ let running_x = text_x + title_width + ctx.px(RUNNING_LABEL_GAP);+ let running_limit = text_x + text_limit - running_x;+ if running_limit >= ctx.px(RUNNING_LABEL_MIN_WIDTH) {+ ctx.draw_text(+ layers,+ card_font,+ running_x,+ title_y,+ running,+ palette.muted_text,+ running_limit,+ )?;+ }+ }}let preview_width = (rect.size.width - card_inset * 2.0).max(1.0);@@ -535,6 +799,22 @@ impl LiveOverviewView {preview_width,preview_width / self.host_preview_aspect,);+ let in_flight = self.terminal_in_flight == Some(tab_id);+ // A card whose terminal is currently flying to it is left+ // empty, but not neutral: the panel takes that terminal's+ // own background so the arriving picture settles onto the+ // same colour it is already showing. Filling it with the+ // generic preview grey put a step in the handover, and the+ // step read as a flash.+ let preview_fill = if in_flight {+ snapshot+ .as_ref()+ .and_then(|snapshot| snapshot.panes.first())+ .map(|pane| pane.palette.background.to_linear())+ .unwrap_or(colors.preview)+ } else {+ colors.preview+ };if let Some(clip) = preview.intersection(&self.viewport) {if clip.size.width > 1.0 && clip.size.height > 1.0 {ctx.draw_rounded_rect(@@ -544,14 +824,15 @@ impl LiveOverviewView {preview.origin.y,preview.size.width,preview.size.height,- colors.preview,+ preview_fill,ctx.px(PREVIEW_RADIUS),)?;- if let Some(snapshot) = snapshot.as_ref() {+ if let Some(snapshot) = snapshot.as_ref().filter(|_| !in_flight) {self.previews.push(TerminalPreviewRequest {snapshot: Arc::clone(snapshot),area: preview,clip,+ hold_scale: self.live_resizing,});self.visible_panes.extend(snapshot.panes.iter().map(|pane| pane.pane_id));@@ -562,6 +843,7 @@ impl LiveOverviewView {fill,border: colors.preview_border,});+ self.card_preview_rects.insert(tab_id, preview);}}@@ -600,6 +882,16 @@ impl LiveOverviewView {self.scrollbar_visible_until = None;}self.snapshot_cache.retain(|key, _| warm_keys.contains(key));+ // The running-label cache is pruned in `collect_groups`, against every+ // live tab rather than against the cards that happened to be drawn.+ // A card that is gone has nowhere left to travel to; keeping its+ // motion would also mean a reopened thread animating in from wherever+ // it happened to sit last time.+ self.card_motion.retain(|key, _| seen_keys.contains(key));+ self.card_motion_running = self+ .card_motion+ .values()+ .any(|motion| motion.travel.is_running());Ok(())}@@ -689,13 +981,16 @@ impl LiveOverviewView {area: RectF,palette: UiPalette,) -> anyhow::Result<()> {- if self.scrollbar_visible_at(Instant::now()) {+ let scrollbar_opacity = self.scrollbar_opacity_at(Instant::now());+ if scrollbar_opacity > 0.0 {let scrollbar_area = euclid::rect(self.viewport.origin.x,self.viewport.origin.y,self.viewport.size.width,self.viewport.size.height,);+ let mut palette = palette;+ palette.scrollbar_thumb = palette.scrollbar_thumb.mul_alpha(scrollbar_opacity);draw_scrollbar_on_layer(ctx,layers,@@ -733,21 +1028,53 @@ impl LiveOverviewView {}}- fn scrollbar_visible_at(&self, now: Instant) -> bool {- self.scroll.max_offset() > 0.0- && self- .scrollbar_visible_until- .is_some_and(|until| until > now)+ /// The scrollbar is transient, and used to vanish between one frame and+ /// the next. Spend the tail of its visible interval fading instead, so+ /// what the eye catches is something leaving rather than something+ /// disappearing.+ fn scrollbar_opacity_at(&self, now: Instant) -> f32 {+ if self.scroll.max_offset() <= 0.0 {+ return 0.0;+ }+ let Some(until) = self.scrollbar_visible_until else {+ return 0.0;+ };+ let Some(remaining) = until.checked_duration_since(now) else {+ return 0.0;+ };+ if remaining >= SCROLLBAR_FADE {+ return 1.0;+ }+ Easing::Smooth.apply(remaining.as_secs_f32() / SCROLLBAR_FADE.as_secs_f32())}fn next_frame_deadline(&self, now: Instant) -> Option<Instant> {- let scrollbar_deadline = self.scrollbar_visible_until.filter(|until| *until > now);- match (self.next_preview_refresh, scrollbar_deadline) {- (Some(preview), Some(scrollbar)) => Some(preview.min(scrollbar)),- (Some(preview), None) => Some(preview),- (None, Some(scrollbar)) => Some(scrollbar),- (None, None) => None,- }+ // A travelling card wants the next frame the display will give it.+ // Asking for `now` rather than naming an interval leaves the pacing to+ // 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);+ // 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| {+ let fade_from = until.checked_sub(SCROLLBAR_FADE).unwrap_or(until);+ if now < fade_from {+ Some(fade_from)+ } else if now < until {+ Some(now)+ } else {+ None+ }+ });+ [+ motion_deadline,+ self.next_preview_refresh,+ scrollbar_deadline,+ ]+ .iter()+ .flatten()+ .copied()+ .min()}fn paint_empty(@@ -1021,6 +1348,9 @@ impl LiveOverviewView {match kind {WMEK::VertWheel(_) if modal_active => ContentViewResponse::Ignored,WMEK::VertWheel(amount) => {+ // Reached only when the wheel arrives without its full event,+ // which is every backend that has no pixel deltas to report.+ // See `on_wheel` for the trackpad path.let old = self.scroll.offset;self.scroll.scroll_by(wheel_delta_pixels(amount, self.last_ui_scale));@@ -1127,6 +1457,20 @@ impl ContentView for LiveOverviewView {}}+ fn terminal_landing_rect(&self, tab_id: TabId) -> Option<RectF> {+ self.card_preview_rects.get(&tab_id).copied()+ }++ fn set_terminal_in_flight(&mut self, tab_id: Option<TabId>) {+ self.terminal_in_flight = tab_id;+ }++ 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);+ }+ }+fn terminal_previews(&self) -> Vec<TerminalPreviewRequest> {self.previews.clone()}@@ -1187,6 +1531,37 @@ impl ContentView for LiveOverviewView {self.on_mouse_impl(x, y, kind)}+ fn on_wheel(&mut self, _x: f32, _y: f32, event: &window::MouseEvent) -> ContentViewResponse {+ if self.pending_close.is_some() {+ return ContentViewResponse::Ignored;+ }+ self.scroll+ .set_phase(event.momentum_phase.or(event.scroll_phase));++ let before = (self.scroll.offset, self.scroll.velocity);+ if let Some(delta) = precise_wheel_delta_pixels(event) {+ // A trackpad is already carrying its own momentum; take the+ // pixels it reports and add nothing.+ self.scroll.scroll_by(delta);+ } else if let WMEK::VertWheel(amount) = event.kind {+ // A notched wheel has no glide of its own, so give it one rather+ // than teleporting the list a fixed distance per click.+ self.scroll+ .scroll_by_smooth(wheel_delta_pixels(amount, self.last_ui_scale));+ } else {+ return ContentViewResponse::Ignored;+ }++ if (before.0 - self.scroll.offset).abs() > 0.01+ || (before.1 - self.scroll.velocity).abs() > 0.5+ {+ self.reveal_scrollbar(Instant::now());+ ContentViewResponse::Redraw+ } else {+ ContentViewResponse::Ignored+ }+ }+fn on_key(&mut self, key: KeyCode, _mods: KeyModifiers) -> ContentViewResponse {if key == KeyCode::Escape {if self.pending_close.is_some() {@@ -1359,6 +1734,26 @@ fn terminal_preview_fingerprint(tab_id: TabId) -> Option<TerminalPreviewFingerpr}}+/// Prune the running-label cache to the tabs that are still live.+///+/// Keyed on every card `collect_groups` walked, not on the cards that were+/// drawn. Retaining against the drawn set -- which is what `card_keys` holds --+/// discarded every offscreen card's entry on each frame as soon as there were+/// more cards than fit in the viewport, so the next frame asked the system+/// again for all of them and [`RUNNING_LABEL_REFRESH`] never held anything.+/// The cost lands on the render thread, in a lookup that spawns a thread when+/// its own cache has gone stale.+fn retain_running_labels(+ labels: &mut HashMap<TabId, (Instant, Option<String>)>,+ groups: &[LiveGroup],+) {+ let live_tabs: HashSet<TabId> = groups+ .iter()+ .flat_map(|group| group.cards.iter().map(|card| card.tab_id))+ .collect();+ labels.retain(|tab_id, _| live_tabs.contains(tab_id));+}+fn palette_identity(palette: &wezterm_term::color::ColorPalette) -> u64 {let mut hasher = DefaultHasher::new();palette.colors.0.hash(&mut hasher);@@ -1386,11 +1781,14 @@ fn capture_terminal_snapshot(tab_id: TabId) -> Option<TerminalPreviewSnapshot> {for positioned in tab.iter_panes() {let pane = positioned.pane;let dimensions = pane.get_dimensions();- let rows = positioned.height.min(dimensions.viewport_rows);- let cols = positioned.width.min(dimensions.cols);- let first_row = dimensions- .physical_top- .saturating_add(dimensions.viewport_rows.saturating_sub(rows) as isize);+ // A positioned pane is measured in the tab's root-cell grid, while+ // its terminal dimensions are measured in that pane's own cells.+ // Those differ when a pane has a local font scale. Clamping the latter+ // to the former discards the extra rows/columns of a smaller-font pane+ // and makes a larger-font pane look artificially short in a preview.+ let rows = dimensions.viewport_rows;+ let cols = dimensions.cols;+ let first_row = dimensions.physical_top;let (resolved_top, lines) = if rows == 0 || cols == 0 {(first_row, Vec::new())} else {@@ -1407,6 +1805,7 @@ fn capture_terminal_snapshot(tab_id: TabId) -> Option<TerminalPreviewSnapshot> {rows,resolved_top,lines,+ box_pixel_height: positioned.pixel_height,dimensions,palette: pane.palette_override().unwrap_or_else(|| pane.palette()),cursor: pane.get_cursor_position(),@@ -1469,6 +1868,25 @@ where)}+/// The command in the foreground of a tab's active pane, basename only, or+/// `None` when the pane is a shell waiting at its prompt.+///+/// `AllowStale` keeps this to a cache read: it runs for every card on every+/// frame, and a name that is one refresh out of date is not worth walking the+/// process table for.+fn foreground_process_name(tab_id: TabId) -> Option<String> {+ let pane = Mux::get().get_tab(tab_id)?.get_active_pane()?;+ let path = pane.get_foreground_process_name(CachePolicy::AllowStale)?;+ let name = std::path::Path::new(&path)+ .file_name()?+ .to_string_lossy()+ .to_string();+ if crate::termwindow::ui::is_default_shell_title(&name) {+ return None;+ }+ Some(name)+}+fn card_title(project_name: &str, thread_name: &str) -> String {if project_name.is_empty() || project_name == thread_name {thread_name.to_string()@@ -1989,18 +2407,255 @@ mod tests {assert!(view.pending_close.is_none());}+ fn live_group_with_active(count: usize, active: usize) -> LiveGroup {+ LiveGroup {+ name: "space".to_string(),+ offline: false,+ cards: (0..count)+ .map(|index| LiveCard {+ key: LiveThreadKey {+ space_id: "space".to_string(),+ thread_id: format!("thread-{index}"),+ },+ title: format!("thread {index}"),+ running: None,+ tab_id: index as TabId,+ active: index == active,+ })+ .collect(),+ }+ }++ fn reveal_layout(columns: usize, rows: usize, card_height: f32) -> Vec<GroupLayout> {+ vec![GroupLayout {+ header_y: 0.0,+ cards_y: 40.0,+ grid: GroupGrid {+ columns,+ rows,+ card_width: 480.0,+ card_height,+ },+ }]+ }++ #[test]+ fn opening_scrolls_an_active_card_below_the_fold_into_view() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ view.viewport = euclid::rect(0.0, 0.0, 1000.0, 400.0);+ let layouts = reveal_layout(2, 3, 300.0);+ let groups = vec![live_group_with_active(6, 5)];+ // Three rows of 300 separated by a 16 gap, below a 40px heading.+ view.scroll.set_extents(400.0, 40.0 + 3.0 * 300.0 + 2.0 * 16.0);++ let offset = view+ .offset_revealing_active(&groups, &layouts, 0.0, 1000.0, 16.0)+ .expect("the last row starts below the fold");+ // The last row wants to be centred at 622; the list bottoms out at 572.+ assert!((offset - 572.0).abs() < 0.01, "offset was {offset}");+ }++ #[test]+ fn a_revealed_card_is_centred_when_the_list_is_long_enough() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ view.viewport = euclid::rect(0.0, 0.0, 1000.0, 400.0);+ let layouts = reveal_layout(1, 10, 100.0);+ let groups = vec![live_group_with_active(10, 4)];+ view.scroll.set_extents(400.0, 40.0 + 10.0 * 100.0 + 9.0 * 16.0);++ let offset = view+ .offset_revealing_active(&groups, &layouts, 0.0, 1000.0, 16.0)+ .expect("the fifth row is below the fold");+ // Row 4 sits at 40 + 4 * 116 = 504; centring a 100 tall card in 400+ // lifts it by 150.+ assert!((offset - 354.0).abs() < 0.01, "offset was {offset}");+ }++ #[test]+ fn opening_leaves_an_already_visible_active_card_alone() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ view.viewport = euclid::rect(0.0, 0.0, 1000.0, 400.0);+ let layouts = reveal_layout(2, 3, 300.0);+ let groups = vec![live_group_with_active(6, 0)];+ view.scroll.set_extents(400.0, 40.0 + 3.0 * 300.0 + 2.0 * 16.0);++ assert!(view+ .offset_revealing_active(&groups, &layouts, 0.0, 1000.0, 16.0)+ .is_none());+ }++ #[test]+ fn a_list_with_no_active_card_is_left_where_it_is() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ view.viewport = euclid::rect(0.0, 0.0, 1000.0, 400.0);+ let layouts = reveal_layout(2, 3, 300.0);+ let mut groups = vec![live_group_with_active(6, 0)];+ groups[0].cards[0].active = false;+ view.scroll.set_extents(400.0, 40.0 + 3.0 * 300.0 + 2.0 * 16.0);++ assert!(view+ .offset_revealing_active(&groups, &layouts, 0.0, 1000.0, 16.0)+ .is_none());+ }++ #[test]+ fn offscreen_cards_keep_their_running_label_between_frames() {+ // Six cards; a viewport that fits two. Whether a card was drawn is not+ // this function's business -- every live tab keeps its entry, or the+ // one-second cache never survives a frame.+ let groups = vec![live_group_with_active(6, 0)];+ let now = Instant::now();+ let mut labels: HashMap<TabId, (Instant, Option<String>)> = (0..6)+ .map(|index| (index as TabId, (now, Some(format!("cmd-{index}")))))+ .collect();++ retain_running_labels(&mut labels, &groups);++ assert_eq!(labels.len(), 6, "every live tab keeps its label");+ assert_eq!(+ labels[&5].1.as_deref(),+ Some("cmd-5"),+ "the last row is offscreen but still live"+ );+ }++ #[test]+ fn a_closed_tab_loses_its_running_label() {+ let groups = vec![live_group_with_active(2, 0)];+ let now = Instant::now();+ let mut labels: HashMap<TabId, (Instant, Option<String>)> = (0..4)+ .map(|index| (index as TabId, (now, Some("cmd".to_string()))))+ .collect();++ retain_running_labels(&mut labels, &groups);++ assert_eq!(labels.len(), 2);+ assert!(labels.contains_key(&0) && labels.contains_key(&1));+ }++ fn card_key() -> LiveThreadKey {+ LiveThreadKey {+ space_id: "space".to_string(),+ thread_id: "thread".to_string(),+ }+ }++ /// One frame of `paint_impl`: every travel is advanced once, then each+ /// card asks where it should be drawn.+ fn card_frame(+ view: &mut LiveOverviewView,+ key: &LiveThreadKey,+ target: RectF,+ now: Instant,+ ) -> RectF {+ for motion in view.card_motion.values_mut() {+ motion.travel.advance(now);+ }+ view.settle_card_rect(key, target, now)+ }++ #[test]+ fn a_card_appears_where_the_grid_puts_it_and_stays_there() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ let key = card_key();+ let now = Instant::now();+ let slot = euclid::rect(0.0, 0.0, 100.0, 80.0);++ assert_eq!(card_frame(&mut view, &key, slot, now), slot);+ let later = now + Duration::from_millis(500);+ assert_eq!(card_frame(&mut view, &key, slot, later), slot);+ assert!(!view.card_motion[&key].travel.is_running());+ }++ #[test]+ fn a_card_whose_neighbour_closed_travels_into_the_gap() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ let key = card_key();+ let start = Instant::now();+ let was = euclid::rect(0.0, 200.0, 100.0, 80.0);+ let now_at = euclid::rect(0.0, 0.0, 100.0, 80.0);+ let at = |ms: u64| start + Duration::from_millis(ms);++ card_frame(&mut view, &key, was, at(0));++ // The frame that discovers the new layout is also the frame that pays+ // for redrawing it, so the card has not set off yet.+ assert_eq!(card_frame(&mut view, &key, now_at, at(10)), was);+ assert_eq!(card_frame(&mut view, &key, now_at, at(20)), was);++ // Halfway through, ease-out has it well past the midpoint.+ let midway = card_frame(&mut view, &key, now_at, at(110));+ assert!(midway.origin.y < 100.0 && midway.origin.y > 0.0);++ assert_eq!(card_frame(&mut view, &key, now_at, at(400)), now_at);+ assert!(!view.card_motion[&key].travel.is_running());+ }++ #[test]+ fn closing_a_second_card_mid_travel_does_not_send_the_first_backwards() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ let key = card_key();+ let start = Instant::now();+ let at = |ms: u64| start + Duration::from_millis(ms);+ let bottom = euclid::rect(0.0, 200.0, 100.0, 80.0);+ let middle = euclid::rect(0.0, 100.0, 100.0, 80.0);+ let top = euclid::rect(0.0, 0.0, 100.0, 80.0);++ card_frame(&mut view, &key, bottom, at(0));+ card_frame(&mut view, &key, middle, at(10));+ card_frame(&mut view, &key, middle, at(20));+ let mid_travel = card_frame(&mut view, &key, middle, at(110));+ assert!(mid_travel.origin.y < 200.0 && mid_travel.origin.y > 100.0);++ // A second card closes while this one is still moving.+ let redirected = card_frame(&mut view, &key, top, at(110));+ assert_eq!(redirected.origin.y, mid_travel.origin.y);++ card_frame(&mut view, &key, top, at(126));+ assert_eq!(card_frame(&mut view, &key, top, at(500)), top);+ }++ #[test]+ fn dragging_the_window_relays_out_the_grid_without_animating_it() {+ let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);+ let key = card_key();+ let start = Instant::now();+ let narrow = euclid::rect(0.0, 0.0, 100.0, 80.0);+ let wide = euclid::rect(0.0, 0.0, 260.0, 80.0);++ card_frame(&mut view, &key, narrow, start);+ view.live_resizing = true;+ // Chasing the window edge one frame behind reads as lag, not motion.+ assert_eq!(+ card_frame(&mut view, &key, wide, start + Duration::from_millis(8)),+ wide+ );+ assert!(!view.card_motion[&key].travel.is_running());+ }+#[test]fn scrollbar_is_transient_and_schedules_its_hide_frame() {let mut view = LiveOverviewView::new(0, "space", "workspace", 1.8);view.scroll.set_extents(100.0, 300.0);let now = Instant::now();- assert!(!view.scrollbar_visible_at(now));+ assert_eq!(view.scrollbar_opacity_at(now), 0.0);view.reveal_scrollbar(now);let deadline = now + SCROLLBAR_VISIBLE_INTERVAL;- assert!(view.scrollbar_visible_at(deadline - Duration::from_millis(1)));- assert!(!view.scrollbar_visible_at(deadline));- assert_eq!(view.next_frame_deadline(now), Some(deadline));+ assert!(view.scrollbar_opacity_at(deadline - Duration::from_millis(1)) > 0.0);++ // Full strength until the fade starts, then on its way out.+ let fade_from = deadline - SCROLLBAR_FADE;+ assert_eq!(view.scrollbar_opacity_at(fade_from), 1.0);+ let half_faded = view.scrollbar_opacity_at(fade_from + SCROLLBAR_FADE / 2);+ assert!(half_faded > 0.0 && half_faded < 1.0);+ assert_eq!(view.scrollbar_opacity_at(deadline), 0.0);++ // One frame to begin the fade; once inside it, every frame.+ assert_eq!(view.next_frame_deadline(now), Some(fade_from));+ let mid_fade = fade_from + Duration::from_millis(20);+ assert_eq!(view.next_frame_deadline(mid_fade), Some(mid_fade));+ assert_eq!(view.next_frame_deadline(deadline), None);}#[test]diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 594e7dac..0bedb272 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -249,6 +249,72 @@ use prevcursor::PrevCursorPos;const ATLAS_SIZE: usize = 128;+/// Ceiling on growing the glyph atlas to fit a working set, in texels per side.+///+/// [`ATLAS_SIZE`] is only a seed: startup grows it until the utility sprites+/// fit and then stops, which lands at 512 and has nothing to do with how many+/// glyphs are actually in use. The overview pushed the working set well past+/// that -- a terminal's glyphs, the window chrome, and every card's thumbnail+/// at its own font size -- and the overflow path answered by clearing the+/// atlas at the same size. Any single frame fits after a clear, so it never+/// grew and cleared again on the next transition instead: every glyph on+/// screen re-rasterised, several times a minute.+///+/// The atlas is BGRA32, so this is 16MB. Growth stays demand-driven -- nothing+/// is allocated until a frame actually overflows -- and at the ceiling the old+/// clear-in-place behaviour takes over again, which is also what reclaims the+/// one-off glyphs a closed overview leaves behind.+const MAX_GROWN_ATLAS_SIZE: usize = 2048;++/// How long a full-window view takes to arrive or leave.+///+/// Shorter than the Space swipe settle: that one continues a gesture the hand+/// is still invested in, while this is the cost of a glance. The overview is+/// opened to survey what is running, several times an hour, and every+/// millisecond here is charged to that glance.+const CONTENT_VIEW_FADE: Duration = Duration::from_millis(140);++/// How long the terminal takes to travel into the card it becomes.+///+/// Longer than the fade it happens under: the eye is following something+/// across most of the window, and a distance that large read at fade speed+/// registers as a jump rather than as travel.+const CONTENT_VIEW_TRAVEL: Duration = Duration::from_millis(260);++/// How long the travelling terminal takes to dissolve into the card's own+/// thumbnail of it, once the two are close enough in size to overlap.+///+/// Long enough to be seen, which is a lower bound with real teeth: a timeline+/// does not start its clock until the frame after it is armed, so a dissolve+/// budgeted at 45ms spent one frame arming and left two usable ones. That is a+/// cut with extra steps, and it is what the first version of this shipped as.+///+/// Deliberately outlasts the travel. The last stretch of it therefore runs+/// after the terminal has settled into the card, where the two pictures are+/// aligned exactly and the dissolve costs nothing at all.+const CONTENT_VIEW_LANDING_FADE: Duration = Duration::from_millis(140);++/// How long the window frame takes to clear its own edges. Shorter than the+/// terminal's journey: it only has to get out of the way, and the eye should+/// be on the terminal by the time it is halfway across.+const CONTENT_VIEW_CHROME_TRAVEL: Duration = Duration::from_millis(180);++/// How long the frame waits, on the way back, for the terminal to land first.+/// Arriving together would leave the frame sitting around an empty middle.+const CHROME_RETURN_DELAY: Duration = Duration::from_millis(90);++/// Z-index the travelling terminal is composited into: above the arriving+/// view, because it is shrinking *into* the card and has to be seen crossing+/// the grid that is arriving underneath it.+pub(crate) const CONTENT_VIEW_FLIGHT_ZINDEX: i8 = 9;++/// Z-index a transitioning full-window view is composited into.+///+/// Everything else in the window draws at zero. The quad layers within a+/// z-index are a global order rather than per-surface depth, so a view sharing+/// them with the terminal would have the terminal's text drawn through it.+pub(crate) const CONTENT_VIEW_FADE_ZINDEX: i8 = 8;+lazy_static::lazy_static! {static ref WINDOW_CLASS: Mutex<String> = Mutex::new(wezterm_gui_subcommands::DEFAULT_WINDOW_CLASS.to_owned());static ref POSITION: Mutex<Option<GuiPosition>> = Mutex::new(None);@@ -1427,6 +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>,+ /// 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>>,semantic_zones: HashMap<PaneId, SemanticZoneCache>,window_background: Vec<LoadedBackgroundLayer>,@@ -1495,6 +1567,12 @@ pub struct TermWindow {/// foreground. It is flushed once when terminal content becomes visible/// again; merely opening and closing a view must not resize mux tabs.content_view_deferred_mux_resize: bool,+ /// A full-window view arriving or leaving. `None` outside a transition,+ /// which is the state the paint pass treats as "one world or the other".+ content_view_fade: Option<crate::termwindow::content_view::ContentViewFade>,+ /// The most recent full-window view frame, recorded so that closing one+ /// has a picture to take away after the view itself is gone.+ content_view_last_frame: Option<crate::quad::HeapQuadAllocator>,next_content_view_id: ContentViewId,registered_content_view_surfaces: HashMap<ContentViewId, MuxWindowId>,/// Tracks SSH connections kicked off by `RemoteThreadView`s.@@ -1977,6 +2055,56 @@ impl TermWindow {}}+ /// Drop what a running full-window transition had recorded, keeping the+ /// transition itself.+ ///+ /// Same reason as the space swipe above: captured quads hold atlas UV+ /// coordinates rather than pixels, so a repack moves every glyph out from+ /// under them and replaying them afterwards draws whatever now sits at+ /// those coordinates. A transition is a likely moment for a repack -- it+ /// is generating thumbnails at font sizes nothing has used before.+ ///+ /// Most of it can simply be recorded again. Clearing `flight` is what asks+ /// for that: the next frame sees no recording, paints the terminal world+ /// into a fresh one, and re-resolves where it is going -- the timelines+ /// keep running throughout, so the animation continues from where it had+ /// reached rather than restarting. The window frame comes along on the+ /// same frame.+ ///+ /// `ghost` is kept, stale coordinates and all. It is a closing view's last+ /// frame and that view has already been torn down, so nothing can record+ /// it again -- and on the frame this runs on, the terminal world is going+ /// into a recording rather than onto the screen. Dropping the ghost there+ /// leaves nothing at all to draw: the whole window goes black for a frame,+ /// with the shrunken terminal alone in the middle of it. Wrong glyphs in a+ /// picture that is already fading out are much cheaper than that.+ ///+ /// This deliberately does *not* cancel the fade either. That was the first+ /// version, and it traded the same frame of wrong glyphs for an animation+ /// that silently stopped partway.+ 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;+ let Some(fade) = self.content_view_fade.as_mut() else {+ return;+ };+ // Logged, not silent. This fires far more often than "the atlas+ // occasionally repacks" suggests -- three times in thirteen seconds of+ // opening and closing the overview -- and every symptom it produces+ // looks like a rendering bug rather than like recovery.+ log::info!(+ "atlas recreated mid-transition; re-recording flight and chrome (ghost kept: {})",+ fade.ghost.is_some()+ );+ fade.flight = None;+ fade.chrome = None;+ // The card hides its own thumbnail while its terminal is in flight.+ // There is no flight for the moment, so let it draw one.+ if let Some(view) = self.active_content_view_mut() {+ view.set_terminal_in_flight(None);+ }+ }+fn focus_changed(&mut self, focused: bool, window: &Window) {log::trace!("Setting focus to {:?}", focused);self.focused = if focused { Some(Instant::now()) } else { None };@@ -2300,6 +2428,8 @@ 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_scale_hold: RefCell::new(HashMap::new()),current_mouse_buttons: vec![],current_mouse_capture: None,last_mouse_click: None,@@ -2375,6 +2505,8 @@ impl TermWindow {active_content_view_id: None,content_view_response_tab_id: None,content_view_deferred_mux_resize: false,+ content_view_fade: None,+ content_view_last_frame: None,next_content_view_id: 1,registered_content_view_surfaces: HashMap::new(),remote_connects: HashMap::new(),@@ -4263,6 +4395,9 @@ impl TermWindow {.borrow_mut().update_config(&config);self.pane_font_cache.borrow_mut().clear();+ // The held scales name entries in the cache just emptied, and a config+ // change can move the font size out from under them anyway.+ self.preview_scale_hold.borrow_mut().clear();self.fancy_tab_bar.take();self.invalidate_fancy_tab_bar();self.invalidate_modal();@@ -4329,6 +4464,23 @@ impl TermWindow {self.active_content_view_index().is_some()}+ /// Whether a full-window view is arriving or leaving right now, and so+ /// owns the keyboard and the pointer.+ ///+ /// Every other input gate asks [`Self::content_view_foreground`], which is+ /// false for the whole of a *closing* transition: the view is removed from+ /// `content_views` before the fade is started. Without this the terminal+ /// was reachable for the length of that animation, while what the user was+ /// looking at was a recording of it on its way into a card.+ pub(crate) fn content_view_transition_running(&self) -> bool {+ let now = Instant::now();+ self.content_view_fade.as_ref().is_some_and(|fade| {+ crate::termwindow::content_view::transition_holds_input(+ now.saturating_duration_since(fade.started_at),+ )+ })+ }+pub(crate) fn active_content_view_presentation(&self) -> ContentViewPresentation {self.active_content_view().map(|view| view.presentation())@@ -4398,6 +4550,37 @@ impl TermWindow {euclid::rect(left, top, (right - left).max(0.0), (bottom - top).max(0.0))}+ /// Where the terminal grid itself lives: the window minus the sidebars,+ /// the tab bar and the borders.+ ///+ /// Unlike [`Self::content_view_area`] this ignores whether a full-window+ /// view is currently open, because it answers a question about the+ /// terminal rather than about the view sitting on top of it.+ pub(crate) fn terminal_content_rect(&self) -> RectF {+ let border = self.get_os_border();+ let top_tab_h = if self.show_tab_bar && !self.config.tab_bar_at_bottom {+ self.tab_bar_pixel_height().unwrap_or(0.0)+ } else {+ 0.0+ };+ let bottom_tab_h = if self.show_tab_bar && self.config.tab_bar_at_bottom {+ self.tab_bar_pixel_height().unwrap_or(0.0)+ } else {+ 0.0+ };+ let left = self.workspace_sidebar_width() as f32 + border.left.get() as f32;+ let top = border.top.get() as f32 + top_tab_h;+ let right = self+ .dimensions+ .pixel_width+ .saturating_sub(border.right.get() as usize)+ .saturating_sub(self.right_sidebar_width()) as f32;+ let bottom =+ (self.dimensions.pixel_height as f32 - border.bottom.get() as f32 - bottom_tab_h)+ .max(top);+ euclid::rect(left, top, (right - left).max(0.0), (bottom - top).max(0.0))+ }+fn content_view_visible_in_active_space(&self, tab: &ContentViewTab) -> bool {match tab.space_id.as_deref() {Some(space_id) => space_id == self.active_space_id,@@ -4581,6 +4764,7 @@ impl TermWindow {let id = self.next_content_view_id;self.next_content_view_id = self.next_content_view_id.saturating_add(1).max(1);+ let full_window = matches!(view.presentation(), ContentViewPresentation::FullWindow);self.content_views.push(ContentViewTab {id,key,@@ -4588,9 +4772,90 @@ impl TermWindow {view,});self.set_active_content_view_id(Some(id));+ if full_window {+ self.begin_content_view_fade(false);+ }id}+ /// Start a full-window view's arrival or departure.+ ///+ /// The clock is deliberately left unstarted: the first frame of an+ /// arriving view rasterises every glyph it contains and grows the atlas+ /// for them, and charging that to the transition would spend most of it+ /// on a picture nobody has seen yet.+ fn begin_content_view_fade(&mut self, closing: bool) {+ self.begin_content_view_fade_to(closing, None);+ }++ fn begin_content_view_fade_to(&mut self, closing: bool, destination: Option<RectF>) {+ let now = Instant::now();+ let ghost = closing.then(|| self.content_view_last_frame.take()).flatten();+ if closing && ghost.is_none() {+ // Nothing was ever composited for this view -- it opened and+ // closed inside a single frame. There is no picture to take away.+ self.content_view_fade = None;+ return;+ }+ let (from, to) = if closing { (1.0, 0.0) } else { (0.0, 1.0) };+ // A toggle can land while the previous one is still running. Departing+ // from where each value currently is, rather than from the far end, is+ // the difference between a reversal and a jump followed by a reversal.+ let (opacity_from, travel_from, chrome_from) = self+ .content_view_fade+ .as_ref()+ .map(|fade| {+ (+ fade.opacity.value(now),+ fade.travel.value(now),+ fade.chrome_travel.value(now),+ )+ })+ .unwrap_or((from, from, from));+ // Time the reversal by how far it actually has to go. Replaying the+ // full duration to cover the last tenth of a journey reads as the+ // animation having stalled; the floor keeps a near-complete one from+ // snapping.+ let span = |start: f32| ((to - start).abs()).clamp(0.25, 1.0);+ self.content_view_fade = Some(crate::termwindow::content_view::ContentViewFade {+ opacity: crate::ui::anim::Timeline::new(+ now,+ opacity_from,+ to,+ CONTENT_VIEW_FADE.mul_f32(span(opacity_from)),+ crate::ui::anim::Easing::Smooth,+ ),+ travel: crate::ui::anim::Timeline::new(+ now,+ travel_from,+ to,+ CONTENT_VIEW_TRAVEL.mul_f32(span(travel_from)),+ crate::ui::anim::Easing::OutCubic,+ ),+ // Opening, the frame is seen leaving before the terminal starts+ // crossing; closing, it comes back only once the terminal has+ // landed. Same two events, opposite order, so the delay swaps ends.+ chrome_travel: crate::ui::anim::Timeline::delayed(+ now,+ chrome_from,+ to,+ if closing { CHROME_RETURN_DELAY } else { Duration::ZERO },+ CONTENT_VIEW_CHROME_TRAVEL.mul_f32(span(chrome_from)),+ crate::ui::anim::Easing::OutCubic,+ ),+ chrome: None,+ ghost,+ flight: None,+ landing: None,+ pending_destination: destination,+ started_at: now,+ });+ // Input is held for the duration, so a press that is still waiting for+ // its release must not be left half-finished: the release would be+ // swallowed and the drag would resume against the next stray motion.+ self.dragging = None;+ }+pub(crate) fn close_content_view(&mut self) {if let Some(id) = self.content_view_response_tab_id@@ -4605,7 +4870,26 @@ impl TermWindow {let Some(idx) = self.content_views.iter().position(|tab| tab.id == id) else {return;};+ let was_full_window = matches!(+ self.content_views[idx].view.presentation(),+ ContentViewPresentation::FullWindow+ );+ // Ask, while the view still exists, where the terminal it is giving+ // the window back to was sitting. After the removal there is nobody+ // left to answer.+ let departing_destination = Mux::get()+ .get_active_tab_for_window(self.mux_window_id)+ .map(|tab| tab.tab_id())+ .and_then(|tab_id| self.content_views[idx].view.terminal_landing_rect(tab_id));+ // Deliberately not gated on `was_foreground`: some close paths clear+ // the active id before removing the view, and a view that had been+ // painting is on screen whether or not it still holds that id. Having+ // a recorded frame is the evidence that matters.+ let was_on_screen = was_full_window && self.content_view_last_frame.is_some();self.content_views.remove(idx);+ if was_on_screen {+ self.begin_content_view_fade_to(true, departing_destination);+ }if was_foreground {self.active_content_view_id = self@@ -4737,7 +5021,19 @@ impl TermWindow {let active_workspace = self.current_mux_workspace().unwrap_or_else(|| Mux::get().active_workspace());- let host_preview_aspect = if self.terminal_size.pixel_height > 0 {+ // A card is a picture of the space the terminal occupies on+ // screen, and that is also what the opening transition flies from:+ // `terminal_content_rect`, grid plus padding. Sizing the card from+ // the bare grid instead left the two ends measuring different+ // rectangles of the same terminal -- the flight arrived stretched+ // by whatever share the padding held, non-uniformly, because the+ // card it landed in had never accounted for it.+ let content = self.terminal_content_rect();+ let host_preview_aspect = if content.size.height > 0.0+ && content.size.width > 0.0+ {+ content.size.width / content.size.height+ } else if self.terminal_size.pixel_height > 0 {self.terminal_size.pixel_width as f32 / self.terminal_size.pixel_height as f32} else {let width = self.terminal_size.cols as f32diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 0de596e8..e65e3700 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1500,10 +1500,11 @@ impl super::TermWindow {/// Release the pointer-ownership bookkeeping for a `Release` that is/// about to be consumed by an early return.///- /// `mouse_event_impl` normally clears these in its `Release` arm, but two- /// context-menu paths return before reaching it: the suppressed release- /// that follows a menu choice, and any release delivered while a menu is- /// open. Suppressing the *action* is intended; forgetting that the button+ /// `mouse_event_impl` normally clears these in its `Release` arm, but+ /// three paths return before reaching it: the suppressed release that+ /// follows a menu choice, any release delivered while a menu is open, and+ /// any release that lands while a full-window view is transitioning.+ /// Suppressing the *action* is intended; forgetting that the button/// physically came up is not. Left armed, `current_mouse_capture` and/// `current_mouse_buttons` stay set for the rest of the session and/// silently veto every guard that tests them -- which disabled the@@ -1525,6 +1526,18 @@ impl super::TermWindow {pub fn mouse_event_impl(&mut self, event: MouseEvent, context: &dyn WindowOps) {log::trace!("{:?}", event);+ // See `key_event_impl`: nothing on screen during a transition is live,+ // including the card layout a click would be aiming at, which is still+ // moving.+ if self.content_view_transition_running() {+ // Suppressing the action is the point; forgetting that the button+ // physically came up is not. A press held across the start of a+ // transition -- holding a card and hitting Escape, say -- would+ // otherwise leave the pointer bookkeeping armed, and every guard+ // that tests it reads as if the button were still down.+ self.release_pointer_ownership(&event);+ return;+ }let pane = self.get_active_pane_or_overlay();if self.frontend_handoff_consumed_press && matches!(event.kind, WMEK::Release(_)) {@@ -1961,9 +1974,16 @@ impl super::TermWindow {let py = event.coords.y as f32;let area = self.content_view_area();if px >= area.min_x() && px < area.max_x() && py >= area.min_y() && py < area.max_y() {- let resp = self- .active_content_view_mut()- .map(|v| v.on_mouse(px, py, event.kind));+ let resp = self.active_content_view_mut().map(|v| {+ if matches!(event.kind, WMEK::VertWheel(_) | WMEK::HorzWheel(_)) {+ // Pixel deltas and scroll phases do not survive the+ // trip through `MouseEventKind`; hand the view the+ // whole event so it can scroll like a trackpad.+ v.on_wheel(px, py, &event)+ } else {+ v.on_mouse(px, py, event.kind)+ }+ });if let Some(resp) = resp {self.handle_content_response(resp);}diff --git a/wezterm-gui/src/termwindow/onboarding.rs b/wezterm-gui/src/termwindow/onboarding.rsindex 81bbadc1..83c87cb6 100644--- a/wezterm-gui/src/termwindow/onboarding.rs+++ b/wezterm-gui/src/termwindow/onboarding.rs@@ -5,6 +5,7 @@ use crate::quad::TripleLayerQuadAllocator;use crate::termwindow::content_view::{ContentView, ContentViewResponse};use crate::termwindow::ui::icons::SvgIcon;use crate::termwindow::TermWindow;+use crate::ui::anim::Easing;use crate::ui::{draw_scrollbar, draw_toggle, rect, wheel_delta_pixels, ControlState, DrawContext,InteractionState, ScrollState, UiContext, UiPalette, UiTokens, WidgetKind,@@ -546,11 +547,6 @@ impl OnboardingView {Duration::from_millis(TRANSITION_MS)}- fn ease_in_out(t: f32) -> f32 {- let t = t.clamp(0.0, 1.0);- t * t * (3.0 - 2.0 * t)- }-fn transition_t(&self) -> Option<f32> {self.transition.map(|transition| {let elapsed = transition.started_at.elapsed();@@ -1156,7 +1152,7 @@ impl OnboardingView {if let (Some(transition), Some(raw_t)) = (self.transition, self.transition_t()) {let from = transition.from.index() as f32;let to = transition.to.index() as f32;- from + (to - from) * Self::ease_in_out(raw_t)+ from + (to - from) * Easing::Smooth.apply(raw_t)} else {self.step.index() as f32};diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 463d4bdd..ffbd0f3d 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -5,9 +5,10 @@ use crate::termwindow::{RenderFrame, TermWindowNotif};use crate::ui::{DrawContext, UiPalette};use ::window::bitmaps::atlas::OutOfTextureSpace;use ::window::color::LinearRgba;+use ::window::RectF;use ::window::WindowOps;use anyhow::Context;-use mux::renderable::StableCursorPosition;+use mux::renderable::{RenderableDimensions, StableCursorPosition};use mux::tab::SplitDirection;use smol::Timer;use std::collections::hash_map::DefaultHasher;@@ -15,9 +16,26 @@ use std::hash::{Hash, Hasher};use std::time::{Duration, Instant};use wezterm_font::ClearShapeCache;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;+/// 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.+const MAX_PREVIEW_SCALE_STEPS: usize = 12;+/// How far a thumbnail may be stretched on one axis to undo the proportions+/// lost when a cell is rounded to whole pixels. Enough to cover that rounding+/// at the sizes cards use; far short of reshaping a terminal that is honestly+/// a different shape.+const MAX_PREVIEW_ASPECT_TRIM: f32 = 1.15;+/// Ceiling on enlarging a thumbnail to fill its card. Only ever closes the gap+/// left by whole-pixel cells, which is under one cell's worth.+const MAX_PREVIEW_FILL: f32 = 1.5;++/// Height of the pane layer divider the tab bar draws below itself, in the same+/// device pixels the divider quad uses. Kept in step with `fancy_tab_bar`.+const TAB_BAR_SEAM_HEIGHT: f32 = 1.0;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);@@ -28,6 +46,43 @@ fn quantized_terminal_preview_extent(extent: f32, dpi: usize) -> f32 {}}+/// How much to stretch a laid-out grid, per axis, so it fills its card.+///+/// The font scale a thumbnail settles on lands on whole pixels -- a cell is+/// 6px or 7px and nothing between -- so the grid it builds routinely stops+/// short of the card, by up to a whole cell across the full width. Worse,+/// rounding does not preserve a cell's proportions: a real 19x41 cell becomes+/// 6x14, which is 8% narrow for its height, and a grid of narrow cells is the+/// wrong *shape* for its card however uniformly it is scaled. It fills the+/// height and leaves a bare strip down the side.+///+/// So: enlarge uniformly as far as both axes allow, then let the short axis+/// catch up by a bounded amount. That second step undoes the rounding rather+/// than inventing a distortion. The bound is what keeps it honest -- a card+/// can be showing a terminal from another window whose grid is a genuinely+/// different shape, and that difference is not ours to erase.+fn preview_fill_factors(+ grid_width: f32,+ grid_height: f32,+ area_width: f32,+ area_height: f32,+) -> (f32, f32) {+ if !(grid_width > 0.0 && grid_height > 0.0 && area_width > 0.0 && area_height > 0.0) {+ return (1.0, 1.0);+ }+ let want_x = area_width / grid_width;+ let want_y = area_height / grid_height;+ let smaller = want_x.min(want_y);+ let uniform = smaller.clamp(1.0, MAX_PREVIEW_FILL);+ // Measured against what both axes wanted, not against the capped uniform:+ // dividing by the cap makes the ratio enormous whenever the card is much+ // larger than the grid, and then both axes take the full trim -- turning a+ // bounded uniform fill into an unbounded one, for a grid that was already+ // the right shape.+ let trim = |want: f32| (want / smaller).clamp(1.0, MAX_PREVIEW_ASPECT_TRIM);+ (uniform * trim(want_x), uniform * trim(want_y))+}+fn minimum_terminal_preview_scale(font_size: f64, dpi: usize, global_scale: f64) -> f64 {let global_scale = global_scale.max(1.0 / TERMINAL_PREVIEW_SCALE_BUCKETS_PER_UNIT);if !font_size.is_finite() || font_size <= 0.0 || dpi == 0 {@@ -47,12 +102,63 @@ fn quantize_terminal_preview_scale_down(scale: f64, minimum: f64) -> f64 {.max(minimum)}+/// Recover a pane's font-size ratio from the terminal geometry captured in+/// the snapshot. `Tab::get_size` is expressed using the root grid's cell+/// metrics, while each pane's pixel dimensions use that pane's own metrics.+/// Comparing their effective cell sizes preserves pane-local font scaling+/// without reaching back into another GUI window's mutable pane state.+fn terminal_preview_pane_scale_ratio(+ tab_size: TerminalSize,+ pane_dims: RenderableDimensions,+) -> f64 {+ fn ratio(+ pane_pixels: usize,+ pane_cells: usize,+ root_pixels: usize,+ root_cells: usize,+ ) -> Option<f64> {+ if pane_pixels == 0 || pane_cells == 0 || root_pixels == 0 || root_cells == 0 {+ return None;+ }+ let pane_cell = pane_pixels as f64 / pane_cells as f64;+ let root_cell = root_pixels as f64 / root_cells as f64;+ let ratio = pane_cell / root_cell;+ ratio.is_finite().then_some(ratio)+ }++ let width_ratio = ratio(+ pane_dims.pixel_width,+ pane_dims.cols,+ tab_size.pixel_width,+ tab_size.cols,+ );+ let height_ratio = ratio(+ pane_dims.pixel_height,+ pane_dims.viewport_rows,+ tab_size.pixel_height,+ tab_size.rows,+ );++ // Start from the larger axis. The raster-metric correction in the paint+ // path then scales down to the largest font that fits both axes, avoiding+ // a permanently under-filled pane due to integer font metrics.+ match (width_ratio, height_ratio) {+ (Some(width), Some(height)) => width.max(height),+ (Some(width), None) => width,+ (None, Some(height)) => height,+ (None, None) => 1.0,+ }+ .clamp(0.25, 4.0)+}+#[cfg(test)]mod terminal_preview_tests {use super::{minimum_terminal_preview_scale, quantize_terminal_preview_scale_down,- quantized_terminal_preview_extent,+ quantized_terminal_preview_extent, terminal_preview_pane_scale_ratio,};+ use mux::renderable::RenderableDimensions;+ use wezterm_term::TerminalSize;#[test]fn preview_extent_uses_four_logical_pixel_buckets() {@@ -76,6 +182,37 @@ mod terminal_preview_tests {minimum);}++ #[test]+ fn preview_recovers_a_pane_local_font_scale_from_its_cell_geometry() {+ let tab_size = TerminalSize {+ rows: 40,+ cols: 100,+ pixel_width: 1_000,+ pixel_height: 800,+ dpi: 144,+ };+ let pane_dims = RenderableDimensions {+ cols: 40,+ viewport_rows: 12,+ pixel_width: 600,+ pixel_height: 360,+ ..RenderableDimensions::default()+ };++ assert_eq!(terminal_preview_pane_scale_ratio(tab_size, pane_dims), 1.5);+ }++ #[test]+ fn preview_uses_the_default_scale_when_cell_geometry_is_unavailable() {+ assert_eq!(+ terminal_preview_pane_scale_ratio(+ TerminalSize::default(),+ RenderableDimensions::default()+ ),+ 1.0+ );+ }}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -106,7 +243,7 @@ impl crate::TermWindow {self.filled_rectangle(layers, 0, area, palette.window_bg).context("frontend handoff opaque background")?;- let font_size = crate::native_settings::home_font_size(&crate::native_settings::load());+ let font_size = crate::native_settings::home_font_size(&crate::native_settings::load_shared());let title_font = self.fonts.title_font_with_size(font_size + 2.0)?;let hint_font = self.fonts.title_font_with_size(font_size)?;let metrics = crate::utilsprites::RenderMetrics::with_font_metrics(&title_font.metrics());@@ -323,10 +460,31 @@ impl crate::TermWindow {}) = err.root_cause().downcast_ref::<OutOfTextureSpace>(){let result = if pass == 0 {- // Let's try clearing out the atlas and trying again- // self.clear_texture_atlas()- log::trace!("recreate_texture_atlas");- self.recreate_texture_atlas(Some(current_size))+ // Grow while there is headroom, rather than+ // clearing in place.+ //+ // Clearing answers "the atlas is full of glyphs we+ // no longer need". It is the wrong answer to "the+ // working set does not fit": the frame that+ // overflowed fits once the atlas is empty, so this+ // never reached the growth branch below, and the+ // next frame that wants the same glyphs overflows+ // again. Toggling the overview cleared the atlas+ // every single time, re-rasterising every glyph on+ // screen -- and taking the recorded transition+ // frames, whose texture coordinates the rebuild+ // invalidates, with it.+ let grown = size.min(crate::termwindow::MAX_GROWN_ATLAS_SIZE);+ if grown > current_size {+ log::trace!("grow texture atlas {current_size} -> {grown}");+ self.recreate_texture_atlas(Some(grown))+ } else {+ // At the ceiling: clearing is all that is left,+ // and it is also what reclaims the one-off+ // glyphs a closed overview leaves behind.+ log::trace!("recreate_texture_atlas at {current_size}");+ self.recreate_texture_atlas(Some(current_size))+ }} else {log::trace!("grow texture atlas to {}", size);self.recreate_texture_atlas(Some(size))@@ -339,6 +497,7 @@ impl crate::TermWindow {// waiting for its first source capture; the retry can// repaint that source and complete the pending switch.self.recover_workspace_space_swipe_after_atlas_recreation();+ self.discard_content_view_captures_after_atlas_recreation();if let Err(err) = result {self.allow_images = match self.allow_images {@@ -421,11 +580,360 @@ impl crate::TermWindow {/// Paint the active content view into the content area (right of the/// sidebar, below the tab bar).+ /// Advance a full-window view's arrival or departure.+ fn advance_content_view_fade(&mut self, now: Instant) {+ let Some(fade) = self.content_view_fade.as_mut() else {+ return;+ };+ // Once the travelling terminal has closed to within touching distance+ // of its card, hand the card back its own thumbnail and dissolve the+ // recording into it. Both pictures are then on screen at the same+ // rectangle, which is the only arrangement in which a dissolve reads as+ // one thing settling rather than as two things overlapping.+ let mut landed = false;+ if fade.landing.is_none() && fade.travel.target() >= 0.5 {+ if let Some(flight) = fade.flight.as_ref() {+ if crate::termwindow::content_view::flight_is_landing(+ flight.source,+ flight.destination,+ fade.travel.value(now),+ ) {+ fade.landing = Some(crate::ui::anim::Timeline::new(+ now,+ 1.0,+ 0.0,+ crate::termwindow::CONTENT_VIEW_LANDING_FADE,+ crate::ui::anim::Easing::Smooth,+ ));+ landed = true;+ }+ }+ }+ let travelling = fade.travel.advance(now)+ | fade.chrome_travel.advance(now)+ | fade.landing.as_mut().is_some_and(|fade| fade.advance(now));+ if landed {+ // Painted after this runs, so the thumbnail appears underneath the+ // dissolve on this very frame rather than one frame late.+ if let Some(view) = self.active_content_view_mut() {+ view.set_terminal_in_flight(None);+ }+ }+ let Some(fade) = self.content_view_fade.as_mut() else {+ return;+ };+ if fade.opacity.advance(now) || travelling {+ // Unnamed interval, as with the Space swipe: the backend paces+ // repaints to this display's refresh rate.+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ } else {+ self.content_view_fade = None;+ // 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;+ if let Some(view) = self.active_content_view_mut() {+ view.set_terminal_in_flight(None);+ }+ self.invalidate_window();+ }+ }++ fn content_view_fade_opacity(&self, now: Instant) -> Option<f32> {+ self.content_view_fade+ .as_ref()+ .map(|fade| fade.opacity.value(now))+ }++ fn window_rect(&self) -> RectF {+ euclid::rect(+ 0.0,+ 0.0,+ self.dimensions.pixel_width as f32,+ self.dimensions.pixel_height as f32,+ )+ }++ fn clip_of(&self, rect: RectF) -> QuadClipRect {+ QuadClipRect::from_top_left_pixels(+ rect.min_x(),+ rect.min_y(),+ rect.max_x(),+ rect.max_y(),+ &self.dimensions,+ )+ }++ /// Replay the recorded terminal at the size its travel has reached.+ ///+ /// It rides above the view: the terminal is shrinking *into* the card, so+ /// it has to be seen crossing the grid that is arriving underneath it. The+ /// last stretch is spent fading, because what it lands on is the card's+ /// own thumbnail of the same terminal drawn from the same snapshot -- near+ /// enough to blend into, not near enough to cut to.+ fn paint_content_view_flight(&self) -> anyhow::Result<()> {+ let now = Instant::now();+ let Some(fade) = self.content_view_fade.as_ref() else {+ return Ok(());+ };+ let Some(flight) = fade.flight.as_ref() else {+ return Ok(());+ };+ // The terminal grid is what travels, and the card's own thumbnail is+ // what it lands on, so both ends of the journey are the same picture.+ //+ // The source is the one recorded with the surface, not the terminal's+ // rectangle now: these quads hold the positions they were authored at.+ let source = flight.source;+ // The destination, on the other hand, is re-asked every frame. An+ // arriving overview keeps laying itself out while the terminal crosses+ // the window -- closing a card reflows the grid underneath it -- and a+ // rectangle sampled once meant landing on where the card used to be+ // and then jumping to where it is.+ let destination = flight+ .tab_id+ .and_then(|tab_id| {+ self.active_content_view()+ .and_then(|view| view.terminal_landing_rect(tab_id))+ })+ .unwrap_or(flight.destination);+ let travel = fade.travel.value(now);+ let target = crate::termwindow::content_view::flight_rect_at(source, destination, travel);+ // Opaque for all of the journey but the landing.+ //+ // An earlier version faded over the last tenth of the *distance*, and+ // ease-out spends its time unevenly: that tenth is nearly half of the+ // duration, so the fade ran translucent for seven frames at a size+ // 3-18% off the card it was landing on. Worse, the card drew no+ // thumbnail while its terminal was in flight, so there was nothing on+ // the far side to dissolve into -- only the flat panel colour. Two+ // misaligned pictures with a panel showing between them is exactly+ // what "it looks like two layers" meant.+ //+ // Both of those are now addressed rather than avoided: the window is+ // bounded by size instead of by distance, and the card is handed its+ // thumbnail back as the window opens. See `flight_is_landing`.+ let opacity = fade.landing.as_ref().map_or(1.0, |fade| fade.value(now));++ let gl_state = self.render_state.as_ref().unwrap();+ let layer = gl_state+ .layer_for_zindex(crate::termwindow::CONTENT_VIEW_FLIGHT_ZINDEX)+ .context("content view flight layer")?;+ let mut layers = layer.quad_allocator();+ flight.surface.apply_to_scaled(+ &mut layers,+ self.clip_of(source),+ self.clip_of(target),+ self.clip_of(target),+ opacity,+ )+ }++ /// Record the window frame in three pieces, one per edge it can leave by.+ fn record_content_view_chrome(&mut self) -> anyhow::Result<()> {+ let mut chrome = crate::termwindow::content_view::ContentViewChrome::default();+ {+ let mut left = TripleLayerQuadAllocator::Heap(&mut chrome.left);+ self.paint_workspace_sidebar(&mut left)+ .context("record workspace sidebar")?;+ }+ {+ let mut right = TripleLayerQuadAllocator::Heap(&mut chrome.right);+ self.paint_right_sidebar(&mut right)+ .context("record right sidebar")?;+ }+ if self.show_tab_bar {+ let mut top = TripleLayerQuadAllocator::Heap(&mut chrome.top);+ self.paint_tab_bar(&mut top).context("record tab bar")?;+ }+ if let Some(fade) = self.content_view_fade.as_mut() {+ fade.chrome = Some(chrome);+ }+ Ok(())+ }++ /// Slide each piece of the frame off the edge it belongs to.+ ///+ /// Anchored motion rather than a fade: a panel that lives against the left+ /// edge reads as leaving when it goes left, and as merely disappearing+ /// when it dissolves in place.+ fn paint_content_view_chrome(&self) -> anyhow::Result<()> {+ let now = Instant::now();+ let Some(fade) = self.content_view_fade.as_ref() else {+ return Ok(());+ };+ let Some(chrome) = fade.chrome.as_ref() else {+ return Ok(());+ };+ let gone = fade.chrome_travel.value(now).clamp(0.0, 1.0);+ let window = self.window_rect();+ let terminal = self.terminal_content_rect();+ let left_width = terminal.min_x() - window.min_x();+ let right_width = window.max_x() - terminal.max_x();+ // The tab bar paints one row past its own band. The pane layer divider+ // in `fancy_tab_bar` sits at the seam -- `row_y + row_height`, which is+ // the terminal's first row, not the tab bar's last -- so sliding by the+ // terminal's top inset alone parks exactly that row against the top of+ // the window and leaves it there. Windowed, the rounded corner mask+ // hides most of it; fullscreen has no corners and it reads as a+ // hairline that never leaves.+ let top_height = terminal.min_y() - window.min_y() + TAB_BAR_SEAM_HEIGHT;++ let gl_state = self.render_state.as_ref().unwrap();+ let layer = gl_state+ .layer_for_zindex(crate::termwindow::CONTENT_VIEW_FLIGHT_ZINDEX)+ .context("content view chrome layer")?;+ let mut layers = layer.quad_allocator();+ let full = self.clip_of(window);+ for (surface, dx, dy) in [+ (&chrome.left, -left_width * gone, 0.0),+ (&chrome.right, right_width * gone, 0.0),+ (&chrome.top, 0.0, -top_height * gone),+ ] {+ let shifted = window.translate(euclid::vec2(dx, dy));+ surface.apply_to_scaled(&mut layers, full, self.clip_of(shifted), full, 1.0)?;+ }+ Ok(())+ }++ /// Work out where the terminal is heading and hand it the recorded frame.+ ///+ /// Called after the view has painted, because the destination comes from+ /// the view's layout and the layout is produced by painting. This lands on+ /// the transition's first frame, which the timelines have deliberately not+ /// started counting yet.+ fn resolve_content_view_flight(&mut self, surface: HeapQuadAllocator) {+ let tab_id = mux::Mux::get()+ .get_active_tab_for_window(self.mux_window_id)+ .map(|tab| tab.tab_id());+ // A closing transition recorded its destination before the view was+ // torn down; an opening one asks the view that has just laid itself+ // out.+ let recorded = self+ .content_view_fade+ .as_ref()+ .and_then(|fade| fade.pending_destination);+ let destination = recorded+ .or_else(|| {+ tab_id.and_then(|tab_id| {+ self.active_content_view()+ .and_then(|view| view.terminal_landing_rect(tab_id))+ })+ })+ .unwrap_or_else(|| self.window_rect());+ // The view must not draw its own copy of a terminal that is currently+ // crossing the window towards it.+ if destination != self.window_rect() {+ if let Some(view) = self.active_content_view_mut() {+ view.set_terminal_in_flight(tab_id);+ }+ }+ let source = self.terminal_content_rect();+ if let Some(fade) = self.content_view_fade.as_mut() {+ fade.flight = Some(crate::termwindow::content_view::ContentViewFlight {+ surface,+ source,+ destination,+ tab_id,+ });+ }+ }++ fn surface_clip(&self) -> QuadClipRect {+ QuadClipRect::from_top_left_pixels(+ 0.0,+ 0.0,+ self.dimensions.pixel_width as f32,+ self.dimensions.pixel_height as f32,+ &self.dimensions,+ )+ }++ /// Composite a recorded surface above everything the terminal drew.+ ///+ /// The three quad layers are a global z-order, not per-surface depth:+ /// every layer-0 quad in the window is drawn, then every layer-1 quad,+ /// then every layer-2 quad. Appending a second surface into the same+ /// layers therefore interleaves the two -- terminal text, which lives in+ /// layer 1, lands on top of a view's card backgrounds in layer 0. A+ /// separate z-index is a separate set of passes, so the whole surface+ /// arrives above the whole terminal.+ fn composite_above_terminal(+ &self,+ surface: &HeapQuadAllocator,+ opacity: f32,+ ) -> anyhow::Result<()> {+ let gl_state = self.render_state.as_ref().unwrap();+ let layer = gl_state+ .layer_for_zindex(crate::termwindow::CONTENT_VIEW_FADE_ZINDEX)+ .context("content view transition layer")?;+ let mut layers = layer.quad_allocator();+ surface.apply_to_clipped(&mut layers, self.surface_clip(), opacity)+ }++ /// Paint the foreground view, recording the frame so that closing it later+ /// has a picture to take away, and compositing it at the transition's+ /// opacity while one is running.+ fn paint_content_view_composited(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ ) -> anyhow::Result<()> {+ if !self.content_view_is_full_window() {+ // Only full-window views transition, and only they are worth the+ // extra copy through a heap.+ return self.paint_content_view(layers);+ }++ // One surface, recorded in one pass: the view, its thumbnails and the+ // 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 mut heap = HeapQuadAllocator::default();+ {+ let mut recorded = TripleLayerQuadAllocator::Heap(&mut heap);+ self.paint_content_view(&mut recorded)?;+ let mut chrome_items = self+ .paint_full_window_chrome(&mut recorded)+ .context("paint full-window client chrome")?;+ self.ui_items.append(&mut chrome_items);+ }+ 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)?,+ // 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);+ Ok(())+ }++ /// Composite the recorded frame of a view that has already been closed.+ fn paint_departing_content_view(&mut self) -> anyhow::Result<()> {+ let opacity = self+ .content_view_fade_opacity(Instant::now())+ .unwrap_or(0.0);+ let Some(ghost) = self+ .content_view_fade+ .as_ref()+ .and_then(|fade| fade.ghost.as_ref())+ else {+ return Ok(());+ };+ let gl_state = self.render_state.as_ref().unwrap();+ let layer = gl_state+ .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)+ }+pub fn paint_content_view(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,) -> anyhow::Result<()> {- let settings = crate::native_settings::load();+ let settings = crate::native_settings::load_shared();let font_weight = crate::native_settings::settings_font_weight(&settings);let active_content_view_idx = self.active_content_view_index();let typography = active_content_view_idx@@ -486,11 +994,24 @@ impl crate::TermWindow {self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(blink_ms)));}+ // Measured before the view is borrowed, and re-measured every frame:+ // the terminal area behind a full-window view keeps changing shape+ // while the view is up.+ let host_preview_aspect = {+ let content = self.terminal_content_rect();+ if content.size.width > 0.0 && content.size.height > 0.0 {+ content.size.width / content.size.height+ } else {+ 0.0+ }+ };+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_host_preview_aspect(host_preview_aspect);view.paint_surface_background(&ctx, layers, surface, palette)?;view.paint(&ctx,@@ -535,20 +1056,33 @@ impl crate::TermWindow {layers: &mut TripleLayerQuadAllocator<'_>,previews: &[TerminalPreviewRequest],) -> anyhow::Result<()> {- for preview in previews {- self.paint_terminal_preview(layers, preview)?;- }- Ok(())+ // 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)?;+ }+ Ok(())+ })();+ heap.recycle();+ *self.preview_quad_heap.borrow_mut() = heap;+ result}fn paint_terminal_preview(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,preview: &TerminalPreviewRequest,+ heap: &mut HeapQuadAllocator,) -> anyhow::Result<()> {- let mut heap = HeapQuadAllocator::default();+ heap.recycle();{- let mut clipped_layers = TripleLayerQuadAllocator::Heap(&mut heap);+ let mut clipped_layers = TripleLayerQuadAllocator::Heap(heap);self.paint_terminal_preview_unclipped(&mut clipped_layers, preview)?;}let clip = QuadClipRect::from_top_left_pixels(@@ -558,7 +1092,7 @@ impl crate::TermWindow {preview.clip.max_y(),&self.dimensions,);- heap.apply_to_clipped(layers, clip)+ heap.apply_to_clipped(layers, clip, 1.0)}fn paint_terminal_preview_unclipped(@@ -609,6 +1143,16 @@ impl crate::TermWindow {.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.+ 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@@ -631,22 +1175,79 @@ impl crate::TermWindow {}}- let still_too_wide =- tab_size.cols as f32 * metrics.cell_size.width.max(1) as f32 > bucketed_width;- let still_too_tall =- tab_size.rows as f32 * metrics.cell_size.height.max(1) as f32 > bucketed_height;- if (still_too_wide || still_too_tall) && quantized_scale > minimum_scale {- quantized_scale = minimum_scale;+ // Step down a bucket at a time until the grid fits.+ //+ // This used to answer any remaining overflow by dropping straight to+ // `minimum_scale`, which is a cliff rather than a correction: being one+ // pixel too tall after the analytical estimate is a rounding artefact+ // of integer raster metrics, and paying for it with the smallest font+ // the preview allows collapsed the whole thumbnail to 1x3px cells --+ // a thumb-sized smear of text in the corner of an otherwise empty card.+ // Reachable as soon as a card is tall enough relative to its terminal,+ // which is what opening a sidebar does.+ //+ // The step is bounded: each iteration builds a FontConfiguration, and+ // the estimate is close enough that this normally settles in one.+ for _ in 0..MAX_PREVIEW_SCALE_STEPS {+ if quantized_scale <= minimum_scale {+ break;+ }+ let too_wide =+ tab_size.cols as f32 * metrics.cell_size.width.max(1) as f32 > bucketed_width;+ let too_tall =+ tab_size.rows as f32 * metrics.cell_size.height.max(1) as f32 > bucketed_height;+ if !too_wide && !too_tall {+ break;+ }+ let next = quantize_terminal_preview_scale_down(+ quantized_scale - 1.0 / TERMINAL_PREVIEW_SCALE_BUCKETS_PER_UNIT,+ minimum_scale,+ );+ if next >= quantized_scale {+ break;+ }+ quantized_scale = next;(font_config, metrics) = self.pane_font_resources(quantized_scale)?;}+ // Whatever the search settled on is what a drag will hold to. Recorded+ // even mid-drag, because the stepping loop above may still have had to+ // come down to make the grid fit a card that has since shrunk.+ self.preview_scale_hold+ .borrow_mut()+ .insert(scale_key, quantized_scale);+let cell_width = metrics.cell_size.width.max(1) as f32;let cell_height = metrics.cell_size.height.max(1) as f32;++ // Close the gap left by whole-pixel cells.+ //+ // A thumbnail cell is 6px or 7px and nothing in between, and the scale+ // search can only round down, so the grid routinely stops a whole cell+ // short across its full width -- 87 columns at 6px is 522px inside a+ // 610px card, a bare strip down the right-hand side. The per-pane+ // position transform below already maps rendered text into whatever+ // rect the layout asks for; it simply had nothing to do, because the+ // layout asked for exactly the size the text already was. Stretching+ // the layout is what gives it something to do. One factor for both+ // axes, so this enlarges the picture rather than distorting it.+ let (fill_x, fill_y) = preview_fill_factors(+ tab_size.cols as f32 * cell_width,+ tab_size.rows as f32 * cell_height,+ preview.area.size.width,+ preview.area.size.height,+ );+ let cell_width = cell_width * fill_x;+ let cell_height = cell_height * fill_y;// Terminal content begins at the same top-left origin as the real// terminal. Any remainder stays on the right/bottom and is visually// continuous with the background painted above.let origin_x = preview.area.origin.x;let origin_y = preview.area.origin.y;+ // One nav bar height for every pane in the tab, because that is how the+ // terminal draws it.+ let nav_bar_height = self.pane_nav_bar_height() as f32;+let gl_state = self.render_state.as_ref().unwrap();let white_space = gl_state.util_sprites.white_space.texture_coords();let filled_box = gl_state.util_sprites.filled_box.texture_coords();@@ -660,14 +1261,15 @@ 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);- if let Some(visible) = pane_rect.intersection(&preview.clip) {- self.filled_rectangle(- layers,- 0,- visible,- palette.resolve_bg(ColorAttribute::Default).to_linear(),- )?;- }+ let Some(pane_clip) = pane_rect.intersection(&preview.clip) else {+ continue;+ };+ self.filled_rectangle(+ layers,+ 0,+ pane_clip,+ palette.resolve_bg(ColorAttribute::Default).to_linear(),+ )?;let source_dims = pane.dimensions;let rows = pane.rows;@@ -676,12 +1278,59 @@ impl crate::TermWindow {continue;}+ // The real terminal reserves the top of a pane's box for its nav+ // bar and starts the grid below it: `terminal_size_for_positioned_pane`+ // subtracts that height before dividing into rows. `pane.height`+ // is the whole box, so laying the grid out against the box's top+ // edge both lifts the text by the height of a nav bar and stretches+ // it vertically, mapping the same rows onto a taller target. The+ // strip left behind is the picture the terminal shows once its+ // chrome is taken away, which is what a card is.+ // Take the nav bar's real height rather than inferring it from+ // what the grid left over. That leftover is the nav bar *plus* the+ // remainder of dividing the box by a cell, and the remainder+ // depends on each pane's own cell height -- so two panes sharing+ // one nav bar derived strips 22px apart and their text no longer+ // lined up across the split, which it does in the terminal.+ let reserved = pane+ .box_pixel_height+ .saturating_sub(source_dims.pixel_height);+ let nav_fraction = if reserved > 0 && pane.box_pixel_height > 0 {+ (nav_bar_height / pane.box_pixel_height as f32).clamp(0.0, 0.5)+ } else {+ 0.0+ };+ let grid_top = pane_rect.min_y() + pane_height * nav_fraction;+ let grid_height = pane_height * (1.0 - nav_fraction);++ // Pane placement remains in the root grid so every split keeps+ // the same outer frame. Content inside that frame uses the pane's+ // own effective cell size, reconstructed from the immutable+ // snapshot. This is the preview equivalent of the normal pane+ // renderer's `pane_font_resources` path.+ let pane_scale_ratio = terminal_preview_pane_scale_ratio(tab_size, source_dims);+ let pane_scale = quantize_terminal_preview_scale_down(+ quantized_scale * pane_scale_ratio,+ minimum_scale,+ );+ let (pane_font_config, pane_metrics) =+ if pane_scale.to_bits() == quantized_scale.to_bits() {+ (font_config.clone(), metrics)+ } else {+ self.pane_font_resources(pane_scale)?+ };++ let pane_cell_width = pane_metrics.cell_size.width.max(1) as f32;+ let pane_cell_height = pane_metrics.cell_size.height.max(1) as f32;+ let rendered_width = cols as f32 * pane_cell_width;+ let rendered_height = rows as f32 * pane_cell_height;+let mut render_dims = source_dims;render_dims.cols = cols;render_dims.viewport_rows = rows;- render_dims.pixel_width = (cols as f32 * cell_width).round() as usize;- render_dims.pixel_height = (rows as f32 * cell_height).round() as usize;- let rendered_y = pane_y + pane.height.saturating_sub(rows) as f32 * cell_height;+ 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@@ -698,13 +1347,45 @@ impl crate::TermWindow {palette.selection_fg.hash(&mut palette_hasher);palette.selection_bg.hash(&mut palette_hasher);let palette_identity = palette_hasher.finish();- let font_identity = quantized_scale.to_bits()- ^ palette_identity.rotate_left(17)- ^ 0x4c49_5645_5052_4556;-- for (line_idx, line) in pane.lines.iter().enumerate() {- let y = rendered_y + line_idx as f32 * cell_height;- if y + cell_height <= preview.clip.min_y() || y >= preview.clip.max_y() {+ let font_identity =+ pane_scale.to_bits() ^ palette_identity.rotate_left(17) ^ 0x4c49_5645_5052_4556;++ // Map positions as the pane is authored. At thumbnail sizes a+ // cell can only jump from (for example) 3 px to 4 px, so no font+ // 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.+ let source_rect = QuadClipRect::from_top_left_pixels(+ pane_x,+ rendered_y,+ pane_x + rendered_width,+ rendered_y + rendered_height,+ &self.dimensions,+ );+ let target_rect = QuadClipRect::from_top_left_pixels(+ pane_rect.min_x(),+ grid_top,+ pane_rect.max_x(),+ grid_top + grid_height,+ &self.dimensions,+ );+ // Bind the call before asserting on it. `debug_assert!` does not+ // evaluate its argument in release, and this workspace ships+ // release without debug assertions, so writing the call inside the+ // macro meant the transform was never applied in the build users+ // run -- panes were drawn at their authored size and whatever did+ // not fit was clipped away.+ 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);++ for (line_idx, line) in pane.lines.iter().take(rows).enumerate() {+ let y = rendered_y + line_idx as f32 * pane_cell_height;+ if y + pane_cell_height <= source_visible_top || y >= source_visible_bottom {continue;}let shape_hash = self.shape_hash_for_line(line);@@ -712,7 +1393,7 @@ impl crate::TermWindow {RenderScreenLineParams {top_pixel_y: y,left_pixel_x: pane_x,- pixel_width: cols as f32 * cell_width,+ pixel_width: rendered_width,stable_line_idx: Some(pane.resolved_top + line_idx as isize),line,selection: 0..0,@@ -736,8 +1417,8 @@ impl crate::TermWindow {font: None,style: None,use_pixel_positioning: false,- render_metrics: metrics,- font_config: Some(font_config.clone()),+ render_metrics: pane_metrics,+ font_config: Some(pane_font_config.clone()),font_identity,shape_key: Some(LineToEleShapeCacheKey {shape_hash,@@ -763,40 +1444,40 @@ impl crate::TermWindow {&& (cursor_row as usize) < rows&& cursor.x < cols{- let cursor_rect = euclid::rect(- pane_x + cursor.x as f32 * cell_width,- rendered_y + cursor_row as f32 * cell_height,- cell_width,- cell_height,+ 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,+ pane_cell_width,+ pane_cell_height,);- if let Some(cursor_rect) = cursor_rect.intersection(&preview.clip) {- let color = palette.cursor_border.to_linear().mul_alpha(0.72);- let stroke = 1.0_f32.min(cursor_rect.size.width / 2.0);- self.filled_rectangle(- layers,- 2,- euclid::rect(- cursor_rect.origin.x,- cursor_rect.origin.y,- cursor_rect.size.width,- stroke,- ),- color,- )?;- self.filled_rectangle(- layers,- 2,- euclid::rect(- cursor_rect.origin.x,- cursor_rect.max_y() - stroke,- cursor_rect.size.width,- stroke,- ),- color,- )?;- }+ let color = palette.cursor_border.to_linear().mul_alpha(0.72);+ let stroke = 1.0_f32.min(cursor_rect.size.width / 2.0);+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ cursor_rect.origin.x,+ cursor_rect.origin.y,+ cursor_rect.size.width,+ stroke,+ ),+ color,+ )?;+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ cursor_rect.origin.x,+ cursor_rect.max_y() - stroke,+ cursor_rect.size.width,+ stroke,+ ),+ color,+ )?;}}+ let cleared = layers.set_heap_position_transform(None);+ debug_assert!(cleared);}// Preserve split topology in the thumbnail. PositionedSplit is part@@ -851,7 +1532,7 @@ impl crate::TermWindow {&mut self,layers: &mut TripleLayerQuadAllocator<'_>,) -> anyhow::Result<()> {- let settings = crate::native_settings::load();+ let settings = crate::native_settings::load_shared();if !settings.terminal.bottom_quote_enabled {return Ok(());}@@ -918,12 +1599,18 @@ impl crate::TermWindow {.min(max_width);let x = (grid_left + self.terminal_size.pixel_width as f32 - inset - text_width).max(0.0);let y = (grid_bottom + ((gutter_height - quote_height) / 2.0).max(0.0)).max(0.0);+ // Opaque, and deliberately so. These carried `.mul_alpha(0.46)` and+ // `.mul_alpha(0.38)`, but the glyph shader discarded a vertex alpha+ // until it was fixed to honour one, so the quote has always rendered+ // solid and was tuned by eye against that. Keeping the multiplier now+ // that it works would darken shipped output to settle an intent nobody+ // ever saw. The muting lives in the colour itself.let color = match crate::native_settings::effective_appearance() {window::Appearance::Light | window::Appearance::LightHighContrast => {- LinearRgba::with_srgba(80, 80, 90, 255).mul_alpha(0.46)+ LinearRgba::with_srgba(80, 80, 90, 255)}window::Appearance::Dark | window::Appearance::DarkHighContrast => {- LinearRgba::with_srgba(210, 210, 220, 255).mul_alpha(0.38)+ LinearRgba::with_srgba(210, 210, 220, 255)}};@@ -1118,7 +1805,7 @@ impl crate::TermWindow {if label.is_empty() {return Ok(());}- let settings = crate::native_settings::load();+ let settings = crate::native_settings::load_shared();let font_size = crate::native_settings::home_font_size(&settings);let ui_font = self.fonts@@ -1318,6 +2005,7 @@ impl crate::TermWindow {pub fn paint_pass(&mut self) -> anyhow::Result<()> {let frame_now = Instant::now();self.advance_workspace_space_swipe_push(frame_now);+ self.advance_content_view_fade(frame_now);{let gl_state = self.render_state.as_ref().unwrap();for layer in gl_state.layers.borrow().iter() {@@ -1344,7 +2032,21 @@ impl crate::TermWindow {let layer = gl_state.layer_for_zindex(0).context("layer_for_zindex(0)")?;- let mut layers = layer.quad_allocator();+ // The first frame of a transition records the terminal instead of+ // drawing it, and every frame after replays that recording at the size+ // its travel has reached. Redirecting the allocator here catches the+ // whole world -- panes, splits, sidebars, tab bar -- without each of+ // them having to know a transition is running.+ let recording_flight = self+ .content_view_fade+ .as_ref()+ .is_some_and(|fade| fade.flight.is_none());+ let mut flight_capture = HeapQuadAllocator::default();+ let mut layers = if recording_flight {+ TripleLayerQuadAllocator::Heap(&mut flight_capture)+ } else {+ layer.quad_allocator()+ };log::trace!("quad map elapsed {:?}", start.elapsed());metrics::histogram!("quad.map").record(start.elapsed());@@ -1438,8 +2140,29 @@ impl crate::TermWindow {}// When a content view is the foreground it takes over the content area,- // so skip painting the terminal panes / splits.+ // so skip painting the terminal panes / splits -- except while one is+ // arriving or leaving, when both have to be on screen at once for the+ // view to have anything to fade against.let content_view_active = self.content_view_foreground();+ // A transition puts both worlds on screen: the terminal is painted as+ // usual and the view is composited over it at a partial opacity. A+ // closing view is already gone by now, so its side of the transition+ // is a recorded frame rather than a live paint.+ let fading_content_view = self.content_view_fade.is_some();+ // While a transition runs the terminal is a recording: drawn once into+ // `flight_capture` on the opening frame, replayed thereafter.+ //+ // `content_view_active` is false for the whole of a *closing*+ // transition -- the view is removed from `content_views` before the+ // fade is started, so there is no longer an active one to find. Left to+ // `!content_view_active` alone this put the live terminal on screen at+ // full size from the transition's second frame, underneath the+ // recording that was still growing back out of the card. Two terminals,+ // two scales, and anything the terminal world draws once per frame --+ // the bottom quote most visibly, at 38% alpha over itself -- drawn+ // twice. It also made the return look like a dissolve rather than a+ // move, because the picture being travelled towards was already there.+ let paint_terminal_world = (!content_view_active && !fading_content_view) || recording_flight;if !content_view_active {// Takeover remains opaque while this actively polls and hydrates@@ -1450,7 +2173,13 @@ impl crate::TermWindow {let frontend_blocked = !content_view_active && self.frontend_surface_blocked();- if !content_view_active && !frontend_blocked {+ // Everything the terminal registers during a transition sits under a+ // view that is on its way in or out. Leaving those targets live would+ // let a click land on a pane the user is looking at through a+ // half-drawn overview.+ let ui_items_before_terminal = self.ui_items.len();++ if paint_terminal_world && !frontend_blocked {for pos in panes {if pos.is_active {self.update_text_cursor(&pos);@@ -1473,7 +2202,7 @@ impl crate::TermWindow {.context("paint shared unused grid")?;}- if !content_view_active && !frontend_blocked {+ if paint_terminal_world && !frontend_blocked {self.paint_bottom_quote(&mut layers).context("paint_bottom_quote")?;}@@ -1483,20 +2212,42 @@ impl crate::TermWindow {.context("paint frontend handoff overlay")?;}+ if fading_content_view {+ self.ui_items.truncate(ui_items_before_terminal);+ }+if content_view_active {- self.paint_content_view(&mut layers)+ self.paint_content_view_composited(&mut layers).context("paint_content_view")?;+ } else if fading_content_view {+ self.paint_departing_content_view()+ .context("paint departing content view")?;}+ // Only the arriving view answers to the pointer while a transition+ // runs. The chrome painted below belongs to the terminal, which is on+ // screen but on its way behind something, and a click landing there+ // would go somewhere the user is no longer looking.+ let ui_items_after_view = self.ui_items.len();// A full-window ContentView owns all ThinkTerm chrome below the native// title bar. This is presentation-only: sidebar widths/collapse state// and terminal geometry stay unchanged behind the view.- if self.content_view_is_full_window() {- let mut chrome_items = self- .paint_full_window_chrome(&mut layers)- .context("paint full-window client chrome")?;- self.ui_items.append(&mut chrome_items);+ //+ // The window frame stays where it is while the terminal inside it+ // travels, so a transition keeps painting it. Only the terminal grid+ // flies, because the card it is flying into shows a terminal and+ // nothing else -- carrying the sidebar along made the picture that+ // landed and the picture already in the card visibly different things.+ if self.content_view_is_full_window() && !fading_content_view {+ // Recorded into the view's own surface, so the two arrive and+ // leave together.drop(layers);+ } else if fading_content_view {+ drop(layers);+ if recording_flight {+ self.record_content_view_chrome()+ .context("record window frame")?;+ }} else {// Space switching is a left-sidebar interaction. Keep the terminal,// tab bar, right sidebar and window chrome on the live GPU path, then@@ -1714,6 +2465,23 @@ impl crate::TermWindow {drop(chrome_layers);}+ if fading_content_view {+ self.ui_items.truncate(ui_items_after_view);+ }++ if recording_flight {+ // Every allocator borrowing the recording has been dropped, and+ // the view has laid itself out, so it can now say where this+ // terminal is going.+ self.resolve_content_view_flight(flight_capture);+ }+ if fading_content_view {+ self.paint_content_view_chrome()+ .context("paint content view chrome")?;+ self.paint_content_view_flight()+ .context("paint content view flight")?;+ }+let mut layers = layer.quad_allocator();self.paint_window_borders(&mut layers).context("paint_window_borders")?;@@ -1731,3 +2499,86 @@ impl crate::TermWindow {Ok(())}}++#[cfg(test)]+mod tests {+ use super::*;++ /// A card exactly the size of the grid it holds is left alone. This is the+ /// case the fill exists to *not* disturb.+ #[test]+ fn a_grid_that_already_fits_its_card_is_not_touched() {+ let (x, y) = preview_fill_factors(522.0, 504.0, 522.0, 504.0);+ assert_eq!((x, y), (1.0, 1.0));+ }++ /// Whole-pixel cells leave the grid short on both axes; closing that gap is+ /// a uniform enlargement, so the picture grows without changing shape.+ #[test]+ fn a_grid_short_on_both_axes_is_enlarged_without_reshaping() {+ let (x, y) = preview_fill_factors(500.0, 400.0, 550.0, 440.0);+ assert!((x - 1.1).abs() < 1e-4, "{x}");+ assert!((y - x).abs() < 1e-4, "axes diverged: {x} vs {y}");+ }++ /// The case that left a bare strip down the side of every card: rounding+ /// made the cells narrow, so the grid filled the height with room to spare+ /// across. The short axis is allowed to catch up.+ #[test]+ fn the_axis_left_short_by_cell_rounding_catches_up() {+ // Height binds at 1.0; width has 8% of slack, the amount a 19x41 cell+ // loses becoming 6x14.+ let (x, y) = preview_fill_factors(500.0, 400.0, 540.0, 400.0);+ assert!((y - 1.0).abs() < 1e-4, "bound axis moved: {y}");+ assert!((x - 1.08).abs() < 1e-4, "{x}");+ }++ /// A card can be showing a terminal from another window, genuinely a+ /// different shape. Filling the card must not turn it into a different+ /// terminal.+ #[test]+ fn a_terminal_of_a_different_shape_is_not_reshaped_to_fit() {+ // Twice as wide as the card wants: far past anything rounding explains.+ let (x, y) = preview_fill_factors(500.0, 400.0, 1000.0, 400.0);+ assert!((y - 1.0).abs() < 1e-4);+ assert!(+ (x - MAX_PREVIEW_ASPECT_TRIM).abs() < 1e-4,+ "stretched to {x}, past the bound"+ );+ }++ #[test]+ fn enlargement_has_a_ceiling() {+ let (x, y) = preview_fill_factors(100.0, 100.0, 10_000.0, 10_000.0);+ assert!((x - MAX_PREVIEW_FILL).abs() < 1e-4, "{x}");+ assert!((y - MAX_PREVIEW_FILL).abs() < 1e-4, "{y}");+ }++ #[test]+ fn a_degenerate_card_or_grid_asks_for_no_stretch() {+ assert_eq!(preview_fill_factors(0.0, 400.0, 500.0, 400.0), (1.0, 1.0));+ assert_eq!(preview_fill_factors(500.0, 400.0, 0.0, 400.0), (1.0, 1.0));+ assert_eq!(preview_fill_factors(500.0, 0.0, 500.0, 400.0), (1.0, 1.0));+ }++ /// Quantization only ever rounds down, so a grid laid out at the quantized+ /// scale cannot overflow the extent it was measured against.+ #[test]+ fn quantizing_a_scale_never_rounds_up() {+ let minimum = 1.0 / TERMINAL_PREVIEW_SCALE_BUCKETS_PER_UNIT;+ for raw in [0.9999_f64, 0.5, 0.33, 0.0417, 0.001] {+ let quantized = quantize_terminal_preview_scale_down(raw, minimum);+ assert!(quantized <= raw.max(minimum) + 1e-9, "{raw} -> {quantized}");+ assert!(quantized >= minimum);+ }+ }++ #[test]+ fn a_scale_that_is_not_a_number_falls_back_to_the_minimum() {+ let minimum = 0.25;+ assert_eq!(+ quantize_terminal_preview_scale_down(f64::NAN, minimum),+ minimum+ );+ }+}diff --git a/wezterm-gui/src/termwindow/space_swipe.rs b/wezterm-gui/src/termwindow/space_swipe.rsindex 1ff4c620..a7833d0b 100644--- a/wezterm-gui/src/termwindow/space_swipe.rs+++ b/wezterm-gui/src/termwindow/space_swipe.rs@@ -1,3 +1,4 @@+use crate::ui::anim::{Easing, Timeline};use std::time::{Duration, Instant};const HORIZONTAL_LOCK_DISTANCE: f32 = 8.0;@@ -184,15 +185,11 @@ struct Settle {source_space_id: String,target_space_id: Option<String>,source_scroll_offset: f32,- from: f32,- to: f32,- started_at: Instant,- /// The frame that first shows `from` is also the frame that adopts the- /// destination Space, so it pays for its glyph rasterisation and atlas- /// growth -- routinely 100ms+, roughly half the transition. Holding the- /// clock until the *next* frame starts keeps that cost out of the- /// animation instead of letting it swallow the opening frames.- started: bool,+ /// The sidebar offset travelling to its resting place. A committed switch+ /// leaves its opening frame uncharged, because that frame also adopts the+ /// destination Space and pays for its glyph rasterisation and atlas+ /// growth -- routinely 100ms+, roughly half the transition.+ travel: Timeline,committed: bool,}@@ -305,10 +302,15 @@ impl SidebarSpaceSwipeState {source_space_id: gesture.source_space_id,target_space_id,source_scroll_offset: gesture.source_scroll_offset,- from,- to: 0.0,- started_at: now,- started: true,+ // The pages are already where the finger left them, so+ // there is nothing new to draw before travelling back.+ travel: Timeline::running(+ now,+ from,+ 0.0,+ SETTLE_DURATION,+ Easing::OutCubic,+ ),committed: false,});SidebarSpaceSwipeFinish::AnimateBack@@ -360,12 +362,16 @@ impl SidebarSpaceSwipeState {source_space_id: gesture.source_space_id,target_space_id,source_scroll_offset: gesture.source_scroll_offset,- from,- to: if switched { target_offset } else { 0.0 },- started_at: now,// A committed switch defers its clock to the next frame;// a rejected one has nothing expensive to wait for.- started: !switched,+ travel: {+ let to = if switched { target_offset } else { 0.0 };+ if switched {+ Timeline::new(now, from, to, SETTLE_DURATION, Easing::OutCubic)+ } else {+ Timeline::running(now, from, to, SETTLE_DURATION, Easing::OutCubic)+ }+ },committed: switched,});}@@ -385,16 +391,7 @@ impl SidebarSpaceSwipeState {return false;};- if !settle.started {- // The opening frame has been presented; start timing from here.- settle.started = true;- settle.started_at = now;- self.phase = Phase::Settling(settle);- return true;- }-- let elapsed = now.saturating_duration_since(settle.started_at);- if elapsed >= SETTLE_DURATION {+ if !settle.travel.advance(now) {self.phase = Phase::Idle;return false;}@@ -417,24 +414,12 @@ impl SidebarSpaceSwipeState {offset: gesture.display_offset(sidebar_width),})}- Phase::Settling(settle) => {- let raw_t = if settle.started {- now.saturating_duration_since(settle.started_at)- .as_secs_f32()- / SETTLE_DURATION.as_secs_f32()- } else {- // Clock not running yet: hold the opening position.- 0.0- };- let t = raw_t.clamp(0.0, 1.0);- let eased = 1.0 - (1.0 - t).powi(3);- Some(SidebarSpaceSwipeVisual {- source_space_id: settle.source_space_id.clone(),- target_space_id: settle.target_space_id.clone(),- source_scroll_offset: settle.source_scroll_offset,- offset: settle.from + (settle.to - settle.from) * eased,- })- }+ Phase::Settling(settle) => Some(SidebarSpaceSwipeVisual {+ source_space_id: settle.source_space_id.clone(),+ target_space_id: settle.target_space_id.clone(),+ source_scroll_offset: settle.source_scroll_offset,+ offset: settle.travel.value(now),+ }),_ => None,}}@@ -784,12 +769,17 @@ mod tests {);assert!(swipe.is_committing_or_committed());- // First paint after the commit: starts the clock, nothing elapsed yet.- assert!(swipe.advance(at(start, 120)));+ // The opening frame: painted at rest, and not charged to the+ // transition -- it is the frame that adopts the destination Space.+ assert!(swipe.advance(at(start, 30)));+ assert_eq!(swipe.visual(at(start, 30), 300.0).unwrap().offset, -120.0);assert!(swipe.is_committing_or_committed());- assert!(swipe.advance(at(start, 250)));++ // Timing runs from the frame after that one.+ assert!(swipe.advance(at(start, 46)));+ assert!(swipe.advance(at(start, 200)));assert!(swipe.is_committing_or_committed());- assert!(!swipe.advance(at(start, 350)));+ assert!(!swipe.advance(at(start, 280)));assert!(!swipe.is_committing_or_committed());}@@ -841,8 +831,11 @@ mod tests {swipe.visual(adoption_finished, 300.0).unwrap().offset,-120.0);+ // The full transition is still ahead: the second of adoption before it+ // has been spent on work, not on the animation.assert!(swipe.advance(at(start, 1_100)));- assert!(!swipe.advance(at(start, 1_250)));+ assert!(swipe.advance(at(start, 1_250)));+ assert!(!swipe.advance(at(start, 1_330)));}#[test]diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rsindex 321a90c2..40395742 100644--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs@@ -9,6 +9,7 @@ use crate::ssh_hosts::{self, SshHostEntry, SshHostSource, SshHostSpec};use crate::termwindow::content_view::{ContentView, ContentViewResponse};use crate::termwindow::ui::icons::{distro_to_icon, SvgIcon};use crate::termwindow::TermWindow;+use crate::ui::anim::Easing;use crate::ui::{char_index_for_x, contains, draw_button, draw_icon_button, draw_scrollbar, draw_text_input,draw_toggle, rect, text_width_to_char, wheel_delta_pixels, ButtonSpec, ControlState,@@ -1457,7 +1458,7 @@ impl SshHostsView {if self.scroll.offset > 0.5 {for step in 0..fade_height {let progress = step as f32 / fade_height as f32;- let alpha = 1.0 - Self::smoothstep(progress);+ let alpha = 1.0 - Easing::Smooth.apply(progress);ctx.draw_rect(layers,2,@@ -1474,7 +1475,7 @@ impl SshHostsView {let start_y = area.origin.y + area.size.height - fade_height as f32;for step in 0..fade_height {let progress = (step + 1) as f32 / fade_height as f32;- let alpha = Self::smoothstep(progress);+ let alpha = Easing::Smooth.apply(progress);ctx.draw_rect(layers,2,@@ -1490,11 +1491,6 @@ impl SshHostsView {Ok(())}- fn smoothstep(t: f32) -> f32 {- let t = t.clamp(0.0, 1.0);- t * t * (3.0 - 2.0 * t)- }-fn paint_list_mask(&self,ctx: &DrawContext,diff --git a/wezterm-gui/src/termwindow/ui/mod.rs b/wezterm-gui/src/termwindow/ui/mod.rsindex 11d280b3..c163d9f3 100644--- a/wezterm-gui/src/termwindow/ui/mod.rs+++ b/wezterm-gui/src/termwindow/ui/mod.rs@@ -41,13 +41,26 @@ pub fn terminal_title_for_display(title: &str) -> &str {}}-fn is_default_shell_title(title: &str) -> bool {+/// Whether a process or title names a shell rather than something a shell is+/// running. A shell sitting at its prompt is the absence of activity, so+/// surfaces that report "what is this terminal doing" say nothing at all+/// rather than saying `fish` on every idle card.+pub(crate) fn is_default_shell_title(title: &str) -> bool {let title = title.rsplit(['/', '\\']).next().unwrap_or(title);+ let title = title.to_ascii_lowercase();+ // Windows reports the executable, extension and all, so an idle prompt+ // arrives here as `pwsh.exe` and matches nothing -- which reads to the+ // caller as "this terminal is running a program called pwsh.exe".+ let title = title.strip_suffix(".exe").unwrap_or(title.as_str());matches!(- title.to_ascii_lowercase().as_str(),+ title,"zsh"| "bash"| "sh"+ | "dash"+ | "ksh"+ | "csh"+ | "tcsh"| "fish"| "nu"| "nushell"@@ -55,5 +68,44 @@ fn is_default_shell_title(title: &str) -> bool {| "xonsh"| "pwsh"| "powershell"+ | "cmd")}++#[cfg(test)]+mod default_shell_title_tests {+ use super::is_default_shell_title;++ /// A shell sitting at its prompt is not "running" anything worth naming.+ #[test]+ fn a_bare_shell_is_not_a_running_program() {+ for shell in ["zsh", "bash", "fish", "nu", "pwsh", "cmd", "dash", "tcsh"] {+ assert!(is_default_shell_title(shell), "{shell}");+ }+ }++ /// Windows reports the executable, extension and all. Without stripping it+ /// an idle prompt was announcing itself as a program called `pwsh.exe`.+ #[test]+ fn windows_executables_are_recognised_with_their_extension() {+ for shell in ["pwsh.exe", "powershell.exe", "cmd.exe", "CMD.EXE"] {+ assert!(is_default_shell_title(shell), "{shell}");+ }+ }++ #[test]+ fn a_full_path_is_matched_on_its_last_component() {+ assert!(is_default_shell_title("/bin/zsh"));+ assert!(is_default_shell_title(+ r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"+ ));+ }++ /// The point of all this: something the user actually started must survive.+ #[test]+ fn an_actual_program_is_still_named() {+ for program in ["vim", "htop", "node", "cargo", "claude", "zshrc", "bashful"] {+ assert!(!is_default_shell_title(program), "{program}");+ }+ }+}diff --git a/wezterm-gui/src/ui/anim.rs b/wezterm-gui/src/ui/anim.rsnew file mode 100644index 00000000..f064ca56--- /dev/null+++ b/wezterm-gui/src/ui/anim.rs@@ -0,0 +1,324 @@+//! The timing half of an animation: given a start value, an end value and a+//! duration, what should be drawn at this instant.+//!+//! This exists because the arithmetic had been written four times over --+//! ease-out cubic in the Space swipe settle, `t*t*(3-2t)` in onboarding and+//! again, byte for byte, in the SSH host list, plus the exponential friction+//! in [`crate::ui::state::ScrollState`]. Three of those are the same idea with+//! different constants; the fourth is genuinely different (it is a physical+//! response to a finger, not a scripted transition) and deliberately stays+//! where it is.+//!+//! Two behaviours are folded in here rather than left to each caller, because+//! both are invisible until they are wrong and both were only discovered by+//! shipping the Space swipe: the clock does not start until the opening frame+//! has been presented, and retargeting mid-flight departs from where the thing+//! currently *is*. See [`Timeline::advance`] and [`Timeline::retarget`].++use std::cell::Cell;+use std::time::{Duration, Instant};++/// Hover, press and other feedback that only needs the hard edge taken off.+pub(crate) const MICRO: Duration = Duration::from_millis(120);+/// Short travel and opacity: cards closing the gap, chrome fading out.+pub(crate) const SHORT: Duration = Duration::from_millis(180);+/// Page-level movement. Matches the Space swipe settle, which is the one+/// duration in the app that has actually been tuned against a finger.+pub(crate) const STANDARD: Duration = Duration::from_millis(220);+/// Travel across most of the window, where the eye needs longer to follow.+pub(crate) const LONG: Duration = Duration::from_millis(300);++/// How long a timeline will wait for its opening frame before giving up and+/// timing from the present. Without a bound, a timeline attached to something+/// that is never painted -- a card scrolled out of the viewport, say -- would+/// keep asking for frames forever.+const PRESENT_GRACE: Duration = Duration::from_millis(120);++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum Easing {+ /// Decelerate into the target. The default for anything that moves: the+ /// destination is already on screen, so slowing into it reads as the thing+ /// arriving. Accelerating away from the start reads as a stall instead.+ OutCubic,+ /// Symmetric. For opacity, where there is no position for the eye to+ /// track and a hard start is what looks wrong.+ Smooth,+ Linear,+}++impl Easing {+ pub(crate) fn apply(self, t: f32) -> f32 {+ let t = t.clamp(0.0, 1.0);+ match self {+ Self::OutCubic => 1.0 - (1.0 - t).powi(3),+ Self::Smooth => t * t * (3.0 - 2.0 * t),+ Self::Linear => t,+ }+ }+}++/// One value travelling from `from` to `to` over `duration`.+///+/// Drive it by calling [`Self::advance`] once per frame and asking for+/// [`Self::value`] while painting.+#[derive(Debug, Clone)]+pub(crate) struct Timeline {+ from: f32,+ to: f32,+ duration: Duration,+ easing: Easing,+ /// When the clock actually started, which is later than construction --+ /// see [`Self::advance`]. `None` while still waiting.+ started_at: Option<Instant>,+ /// When the timeline was armed, so the wait above can be bounded.+ armed_at: Instant,+ /// Held at `from` for this long after the clock starts.+ delay: Duration,+ /// Set by [`Self::value`], because being sampled is the only evidence a+ /// timeline has that its opening frame was drawn. A `Cell` so painting can+ /// keep taking `&self`.+ presented: Cell<bool>,+ finished: bool,+}++impl Timeline {+ pub(crate) fn new(now: Instant, from: f32, to: f32, duration: Duration, easing: Easing) -> Self {+ Self {+ from,+ to,+ duration,+ easing,+ started_at: None,+ armed_at: now,+ delay: Duration::ZERO,+ presented: Cell::new(false),+ finished: from == to || duration.is_zero(),+ }+ }++ /// A timeline that holds at `from` for `delay` before it starts.+ ///+ /// For the second half of a two-part move, where one thing has to be seen+ /// leaving before the other follows it.+ pub(crate) fn delayed(+ now: Instant,+ from: f32,+ to: f32,+ delay: Duration,+ duration: Duration,+ easing: Easing,+ ) -> Self {+ let mut timeline = Self::new(now, from, to, duration, easing);+ timeline.delay = delay;+ timeline+ }++ /// A timeline whose clock is already running.+ ///+ /// For movement that continues something already on screen, where no new+ /// content has to be drawn before it can begin -- a gesture rebounding to+ /// where it started, say. Everything else should use [`Self::new`] and let+ /// the opening frame go uncharged.+ pub(crate) fn running(+ now: Instant,+ from: f32,+ to: f32,+ duration: Duration,+ easing: Easing,+ ) -> Self {+ let mut timeline = Self::new(now, from, to, duration, easing);+ timeline.started_at = Some(now);+ timeline+ }++ /// A timeline from 0 to 1, for callers interpolating something that is not+ /// a single number -- a rectangle, a colour -- from its progress.+ pub(crate) fn progress(now: Instant, duration: Duration, easing: Easing) -> Self {+ Self::new(now, 0.0, 1.0, duration, easing)+ }++ /// A timeline that is already over, sitting at `value`.+ pub(crate) fn settled(now: Instant, value: f32) -> Self {+ Self::new(now, value, value, Duration::ZERO, Easing::Linear)+ }++ /// Advance to `now`; returns whether another frame is still wanted.+ ///+ /// Call this once per frame, before painting. The first call does not+ /// start the clock: the frame that introduces whatever is being animated+ /// is also the frame that pays for rasterising its glyphs and growing the+ /// atlas, which can run well past 100ms. Timing from before that frame+ /// spends a large part of the transition on a picture that has not been+ /// presented yet, and the movement appears to begin already half over.+ pub(crate) fn advance(&mut self, now: Instant) -> bool {+ if self.finished {+ return false;+ }++ let Some(started_at) = self.started_at else {+ if self.presented.get() || now.saturating_duration_since(self.armed_at) >= PRESENT_GRACE+ {+ self.started_at = Some(now);+ }+ return true;+ };++ if now.saturating_duration_since(started_at) >= self.delay + self.duration {+ self.finished = true;+ return false;+ }+ true+ }++ pub(crate) fn value(&self, now: Instant) -> f32 {+ self.presented.set(true);+ if self.finished {+ return self.to;+ }+ let Some(started_at) = self.started_at else {+ // Clock not running yet: hold the opening value.+ return self.from;+ };+ let elapsed = now+ .saturating_duration_since(started_at)+ .saturating_sub(self.delay);+ let t = elapsed.as_secs_f32() / self.duration.as_secs_f32().max(f32::EPSILON);+ if t >= 1.0 {+ return self.to;+ }+ self.from + (self.to - self.from) * self.easing.apply(t)+ }++ /// Send the value somewhere else, departing from wherever it is right now.+ ///+ /// The current position is the only correct origin for a redirection. A+ /// hand is always faster than a transition -- close three cards in a row+ /// and the second close lands while the first reflow is still travelling+ /// -- and restarting from the previous target makes the thing jump+ /// backwards before setting off again.+ pub(crate) fn retarget(&mut self, now: Instant, to: f32, duration: Duration, easing: Easing) {+ let from = self.value(now);+ *self = Self::new(now, from, to, duration, easing);+ // The content is already on screen this time, so there is nothing+ // expensive to wait for; but keeping one rule for when the clock+ // starts costs a single frame and removes a way to get this wrong.+ }++ /// Jump to the end. For keyboard-driven changes, which want to be+ /// instant, and for teardown.+ pub(crate) fn finish(&mut self) {+ self.finished = true;+ }++ pub(crate) fn is_running(&self) -> bool {+ !self.finished+ }++ pub(crate) fn target(&self) -> f32 {+ self.to+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(start: Instant, millis: u64) -> Instant {+ start + Duration::from_millis(millis)+ }++ fn armed(start: Instant) -> Timeline {+ Timeline::new(start, 0.0, 100.0, Duration::from_millis(200), Easing::Linear)+ }++ #[test]+ fn the_clock_waits_for_the_frame_that_carries_the_new_content() {+ let start = Instant::now();+ let mut timeline = armed(start);++ // The opening frame: sampled, so it was drawn, but it must not have+ // consumed any of the transition.+ assert!(timeline.advance(at(start, 0)));+ assert_eq!(timeline.value(at(start, 0)), 0.0);++ // That frame took 100ms to rasterise. Timing starts from its end, so+ // the next frame is at the beginning of the travel, not halfway.+ assert!(timeline.advance(at(start, 100)));+ assert_eq!(timeline.value(at(start, 100)), 0.0);++ assert_eq!(timeline.value(at(start, 200)), 50.0);+ assert!(!timeline.advance(at(start, 300)));+ assert_eq!(timeline.value(at(start, 300)), 100.0);+ }++ #[test]+ fn a_timeline_nobody_paints_still_starts_rather_than_asking_for_frames_forever() {+ let start = Instant::now();+ let mut timeline = armed(start);++ // Never sampled -- the card it belongs to is scrolled out of view.+ assert!(timeline.advance(at(start, 0)));+ assert!(timeline.advance(at(start, 60)));+ // Past the grace period the clock starts anyway.+ assert!(timeline.advance(at(start, 130)));+ assert!(!timeline.advance(at(start, 331)));+ }++ #[test]+ fn redirecting_departs_from_where_the_value_is_now() {+ let start = Instant::now();+ let mut timeline = armed(start);+ // A frame is advance-then-paint, so follow that order throughout.+ timeline.advance(at(start, 0));+ assert_eq!(timeline.value(at(start, 0)), 0.0);+ timeline.advance(at(start, 10));+ assert_eq!(timeline.value(at(start, 110)), 50.0);++ // A second change arrives mid-flight and wants to go back to 0.+ timeline.retarget(+ at(start, 110),+ 0.0,+ Duration::from_millis(200),+ Easing::Linear,+ );++ // No jump: it leaves from where it was seen last.+ timeline.advance(at(start, 110));+ assert_eq!(timeline.value(at(start, 110)), 50.0);+ timeline.advance(at(start, 120));+ assert_eq!(timeline.value(at(start, 220)), 25.0);+ assert!(!timeline.advance(at(start, 321)));+ }++ #[test]+ fn a_timeline_that_goes_nowhere_never_asks_for_a_frame() {+ let start = Instant::now();+ let mut timeline = Timeline::new(start, 12.0, 12.0, STANDARD, Easing::OutCubic);+ assert!(!timeline.advance(start));+ assert_eq!(timeline.value(at(start, 500)), 12.0);+ }++ #[test]+ fn finishing_early_lands_on_the_target() {+ let start = Instant::now();+ let mut timeline = armed(start);+ timeline.advance(start);+ timeline.finish();+ assert!(!timeline.advance(at(start, 1)));+ assert_eq!(timeline.value(at(start, 1)), 100.0);+ }++ #[test]+ fn movement_decelerates_and_opacity_is_symmetric() {+ // Ease-out is past halfway at the halfway point; smoothstep is not.+ assert!(Easing::OutCubic.apply(0.5) > 0.8);+ assert_eq!(Easing::Smooth.apply(0.5), 0.5);+ // Both are pinned at the ends, so nothing overshoots.+ for easing in [Easing::OutCubic, Easing::Smooth, Easing::Linear] {+ assert_eq!(easing.apply(0.0), 0.0);+ assert_eq!(easing.apply(1.0), 1.0);+ assert_eq!(easing.apply(-1.0), 0.0);+ assert_eq!(easing.apply(2.0), 1.0);+ }+ }+}diff --git a/wezterm-gui/src/ui/draw.rs b/wezterm-gui/src/ui/draw.rsindex 7dd64b88..98f1076f 100644--- a/wezterm-gui/src/ui/draw.rs+++ b/wezterm-gui/src/ui/draw.rs@@ -310,7 +310,7 @@ impl<'a> DrawContext<'a> {clip.max_y(),&self.dimensions,);- heap.apply_to_clipped(layers, clip)+ heap.apply_to_clipped(layers, clip, 1.0)}pub(crate) fn draw_rounded_rect(diff --git a/wezterm-gui/src/ui/mod.rs b/wezterm-gui/src/ui/mod.rsindex 8039db52..100781a9 100644--- a/wezterm-gui/src/ui/mod.rs+++ b/wezterm-gui/src/ui/mod.rs@@ -1,5 +1,6 @@#![allow(dead_code)]+pub(crate) mod anim;pub(crate) mod draw;pub(crate) mod events;pub(crate) mod geometry;