From d0d8281e9b33f4b5e4b6e1fbc4c5b53b64ae1879 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 05:02:29 -0500 Subject: [PATCH] pdf-canvas-w1: net change of 2 commits - pdf-canvas-w1: written from its sheet - pdf-canvas-w1: review fixes (review-1) --- crates/ui-canvas/src/canvas/mod.rs | 222 ++++++++++-- crates/ui-canvas/src/canvas/navigate/mod.rs | 45 +-- .../ui-canvas/src/canvas/navigate/options.rs | 3 - .../ui-canvas/src/canvas/navigate/stories.rs | 39 ++- crates/ui-canvas/src/canvas/navigate/wheel.rs | 24 +- .../ui-canvas/src/canvas/navigator/preview.rs | 4 +- crates/ui-canvas/src/canvas/space.rs | 9 +- crates/ui-canvas/src/canvas/zoom_motion.rs | 8 +- crates/ui-canvas/tests/it/canvas/navigate.rs | 318 ++++++++++++++++-- .../ui-canvas/tests/it/full_window_parts.rs | 4 +- migration/api-map/canvas-core.toml | 21 +- 11 files changed, 572 insertions(+), 125 deletions(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index c30064100..4d0171d5f 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -3,12 +3,12 @@ //! `Canvas` is an arena root: the leaf components its body shows with `show_at(canvas_rect)` (canvas controls, //! such as `CropOverlay`) join its arena, and a press away from all of their parts reaches the active tool through //! the canvas's background part. A canvas given a view ([`Canvas::view`]) owns what happens to it in a pass: it -//! sets the view's rect to its own, fits a view never shown, folds in the wheel, a middle-button pan and the view -//! commands routed to it ([`ViewCommands`]), keeps the document in view with Overscroll off, eases a zoom under -//! Animated Zoom, publishes the view it shows as a [`CanvasSpace`] to its body, and reports the view the app copies. +//! sets the view's rect to its own, fits a view never shown, folds in the wheel (eased under the eased wheel, gliding +//! on after a touchpad lift), a middle-button pan or latched scroll and the view commands routed to it +//! ([`ViewCommands`]), keeps the document in view with Overscroll off, eases a zoom under Animated Zoom, publishes the +//! view it shows as a [`CanvasSpace`] to its body, and reports the view the app copies. mod crop; -mod frame_step; // The full-window dialog family; `dialog` re-exports it. pub(crate) mod full_window; pub(crate) mod full_window_parts; @@ -27,7 +27,7 @@ mod tool_host; pub use crate::canvas_data::{Guide, GuideColor, GuideDrag, GuideKey, GuideLine, NavigatorOptions, NavigatorSettings, ProxyColor}; pub use crop::{CropOutside, CropOverlay, CropOverlayOutput, CropShield, CropStyle, ShieldColor, paint_outside}; -pub use frame_step::{FRAME_STEP_MAX, frame_step}; +pub use craft_behavior::{FRAME_STEP_MAX, frame_step}; pub(crate) use march::{MARCH_SECONDS, MARCH_TICK, march_shift}; pub use readout::{ShowReadouts, hud, readout}; pub use space::{CanvasSpace, RulerText, canvas_space, pixel_aligned}; @@ -72,8 +72,7 @@ mod zoom_motion; pub use momentary::{Momentary, MomentaryCommands, MomentaryTool}; pub use navigate::{ - Autoscroll, FlickPan, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, TouchpadGlide, WheelAction, WheelInput, WheelNavigation, - WheelScheme, pan, + Autoscroll, FlickPan, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, WheelAction, WheelInput, WheelNavigation, WheelScheme, pan, }; pub use rotate::{RotateView, RotateViewOutput, RotateViewStyle, ViewTurn}; pub use tools::{HandTool, LayerBounds, RotateViewTool, ViewCommands, ViewRequest, ViewTarget, ZoomTool}; @@ -103,9 +102,11 @@ pub mod navigator_panel; use crate::contract::{ Bind, Common, Component, Container, ContainerProps, Cx, Focus as _, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, Sizing, }; +use crate::style::AutoScrollMarkLook; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; +use crate::runtime::frame; use crate::runtime::lock_keys; use crate::runtime::measure; use crate::runtime::motion::{Animate as _, spec}; @@ -113,9 +114,10 @@ use crate::style::{ComponentStyle, Stateful, StyleCx, SurfaceKind, SurfaceLook}; use craft_behavior::geometry::crop::normalized_angle; use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; use craft_behavior::{ - CanvasTransform, CanvasView, EditEvent, HitLevel, HitPriority, HitShape, Intent, Metrics, Mixed, PartKey, PointerButton, PressPhase, PressState, - Sense, WheelNotch, + CanvasTransform, CanvasView, CursorIcon, CursorPriority, EditEvent, HitLevel, HitPriority, HitShape, Intent, Metrics, MiddleButton, Mixed, + PartKey, PointerButton, PressPhase, PressState, Sense, Wheel, WheelNotch, WheelUnit, }; +use craft_keymap::{Chord, Key}; use egui::{Pos2, Rect, Response, Vec2}; use zoom_motion::{Steer, ViewMotion}; @@ -129,6 +131,10 @@ const TOOL_REGION: PartKey = PartKey::new("toolRegion"); /// ([`CanvasTool::command_form`]), the one owner of that fact. const TOOL_PATH: &str = "the running tool's command form"; +/// The key that ends a latched middle scroll. The canvas claims it only while a latch runs, so otherwise Escape reaches +/// the tool and the dialog around the canvas. +const LATCH_ESCAPE: Chord = Chord::plain(Key::Escape); + /// How a tool is reached without a pointer (8.3, owner question 15). #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -153,6 +159,8 @@ pub struct CanvasStyle { metrics: Metrics, /// How far the rulers' strips push the view's rect in from the canvas's top-left corner, while they show. rulers: Vec2, + /// The mark a latched middle scroll shows at its anchor. + mark: Option, } /// A canvas: a pasteboard the caller's canvas controls and the active tool share. @@ -257,6 +265,14 @@ struct Settled { easing: bool, /// The keys the canvas leaves to its body. keys: BodyKeys, + /// The wheel share the canvas took this pass, handed on to its body. + wheel: Option, + /// A latched or held middle scroll runs. + auto_scrolling: bool, + /// Where a latched middle scroll is anchored. + mark: Option, + /// The press on the background is the one that ended a latch: it reaches no tool through its release. + swallowed: bool, } impl<'a> Canvas<'a> { @@ -385,8 +401,9 @@ impl<'a> Canvas<'a> { if self.show_rulers { Rect::from_min_max(rect.min + style.rulers, rect.max) } else { rect } } - /// The view of this pass from the app's `given` view: this pass's rect, the first fit, the wheel, a middle-button - /// pan, the view commands, the Overscroll clamp, and the zoom ease. + /// The view of this pass from the app's `given` view: this pass's rect, the first fit, the wheel with its ease and + /// the touchpad glide, a middle-button pan or latched scroll, the view commands, the Overscroll clamp, and the zoom + /// ease. fn settle(&self, cx: &mut Cx<'_, Self>, given: CanvasView) -> Settled { let ctx = cx.core.ctx.clone(); let id = cx.core.id; @@ -402,22 +419,115 @@ impl<'a> Canvas<'a> { ViewCommands::FitOnScreen.apply(&mut view, &document, None, pixels_per_point); } } + let at_start = view; + // The pass clock. A later pass of the same frame reads the same time and no elapsed time, so the glide and the + // latched scroll move the view only in the pass that receives the frame's time. + + let now = frame::clock(&ctx); + let elapsed = frame::running(&ctx).map_or(0.0, |facts| facts.elapsed); + let (press, on_region) = self.pressed(cx); + // A press, a zoom, a key move and a view command end the touchpad glide and the eased wheel's owed motion. + let mut halt = matches!(press.phase, PressPhase::Down { .. }); let mut jumped = false; - if let Some(wheel) = cx.take_wheel() { - let os = cx.env.shell().os; - if let Some(action) = motion.wheel.read(&wheel, WheelNavigation::LINE, os, &self.navigation) { - // The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in its body - // covers it. - let at = wheel.at.unwrap_or_else(|| view.rect.center()); - jumped |= WheelNavigation::apply(&mut view, action, at, size, pixels_per_point); + let mut line_pan = Vec2::ZERO; + let wheel = cx.take_wheel(); + if let Some(wheel) = wheel { + let (line, os) = (self.navigation.wheel_line, cx.env.shell().os); + let mut zoomed = false; + if let Some(action) = motion.wheel.read(&wheel, line, os, &self.navigation) { + match action { + // The eased wheel hands a line's pan to the wheel service, which pays it out over the passes after. + WheelAction::Pan(delta) if self.navigation.eased_wheel && wheel.unit == WheelUnit::Line => line_pan = delta, + action => { + zoomed = !matches!(action, WheelAction::Pan(_)); + // The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in + // its body covers it. + let at = wheel.at.unwrap_or_else(|| view.rect.center()); + jumped |= WheelNavigation::apply(&mut view, action, at, size, pixels_per_point); + } + } } // A trackpad rotation or a twist of two fingers turns the view; a mirrored view turns the other way. - if let Some(degrees) = WheelNavigation::rotation(&WheelInput::of(&wheel, WheelNavigation::LINE, os), &self.navigation) { + if let Some(degrees) = WheelNavigation::rotation(&WheelInput::of(&wheel, line, os), &self.navigation) { view.rotation = normalized_angle(view.rotation + ViewTurn::screen_delta(degrees, view.flip_x)); jumped = true; + zoomed = true; + } + halt |= zoomed; + motion.glide.read(&wheel, now, !zoomed && self.navigation.touchpad_glide); + // The wheel ends a latched middle scroll. + if motion.middle.active() { + motion.middle.cancel(); } } - if let Some(delta) = self.background_press(cx).1 { + // Every pass feeds the ease, the line pan or nothing, so owed motion keeps paying; the service takes the time + // from its own clock, so a later pass of the same frame pays nothing. + if self.navigation.eased_wheel && !halt { + let step = cx.ease_wheel(line_pan); + if step != Vec2::ZERO { + pan(&mut view, step); + jumped = true; + } + if step != Vec2::ZERO || line_pan != Vec2::ZERO { + frame::request_own_repaint(&ctx); + } + } + let before_glide = view; + let glide = if halt { Vec2::ZERO } else { motion.glide.step(now) }; + if glide != Vec2::ZERO { + pan(&mut view, glide); + jumped = true; + } + if motion.glide.gliding() { + frame::request_own_repaint(&ctx); + } + // The middle button latches a scroll over the background (no tool region holds the press): a click latches it, + // a second press ends it, and a release after a drag past the dead zone ends it. + let middle = press.phase.start().is_some_and(|start| start.button == PointerButton::Middle); + let latching = middle && !on_region && self.navigation.middle_button == MiddleButton::AutoScroll; + let held = latching && press.phase.button_down(); + match press.phase { + PressPhase::Down { start, .. } if latching => motion.middle.press(start.origin, area.contains(start.origin)), + PressPhase::Release { .. } if latching => motion.middle.release(), + PressPhase::Cancel { .. } if latching => motion.middle.cancel(), + // Any other press on the background ends a latch. + PressPhase::Down { .. } if motion.middle.active() => motion.middle.cancel(), + _ => {} + } + // PLAN: assumed MiddleScroll::swallows(&mut self, PressPhase) -> bool (pdf-canvas-w2) + let swallowed = motion.middle.swallows(press.phase); + // A latch with the button up ends on Escape, claimed only while it runs, and when the canvas loses focus. + if motion.middle.active() && !held { + if cx.take_claimed(LATCH_ESCAPE) || !cx.is_focused() { + motion.middle.cancel(); + } else { + cx.claim(LATCH_ESCAPE); + } + } + if motion.middle.active() { + // The pointer is read where it is over the background: the press while the button is held, the hover after. + let pointer = match press.phase { + PressPhase::Held { pos, .. } | PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } if held => Some(pos), + _ => cx.hover_pos(BACKGROUND), + }; + if let Some(pointer) = pointer { + let step = motion.middle.step(pointer, held, elapsed, self.navigation.invert_middle); + if step != Vec2::ZERO { + pan(&mut view, step); + jumped = true; + } + } + cx.cursor(CursorIcon::ResizeVertical, CursorPriority::Part); + frame::request_own_repaint(&ctx); + } + // Under a latch the held press scrolls by its distance from the anchor; only the Pan mode drags the view 1:1. + let held_pan = middle && !latching && press.phase.is_drag(); + if held_pan { + cx.cursor(CursorIcon::Grabbing, CursorPriority::Drag); + } + let auto_scrolling = motion.middle.active() || held_pan; + let mark = motion.middle.anchor(); + if let Some(delta) = self.background_press(cx, swallowed).1 { pan(&mut view, delta); jumped = true; } @@ -435,6 +545,7 @@ impl<'a> Canvas<'a> { moves.push(mv); } moves.extend(cx.take_scroll_moves()); + halt |= !moves.is_empty(); for (step, mods) in moves { if self.keys_to_body { keys.page = Some((step, mods)); @@ -457,6 +568,7 @@ impl<'a> Canvas<'a> { let before = view; if let Some((next, motion)) = self.view_commands(cx, Some(view)) { view = next; + halt = true; match motion { CommandMotion::Ease if self.navigation.animated_zoom => { // A zoom that keeps the centre eases about it; one that moves the centre (Fit on Screen) eases @@ -469,6 +581,18 @@ impl<'a> Canvas<'a> { } } let target = clamped(view, self.document_size(), &self.navigation); + if glide != Vec2::ZERO { + motion.glide.moved(target != before_glide); + } + if halt { + motion.glide.stop(); + cx.stop_wheel_ease(); + } + // A view that moves during a wheel gesture marks it moved, so a body that turns pages at the edge does not turn + // one after a pan or a go-to. + if target != at_start { + cx.mark_wheel_moved(); + } let mut progress = cx.anim("zoom", motion.animation.target(), spec::MOVE); match steer { Some(Steer::Ease { mut from, anchor }) => { @@ -482,7 +606,7 @@ impl<'a> Canvas<'a> { let shown = motion.animation.shown(&target, progress); let easing = motion.animation.running(); motion.restore(&ctx, id); - Settled { target, shown, easing, keys } + Settled { target, shown, easing, keys, wheel, auto_scrolling, mark, swallowed } } /// Measures the document's axes in `x` and `y`, counted from `zero` (document units). The rulers, the guides and @@ -497,9 +621,9 @@ impl<'a> Canvas<'a> { /// The space the body and the tool see in this pass; `caps_lock` is whether Caps Lock is on in it. fn space(&self, id: egui::Id, pixels_per_point: f32, background: BackgroundPress, caps_lock: bool) -> Option { - let (shown, target, easing, keys) = match self.settled { - Some(settled) => (settled.shown, settled.target, settled.easing, settled.keys), - None => (self.given?, self.given?, false, BodyKeys::default()), + let (shown, target, easing, keys, wheel) = match self.settled { + Some(settled) => (settled.shown, settled.target, settled.easing, settled.keys, settled.wheel), + None => (self.given?, self.given?, false, BodyKeys::default(), None), }; let mut space = CanvasSpace::new(target, pixels_per_point).with_follows_pointer(self.follows_pointer); space.set_view(target); @@ -513,6 +637,7 @@ impl<'a> Canvas<'a> { .with_pasteboard(self.pasteboard) .with_background(background) .with_precise(self.precise_cursors != caps_lock) + .with_wheel(wheel) .with_canvas(id); Some(match self.picture { Some(slot) => space.with_picture(slot), @@ -526,18 +651,34 @@ impl<'a> Canvas<'a> { self.snap.clone().map(|snap| snap.at(&view, os)) } - /// The press on the background part, or on the tool region that holds it, as the canvas reports it, and the pan - /// of a middle-button drag: a middle press pans the view and is never a tool press. - fn background_press(&self, cx: &Cx<'_, Self>) -> (PressState, Option) { + /// The press on the background part, or on the tool region that holds it, and whether a tool region holds it. + fn pressed(&self, cx: &Cx<'_, Self>) -> (PressState, bool) { let region = (0..self.tool_regions.len() as u64) .filter_map(|i| cx.part_if_declared(TOOL_REGION.at(i))) .map(|result| result.press) .find(|press| !matches!(press.phase, PressPhase::Idle)); - let press = region.unwrap_or(cx.part(BACKGROUND).press); + match region { + Some(press) => (press, true), + None => (cx.part(BACKGROUND).press, false), + } + } + + /// The press on the background part, or on the tool region that holds it, as the canvas reports it, and the pan + /// of a middle-button drag: a middle press pans the view and is never a tool press. Under Invert Middle the drag + /// pans the other way, as the latched scroll does. Where the middle button latches (`MiddleButton::AutoScroll`, no + /// tool region under the press) the drag does not pan: the latch's step scrolls. A `swallowed` press (the one that + /// ended a latch) is idle. + fn background_press(&self, cx: &Cx<'_, Self>, swallowed: bool) -> (PressState, Option) { + let (press, on_region) = self.pressed(cx); + if swallowed { + return (PressState::IDLE, None); + } + let pans = !(self.navigation.middle_button == MiddleButton::AutoScroll && !on_region); let middle = press.phase.start().is_some_and(|start| start.button == PointerButton::Middle); + let sign = if self.navigation.invert_middle { -1.0 } else { 1.0 }; match press.phase { - PressPhase::DragStart { start, pos, .. } if middle => (PressState::IDLE, Some(pos - start.origin)), - PressPhase::Drag { delta, .. } if middle => (PressState::IDLE, Some(delta)), + PressPhase::DragStart { start, pos, .. } if middle && pans => (PressState::IDLE, Some((pos - start.origin) * sign)), + PressPhase::Drag { delta, .. } if middle && pans => (PressState::IDLE, Some(delta * sign)), _ if middle => (PressState::IDLE, None), _ => (press, None), } @@ -545,7 +686,7 @@ impl<'a> Canvas<'a> { /// The tool host's input of this pass: settled in `update`, so the body and `finish` read the same. fn tool_pass(&self, cx: &Cx<'_, Self>) -> ToolPass { - let press = self.background_press(cx).0; + let press = self.background_press(cx, self.settled.is_some_and(|settled| settled.swallowed)).0; let caps_lock = lock_keys::caps_lock(&cx.response.ctx); let space = self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key), caps_lock); ToolPass { @@ -647,7 +788,12 @@ impl Component for Canvas<'_> { fn style(cx: &StyleCx<'_>, _: CanvasStyleKey) -> CanvasStyle { let surface = SurfaceLook::new(Stateful::new(cx.color(cx.tokens.color.surface.canvas))).kind(SurfaceKind::Canvas); // The rulers' own layout says where the view lies inside them. - CanvasStyle { surface: Some(surface), rulers: Rulers::content_rect(cx, Rect::ZERO).min.to_vec2(), ..CanvasStyle::default() } + CanvasStyle { + surface: Some(surface), + rulers: Rulers::content_rect(cx, Rect::ZERO).min.to_vec2(), + mark: Some(cx.auto_scroll_mark()), + ..CanvasStyle::default() + } } fn sense(&self) -> Sense { @@ -655,7 +801,7 @@ impl Component for Canvas<'_> { } fn wheel_notch(&self) -> WheelNotch { - WheelNotch::Points(WheelNavigation::LINE) + WheelNotch::Points(self.navigation.wheel_line) } /// Reserves the slot the picture paints into, under every canvas control of the body (`CanvasSpace::paint_picture`). @@ -663,6 +809,13 @@ impl Component for Canvas<'_> { self.picture = Some(ui.reserve_slot(cx.content_rect)); } + /// The mark of a latched middle scroll, at its anchor above the body. + fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + if let (Some(anchor), Some(look)) = (self.settled.and_then(|settled| settled.mark), cx.style.mark) { + ui.draw().auto_scroll_mark(&look, anchor); + } + } + /// The view of this pass, kept for the body and `finish`. fn update(&mut self, cx: &mut Cx<'_, Self>) { // Left untaken: the canvas's generic context request is recorded as for a secondary click. @@ -726,7 +879,8 @@ impl Component for Canvas<'_> { fn finish(self, cx: Cx<'_, Self>) -> CanvasOutput { let pass = self.tool_pass(&cx); - CanvasOutput { response: cx.response.clone(), press: pass.press, space: pass.space, view: pass.view, auto_scrolling: false } // P3(pdf-canvas-w1): CV-C6 + let auto_scrolling = self.settled.is_some_and(|settled| settled.auto_scrolling); + CanvasOutput { response: cx.response.clone(), press: pass.press, space: pass.space, view: pass.view, auto_scrolling } } } diff --git a/crates/ui-canvas/src/canvas/navigate/mod.rs b/crates/ui-canvas/src/canvas/navigate/mod.rs index 48ff8f74b..30603104d 100644 --- a/crates/ui-canvas/src/canvas/navigate/mod.rs +++ b/crates/ui-canvas/src/canvas/navigate/mod.rs @@ -132,11 +132,10 @@ impl FlickPan { } /// Touchpad momentum where the platform leaves it to the app (Wayland, which reports a lift as the end of the -/// scroll): a two-finger swipe keeps gliding after the fingers lift. The app creates it enabled only on a platform -/// that sends no momentum of its own. -#[derive(Clone, Debug, PartialEq)] -pub struct TouchpadGlide { - enabled: bool, +/// scroll): a two-finger swipe keeps gliding after the fingers lift. A canvas runs one under Touchpad Glide +/// ([`NavigationOptions::touchpad_glide`]), which an app turns on only on a platform that sends no momentum of its own. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct TouchpadGlide { samples: Vec<(f64, Vec2)>, /// The glide's speed in points per second, or zero. velocity: Vec2, @@ -160,13 +159,14 @@ impl TouchpadGlide { /// A pass this long after the last one (the view was hidden, the app stalled) ends a glide. const STALE: f64 = 0.1; - /// A glide that runs when `enabled`. - pub fn new(enabled: bool) -> Self { - Self { enabled, samples: Vec::new(), velocity: Vec2::ZERO, at: 0.0 } + /// 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.velocity = Vec2::ZERO; } - fn halt(&mut self) { - self.velocity = Vec2::ZERO; + /// Whether a glide runs: the canvas keeps passes coming while it does. + pub(crate) fn gliding(&self) -> bool { + self.velocity != Vec2::ZERO } fn push(&mut self, now: f64, delta: Vec2) { @@ -200,9 +200,9 @@ 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 (a zoom, a dialog). - pub fn read(&mut self, wheel: &Wheel, now: f64, glide: bool) { - self.halt(); + /// `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(); // 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(); @@ -215,7 +215,7 @@ impl TouchpadGlide { } WheelPhase::Move => self.push(now, wheel.scroll), WheelPhase::End => { - if glide && self.enabled { + if glide { self.velocity = self.lift_velocity(now); self.at = now; } @@ -225,14 +225,15 @@ impl TouchpadGlide { } } - /// The scroll this pass at `now`, in points; zero once stopped. - pub fn step(&mut self, now: f64) -> Vec2 { + /// The scroll this pass at `now`, in points; zero once stopped, and zero in a later pass of the same frame, which + /// reads the same `now`. + pub(crate) fn step(&mut self, now: f64) -> Vec2 { if self.velocity == Vec2::ZERO { return Vec2::ZERO; } let dt = now - self.at; if !(0.0..=Self::STALE).contains(&dt) { - self.halt(); + self.stop(); return Vec2::ZERO; } self.at = now; @@ -240,16 +241,16 @@ impl TouchpadGlide { let moved = self.velocity * Self::TAU * (1.0 - decay); self.velocity *= decay; if self.velocity.length() < Self::STOP_SPEED { - self.halt(); + self.stop(); } moved } - /// Whether the view moved in the pass of the last [`step`](Self::step): a pass that left it where it was (the - /// edge clamp) stops the glide. - pub fn moved(&mut self, moved: bool) { + /// Whether the view moved in the pass of the last [`step`](Self::step) that moved: a pass that left it where it + /// was (the edge clamp) stops the glide. + pub(crate) fn moved(&mut self, moved: bool) { if !moved { - self.halt(); + self.stop(); } } } diff --git a/crates/ui-canvas/src/canvas/navigate/options.rs b/crates/ui-canvas/src/canvas/navigate/options.rs index 49edffc24..c6d8b303e 100644 --- a/crates/ui-canvas/src/canvas/navigate/options.rs +++ b/crates/ui-canvas/src/canvas/navigate/options.rs @@ -7,8 +7,6 @@ use super::PageKey; #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct NavigationOptions { - /// General, Zoom with Scroll Wheel: the wheel zooms and Alt + wheel scrolls. Off. - pub zoom_with_wheel: bool, /// General, Animated Zoom: a zoom command, a Zoom tool click and a Navigator zoom ease on the canvas, and a held Zoom /// tool press zooms continuously; the wheel and a pinch follow the input at once. On. pub animated_zoom: bool, @@ -67,7 +65,6 @@ impl WheelScheme { impl Default for NavigationOptions { fn default() -> Self { Self { - zoom_with_wheel: false, animated_zoom: true, zoom_resizes_windows: false, zoom_clicked_point_to_center: false, diff --git a/crates/ui-canvas/src/canvas/navigate/stories.rs b/crates/ui-canvas/src/canvas/navigate/stories.rs index 4f40d15b8..3e07e9b1a 100644 --- a/crates/ui-canvas/src/canvas/navigate/stories.rs +++ b/crates/ui-canvas/src/canvas/navigate/stories.rs @@ -1,14 +1,15 @@ -//! Stories of the compass and the navigate bar. +//! Stories of the compass, the navigate bar and the canvas's latched middle scroll. use crate::bars::{Bar, BarKind}; use crate::canvas::rotate::RIM; -use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with}; +use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with, show_document}; use crate::canvas::{Canvas, NavigateBar, NavigationOptions, RotateView, RotateViewOutput, ViewTarget}; use crate::contract::{Bind, Show as _, ShowContainer as _, Validity}; +use crate::runtime::access::Role; use crate::runtime::env::Message; -use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; +use crate::testing::{Drive, Fixture, StoryData, StoryOutput, pointer, story}; use craft_behavior::kurbo::Point; -use craft_behavior::{CanvasView, Mixed}; +use craft_behavior::{CanvasView, MiddleButton, Mixed}; use egui::{Rect, Ui, Vec2}; /// The angle the stories start at, in degrees. @@ -104,3 +105,33 @@ fn hand_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let Navigation { view, options, .. } = data.value("navigation", Navigation::default()); bar_over_canvas(ui, view, |ui, _, _| NavigateBar::hand(&mut *options).show(ui).into()) } + +/// The latched scroll story's zoom, in percent: the document is taller than the canvas, so the latch has room to +/// scroll. +const LATCHED: f64 = 200.0; + +/// Latches the middle button's scroll with a middle click in the canvas's middle, then rests the pointer below the +/// anchor, where the view scrolls. The testing kit has no middle-button helper, so the drive sends the raw events. +fn latch_middle(fixture: &mut Fixture) { + let Some(canvas) = fixture.by_role(Role::CANVAS).first().map(|target| target.rect) else { return }; + let anchor = canvas.center(); + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: anchor, button: egui::PointerButton::Middle, pressed, modifiers: egui::Modifiers::NONE }; + fixture.frame(vec![pointer::moved(anchor), button]); + } + fixture.frame(vec![pointer::moved(anchor + Vec2::new(0.0, canvas.height() / 4.0))]); + fixture.idle(3); +} + +/// A canvas whose middle button latches a scroll ([`MiddleButton::AutoScroll`]): the mark shows at the anchor while +/// the latch runs. +#[story(Canvas, covers = [], drive = Drive::Custom(latch_middle))] +fn latched_middle_scroll(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let room = crate::testing::stage(ui); + let view = data.value("view", StoryDocument::STANDARD.view(room, ui.pixels_per_point(), LATCHED)); + let mut navigation = NavigationOptions::default(); + navigation.middle_button = MiddleButton::AutoScroll; + let target = ViewTarget::new(StoryDocument::STANDARD.rect().size()); + let canvas = Canvas::new("Document").view(Bind::bound(view)).document(target).navigation(navigation); + canvas.show_at(ui, room, |ui, body| show_document(ui, body.rect, &StoryDocument::STANDARD)).output.into() +} diff --git a/crates/ui-canvas/src/canvas/navigate/wheel.rs b/crates/ui-canvas/src/canvas/navigate/wheel.rs index 22b6c0db3..d813034d2 100644 --- a/crates/ui-canvas/src/canvas/navigate/wheel.rs +++ b/crates/ui-canvas/src/canvas/navigate/wheel.rs @@ -5,7 +5,7 @@ //! reads its share with these rules and applies it to the view it reports; a wheel zoom follows the wheel at once, //! with no ease. -use super::NavigationOptions; +use super::{NavigationOptions, WheelScheme}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Size; use craft_behavior::{CanvasView, Wheel, WheelNotch, WheelUnit, ZoomLadder}; @@ -76,8 +76,12 @@ impl WheelInput { /// - The wheel scrolls up and down; Shift or Cmd/Ctrl + wheel scrolls sideways. /// - Alt + wheel zooms about the pointer, 1.1 a notch; Shift + Alt + wheel steps the ladder. Alt with the Control /// key is the same zoom: on macOS Control may join it, elsewhere Ctrl (cmd) without Shift (production's #10488). -/// - A wheel line pans the canvas [`WheelNavigation::LINE`] points. -/// - Zoom with Scroll Wheel swaps them: the wheel zooms, Alt + wheel scrolls, Shift + wheel steps the ladder. +/// - A wheel line pans the canvas [`NavigationOptions::wheel_line`] points; a zoom is one notch a line whatever the +/// wheel line. +/// - [`WheelScheme::Zoom`] (Zoom with Scroll Wheel) swaps them: the wheel zooms, Alt + wheel scrolls, Shift + wheel +/// steps the ladder. +/// - [`WheelScheme::Acrobat`]: Cmd/Ctrl + wheel zooms about the pointer, [`WheelScheme::ACROBAT_NOTCH`] a line; +/// Shift + wheel scrolls sideways; there is no ladder step. /// - A trackpad pinch zooms about the pointer (Zoom with Trackpad Pinch). /// /// The value keeps the part of a ladder-step notch a trackpad has not finished, so slow scrolling still steps. @@ -90,9 +94,6 @@ impl WheelNavigation { /// The zoom factor of one wheel notch. pub const NOTCH: f64 = 1.1; - /// The points one wheel line pans the canvas: Photoshop's 16 (production's #12028). - pub const LINE: f32 = 16.0; - /// The most ladder steps one pass takes. const MOST_STEPS: f32 = 10.0; @@ -137,13 +138,18 @@ impl WheelNavigation { } let scroll_finite = input.scroll.x.is_finite() && input.scroll.y.is_finite(); let plain = !input.mods.cmd && !input.mods.ctrl; - let zooms = if options.zoom_with_wheel { plain && !input.mods.alt } else { Self::alt_gesture(input.mods, input.os) }; - if zooms && input.mods.shift { + // Whether the modifiers zoom, the zoom factor of one line, and whether Shift turns the zoom into ladder steps. + let (zooms, line_factor, ladder) = match options.wheel { + WheelScheme::Scroll => (Self::alt_gesture(input.mods, input.os), Self::NOTCH, true), + WheelScheme::Zoom => (plain && !input.mods.alt, Self::NOTCH, true), + WheelScheme::Acrobat => (!plain, WheelScheme::ACROBAT_NOTCH, false), + }; + if zooms && ladder && input.mods.shift { return scroll_finite.then(|| self.snap(input.along(), notch)).flatten().map(WheelAction::SnapZoom); } self.residual = 0.0; if zooms { - let factor = Self::NOTCH.powf(f64::from(input.along() / notch)); + let factor = line_factor.powf(f64::from(input.along() / notch)); return (scroll_finite && factor.is_finite() && factor > 0.0 && factor != 1.0).then_some(WheelAction::Zoom(factor)); } if !scroll_finite || input.scroll == Vec2::ZERO { diff --git a/crates/ui-canvas/src/canvas/navigator/preview.rs b/crates/ui-canvas/src/canvas/navigator/preview.rs index ad069c743..7562f7767 100644 --- a/crates/ui-canvas/src/canvas/navigator/preview.rs +++ b/crates/ui-canvas/src/canvas/navigator/preview.rs @@ -5,7 +5,7 @@ use super::proxy::{preview_rect, proxy_quad, view_center_for, zoom_to_document_rect}; use crate::canvas::AppPaint; use crate::canvas::zoom_motion::{self, Steer}; -use crate::canvas::{CanvasWords, NavigationOptions, PageKey, ViewCommands, WheelAction, WheelNavigation}; +use crate::canvas::{CanvasWords, NavigationOptions, PageKey, ViewCommands, WheelAction, WheelNavigation, WheelScheme}; use crate::canvas_data::ProxyColor; use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi, @@ -405,7 +405,7 @@ impl Component for Navigator<'_> { if let Some(wheel) = cx.take_wheel() && !running { - let options = NavigationOptions { zoom_with_wheel: true, ..self.navigation }; + let options = NavigationOptions { wheel: WheelScheme::Zoom, ..self.navigation }; let (line, os) = (craft_behavior::WheelNotch::DEFAULT.points(0.0), cx.env.shell().os); let action = cx.memory::().read(&wheel, line, os, &options); if let Some(action @ (WheelAction::Zoom(_) | WheelAction::SnapZoom(_))) = action { diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 2e7a0cb99..09d7d6179 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -40,7 +40,6 @@ 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, - #[allow(dead_code)] // P3(pdf-canvas-w1): CV-C5 wheel: Option, } @@ -68,14 +67,14 @@ 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 { - todo!("CV-C5") + self.wheel } /// This space with the wheel share the canvas read this pass. #[must_use] - pub fn with_wheel(self, wheel: Option) -> Self { - let _ = wheel; - todo!("CV-C5") + pub fn with_wheel(mut self, wheel: Option) -> Self { + self.wheel = wheel; + self } /// This space for a pass in which the app's tool moves the view with the pointer diff --git a/crates/ui-canvas/src/canvas/zoom_motion.rs b/crates/ui-canvas/src/canvas/zoom_motion.rs index e2a6188f3..fa6ade6e5 100644 --- a/crates/ui-canvas/src/canvas/zoom_motion.rs +++ b/crates/ui-canvas/src/canvas/zoom_motion.rs @@ -6,12 +6,12 @@ //! start it through [`ease`]. use super::frame_step; -use super::navigate::WheelNavigation; +use super::navigate::{TouchpadGlide, WheelNavigation}; use crate::runtime::frame; use crate::runtime::memory::{global, with_session}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, ZoomLadder}; +use craft_behavior::{CanvasView, MiddleScroll, ZoomLadder}; use egui::{Context, Id, Pos2, Rect}; /// How far the app's view may differ from the zoom anchor, in document units, before the anchor is dropped. @@ -130,6 +130,10 @@ pub(crate) struct ViewMotion { pub(crate) animation: ZoomAnimation, /// What the tool host or the Navigator asked of the ease since the canvas's last pass. pub(crate) steer: Option, + /// The touchpad's glide after the fingers lift. + pub(crate) glide: TouchpadGlide, + /// The middle button's latched scroll. + pub(crate) middle: MiddleScroll, } impl ViewMotion { diff --git a/crates/ui-canvas/tests/it/canvas/navigate.rs b/crates/ui-canvas/tests/it/canvas/navigate.rs index 3bab71e46..9736a7e6a 100644 --- a/crates/ui-canvas/tests/it/canvas/navigate.rs +++ b/crates/ui-canvas/tests/it/canvas/navigate.rs @@ -2,11 +2,11 @@ use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{Axis, CanvasView, GESTURE_GAP, MotionMode, Wheel, WheelPhase, WheelUnit, ZoomLadder}; +use craft_behavior::{Axis, CanvasView, GESTURE_GAP, MiddleButton, MotionMode, ZoomLadder}; use craft_keymap::{Mods, Platform}; use craft_ui::canvas::{ - Autoscroll, Canvas, CanvasSpace, Guide, GuideKey, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, TouchpadGlide, ViewCommands, - ViewRequest, WheelNavigation, + Autoscroll, Canvas, CanvasSpace, Guide, GuideKey, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, ViewCommands, ViewRequest, + WheelNavigation, WheelScheme, }; use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; @@ -19,25 +19,83 @@ use egui::{Key, Modifiers, Pos2, TouchPhase, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +/// A canvas over a large document with Touchpad Glide set to `touchpad_glide`, whose view starts 60 points short of +/// the document's right edge with the pointer over it: the fixture and the view it shows. +fn glide_rig(touchpad_glide: bool) -> (Fixture, Rc>) { + 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 options = NavigationOptions::default(); + options.touchpad_glide = touchpad_glide; + 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, |_, _| {}); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + let mut near = view.get(); + near.center.x = 4000.0 - f64::from(near.rect.width()) / 2.0 - 60.0; + view.set(near); + fixture.frame(vec![pointer::moved(near.rect.center())]); + (fixture, view) +} + +/// A two-finger swipe that scrolls the view `per_frame` points a frame toward the document's right edge over five +/// frames, and lifts `pause` seconds after the last motion. The content follows the delta, so a leftward delta moves +/// the view right. +fn swipe(fixture: &mut Fixture, per_frame: f32, pause: f64) { + let event = |phase: TouchPhase, dx: f32| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-dx, 0.0), + phase, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, per_frame)]); + for _ in 0..4 { + fixture.frame(vec![event(TouchPhase::Move, per_frame)]); + } + if pause > 0.0 { + fixture.advance(pause); + } + fixture.frame(vec![event(TouchPhase::End, 0.0)]); +} + #[trial] fn a_touchpad_glide_stops_in_the_pass_the_edge_clamp_leaves_the_view_where_it_was() { - const STEP: f64 = 0.016; - let mut glide = TouchpadGlide::new(true); - let mut now = 0.0; - glide.read(&Wheel::new(Vec2::new(30.0, 0.0), Mods::NONE, WheelUnit::Point, WheelPhase::Start), now, true); - for _ in 0..4 { - now += STEP; - glide.read(&Wheel::new(Vec2::new(30.0, 0.0), Mods::NONE, WheelUnit::Point, WheelPhase::Move), now, true); + let (mut fixture, view) = glide_rig(true); + swipe(&mut fixture, 30.0, 0.0); + let lifted = view.get().center.x; + fixture.frame(vec![]); + let mut last = view.get().center.x; + assert!(last > lifted, "a fast lift glides on over later passes: {lifted} -> {last}"); + let mut frames = 0; + loop { + fixture.frame(vec![]); + let x = view.get().center.x; + if x == last { + break; + } + last = x; + frames += 1; + assert!(frames < 120, "the glide ends"); + } + // Slowing alone would take about a hundred frames from this speed; the edge is 60 points away. + assert!(frames < 30, "the edge stopped the glide, not its slowing: {frames} frames"); + // The pass in which the clamp left the view where it was ended the glide: a view moved back from the edge stays. + let mut back = view.get(); + back.center.x -= 100.0; + view.set(back); + fixture.idle(2); + assert_eq!(view.get().center.x, back.center.x, "the glide ended at the edge"); + + for (case, glide, per_frame, pause) in [("a slow lift", true, 1.0, 0.0), ("a lift after a pause", true, 30.0, 0.2), ("Touchpad Glide off", false, 30.0, 0.0)] { + let (mut fixture, view) = glide_rig(glide); + swipe(&mut fixture, per_frame, pause); + let lifted = view.get().center.x; + fixture.idle(3); + assert_eq!(view.get().center.x, lifted, "{case} does not glide"); } - glide.read(&Wheel::new(Vec2::ZERO, Mods::NONE, WheelUnit::Point, WheelPhase::End), now, true); - now += STEP; - assert!(glide.step(now).x > 0.0, "a fast lift glides"); - glide.moved(true); - now += STEP; - assert!(glide.step(now).x > 0.0, "a glide whose view moved goes on"); - glide.moved(false); - now += STEP; - assert_eq!(glide.step(now), Vec2::ZERO, "a pass that left the view where it was ends the glide"); } #[trial] @@ -176,9 +234,9 @@ type NavCase<'a> = (&'a str, NavigationOptions, &'a dyn Fn(Pos2) -> Vec>, Rc>>, Rc>); -/// A canvas over a large document at zoom 1 below a framework number field and an app's own text field, on `os`: the -/// fixture, the view it shows, the number and where the app's field is. -fn wheel_rig(os: Platform) -> WheelRig { +/// A canvas over a large document at zoom 1 under `options` below a framework number field and an app's own text +/// field, on `os`: the fixture, the view it shows, the number and where the app's field is. +fn wheel_rig(os: Platform, options: NavigationOptions) -> WheelRig { let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); let number = Rc::new(Cell::new(Some(10.0))); let app_field = Rc::new(Cell::new(egui::Rect::NOTHING)); @@ -191,7 +249,7 @@ fn wheel_rig(os: Platform) -> WheelRig { field_at.set(ui.add(egui::TextEdit::singleline(&mut text)).rect); 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, |_, _| {}); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |_, _| {}); shown.set(canvas.output.view.unwrap_or(given)); }); fixture.os(os); @@ -201,27 +259,33 @@ fn wheel_rig(os: Platform) -> WheelRig { (fixture, view, number, app_field) } -/// One wheel line of `dy` with `modifiers` over the middle of the canvas. -fn wheel_line(fixture: &mut Fixture, view: &Cell, dy: f32, modifiers: Modifiers) { - let at = view.get().rect.center(); - fixture.frame(vec![pointer::moved(at)]); - fixture.frame(vec![egui::Event::MouseWheel { +/// A mouse wheel's line of `dy` with `modifiers`. +fn line_event(dy: f32, modifiers: Modifiers) -> egui::Event { + egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: Vec2::new(0.0, dy), phase: egui::TouchPhase::Move, modifiers, source: egui::MouseWheelSource::Wheel, - }]); + } +} + +/// One wheel line of `dy` with `modifiers` over the middle of the canvas. +fn wheel_line(fixture: &mut Fixture, view: &Cell, dy: f32, modifiers: Modifiers) { + let at = view.get().rect.center(); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![line_event(dy, modifiers)]); } #[trial] fn a_wheel_line_pans_the_canvas_photoshops_line_and_ctrl_alt_zooms_as_alt_does() { + let line = f64::from(NavigationOptions::default().wheel_line); for os in [Platform::Mac, Platform::Windows, Platform::Linux] { - let (mut fixture, view, _, _) = wheel_rig(os); + let (mut fixture, view, _, _) = wheel_rig(os, NavigationOptions::default()); let before = view.get(); wheel_line(&mut fixture, &view, -1.0, Modifiers::NONE); let panned = view.get(); - assert!((panned.center.y - before.center.y - f64::from(WheelNavigation::LINE)).abs() < 1e-3, "{os:?}: {before:?} -> {panned:?}"); + assert!((panned.center.y - before.center.y - line).abs() < 1e-3, "{os:?}: {before:?} -> {panned:?}"); wheel_line(&mut fixture, &view, 1.0, Modifiers::ALT); let alt = view.get().zoom / panned.zoom; assert!((alt - WheelNavigation::NOTCH).abs() < 1e-3, "{os:?}: Alt + a line zooms a notch: {alt}"); @@ -242,6 +306,190 @@ fn a_wheel_line_pans_the_canvas_photoshops_line_and_ctrl_alt_zooms_as_alt_does() } } +#[trial] +fn the_wheel_line_sets_the_scroll_but_not_the_zoom_per_notch_in_the_acrobat_scheme() { + const LINE: f32 = 40.0; + for scheme in [WheelScheme::Scroll, WheelScheme::Zoom, WheelScheme::Acrobat] { + let mut options = NavigationOptions::default(); + options.wheel = scheme; + options.wheel_line = LINE; + let (mut fixture, view, _, _) = wheel_rig(Platform::Linux, options); + // The modifiers of a scrolling and of a zooming line in the scheme, and the zoom of one line. + let (scroll, zoom, notch) = match scheme { + WheelScheme::Zoom => (Modifiers::ALT, Modifiers::NONE, WheelNavigation::NOTCH), + WheelScheme::Acrobat => (Modifiers::NONE, Modifiers::COMMAND, WheelScheme::ACROBAT_NOTCH), + _ => (Modifiers::NONE, Modifiers::ALT, WheelNavigation::NOTCH), + }; + let before = view.get(); + wheel_line(&mut fixture, &view, -1.0, scroll); + let panned = view.get(); + assert!((panned.center.y - before.center.y - f64::from(LINE)).abs() < 1e-3, "{scheme:?}: a line scrolls the wheel line: {before:?} -> {panned:?}"); + assert_eq!(panned.zoom, before.zoom, "{scheme:?}: a scrolling line does not zoom"); + wheel_line(&mut fixture, &view, 1.0, zoom); + let ratio = view.get().zoom / panned.zoom; + assert!((ratio - notch).abs() < 1e-3, "{scheme:?}: a line zooms one notch whatever the wheel line: {ratio}"); + let pinched = view.get(); + fixture.frame(vec![egui::Event::Zoom(1.2)]); + assert!(view.get().zoom / pinched.zoom > 1.01, "{scheme:?}: a pinch zooms"); + } + + let mut options = NavigationOptions::default(); + options.wheel = WheelScheme::Acrobat; + let (mut fixture, view, _, _) = wheel_rig(Platform::Linux, options); + let before = view.get(); + wheel_line(&mut fixture, &view, -1.0, Modifiers::SHIFT); + let sideways = view.get(); + assert!(sideways.center.x != before.center.x && sideways.center.y == before.center.y, "Shift scrolls sideways: {before:?} -> {sideways:?}"); + wheel_line(&mut fixture, &view, 1.0, Modifiers::ALT); + assert_eq!(view.get().zoom, sideways.zoom, "Alt + wheel is no zoom in the Acrobat scheme"); +} + +type LatchRig = (Fixture, Rc>, Rc>>); + +/// A canvas over a large document whose middle button latches a scroll: the fixture, the view it shows and the +/// canvas's id. +fn latch_rig() -> LatchRig { + let mut options = NavigationOptions::default(); + options.middle_button = MiddleButton::AutoScroll; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let canvas = Rc::new(Cell::new(None)); + let (shown, seen) = (Rc::clone(&view), Rc::clone(&canvas)); + 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, |_, _| {}); + shown.set(canvas.output.view.unwrap_or(given)); + seen.set(Some(canvas.output.response.id)); + }); + fixture.settle(); + (fixture, view, canvas) +} + +/// The middle button going down (`pressed`) or up at `at`, with the pointer there. The testing kit has no +/// middle-button helper. +fn middle(fixture: &mut Fixture, at: Pos2, pressed: bool) { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed, modifiers: Modifiers::NONE }; + fixture.frame(vec![pointer::moved(at), button]); +} + +/// Whether the view moves over five frames with no input. +fn scrolls(fixture: &mut Fixture, view: &Cell) -> bool { + let before = view.get().center; + fixture.idle(5); + view.get().center != before +} + +#[trial] +fn a_latched_middle_scroll_ends_on_escape_a_second_press_or_the_wheel_and_a_held_press_scrolls_until_its_release() { + let (mut fixture, view, canvas) = latch_rig(); + let anchor = view.get().rect.center(); + let below = anchor + Vec2::new(0.0, 80.0); + // A middle click latches the scroll; the pointer resting below the anchor, past the dead zone, scrolls the view. + let latch = |fixture: &mut Fixture| { + middle(fixture, anchor, true); + middle(fixture, anchor, false); + fixture.frame(vec![pointer::moved(below)]); + }; + + latch(&mut fixture); + assert!(fixture.focused_stop().is_some_and(|(id, _)| Some(id) == canvas.get()), "the middle press focuses the canvas, which its Escape claim needs"); + assert!(scrolls(&mut fixture, &view), "a latched scroll moves the view"); + fixture.key(Key::Escape, Modifiers::NONE); + assert!(!scrolls(&mut fixture, &view), "Escape ends the latch"); + + latch(&mut fixture); + assert!(scrolls(&mut fixture, &view), "a click latches again"); + middle(&mut fixture, below, true); + middle(&mut fixture, below, false); + assert!(!scrolls(&mut fixture, &view), "a second press ends the latch"); + + latch(&mut fixture); + assert!(scrolls(&mut fixture, &view), "a click latches again"); + fixture.frame(vec![line_event(-1.0, Modifiers::NONE)]); + assert!(!scrolls(&mut fixture, &view), "the wheel ends the latch"); + + // A held press resting past the dead zone keeps scrolling with no pointer motion; its release ends the latch. + middle(&mut fixture, anchor, true); + fixture.frame(vec![pointer::moved(below)]); + assert!(scrolls(&mut fixture, &view), "a held press resting past the dead zone scrolls with no pointer motion"); + middle(&mut fixture, below, false); + assert!(!scrolls(&mut fixture, &view), "the release of a held press ends the latch"); +} + +/// The seconds of one fixture frame. +const FRAME: f64 = 1.0 / 60.0; + +type EasedRig = (Fixture, Rc>, Rc>); + +/// A canvas over a large document with the eased wheel, whose app reruns the pass of a frame while the flag is set: +/// the fixture, the view it shows and the flag. +fn eased_rig() -> EasedRig { + let mut options = NavigationOptions::default(); + options.eased_wheel = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let rerun = Rc::new(Cell::new(false)); + let (shown, again) = (Rc::clone(&view), Rc::clone(&rerun)); + 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, |_, _| {}); + shown.set(canvas.output.view.unwrap_or(given)); + if again.replace(false) && frame::discardable(ui.ctx()) { + frame::discard_pass(ui.ctx(), "the trial's second pass"); + } + }); + fixture.settle(); + (fixture, view, rerun) +} + +/// One frame of `events`, run as two passes when `twice`. +fn eased_frame(fixture: &mut Fixture, rerun: &Cell, twice: bool, events: Vec) { + rerun.set(twice); + fixture.frame(events); + assert!(!twice || fixture.passes() >= 2, "the frame ran a second pass"); +} + +/// How far down the document the view travels from one wheel line through the `frames` frames of `step` seconds +/// after it, each frame run as two passes when `twice`; and whether the first frame after the line still moved it. +fn eased_travel(step: f64, frames: usize, twice: bool) -> (f64, bool) { + let (mut fixture, view, rerun) = eased_rig(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let start = view.get().center.y; + eased_frame(&mut fixture, &rerun, twice, vec![line_event(-1.0, Modifiers::NONE)]); + let notched = view.get().center.y; + let mut moved_after = None; + for _ in 0..frames { + if step > FRAME { + fixture.advance(step - FRAME); + } + eased_frame(&mut fixture, &rerun, twice, vec![]); + moved_after.get_or_insert(view.get().center.y != notched); + } + (view.get().center.y - start, moved_after.unwrap_or(false)) +} + +#[trial] +fn an_eased_wheel_pays_the_same_distance_at_any_frame_rate_keeps_paying_after_the_notch_and_stops_on_a_key_move() { + // A tenth of a second after the notch: six frames at 60 Hz, two at 20 Hz. + let (fast, moved_after) = eased_travel(FRAME, 6, false); + let (slow, _) = eased_travel(0.05, 2, false); + let (rerun, _) = eased_travel(FRAME, 6, true); + assert!(fast > 0.0, "the line moves the view: {fast}"); + assert!(moved_after, "the view still moves on a pass after the notch"); + assert!((fast - slow).abs() < 0.5, "the same distance at 60 Hz and at 20 Hz: {fast} and {slow}"); + assert!((fast - rerun).abs() < 0.5, "a frame's second pass pays nothing more: {fast} and {rerun}"); + + let (mut fixture, view, _) = eased_rig(); + let canvas = fixture.by_role(Role::CANVAS)[0]; + fixture.click(&canvas); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + fixture.frame(vec![line_event(-1.0, Modifiers::NONE)]); + fixture.key(Key::PageDown, Modifiers::NONE); + let paged = view.get().center; + fixture.idle(5); + assert_eq!(view.get().center, paged, "a key move ends the owed motion"); +} + #[trial] fn a_held_alt_key_is_in_the_wheels_modifiers_when_the_wheel_events_miss_it() { // Windows can report a held Alt in its key events and not in the wheel's modifier state. @@ -252,7 +500,7 @@ fn a_held_alt_key_is_in_the_wheels_modifiers_when_the_wheel_events_miss_it() { repeat, modifiers: Modifiers::NONE, }; - let (mut fixture, view, _, _) = wheel_rig(Platform::Windows); + let (mut fixture, view, _, _) = wheel_rig(Platform::Windows, NavigationOptions::default()); fixture.frame(vec![alt_key(true, false)]); let before = view.get(); wheel_line(&mut fixture, &view, 1.0, Modifiers::NONE); @@ -271,7 +519,7 @@ fn a_held_alt_key_is_in_the_wheels_modifiers_when_the_wheel_events_miss_it() { #[trial] fn a_focused_field_takes_the_plain_wheel_over_the_canvas_and_leaves_it_the_view_keys() { - let (mut fixture, view, number, _) = wheel_rig(Platform::Linux); + let (mut fixture, view, number, _) = wheel_rig(Platform::Linux, NavigationOptions::default()); let field = fixture.by_label("Smoothing").expect("the number field"); fixture.click(&field); let before = view.get(); @@ -285,7 +533,7 @@ fn a_focused_field_takes_the_plain_wheel_over_the_canvas_and_leaves_it_the_view_ assert!(view.get().center.x != zoomed.center.x, "Cmd/Ctrl + wheel still scrolls the view sideways"); assert_eq!(number.get(), Some(11.0), "the view's wheel does not step the field"); - let (mut fixture, view, _, app_field) = wheel_rig(Platform::Linux); + let (mut fixture, view, _, app_field) = wheel_rig(Platform::Linux, NavigationOptions::default()); fixture.click_at(app_field.get().center()); let before = view.get(); wheel_line(&mut fixture, &view, 1.0, Modifiers::NONE); @@ -296,7 +544,7 @@ fn a_focused_field_takes_the_plain_wheel_over_the_canvas_and_leaves_it_the_view_ #[trial] fn the_view_commands_a_canvas_runs_are_in_the_frame_output_whatever_fired_them() { - let (mut fixture, view, _, _) = wheel_rig(Platform::Linux); + let (mut fixture, view, _, _) = wheel_rig(Platform::Linux, NavigationOptions::default()); let canvas = fixture.by_role(Role::CANVAS)[0]; fixture.click(&canvas); frame::take_output(fixture.ctx()); diff --git a/crates/ui-canvas/tests/it/full_window_parts.rs b/crates/ui-canvas/tests/it/full_window_parts.rs index a803f723d..edd40467f 100644 --- a/crates/ui-canvas/tests/it/full_window_parts.rs +++ b/crates/ui-canvas/tests/it/full_window_parts.rs @@ -42,7 +42,7 @@ fn a_zoom_command_ends_the_fit_and_fit_returns_to_it() { mod canvas_navigation { use craft_behavior::PixelSize; use craft_behavior::kurbo::Point; - use craft_ui::canvas::{NavigationOptions, PixelRect, RasterSource}; + use craft_ui::canvas::{NavigationOptions, PixelRect, RasterSource, WheelScheme}; use craft_ui::contract::Bind; use craft_ui::dialog::{FullWindowCanvas, FullWindowView}; use craft_ui::primitives::Revision; @@ -112,7 +112,7 @@ mod canvas_navigation { assert_eq!(plain.zoom(), fitted, "the plain wheel does not zoom by default"); let mut navigation = NavigationOptions::default(); - navigation.zoom_with_wheel = true; + navigation.wheel = WheelScheme::Zoom; navigation.animated_zoom = false; // Overscroll on: the fit leaves room around the image, and with Overscroll off an image still smaller than the // canvas after one notch is centred again, whatever the pointer. diff --git a/migration/api-map/canvas-core.toml b/migration/api-map/canvas-core.toml index 5529bc472..156716908 100644 --- a/migration/api-map/canvas-core.toml +++ b/migration/api-map/canvas-core.toml @@ -592,7 +592,7 @@ name = "SplitViewsOutput" old = "" new = "craft_ui::canvas::SplitViewsOutput" status = "replaced" -note = "Replaces `SplitResponse`; `edit` carries the divider edits and the response." +note = "Replaces `SplitResponse`; `edit` carries the divider edits and the response. `tab_drop: Option>` reports a document tab dropped on a pane (`TabDropTarget` says where); `SplitViews::takes_tabs(accepts)` makes the panes take tab drops." [[type]] name = "SplitAt" @@ -905,7 +905,7 @@ name = "NavigationOptions" old = "craft_ui::canvas::navigate::NavigationOptions" new = "craft_ui::canvas::NavigationOptions" status = "moved" -note = "Plain data, `#[non_exhaustive]`: build it with `NavigationOptions::default()` and assign the fields. The fields and their defaults are unchanged." +note = "Plain data, `#[non_exhaustive]`, `PartialEq` but not `Eq`: build it with `NavigationOptions::default()` and assign the fields. `zoom_with_wheel: bool` is gone: `wheel: WheelScheme` (`Scroll` by default; `Zoom` is the old `zoom_with_wheel = true`; `Acrobat`). New fields: `wheel_line` (16 points a wheel line, which replaces `WheelNavigation::LINE`), `key_line` (`PageKey::SMALL_STEP`), `eased_wheel` (off), `touchpad_glide` (off; the canvas runs the glide), `middle_button` (`craft_behavior::MiddleButton`, `Pan`) and `invert_middle` (off). The other fields and their defaults are unchanged." [[type]] name = "WheelNavigation" @@ -945,9 +945,16 @@ note = "A value the Hand tool or the app keeps: `drag(now, delta)`, `release(now [[type]] name = "TouchpadGlide" old = "craft_ui::canvas::navigate::TouchpadGlide" -new = "craft_ui::canvas::TouchpadGlide" -status = "moved" -note = "`TouchpadGlide::new(enabled)` (the app decides the platform) and `read(&Wheel, now, glide)`; it reads the wheel share, not egui events. `default()` is gone." +new = "" +status = "removed" +note = "The canvas runs the touchpad glide itself under `NavigationOptions::touchpad_glide` (the app turns it on where the platform sends no momentum); the type is internal." + +[[type]] +name = "WheelScheme" +old = "" +new = "craft_ui::canvas::WheelScheme" +status = "replaced" +note = "What a plain and a modified wheel do over a canvas (`NavigationOptions::wheel`): `Scroll` (Alt zooms), `Zoom` (the old `zoom_with_wheel = true`: the wheel zooms, Alt scrolls) or `Acrobat` (Cmd/Ctrl zooms by `WheelScheme::ACROBAT_NOTCH` a line, Shift scrolls sideways)." [[type]] name = "Autoscroll" @@ -1284,12 +1291,12 @@ name = "frame_step" old = "" new = "craft_ui::canvas::frame_step" status = "replaced" -note = "`frame_step(dt: f64) -> f64`: the one step Hand glides, held Zoom presses and autoscroll integrate over, capped at `FRAME_STEP_MAX` (0.1 s). Replaces `FlickPan`'s, `Autoscroll::MAX_DT` and `HoldZoom::MAX_DT`, which never shipped." +note = "`frame_step(dt: f64) -> f64`: the one step Hand glides, held Zoom presses, autoscroll and the middle button's latched scroll integrate over, capped at `FRAME_STEP_MAX` (0.1 s). It lives in `craft_behavior` (`craft_behavior::frame_step`) and `craft_ui::canvas` re-exports it. Replaces `FlickPan`'s, `Autoscroll::MAX_DT` and `HoldZoom::MAX_DT`, which never shipped." [[type]] name = "FRAME_STEP_MAX" old = "" new = "craft_ui::canvas::FRAME_STEP_MAX" status = "replaced" -note = "The longest frame step of canvas motion, in seconds." +note = "The longest frame step of canvas motion, in seconds. It lives in `craft_behavior` (`craft_behavior::FRAME_STEP_MAX`) and `craft_ui::canvas` re-exports it." # End of l4z-canvas.