Skip to content

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

Integrate Space swipe with live overview

RoversX600d349499e2
diff --cc wezterm-gui/src/quad.rs
index 24709270,cb9ab693..1aa622fc
--- a/wezterm-gui/src/quad.rs
+++ b/wezterm-gui/src/quad.rs
@@@ -150,26 -148,6 +163,34 @@@ impl<'a> QuadTrait for QuadImpl<'a>
}
}
+ fn set_corner_gradient(
+ &mut self,
+ top_left: LinearRgba,
+ top_right: LinearRgba,
+ bottom_left: LinearRgba,
+ bottom_right: LinearRgba,
+ ) {
+ 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::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);
++ }
+ }
+ }
+
+ 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::Tee(gpu, heap) => {
++ gpu.set_vertical_gradient(top, bottom);
++ heap.set_vertical_gradient(top, bottom);
++ }
+ }
+ }
+
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),
@@@ -400,81 -332,6 +433,95 @@@ impl BoxedQuad
vert
}
+
- fn clipped_to(&self, clip: (f32, f32, f32, f32)) -> Option<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> {
+ let (left, top, right, bottom) = self.position;
- let (clip_left, clip_top, clip_right, clip_bottom) = clip;
- if !(right > left && bottom > top && clip_right > clip_left && clip_bottom > clip_top) {
++ let translated_left = left + offset_x;
++ 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
++ && clip.right() > clip.left()
++ && clip.bottom() > clip.top())
++ {
+ return None;
+ }
+
- 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);
++ 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());
+ if visible_right <= visible_left || visible_bottom <= visible_top {
+ return None;
+ }
- if visible_left == left
- && visible_top == top
- && visible_right == right
- && visible_bottom == bottom
- {
- return Some(self.clone());
- }
+
- 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 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 (u0, u1, v0, v1) = self.tex;
+ let source_colors = self
+ .fg_color_corners
+ .as_deref()
+ .copied()
+ .unwrap_or([self.fg_color; VERTICES_PER_CELL]);
+ let clipped_colors = [
+ bilerp_color(source_colors, x0, y0),
+ bilerp_color(source_colors, x1, y0),
+ bilerp_color(source_colors, x0, y1),
+ bilerp_color(source_colors, x1, y1),
+ ];
+ let fg_color = clipped_colors[V_TOP_LEFT];
+
- Some(Self {
++ let mut clipped = Self {
+ position: (visible_left, visible_top, visible_right, visible_bottom),
+ fg_color,
+ fg_color_corners: clipped_colors
+ .iter()
+ .skip(1)
+ .any(|color| *color != fg_color)
+ .then(|| Box::new(clipped_colors)),
+ alt_color: self.alt_color,
+ tex: (
+ lerp(u0, u1, x0),
+ lerp(u0, u1, x1),
+ lerp(v0, v1, y0),
+ lerp(v0, v1, y1),
+ ),
+ hsv: self.hsv,
+ has_color: self.has_color,
+ mix_value: self.mix_value,
- })
++ };
++ // Solid-colour quads conventionally use zero-width texture intervals.
++ // Preserve those intervals exactly rather than introducing tiny
++ // floating-point differences while cropping.
++ if u0 == u1 {
++ clipped.tex.0 = u0;
++ clipped.tex.1 = u1;
++ }
++ if v0 == v1 {
++ clipped.tex.2 = v0;
++ clipped.tex.3 = v1;
++ }
++ Some(clipped)
+ }
+}
+
+fn lerp(start: f32, end: f32, amount: f32) -> f32 {
+ start + (end - start) * amount
+}
+
+fn lerp_color(start: [f32; 4], end: [f32; 4], amount: f32) -> [f32; 4] {
+ std::array::from_fn(|index| lerp(start[index], end[index], amount))
+}
+
+fn bilerp_color(corners: [[f32; 4]; 4], x: f32, y: f32) -> [f32; 4] {
+ let top = lerp_color(corners[V_TOP_LEFT], corners[V_TOP_RIGHT], x);
+ let bottom = lerp_color(corners[V_BOT_LEFT], corners[V_BOT_RIGHT], x);
+ lerp_color(top, bottom, y)
}
#[derive(Default)]
@@@ -502,36 -484,63 +674,84 @@@ impl HeapQuadAllocator
Ok(())
}
- /// Copy these heap-backed quads into `other`, hard-clipped to a surface
- /// pixel rectangle. Position, texture coordinates and per-corner colors are
- /// cropped together, so glyphs and gradients retain their original shape.
++ /// Copy every recorded quad into `other`, cropped to `clip`.
++ /// Position, texture coordinates and per-corner colors are transformed
++ /// together by the same primitive used by Space swipe composition.
+ pub fn apply_to_clipped(
+ &self,
+ other: &mut TripleLayerQuadAllocator,
- clip: RectF,
- surface_width: f32,
- surface_height: f32,
++ clip: QuadClipRect,
+ ) -> anyhow::Result<()> {
- if clip.size.width <= 0.0 || clip.size.height <= 0.0 {
- return Ok(());
- }
- let left_offset = surface_width / 2.0;
- let top_offset = surface_height / 2.0;
- let centered_clip = (
- clip.min_x() - left_offset,
- clip.min_y() - top_offset,
- clip.max_x() - left_offset,
- clip.max_y() - top_offset,
- );
- let start = std::time::Instant::now();
- for (layer_num, quads) in [(0, &self.layer0), (1, &self.layer1), (2, &self.layer2)] {
++ let started = std::time::Instant::now();
++ for (layer_num, quads) in self.layers() {
+ for quad in quads {
- if let Some(clipped) = quad.clipped_to(centered_clip) {
- other.extend_with(layer_num, &clipped.to_vertices());
- }
++ let Some(clipped) = quad.translated_clipped(0.0, 0.0, clip) else {
++ continue;
++ };
++ other.extend_with(layer_num, &clipped.to_vertices());
+ }
+ }
- metrics::histogram!("quad_buffer_apply_clipped").record(start.elapsed());
++ metrics::histogram!("quad_buffer_apply_clipped").record(started.elapsed());
++ Ok(())
++ }
++
+ /// Replay everything recorded before `mark`, in place.
+ pub fn apply_before(
+ &self,
+ other: &mut TripleLayerQuadAllocator,
+ mark: &HeapQuadMark,
+ ) -> anyhow::Result<()> {
+ for (layer_num, quads) in self.layers() {
+ let end = Self::layer_bounds(mark, layer_num).min(quads.len());
+ for quad in &quads[..end] {
+ other.extend_with(layer_num, &quad.to_vertices());
+ }
+ }
+ Ok(())
+ }
+
+ /// Replay everything recorded from `mark` onwards, in place.
+ pub fn apply_after(
+ &self,
+ other: &mut TripleLayerQuadAllocator,
+ mark: &HeapQuadMark,
+ ) -> anyhow::Result<()> {
+ for (layer_num, quads) in self.layers() {
+ let begin = Self::layer_bounds(mark, layer_num).min(quads.len());
+ for quad in &quads[begin..] {
+ other.extend_with(layer_num, &quad.to_vertices());
+ }
+ }
+ Ok(())
+ }
+
+ /// Replay `start..end`, shifted horizontally and clipped.
+ ///
+ /// The clip is a containment bound -- it stops the shifted quads escaping
+ /// the surface they belong to -- and not a way to carve the frame into
+ /// moving and stationary parts. Use the marks for that.
+ pub fn apply_between(
+ &self,
+ other: &mut TripleLayerQuadAllocator,
+ start: &HeapQuadMark,
+ end: &HeapQuadMark,
+ offset_x: f32,
+ clip: QuadClipRect,
+ ) -> anyhow::Result<()> {
+ let started = std::time::Instant::now();
+ for (layer_num, quads) in self.layers() {
+ let begin = Self::layer_bounds(start, layer_num).min(quads.len());
+ let finish = Self::layer_bounds(end, layer_num)
+ .min(quads.len())
+ .max(begin);
+ for quad in &quads[begin..finish] {
- let Some(vertices) = quad.translated_clipped_vertices(offset_x, clip) else {
++ let Some(clipped) = quad.translated_clipped(offset_x, 0.0, clip) else {
+ continue;
+ };
- other.extend_with(layer_num, &vertices);
++ other.extend_with(layer_num, &clipped.to_vertices());
+ }
+ }
+ metrics::histogram!("quad_buffer_translated_rect_clip_apply").record(started.elapsed());
Ok(())
}
}
@@@ -597,97 -704,157 +846,255 @@@ impl<'a> TripleLayerQuadAllocatorTrait
}
}
++#[cfg(test)]
++const TEST_ORIGIN: Dimensions = Dimensions {
++ pixel_width: 0,
++ pixel_height: 0,
++ dpi: 96,
++};
++
#[cfg(test)]
#[test]
fn size() {
assert_eq!(std::mem::size_of::<Vertex>() * VERTICES_PER_CELL, 272);
- assert_eq!(std::mem::size_of::<BoxedQuad>(), 84);
+ assert_eq!(std::mem::size_of::<BoxedQuad>(), 96);
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_preserves_vertical_gradient_colors() {
+ let top = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
+ let bottom = LinearRgba::with_components(0.4, 0.5, 0.6, 1.0);
+ let mut quad = BoxedQuad::default();
+ quad.set_vertical_gradient(top, bottom);
+ let vertices = quad.to_vertices();
+ let top: [f32; 4] = top.into();
+ let bottom: [f32; 4] = bottom.into();
+ assert_eq!(vertices[V_TOP_LEFT].fg_color, top);
+ assert_eq!(vertices[V_TOP_RIGHT].fg_color, top);
+ assert_eq!(vertices[V_BOT_LEFT].fg_color, bottom);
+ assert_eq!(vertices[V_BOT_RIGHT].fg_color, bottom);
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_preserves_corner_gradient_colors() {
+ let top_left = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
+ let top_right = LinearRgba::with_components(0.2, 0.3, 0.4, 1.0);
+ let bottom_left = LinearRgba::with_components(0.3, 0.4, 0.5, 1.0);
+ let bottom_right = LinearRgba::with_components(0.4, 0.5, 0.6, 1.0);
+ let mut quad = BoxedQuad::default();
+ quad.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
+ let vertices = quad.to_vertices();
+ assert_eq!(vertices[V_TOP_LEFT].fg_color, <[f32; 4]>::from(top_left));
+ assert_eq!(vertices[V_TOP_RIGHT].fg_color, <[f32; 4]>::from(top_right));
+ assert_eq!(vertices[V_BOT_LEFT].fg_color, <[f32; 4]>::from(bottom_left));
+ assert_eq!(
+ vertices[V_BOT_RIGHT].fg_color,
+ <[f32; 4]>::from(bottom_right)
+ );
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_keeps_solid_colors_inline() {
+ let color = LinearRgba::with_components(0.1, 0.2, 0.3, 1.0);
+ let mut quad = BoxedQuad::default();
+ quad.set_fg_color(color);
+ assert!(quad.fg_color_corners.is_none());
+ quad.set_vertical_gradient(color, color);
+ assert!(quad.fg_color_corners.is_none());
+}
+
+#[cfg(test)]
+#[test]
- fn boxed_quad_clip_crops_position_texture_and_gradient_together() {
++fn boxed_quad_translation_and_clip_crop_position_texture_and_gradient_together() {
+ let mut quad = BoxedQuad::default();
+ quad.set_position(0.0, 0.0, 100.0, 80.0);
+ quad.set_texture_discrete(0.1, 0.9, 0.2, 0.6);
+ quad.set_corner_gradient(
+ LinearRgba::with_components(0.0, 0.0, 0.0, 1.0),
+ LinearRgba::with_components(1.0, 0.0, 0.0, 1.0),
+ LinearRgba::with_components(0.0, 1.0, 0.0, 1.0),
+ LinearRgba::with_components(1.0, 1.0, 0.0, 1.0),
+ );
+
- let clipped = quad.clipped_to((25.0, 20.0, 75.0, 60.0)).unwrap();
- assert_eq!(clipped.position, (25.0, 20.0, 75.0, 60.0));
++ let clip = QuadClipRect::from_top_left_pixels(35.0, 25.0, 85.0, 65.0, &TEST_ORIGIN);
++ let clipped = quad.translated_clipped(10.0, 5.0, clip).unwrap();
++ assert_eq!(clipped.position, (35.0, 25.0, 85.0, 65.0));
+ for (actual, expected) in std::iter::zip(
+ [clipped.tex.0, clipped.tex.1, clipped.tex.2, clipped.tex.3]
+ .iter()
+ .copied(),
+ [0.3, 0.7, 0.3, 0.5].iter().copied(),
+ ) {
+ assert!((actual - expected).abs() < 0.000_001);
+ }
+ let colors = clipped.fg_color_corners.unwrap();
+ assert_eq!(colors[V_TOP_LEFT], [0.25, 0.25, 0.0, 1.0]);
+ assert_eq!(colors[V_TOP_RIGHT], [0.75, 0.25, 0.0, 1.0]);
+ assert_eq!(colors[V_BOT_LEFT], [0.25, 0.75, 0.0, 1.0]);
+ assert_eq!(colors[V_BOT_RIGHT], [0.75, 0.75, 0.0, 1.0]);
+}
+
+#[cfg(test)]
+#[test]
+fn boxed_quad_clip_rejects_outside_and_preserves_inside() {
+ let mut quad = BoxedQuad::default();
+ quad.set_position(10.0, 20.0, 30.0, 40.0);
+ quad.set_texture_discrete(0.2, 0.6, 0.3, 0.7);
- assert!(quad.clipped_to((30.0, 0.0, 50.0, 50.0)).is_none());
- let inside = quad.clipped_to((0.0, 0.0, 50.0, 50.0)).unwrap();
++ let outside = QuadClipRect::from_top_left_pixels(30.0, 0.0, 50.0, 50.0, &TEST_ORIGIN);
++ assert!(quad.translated_clipped(0.0, 0.0, outside).is_none());
++ let full = QuadClipRect::from_top_left_pixels(0.0, 0.0, 50.0, 50.0, &TEST_ORIGIN);
++ let inside = quad.translated_clipped(0.0, 0.0, full).unwrap();
+ assert_eq!(inside.position, quad.position);
+ assert_eq!(inside.tex, quad.tex);
}
+
+ #[cfg(test)]
+ mod translated_clip_tests {
+ use super::*;
+
+ /// Fixtures below that predate the rebase work state their coordinates
+ /// already centre-relative, so they convert against a zero-sized window.
+ const ORIGIN: Dimensions = Dimensions {
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 96,
+ };
+
+ #[test]
+ fn translated_rect_clip_moves_positions_and_crops_texture_coordinates_together() {
+ let quad = BoxedQuad {
+ position: (10.0, 2.0, 30.0, 8.0),
+ tex: (0.2, 0.6, 0.1, 0.9),
+ ..Default::default()
+ };
+ let clip = QuadClipRect::from_top_left_pixels(25.0, 3.0, 35.0, 7.0, &ORIGIN);
+ let vertices = quad
- .translated_clipped_vertices(10.0, clip)
- .expect("visible clip");
++ .translated_clipped(10.0, 0.0, clip)
++ .expect("visible clip")
++ .to_vertices();
+
+ assert_eq!(vertices[V_TOP_LEFT].position, [25.0, 3.0]);
+ assert_eq!(vertices[V_BOT_RIGHT].position, [35.0, 7.0]);
+ assert!((vertices[V_TOP_LEFT].tex[0] - 0.3).abs() < 0.0001);
+ assert!((vertices[V_TOP_RIGHT].tex[0] - 0.5).abs() < 0.0001);
+ assert!((vertices[V_TOP_LEFT].tex[1] - (0.1 + 0.8 / 6.0)).abs() < 0.0001);
+ assert!((vertices[V_BOT_LEFT].tex[1] - (0.9 - 0.8 / 6.0)).abs() < 0.0001);
+ }
+
+ /// Regression: the swipe transition built its clip rect straight from the
+ /// sidebar's top-left layout geometry and handed it to the quad clipper,
+ /// whose quads are window-centre relative. Every one of the ~300 quads
+ /// failed the bounds test, so the sidebar drew nothing at all for the
+ /// whole 220ms -- with correct-looking offsets in every log. Nothing about
+ /// that is visible from inside the clipper, so pin the conversion here.
+ #[test]
+ fn a_clip_rect_is_useless_until_it_is_rebased_into_the_quads_own_space() {
+ let window = Dimensions {
+ pixel_width: 2560,
+ pixel_height: 1600,
+ dpi: 144,
+ };
+ // A window of zero size is the only way to express the old bug now.
+ let no_window = Dimensions {
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 144,
+ };
+
+ // A sidebar row as a painter would emit it: laid out at top-left
+ // pixels x 0..465, y 300..320, then written centre-relative.
+ let row = QuadClipRect::from_top_left_pixels(0.0, 300.0, 465.0, 320.0, &window);
+ let quad = BoxedQuad {
+ position: (row.left(), row.top(), row.right(), row.bottom()),
+ ..Default::default()
+ };
+
+ // The list viewport in the layout's own coordinates. Used as-is, it
+ // silently discards a row that is plainly inside it.
+ // `QuadClipRect` has private fields, so this is only expressible in a
+ // test that reaches for the raw numbers on purpose.
+ let unrebased = QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &no_window);
+ assert!(
- quad.translated_clipped_vertices(0.0, unrebased).is_none(),
++ quad.translated_clipped(0.0, 0.0, unrebased).is_none(),
+ "an un-rebased clip rect drops everything -- this is the failure \
+ mode, not a healthy result"
+ );
+
+ // Rebased against the real window, the row survives.
- let list =
- QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &window);
- assert!(quad.translated_clipped_vertices(0.0, list).is_some());
++ let list = QuadClipRect::from_top_left_pixels(0.0, 204.0, 465.0, 1316.0, &window);
++ assert!(quad.translated_clipped(0.0, 0.0, list).is_some());
+ }
+
+ /// Regression: the transition used to decide what slides by cutting the
+ /// sidebar at a y coordinate. It cannot work. The bottom fade and the
+ /// settings row are painted *over* the list on purpose, so any horizontal
+ /// line drawn between "moving" and "stationary" runs straight through
+ /// whichever list row happens to reach that far -- the row's top half slid
+ /// away while its bottom half stayed put, already showing the destination.
+ /// Splitting by paint order instead asks the question that has an answer.
+ #[test]
+ fn chrome_painted_over_the_list_stays_put_when_the_list_slides_under_it() {
+ const WINDOW: Dimensions = Dimensions {
+ pixel_width: 1000,
+ pixel_height: 800,
+ dpi: 96,
+ };
+ fn quad_at(left: f32, top: f32, right: f32, bottom: f32) -> Box<BoxedQuad> {
+ let rect = QuadClipRect::from_top_left_pixels(left, top, right, bottom, &WINDOW);
+ Box::new(BoxedQuad {
+ position: (rect.left(), rect.top(), rect.right(), rect.bottom()),
+ ..Default::default()
+ })
+ }
+ // Left edge of a top-left `x`, in the centre-relative space quads use.
+ let at = |x: f32| x - WINDOW.pixel_width as f32 / 2.0;
+
+ let mut frame = HeapQuadAllocator::default();
+ // Chrome above the list.
+ frame.layer2.push(quad_at(0.0, 0.0, 400.0, 100.0));
+
+ let list_start = frame.mark();
+ // A row reaching down into the band the footer chrome covers. Inset
+ // from the sidebar edges so a horizontal shift is visible rather than
+ // being cropped away by the containment clip.
+ frame.layer2.push(quad_at(100.0, 600.0, 300.0, 660.0));
+ let list_end = frame.mark();
+
+ // The fade and the settings row: painted last, and deliberately
+ // overlapping the row above.
+ frame.layer2.push(quad_at(0.0, 620.0, 400.0, 700.0));
+
+ let mut out = HeapQuadAllocator::default();
+ let mut sink = TripleLayerQuadAllocator::Heap(&mut out);
+ let clip = QuadClipRect::from_top_left_pixels(0.0, 0.0, 400.0, 800.0, &WINDOW);
+ frame.apply_before(&mut sink, &list_start).unwrap();
+ frame
+ .apply_between(&mut sink, &list_start, &list_end, -50.0, clip)
+ .unwrap();
+ frame.apply_after(&mut sink, &list_end).unwrap();
+ drop(sink);
+
+ let left_edges: Vec<f32> = out.layer2.iter().map(|q| q.position.0).collect();
+ assert_eq!(
+ left_edges,
+ vec![at(0.0), at(50.0), at(0.0)],
+ "only the marked list span may move, and the chrome recorded after \
+ it must still be replayed last so it keeps masking the row"
+ );
+ }
+
+ #[test]
+ fn translated_rect_clip_discards_quads_outside_the_sidebar_page() {
+ let quad = BoxedQuad {
+ position: (10.0, 2.0, 30.0, 8.0),
+ ..Default::default()
+ };
+ let full = QuadClipRect::from_top_left_pixels(0.0, 0.0, 40.0, 10.0, &ORIGIN);
+ let below = QuadClipRect::from_top_left_pixels(0.0, 20.0, 40.0, 30.0, &ORIGIN);
- assert!(quad.translated_clipped_vertices(-100.0, full).is_none());
- assert!(quad.translated_clipped_vertices(0.0, below).is_none());
++ assert!(quad.translated_clipped(-100.0, 0.0, full).is_none());
++ assert!(quad.translated_clipped(0.0, 0.0, below).is_none());
+ }
+ }
diff --cc wezterm-gui/src/termwindow/mod.rs
index 1aea987b,fe529bd6..594e7dac
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@@ -1866,6 -1907,47 +1913,70 @@@ impl TermWindow
}
}
+ /// Save where the sidebar is scrolled for the Space currently adopted, so
+ /// coming back to it lands where it was left rather than at the top.
+ fn remember_workspace_sidebar_scroll(&mut self) {
+ let offset = self.workspace_sidebar_scroll_offset;
+ self.workspace_sidebar_scroll_offsets
+ .insert(self.active_space_id.clone(), offset);
+ }
+
+ /// Where `active_space_id` was last scrolled to. A Space seen for the
+ /// first time starts at the top. The value is not clamped here: the list
+ /// it belongs to may have grown or shrunk since, and the paint clamps
+ /// against the extent it actually measures.
+ fn remembered_workspace_sidebar_scroll(&self) -> f32 {
+ self.workspace_sidebar_scroll_offsets
+ .get(&self.active_space_id)
+ .copied()
+ .unwrap_or(0.0)
+ }
+
+ /// The Space the left sidebar should render. Everything painting sidebar
+ /// content must read this rather than `active_space_id`, or the offscreen
+ /// paint of the neighbouring Space silently draws the adopted one instead
+ /// and the swipe slides a page against its own copy.
+ pub(crate) fn workspace_sidebar_space_id(&self) -> &str {
+ self.workspace_sidebar_preview_space_id
+ .as_deref()
+ .unwrap_or(self.active_space_id.as_str())
+ }
+
+ fn clear_workspace_space_swipe_frame_transition(&mut self) {
+ self.workspace_space_swipe_source_frame = None;
+ self.workspace_space_swipe_target_frame = None;
+ self.workspace_space_swipe_tracked = false;
+ self.workspace_sidebar_preview_space_id = None;
+ self.workspace_space_swipe_capture_source = false;
+ self.workspace_space_swipe_push_active = false;
+ self.workspace_space_swipe_direction = 0.0;
+ self.workspace_space_swipe_pending_commit = None;
+ self.workspace_space_swipe_needs_settle_start = false;
+ }
+
++ /// Drop atlas-backed captures after the glyph atlas is recreated. A fast
++ /// flick that committed before its first source paint has no stale source
++ /// frame yet, so preserve its pending switch and retry that capture.
++ fn recover_workspace_space_swipe_after_atlas_recreation(&mut self) {
++ let preserve_pending =
++ crate::termwindow::space_swipe::preserve_pending_source_capture_after_atlas_recreation(
++ self.workspace_space_swipe_source_frame.is_some(),
++ self.workspace_space_swipe_capture_source,
++ self.workspace_space_swipe_pending_commit.is_some(),
++ );
++ if preserve_pending {
++ self.workspace_space_swipe_target_frame = None;
++ self.workspace_sidebar_preview_space_id = None;
++ self.workspace_space_swipe_tracked = false;
++ self.workspace_space_swipe_push_active = false;
++ self.workspace_space_swipe_direction = 0.0;
++ self.workspace_space_swipe_needs_settle_start = false;
++ } else {
++ self.workspace_sidebar_swipe.cancel_immediately();
++ self.clear_workspace_space_swipe_frame_transition();
++ }
++ }
++
fn focus_changed(&mut self, focused: bool, window: &Window) {
log::trace!("Setting focus to {:?}", focused);
self.focused = if focused { Some(Instant::now()) } else { None };
@@@ -4397,14 -4467,9 +4539,18 @@@ impl TermWindow
.iter()
.any(|tab| tab.id == *id && self.content_view_visible_in_active_space(tab))
});
++ if self.content_view_is_full_window() {
++ self.workspace_sidebar_swipe.cancel_immediately();
++ self.clear_workspace_space_swipe_frame_transition();
++ }
self.sync_content_view_surfaces_with_mux();
self.sync_workspace_sidebar_pending_thread_selection();
- if was_foreground && !self.content_view_foreground() {
+ let is_foreground = self.content_view_foreground();
+ if crate::termwindow::content_view::take_deferred_mux_resize_on_exit(
+ &mut self.content_view_deferred_mux_resize,
+ was_foreground,
+ is_foreground,
+ ) {
self.resize_mux_tabs_to_current_terminal_size();
}
self.invalidate_window();
diff --cc wezterm-gui/src/termwindow/render/paint.rs
index b40ddd6f,6b95ec5a..463d4bdd
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@@ -1,6 -1,4 +1,6 @@@
--use crate::quad::{HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocator};
++use crate::quad::{HeapQuadAllocator, QuadClipRect, QuadTrait, TripleLayerQuadAllocator};
+use crate::termwindow::content_view::{ContentViewTypography, TerminalPreviewRequest};
+use crate::termwindow::render::{LineToEleShapeCacheKey, RenderScreenLineParams};
use crate::termwindow::{RenderFrame, TermWindowNotif};
use crate::ui::{DrawContext, UiPalette};
use ::window::bitmaps::atlas::OutOfTextureSpace;
@@@ -333,6 -264,21 +333,12 @@@ impl crate::TermWindow
};
self.invalidate_fancy_tab_bar();
self.invalidate_modal();
- // The captured sidebar holds atlas UV coordinates, not
- // pixels, so repacking the atlas leaves them addressing
- // whatever now occupies those texels. There is no way
- // to re-point them; abandon the transition and let the
- // next pass paint the destination outright. Losing the
- // tail of a 220ms animation beats drawing garbage.
- //
- // The state machine has to go with the frames. Dropping
- // only the frames can strand it in `AwaitingCommit` --
- // reachable here, since rasterising the neighbouring
- // Space is exactly what exhausts the atlas -- where it
- // reports itself active forever, so nothing retires it
- // and momentum stays suppressed until the next gesture.
- self.workspace_sidebar_swipe.cancel_immediately();
- self.clear_workspace_space_swipe_frame_transition();
++ // Captured sidebars hold atlas UV coordinates, not
++ // pixels, so cached frames cannot survive repacking.
++ // Preserve only a fast committed flick that is still
++ // 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();
if let Err(err) = result {
self.allow_images = match self.allow_images {
@@@ -521,309 -427,6 +527,311 @@@
Ok(())
}
+ /// Render live, read-only terminal thumbnails requested by a ContentView.
+ /// This reuses the normal screen-line renderer at a smaller font scale;
+ /// panes are never resized and no input or focus is sent to them.
+ fn paint_terminal_previews(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ previews: &[TerminalPreviewRequest],
+ ) -> anyhow::Result<()> {
+ for preview in previews {
+ self.paint_terminal_preview(layers, preview)?;
+ }
+ Ok(())
+ }
+
+ fn paint_terminal_preview(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ preview: &TerminalPreviewRequest,
+ ) -> anyhow::Result<()> {
+ let mut heap = HeapQuadAllocator::default();
+ {
+ let mut clipped_layers = TripleLayerQuadAllocator::Heap(&mut heap);
+ self.paint_terminal_preview_unclipped(&mut clipped_layers, preview)?;
+ }
- heap.apply_to_clipped(
- layers,
- preview.clip,
- self.dimensions.pixel_width as f32,
- self.dimensions.pixel_height as f32,
- )
++ let clip = QuadClipRect::from_top_left_pixels(
++ preview.clip.min_x(),
++ preview.clip.min_y(),
++ preview.clip.max_x(),
++ preview.clip.max_y(),
++ &self.dimensions,
++ );
++ heap.apply_to_clipped(layers, clip)
+ }
+
+ fn paint_terminal_preview_unclipped(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ preview: &TerminalPreviewRequest,
+ ) -> anyhow::Result<()> {
+ let snapshot = &preview.snapshot;
+ let tab_size = snapshot.tab_size;
+ if tab_size.cols == 0 || tab_size.rows == 0 {
+ return Ok(());
+ }
+ if snapshot.panes.is_empty() {
+ return Ok(());
+ }
+
+ // A thumbnail represents the whole terminal surface, not just the
+ // shrunken PTY grid. Fill any aspect-ratio remainder with the active
+ // terminal's own background so the card never looks letterboxed.
+ let preview_background = snapshot
+ .panes
+ .iter()
+ .find(|pane| pane.is_active)
+ .or_else(|| snapshot.panes.first())
+ .map(|pane| pane.palette.resolve_bg(ColorAttribute::Default).to_linear())
+ .expect("checked that the tab has panes");
+ self.filled_rectangle(layers, 0, preview.clip, preview_background)?;
+
+ // Quantization bounds the number of cached FontConfigurations even
+ // when cards continuously resize. Flooring guarantees the terminal
+ // grid stays inside its preview rather than clipping the last column.
+ let bucketed_width =
+ quantized_terminal_preview_extent(preview.area.size.width, self.dimensions.dpi);
+ let bucketed_height =
+ quantized_terminal_preview_extent(preview.area.size.height, self.dimensions.dpi);
+ let width_ratio = bucketed_width
+ / (tab_size.cols as f32 * self.render_metrics.cell_size.width.max(1) as f32);
+ let height_ratio = bucketed_height
+ / (tab_size.rows as f32 * self.render_metrics.cell_size.height.max(1) as f32);
+ let global_scale = self.fonts.get_font_scale();
+ let minimum_scale = minimum_terminal_preview_scale(
+ self.config.font_size,
+ self.dimensions.dpi,
+ global_scale,
+ );
+ let maximum_scale = (global_scale * 0.84).max(minimum_scale);
+ let desired_scale = (global_scale * f64::from(width_ratio.min(height_ratio)))
+ .clamp(minimum_scale, maximum_scale);
+ let mut quantized_scale =
+ quantize_terminal_preview_scale_down(desired_scale, minimum_scale);
+ let (mut font_config, mut metrics) = self.pane_font_resources(quantized_scale)?;
+
+ // Font raster metrics are integer pixels and therefore do not scale
+ // perfectly linearly. Correct the analytical estimate once using the
+ // actual metrics; if the one-pixel raster floor is still too large, the
+ // hard quad clip below remains the final safety boundary.
+ let rendered_width = tab_size.cols as f32 * metrics.cell_size.width.max(1) as f32;
+ let rendered_height = tab_size.rows as f32 * metrics.cell_size.height.max(1) as f32;
+ let correction = (bucketed_width / rendered_width)
+ .min(bucketed_height / rendered_height)
+ .min(1.0);
+ if correction < 1.0 {
+ let corrected_scale = quantize_terminal_preview_scale_down(
+ quantized_scale * f64::from(correction) * 0.999,
+ minimum_scale,
+ );
+ if corrected_scale < quantized_scale {
+ quantized_scale = corrected_scale;
+ (font_config, metrics) = self.pane_font_resources(quantized_scale)?;
+ }
+ }
+
+ 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;
+ (font_config, metrics) = self.pane_font_resources(quantized_scale)?;
+ }
+ let cell_width = metrics.cell_size.width.max(1) as f32;
+ let cell_height = metrics.cell_size.height.max(1) as f32;
+ // 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;
+
+ 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();
+ let mut hidden_cursor = StableCursorPosition::default();
+ hidden_cursor.y = isize::MIN;
+
+ for pane in &snapshot.panes {
+ let palette = &pane.palette;
+ let pane_x = origin_x + pane.left as f32 * cell_width;
+ let pane_y = origin_y + pane.top as f32 * cell_height;
+ 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 source_dims = pane.dimensions;
+ let rows = pane.rows;
+ let cols = pane.cols;
+ if rows == 0 || cols == 0 {
+ continue;
+ }
+
+ 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;
+ let foreground = palette.foreground.to_linear();
+ let default_bg = palette.background.to_linear();
+ // LineToElementShape caches resolved colors as well as glyph
+ // geometry. Include the pane palette so two terminals with the
+ // same text/ANSI indexes cannot reuse each other's resolved color
+ // values inside the overview.
+ let mut palette_hasher = DefaultHasher::new();
+ palette.colors.0.hash(&mut palette_hasher);
+ palette.foreground.hash(&mut palette_hasher);
+ palette.background.hash(&mut palette_hasher);
+ palette.cursor_fg.hash(&mut palette_hasher);
+ palette.cursor_bg.hash(&mut palette_hasher);
+ palette.cursor_border.hash(&mut palette_hasher);
+ 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() {
+ continue;
+ }
+ let shape_hash = self.shape_hash_for_line(line);
+ self.render_screen_line(
+ RenderScreenLineParams {
+ top_pixel_y: y,
+ left_pixel_x: pane_x,
+ pixel_width: cols as f32 * cell_width,
+ stable_line_idx: Some(pane.resolved_top + line_idx as isize),
+ line,
+ selection: 0..0,
+ cursor: &hidden_cursor,
+ palette,
+ dims: &render_dims,
+ config: &self.config,
+ pane: None,
+ white_space,
+ filled_box,
+ cursor_border_color: palette.cursor_border.to_linear(),
+ foreground,
+ is_active: true,
+ selection_fg: palette.selection_fg.to_linear(),
+ selection_bg: palette.selection_bg.to_linear(),
+ cursor_fg: palette.cursor_fg.to_linear(),
+ cursor_bg: palette.cursor_bg.to_linear(),
+ cursor_is_default_color: true,
+ window_is_transparent: false,
+ default_bg,
+ font: None,
+ style: None,
+ use_pixel_positioning: false,
+ render_metrics: metrics,
+ font_config: Some(font_config.clone()),
+ font_identity,
+ shape_key: Some(LineToEleShapeCacheKey {
+ shape_hash,
+ composing: None,
+ shape_generation: self.shape_generation,
+ font_identity,
+ }),
+ password_input: false,
+ allow_images: false,
+ },
+ layers,
+ )?;
+ }
+
+ // Draw a non-blinking cursor for the active split. The regular
+ // renderer intentionally receives a hidden cursor above, so this
+ // thumbnail cannot start the foreground cursor animation timer.
+ if pane.is_active {
+ let cursor = pane.cursor;
+ let cursor_row = cursor.y.saturating_sub(pane.resolved_top);
+ if cursor.visibility == termwiz::surface::CursorVisibility::Visible
+ && cursor_row >= 0
+ && (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,
+ );
+ 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,
+ )?;
+ }
+ }
+ }
+ }
+
+ // Preserve split topology in the thumbnail. PositionedSplit is part
+ // of the immutable snapshot, so this pass also performs no mux reads.
+ let split_color = snapshot
+ .panes
+ .iter()
+ .find(|pane| pane.is_active)
+ .or_else(|| snapshot.panes.first())
+ .map(|pane| pane.palette.split.to_linear())
+ .unwrap_or(preview_background);
+ let split_stroke = (metrics.underline_height as f32 * 0.7).max(1.0);
+ for split in &snapshot.splits {
+ let rect = if split.direction == SplitDirection::Horizontal {
+ euclid::rect(
+ origin_x + (split.left as f32 + 0.5) * cell_width,
+ origin_y + (split.top as f32 - 0.5) * cell_height,
+ split_stroke,
+ (1.0 + split.size as f32) * cell_height,
+ )
+ } else {
+ euclid::rect(
+ origin_x + (split.left as f32 - 0.5) * cell_width,
+ origin_y + (split.top as f32 + 0.5) * cell_height,
+ (1.0 + split.size as f32) * cell_width,
+ split_stroke,
+ )
+ };
+ if let Some(visible) = rect.intersection(&preview.clip) {
+ self.filled_rectangle(layers, 2, visible, split_color)?;
+ }
+ }
+ Ok(())
+ }
+
pub fn paint_modal(&mut self) -> anyhow::Result<()> {
if let Some(modal) = self.get_modal() {
for computed in modal.computed_element(self)?.iter() {
@@@ -1350,25 -1083,218 +1488,233 @@@
.context("paint_content_view")?;
}
- // Space switching is a left-sidebar interaction. Keep the terminal,
- // tab bar, right sidebar and window chrome on the live GPU path, then
- // isolate just the left sidebar while its middle list page transitions.
- drop(layers);
-
- self.capture_workspace_space_swipe_target(frame_now)?;
-
- let render_space_push = self.workspace_space_swipe_push_active
- && self.workspace_space_swipe_source_frame.is_some();
- // Before the commit the window still shows the Space being left, so
- // the live paint is the *source* page and the captured neighbour is
- // the target. Committing swaps those roles.
- let render_space_track = !render_space_push
- && !self.workspace_space_swipe_push_active
- && self.workspace_space_swipe_target_frame.is_some();
- // Only needed when a gesture committed before the pages ever tracked
- // it -- a flick fast enough to finish inside one frame. Otherwise the
- // tracking branch below hands over its own last paint.
- let capture_space_source = self.workspace_space_swipe_capture_source
- && !render_space_push
- && !render_space_track;
- let mut sidebar_frame = HeapQuadAllocator::default();
- let mut composited_tracking_frame = false;
-
- if render_space_push || render_space_track {
- let mut sidebar_layers = TripleLayerQuadAllocator::Heap(&mut sidebar_frame);
- self.paint_workspace_sidebar(&mut sidebar_layers)
- .context("paint live workspace sidebar")?;
- drop(sidebar_layers);
- let live_list = self.workspace_sidebar_list_quads;
-
- if self.workspace_space_swipe_needs_settle_start {
- let gesture_extent = self.workspace_sidebar_width() as f32;
- let opening = if self.workspace_space_swipe_tracked {
- crate::termwindow::space_swipe::SettleOpening::WhereTheFingerLeftIt
- } else {
- crate::termwindow::space_swipe::SettleOpening::AtRest
- };
- self.workspace_sidebar_swipe.resolve_switch(
- true,
- Instant::now(),
- gesture_extent,
- opening,
- );
- self.workspace_space_swipe_needs_settle_start = false;
- // The settle clock does not start until the *next* frame (see
- // `Settle::started`), so this frame only has to make sure a
- // next frame happens; `advance` paces everything after it.
- if let Some(window) = self.window.as_ref() {
- window.invalidate();
+ // 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);
++ drop(layers);
+ } else {
- self.paint_workspace_sidebar(&mut layers)
- .context("paint_workspace_sidebar")?;
- self.paint_right_sidebar(&mut layers)
++ // Space switching is a left-sidebar interaction. Keep the terminal,
++ // tab bar, right sidebar and window chrome on the live GPU path, then
++ // isolate just the left sidebar while its middle list page transitions.
++ drop(layers);
++
++ self.capture_workspace_space_swipe_target(frame_now)?;
++
++ let render_space_push = self.workspace_space_swipe_push_active
++ && self.workspace_space_swipe_source_frame.is_some();
++ // Before the commit the window still shows the Space being left, so
++ // the live paint is the *source* page and the captured neighbour is
++ // the target. Committing swaps those roles.
++ let render_space_track = !render_space_push
++ && !self.workspace_space_swipe_push_active
++ && self.workspace_space_swipe_target_frame.is_some();
++ // Only needed when a gesture committed before the pages ever tracked
++ // it -- a flick fast enough to finish inside one frame. Otherwise the
++ // tracking branch below hands over its own last paint.
++ let capture_space_source = self.workspace_space_swipe_capture_source
++ && !render_space_push
++ && !render_space_track;
++ let mut sidebar_frame = HeapQuadAllocator::default();
++ let mut composited_tracking_frame = false;
++
++ if render_space_push || render_space_track {
++ let mut sidebar_layers = TripleLayerQuadAllocator::Heap(&mut sidebar_frame);
++ self.paint_workspace_sidebar(&mut sidebar_layers)
++ .context("paint live workspace sidebar")?;
++ drop(sidebar_layers);
++ let live_list = self.workspace_sidebar_list_quads;
++
++ if self.workspace_space_swipe_needs_settle_start {
++ let gesture_extent = self.workspace_sidebar_width() as f32;
++ let opening = if self.workspace_space_swipe_tracked {
++ crate::termwindow::space_swipe::SettleOpening::WhereTheFingerLeftIt
++ } else {
++ crate::termwindow::space_swipe::SettleOpening::AtRest
++ };
++ self.workspace_sidebar_swipe.resolve_switch(
++ true,
++ Instant::now(),
++ gesture_extent,
++ opening,
++ );
++ self.workspace_space_swipe_needs_settle_start = false;
++ // The settle clock does not start until the *next* frame (see
++ // `Settle::started`), so this frame only has to make sure a
++ // next frame happens; `advance` paces everything after it.
++ if let Some(window) = self.window.as_ref() {
++ window.invalidate();
++ }
+ }
- }
+
- let mut gpu_layers = layer.quad_allocator();
- if let Some(rect) = self.workspace_sidebar_rect() {
- // Quad positions are window-centre relative (see
- // `filled_rectangle`) while the sidebar rect is in top-left
- // pixels. Rebase, or every quad fails the bounds test and the
- // sidebar renders empty for the whole transition.
- //
- // This is a containment bound, nothing more: it keeps a page
- // that has slid partway out of the sidebar from spilling over
- // the terminal. The pages may use the sidebar's full height --
- // the masks painted after the list already hide whatever
- // overshoots the viewport, and they do it without cutting a row
- // in half the way a clip edge through the middle of the list
- // would.
- let sidebar_clip = crate::quad::QuadClipRect::from_top_left_pixels(
- rect.x as f32,
- rect.y as f32,
- rect.x.saturating_add(rect.width) as f32,
- rect.y.saturating_add(rect.height) as f32,
- &self.dimensions,
- );
- // The one-pixel separator is sidebar chrome, not page content.
- let page_right = (sidebar_clip.right() - 1.0).max(sidebar_clip.left());
- let page_width = page_right - sidebar_clip.left();
- let page_clip = sidebar_clip.with_horizontal(sidebar_clip.left(), page_right);
- let offsets = self
- .workspace_space_swipe_push_offsets(Instant::now(), page_width)
- .filter(|_| page_width > 0.0);
- // Which Space the live paint holds flips at the commit, so the
- // offset that belongs to it flips with it. The captured
- // neighbour always takes the other one.
- let offscreen = if render_space_push {
- self.workspace_space_swipe_source_frame.as_ref()
- } else {
- self.workspace_space_swipe_target_frame
- .as_ref()
- .map(|(_, captured)| captured)
- };
- let offscreen_span = offscreen.and_then(|captured| captured.list);
-
- match (offsets, live_list, offscreen_span) {
- (Some((source_offset, target_offset)), Some(live), Some(other)) => {
- let (live_offset, offscreen_offset) = if render_space_push {
- (target_offset, source_offset)
- } else {
- (source_offset, target_offset)
- };
- // Order matters within a layer: the chrome recorded
- // after the list is what masks it, so it has to be
- // replayed after the pages here too.
- sidebar_frame
- .apply_before(&mut gpu_layers, &live.0)
- .context("space swipe sidebar chrome above the list")?;
- if let Some(captured) = offscreen {
- captured
- .quads
++ let mut gpu_layers = layer.quad_allocator();
++ if let Some(rect) = self.workspace_sidebar_rect() {
++ // Quad positions are window-centre relative (see
++ // `filled_rectangle`) while the sidebar rect is in top-left
++ // pixels. Rebase, or every quad fails the bounds test and the
++ // sidebar renders empty for the whole transition.
++ //
++ // This is a containment bound, nothing more: it keeps a page
++ // that has slid partway out of the sidebar from spilling over
++ // the terminal. The pages may use the sidebar's full height --
++ // the masks painted after the list already hide whatever
++ // overshoots the viewport, and they do it without cutting a row
++ // in half the way a clip edge through the middle of the list
++ // would.
++ let sidebar_clip = crate::quad::QuadClipRect::from_top_left_pixels(
++ rect.x as f32,
++ rect.y as f32,
++ rect.x.saturating_add(rect.width) as f32,
++ rect.y.saturating_add(rect.height) as f32,
++ &self.dimensions,
++ );
++ // The one-pixel separator is sidebar chrome, not page content.
++ let page_right = (sidebar_clip.right() - 1.0).max(sidebar_clip.left());
++ let page_width = page_right - sidebar_clip.left();
++ let page_clip = sidebar_clip.with_horizontal(sidebar_clip.left(), page_right);
++ let offsets = self
++ .workspace_space_swipe_push_offsets(Instant::now(), page_width)
++ .filter(|_| page_width > 0.0);
++ // Which Space the live paint holds flips at the commit, so the
++ // offset that belongs to it flips with it. The captured
++ // neighbour always takes the other one.
++ let offscreen = if render_space_push {
++ self.workspace_space_swipe_source_frame.as_ref()
++ } else {
++ self.workspace_space_swipe_target_frame
++ .as_ref()
++ .map(|(_, captured)| captured)
++ };
++ let offscreen_span = offscreen.and_then(|captured| captured.list);
++
++ match (offsets, live_list, offscreen_span) {
++ (Some((source_offset, target_offset)), Some(live), Some(other)) => {
++ let (live_offset, offscreen_offset) = if render_space_push {
++ (target_offset, source_offset)
++ } else {
++ (source_offset, target_offset)
++ };
++ // Order matters within a layer: the chrome recorded
++ // after the list is what masks it, so it has to be
++ // replayed after the pages here too.
++ sidebar_frame
++ .apply_before(&mut gpu_layers, &live.0)
++ .context("space swipe sidebar chrome above the list")?;
++ if let Some(captured) = offscreen {
++ captured
++ .quads
++ .apply_between(
++ &mut gpu_layers,
++ &other.0,
++ &other.1,
++ offscreen_offset,
++ page_clip,
++ )
++ .context("space swipe offscreen sidebar page")?;
++ }
++ sidebar_frame
+ .apply_between(
+ &mut gpu_layers,
- &other.0,
- &other.1,
- offscreen_offset,
++ &live.0,
++ &live.1,
++ live_offset,
+ page_clip,
+ )
- .context("space swipe offscreen sidebar page")?;
++ .context("space swipe live sidebar page")?;
++ sidebar_frame
++ .apply_after(&mut gpu_layers, &live.1)
++ .context("space swipe sidebar chrome below the list")?;
++ composited_tracking_frame = render_space_track;
++ }
++ _ => {
++ sidebar_frame
++ .apply_to(&mut gpu_layers)
++ .context("space swipe sidebar fallback")?;
+ }
- sidebar_frame
- .apply_between(
- &mut gpu_layers,
- &live.0,
- &live.1,
- live_offset,
- page_clip,
- )
- .context("space swipe live sidebar page")?;
- sidebar_frame
- .apply_after(&mut gpu_layers, &live.1)
- .context("space swipe sidebar chrome below the list")?;
- composited_tracking_frame = render_space_track;
+ }
- _ => {
- sidebar_frame
- .apply_to(&mut gpu_layers)
- .context("space swipe sidebar fallback")?;
++ } else {
++ sidebar_frame
++ .apply_to(&mut gpu_layers)
++ .context("space swipe target sidebar without viewport")?;
++ }
++ drop(gpu_layers);
++ // Unconditional: the pages either followed the finger this frame
++ // or they did not, and that is true regardless of which branch
++ // captured what. Gating this on the source capture meant the usual
++ // path -- source captured back at `MayBegin`, long before the axis
++ // locked -- never recorded a single tracking frame, so committing
++ // opened `AtRest` and yanked the pages back to zero first.
++ self.workspace_space_swipe_tracked |= composited_tracking_frame;
++
++ // The finger lifted on a committing gesture while the pages were
++ // already tracking it. This paint is the last frame of the Space
++ // being left, so keep it as the outgoing page instead of spending
++ // another frame re-rendering it -- that frame would have to show
++ // the sidebar untransitioned, snapping the pages back to rest just
++ // before the settle animates them forward again.
++ if render_space_track && self.workspace_space_swipe_capture_source {
++ self.workspace_space_swipe_source_frame =
++ Some(crate::termwindow::CapturedSidebar {
++ quads: std::mem::take(&mut sidebar_frame),
++ list: live_list,
++ });
++ self.workspace_space_swipe_capture_source = false;
++ #[cfg(target_os = "macos")]
++ if self.workspace_space_swipe_pending_commit.is_some() {
++ if let Some(window) = self.window.clone() {
++ window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
++ |term_window| {
++ term_window.complete_workspace_space_swipe_switch();
++ },
++ )));
++ }
+ }
+ }
- } else {
- sidebar_frame
- .apply_to(&mut gpu_layers)
- .context("space swipe target sidebar without viewport")?;
- }
- drop(gpu_layers);
- // Unconditional: the pages either followed the finger this frame
- // or they did not, and that is true regardless of which branch
- // captured what. Gating this on the source capture meant the usual
- // path -- source captured back at `MayBegin`, long before the axis
- // locked -- never recorded a single tracking frame, so committing
- // opened `AtRest` and yanked the pages back to zero first.
- self.workspace_space_swipe_tracked |= composited_tracking_frame;
-
- // The finger lifted on a committing gesture while the pages were
- // already tracking it. This paint is the last frame of the Space
- // being left, so keep it as the outgoing page instead of spending
- // another frame re-rendering it -- that frame would have to show
- // the sidebar untransitioned, snapping the pages back to rest just
- // before the settle animates them forward again.
- if render_space_track && self.workspace_space_swipe_capture_source {
++ } else if capture_space_source {
++ let mut sidebar_layers = layer.tee_quad_allocator(&mut sidebar_frame);
++ self.paint_workspace_sidebar(&mut sidebar_layers)
++ .context("capture source workspace sidebar")?;
++ drop(sidebar_layers);
++
+ self.workspace_space_swipe_source_frame =
+ Some(crate::termwindow::CapturedSidebar {
- quads: std::mem::take(&mut sidebar_frame),
- list: live_list,
++ quads: sidebar_frame,
++ list: self.workspace_sidebar_list_quads,
+ });
+ self.workspace_space_swipe_capture_source = false;
+ #[cfg(target_os = "macos")]
+ if self.workspace_space_swipe_pending_commit.is_some() {
+ if let Some(window) = self.window.clone() {
+ window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ |term_window| {
+ term_window.complete_workspace_space_swipe_switch();
+ },
+ )));
+ }
+ }
++ } else {
++ let mut sidebar_layers = layer.quad_allocator();
++ self.paint_workspace_sidebar(&mut sidebar_layers)
++ .context("paint_workspace_sidebar")?;
++ drop(sidebar_layers);
+ }
- } else if capture_space_source {
- let mut sidebar_layers = layer.tee_quad_allocator(&mut sidebar_frame);
- self.paint_workspace_sidebar(&mut sidebar_layers)
- .context("capture source workspace sidebar")?;
- drop(sidebar_layers);
-
- self.workspace_space_swipe_source_frame = Some(crate::termwindow::CapturedSidebar {
- quads: sidebar_frame,
- list: self.workspace_sidebar_list_quads,
- });
- self.workspace_space_swipe_capture_source = false;
- #[cfg(target_os = "macos")]
- if self.workspace_space_swipe_pending_commit.is_some() {
- if let Some(window) = self.window.clone() {
- window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
- |term_window| {
- term_window.complete_workspace_space_swipe_switch();
- },
- )));
- }
- }
- } else {
- let mut sidebar_layers = layer.quad_allocator();
- self.paint_workspace_sidebar(&mut sidebar_layers)
- .context("paint_workspace_sidebar")?;
- drop(sidebar_layers);
- }
+
- let mut layers = layer.quad_allocator();
- self.paint_right_sidebar(&mut layers)
- .context("paint_right_sidebar")?;
++ let mut chrome_layers = layer.quad_allocator();
++ self.paint_right_sidebar(&mut chrome_layers)
+ .context("paint_right_sidebar")?;
- if self.show_tab_bar {
- self.paint_tab_bar(&mut layers).context("paint_tab_bar")?;
+ if self.show_tab_bar {
- self.paint_tab_bar(&mut layers).context("paint_tab_bar")?;
++ self.paint_tab_bar(&mut chrome_layers)
++ .context("paint_tab_bar")?;
+ }
++ drop(chrome_layers);
}
++ let mut layers = layer.quad_allocator();
self.paint_window_borders(&mut layers)
.context("paint_window_borders")?;
drop(layers);
diff --cc wezterm-gui/src/termwindow/space_swipe.rs
index 00000000,4377b17d..1ff4c620
mode 000000,100644..100644
--- a/wezterm-gui/src/termwindow/space_swipe.rs
+++ b/wezterm-gui/src/termwindow/space_swipe.rs
@@@ -1,0 -1,955 +1,997 @@@
+ use std::time::{Duration, Instant};
+
+ const HORIZONTAL_LOCK_DISTANCE: f32 = 8.0;
+ const VERTICAL_LOCK_DISTANCE: f32 = 18.0;
+ const AXIS_LOCK_RATIO: f32 = 1.15;
+ const AXIS_LOCK_FALLBACK_DISTANCE: f32 = 32.0;
+ const EDGE_RESISTANCE: f32 = 0.25;
+ const EDGE_MAX_OFFSET: f32 = 48.0;
+ const COMMIT_DISTANCE_RATIO: f32 = 0.28;
+ const COMMIT_MIN_FLING_DISTANCE: f32 = 16.0;
+ const COMMIT_VELOCITY: f32 = 600.0;
+ const SETTLE_DURATION: Duration = Duration::from_millis(220);
+
+ pub(crate) fn sidebar_page_push_offsets(
+ visual_offset: f32,
+ gesture_extent: f32,
+ page_width: f32,
+ direction: f32,
+ ) -> (f32, f32) {
+ if gesture_extent <= 0.0 || page_width <= 0.0 || direction == 0.0 {
+ return (0.0, 0.0);
+ }
+
+ let direction = direction.signum();
+ let progress = (visual_offset.abs() / gesture_extent).clamp(0.0, 1.0);
+ let source = direction * page_width * progress;
+ let target = source - direction * page_width;
+ (source, target)
+ }
+
++/// Atlas recreation invalidates captured quad UVs, but a fast committed flick
++/// can still be waiting for its first source capture and therefore has no
++/// source frame to invalidate. Keep that semantic commit alive so the retry
++/// can capture the source and finish the switch; any cached neighbour is
++/// discarded and repainted separately.
++pub(crate) fn preserve_pending_source_capture_after_atlas_recreation(
++ source_frame_captured: bool,
++ capture_source: bool,
++ pending_commit: bool,
++) -> bool {
++ !source_frame_captured && capture_source && pending_commit
++}
++
+ #[derive(Debug, Clone, Copy, PartialEq)]
+ pub(crate) enum SidebarSpaceSwipeUpdate {
+ Pending,
+ Horizontal,
+ Vertical(f32),
+ }
+
+ #[derive(Debug, Clone, PartialEq)]
+ pub(crate) enum SidebarSpaceSwipeFinish {
+ None,
+ Switch(String),
+ AnimateBack,
+ /// The gesture ended before either axis locked, so its vertical travel was
+ /// only ever accumulated. Scroll by it now: the state machine consumed the
+ /// events, so nothing else will.
+ FlushVertical(f32),
+ }
+
+ /// Where a committed transition should begin its travel.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub(crate) enum SettleOpening {
+ /// The pages were already following the finger, so carry on from where it
+ /// let go. Restarting at rest would snap them backwards first.
+ WhereTheFingerLeftIt,
+ /// Nothing was ever composited for this gesture -- a flick that began and
+ /// ended inside a single frame -- so the pages are still sitting at rest
+ /// no matter what the gesture's arithmetic says. Travelling the whole way
+ /// is what makes the switch visible rather than an instant cut.
+ AtRest,
+ }
+
+ #[derive(Debug, Clone, PartialEq)]
+ pub(crate) struct SidebarSpaceSwipeVisual {
+ pub(crate) source_space_id: String,
+ pub(crate) target_space_id: Option<String>,
+ pub(crate) source_scroll_offset: f32,
+ pub(crate) offset: f32,
+ }
+
+ #[derive(Debug, Clone)]
+ struct Gesture {
+ source_space_id: String,
+ previous_space_id: Option<String>,
+ next_space_id: Option<String>,
+ source_scroll_offset: f32,
+ raw_x: f32,
+ raw_y: f32,
+ velocity_x: f32,
+ last_sample_at: Instant,
+ }
+
+ impl Gesture {
+ fn new(
+ source_space_id: String,
+ previous_space_id: Option<String>,
+ next_space_id: Option<String>,
+ source_scroll_offset: f32,
+ now: Instant,
+ ) -> Self {
+ Self {
+ source_space_id,
+ previous_space_id,
+ next_space_id,
+ source_scroll_offset,
+ raw_x: 0.0,
+ raw_y: 0.0,
+ velocity_x: 0.0,
+ last_sample_at: now,
+ }
+ }
+
+ fn update(&mut self, delta_x: f32, delta_y: f32, now: Instant) {
+ let dt = now
+ .saturating_duration_since(self.last_sample_at)
+ .as_secs_f32()
+ .clamp(1.0 / 240.0, 1.0 / 20.0);
+ self.last_sample_at = now;
+ self.raw_x += delta_x;
+ self.raw_y += delta_y;
+
+ let instantaneous = delta_x / dt;
+ self.velocity_x = self.velocity_x * 0.65 + instantaneous * 0.35;
+ }
+
+ fn target_space_id(&self) -> Option<&String> {
+ if self.raw_x < 0.0 {
+ self.next_space_id.as_ref()
+ } else if self.raw_x > 0.0 {
+ self.previous_space_id.as_ref()
+ } else {
+ None
+ }
+ }
+
+ fn display_offset(&self, sidebar_width: f32) -> f32 {
+ if self.raw_x < 0.0 {
+ if self.next_space_id.is_some() {
+ self.raw_x.max(-sidebar_width)
+ } else {
+ (self.raw_x * EDGE_RESISTANCE).max(-EDGE_MAX_OFFSET)
+ }
+ } else if self.raw_x > 0.0 {
+ if self.previous_space_id.is_some() {
+ self.raw_x.min(sidebar_width)
+ } else {
+ (self.raw_x * EDGE_RESISTANCE).min(EDGE_MAX_OFFSET)
+ }
+ } else {
+ 0.0
+ }
+ }
+
+ fn target_offset(&self, sidebar_width: f32) -> f32 {
+ if self.raw_x < 0.0 {
+ -sidebar_width
+ } else {
+ sidebar_width
+ }
+ }
+
+ fn should_commit(&self, sidebar_width: f32) -> bool {
+ if self.target_space_id().is_none() {
+ return false;
+ }
+
+ let distance_commit =
+ self.display_offset(sidebar_width).abs() >= sidebar_width * COMMIT_DISTANCE_RATIO;
+ let velocity_toward_target = if self.raw_x < 0.0 {
+ -self.velocity_x
+ } else {
+ self.velocity_x
+ };
+ let fling_commit = self.raw_x.abs() >= COMMIT_MIN_FLING_DISTANCE
+ && velocity_toward_target >= COMMIT_VELOCITY;
+ distance_commit || fling_commit
+ }
+ }
+
+ #[derive(Debug, Clone)]
+ 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,
+ committed: bool,
+ }
+
+ #[derive(Debug, Clone)]
+ enum Phase {
+ Idle,
+ Candidate(Gesture),
+ Vertical,
+ Tracking(Gesture),
+ AwaitingCommit(Gesture),
+ Settling(Settle),
+ }
+
+ impl Default for Phase {
+ fn default() -> Self {
+ Self::Idle
+ }
+ }
+
+ #[derive(Debug, Clone, Default)]
+ pub(crate) struct SidebarSpaceSwipeState {
+ phase: Phase,
+ suppress_momentum: bool,
+ }
+
+ impl SidebarSpaceSwipeState {
+ pub(crate) fn begin(
+ &mut self,
+ source_space_id: String,
+ previous_space_id: Option<String>,
+ next_space_id: Option<String>,
+ source_scroll_offset: f32,
+ now: Instant,
+ ) -> bool {
+ if !matches!(self.phase, Phase::Idle) {
+ return false;
+ }
+ self.suppress_momentum = false;
+ self.phase = Phase::Candidate(Gesture::new(
+ source_space_id,
+ previous_space_id,
+ next_space_id,
+ source_scroll_offset,
+ now,
+ ));
+ true
+ }
+
+ pub(crate) fn update(
+ &mut self,
+ delta_x: f32,
+ delta_y: f32,
+ now: Instant,
+ ) -> SidebarSpaceSwipeUpdate {
+ let phase = std::mem::take(&mut self.phase);
+ match phase {
+ Phase::Candidate(mut gesture) => {
+ gesture.update(delta_x, delta_y, now);
+ let x = gesture.raw_x.abs();
+ let y = gesture.raw_y.abs();
+ let max_axis = x.max(y);
+
+ if x >= HORIZONTAL_LOCK_DISTANCE && x > y * AXIS_LOCK_RATIO {
+ self.phase = Phase::Tracking(gesture);
+ SidebarSpaceSwipeUpdate::Horizontal
+ } else if y >= VERTICAL_LOCK_DISTANCE && y > x * AXIS_LOCK_RATIO {
+ self.phase = Phase::Vertical;
+ SidebarSpaceSwipeUpdate::Vertical(gesture.raw_y)
+ } else if max_axis >= AXIS_LOCK_FALLBACK_DISTANCE && x >= y {
+ self.phase = Phase::Tracking(gesture);
+ SidebarSpaceSwipeUpdate::Horizontal
+ } else if max_axis >= AXIS_LOCK_FALLBACK_DISTANCE {
+ self.phase = Phase::Vertical;
+ SidebarSpaceSwipeUpdate::Vertical(gesture.raw_y)
+ } else {
+ self.phase = Phase::Candidate(gesture);
+ SidebarSpaceSwipeUpdate::Pending
+ }
+ }
+ Phase::Tracking(mut gesture) => {
+ gesture.update(delta_x, delta_y, now);
+ self.phase = Phase::Tracking(gesture);
+ SidebarSpaceSwipeUpdate::Horizontal
+ }
+ Phase::Vertical => {
+ self.phase = Phase::Vertical;
+ SidebarSpaceSwipeUpdate::Vertical(delta_y)
+ }
+ other => {
+ self.phase = other;
+ SidebarSpaceSwipeUpdate::Pending
+ }
+ }
+ }
+
+ pub(crate) fn finish(&mut self, now: Instant, sidebar_width: f32) -> SidebarSpaceSwipeFinish {
+ let phase = std::mem::take(&mut self.phase);
+ match phase {
+ Phase::Tracking(gesture) if gesture.should_commit(sidebar_width) => {
+ self.suppress_momentum = true;
+ let target = gesture.target_space_id().cloned().expect("checked above");
+ self.phase = Phase::AwaitingCommit(gesture);
+ SidebarSpaceSwipeFinish::Switch(target)
+ }
+ Phase::Tracking(gesture) => {
+ self.suppress_momentum = true;
+ let from = gesture.display_offset(sidebar_width);
+ let target_space_id = gesture.target_space_id().cloned();
+ self.phase = Phase::Settling(Settle {
+ 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,
+ committed: false,
+ });
+ SidebarSpaceSwipeFinish::AnimateBack
+ }
+ Phase::Candidate(gesture) => {
+ // Below both lock distances the gesture is still undecided, so
+ // `update` has been swallowing every delta to keep the sidebar
+ // from twitching while the axis is in doubt. A stroke that ends
+ // here never reached the `Vertical` arm that flushes them, so
+ // hand the accumulation over now or a gentle nudge scrolls
+ // nothing at all.
+ self.phase = Phase::Idle;
+ self.suppress_momentum = false;
+ if gesture.raw_y.abs() > f32::EPSILON {
+ SidebarSpaceSwipeFinish::FlushVertical(gesture.raw_y)
+ } else {
+ SidebarSpaceSwipeFinish::None
+ }
+ }
+ Phase::Vertical => {
+ self.phase = Phase::Idle;
+ self.suppress_momentum = false;
+ SidebarSpaceSwipeFinish::None
+ }
+ other => {
+ self.phase = other;
+ SidebarSpaceSwipeFinish::None
+ }
+ }
+ }
+
+ pub(crate) fn resolve_switch(
+ &mut self,
+ switched: bool,
+ now: Instant,
+ sidebar_width: f32,
+ opening: SettleOpening,
+ ) {
+ let phase = std::mem::take(&mut self.phase);
+ match phase {
+ Phase::AwaitingCommit(gesture) => {
+ let from = match opening {
+ SettleOpening::WhereTheFingerLeftIt => gesture.display_offset(sidebar_width),
+ SettleOpening::AtRest => 0.0,
+ };
+ let target_space_id = gesture.target_space_id().cloned();
+ let target_offset = gesture.target_offset(sidebar_width);
+ self.phase = Phase::Settling(Settle {
+ 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,
+ committed: switched,
+ });
+ }
+ other => self.phase = other,
+ }
+ }
+
+ pub(crate) fn cancel_immediately(&mut self) {
+ self.phase = Phase::Idle;
+ self.suppress_momentum = false;
+ }
+
+ pub(crate) fn advance(&mut self, now: Instant) -> bool {
+ let phase = std::mem::take(&mut self.phase);
+ let Phase::Settling(mut settle) = phase else {
+ self.phase = phase;
+ 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 {
+ self.phase = Phase::Idle;
+ return false;
+ }
+
+ self.phase = Phase::Settling(settle);
+ true
+ }
+
+ pub(crate) fn visual(
+ &self,
+ now: Instant,
+ sidebar_width: f32,
+ ) -> Option<SidebarSpaceSwipeVisual> {
+ match &self.phase {
+ Phase::Tracking(gesture) | Phase::AwaitingCommit(gesture) => {
+ Some(SidebarSpaceSwipeVisual {
+ source_space_id: gesture.source_space_id.clone(),
+ target_space_id: gesture.target_space_id().cloned(),
+ source_scroll_offset: gesture.source_scroll_offset,
+ 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()
++ 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,
+ })
+ }
+ _ => None,
+ }
+ }
+
+ pub(crate) fn is_active(&self) -> bool {
+ !matches!(self.phase, Phase::Idle)
+ }
+
+ pub(crate) fn is_committing_or_committed(&self) -> bool {
+ matches!(
+ &self.phase,
+ Phase::AwaitingCommit(_)
+ | Phase::Settling(Settle {
+ committed: true,
+ ..
+ })
+ )
+ }
+
+ pub(crate) fn pending_switch_target(&self) -> Option<&str> {
+ match &self.phase {
+ Phase::AwaitingCommit(gesture) => gesture.target_space_id().map(String::as_str),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn consume_momentum(&mut self, ended: bool) -> bool {
+ let consume = self.suppress_momentum || self.is_active();
+ if ended {
+ self.suppress_momentum = false;
+ }
+ consume
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ fn at(start: Instant, millis: u64) -> Instant {
+ start + Duration::from_millis(millis)
+ }
+
+ #[test]
+ fn sidebar_page_push_tiles_source_and_target_across_the_list_viewport() {
+ assert_eq!(
+ sidebar_page_push_offsets(-150.0, 300.0, 300.0, -1.0),
+ (-150.0, 150.0)
+ );
+ assert_eq!(
+ sidebar_page_push_offsets(300.0, 300.0, 300.0, 1.0),
+ (300.0, 0.0)
+ );
+ }
+
+ #[test]
+ fn horizontal_gesture_tracks_then_commits_by_distance() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ assert!(swipe.begin(
+ "source".into(),
+ Some("previous".into()),
+ Some("next".into()),
+ 0.0,
+ start,
+ ));
+ assert_eq!(
+ swipe.update(-4.0, 1.0, at(start, 8)),
+ SidebarSpaceSwipeUpdate::Pending
+ );
+ assert_eq!(
+ swipe.update(-92.0, 1.0, at(start, 24)),
+ SidebarSpaceSwipeUpdate::Horizontal
+ );
+ assert_eq!(
+ swipe.visual(at(start, 24), 300.0),
+ Some(SidebarSpaceSwipeVisual {
+ source_space_id: "source".into(),
+ target_space_id: Some("next".into()),
+ source_scroll_offset: 0.0,
+ offset: -96.0,
+ })
+ );
+ assert_eq!(
+ swipe.finish(at(start, 30), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ swipe.resolve_switch(
+ true,
+ at(start, 30),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+ // The frame that commits renders the opening position -- the finger's
+ // own -96 -- and `advance`, run at the top of each paint, starts the
+ // clock on the frame after it.
+ assert_eq!(swipe.visual(at(start, 30), 300.0).unwrap().offset, -96.0);
+ assert!(swipe.advance(at(start, 100)));
+ assert!(swipe.visual(at(start, 200), 300.0).unwrap().offset < -96.0);
+ assert!(!swipe.advance(at(start, 340)));
+ }
+
+ #[test]
+ fn vertical_axis_stays_vertical_for_the_whole_gesture() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ assert_eq!(
+ swipe.update(2.0, -20.0, at(start, 16)),
+ SidebarSpaceSwipeUpdate::Vertical(-20.0)
+ );
+ assert_eq!(
+ swipe.update(-40.0, 1.0, at(start, 32)),
+ SidebarSpaceSwipeUpdate::Vertical(1.0)
+ );
+ assert_eq!(swipe.visual(at(start, 32), 300.0), None);
+ assert_eq!(
+ swipe.finish(at(start, 40), 300.0),
+ SidebarSpaceSwipeFinish::None
+ );
+ }
+
+ #[test]
+ fn the_pages_report_an_offset_while_the_finger_is_still_down() {
+ // The whole point of following the finger: an offset exists from the
+ // moment the axis locks, not only once the gesture has been released.
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ assert_eq!(
+ swipe.update(-20.0, 0.0, at(start, 16)),
+ SidebarSpaceSwipeUpdate::Horizontal
+ );
+ assert_eq!(swipe.visual(at(start, 16), 300.0).unwrap().offset, -20.0);
+ swipe.update(-30.0, 0.0, at(start, 32));
+ assert_eq!(swipe.visual(at(start, 32), 300.0).unwrap().offset, -50.0);
+
+ // Reversing under the finger walks it back, rather than latching.
+ swipe.update(45.0, 0.0, at(start, 48));
+ assert_eq!(swipe.visual(at(start, 48), 300.0).unwrap().offset, -5.0);
+ }
+
+ #[test]
+ fn reversing_past_the_start_retargets_the_neighbour_on_the_other_side() {
+ // A drag that crosses back over its origin is now approaching the
+ // *other* neighbour. The renderer captures whichever Space this
+ // reports, so getting it wrong composites a page against the Space it
+ // is sliding away from.
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin(
+ "source".into(),
+ Some("previous".into()),
+ Some("next".into()),
+ 0.0,
+ start,
+ );
+ swipe.update(-40.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.visual(at(start, 16), 300.0).unwrap().target_space_id,
+ Some("next".into())
+ );
+
+ swipe.update(70.0, 0.0, at(start, 32));
+ let visual = swipe.visual(at(start, 32), 300.0).unwrap();
+ assert_eq!(visual.target_space_id, Some("previous".into()));
+ assert_eq!(visual.offset, 30.0);
+ }
+
+ #[test]
- fn a_rebound_travels_back_instead_of_snapping(){
++ fn a_rebound_travels_back_instead_of_snapping() {
+ // A gesture too short to commit has still moved the pages, so it owes
+ // them a trip home. Before the pages tracked the finger there was
+ // nothing on screen to return and the settle was simply cancelled.
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-20.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 24), 300.0),
+ SidebarSpaceSwipeFinish::AnimateBack
+ );
+
+ // Still animating, and starting from where the finger let go.
+ assert_eq!(swipe.visual(at(start, 24), 300.0).unwrap().offset, -20.0);
+ assert!(swipe.advance(at(start, 30)));
+ let midway = swipe.visual(at(start, 130), 300.0).unwrap().offset;
+ assert!(
+ midway > -20.0 && midway < 0.0,
+ "expected travel back toward rest, got {}",
+ midway
+ );
+ assert_eq!(swipe.visual(at(start, 300), 300.0).unwrap().offset, 0.0);
+ }
+
+ #[test]
+ fn a_nudge_too_small_to_lock_an_axis_still_scrolls_by_what_it_travelled() {
+ // Under both lock distances `update` reports Pending and keeps the
+ // deltas to itself, so the sidebar cannot twitch while the axis is
+ // undecided. Nothing downstream sees those events -- the swipe handler
+ // has already claimed them -- so ending here has to hand them back.
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ for frame in 1..=3 {
+ assert_eq!(
+ swipe.update(0.0, -4.0, at(start, frame * 16)),
+ SidebarSpaceSwipeUpdate::Pending,
+ "12 pixels is under VERTICAL_LOCK_DISTANCE, so nothing scrolls yet"
+ );
+ }
+ assert_eq!(
+ swipe.finish(at(start, 64), 300.0),
+ SidebarSpaceSwipeFinish::FlushVertical(-12.0)
+ );
+
+ // A gesture that never moved has nothing to hand back, and must not
+ // pass a zero scroll to the sidebar.
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ assert_eq!(
+ swipe.finish(at(start, 16), 300.0),
+ SidebarSpaceSwipeFinish::None
+ );
+ }
+
+ #[test]
+ fn early_vertical_noise_does_not_steal_a_horizontal_swipe() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+
+ assert_eq!(
+ swipe.update(-1.0, 5.0, at(start, 8)),
+ SidebarSpaceSwipeUpdate::Pending
+ );
+ assert_eq!(
+ swipe.update(-2.0, 5.0, at(start, 16)),
+ SidebarSpaceSwipeUpdate::Pending
+ );
+ assert_eq!(
+ swipe.update(-12.0, 2.0, at(start, 24)),
+ SidebarSpaceSwipeUpdate::Horizontal
+ );
+ assert_eq!(swipe.visual(at(start, 24), 300.0).unwrap().offset, -15.0);
+ }
+
+ #[test]
+ fn short_slow_drag_animates_back_without_switching() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-20.0, 0.0, at(start, 100));
+ assert_eq!(
+ swipe.finish(at(start, 200), 300.0),
+ SidebarSpaceSwipeFinish::AnimateBack
+ );
+ let before = swipe.visual(at(start, 200), 300.0).unwrap().offset;
+ let after = swipe.visual(at(start, 300), 300.0).unwrap().offset;
+ assert!(before < 0.0);
+ assert!(after > before);
+ }
+
+ #[test]
+ fn quick_flick_commits_before_the_distance_threshold() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-10.0, 0.0, at(start, 8));
+ swipe.update(-10.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ }
+
+ #[test]
+ fn unavailable_edge_is_resisted_and_never_commits() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(400.0, 0.0, at(start, 16));
+ let visual = swipe.visual(at(start, 16), 300.0).unwrap();
+ assert_eq!(visual.target_space_id, None);
+ assert_eq!(visual.offset, 48.0);
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::AnimateBack
+ );
+ }
+
+ #[test]
+ fn momentum_is_suppressed_after_a_completed_gesture() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-20.0, 0.0, at(start, 16));
+ swipe.finish(at(start, 20), 300.0);
+ assert!(swipe.consume_momentum(false));
+ assert!(swipe.consume_momentum(true));
+ swipe.cancel_immediately();
+ assert!(!swipe.consume_momentum(false));
+ }
+
+ #[test]
+ fn a_rejected_switch_returns_to_the_source_and_cannot_commit_twice() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 23.0, start);
+ swipe.update(-120.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ assert_eq!(
+ swipe.finish(at(start, 21), 300.0),
+ SidebarSpaceSwipeFinish::None
+ );
+
+ swipe.resolve_switch(
+ false,
+ at(start, 24),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+ let visual = swipe.visual(at(start, 100), 300.0).unwrap();
+ assert_eq!(visual.source_scroll_offset, 23.0);
+ assert!(visual.offset > -120.0);
+ assert!(visual.offset < 0.0);
+ }
+
+ #[test]
+ fn committed_settle_survives_layout_sync_until_the_animation_finishes() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-120.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ swipe.resolve_switch(
+ true,
+ at(start, 20),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+
+ assert!(swipe.is_committing_or_committed());
+ // First paint after the commit: starts the clock, nothing elapsed yet.
+ assert!(swipe.advance(at(start, 120)));
+ assert!(swipe.is_committing_or_committed());
+ assert!(swipe.advance(at(start, 250)));
+ assert!(swipe.is_committing_or_committed());
+ assert!(!swipe.advance(at(start, 350)));
+ assert!(!swipe.is_committing_or_committed());
+ }
+
+ #[test]
+ fn awaiting_commit_is_preserved_during_the_switch_layout_sync() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-120.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+
+ // switch_space_to_thread can synchronously cause a Resized event
+ // before resolve_switch records the successful commit.
+ assert!(swipe.is_committing_or_committed());
+ swipe.resolve_switch(
+ true,
+ at(start, 20),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+ assert!(swipe.is_committing_or_committed());
+ }
+
+ #[test]
+ fn committed_animation_clock_starts_after_slow_space_adoption() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-120.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+
+ // Model a destination adoption that takes much longer than the visual
+ // transition. Resolution supplies a fresh clock after that work.
+ let adoption_finished = at(start, 1_000);
+ swipe.resolve_switch(
+ true,
+ adoption_finished,
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+ assert!(swipe.advance(adoption_finished));
+ assert_eq!(
+ swipe.visual(adoption_finished, 300.0).unwrap().offset,
+ -120.0
+ );
+ assert!(swipe.advance(at(start, 1_100)));
+ assert!(!swipe.advance(at(start, 1_250)));
+ }
+
+ #[test]
+ fn unpainted_full_distance_swipe_still_has_a_visible_commit_animation() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-500.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ // A flick this fast is over before a frame is composited, so the pages
+ // never left rest. Opening where the finger "left off" would put them
+ // at the full -300 immediately and the switch would be an instant cut.
+ swipe.resolve_switch(true, at(start, 1_000), 300.0, SettleOpening::AtRest);
+
+ let first = swipe.visual(at(start, 1_000), 300.0).unwrap().offset;
+ assert_eq!(first, 0.0);
+ assert!(swipe.advance(at(start, 1_000)));
+ let middle = swipe.visual(at(start, 1_100), 300.0).unwrap().offset;
+ let last = swipe.visual(at(start, 1_220), 300.0).unwrap().offset;
+ assert!(middle < first && middle > -300.0);
+ assert_eq!(last, -300.0);
+ }
+
+ /// Regression: macOS routinely delivers a trailing `Ended` after momentum
+ /// has already ended the gesture, so `finish` runs a second time moments
+ /// after a commit. That second call has nothing to settle and returns
+ /// `None` -- which the caller read as "no gesture in flight" and used to
+ /// tear down the frame transition, destroying the just-committed animation
+ /// before its first frame. `None` must therefore leave an in-flight settle
+ /// completely untouched, and `is_active` must stay true so the caller can
+ /// tell "nothing to do" apart from "nothing here".
+ #[test]
+ fn a_second_finish_after_committing_reports_none_without_disturbing_the_settle() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-120.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+
+ // Trailing Ended, still in AwaitingCommit.
- assert_eq!(swipe.finish(at(start, 21), 300.0), SidebarSpaceSwipeFinish::None);
++ assert_eq!(
++ swipe.finish(at(start, 21), 300.0),
++ SidebarSpaceSwipeFinish::None
++ );
+ assert!(swipe.is_active());
+ assert!(swipe.is_committing_or_committed());
+ assert_eq!(swipe.pending_switch_target(), Some("next"));
+
+ swipe.resolve_switch(
+ true,
+ at(start, 22),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+ assert!(swipe.advance(at(start, 30)));
+
+ // And again once the settle is running.
- assert_eq!(swipe.finish(at(start, 40), 300.0), SidebarSpaceSwipeFinish::None);
++ assert_eq!(
++ swipe.finish(at(start, 40), 300.0),
++ SidebarSpaceSwipeFinish::None
++ );
+ assert!(swipe.is_active());
+ assert!(swipe.is_committing_or_committed());
- let mid = swipe.visual(at(start, 120), 300.0).expect("settle still live");
++ let mid = swipe
++ .visual(at(start, 120), 300.0)
++ .expect("settle still live");
+ assert!(mid.offset < 0.0 && mid.offset > -300.0);
+
+ // An idle machine is the only case where `None` really means empty.
+ swipe.cancel_immediately();
- assert_eq!(swipe.finish(at(start, 50), 300.0), SidebarSpaceSwipeFinish::None);
++ assert_eq!(
++ swipe.finish(at(start, 50), 300.0),
++ SidebarSpaceSwipeFinish::None
++ );
+ assert!(!swipe.is_active());
+ }
+
+ /// The commit frame adopts the destination Space, so it can take 100ms+ of
+ /// glyph rasterisation before it reaches the screen. That cost must not be
+ /// billed to the 220ms transition, or the first visible motion jumps
+ /// straight to ~87% and the swipe reads as an instant cut.
+ #[test]
+ fn a_slow_commit_frame_does_not_consume_the_transition() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-120.0, 0.0, at(start, 16));
+ assert_eq!(
+ swipe.finish(at(start, 20), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ swipe.resolve_switch(true, at(start, 20), 300.0, SettleOpening::AtRest);
+
+ // That first frame takes 500ms to present.
+ let after_slow_frame = at(start, 520);
+ assert!(swipe.advance(after_slow_frame));
+ assert_eq!(swipe.visual(after_slow_frame, 300.0).unwrap().offset, 0.0);
+
+ // A full 220ms of travel is still ahead, measured from that point.
+ let mid = swipe.visual(at(start, 520 + 110), 300.0).unwrap().offset;
+ assert!(mid < 0.0 && mid > -300.0);
+ assert!(swipe.advance(at(start, 520 + 200)));
+ assert!(!swipe.advance(at(start, 520 + 240)));
+ }
+
+ #[test]
+ fn a_committed_push_opens_where_the_finger_let_go() {
+ let start = Instant::now();
+ let mut swipe = SidebarSpaceSwipeState::default();
+ swipe.begin("source".into(), None, Some("next".into()), 0.0, start);
+ swipe.update(-40.0, 0.0, at(start, 16));
+ swipe.update(-40.0, 0.0, at(start, 48));
+ swipe.update(-40.0, 0.0, at(start, 80));
+ assert_eq!(
+ swipe.finish(at(start, 90), 300.0),
+ SidebarSpaceSwipeFinish::Switch("next".into())
+ );
+ swipe.resolve_switch(
+ true,
+ at(start, 100),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
+ // The pages have been sitting at -120 under the finger. Opening the
+ // settle anywhere else -- at rest, most temptingly -- yanks them
+ // backwards for one frame before they travel on.
+ assert_eq!(swipe.visual(at(start, 100), 300.0).unwrap().offset, -120.0);
+ }
++
++ #[test]
++ fn atlas_recreation_preserves_only_a_commit_waiting_for_its_source_capture() {
++ assert!(preserve_pending_source_capture_after_atlas_recreation(
++ false, true, true
++ ));
++
++ assert!(!preserve_pending_source_capture_after_atlas_recreation(
++ true, true, true
++ ));
++ assert!(!preserve_pending_source_capture_after_atlas_recreation(
++ false, false, true
++ ));
++ assert!(!preserve_pending_source_capture_after_atlas_recreation(
++ false, true, false
++ ));
++ }
+ }
diff --cc wezterm-gui/src/termwindow/ui/sidebar.rs
index 9333796f,26d82ee6..e8ef030a
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@@ -817,10 -819,10 +819,11 @@@ impl crate::TermWindow
ui_cell_height: usize,
register_ui_item: bool,
) -> anyhow::Result<()> {
- let reconnect_in_flight = workspace_threads::client_domain_for_space(&self.active_space_id)
- let reconnect_in_flight = workspace_threads::client_domain_for_space(self.workspace_sidebar_space_id())
-- .map_or(false, |name| {
-- self.space_reconnects_in_flight.contains(&name)
-- });
++ let reconnect_in_flight =
++ workspace_threads::client_domain_for_space(self.workspace_sidebar_space_id())
++ .map_or(false, |name| {
++ self.space_reconnects_in_flight.contains(&name)
++ });
let hovered =
!reconnect_in_flight && self.is_pointer_over_ui_rect(row_x, y, row_width, row_height);
self.fill_rounded_rectangle(
@@@ -1172,9 -1178,9 +1179,10 @@@
.saturating_add(space_menu_width)
.saturating_sub(self.ui_px(SIDEBAR_INSET) + space_action_icon_size + top_action_gap);
let space_text_x = space_icon_x + space_icon_size + top_action_gap;
- let space_name = crate::workspace_threads::active_space_name(&self.active_space_id)
- let space_name = crate::workspace_threads::active_space_name(self.workspace_sidebar_space_id())
-- .unwrap_or_else(|| crate::i18n::tr("sidebar-default-space"));
- let space_title = self.sidebar_space_title(&self.active_space_id, &space_name);
++ let space_name =
++ crate::workspace_threads::active_space_name(self.workspace_sidebar_space_id())
++ .unwrap_or_else(|| crate::i18n::tr("sidebar-default-space"));
+ let space_title = self.sidebar_space_title(self.workspace_sidebar_space_id(), &space_name);
let space_label = self.ellipsize_ui_text(
&ui_font,
&space_title,
diff --cc wezterm-gui/src/ui/draw.rs
index a4b0e542,2a924faf..7dd64b88
--- a/wezterm-gui/src/ui/draw.rs
+++ b/wezterm-gui/src/ui/draw.rs
@@@ -9,16 -9,11 +9,17 @@@
//! becomes the borrowed `self.render_state` field.
use crate::customglyph::{BlockKey, Poly};
-use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::quad::{
- HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait,
++ HeapQuadAllocator, QuadClipRect, QuadTrait, TripleLayerQuadAllocator,
++ TripleLayerQuadAllocatorTrait,
+};
use crate::renderstate::RenderState;
use crate::termwindow::render::corners::{
- BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
- TOP_RIGHT_ROUNDED_CORNER,
+ BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_LEFT_ROUNDED_CORNER_MASK,
+ BOTTOM_LEFT_ROUNDED_CORNER_OUTLINE, BOTTOM_RIGHT_ROUNDED_CORNER,
+ BOTTOM_RIGHT_ROUNDED_CORNER_MASK, BOTTOM_RIGHT_ROUNDED_CORNER_OUTLINE, TOP_LEFT_ROUNDED_CORNER,
+ TOP_LEFT_ROUNDED_CORNER_MASK, TOP_LEFT_ROUNDED_CORNER_OUTLINE, TOP_RIGHT_ROUNDED_CORNER,
+ TOP_RIGHT_ROUNDED_CORNER_MASK, TOP_RIGHT_ROUNDED_CORNER_OUTLINE,
};
use crate::termwindow::ui::icons::{BrandIcon, SvgIcon};
use crate::utilsprites::RenderMetrics;
@@@ -91,225 -86,6 +92,227 @@@ impl<'a> DrawContext<'a>
Ok(())
}
+ /// Draw a true GPU-interpolated gradient using a single quad. This keeps
+ /// full-window native UI backgrounds smooth without uploading a texture or
+ /// exposing visible color bands on large displays.
+ pub(crate) fn draw_vertical_gradient(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ area: RectF,
+ top: LinearRgba,
+ bottom: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if area.size.width <= 0.0 || area.size.height <= 0.0 {
+ return Ok(());
+ }
+
+ let mut quad = layers.allocate(layer_num)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ area.origin.x - left_offset,
+ area.origin.y - top_offset,
+ area.max_x() - left_offset,
+ area.max_y() - top_offset,
+ );
+ quad.set_texture(self.render_state.util_sprites.filled_box.texture_coords());
+ quad.set_is_background();
+ quad.set_vertical_gradient(top, bottom);
+ quad.set_alt_color_and_mix_value(top, 0.0);
+ quad.set_hsv(None);
+ Ok(())
+ }
+
+ /// Draw a smoothly interpolated four-corner gradient with one GPU quad.
+ /// This is intended for restrained native surfaces where a flat vertical
+ /// blend is visually too uniform but a texture or blur would be wasteful.
+ pub(crate) fn draw_corner_gradient(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ area: RectF,
+ top_left: LinearRgba,
+ top_right: LinearRgba,
+ bottom_left: LinearRgba,
+ bottom_right: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if area.size.width <= 0.0 || area.size.height <= 0.0 {
+ return Ok(());
+ }
+
+ let mut quad = layers.allocate(layer_num)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ area.origin.x - left_offset,
+ area.origin.y - top_offset,
+ area.max_x() - left_offset,
+ area.max_y() - top_offset,
+ );
+ quad.set_texture(self.render_state.util_sprites.filled_box.texture_coords());
+ quad.set_is_background();
+ quad.set_corner_gradient(top_left, top_right, bottom_left, bottom_right);
+ quad.set_alt_color_and_mix_value(top_left, 0.0);
+ quad.set_hsv(None);
+ Ok(())
+ }
+
+ /// Standard elevated surface used by overview cards. Two restrained
+ /// layers provide depth without a hard concentric halo.
+ pub(crate) fn draw_elevated_surface(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ rect: RectF,
+ fill: LinearRgba,
+ border: LinearRgba,
+ shadow: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ for (spread, offset_y, alpha) in [
+ (self.px(6.0), self.px(5.0), 0.14),
+ (self.px(2.0), self.px(3.0), 0.24),
+ ] {
+ self.draw_rounded_rect(
+ layers,
+ layer_num,
+ rect.origin.x - spread,
+ rect.origin.y - spread + offset_y,
+ rect.size.width + spread * 2.0,
+ rect.size.height + spread * 2.0,
+ color_with_alpha(shadow, shadow.3 * alpha),
+ radius + spread,
+ )?;
+ }
+ self.draw_rounded_frame(
+ layers,
+ layer_num,
+ rect.origin.x,
+ rect.origin.y,
+ rect.size.width,
+ rect.size.height,
+ fill,
+ border,
+ radius,
+ )
+ }
+
+ /// Cover the four wedges outside a rounded preview after the terminal has
+ /// been painted, then redraw its thin outline. The complete chrome is
+ /// emitted into a heap buffer and clipped as quads, so a corner crossing a
+ /// scroll boundary remains rounded instead of disappearing all at once.
+ pub(crate) fn draw_rounded_preview_chrome(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ rect: RectF,
+ clip: RectF,
+ mask: LinearRgba,
+ border: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ let radius = radius
+ .min(rect.size.width / 2.0)
+ .min(rect.size.height / 2.0)
+ .round()
+ .max(0.0);
+ if radius <= 0.0 {
+ return Ok(());
+ }
+ let size = euclid::size2(radius, radius);
+
+ let corners = [
+ (
+ rect.min_x(),
+ rect.min_y(),
+ TOP_LEFT_ROUNDED_CORNER_MASK,
+ TOP_LEFT_ROUNDED_CORNER_OUTLINE,
+ ),
+ (
+ rect.max_x() - radius,
+ rect.min_y(),
+ TOP_RIGHT_ROUNDED_CORNER_MASK,
+ TOP_RIGHT_ROUNDED_CORNER_OUTLINE,
+ ),
+ (
+ rect.min_x(),
+ rect.max_y() - radius,
+ BOTTOM_LEFT_ROUNDED_CORNER_MASK,
+ BOTTOM_LEFT_ROUNDED_CORNER_OUTLINE,
+ ),
+ (
+ rect.max_x() - radius,
+ rect.max_y() - radius,
+ BOTTOM_RIGHT_ROUNDED_CORNER_MASK,
+ BOTTOM_RIGHT_ROUNDED_CORNER_OUTLINE,
+ ),
+ ];
+ let mut heap = HeapQuadAllocator::default();
+ {
+ let mut clipped_layers = TripleLayerQuadAllocator::Heap(&mut heap);
+ for (x, y, mask_poly, outline_poly) in corners {
+ self.draw_corner(&mut clipped_layers, layer_num, x, y, mask_poly, size, mask)?;
+ self.draw_corner(
+ &mut clipped_layers,
+ layer_num,
+ x,
+ y,
+ outline_poly,
+ size,
+ border,
+ )?;
+ }
+
+ let stroke = self.px(1.0).max(1.0);
+ let edges: [RectF; 4] = [
+ euclid::rect(
+ rect.min_x() + radius,
+ rect.min_y(),
+ rect.size.width - radius * 2.0,
+ stroke,
+ ),
+ euclid::rect(
+ rect.min_x() + radius,
+ rect.max_y() - stroke,
+ rect.size.width - radius * 2.0,
+ stroke,
+ ),
+ euclid::rect(
+ rect.min_x(),
+ rect.min_y() + radius,
+ stroke,
+ rect.size.height - radius * 2.0,
+ ),
+ euclid::rect(
+ rect.max_x() - stroke,
+ rect.min_y() + radius,
+ stroke,
+ rect.size.height - radius * 2.0,
+ ),
+ ];
+ for edge in edges {
+ self.draw_rect(
+ &mut clipped_layers,
+ layer_num,
+ edge.origin.x,
+ edge.origin.y,
+ edge.size.width,
+ edge.size.height,
+ border,
+ )?;
+ }
+ }
- heap.apply_to_clipped(
- layers,
- clip,
- self.dimensions.pixel_width as f32,
- self.dimensions.pixel_height as f32,
- )
++ let clip = QuadClipRect::from_top_left_pixels(
++ clip.min_x(),
++ clip.min_y(),
++ clip.max_x(),
++ clip.max_y(),
++ &self.dimensions,
++ );
++ heap.apply_to_clipped(layers, clip)
+ }
+
pub(crate) fn draw_rounded_rect(
&self,
layers: &mut TripleLayerQuadAllocator<'_>,
diff --cc wezterm-gui/src/workspace_threads.rs
index b084ca6e,b87051d0..c6658b71
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@@ -5236,10 -5281,18 +5314,17 @@@ fn persist_snapshot(store: &WorkspaceTh
if STORE_IS_UNREADABLE.load(Ordering::Acquire) {
return;
}
- if let Err(err) = save_workspace_thread_store(store) {
- log::warn!("failed to save ThinkTerm thread store: {err:#}");
- let wrote = THREAD_STORE_WRITES.write_if_newest(seq, || {
- match save_workspace_thread_store(store) {
++ let wrote =
++ THREAD_STORE_WRITES.write_if_newest(seq, || match save_workspace_thread_store(store) {
+ Ok(()) => true,
+ Err(err) => {
+ log::warn!("failed to save ThinkTerm thread store: {err:#}");
+ false
+ }
- }
- });
++ });
+ if wrote {
+ publish_thinkterm_session_changed();
}
- publish_thinkterm_session_changed();
}
fn schedule_workspace_thread_store_persist() {