diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index a5de8554a7..9d81b764ea 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -106,8 +106,20 @@ pub struct Wheel { /// taker that owns the gesture; another taker's share holds its own `mods`. pub held: Mods, /// A wheel event of the running gesture, or one less than [`GESTURE_GAP`] seconds before it began, arrived while a - /// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. + /// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. An + /// app's own modal window marks it too (`CanvasSpace::mark_wheel_modal`). pub modal: bool, + /// The owner claimed an earlier share of the running gesture (`CanvasSpace::claim_wheel`): it takes the gesture + /// for itself. For the taker that owns the gesture; another taker's share is never claimed. + pub claimed: bool, + /// The `scroll` of the running gesture's shares the owner claimed before this one. Motion the owner did not + /// claim is not counted. + pub claimed_gathered: Vec2, + /// The `zoom_lines` of the running gesture's shares the owner claimed before this one. + pub claimed_zoom_gathered: Vec2, + /// The motion the owner said it used up (`spent`) with its claims of the running gesture so far, in its own + /// unit: `claimed_gathered` or `claimed_zoom_gathered` less this is what the claimed shares left over. + pub claimed_spent: Vec2, } /// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. @@ -256,6 +268,10 @@ impl Wheel { moved: false, held: mods, modal: false, + claimed: false, + claimed_gathered: Vec2::ZERO, + claimed_zoom_gathered: Vec2::ZERO, + claimed_spent: Vec2::ZERO, } } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 963fd75f92..b74be1fb3e 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -305,6 +305,7 @@ struct Settled { keys: BodyKeys, /// The wheel share the canvas took this pass, handed on to its body. wheel: Option, + wheel_token: Option, /// A middle-button autoscroll or a held middle pan runs. auto_scrolling: bool, /// The mark of a running middle-button autoscroll, in screen points. @@ -480,7 +481,15 @@ impl<'a> Canvas<'a> { let mut zoom_anchor = None; let wheel = cx.take_wheel(); let wheeled = wheel.is_some(); - if let Some(wheel) = &wheel { + // A share of a gesture the body claimed (`CanvasSpace::claim_wheel`) goes to the body alone: the view stays, and + // the motion the eased wheel and the eased wheel zoom still owe is dropped. + if crate::runtime::wheel::claimed(&ctx, id) || wheel.as_ref().is_some_and(|wheel| wheel.claimed) { + motion.glide.stop(); + cx.stop_wheel_ease(); + motion.wheel_zoom.stop_if(true); + motion.wheel = WheelNavigation::default(); + } + if let Some(wheel) = wheel.as_ref().filter(|wheel| !wheel.claimed) { let read = self.read_wheel(cx, &mut motion, &mut view, wheel, now); line_pan = read.line_pan; jumped |= read.jumped; @@ -618,7 +627,8 @@ impl<'a> Canvas<'a> { let easing = motion.animation.running(); let mark = motion.autoscroll.mark(); motion.restore(&ctx, id); - Settled { target, shown, easing, keys, wheel, auto_scrolling, mark, swallowing, zoom_anchor } + let wheel_token = crate::runtime::wheel::claim_token(&ctx, id); + Settled { target, shown, easing, keys, wheel, wheel_token, auto_scrolling, mark, swallowing, zoom_anchor } } /// One pass's wheel on `view`: a pan the eased wheel pays out later, or a pan, zoom or turn applied now, and the @@ -778,6 +788,7 @@ impl<'a> Canvas<'a> { .with_precise(self.precise_cursors != caps_lock) .with_zoom_scheme(scheme) .with_wheel(wheel) + .with_wheel_token(self.settled.and_then(|settled| settled.wheel_token)) .with_canvas(id); Some(match self.picture { Some(slot) => space.with_picture(slot), diff --git a/crates/ui-canvas/src/canvas/navigate/mod.rs b/crates/ui-canvas/src/canvas/navigate/mod.rs index de5a82eec4..3e9e886733 100644 --- a/crates/ui-canvas/src/canvas/navigate/mod.rs +++ b/crates/ui-canvas/src/canvas/navigate/mod.rs @@ -163,6 +163,7 @@ impl TouchpadGlide { /// Stops a glide (the view hit a limit, a press, a key move, a zoom, a view command). pub(crate) fn stop(&mut self) { + self.samples.clear(); self.velocity = Vec2::ZERO; } @@ -204,7 +205,7 @@ impl TouchpadGlide { /// Reads the pass's wheel share at `now`; any wheel input stops a glide, a touchpad gesture's end may start one. /// `glide` is false where the view must not glide this pass (Touchpad Glide off, a zoom, a dialog). pub(crate) fn read(&mut self, wheel: &Wheel, now: f64, glide: bool) { - self.stop(); + self.velocity = Vec2::ZERO; // Zooming, a mouse wheel and sideways Shift scrolling never glide. if wheel.unit != WheelUnit::Point || wheel.mods.cmd || wheel.mods.ctrl || wheel.mods.shift || wheel.zoom != 1.0 { self.samples.clear(); @@ -326,3 +327,29 @@ fn document_bounds(view: &CanvasView, size: Size) -> Option { let bounds = quad.iter().skip(1).fold(Rect::from_min_max(quad[0], quad[0]), |r, &p| r.union(Rect::from_min_max(p, p))); (bounds.is_finite() && view.rect.is_finite()).then_some(bounds) } + +#[cfg(feature = "suite")] +pub(crate) mod trials { + use super::TouchpadGlide; + use crate::testing::trial; + use egui::Vec2; + + /// One sample of a touchpad swipe upward, in points: the glide's input, not a size of anything drawn. + const SWIPE: Vec2 = Vec2::new(0.0, -30.0); + + #[trial] + fn stopping_a_touchpad_glide_clears_its_lift_samples() { + let mut glide = TouchpadGlide::default(); + glide.push(0.0, SWIPE); + glide.push(0.01, SWIPE); + assert_ne!(glide.lift_velocity(0.02), Vec2::ZERO); + glide.velocity = glide.lift_velocity(0.02); + + glide.stop(); + + assert!(!glide.gliding()); + assert!(glide.samples.is_empty()); + glide.push(0.03, Vec2::new(0.0, -1.0)); + assert_eq!(glide.lift_velocity(0.04), Vec2::ZERO); + } +} diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index c8c9dc8432..770ea60a92 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -42,7 +42,7 @@ pub struct CanvasSpace { /// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a /// measuring pass. picture: Option, - wheel: Option, + wheel: Option<(craft_behavior::Wheel, Option)>, zoom_anchor: Option, } @@ -73,13 +73,21 @@ impl CanvasSpace { /// The wheel share the canvas read this pass, for a body that pages by wheel to read once. pub fn wheel(&self) -> Option { - self.wheel + self.wheel.map(|(wheel, _)| wheel) } - /// This space with the wheel share the canvas read this pass. + /// This space with the wheel share the canvas read. #[must_use] pub fn with_wheel(mut self, wheel: Option) -> Self { - self.wheel = wheel; + self.wheel = wheel.map(|wheel| (wheel, None)); + self + } + + #[must_use] + pub(crate) fn with_wheel_token(mut self, token: Option) -> Self { + if let Some((_, claim)) = self.wheel.as_mut() { + *claim = token; + } self } @@ -298,6 +306,29 @@ impl CanvasSpace { nudge } + /// Claims this pass's wheel share ([`wheel`](Self::wheel)) for the canvas's body, recording `spent`, the part of + /// the claimed motion the body used up, in its own unit, and returning whether the claim succeeded. The gesture's + /// later shares carry `Wheel::claimed` and count only the claimed shares in `claimed_gathered`, + /// `claimed_zoom_gathered` and `claimed_spent`, so a body that turns a gesture into steps keeps no state of its + /// own. A second claim in the same pass replaces the first. + /// The canvas must own the gesture and have a share in the running pass. A share returned by `wheel` can belong + /// to a gesture another scroller owns; that share cannot be claimed. A snapshot from another share cannot claim the + /// running pass's share, including after a viewport is recreated. The body should act only on an accepted claim. + pub fn claim_wheel(&self, ctx: &egui::Context, spent: Vec2) -> bool { + if let (Some(canvas), Some((_, Some(token)))) = (self.canvas, self.wheel) { + return crate::runtime::wheel::claim(ctx, canvas, token, spent); + } + false + } + + /// Marks the running wheel gesture as begun or gone on under a modal, for one of the app's own modal windows that + /// the wheel service does not see. The gesture's later shares carry `Wheel::modal` until it ends. + pub fn mark_wheel_modal(&self, ctx: &egui::Context) { + if let Some(canvas) = self.canvas { + crate::runtime::wheel::mark_modal(ctx, canvas); + } + } + /// Device pixels per document unit (1 is 100 %) of the view at this scale. pub fn zoom_device(&self) -> f64 { zoom::device(&self.view, self.pixels_per_point) diff --git a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs index 314fe1eeb2..a6e7b64038 100644 --- a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs +++ b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs @@ -2,12 +2,12 @@ use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Size}; -use craft_ui::canvas::{Canvas, NavigationOptions}; +use craft_ui::canvas::{Canvas, CanvasSpace, NavigationOptions, WheelScheme, canvas_space}; use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _}; use craft_ui::style::StyleCx; -use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::testing::{Fixture, Frames, pointer, trial}; use craft_ui_test_kit::contract::PlainStyle; -use egui::{Response, Vec2}; +use egui::{Response, TouchPhase, Vec2}; use std::cell::Cell; use std::rc::Rc; @@ -81,3 +81,529 @@ fn the_wheel_over_a_canvas_under_a_modal_moves_nothing() { } } } + +/// A body that claims a wheel gesture (`CanvasSpace::claim_wheel`) reads the rest of it alone: the later shares reach +/// the body, and the view does not move by them. +#[trial] +fn the_rest_of_a_wheel_gesture_the_body_claimed_does_not_move_the_view() { + for eased in [false, true] { + claimed_gesture_keeps_the_view(eased); + } +} + +/// The claimed rest of a gesture of point scroll, or with `eased` of eased wheel lines whose first notch still owes +/// motion when the body claims the gesture. +fn claimed_gesture_keeps_the_view(eased: bool) { + let mut options = NavigationOptions::default(); + options.eased_wheel = eased; + let event = move || if eased { pointer::wheel_lines(-1.0) } else { pointer::wheel(-30.0) }; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claims = Rc::new(Cell::new(false)); + let read = Rc::new(Cell::new(0_u32)); + let (shown, claiming, reads) = (Rc::clone(&view), Rc::clone(&claims), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some() + { + reads.set(reads.get() + 1); + if claiming.get() { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas owns this gesture"); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + let at = view.get().rect.center() + Vec2::new(0.0, 150.0); + fixture.frame(vec![pointer::moved(at)]); + let start = view.get(); + fixture.frame(vec![event()]); + fixture.idle(40); + assert!(view.get().center.y > start.center.y + 1.0, "eased {eased}: precondition: an unclaimed share scrolls the canvas"); + + // The first share of the gesture moves the view before the body claims it; an eased notch still owes motion. + claims.set(true); + fixture.frame(vec![event()]); + let claimed = view.get(); + // The motion the claimed notch still owed is dropped, with no more wheel input too. + fixture.idle(5); + let still = view.get(); + assert!((still.center.y - claimed.center.y).abs() < 1e-3, "eased {eased}: owed motion moved the view: {claimed:?} -> {still:?}"); + read.set(0); + for _ in 0..3 { + fixture.frame(vec![event()]); + } + assert_eq!(read.get(), 3, "eased {eased}: the body reads every share of the claimed gesture"); + claims.set(false); + fixture.idle(40); + let after = view.get(); + assert!( + (after.center.y - claimed.center.y).abs() < 1e-3 && after.zoom == claimed.zoom, + "eased {eased}: the view moved: {claimed:?} -> {after:?}" + ); +} + +#[trial] +fn a_canvas_space_with_a_supplied_wheel_share_has_no_claim_token() { + let read = Rc::new(Cell::new(0_u32)); + let reads = Rc::clone(&read); + let mut fixture = Fixture::new(move |ui| { + let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0); + Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let supplied = space.with_wheel(Some(wheel)); + assert_eq!(supplied.wheel(), Some(wheel)); + assert!(!supplied.claim_wheel(ui.ctx(), Vec2::ZERO), "a supplied share has no claim token"); + assert!(supplied.with_wheel(None).wheel().is_none()); + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas's original share keeps its token"); + reads.set(reads.get() + 1); + } + }); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(read.get(), 1); +} + +/// A canvas reports a rejected claim when a nested scroller owns the diagonal gesture. +#[trial] +fn a_canvas_cannot_claim_the_horizontal_share_of_a_nested_scrollers_gesture() { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let read = Rc::new(Cell::new(0_u32)); + let (shown, reads) = (Rc::clone(&view), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + let scroller = egui::Id::unique("nested_wheel_scroller"); + let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0)); + craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true)); + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0, "the canvas receives only horizontal motion"); + let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion"); + assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0); + assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "the nested scroller owns the gesture"); + reads.set(reads.get() + 1); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let diagonal = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-20.0, -30.0), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }; + fixture.frame(vec![diagonal()]); + let first = view.get(); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 2, "the canvas receives both horizontal shares"); + assert!(view.get().center.x > first.center.x, "a rejected claim leaves later horizontal panning enabled"); +} + +#[trial] +fn a_canvas_can_mark_the_horizontal_share_of_a_nested_scrollers_gesture_modal() { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let read = Rc::new(Cell::new(0_u32)); + let (shown, reads) = (Rc::clone(&view), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + let scroller = egui::Id::unique("modal_nested_wheel_scroller"); + let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0)); + craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true)); + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion"); + assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0); + assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0); + assert_eq!(wheel.modal, reads.get() == 1, "only the rest of the marked gesture is modal"); + assert_eq!(vertical.modal, wheel.modal, "both shares carry the gesture's modal mark"); + assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "marking does not let the canvas claim the gesture"); + assert!(craft_ui::runtime::wheel::claim_token(ui.ctx(), scroller).is_some(), "the nested scroller owns the gesture"); + if reads.get() == 0 { + space.mark_wheel_modal(ui.ctx()); + } + reads.set(reads.get() + 1); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let diagonal = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-20.0, -30.0), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }; + fixture.frame(vec![diagonal()]); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 2, "the canvas receives both horizontal shares"); + fixture.advance(craft_behavior::GESTURE_GAP); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 3, "a new gesture starts without the modal mark"); +} + +/// A body that first claims the device End stops the canvas glide after the gesture closes. +#[trial] +fn claiming_the_device_end_stops_the_canvas_glide() { + for claim_end in [false, true] { + let mut options = NavigationOptions::default(); + options.touchpad_glide = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claimed = Rc::new(Cell::new(false)); + let (shown, claims) = (Rc::clone(&view), Rc::clone(&claimed)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if claim_end + && let Some(space) = canvas_space(&body.env) + && space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + claims.set(true); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let event = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, -30.0)]); + for _ in 0..4 { + fixture.frame(vec![event(TouchPhase::Move, -30.0)]); + } + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + assert_eq!(claimed.get(), claim_end, "the body claims only the device End"); + let lifted = view.get(); + fixture.idle(5); + let after = view.get(); + if claim_end { + assert!((after.center.y - lifted.center.y).abs() < 1e-3, "the claimed End left a glide: {lifted:?} -> {after:?}"); + } else { + assert!(after.center.y > lifted.center.y + 1.0, "precondition: the unclaimed End starts a glide"); + } + } +} + +/// A fresh notch and its eased tail move the view after the body claims the previous device End. +#[trial] +fn a_fresh_notch_eases_after_a_claimed_device_end() { + for zoom in [false, true] { + let mut options = NavigationOptions::default(); + options.eased_wheel = true; + options.eased_wheel_zoom = true; + options.touchpad_glide = true; + options.wheel = WheelScheme::Acrobat; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let shown = Rc::clone(&view); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let swipe = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![swipe(TouchPhase::Start, -30.0)]); + fixture.frame(vec![swipe(TouchPhase::End, 0.0)]); + let before = view.get(); + fixture.frame(vec![egui::Event::MouseWheel { + unit: if zoom { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line }, + delta: Vec2::new(0.0, if zoom { -60.0 } else { -1.0 }), + phase: TouchPhase::Move, + modifiers: if zoom { egui::Modifiers::COMMAND } else { egui::Modifiers::NONE }, + source: egui::MouseWheelSource::Wheel, + }]); + let first = view.get(); + fixture.idle(5); + let after = view.get(); + if zoom { + assert!( + first.zoom < before.zoom && after.zoom < first.zoom, + "the fresh zoom notch and its tail move the view: {before:?} -> {first:?} -> {after:?}" + ); + } else { + assert!( + first.center.y > before.center.y && after.center.y > first.center.y, + "the fresh scroll notch and its tail move the view: {before:?} -> {first:?} -> {after:?}" + ); + } + } +} + +/// A partial zoom notch from a claimed gesture does not combine with the next gesture's first half notch. +#[trial] +fn claiming_a_gesture_clears_its_partial_zoom_notch() { + let mut options = NavigationOptions::default(); + options.wheel = WheelScheme::Zoom; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claim = Rc::new(Cell::new(true)); + let (shown, claiming) = (Rc::clone(&view), Rc::clone(&claim)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some() + && claiming.replace(false) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let half = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: Vec2::new(0.0, 0.5), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::SHIFT, + source: egui::MouseWheelSource::Wheel, + }; + let before = view.get().zoom; + fixture.frame(vec![half()]); + assert!(!claim.get(), "the body claimed the first half notch"); + assert_eq!(view.get().zoom, before, "a half notch does not zoom"); + fixture.frame(vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::ZERO, + phase: TouchPhase::End, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }]); + fixture.frame(vec![half()]); + assert_eq!(view.get().zoom, before, "the new gesture has only half a notch"); + fixture.frame(vec![half()]); + assert!(view.get().zoom > before, "the new gesture's two half notches complete a rung"); +} + +#[trial] +fn a_claimed_swipes_samples_do_not_glide_after_a_coalesced_start() { + let mut options = NavigationOptions::default(); + options.touchpad_glide = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claim = Rc::new(Cell::new(false)); + let last = Rc::new(Cell::new(None)); + let (shown, claiming, shares) = (Rc::clone(&view), Rc::clone(&claim), Rc::clone(&last)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + shares.set(Some(wheel)); + if claiming.get() { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let event = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, -30.0)]); + claim.set(true); + fixture.frame(vec![event(TouchPhase::Move, -30.0)]); + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + assert!(last.get().expect("the claimed End").claimed); + + claim.set(false); + fixture.frame(vec![event(TouchPhase::Move, -1.0)]); + let fresh = last.get().expect("the next swipe's Move"); + assert_eq!(fresh.phase, craft_behavior::WheelPhase::Move); + assert!(!fresh.claimed); + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + let lifted = view.get(); + fixture.idle(5); + assert_eq!(view.get().center, lifted.center, "one small sample cannot start a glide"); +} + +#[trial] +fn a_stale_canvas_space_cannot_claim_a_wheel_share_in_a_later_pass() { + claim_from_retained_space(false); +} + +#[trial] +fn a_fresh_canvas_space_can_claim_after_a_stale_claim_is_refused() { + claim_from_retained_space(true); +} + +#[trial] +fn a_retained_canvas_space_cannot_claim_a_recreated_viewports_share_with_the_same_pass_number() { + for claim_fresh in [false, true] { + let viewport = egui::ViewportId::from_hash_of("canvas window"); + let retained: Cell> = Cell::new(None); + let issued = Cell::new(None); + let owner = egui::Id::unique("moving canvas"); + let recreated = Cell::new(false); + let attempts = Cell::new(0); + let last = Cell::new(None); + let view = Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)); + let mut show = |ui: &mut egui::Ui| { + let mut given = view.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").id(owner).document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + last.set(Some(wheel)); + let pass = craft_ui::runtime::frame::running(ui.ctx()).expect("a running pass"); + if !recreated.get() { + retained.set(Some(space)); + issued.set(Some(pass.pass_nr)); + } else if attempts.get() == 0 { + assert_eq!(pass.viewport, viewport, "the recreated viewport has the same ID"); + assert_eq!(Some(pass.pass_nr), issued.get(), "the recreated viewport has the same pass counter"); + assert!(!retained.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::new(0.0, -30.0))); + assert!(!craft_ui::runtime::wheel::claimed(ui.ctx(), owner), "the rejected claim leaves the new share unclaimed"); + if claim_fresh { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + attempts.set(attempts.get() + 1); + } + } + }); + view.set(canvas.output.view.unwrap_or(given)); + }; + let mut frames = Frames::new(); + for reopen in [false, true] { + if reopen { + frames.close_viewport(viewport); + frames.frame(Vec::new(), |_| {}); + recreated.set(true); + } + frames.frame_in_viewport(viewport, Vec::new(), &mut show); + frames.frame_in_viewport(viewport, Vec::new(), &mut show); + frames.frame_in_viewport(viewport, vec![pointer::moved(view.get().rect.center())], &mut show); + frames.frame_in_viewport(viewport, vec![pointer::wheel_lines(-1.0)], &mut show); + } + assert_eq!(attempts.get(), 1); + last.set(None); + frames.frame_in_viewport(viewport, vec![pointer::wheel(-30.0)], &mut show); + let next = last.get().expect("the share after the claim attempt"); + assert_eq!(next.claimed, claim_fresh); + if !claim_fresh { + assert_eq!(next.claimed_gathered, Vec2::ZERO, "the rejected claim records no claimed motion"); + } + assert_eq!(next.claimed_spent, Vec2::ZERO, "the rejected claim records no spent motion"); + } +} + +fn claim_from_retained_space(claim_fresh: bool) { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let retained: Rc>> = Rc::new(Cell::new(None)); + let later = Rc::new(Cell::new(false)); + let read = Rc::new(Cell::new(None)); + let attempts = Rc::new(Cell::new(0)); + let (shown, saved, claiming, shares, claims) = + (Rc::clone(&view), Rc::clone(&retained), Rc::clone(&later), Rc::clone(&read), Rc::clone(&attempts)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + shares.set(Some(wheel)); + if claiming.get() { + assert!(!saved.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::ZERO)); + if claim_fresh { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + claims.set(claims.get() + 1); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + if !claiming.get() && canvas.output.space.is_some_and(|space| space.wheel().is_some()) { + saved.set(canvas.output.space); + } + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert!(retained.get().is_some()); + later.set(true); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(attempts.get(), 1); + later.set(false); + fixture.frame(vec![pointer::wheel(-30.0)]); + let next = read.get().expect("the share after the claim attempt"); + assert_eq!(next.claimed, claim_fresh); + if claim_fresh { + assert_eq!(next.claimed_gathered, next.scroll, "only the fresh snapshot's share was claimed"); + } else { + assert_eq!(next.claimed_gathered, Vec2::ZERO, "the stale snapshot left the new share unclaimed"); + } +} + +#[trial] +fn a_small_reversal_of_a_claimed_gesture_keeps_the_step_count() { + let steps = Rc::new(Cell::new(0.0)); + let count = Rc::clone(&steps); + let mut fixture = Fixture::new(move |ui| { + let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0); + Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let remaining = wheel.claimed_gathered.y + wheel.scroll.y - wheel.claimed_spent.y; + let steps = (remaining / 30.0).trunc(); + if space.claim_wheel(ui.ctx(), Vec2::new(0.0, steps * 30.0)) { + count.set(count.get() + steps); + } + } + }); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(steps.get(), -1.0, "the first share takes one step"); + fixture.frame(vec![pointer::wheel(5.0)]); + assert_eq!(steps.get(), -1.0, "a reversal smaller than one step leaves the count unchanged"); +} diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 97ecae6636..dc0720d782 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -13,6 +13,13 @@ use craft_behavior::{ }; use craft_keymap::Mods; use egui::{Context, Id, IdMap, Pos2, Vec2}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The process-unique identity of a wheel share that can be claimed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClaimToken(u64); + +static NEXT_CLAIM_TOKEN: AtomicU64 = AtomicU64::new(0); pub(crate) struct State { this: Vec>, @@ -23,6 +30,7 @@ pub(crate) struct State { /// The last-pressed gated control while the pointer has stayed inside it since. armed: Option, shares: Vec<(Id, Wheel)>, + recipients: Vec, /// The wheel gesture the split tracks across passes. gesture: WheelGesture, /// The running gesture's gathered scroll in its owner's points, reset when the gesture closes. @@ -37,6 +45,14 @@ pub(crate) struct State { modal: bool, /// The time of the last wheel event a modal held; −∞ before the first. modal_last: f64, + /// The owner's claims on the running gesture, reset when the gesture closes. + claim: Claim, + /// The owner, token and motion of the running gesture's last share, which a claim in the same pass takes. + last_share: Option<(Id, ClaimToken, Vec2, Vec2)>, + /// This pass's claim of the last share, with the motion it spent; it joins `claim` when the next share gathers. + pending: Option<(Vec2, Vec2, Vec2)>, + /// Each registered owner remains here until it reads the cancellation of its claimed motion. + cancellations: IdMap<()>, /// The last gesture the device ended, which a momentum run of the same owner within `GESTURE_GAP` resumes. device_ended: Option, /// The wheel ease each owner holds. @@ -52,6 +68,7 @@ impl Default for State { last_layers: IdMap::default(), armed: None, shares: Vec::new(), + recipients: Vec::new(), gesture: WheelGesture::default(), gathered: Vec2::ZERO, zoom_gathered: Vec2::ZERO, @@ -59,6 +76,10 @@ impl Default for State { held: Mods::NONE, modal: false, modal_last: f64::NEG_INFINITY, + claim: Claim::default(), + last_share: None, + pending: None, + cancellations: IdMap::default(), device_ended: None, eases: IdMap::default(), } @@ -75,6 +96,32 @@ struct Ended { moved: bool, held: Mods, modal: bool, + claim: Claim, +} + +/// What the owner of a gesture claimed of it: whether it claimed a share, the claimed shares' scroll and zoom lines, +/// and the motion it said it spent. +#[derive(Clone, Copy, Default)] +struct Claim { + claimed: bool, + gathered: Vec2, + zoom_gathered: Vec2, + spent: Vec2, +} + +impl Claim { + /// Gives `share` the claims made before it. + fn give(self, share: &mut Wheel) { + share.claimed = self.claimed; + share.claimed_gathered = self.gathered; + share.claimed_zoom_gathered = self.zoom_gathered; + share.claimed_spent = self.spent; + } + + /// These claims and one more, of a share of `scroll` and `zoom_lines` that spent `spent`. + fn with(self, scroll: Vec2, zoom_lines: Vec2, spent: Vec2) -> Self { + Claim { claimed: true, gathered: self.gathered + scroll, zoom_gathered: self.zoom_gathered + zoom_lines, spent: self.spent + spent } + } } /// The modifiers held in `a` or in `b`. @@ -95,6 +142,70 @@ pub(crate) fn mark_moved(ctx: &Context, id: Id) { }); } +/// The token for the share `id` can claim in the running pass, including after it reads the share. +pub fn claim_token(ctx: &Context, id: Id) -> Option { + let running = crate::runtime::frame::running(ctx)?; + PerViewport::::with(ctx, running.viewport, |state| state.last_share.filter(|(owner, _, _, _)| *owner == id).map(|share| share.1)) +} + +/// Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion +/// it used up, in its own unit, returning whether the claim succeeded. The shares that follow in the gesture carry +/// `claimed` and the claimed motion (`Wheel::claimed_gathered`, `claimed_zoom_gathered` and `claimed_spent`); a share +/// the owner does not claim is not counted in them. A second claim in the same pass replaces the first, so a body +/// that runs twice claims once. Without a share for `id` in the running pass, or if `id` does not own the gesture, +/// it returns `false` without changing the claims. `token` must identify the share being claimed. +pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool { + if !spent.is_finite() { + return false; + } + let Some(running) = crate::runtime::frame::running(ctx) else { return false }; + PerViewport::::with(ctx, running.viewport, |state| { + let Some((owner, shared_token, scroll, zoom_lines)) = state.last_share else { return false }; + if owner != id || shared_token != token { + return false; + } + if state.gesture.owner != Some(id) { + return false; + } + state.pending = Some((scroll, zoom_lines, spent)); + state.cancellations.insert(id, ()); + // The eased wheel's owed motion stops with the claim: the owner's view moves no further by the gesture. + state.eases.remove(&id); + let now = crate::runtime::frame::clock(ctx); + // The swipe the device ended in this pass goes on in its momentum run, which must see the claim too. + let claimed = state.claim.with(scroll, zoom_lines, spent); + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id && ended.at == now) { + ended.claim = claimed; + } + true + }) +} + +/// Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that +/// cancellation. A cancellation persists after the gesture closes until the owner reads it or stops registering. +pub fn claimed(ctx: &Context, id: Id) -> bool { + PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + let canceled = state.cancellations.remove(&id).is_some(); + canceled || (state.gesture.owner == Some(id) && (state.claim.claimed || state.pending.is_some())) + }) +} + +/// Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under an app's own +/// modal window that the wheel service does not see as a modal layer. The gesture's later shares carry +/// `Wheel::modal` until it ends. +pub fn mark_modal(ctx: &Context, id: Id) { + PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + let received = state.recipients.contains(&id); + if state.gesture.owner == Some(id) || received { + state.modal = true; + } + let now = crate::runtime::frame::clock(ctx); + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id || (received && ended.at == now)) { + ended.modal = true; + } + }); +} + /// Feeds `pan` to the wheel ease of `id` and returns this pass's eased step. The step is paid by the clock, so a /// later pass of the same frame pays zero. pub(crate) fn ease(ctx: &Context, id: Id, pan: Vec2) -> Vec2 { @@ -142,6 +253,7 @@ impl State { } let last = &self.last; self.eases.retain(|id, _| last.iter().any(|taker| taker.owner == *id)); + self.cancellations.retain(|id, _| last.iter().any(|taker| taker.owner == *id)); let open = self.gesture.last.is_finite(); let ended = self.gesture.end(if pressed { f64::INFINITY } else { now }); if open && !self.gesture.last.is_finite() { @@ -150,6 +262,7 @@ impl State { self.moved = false; self.held = Mods::NONE; self.modal = false; + self.clear_claim(Claim::default()); } ended } @@ -166,9 +279,25 @@ impl State { swipe.map_or((Vec2::ZERO, Vec2::ZERO, false, Mods::NONE), |ended| (ended.gathered, ended.zoom_gathered, ended.moved, ended.held)); // A turn that went on under a modal until just now goes on under it after the modal closes. self.modal = swipe.is_some_and(|ended| ended.modal) || now - self.modal_last < GESTURE_GAP; + self.clear_claim(swipe.map_or(Claim::default(), |ended| ended.claim)); swipe.map(|ended| ended.owner) } + /// Starts the running gesture's claims at `claim`, with no claim pending. + fn clear_claim(&mut self, claim: Claim) { + self.claim = claim; + self.last_share = None; + self.pending = None; + } + + /// Adds this pass's claim, if any, to the running gesture's claims. + fn settle_claim(&mut self) { + if let Some((scroll, zoom_lines, spent)) = self.pending.take() { + self.claim = self.claim.with(scroll, zoom_lines, spent); + } + self.last_share = None; + } + /// Adds `share`, in its owner's points, to the gesture it belongs to and gives it the gesture's gathered scroll, /// mark and held modifiers; a share of another owner than the gesture's gathers only itself. Every share carries /// whether the gesture went on under a modal. A point share cancels its owner's @@ -181,6 +310,12 @@ impl State { } share.modal = self.modal; if self.gesture.owner == Some(owner) { + self.claim.give(share); + if self.last_share.is_none() + && let Ok(token) = NEXT_CLAIM_TOKEN.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1)) + { + self.last_share = Some((owner, ClaimToken(token), share.scroll, share.zoom_lines)); + } self.gathered += share.scroll; self.zoom_gathered += share.zoom_lines; share.gathered = self.gathered; @@ -290,6 +425,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.last = std::mem::take(&mut state.this); state.last_layers = std::mem::take(&mut state.this_layers); state.shares.clear(); + // Last pass's claim joins the gesture's; a claim in this pass takes only a share of this pass. + state.settle_claim(); if let Some(winner) = pressed_on { state.armed = winner.filter(|id| state.last.iter().any(|taker| taker.gated && taker.owner == *id)); } @@ -312,6 +449,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { let held_before = if closing_press { either(state.held, press_mods) } else { state.held }; // A wheel a modal held in the pass before that press arrived during the gesture too. let modal_before = state.modal || (closing_press && wheel_before_press && (blocked || modal_family.is_some())); + let claim_before = state.claim; let ended = state.close_gesture(pressed_on.is_some(), now); let ended = ended.filter(|owner| state.last.iter().any(|taker| taker.owner == *owner && taker.value)); // A key tapped between the running gesture's wheel events counts as held for the rest of it, and one tapped @@ -331,6 +469,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { // The end carries the metadata of the gesture it ends. let mut end = Wheel::new(Vec2::ZERO, mods, WheelUnit::Point, WheelPhase::End); (end.held, end.modal) = (held_before, modal_before); + claim_before.give(&mut end); state.shares.push((owner, end)); } if let (Some(frame), Some(at)) = (&frame, hover) @@ -384,12 +523,17 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { }) }) .collect(); - let (previous_owner, held, modal) = (state.gesture.owner, state.held, state.modal); + let (previous_owner, held, modal, claimed) = (state.gesture.owner, state.held, state.modal, state.claim); let shares = split(&eligible, at, share, focus, state.armed, &mut state.gesture, now); // A momentum run resumes its swipe only on the swipe's owner; any split drops the ended swipe. if swipe.is_some() && state.gesture.owner != swipe { (state.gathered, state.zoom_gathered, state.moved, state.held) = (Vec2::ZERO, Vec2::ZERO, false, Mods::NONE); state.modal = now - state.modal_last < GESTURE_GAP; + state.clear_claim(Claim::default()); + } + // A running gesture the split hands to another owner starts its claims again: the new owner claimed none. + if previous_owner.is_some() && state.gesture.owner != previous_owner { + state.clear_claim(Claim::default()); } state.held = either(state.held, either(mods, held_mods)); state.device_ended = None; @@ -405,12 +549,15 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.gather(owner, &mut share); if share.phase == WheelPhase::End && Some(owner) == previous_owner && state.gesture.owner != previous_owner { (share.held, share.modal) = (held, modal); + claimed.give(&mut share); } state.shares.push((owner, share)); } if device_end { - let (gathered, zoom_gathered, moved, held, modal) = (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal); - state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal }); + let (gathered, zoom_gathered, moved, held, modal, claim) = + (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal, state.claim); + state.device_ended = + state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal, claim }); } } } @@ -422,6 +569,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.shares.remove(0); state.shares[at].1.phase = WheelPhase::Start; } + state.recipients.clear(); + state.recipients.extend(state.shares.iter().map(|(owner, _)| *owner)); // A value control that owns the running gesture hears its end without a timer of its own: a pass at the gap. // An owed ease pays in the passes that follow. state.wake(now) diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index aa33841af6..c5de7bda0c 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -558,6 +558,118 @@ fn a_wheel_gesture_carries_the_keys_held_during_it_and_whether_it_began_under_a_ assert!(!fresh.modal, "a turn begun after the gap: {fresh:?}"); } +#[trial] +fn a_wheel_gesture_counts_only_the_shares_its_owner_claimed_and_an_app_modal_marks_it() { + let canvas = Id::unique("claim_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + // What the body does with this pass's share: claim it with this much spent, and mark the turn modal. + let claim: Cell> = Cell::new(None); + let modal = Cell::new(false); + let last: Cell> = Cell::new(None); + let last_token = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if let Some(share) = take_share(ui.ctx(), canvas) { + last.set(Some(share)); + let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share"); + last_token.set(Some(token)); + for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + for spent in [Vec2::new(invalid, 0.0), Vec2::new(0.0, invalid)] { + assert!(!craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent), "a claim of {spent:?} is refused"); + } + } + if let Some(spent) = claim.get() { + // A body that runs twice in a pass claims once. + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent)); + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent)); + } + if modal.get() { + craft_ui::runtime::wheel::mark_modal(ui.ctx(), canvas); + } + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(Pos2::new(200.0, 200.0))], &mut show_frame); + let turn = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), take: Option| { + claim.set(take); + last.set(None); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + last.take().expect("the canvas takes the wheel") + }; + + // The first share is not claimed: the claims count nothing of it. + let first = turn(&mut frames, &mut show_frame, None); + assert!(!first.claimed && first.claimed_gathered == Vec2::ZERO, "nothing claimed yet: {first:?}"); + assert!( + !craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)), + "a share cannot be claimed between passes" + ); + assert!(!craft_ui::runtime::wheel::claimed(&frames.ctx, canvas), "a rejected claim does not cancel navigation"); + let second = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, 1.0))); + assert!(!second.claimed && second.claimed_gathered == Vec2::ZERO, "the first share was left unclaimed: {second:?}"); + assert!( + !craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)), + "a late claim cannot replace the body's spent motion" + ); + let third = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, -1.0))); + assert!(third.claimed, "the second share was claimed: {third:?}"); + assert_eq!((third.claimed_gathered, third.claimed_spent), (second.scroll, Vec2::new(0.0, 1.0)), "one claim of the second share: {third:?}"); + assert_eq!(third.gathered, first.scroll + second.scroll + third.scroll, "the gesture still gathers every share: {third:?}"); + let fourth = turn(&mut frames, &mut show_frame, None); + assert_eq!((fourth.claimed_gathered, fourth.claimed_spent), (second.scroll + third.scroll, Vec2::ZERO), "{fourth:?}"); + + // An app's own modal marks the rest of the turn, and a new turn starts with no claims and no mark. + modal.set(true); + let marked = turn(&mut frames, &mut show_frame, None); + assert!(!marked.modal, "the mark comes after the share: {marked:?}"); + modal.set(false); + let after = turn(&mut frames, &mut show_frame, None); + assert!(after.modal && after.claimed, "the rest of the turn is marked: {after:?}"); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut show_frame); + let fresh = turn(&mut frames, &mut show_frame, None); + assert!(!fresh.modal && !fresh.claimed && fresh.claimed_gathered == Vec2::ZERO && fresh.claimed_spent == Vec2::ZERO, "{fresh:?}"); +} + +/// An unread cancellation survives gesture close while its owner registers and is released when that owner leaves. +#[trial] +fn unread_claim_cancellations_follow_registered_owners() { + for discarded in [false, true] { + let canvas = Id::unique("discarded_claim_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let registered = Cell::new(true); + let consume = Cell::new(false); + let claimed = Cell::new(false); + let canceled = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + if registered.get() { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if take_share(ui.ctx(), canvas).is_some() { + let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share"); + craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, Vec2::ZERO); + claimed.set(true); + } + if consume.take() { + canceled.set(Some(craft_ui::runtime::wheel::claimed(ui.ctx(), canvas))); + } + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(rect.center())], &mut show_frame); + frames.frame(vec![pointer::wheel(-30.0)], &mut show_frame); + assert!(claimed.get(), "the owner claimed its share"); + frames.advance(GESTURE_GAP); + registered.set(!discarded); + frames.idle(2, &mut show_frame); + registered.set(true); + consume.set(true); + frames.frame(Vec::new(), &mut show_frame); + assert_eq!(canceled.get(), Some(!discarded), "discarded {discarded}: only a registered owner retains its cancellation"); + } +} + #[trial] fn the_end_share_of_a_pressed_wheel_gesture_carries_a_key_tapped_before_the_press_in_its_pass() { let slider = Id::unique("press_held_slider"); diff --git a/docs/contract-api.md b/docs/contract-api.md index 8d3f7b3c92..b4055910a0 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1842,7 +1842,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. - `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool, pub claimed: bool, pub claimed_gathered: Vec2, pub claimed_zoom_gathered: Vec2, pub claimed_spent: Vec2 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. - `pub const fn zoom_lines(mut self, lines: Vec2) -> Self`. The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). @@ -4604,6 +4604,17 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con - `craft_ui::runtime::toast::shown`: `pub fn shown(ctx: &Context, id: ToastId, text: &str, held: bool)`. The host shows `id` in this pass; `held` says the pointer or focus is on it. - `craft_ui::runtime::toast::snapshot`: `pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)>`. Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's. +## `craft_ui::runtime::wheel` + +The wheel service (8.6): takers register their view rects, the begin hook splits the pass's wheel input among them from last pass's registrations, and each taker reads its share once. + +- `craft_ui::runtime::wheel::ClaimToken`: `pub struct ClaimToken(/* private fields */)`. A small `Copy` token that identifies a claimable wheel share and never repeats in the process. +- `craft_ui::runtime::wheel::claim_token`: `pub fn claim_token(ctx: &Context, id: Id) -> Option`. Returns the token for the share `id` can claim in the running pass, including after it reads the share. +- `craft_ui::runtime::wheel::claim`: `pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool`. Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion it used up, in its own unit, returning whether the claim succeeded. The token must match the share being claimed, including when a viewport is recreated with the same ID and pass counter. +- `craft_ui::canvas::CanvasSpace::with_wheel`: `pub fn with_wheel(mut self, wheel: Option) -> Self`. Sets the wheel share without a claim token. `CanvasSpace::claim_wheel` refuses a snapshot from another share. +- `craft_ui::runtime::wheel::claimed`: `pub fn claimed(ctx: &Context, id: Id) -> bool`. Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that cancellation. +- `craft_ui::runtime::wheel::mark_modal`: `pub fn mark_modal(ctx: &Context, id: Id)`. Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under a modal: an app's own modal window that the wheel service does not see as a modal layer. + ## `craft_ui::runtime::windows` `WindowHost`: the one multi-window driver.