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.

Make the sidebar Space swipe follow the finger

RoversX20d1ce2fcf2d
diff --git a/wezterm-gui/src/quad.rs b/wezterm-gui/src/quad.rs
index abb0997b..cb9ab693 100644
--- a/wezterm-gui/src/quad.rs
+++ b/wezterm-gui/src/quad.rs
@@ -435,10 +435,47 @@ impl QuadClipRect {
}
}
+/// How many quads a [`HeapQuadAllocator`] held at some point during a paint.
+///
+/// Splitting a recorded frame by screen position cannot distinguish a scrolling
+/// row from the chrome drawn over it: the two overlap on purpose, so any
+/// horizontal line drawn through them cuts something in half. Recording where
+/// the painter *was* instead splits by what was being drawn, which is the
+/// question a compositor actually needs answered.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct HeapQuadMark {
+ layer0: usize,
+ layer1: usize,
+ layer2: usize,
+}
+
impl HeapQuadAllocator {
+ /// Where the next quad will land, for later use with [`Self::apply_before`],
+ /// [`Self::apply_between`] and [`Self::apply_after`].
+ pub fn mark(&self) -> HeapQuadMark {
+ HeapQuadMark {
+ layer0: self.layer0.len(),
+ layer1: self.layer1.len(),
+ layer2: self.layer2.len(),
+ }
+ }
+
+ fn layers(&self) -> [(usize, &Vec<Box<BoxedQuad>>); 3] {
+ [(0, &self.layer0), (1, &self.layer1), (2, &self.layer2)]
+ }
+
+ fn layer_bounds(mark: &HeapQuadMark, layer_num: usize) -> usize {
+ match layer_num {
+ 0 => mark.layer0,
+ 1 => mark.layer1,
+ 2 => mark.layer2,
+ _ => unreachable!(),
+ }
+ }
+
pub fn apply_to(&self, other: &mut TripleLayerQuadAllocator) -> anyhow::Result<()> {
let start = std::time::Instant::now();
- for (layer_num, quads) in [(0, &self.layer0), (1, &self.layer1), (2, &self.layer2)] {
+ for (layer_num, quads) in self.layers() {
for quad in quads {
other.extend_with(layer_num, &quad.to_vertices());
}
@@ -447,22 +484,63 @@ impl HeapQuadAllocator {
Ok(())
}
- pub fn apply_to_translated_clipped_rect(
+ /// 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 start = std::time::Instant::now();
- for (layer_num, quads) in [(0, &self.layer0), (1, &self.layer1), (2, &self.layer2)] {
- for quad in quads {
+ 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 {
continue;
};
other.extend_with(layer_num, &vertices);
}
}
- metrics::histogram!("quad_buffer_translated_rect_clip_apply").record(start.elapsed());
+ metrics::histogram!("quad_buffer_translated_rect_clip_apply").record(started.elapsed());
Ok(())
}
}
@@ -585,6 +663,19 @@ pub enum TripleLayerQuadAllocator<'a> {
},
}
+impl<'a> TripleLayerQuadAllocator<'a> {
+ /// The heap's current position, when there is a heap to record into.
+ /// `Gpu` allocators cannot be replayed, so a painter drawing straight to
+ /// the GPU has nothing to mark.
+ pub fn heap_mark(&self) -> Option<HeapQuadMark> {
+ match self {
+ Self::Gpu(_) => None,
+ Self::Heap(heap) => Some(heap.mark()),
+ Self::Tee { heap, .. } => Some(heap.mark()),
+ }
+ }
+}
+
impl<'a> TripleLayerQuadAllocatorTrait for TripleLayerQuadAllocator<'a> {
fn allocate(&mut self, layer_num: usize) -> anyhow::Result<QuadImpl<'_>> {
match self {
@@ -697,6 +788,64 @@ mod translated_clip_tests {
assert!(quad.translated_clipped_vertices(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 {
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 419ab1bd..fe529bd6 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -9,7 +9,7 @@ use crate::overlay::{
start_overlay, start_overlay_pane, CopyModeParams, CopyOverlay, LauncherArgs, LauncherFlags,
QuickSelectOverlay,
};
-use crate::quad::HeapQuadAllocator;
+use crate::quad::{HeapQuadAllocator, HeapQuadMark};
use crate::resize_increment_calculator::ResizeIncrementCalculator;
use crate::scripting::guiwin::GuiWin;
use crate::scrollbar::*;
@@ -1340,6 +1340,17 @@ pub(crate) struct RemoteDividerResizeStream {
pub(crate) final_acknowledged_at: Option<Instant>,
}
+/// A recorded left sidebar, kept so the outgoing Space can be composited
+/// against the incoming one.
+pub(crate) struct CapturedSidebar {
+ pub(crate) quads: HeapQuadAllocator,
+ /// The stretch of `quads` holding the scrolling project list. The rest is
+ /// chrome that deliberately overlaps it -- the bottom fade, the settings
+ /// row -- so only a split by paint order, never by screen position, can
+ /// separate what slides from what stays.
+ pub(crate) list: Option<(HeapQuadMark, HeapQuadMark)>,
+}
+
pub struct TermWindow {
pub window: Option<Window>,
pub config: ConfigHandle,
@@ -1501,16 +1512,40 @@ pub struct TermWindow {
workspace_sidebar_pending_thread_selection: Option<String>,
workspace_sidebar_collapsed: bool,
workspace_sidebar_scroll_offset: f32,
+ /// Where each Space's sidebar was scrolled to when the window last left
+ /// it. Switching used to send every Space back to the top, so glancing at
+ /// a neighbour cost you your place in a long list.
+ workspace_sidebar_scroll_offsets: HashMap<String, f32>,
workspace_sidebar_swipe: space_swipe::SidebarSpaceSwipeState,
/// A CPU-side copy of the source Space's left sidebar. During a committed
/// switch only its middle project/thread list viewport is composited beside
/// the destination; sidebar chrome and the rest of the window stay live.
- workspace_space_swipe_source_frame: Option<HeapQuadAllocator>,
+ workspace_space_swipe_source_frame: Option<CapturedSidebar>,
workspace_space_swipe_capture_source: bool,
workspace_space_swipe_push_active: bool,
workspace_space_swipe_direction: f32,
workspace_space_swipe_pending_commit: Option<(String, f32)>,
workspace_space_swipe_needs_settle_start: bool,
+ /// The Space whose sidebar is being painted right now, when that is not
+ /// the adopted one. A swipe paints the neighbouring Space into an
+ /// offscreen buffer so it can slide in under the finger; this is how that
+ /// paint reads the neighbour's projects and threads without the window
+ /// actually switching to it.
+ workspace_sidebar_preview_space_id: Option<String>,
+ /// The neighbouring Space's sidebar, and which Space it holds. Captured
+ /// once when the axis locks rather than every frame: it is not
+ /// interactive while the finger is down, and re-rasterising its glyphs
+ /// per frame would cost more than the whole animation budget.
+ workspace_space_swipe_target_frame: Option<(String, CapturedSidebar)>,
+ /// Whether any frame was composited with the pages following the finger.
+ /// A flick that begins and ends between two paints never gets one, and
+ /// its transition has to open at rest to be seen at all.
+ workspace_space_swipe_tracked: bool,
+ /// Where the scrolling list began and ended in the most recent
+ /// heap-recorded sidebar paint. `paint_workspace_sidebar` clears this on
+ /// entry and sets it around the row loop, so it describes that paint and
+ /// no other; a paint that bailed out before the list leaves it `None`.
+ workspace_sidebar_list_quads: Option<(HeapQuadMark, HeapQuadMark)>,
workspace_sidebar_scrollbar_visible_until: Option<Instant>,
/// Last notification state painted by this GUI window. Comparing identities
/// and statuses (rather than just the count) lets the bell pulse when one
@@ -1872,8 +1907,40 @@ 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;
@@ -2293,9 +2360,14 @@ impl TermWindow {
workspace_sidebar_pending_thread_selection: None,
workspace_sidebar_collapsed: !native_settings.onboarding.show_left_sidebar_by_default,
workspace_sidebar_scroll_offset: 0.0,
+ workspace_sidebar_scroll_offsets: HashMap::new(),
workspace_sidebar_swipe: space_swipe::SidebarSpaceSwipeState::default(),
workspace_space_swipe_source_frame: None,
workspace_space_swipe_capture_source: false,
+ workspace_sidebar_preview_space_id: None,
+ workspace_space_swipe_target_frame: None,
+ workspace_space_swipe_tracked: false,
+ workspace_sidebar_list_quads: None,
workspace_space_swipe_push_active: false,
workspace_space_swipe_direction: 0.0,
workspace_space_swipe_pending_commit: None,
@@ -3772,10 +3844,11 @@ impl TermWindow {
// correct document and keyboard input can reach the destination pane.
self.clear_right_sidebar_text_focus();
self.set_content_view_active(false);
+ self.remember_workspace_sidebar_scroll();
self.active_space_id = space_id.clone();
self.refresh_active_space_note_vault_flag();
self.sync_content_view_surfaces_with_mux();
- self.workspace_sidebar_scroll_offset = 0.0;
+ self.workspace_sidebar_scroll_offset = self.remembered_workspace_sidebar_scroll();
// Vault availability differs between Spaces; an expanded Note pane
// can activate or deactivate here and the terminal must follow. The
// reflow is deferred until switch_to_mux_window adopts the
@@ -3856,10 +3929,12 @@ impl TermWindow {
let deleted_active_space = self.active_space_id == space_id;
if deleted_active_space {
let previous_sidebar_width = self.right_sidebar_width();
+ self.workspace_sidebar_scroll_offsets.remove(space_id);
self.active_space_id = deleted.fallback_space_id.clone();
self.refresh_active_space_note_vault_flag();
self.sync_content_view_surfaces_with_mux();
- self.workspace_sidebar_scroll_offset = 0.0;
+ self.workspace_sidebar_scroll_offset =
+ self.remembered_workspace_sidebar_scroll();
// Deferred until the fallback Space's mux window is
// adopted so the resize does not hit the deleted Space's
// panes.
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 29cbb647..4a4693a8 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -946,6 +946,9 @@ impl super::TermWindow {
if self.workspace_space_swipe_source_frame.is_none() {
self.prepare_workspace_space_swipe_source_capture();
}
+ // Whether the pages tracked is a fact about *this* gesture. The
+ // previous one having tracked must not decide how this one opens.
+ self.workspace_space_swipe_tracked = false;
self.workspace_sidebar_swipe.begin(
self.active_space_id.clone(),
previous,
@@ -1014,11 +1017,19 @@ impl super::TermWindow {
true
}
SidebarSpaceSwipeFinish::AnimateBack => {
- self.workspace_sidebar_swipe.cancel_immediately();
- self.clear_workspace_space_swipe_frame_transition();
+ // The pages already followed the finger out, so they have to
+ // travel back rather than blink into place. `finish` has put
+ // the state machine into a settle that does exactly that;
+ // leave the captured neighbour alive to be composited until
+ // `advance` retires it.
context.invalidate();
true
}
+ SidebarSpaceSwipeFinish::FlushVertical(delta_y) => {
+ self.clear_workspace_space_swipe_frame_transition();
+ self.scroll_workspace_sidebar_by(-delta_y, context);
+ true
+ }
SidebarSpaceSwipeFinish::None => {
// `None` means "this call had no gesture to settle". That is
// true both when nothing was in flight and when a previous
@@ -1067,10 +1078,18 @@ impl super::TermWindow {
0.0
};
self.workspace_space_swipe_capture_source = false;
+ // The Space this held is the one now adopted, so it is the live paint
+ // from here on; keeping the capture would only leave the compositor a
+ // stale copy to choose.
+ self.workspace_space_swipe_target_frame = None;
self.workspace_space_swipe_needs_settle_start = self.workspace_space_swipe_push_active;
if !switched {
- self.workspace_sidebar_swipe
- .resolve_switch(false, Instant::now(), width);
+ self.workspace_sidebar_swipe.resolve_switch(
+ false,
+ Instant::now(),
+ width,
+ crate::termwindow::space_swipe::SettleOpening::WhereTheFingerLeftIt,
+ );
}
if !self.workspace_space_swipe_push_active {
self.workspace_sidebar_swipe.cancel_immediately();
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index 7512444e..6b95ec5a 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -264,6 +264,21 @@ 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();
if let Err(err) = result {
self.allow_images = match self.allow_images {
@@ -785,31 +800,116 @@ impl crate::TermWindow {
}
}
- if self.workspace_space_swipe_push_active && !self.workspace_sidebar_swipe.is_active() {
+ if !self.workspace_sidebar_swipe.is_active() {
+ // The gesture is over, whether it committed, rebounded or never
+ // locked an axis. Retire both captures: holding either one would
+ // keep the compositor splitting a sidebar that is no longer
+ // transitioning.
self.workspace_space_swipe_push_active = false;
self.workspace_space_swipe_source_frame = None;
+ self.workspace_space_swipe_target_frame = None;
self.workspace_space_swipe_direction = 0.0;
+ self.workspace_space_swipe_tracked = false;
}
}
+ /// Where the outgoing and incoming list pages sit this frame, as
+ /// `(source, target)`. Live throughout the gesture, not just after the
+ /// commit: the pages follow the finger, so an offset exists as soon as the
+ /// axis locks horizontal.
fn workspace_space_swipe_push_offsets(
&self,
now: Instant,
page_width: f32,
) -> Option<(f32, f32)> {
- if !self.workspace_space_swipe_push_active {
- return None;
- }
let gesture_extent = self.workspace_sidebar_width() as f32;
let visual = self.workspace_sidebar_swipe.visual(now, gesture_extent)?;
+ // Before the commit the direction is whichever way the finger has
+ // travelled; after it, the committed direction is authoritative,
+ // because the settle animates the offset back through zero and its
+ // sign would otherwise flip mid-transition.
+ let direction = if self.workspace_space_swipe_push_active {
+ self.workspace_space_swipe_direction
+ } else {
+ visual.offset.signum()
+ };
Some(super::super::space_swipe::sidebar_page_push_offsets(
visual.offset,
gesture_extent,
page_width,
- self.workspace_space_swipe_direction,
+ direction,
))
}
+ /// Record the neighbouring Space's sidebar so it can slide in beside the
+ /// live one while the finger is still down.
+ ///
+ /// Cheap to call every frame: it repaints only when the neighbour changes,
+ /// which is once when the axis locks and once more if the drag reverses.
+ fn capture_workspace_space_swipe_target(&mut self, now: Instant) -> anyhow::Result<()> {
+ if self.workspace_space_swipe_push_active {
+ // The switch already happened, so the live sidebar *is* the
+ // destination and the outgoing one is held in the source frame.
+ return Ok(());
+ }
+ let gesture_extent = self.workspace_sidebar_width() as f32;
+ let target = self
+ .workspace_sidebar_swipe
+ .visual(now, gesture_extent)
+ .and_then(|visual| visual.target_space_id);
+ let Some(target) = target else {
+ // Either no gesture, or one rubber-banding against the end of the
+ // list with no neighbour to show.
+ self.workspace_space_swipe_target_frame = None;
+ return Ok(());
+ };
+ if self
+ .workspace_space_swipe_target_frame
+ .as_ref()
+ .is_some_and(|(captured, _)| *captured == target)
+ {
+ return Ok(());
+ }
+
+ let ui_items_len = self.ui_items.len();
+ let mut quads = HeapQuadAllocator::default();
+ self.workspace_sidebar_preview_space_id = Some(target.clone());
+ // Draw the neighbour where adopting it would actually put it: at the
+ // offset it was left scrolled to. Using the *outgoing* Space's offset
+ // instead slides in a view that does not exist -- blank, when the
+ // neighbour has fewer threads than the offset scrolls past -- and then
+ // jumps once the switch applies the real one.
+ //
+ // Restoring afterwards is not tidiness. `paint_workspace_sidebar`
+ // clamps this field against the painted Space's own scroll extent and
+ // writes it back, so a shorter neighbour would drag the live sidebar
+ // up under the finger the instant the axis locked.
+ let preview_scroll_offset = self
+ .workspace_sidebar_scroll_offsets
+ .get(&target)
+ .copied()
+ .unwrap_or(0.0);
+ let live_scroll_offset = std::mem::replace(
+ &mut self.workspace_sidebar_scroll_offset,
+ preview_scroll_offset,
+ );
+ let mut layers = TripleLayerQuadAllocator::Heap(&mut quads);
+ let painted = self.paint_workspace_sidebar(&mut layers);
+ drop(layers);
+ self.workspace_sidebar_scroll_offset = live_scroll_offset;
+ self.workspace_sidebar_preview_space_id = None;
+ // This paint laid out hit targets for a Space the window has not
+ // adopted, at positions the pointer will never see, and it ran before
+ // the live paint that owns those slots. Drop them.
+ self.ui_items.truncate(ui_items_len);
+ painted.context("capture neighbouring Space sidebar")?;
+
+ let list = self.workspace_sidebar_list_quads;
+ self.workspace_space_swipe_target_frame =
+ Some((target, crate::termwindow::CapturedSidebar { quads, list }));
+ Ok(())
+ }
+
pub fn paint_pass(&mut self) -> anyhow::Result<()> {
let frame_now = Instant::now();
self.advance_workspace_space_swipe_push(frame_now);
@@ -988,21 +1088,45 @@ impl crate::TermWindow {
// 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();
- let capture_space_source = self.workspace_space_swipe_capture_source && !render_space_push;
+ // 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 {
+ 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 target workspace sidebar")?;
+ .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;
- self.workspace_sidebar_swipe
- .resolve_switch(true, Instant::now(), gesture_extent);
+ 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
@@ -1013,108 +1137,89 @@ impl crate::TermWindow {
}
let mut gpu_layers = layer.quad_allocator();
- let sidebar_rect = self.workspace_sidebar_rect();
- let list_viewport = self.workspace_sidebar_list_viewport();
- if let (Some(rect), Some((list_top, list_bottom))) = (sidebar_rect, list_viewport) {
+ if let Some(rect) = self.workspace_sidebar_rect() {
// Quad positions are window-centre relative (see
- // `filled_rectangle`), while the sidebar rect and list
- // viewport are top-left pixel coordinates. Rebase the clip
- // rect into the quads' space, otherwise every quad fails the
- // bounds test and the sidebar renders empty for the whole
- // transition.
- let list_clip = crate::quad::QuadClipRect::from_top_left_pixels(
+ // `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,
- list_top.max(0) as f32,
+ rect.y as f32,
rect.x.saturating_add(rect.width) as f32,
- list_bottom.max(list_top) as f32,
+ rect.y.saturating_add(rect.height) as f32,
&self.dimensions,
);
- let (clip_left, clip_top, clip_right, clip_bottom) = (
- list_clip.left(),
- list_clip.top(),
- list_clip.right(),
- list_clip.bottom(),
- );
- let top_offset = self.dimensions.pixel_height as f32 / 2.0;
- let window_top = -top_offset;
// The one-pixel separator is sidebar chrome, not page content.
- let page_right = (clip_right - 1.0).max(clip_left);
- // The settings row is lifted above `content_bottom` and the
- // scroll fade higher still, so the stationary band starts
- // above the list's own bottom edge and is drawn over the
- // moving pages rather than beside them.
- let footer_chrome_top = self
- .workspace_sidebar_footer_chrome_top()
- .map(|top| top.max(list_top) as f32 - top_offset)
- .unwrap_or(clip_bottom)
- .min(clip_bottom);
- let sidebar_bottom = rect.y.saturating_add(rect.height) as f32 - top_offset;
- let page_width = page_right - clip_left;
-
- // The pages stop where the stationary footer band begins, not
- // at the list's own bottom edge. Overlapping the two bands
- // leaves a moving sliver of the outgoing settings row visible
- // whenever the footer's fade is absent (it is only drawn when
- // the list actually scrolls), so the footer must own that
- // strip outright.
- let page_bottom = footer_chrome_top;
- let page_clip = list_clip
- .with_horizontal(clip_left, page_right)
- .with_vertical(clip_top, page_bottom);
+ 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 && page_bottom > clip_top);
-
- if let Some((source_offset, target_offset)) = offsets {
- // Paint the target sidebar chrome in place. Only the
- // project/thread list viewport below is double-buffered.
- sidebar_frame
- .apply_to_translated_clipped_rect(
- &mut gpu_layers,
- 0.0,
- list_clip.with_vertical(window_top, clip_top),
- )
- .context("space swipe stationary sidebar header")?;
- sidebar_frame
- .apply_to_translated_clipped_rect(
- &mut gpu_layers,
- 0.0,
- list_clip.with_horizontal(page_right, clip_right),
- )
- .context("space swipe stationary sidebar separator")?;
- if let Some(source) = self.workspace_space_swipe_source_frame.as_ref() {
- source
- .apply_to_translated_clipped_rect(
+ .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,
- source_offset,
+ &live.0,
+ &live.1,
+ live_offset,
page_clip,
)
- .context("space swipe source 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_to_translated_clipped_rect(
- &mut gpu_layers,
- target_offset,
- page_clip,
- )
- .context("space swipe target sidebar page")?;
-
- // Drawn last: the settings row is lifted above
- // `content_bottom` and the scroll fade sits above that, so
- // this band overlaps the moving pages instead of abutting
- // them. Compositing it after the pages keeps the footer
- // whole and lets its fade mask the content sliding beneath.
- sidebar_frame
- .apply_to_translated_clipped_rect(
- &mut gpu_layers,
- 0.0,
- list_clip.with_vertical(footer_chrome_top, sidebar_bottom),
- )
- .context("space swipe stationary sidebar footer")?;
- } else {
- sidebar_frame
- .apply_to(&mut gpu_layers)
- .context("space swipe target sidebar fallback")?;
}
} else {
sidebar_frame
@@ -1122,13 +1227,48 @@ impl crate::TermWindow {
.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 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(sidebar_frame);
+ 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() {
diff --git a/wezterm-gui/src/termwindow/space_swipe.rs b/wezterm-gui/src/termwindow/space_swipe.rs
index 84e7f0b1..4377b17d 100644
--- a/wezterm-gui/src/termwindow/space_swipe.rs
+++ b/wezterm-gui/src/termwindow/space_swipe.rs
@@ -35,11 +35,28 @@ pub(crate) enum SidebarSpaceSwipeUpdate {
Vertical(f32),
}
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[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)]
@@ -283,7 +300,22 @@ impl SidebarSpaceSwipeState {
});
SidebarSpaceSwipeFinish::AnimateBack
}
- Phase::Candidate(_) | Phase::Vertical => {
+ 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
@@ -295,18 +327,19 @@ impl SidebarSpaceSwipeState {
}
}
- pub(crate) fn resolve_switch(&mut self, switched: bool, now: Instant, sidebar_width: f32) {
+ 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) => {
- // The renderer captures the source sidebar, adopts and paints
- // the destination, and only then resolves the switch. Always
- // start the list-page push at rest so destination preparation
- // cannot consume or skip its opening frames.
- let from = if switched {
- 0.0
- } else {
- gesture.display_offset(sidebar_width)
+ 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);
@@ -475,10 +508,16 @@ mod tests {
swipe.finish(at(start, 30), 300.0),
SidebarSpaceSwipeFinish::Switch("next".into())
);
- swipe.resolve_switch(true, at(start, 30), 300.0);
- // The frame that commits renders the opening position; `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, 0.0);
+ 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)));
@@ -504,6 +543,110 @@ mod tests {
);
}
+ #[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(){
+ // 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();
@@ -597,7 +740,12 @@ mod tests {
SidebarSpaceSwipeFinish::None
);
- swipe.resolve_switch(false, at(start, 24), 300.0);
+ 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);
@@ -614,7 +762,12 @@ mod tests {
swipe.finish(at(start, 20), 300.0),
SidebarSpaceSwipeFinish::Switch("next".into())
);
- swipe.resolve_switch(true, at(start, 20), 300.0);
+ 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.
@@ -640,7 +793,12 @@ mod tests {
// 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);
+ swipe.resolve_switch(
+ true,
+ at(start, 20),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
assert!(swipe.is_committing_or_committed());
}
@@ -658,9 +816,17 @@ mod tests {
// 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);
+ 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, 0.0);
+ 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)));
}
@@ -675,7 +841,10 @@ mod tests {
swipe.finish(at(start, 20), 300.0),
SidebarSpaceSwipeFinish::Switch("next".into())
);
- swipe.resolve_switch(true, at(start, 1_000), 300.0);
+ // 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);
@@ -711,7 +880,12 @@ mod tests {
assert!(swipe.is_committing_or_committed());
assert_eq!(swipe.pending_switch_target(), Some("next"));
- swipe.resolve_switch(true, at(start, 22), 300.0);
+ swipe.resolve_switch(
+ true,
+ at(start, 22),
+ 300.0,
+ SettleOpening::WhereTheFingerLeftIt,
+ );
assert!(swipe.advance(at(start, 30)));
// And again once the settle is running.
@@ -741,7 +915,7 @@ mod tests {
swipe.finish(at(start, 20), 300.0),
SidebarSpaceSwipeFinish::Switch("next".into())
);
- swipe.resolve_switch(true, at(start, 20), 300.0);
+ 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);
@@ -756,7 +930,7 @@ mod tests {
}
#[test]
- fn committed_push_starts_at_rest_after_destination_preparation() {
+ 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);
@@ -767,7 +941,15 @@ mod tests {
swipe.finish(at(start, 90), 300.0),
SidebarSpaceSwipeFinish::Switch("next".into())
);
- swipe.resolve_switch(true, at(start, 100), 300.0);
- assert_eq!(swipe.visual(at(start, 100), 300.0).unwrap().offset, 0.0);
+ 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);
}
}
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index cdcc85de..26d82ee6 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -628,7 +628,7 @@ impl crate::TermWindow {
let space_menu_y = y;
let space_menu_height = top_action_height + self.ui_px(6);
y += space_menu_height + self.ui_px(SIDEBAR_INSET);
- let reconnect_row_height = if self.space_connection_state(&self.active_space_id)
+ let reconnect_row_height = if self.space_connection_state(self.workspace_sidebar_space_id())
== SpaceConnectionState::Disconnected
{
ui_cell_height + self.ui_px(SIDEBAR_INSET)
@@ -703,7 +703,7 @@ impl crate::TermWindow {
let workspaces = mux.iter_workspaces();
let view =
self.apply_workspace_thread_status_filter(workspace_threads::view_for_current_project(
- &self.active_space_id,
+ self.workspace_sidebar_space_id(),
&active_workspace,
&workspaces,
));
@@ -735,39 +735,6 @@ impl crate::TermWindow {
Some((layout.list_top as isize, layout.content_bottom as isize))
}
- /// Top of the band that belongs to the stationary footer rather than the
- /// scrolling list. `content_bottom` is *not* that boundary: the settings
- /// row is deliberately lifted above `settings_footer_y`, and the scroll
- /// fade sits higher still. A space-swipe transition that splits the
- /// sidebar at `content_bottom` therefore slices those elements in half —
- /// the lower part stays put while the upper sliver slides away with the
- /// page. Everything from here down must be composited in place.
- pub(crate) fn workspace_sidebar_footer_chrome_top(&self) -> Option<isize> {
- let rect = self.workspace_sidebar_rect()?;
- if self.workspace_sidebar_collapsed {
- return None;
- }
- let ui_cell_height = self.workspace_sidebar_cell_height();
- let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
- let layout = self.workspace_sidebar_layout(rect, ui_cell_height, icon_size);
- if layout.settings_footer_height == 0 {
- return Some(layout.content_bottom as isize);
- }
- let settings_row_top = (layout.settings_footer_y
- + self.ui_px(SIDEBAR_SETTINGS_ROW_TOP_PADDING))
- .saturating_sub(self.ui_px(SIDEBAR_SETTINGS_ROW_LIFT));
- let fade_top = layout
- .settings_footer_y
- .saturating_sub(self.ui_px(SIDEBAR_SETTINGS_FADE_HEIGHT));
- Some(
- layout
- .content_bottom
- .min(settings_row_top)
- .min(fade_top)
- .max(layout.list_top) as isize,
- )
- }
-
pub fn workspace_sidebar_scroll_geometry(&self) -> Option<WorkspaceSidebarScrollGeometry> {
let rect = self.workspace_sidebar_rect()?;
if self.workspace_sidebar_collapsed {
@@ -794,7 +761,7 @@ impl crate::TermWindow {
let workspaces = mux.iter_workspaces();
let view =
self.apply_workspace_thread_status_filter(workspace_threads::view_for_current_project(
- &self.active_space_id,
+ self.workspace_sidebar_space_id(),
&active_workspace,
&workspaces,
));
@@ -852,7 +819,7 @@ 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)
});
@@ -917,6 +884,10 @@ impl crate::TermWindow {
&mut self,
layers: &mut TripleLayerQuadAllocator,
) -> anyhow::Result<()> {
+ // Clearing here is what keeps the recording honest: every exit below
+ // this point either reached the row loop and recorded a real span, or
+ // left this `None`. It can never describe an earlier paint.
+ self.workspace_sidebar_list_quads = None;
let rect = match self.workspace_sidebar_rect() {
Some(rect) => rect,
None => return Ok(()),
@@ -1010,7 +981,7 @@ impl crate::TermWindow {
let workspaces = mux.iter_workspaces();
let view =
self.apply_workspace_thread_status_filter(workspace_threads::view_for_current_project(
- &self.active_space_id,
+ self.workspace_sidebar_space_id(),
&active_workspace,
&workspaces,
));
@@ -1207,15 +1178,15 @@ impl crate::TermWindow {
.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_title = self.sidebar_space_title(self.workspace_sidebar_space_id(), &space_name);
let space_label = self.ellipsize_ui_text(
&ui_font,
&space_title,
space_text_right.saturating_sub(space_text_x),
)?;
- let connection_state = self.space_connection_state(&self.active_space_id);
+ let connection_state = self.space_connection_state(self.workspace_sidebar_space_id());
// Swap the icon in place rather than adding text: the indicator
// must not change the row's width or height, so transient lag
// spikes can't make the sidebar layout jump.
@@ -1446,9 +1417,15 @@ impl crate::TermWindow {
);
total_height.saturating_sub(viewport_height) as f32
};
- self.workspace_sidebar_scroll_offset =
- self.workspace_sidebar_scroll_offset.clamp(0.0, max_scroll);
- let scroll_offset = self.workspace_sidebar_scroll_offset;
+ let scroll_offset = self.workspace_sidebar_scroll_offset.clamp(0.0, max_scroll);
+ if self.workspace_sidebar_preview_space_id.is_none() {
+ // Writing the clamp back is what stops the sidebar staying scrolled
+ // past the end after a list shrinks. It must not happen while
+ // previewing a neighbouring Space: `max_scroll` then describes
+ // *that* Space's extent, and a shorter one would drag the live
+ // sidebar upward mid-gesture.
+ self.workspace_sidebar_scroll_offset = scroll_offset;
+ }
let list_top_f = list_top as f32;
let content_bottom_f = content_bottom as f32;
let suppress_hover = self
@@ -1456,6 +1433,10 @@ impl crate::TermWindow {
.as_ref()
.is_some_and(|event| matches!(event.kind, WMEK::VertWheel(_) | WMEK::HorzWheel(_)));
let mut virtual_y = 0usize;
+ // Everything from here until the end of the project loop scrolls with
+ // `virtual_y`. A space-swipe slides exactly this stretch and leaves the
+ // chrome painted before and after it standing.
+ let list_quads_start = layers.heap_mark();
if !view.pinned_threads.is_empty() {
let label_top = list_top_f + virtual_y as f32 - scroll_offset;
@@ -2036,6 +2017,8 @@ impl crate::TermWindow {
}
}
+ self.workspace_sidebar_list_quads = list_quads_start.zip(layers.heap_mark());
+
let header_mask_height = list_top.saturating_sub(panel_y);
if header_mask_height > 0 {
self.filled_rectangle(
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index 44750fa1..b87051d0 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -405,6 +405,52 @@ lazy_static::lazy_static! {
static THREAD_STORE_PERSIST_SCHEDULED: AtomicBool = AtomicBool::new(false);
static THREAD_STORE_PERSIST_DIRTY: AtomicBool = AtomicBool::new(false);
+/// Orders writes of the store file and discards snapshots that have been
+/// overtaken.
+///
+/// The debounced writer copies the store, releases the store lock, and only
+/// then spends ~88ms serializing and fsyncing. A synchronous save landing
+/// inside that window writes newer data first and is then overwritten when
+/// the older copy finishes its rename -- silently undoing whatever the user
+/// had just done. Serializing the writes alone does not help: the stale copy
+/// would still be the one to land last. Stamping each snapshot as it is taken
+/// is what lets the loser be dropped instead of applied.
+struct StoreWriteGate {
+ next_seq: AtomicU64,
+ last_written: Mutex<u64>,
+}
+
+impl StoreWriteGate {
+ const fn new() -> Self {
+ Self {
+ next_seq: AtomicU64::new(0),
+ last_written: Mutex::new(0),
+ }
+ }
+
+ /// Stamp a snapshot. Callers hold `THREAD_STORE`, so the numbers come out
+ /// in the same order as the mutations they describe.
+ fn claim(&self) -> u64 {
+ self.next_seq.fetch_add(1, Ordering::AcqRel) + 1
+ }
+
+ /// Run `write` unless a later snapshot already reached disk. Returns
+ /// whether it ran. Writes are serialized against each other, so `write`
+ /// never races another copy of the file.
+ fn write_if_newest(&self, seq: u64, write: impl FnOnce() -> bool) -> bool {
+ let mut last_written = self.last_written.lock();
+ if *last_written >= seq {
+ return false;
+ }
+ if !write() {
+ return false;
+ }
+ *last_written = seq;
+ true
+ }
+}
+
+static THREAD_STORE_WRITES: StoreWriteGate = StoreWriteGate::new();
/// Set when the store on disk exists but could not be read.
///
/// Nothing may be written while it is set. The in-memory store is empty in
@@ -716,7 +762,7 @@ pub fn switch_window_space(owner_id: u64, space_id: &str) -> bool {
}
store.last_active_space_id = Some(space_id.to_string());
store.remember_space_for_domain(space_id);
- persist_locked(&store);
+ schedule_workspace_thread_store_persist();
drop(store);
WINDOW_SPACES.lock().insert(owner_id, space_id.to_string());
@@ -1413,7 +1459,7 @@ pub fn activate_thread_record(
) -> Option<ActivationPlan> {
let mut store = THREAD_STORE.lock();
let plan = store.activate_thread_record(thread_id, live_workspaces);
- persist_locked(&store);
+ schedule_workspace_thread_store_persist();
if plan.is_some() {
submit_thread_state(&store, thread_id);
}
@@ -1856,7 +1902,7 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(
}
let mut store = THREAD_STORE.lock();
if store.snapshot_remote_thread_font_scales(space_id, workspace, scales) {
- persist_locked(&store);
+ schedule_workspace_thread_store_persist();
}
return;
}
@@ -1870,7 +1916,13 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(
let mut store = THREAD_STORE.lock();
if store.snapshot_active_space_thread_layout(space_id, workspace, snapshot) {
- persist_locked(&store);
+ // Debounced rather than written through. A Space switch calls this,
+ // `switch_window_space` and `activate_thread_record` back to back, and
+ // each one used to fsync the whole store: three ~88ms stalls on the
+ // main thread for three copies of the same file, which is longer than
+ // the switch animation they were blocking. The background writer
+ // collapses them into one.
+ schedule_workspace_thread_store_persist();
}
}
@@ -5217,16 +5269,30 @@ fn valid_font_scale(font_scale: Option<f64>) -> Option<f64> {
font_scale.filter(|scale| scale.is_finite() && *scale > 0.0)
}
+/// Write the store through. Callers hold `THREAD_STORE`, so the snapshot is
+/// current and can be stamped here.
fn persist_locked(store: &WorkspaceThreadStore) {
+ persist_snapshot(store, THREAD_STORE_WRITES.claim());
+}
+
+fn persist_snapshot(store: &WorkspaceThreadStore, seq: u64) {
// See `STORE_IS_UNREADABLE`: this write is the one that would destroy the
// file, so it is the one that has to be refused.
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) {
+ 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() {
@@ -5239,8 +5305,14 @@ fn schedule_workspace_thread_store_persist() {
std::thread::sleep(Duration::from_millis(50));
if THREAD_STORE_PERSIST_DIRTY.swap(false, Ordering::AcqRel) {
- let store = THREAD_STORE.lock().clone();
- persist_locked(&store);
+ // Stamp the copy while the store is still held: the number has to
+ // describe this snapshot, not the moment the write gets around to
+ // running.
+ let (store, seq) = {
+ let store = THREAD_STORE.lock();
+ (store.clone(), THREAD_STORE_WRITES.claim())
+ };
+ persist_snapshot(&store, seq);
continue;
}
@@ -6384,6 +6456,43 @@ mod tests {
}
}
+ /// Regression: the debounced writer copies the store, releases the store
+ /// lock, then spends ~88ms writing. A synchronous save inside that window
+ /// used to be silently undone -- the older copy finished last and its
+ /// rename replaced the newer file, so a project rename made just after a
+ /// Space switch was gone on restart.
+ #[test]
+ fn a_snapshot_overtaken_before_it_reaches_disk_is_dropped_not_applied() {
+ let gate = StoreWriteGate::new();
+ let mut written = vec![];
+
+ // The debounced writer stamps its copy...
+ let stale = gate.claim();
+ // ...then a rename mutates the store and writes through, beating it.
+ let fresh = gate.claim();
+ assert!(gate.write_if_newest(fresh, || {
+ written.push(fresh);
+ true
+ }));
+ // The older copy must not now replace it.
+ assert!(
+ !gate.write_if_newest(stale, || {
+ written.push(stale);
+ true
+ }),
+ "the stale snapshot would overwrite the rename that beat it to disk"
+ );
+ assert_eq!(written, vec![fresh]);
+
+ // A later snapshot still gets through.
+ let later = gate.claim();
+ assert!(gate.write_if_newest(later, || {
+ written.push(later);
+ true
+ }));
+ assert_eq!(written, vec![fresh, later]);
+ }
+
#[test]
fn adjacent_space_swipe_targets_keep_local_order_and_skip_unavailable_spaces() {
let spaces = vec![
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 8e23c1e9..8c0cc386 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -3633,6 +3633,17 @@ impl WindowView {
);
}
+ /// Opting in here is what makes AppKit deliver a horizontal page swipe as
+ /// phased scroll events, which `scroll_wheel` above turns into the
+ /// interactive sidebar gesture.
+ ///
+ /// Deliberately not paired with a `swipeWithEvent:` fallback. That
+ /// responder callback fires window-wide with no notion of what is under
+ /// the pointer, so synthesizing a wheel event from it injects
+ /// WheelLeft/WheelRight into whatever owns that spot -- a terminal running
+ /// an alt-screen application, most of the time. It also carries a single
+ /// discrete delta rather than a stream, so the gesture it produces can only
+ /// ever cut straight to the destination.
extern "C" fn wants_scroll_events_for_swipe_tracking(
_this: &Object,
_sel: Sel,
@@ -3645,48 +3656,6 @@ impl WindowView {
}
}
- extern "C" fn swipe_with_event(this: &mut Object, _sel: Sel, nsevent: id) {
- // When AppKit can track a page swipe as scroll events, scroll_wheel
- // above drives the interactive animation. Some trackpad settings only
- // deliver this discrete responder callback; synthesize a short precise
- // horizontal gesture so the same GUI state machine and hit testing are
- // used in both cases.
- let recently_received_scroll = Self::get_this(this).is_some_and(|myself| {
- myself.inner.borrow().last_wheel.elapsed() < std::time::Duration::from_millis(100)
- });
- if recently_received_scroll {
- return;
- }
-
- let native_x = unsafe { nsevent.deltaX() };
- let native_y = unsafe { nsevent.deltaY() };
- if native_x.abs() <= native_y.abs() || native_x.abs() <= f64::EPSILON {
- return;
- }
-
- // NSEvent uses +1 for a swipe left and -1 for a swipe right, while
- // precise scroll events use a negative x delta for leftward content
- // travel. Preserve the latter convention for the shared state machine.
- let delta_x = -native_x.signum() as f32 * 20.0;
- let amount = if delta_x < 0.0 { -1 } else { 1 };
- Self::mouse_common(
- this,
- nsevent,
- MouseEventKind::HorzWheel(amount),
- Some(PreciseScrollDelta { x: delta_x, y: 0.0 }),
- Some(ScrollPhase::Began),
- None,
- );
- Self::mouse_common(
- this,
- nsevent,
- MouseEventKind::HorzWheel(0),
- None,
- Some(ScrollPhase::Ended),
- None,
- );
- }
-
extern "C" fn right_mouse_down(this: &mut Object, _sel: Sel, nsevent: id) {
Self::mouse_common(
this,
@@ -4713,10 +4682,6 @@ impl WindowView {
Self::wants_scroll_events_for_swipe_tracking
as extern "C" fn(&Object, Sel, NSInteger) -> BOOL,
);
- cls.add_method(
- sel!(swipeWithEvent:),
- Self::swipe_with_event as extern "C" fn(&mut Object, Sel, id),
- );
cls.add_method(
sel!(mouseExited:),
Self::mouse_exited as extern "C" fn(&mut Object, Sel, id),