diff --git a/crates/ui-egui/src/canvas/autoscroll.rs b/crates/ui-egui/src/canvas/autoscroll.rs deleted file mode 100644 index 5a04d1c193..0000000000 --- a/crates/ui-egui/src/canvas/autoscroll.rs +++ /dev/null @@ -1,598 +0,0 @@ -//! Middle-button scrolling for the document viewport: Linux latches auto-scroll, other -//! platforms pan while the button is held. Either way the page tools never see the button, -//! because egui's drag responses accept every pointer button. Also the edge scrolling of a -//! text-selection drag. - -use egui::{Context, CursorIcon, Event, Key, PointerButton, Pos2, Stroke, Vec2, vec2}; - -const DEAD_ZONE: f32 = 15.0; -// Chromium's autoscroll_controller.cc uses distance^2.2 * 0.000008; its -// ui/events/gestures/fixed_velocity_curve.cc multiplies elapsed seconds by 5000. -const SPEED_EXPONENT: f32 = 2.2; -const SPEED_MULTIPLIER: f32 = 0.04; -// Bound hostile coordinates before exponentiation, far beyond ordinary screen distances. -const MAX_DISPLACEMENT: f32 = 1_000_000.0; - -#[derive(Default)] -pub(crate) struct AutoScroll { - anchor: Option, - organize: bool, - /// Consecutive or total frames spent past [`DEAD_ZONE`] while the initiating middle press - /// remained held (`>= 2` distinguishes a held scroll from a quick click). - held_frames_past_dead_zone: u8, - /// Own a cancelling click through its release, so it cannot also edit page content. - cancel_button: Option, - block_input: bool, - /// Where the pointer was last frame during a held middle-button pan (not Linux). - drag: Option, -} - -impl AutoScroll { - pub(crate) fn active(&self) -> bool { - self.anchor.is_some() - } - - /// Whether a held middle-button pan is under way (platforms without auto-scroll). - pub(crate) fn panning(&self) -> bool { - self.drag.is_some() - } - - pub(crate) fn cancel(&mut self) { - self.anchor = None; - self.held_frames_past_dead_zone = 0; - self.drag = None; - self.cancel_button = None; - self.block_input = false; - } - - pub(crate) fn blocks_input(&self) -> bool { - self.block_input - } - - /// Run before the document's widgets. Starting is restricted to the unobstructed viewport; - /// once started, moving outside that viewport still controls the speed. `invert` is - /// Preferences ▸ Invert middle-button drag: the returned delta scrolls the other way. - pub(crate) fn update(&mut self, ui: &egui::Ui, viewport: egui::Rect, organize: bool, invert: bool) -> Vec2 { - self.update_for_platform(ui, viewport, organize, cfg!(target_os = "linux"), invert) - } - - fn update_for_platform(&mut self, ui: &egui::Ui, viewport: egui::Rect, organize: bool, supported: bool, invert: bool) -> Vec2 { - let delta = if supported { self.update_latched(ui, viewport, organize) } else { self.update_drag(ui, viewport) }; - oriented(delta, invert) - } - - fn update_latched(&mut self, ui: &egui::Ui, viewport: egui::Rect, organize: bool) -> Vec2 { - let ctx = ui.ctx(); - let (pointer, middle_press, middle_down, middle_released, has_release_event, cancel, cancel_button, dt) = ctx.input(|i| { - let cancel_button = [PointerButton::Primary, PointerButton::Secondary, PointerButton::Extra1, PointerButton::Extra2] - .into_iter() - .find(|button| i.pointer.button_pressed(*button)); - ( - i.pointer.hover_pos(), - // Read the press event itself: later movement in this frame must not move the anchor. - i.events.iter().find_map(|event| match event { - Event::PointerButton { pos, button: PointerButton::Middle, pressed: true, .. } if pos.is_finite() => Some(*pos), - _ => None, - }), - i.pointer.button_down(PointerButton::Middle), - i.pointer.button_released(PointerButton::Middle), - i.events.iter().any(|e| matches!(e, Event::PointerButton { button: PointerButton::Middle, pressed: false, .. })), - !i.focused - || i.key_pressed(Key::Escape) - || cancel_button.is_some() - || i.events.iter().any(|e| matches!(e, Event::MouseWheel { .. } | Event::Zoom(_))), - cancel_button, - i.stable_dt, - ) - }); - self.block_input = - self.active() || self.cancel_button.is_some() || middle_press.is_some() || middle_down || middle_released || has_release_event; - if let Some(button) = self.cancel_button { - if !ctx.input(|i| i.pointer.button_down(button)) { - self.cancel_button = None; - } - return Vec2::ZERO; - } - if self.active() && (cancel || pointer.is_none() || self.organize != organize || ctx.egui_wants_keyboard_input()) { - self.cancel(); - self.block_input = true; - self.cancel_button = cancel_button; - return Vec2::ZERO; - } - if let Some(pressed_at) = middle_press { - if self.active() { - self.cancel(); - self.block_input = true; - self.cancel_button = Some(PointerButton::Middle); - return Vec2::ZERO; - } else if !cancel - && !ctx.egui_wants_keyboard_input() - && viewport.intersect(ui.clip_rect()).contains(pressed_at) - && ctx.layer_id_at(pressed_at) == Some(ui.layer_id()) - { - self.anchor = Some(pressed_at); - self.organize = organize; - self.held_frames_past_dead_zone = 0; - } - } - let (Some(anchor), Some(pointer)) = (self.anchor, pointer) else { return Vec2::ZERO }; - let displacement = pointer.y - anchor.y; - let past_dead_zone = displacement.is_finite() && displacement.abs() > DEAD_ZONE; - if middle_down && !has_release_event && past_dead_zone { - self.held_frames_past_dead_zone = self.held_frames_past_dead_zone.saturating_add(1); - } - if (middle_released || has_release_event) && self.held_frames_past_dead_zone >= 2 { - self.cancel(); - self.block_input = true; - return Vec2::ZERO; - } - // Cap the elapsed time too: returning from an idle/hidden window must never jump pages. - let delta = scroll_delta(displacement, dt); - if past_dead_zone { - // Continuous redraws let stable_dt use measured frame time. Delayed redraws - // instead use predicted_dt, which can make speed depend on the actual frame rate. - ctx.request_repaint(); - } - vec2(0.0, delta) - } - - /// Without auto-scroll, a middle-button drag pans the view 1:1, like the Hand tool. Input is - /// blocked from the press through the release, so the drag cannot also draw, select or move. - fn update_drag(&mut self, ui: &egui::Ui, viewport: egui::Rect) -> Vec2 { - self.anchor = None; - self.held_frames_past_dead_zone = 0; - self.cancel_button = None; - let ctx = ui.ctx(); - let (pointer, middle_press, middle_down, middle_released, focused) = ctx.input(|i| { - ( - i.pointer.latest_pos().filter(|p| p.is_finite()), - // Read the press event itself: later movement in this frame is part of the pan. - i.events.iter().find_map(|event| match event { - Event::PointerButton { pos, button: PointerButton::Middle, pressed: true, .. } if pos.is_finite() => Some(*pos), - _ => None, - }), - i.pointer.button_down(PointerButton::Middle), - i.pointer.button_released(PointerButton::Middle), - i.focused, - ) - }); - self.block_input = self.drag.is_some() || middle_press.is_some() || middle_down || middle_released; - if !focused { - self.drag = None; - return Vec2::ZERO; - } - if let Some(pressed_at) = middle_press - && self.drag.is_none() - && !ctx.egui_wants_keyboard_input() - && viewport.intersect(ui.clip_rect()).contains(pressed_at) - && ctx.layer_id_at(pressed_at) == Some(ui.layer_id()) - { - self.drag = Some(pressed_at); - } - let (Some(last), Some(pointer)) = (self.drag, pointer) else { return Vec2::ZERO }; - self.drag = middle_down.then_some(pointer); - // egui's delta moves the content, so the page follows the pointer. - let delta = pointer - last; - if delta.is_finite() { delta } else { Vec2::ZERO } - } - - /// Draw an original geometric marker at the activation point, above page content. - pub(crate) fn paint(&self, ui: &egui::Ui, viewport: egui::Rect) { - if self.drag.is_some() { - ui.ctx().set_cursor_icon(CursorIcon::Grabbing); - return; - } - let Some(anchor) = self.anchor else { return }; - let painter = ui.painter().with_clip_rect(viewport); - let ink = ui.visuals().text_color(); - painter.circle(anchor, 13.0, ui.visuals().window_fill(), Stroke::new(1.0, ink)); - painter.circle_filled(anchor, 2.0, ink); - for direction in [-1.0, 1.0] { - painter.add(egui::Shape::convex_polygon( - vec![anchor + vec2(-4.0, direction * 6.0), anchor + vec2(4.0, direction * 6.0), anchor + vec2(0.0, direction * 10.0)], - ink, - Stroke::NONE, - )); - } - ui.ctx().set_cursor_icon(CursorIcon::ResizeVertical); - } - - /// Escape belongs to autoscroll first, leaving selection/find/full-screen intact. - pub(crate) fn escape(&mut self, ctx: &Context) -> bool { - if self.active() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { - self.cancel(); - true - } else { - false - } - } -} - -/// Width of the band along each edge of the viewport where a drawing in progress scrolls the view. -const EDGE_BAND: f32 = 32.0; -/// Scroll speed at the inner edge of the band, in points per second. It grows with the square of -/// how far into the band (or past the edge) the pointer is, up to 1.5 bands deep. -const DRAW_EDGE_SPEED: f32 = 700.0; - -/// How far to scroll the content this frame while a drawing is in progress and the pointer is in -/// the band along an edge of `viewport` (or just past it): up, down, left and right. Positive -/// moves the content down or right, like [`AutoScroll::update`]. The pointer must be within the -/// viewport grown by one band, so a pointer over a neighbouring panel never scrolls the page. -pub(crate) fn edge_scroll(pointer: Option, viewport: egui::Rect, dt: f32) -> Vec2 { - let Some(p) = pointer.filter(|p| p.is_finite()) else { return Vec2::ZERO }; - if !dt.is_finite() || !viewport.is_positive() || !viewport.expand(EDGE_BAND).contains(p) { - return Vec2::ZERO; - } - let dt = dt.clamp(0.0, 0.05); - let axis = |p: f32, lo: f32, hi: f32| { - // A viewport narrower than two bands would scroll both ways at once: scroll neither. - if hi - lo < 2.0 * EDGE_BAND { - return 0.0; - } - let depth = |d: f32| (d / EDGE_BAND).clamp(0.0, 1.5); - let (before, after) = (depth(lo + EDGE_BAND - p), depth(p - (hi - EDGE_BAND))); - (before * before - after * after) * DRAW_EDGE_SPEED * dt - }; - vec2(axis(p.x, viewport.left(), viewport.right()), axis(p.y, viewport.top(), viewport.bottom())) -} - -/// Within this distance of the viewport's top or bottom edge, a text-selection drag scrolls. -const EDGE: f32 = 30.0; -/// Points per second for each point the pointer is into the edge band or past the viewport. -const EDGE_SPEED: f32 = 20.0; - -/// How far a selection drag scrolls this frame with the pointer at `y`, near or past the top or -/// bottom of `viewport` (#1670); faster the farther it goes. egui's delta moves the content. -pub(crate) fn edge_delta(y: f32, viewport: egui::Rect, dt: f32) -> f32 { - if !y.is_finite() || !dt.is_finite() || viewport.height() < 4.0 * EDGE { - return 0.0; - } - let distance = if y > viewport.bottom() - EDGE { - y - (viewport.bottom() - EDGE) - } else if y < viewport.top() + EDGE { - y - (viewport.top() + EDGE) - } else { - return 0.0; - }; - -distance.clamp(-MAX_DISPLACEMENT, MAX_DISPLACEMENT) * EDGE_SPEED * dt.clamp(0.0, 0.05) -} - -/// The middle button's delta, reversed when the user inverted it. -fn oriented(delta: Vec2, invert: bool) -> Vec2 { - if invert { -delta } else { delta } -} - -fn scroll_delta(displacement: f32, dt: f32) -> f32 { - if !displacement.is_finite() || !dt.is_finite() { - return 0.0; - } - let distance = displacement.abs(); - if distance <= DEAD_ZONE { - return 0.0; - } - // Chromium uses the full distance outside the dead zone, without subtracting its radius. - let speed = distance.min(MAX_DISPLACEMENT).powf(SPEED_EXPONENT) * SPEED_MULTIPLIER; - // egui's delta moves content, the opposite of the scroll offset. - -displacement.signum() * speed * dt.clamp(0.0, 0.05) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn middle(pos: Pos2, pressed: bool) -> Event { - Event::PointerButton { pos, button: PointerButton::Middle, pressed, modifiers: egui::Modifiers::NONE } - } - - /// Run one frame of the non-Linux path; `check` sees the pan delta inside the frame. - fn drag_frame(ctx: &Context, scroll: &mut AutoScroll, events: Vec, focused: bool, check: impl Fn(&AutoScroll, Vec2)) { - frame(ctx, scroll, events, focused, (false, false), check); - } - - /// Run one frame; `mode` is (latched auto-scroll supported, inverted). - fn frame(ctx: &Context, scroll: &mut AutoScroll, events: Vec, focused: bool, mode: (bool, bool), check: impl Fn(&AutoScroll, Vec2)) { - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0))), events, focused, ..Default::default() }, - |ui| { - let delta = scroll.update_for_platform(ui, ui.max_rect(), false, mode.0, mode.1); - check(scroll, delta); - }, - ); - // This input-only test has no renderer to apply the generated font texture. - output.textures_delta.clear(); - } - - /// The pan delta after pressing at `p` and moving the pointer by `by`. - fn pan_by(by: Vec2, invert: bool) -> Vec2 { - let (ctx, mut scroll, p) = (Context::default(), AutoScroll::default(), egui::pos2(100.0, 100.0)); - frame(&ctx, &mut scroll, vec![], true, (false, invert), |_, _| {}); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, (false, invert), |_, _| {}); - let moved = std::cell::Cell::new(Vec2::ZERO); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p + by)], true, (false, invert), |_, d| moved.set(d)); - moved.get() - } - - /// The auto-scroll delta in the frame after latching at `p`, with the pointer `dy` below it. - fn latched_by(dy: f32, invert: bool) -> Vec2 { - let (ctx, mut scroll, p) = (Context::default(), AutoScroll::default(), egui::pos2(100.0, 100.0)); - frame(&ctx, &mut scroll, vec![], true, (true, invert), |_, _| {}); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true), middle(p, false)], true, (true, invert), |_, _| {}); - let moved = std::cell::Cell::new(Vec2::ZERO); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p + vec2(0.0, dy))], true, (true, invert), |s, d| { - assert!(s.active(), "the click latched auto-scroll"); - moved.set(d); - }); - moved.get() - } - - #[test] - fn inverting_the_middle_button_reverses_the_pan_and_the_auto_scroll() { - let by = vec2(-30.0, 40.0); - assert_eq!(pan_by(by, false), by, "by default the page follows the pointer"); - assert_eq!(pan_by(by, true), -by, "inverted, the view moves the way the pointer goes"); - let (normal, inverted) = (latched_by(60.0, false), latched_by(60.0, true)); - assert!(normal.y < 0.0, "by default, below the anchor scrolls down: {normal:?}"); - assert_eq!(inverted, -normal, "inverted, the same distance scrolls the other way"); - assert_eq!(latched_by(10.0, true), Vec2::ZERO, "the dead zone still holds still"); - } - - #[test] - fn holding_middle_button_to_auto_scroll_turns_off_on_release() { - let ctx = Context::default(); - let mut scroll = AutoScroll::default(); - let p = egui::pos2(100.0, 100.0); - let far = p + vec2(0.0, 60.0); - frame(&ctx, &mut scroll, vec![], true, (true, false), |_, _| {}); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, (true, false), |s, d| { - assert!(s.active() && s.blocks_input()); - assert_eq!(d, Vec2::ZERO); - }); - for _ in 0..2 { - frame(&ctx, &mut scroll, vec![Event::PointerMoved(far)], true, (true, false), |s, d| { - assert!(s.active() && s.blocks_input()); - assert!(d.y < 0.0, "holding and moving past the dead zone scrolls: {d:?}"); - }); - } - // Primary case: releasing while still past the dead zone stops auto-scroll immediately. - frame(&ctx, &mut scroll, vec![middle(far, false)], true, (true, false), |s, d| { - assert!(!s.active(), "releasing at +60pt after holding must turn auto-scroll off"); - assert!(s.blocks_input(), "the release frame itself still blocks page tools"); - assert_eq!(d, Vec2::ZERO); - }); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(far)], true, (true, false), |s, d| { - assert!(!s.active() && !s.blocks_input()); - assert_eq!(d, Vec2::ZERO); - }); - - // Returning inside the dead zone before releasing still counts as a held scroll gesture. - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, (true, false), |s, _| assert!(s.active())); - for _ in 0..2 { - frame(&ctx, &mut scroll, vec![Event::PointerMoved(far)], true, (true, false), |s, d| assert!(s.active() && d.y < 0.0)); - } - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p + vec2(0.0, 5.0)), middle(p + vec2(0.0, 5.0), false)], true, (true, false), |s, d| { - assert!(!s.active(), "releasing after scrolling while held must turn auto-scroll off"); - assert!(s.blocks_input()); - assert_eq!(d, Vec2::ZERO); - }); - } - - #[test] - fn middle_click_released_within_dead_zone_stays_latched() { - let ctx = Context::default(); - let mut scroll = AutoScroll::default(); - let p = egui::pos2(100.0, 100.0); - let far = p + vec2(0.0, 60.0); - frame(&ctx, &mut scroll, vec![], true, (true, false), |_, _| {}); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, (true, false), |s, _| assert!(s.active())); - frame( - &ctx, - &mut scroll, - vec![Event::PointerMoved(p + vec2(0.0, DEAD_ZONE)), middle(p + vec2(0.0, DEAD_ZONE), false)], - true, - (true, false), - |s, d| { - assert!(s.active(), "releasing within the dead zone keeps auto-scroll latched"); - assert_eq!(d, Vec2::ZERO); - }, - ); - frame(&ctx, &mut scroll, vec![Event::PointerMoved(far)], true, (true, false), |s, d| { - assert!(s.active()); - assert!(d.y < 0.0); - }); - scroll.cancel(); - - // Pointer movement after middle-button release in the same frame does not count as held movement. - frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, (true, false), |s, _| assert!(s.active())); - frame(&ctx, &mut scroll, vec![middle(p, false), Event::PointerMoved(far)], true, (true, false), |s, d| { - assert!(s.active(), "movement after release in the same frame keeps auto-scroll latched"); - assert!(d.y < 0.0); - }); - scroll.cancel(); - - // A press, move, and release arriving in a single frame is a click at the initial press position, - // and stays latched across subsequent frames when egui delivers its deferred button_released state - // or runs multiple layout passes within the activation frame. - frame( - &ctx, - &mut scroll, - vec![Event::PointerMoved(p), middle(p, true), Event::PointerMoved(far), middle(far, false)], - true, - (true, false), - |s, d| { - assert!(s.active(), "single-frame click and move latches auto-scroll"); - assert!(d.y < 0.0); - }, - ); - frame(&ctx, &mut scroll, vec![], true, (true, false), |s, d| { - assert!(s.active(), "deferred button_released in the next frame must keep auto-scroll latched"); - assert!(d.y < 0.0); - }); - frame(&ctx, &mut scroll, vec![], true, (true, false), |s, d| { - assert!(s.active(), "subsequent frames after deferred release must keep auto-scroll latched"); - assert!(d.y < 0.0); - }); - } - - #[test] - fn middle_drag_pans_one_to_one_and_owns_the_button_until_release() { - let ctx = Context::default(); - let mut scroll = AutoScroll::default(); - let p = egui::pos2(100.0, 100.0); - // The first frame lays out the layer that later presses are tested against. - drag_frame(&ctx, &mut scroll, vec![], true, |_, _| {}); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, |s, d| { - assert_eq!(d, Vec2::ZERO); - assert!(s.panning() && s.blocks_input(), "the press itself must not reach the page tools"); - assert!(!s.active(), "no auto-scroll latch outside Linux"); - }); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p + vec2(-30.0, 40.0))], true, |s, d| { - assert_eq!(d, vec2(-30.0, 40.0), "the page follows the pointer on both axes"); - assert!(s.blocks_input()); - }); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p + vec2(-30.0, 50.0)), middle(p + vec2(-30.0, 50.0), false)], true, |s, d| { - assert_eq!(d, vec2(0.0, 10.0), "movement in the release frame still counts"); - assert!(!s.panning()); - assert!(s.blocks_input(), "the release must not finish a drawing drag"); - }); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p)], true, |s, d| { - assert_eq!(d, Vec2::ZERO, "nothing moves once the button is up"); - assert!(!s.blocks_input()); - }); - } - - #[test] - fn middle_drag_ignores_presses_outside_the_viewport_and_stops_when_focus_is_lost() { - let ctx = Context::default(); - let mut scroll = AutoScroll::default(); - let outside = egui::pos2(500.0, 100.0); - drag_frame(&ctx, &mut scroll, vec![], true, |_, _| {}); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(outside), middle(outside, true)], true, |s, _| assert!(!s.panning())); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(outside + vec2(0.0, 50.0))], true, |_, d| assert_eq!(d, Vec2::ZERO)); - drag_frame(&ctx, &mut scroll, vec![middle(outside, false)], true, |_, _| {}); - - let p = egui::pos2(100.0, 100.0); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true)], true, |s, _| assert!(s.panning())); - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p + vec2(0.0, 50.0))], false, |s, d| { - assert_eq!(d, Vec2::ZERO); - assert!(!s.panning(), "losing focus ends the pan"); - }); - } - - #[test] - fn middle_drag_leaves_escape_to_the_existing_shortcuts() { - let ctx = Context::default(); - let mut scroll = AutoScroll::default(); - let p = egui::pos2(100.0, 100.0); - drag_frame(&ctx, &mut scroll, vec![], true, |_, _| {}); - let escape = Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - drag_frame(&ctx, &mut scroll, vec![Event::PointerMoved(p), middle(p, true), escape], true, |s, _| { - assert!(s.panning()); - assert!(ctx.input(|i| i.key_pressed(Key::Escape)), "Escape must remain available to the existing shortcuts"); - }); - assert!(!scroll.escape(&ctx)); - } - - #[test] - fn edge_delta_scrolls_toward_the_edge_the_pointer_is_at() { - let viewport = egui::Rect::from_min_max(egui::pos2(0.0, 100.0), egui::pos2(400.0, 500.0)); - assert_eq!(edge_delta(300.0, viewport, 0.016), 0.0, "nothing away from the edges"); - assert!(edge_delta(495.0, viewport, 0.016) < 0.0, "the bottom edge moves the content up"); - assert!(edge_delta(105.0, viewport, 0.016) > 0.0, "the top edge moves it down"); - assert!(edge_delta(600.0, viewport, 0.016) < edge_delta(495.0, viewport, 0.016), "faster past the viewport"); - for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert_eq!(edge_delta(invalid, viewport, 0.016), 0.0); - assert_eq!(edge_delta(495.0, viewport, invalid), 0.0); - } - assert!(edge_delta(f32::MAX, viewport, 0.016).is_finite()); - } - - #[test] - fn chromium_curve_is_gentle_near_the_anchor_and_accelerates_farther_away() { - // Reference speeds in screen points/second from Chromium's distance exponent (2.2), - // controller multiplier (0.000008), and fixed-velocity animation multiplier (5000). - for (distance, expected_speed) in [(25.0, 48.0), (50.0, 219.0), (100.0, 1005.0), (200.0, 4617.0)] { - let speed = -scroll_delta(distance, 0.01) / 0.01; - assert!((speed - expected_speed).abs() < 1.0, "distance={distance}, speed={speed}, expected={expected_speed}"); - } - for distance in [-15.0, 0.0, 15.0] { - assert_eq!(scroll_delta(distance, 0.01), 0.0); - } - assert!(scroll_delta(15.1, 0.01) < 0.0); - } - - #[test] - fn fractional_motion_covers_the_same_distance_at_different_frame_rates() { - for distance in [16.0, 50.0, 200.0] { - let expected = scroll_delta(distance, 0.01) * 100.0; - for frames in [30, 60, 120, 144] { - let delta = scroll_delta(distance, 1.0 / frames as f32); - let travelled: f32 = (0..frames).map(|_| delta).sum(); - assert!((travelled - expected).abs() < expected.abs() * 0.00001); - } - } - assert!(scroll_delta(16.0, 1.0 / 144.0).abs() < 1.0); - } - - #[test] - fn speed_has_a_dead_zone_is_symmetric_and_rejects_invalid_input() { - for y in [-15.0, -1.0, 0.0, 1.0, 15.0] { - assert_eq!(scroll_delta(y, 0.016), 0.0); - } - assert!(scroll_delta(30.0, 0.016) < 0.0); - for (near, far) in [(16.0, 30.0), (30.0, 100.0), (100.0, 200.0)] { - assert!(scroll_delta(far, 0.016).abs() > scroll_delta(near, 0.016).abs()); - } - assert_eq!(scroll_delta(30.0, 0.016), -scroll_delta(-30.0, 0.016)); - assert!(scroll_delta(200.0, 0.01).abs() / 0.01 > 3200.0, "ordinary distances have no linear-curve speed ceiling"); - assert_eq!(scroll_delta(1000.0, 10.0), scroll_delta(1000.0, 0.05)); - assert_eq!(scroll_delta(1000.0, -1.0), 0.0); - assert_eq!(scroll_delta(f32::MAX, 0.016), scroll_delta(MAX_DISPLACEMENT, 0.016)); - assert!(scroll_delta(f32::MAX, 0.016).is_finite()); - assert_eq!(scroll_delta(-f32::MAX, 0.016), -scroll_delta(f32::MAX, 0.016)); - for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert_eq!(scroll_delta(invalid, 0.016), 0.0); - assert_eq!(scroll_delta(1000.0, invalid), 0.0); - } - } -} - -#[cfg(test)] -mod edge_tests { - use super::*; - - fn view() -> egui::Rect { - egui::Rect::from_min_max(egui::pos2(100.0, 50.0), egui::pos2(900.0, 650.0)) - } - - #[test] - fn scrolls_toward_each_of_the_four_edges() { - let dt = 1.0 / 60.0; - // Near the top or left edge the content moves down or right (positive), and the reverse - // near the bottom or right edge. - assert!(edge_scroll(Some(egui::pos2(500.0, 55.0)), view(), dt).y > 0.0); - assert!(edge_scroll(Some(egui::pos2(500.0, 645.0)), view(), dt).y < 0.0); - assert!(edge_scroll(Some(egui::pos2(105.0, 300.0)), view(), dt).x > 0.0); - assert!(edge_scroll(Some(egui::pos2(895.0, 300.0)), view(), dt).x < 0.0); - // Only the axis whose edge is near moves. - assert_eq!(edge_scroll(Some(egui::pos2(500.0, 55.0)), view(), dt).x, 0.0); - } - - #[test] - fn the_middle_and_far_away_pointers_do_not_scroll() { - let dt = 1.0 / 60.0; - assert_eq!(edge_scroll(Some(egui::pos2(500.0, 300.0)), view(), dt), Vec2::ZERO); - assert_eq!(edge_scroll(Some(egui::pos2(500.0, 900.0)), view(), dt), Vec2::ZERO, "over another panel"); - assert_eq!(edge_scroll(None, view(), dt), Vec2::ZERO); - assert_eq!(edge_scroll(Some(egui::pos2(f32::NAN, 55.0)), view(), dt), Vec2::ZERO); - assert_eq!(edge_scroll(Some(egui::pos2(500.0, 55.0)), view(), f32::INFINITY), Vec2::ZERO); - } - - #[test] - fn it_speeds_up_the_closer_to_the_edge_and_past_it() { - let dt = 1.0 / 60.0; - let shallow = edge_scroll(Some(egui::pos2(500.0, 70.0)), view(), dt).y; - let deep = edge_scroll(Some(egui::pos2(500.0, 51.0)), view(), dt).y; - let past = edge_scroll(Some(egui::pos2(500.0, 40.0)), view(), dt).y; - assert!(0.0 < shallow && shallow < deep && deep < past, "{shallow} {deep} {past}"); - } -} diff --git a/crates/ui-egui/src/canvas/fling.rs b/crates/ui-egui/src/canvas/fling.rs deleted file mode 100644 index b5eafe69d1..0000000000 --- a/crates/ui-egui/src/canvas/fling.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! Touchpad momentum (#531): a two-finger swipe keeps gliding after the fingers lift, and slows -//! to a stop. -//! -//! Wayland compositors leave momentum to the client. libinput reports the swipe as pixel deltas -//! (`MouseWheelUnit::Point`) and the lift as an axis stop, which winit passes on as -//! `TouchPhase::End`; GTK and Firefox glide on from there, and so does the page view. -//! -//! macOS sends its own momentum as a second `Start`…`End`, so gliding there would glide twice, -//! and the web has no touch phases: [`Fling::enabled`] is off on both. Windows and X11 report no -//! touch phases through winit either, so no `End` ever starts a glide there. - -use egui::{Event, MouseWheelUnit, TouchPhase, Vec2}; - -/// Seconds of the gesture the lift speed is measured over. -const WINDOW: f64 = 0.1; -/// A lift this long after the last motion is a finger that stopped first: no glide. -const STILL: f64 = 0.05; -/// The glide slows by `e` every this many seconds; it travels the lift speed times this. -const TAU: f32 = 0.35; -/// Below this speed (points per second) a lift doesn't glide, and a glide stops. -const START_SPEED: f32 = 150.0; -const STOP_SPEED: f32 = 10.0; -/// Fastest glide, in points per second: a flick the system measured over a hiccup can't throw -/// the document to its end. -const MAX_SPEED: f32 = 8000.0; -/// A pass this long after the last one (the view was hidden, the app stalled) ends a glide. -const STALE: f64 = 0.1; - -pub(crate) struct Fling { - /// Whether a lift glides on this platform (see the module docs). - pub(crate) enabled: bool, - /// The gesture in progress: when each pass's motion arrived, and how far it went. - samples: Vec<(f64, Vec2)>, - /// The glide's speed in points per second (positive moves the content down), or zero. - velocity: Vec2, - /// When the glide last moved. - at: f64, - /// Passes in a row the glide moved the view not at all: it is against an edge. - stalled: u8, -} - -impl Default for Fling { - fn default() -> Self { - Self::new(!cfg!(any(target_os = "macos", target_arch = "wasm32"))) - } -} - -impl Fling { - pub(crate) fn new(enabled: bool) -> Self { - Self { enabled, samples: Vec::new(), velocity: Vec2::ZERO, at: 0.0, stalled: 0 } - } - - pub(crate) fn gliding(&self) -> bool { - self.velocity != Vec2::ZERO - } - - pub(crate) fn stop(&mut self) { - self.velocity = Vec2::ZERO; - self.stalled = 0; - } - - /// Reads one pass's wheel events, at time `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 - /// (animations off, single-page paging, a zoom, a dialog). - pub(crate) fn read(&mut self, events: &[Event], now: f64, glide: bool) { - for event in events { - let Event::MouseWheel { unit, delta, phase, modifiers, .. } = event else { continue }; - self.stop(); - // Zooming, a mouse wheel and sideways Shift scrolling never glide. - if *unit != MouseWheelUnit::Point || modifiers.command || modifiers.ctrl || modifiers.shift { - self.samples.clear(); - continue; - } - match phase { - TouchPhase::Start => { - self.samples.clear(); - self.push(now, *delta); - } - TouchPhase::Move => self.push(now, *delta), - TouchPhase::End => { - if glide && self.enabled { - self.velocity = self.lift_velocity(now); - self.at = now; - } - self.samples.clear(); - } - TouchPhase::Cancel => self.samples.clear(), - } - } - } - - fn push(&mut self, now: f64, delta: Vec2) { - if !(delta.x.is_finite() && delta.y.is_finite()) { - return; - } - match self.samples.last_mut() { - // Several events in one pass are one sample: they share its time. - Some((at, d)) if *at == now => *d += delta, - _ => self.samples.push((now, delta)), - } - self.samples.retain(|(at, _)| now - at <= WINDOW); - } - - /// The finger's speed as it lifted at `now`, or zero when it should not glide. - fn lift_velocity(&self, now: f64) -> Vec2 { - let recent: Vec<&(f64, Vec2)> = self.samples.iter().filter(|(at, _)| now - at <= WINDOW).collect(); - let (Some(first), Some(last)) = (recent.first(), recent.last()) else { return Vec2::ZERO }; - let span = (last.0 - first.0) as f32; - if recent.len() < 2 || span <= 0.0 || now - last.0 > STILL { - return Vec2::ZERO; - } - // Each sample is the motion since the pass before it, so the first one's motion - // happened before the span starts. - let moved = recent.iter().skip(1).fold(Vec2::ZERO, |sum, (_, d)| sum + *d); - let v = moved / span; - if !(v.x.is_finite() && v.y.is_finite()) || v.length() < START_SPEED { - return Vec2::ZERO; - } - if v.length() > MAX_SPEED { v * (MAX_SPEED / v.length()) } else { v } - } - - /// How far the glide moves the view in the pass at `now` (zero when not gliding), as the - /// exact distance a speed decaying with [`TAU`] covers since the last pass. - pub(crate) fn step(&mut self, now: f64) -> Vec2 { - if !self.gliding() { - return Vec2::ZERO; - } - let dt = now - self.at; - if !(0.0..=STALE).contains(&dt) { - self.stop(); - return Vec2::ZERO; - } - self.at = now; - let decay = (-(dt as f32) / TAU).exp(); - let moved = self.velocity * TAU * (1.0 - decay); - self.velocity *= decay; - if self.velocity.length() < STOP_SPEED { - self.stop(); - } - moved - } - - /// After a pass the glide moved the view in: whether the offset changed. Two passes that - /// didn't move it mean an edge, and the glide ends there. - pub(crate) fn moved(&mut self, moved: bool) { - if moved { - self.stalled = 0; - } else { - self.stalled = self.stalled.saturating_add(1); - if self.stalled >= 2 { - self.stop(); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use egui::{Modifiers, vec2}; - - fn wheel(dy: f32, phase: TouchPhase) -> Event { - Event::MouseWheel { - unit: MouseWheelUnit::Point, - delta: vec2(0.0, dy), - phase, - modifiers: Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - } - } - - /// A swipe of `moves` passes of `dy` each, 60 per second, lifted the pass after the last. - fn swipe(fling: &mut Fling, dy: f32, moves: usize) -> f64 { - let dt = 1.0 / 60.0; - let mut now = 0.0; - fling.read(&[wheel(dy, TouchPhase::Start)], now, true); - for _ in 0..moves { - now += dt; - fling.read(&[wheel(dy, TouchPhase::Move)], now, true); - } - now += dt; - fling.read(&[wheel(0.0, TouchPhase::End)], now, true); - now - } - - #[test] - fn a_flick_glides_on_at_its_lift_speed_and_stops() { - let mut fling = Fling::new(true); - let mut now = swipe(&mut fling, -25.0, 6); - assert!(fling.gliding()); - // 25 points a pass at 60 passes a second. - assert!((fling.velocity.y + 1500.0).abs() < 1.0, "{:?}", fling.velocity); - let mut travelled = 0.0; - let mut passes = 0; - while fling.gliding() { - now += 1.0 / 60.0; - let d = fling.step(now); - assert!(d.y <= 0.0 && d.x == 0.0, "keeps the swipe's direction: {d:?}"); - travelled += d.y; - passes += 1; - assert!(passes < 600, "the glide ends"); - } - // Speed × TAU, less the tail under STOP_SPEED. - assert!((-travelled - 1500.0 * TAU).abs() < 10.0, "travelled {travelled}"); - assert_eq!(fling.step(now + 1.0 / 60.0), Vec2::ZERO); - } - - #[test] - fn a_slow_drag_or_a_pause_before_lifting_does_not_glide() { - let mut fling = Fling::new(true); - swipe(&mut fling, -1.0, 6); - assert!(!fling.gliding(), "60 points a second is below the start speed"); - - let mut fling = Fling::new(true); - let dt = 1.0 / 60.0; - fling.read(&[wheel(-25.0, TouchPhase::Start)], 0.0, true); - fling.read(&[wheel(-25.0, TouchPhase::Move)], dt, true); - fling.read(&[wheel(0.0, TouchPhase::End)], dt + 0.2, true); - assert!(!fling.gliding(), "the finger rested before it lifted"); - } - - /// Check that new finger or wheel input stops an in-progress glide. - #[test] - fn new_input_stops_a_glide() { - let mut fling = Fling::new(true); - let now = swipe(&mut fling, -25.0, 6); - fling.read(&[wheel(-2.0, TouchPhase::Start)], now + 0.1, true); - assert!(!fling.gliding(), "fingers back on the touchpad"); - - let mut fling = Fling::new(true); - let now = swipe(&mut fling, -25.0, 6); - let notch = Event::MouseWheel { - unit: MouseWheelUnit::Line, - delta: vec2(0.0, -1.0), - phase: TouchPhase::Move, - modifiers: Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }; - fling.read(&[notch], now + 0.1, true); - assert!(!fling.gliding(), "a wheel notch"); - } - - /// Check that disabled flinging, a false glide flag, and a command-modified zoom gesture prevent glide. - #[test] - fn no_glide_where_it_is_off_or_not_wanted() { - let mut off = Fling::new(false); - swipe(&mut off, -25.0, 6); - assert!(!off.gliding(), "macOS and the web glide by themselves or not at all"); - - let mut fling = Fling::new(true); - let dt = 1.0 / 60.0; - fling.read(&[wheel(-25.0, TouchPhase::Start)], 0.0, true); - fling.read(&[wheel(-25.0, TouchPhase::Move)], dt, true); - fling.read(&[wheel(-25.0, TouchPhase::Move)], 2.0 * dt, true); - fling.read(&[wheel(0.0, TouchPhase::End)], 3.0 * dt, false); - assert!(!fling.gliding(), "animations off, paging or a dialog"); - - let mut zoom = Fling::new(true); - let ctrl = |phase| Event::MouseWheel { - unit: MouseWheelUnit::Point, - delta: vec2(0.0, -25.0), - phase, - modifiers: Modifiers::COMMAND, - source: egui::MouseWheelSource::Unknown, - }; - zoom.read(&[ctrl(TouchPhase::Start)], 0.0, true); - zoom.read(&[ctrl(TouchPhase::Move)], dt, true); - zoom.read(&[ctrl(TouchPhase::Move)], 2.0 * dt, true); - zoom.read(&[ctrl(TouchPhase::End)], 3.0 * dt, true); - assert!(!zoom.gliding(), "a pinch or ⌘/Ctrl swipe zooms"); - } - - #[test] - fn an_edge_a_stall_or_a_wild_speed_ends_or_caps_the_glide() { - let mut fling = Fling::new(true); - let now = swipe(&mut fling, -25.0, 6); - fling.step(now + 1.0 / 60.0); - fling.moved(false); - assert!(fling.gliding(), "one pass may not show the move yet"); - fling.moved(false); - assert!(!fling.gliding(), "against the edge"); - - let mut fling = Fling::new(true); - let now = swipe(&mut fling, -25.0, 6); - assert_eq!(fling.step(now + 1.0), Vec2::ZERO, "a second-long gap (the tab was hidden)"); - assert!(!fling.gliding()); - - let mut fling = Fling::new(true); - swipe(&mut fling, -5000.0, 6); - assert!((fling.velocity.length() - MAX_SPEED).abs() < 1.0, "{:?}", fling.velocity); - - let mut fling = Fling::new(true); - swipe(&mut fling, f32::NAN, 6); - assert!(!fling.gliding(), "a speed that isn't a number"); - } -} diff --git a/crates/ui-egui/src/canvas/navigation.rs b/crates/ui-egui/src/canvas/navigation.rs index 1dfadf0963..bc5c671769 100644 --- a/crates/ui-egui/src/canvas/navigation.rs +++ b/crates/ui-egui/src/canvas/navigation.rs @@ -1,5 +1,24 @@ -use super::zoom::GRID_ZOOM_STEP; -use super::{DestView, DocInfo, DocView, Fit, PT, PageLayout, SIDE, ViewAction, pos2, vec2}; +use craft::pages::Fit; +use craft::pages::ui::view::GoTo; +use craft::behavior::kurbo::{Point, Rect}; + +use super::{DestView, DocInfo, DocView, pos2}; + +/// Screen points a page edge may show above the window's top and still be a rounding sliver, not +/// what the reader is looking at. +const SLIVER: f32 = 1.0; + +/// A page-space point from page fractions and the displayed page size in points, with a missing +/// coordinate as NaN, which the page view reads as "keep that axis's offset" +/// (`PageViewState::go_to_point`). +fn point_of([fx, fy]: [Option; 2], (dw, dh): (f32, f32)) -> Point { + Point::new(fx.map_or(f64::NAN, |f| f64::from(f * dw)), fy.map_or(f64::NAN, |f| f64::from(f * dh))) +} + +/// The page's size in points as the view shows it: the view's quarter turns swap its sides. +fn displayed(p: &pdfcraft_render::PageInfo, rotation: u16) -> (f32, f32) { + if rotation % 180 == 90 { (p.height, p.width) } else { (p.width, p.height) } +} impl DocView { /// Where a bookmark made now should go: the page and the `/XYZ` position `[left, top]` in user @@ -15,43 +34,46 @@ impl DocView { return None; } // Across pages, the corner is on the selection's first page. - let first = self.selection.map(|s| *s.pages().start()); - if let Some(sel) = self.selection - && let Some(first) = first - && let Some(text) = self.texts.get(&first) + // PLAN: assumed `self.text.selection: Option` and + // `self.page_text_source(page) -> Option` (the page's `AppText` at view + // rotation 0) (pdf-canvas-w12). + if let Some(sel) = self.text.selection + && let first = *sel.pages().start() + && let Some(source) = self.page_text_source(first) && let Some(p) = info.pages.get(first) { // The selection's bounds in view space, which View ▸ Rotate View leaves unturned: the // corner at the screen's top-left is a different one for each quarter turn. let [x0, y0, x1, y1] = - sel.rects_on(first, text).iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, r| { - [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])] + sel.rects_on(first, &source).iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, r| { + [b[0].min(r.x0), b[1].min(r.y0), b[2].max(r.x1), b[3].max(r.y1)] }); - let (x, y) = match self.rotation { + let (x, y) = match self.view.rotation { 90 => (x0, y1), 180 => (x1, y1), 270 => (x1, y0), _ => (x0, y0), }; if x.is_finite() && y.is_finite() { - return Some((first, p.xyz_for_view(Some(x), Some(y)))); + return Some((first, p.xyz_for_view(Some(x as f32), Some(y as f32)))); } } // The page showing at the window's top edge: one that crosses it (the first, in a spread // of pages of different heights, whose shorter page can start below it), else the // nearest one below. - let top = self.viewport_screen.top(); - // A page showing less than a pixel is rounding, not what the reader is looking at: a jump + let top = self.viewport_rect().top(); + let xforms = self.page_xforms(); + // A page showing less than a sliver is rounding, not what the reader is looking at: a jump // to the next page leaves the previous one's bottom edge within a pixel of the top. Such a // sliver still counts when nothing else shows (the last page at the very end). let pick = |slack: f32| { - let showing = || self.screen_xforms.iter().filter(move |(_, xf)| xf.rect.bottom() > top + slack); + let showing = || xforms.iter().filter(move |(_, xf)| xf.rect.bottom() > top + slack); showing() .filter(|(_, xf)| xf.rect.top() <= top) .min_by_key(|(p, _)| *p) .or_else(|| showing().min_by(|a, b| a.1.rect.top().total_cmp(&b.1.rect.top()).then(a.0.cmp(&b.0)))) }; - let (page, xf) = pick(sliver(self.screen_ppp)).or_else(|| pick(0.0))?; + let (page, xf) = pick(SLIVER).or_else(|| pick(0.0))?; let p = info.pages.get(*page)?; // Above the page (in the gap before it) is the page's own top. The window's vertical is // the view's y, or its x when the view is turned a quarter. @@ -64,54 +86,24 @@ impl DocView { Some((*page, at)) } - /// The user-space `[left, top]` at the window's top-left (where `/XYZ` puts its point), on the - /// page showing there: what a destination's null coordinate keeps (ISO 32000-2 §12.3.2.2). - /// Acrobat keeps the place this way across pages, so a CAD sheet's cross-reference opens the - /// next sheet where the reader was looking. A coordinate is `None` along a screen axis the - /// page fits, which keeps the layout's own placement (centred, or the page's top); the whole - /// place is `None` before the first frame has laid pages out. - fn place_at_corner(&self, info: &DocInfo) -> Option<[Option; 2]> { - let area = self.viewport_screen; - if !area.is_positive() { - return None; + /// Records `from` as the place the reader leaves, for Previous view / Next view. + fn remember_place(&mut self, from: usize) { + if self.back.last() != Some(&from) { + self.back.push(from); + if self.back.len() > 200 { + self.back.remove(0); + } } - let corner = area.min + vec2(SIDE, 0.0); - let (page, xf) = self - .screen_xforms - .iter() - .filter(|(_, xf)| xf.rect.is_positive()) - .min_by(|a, b| a.1.rect.distance_sq_to_pos(corner).total_cmp(&b.1.rect.distance_sq_to_pos(corner)).then(a.0.cmp(&b.0)))?; - let p = info.pages.get(*page)?; - let (x, y) = xf.screen_to_view(corner.clamp(xf.rect.min, xf.rect.max)); - // `max` drops a NaN size, so the bounds stay ordered and `clamp` can't panic. - let (x, y) = (x.clamp(0.0, p.width.max(0.0)), y.clamp(0.0, p.height.max(0.0))); - // The page counts with its side gutters, as the layout places it. - let wide = xf.rect.width() + 2.0 * SIDE > area.width(); - let tall = xf.rect.height() > area.height(); - // The view's x runs across the screen unless the view is turned a quarter. - let (keep_x, keep_y) = if xf.rot.is_multiple_of(180) { (wide, tall) } else { (tall, wide) }; - Some(p.xyz_for_view(keep_x.then_some(x), keep_y.then_some(y))) + self.forward.clear(); } pub fn go_to_page(&mut self, page: usize) { let page = page.min(self.page_count.saturating_sub(1)); self.end_find_following(); - if page != self.current { - // The view history (Previous view / Next view). - if self.back.last() != Some(&self.current) { - self.back.push(self.current); - if self.back.len() > 200 { - self.back.remove(0); - } - } - self.forward.clear(); + if page != self.view.current { + self.remember_place(self.view.current); } - // Partial wheel motion belongs to the old place, and so does a find step's match. - self.reset_coarse_state(); - self.find_hold = None; - self.goto_point = None; - self.goto = Some((page, 0.0)); - self.current = page; + self.view.go_to(page); } /// The end of the document (End): the last page, scrolled to its bottom as far as the view @@ -119,24 +111,23 @@ impl DocView { /// page's top. pub fn go_to_end(&mut self) { self.go_to_page(usize::MAX); - // A fraction past a page's top scrolls as far as the content allows (`goto`, clamped when - // applied), so the whole page down to its bottom edge. - self.goto = Some((self.current, 1.0)); + self.view.go_to_fraction(self.view.current, 1.0); } /// Reveal a user-space rectangle without changing zoom, centred where the scroll bounds allow. pub(crate) fn reveal_rect(&mut self, page: usize, rect: [f32; 4], info: &DocInfo) { self.go_to_page(page); - self.goto_point = None; - let Some(p) = info.pages.get(self.current) else { return }; + let page = self.view.current; + let Some(p) = info.pages.get(page) else { return }; if !rect.iter().all(|v| v.is_finite()) { return; } // Halve before adding so even large finite coordinates cannot overflow the midpoint. let x = rect[0] * 0.5 + rect[2] * 0.5; let y = rect[1] * 0.5 + rect[3] * 0.5; - let [fx, fy] = p.dest_fraction(Some(x), Some(y), self.rotation); - self.goto_point = Some((self.current, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0)); + let rotation = self.view.rotation; + let at = point_of(p.dest_fraction(Some(x), Some(y), rotation), displayed(p, rotation)); + self.view.go_to_point(page, at, (0.5, 0.5)); } /// Go to a destination, a bookmark's or a link's (ISO 32000-2 §12.3.2.2): its page, scrolled @@ -144,94 +135,76 @@ impl DocView { /// top-left at its zoom (null or 0 keeps the zoom); `/Fit`, `/FitH` and `/FitV` switch to fit /// page, width and height with `top` or `left` at the window's edge; `/FitR` zooms so the /// rectangle fits, centred. The `B` (content box) forms are read as the page. A null `/XYZ` - /// coordinate keeps the reader's place: the same user-space point stays at the window's - /// top-left on the new page, as Acrobat does. A point past the end of the document scrolls - /// as far as it can. + /// coordinate keeps the reader's place: that axis of the view is not moved, as Acrobat does. + /// A point past the end of the document scrolls as far as it can. pub fn go_to_dest(&mut self, page: usize, dest: DestView, info: &DocInfo) { - // Read before the jump: it is where the reader is now. - let kept = match dest { - DestView::Xyz { left, top, .. } if left.is_none() || top.is_none() => self.place_at_corner(info), - _ => None, - }; self.go_to_page(page); - let page = self.current; - self.goto_point = None; + let page = self.view.current; let Some(p) = info.pages.get(page) else { return }; - let point = |x: Option, y: Option| p.dest_fraction(x, y, self.rotation); - // The window's top-left as far as pages go: its left edge is the gutter that keeps them - // clear of the floating quick-action bar, so `left` 0 shows the page's edge beside it. - let corner = vec2(SIDE, 0.0); - let (fx, fy, rel) = match dest { + let rotation = self.view.rotation; + let size = displayed(p, rotation); + let fractions = |x: Option, y: Option| p.dest_fraction(x, y, rotation); + let at = match dest { DestView::Top => return, DestView::Xyz { left, top, zoom } => { if let Some(z) = zoom { - self.zoom = z.clamp(0.08, 64.0); - self.fit = Fit::None; - self.zoom_anchor = None; + // The page view's pass clamps the written zoom (`ZOOM_RANGE`). + self.view.zoom = f64::from(z); + self.view.fit = Fit::None; } - let [kept_left, kept_top] = kept.unwrap_or([None, None]); - let [fx, fy] = point(left.or(kept_left), top.or(kept_top)); - (fx, fy, corner) + fractions(left, top) } DestView::Fit => { - self.fit = Fit::Page; + self.view.fit = Fit::Page; return; } DestView::FitH { top } => { - self.fit = Fit::Width; - let [fx, fy] = point(None, top); - (fx, fy, corner) + self.view.fit = Fit::Width; + fractions(None, top) } DestView::FitV { left } => { - self.fit = Fit::Height; - let [fx, fy] = point(left, None); - (fx, fy, corner) + self.view.fit = Fit::Height; + fractions(left, None) } DestView::FitR { rect } => { - let ([Some(ax), Some(ay)], [Some(bx), Some(by)]) = (point(Some(rect[0]), Some(rect[3])), point(Some(rect[2]), Some(rect[1]))) else { + let ([Some(ax), Some(ay)], [Some(bx), Some(by)]) = (fractions(Some(rect[0]), Some(rect[3])), fractions(Some(rect[2]), Some(rect[1]))) + else { return; }; - // The rectangle as displayed, in points (it can be turned a quarter). - let (dw, dh) = self.display_size(p); + // The rectangle as displayed, in page points (it can be turned a quarter). + let (dw, dh) = size; let (w, h) = ((ax - bx).abs() * dw, (ay - by).abs() * dh); - if w >= 1.0 && h >= 1.0 && self.viewport_w >= 1.0 && self.viewport_h >= 1.0 { - self.zoom = (self.viewport_w / (w * PT)).min(self.viewport_h / (h * PT)).clamp(0.08, 64.0); - self.fit = Fit::None; - self.zoom_anchor = None; + if w >= 1.0 && h >= 1.0 { + let rect = Rect::new( + f64::from(ax.min(bx) * dw), + f64::from(ay.min(by) * dh), + f64::from(ax.max(bx) * dw), + f64::from(ay.max(by) * dh), + ); + self.view.go_to = Some(GoTo::Rect { page, rect, margin: 0.0 }); } - (Some((ax + bx) / 2.0), Some((ay + by) / 2.0), vec2(self.viewport_w, self.viewport_h) / 2.0) + return; } }; - if fx.is_some() || fy.is_some() { - self.goto_point = Some((page, fx, fy, rel)); + if at.iter().any(Option::is_some) { + // The pass places the point at the viewport's start corner beside the page gutter. + self.view.go_to = Some(GoTo::Corner { page, at: point_of(at, size) }); } } /// Next page (`true`) or previous page. In two-page view this moves a whole spread: the other /// page of the spread is already on screen, so stepping to it wouldn't move the view (#70). pub fn step_page(&mut self, forward: bool) { - let c = self.current; - let last = self.page_count.saturating_sub(1); - let (target, first) = match self.layout { - PageLayout::TwoUp => { - let first = self.spread_first(c); - let target = match (forward, self.cover && c == 0) { - (true, true) => 1, - (true, false) => first.saturating_add(2), - (false, _) if self.cover && first <= 1 => 0, - (false, _) => first.saturating_sub(2), - }; - (target, first) - } - PageLayout::Single if forward => (c + 1, c), - PageLayout::Single => (c.saturating_sub(1), c), - }; - // Past either end there is nowhere to go: stay put rather than re-align the view, which - // would scroll the page back to its top. - if if forward { target > last } else { first == 0 } { + let before = self.view.current; + // The page view turns in its next pass, so nothing here can see whether the step moved; + // asking where there is no page to turn to is not a step. + let can_turn = if forward { before.saturating_add(1) < self.page_count } else { before > 0 }; + if !can_turn { return; } - self.go_to_page(target); + self.end_find_following(); + self.remember_place(before); + self.view.step(forward); } /// Page-editor focus and drafts belong to a document, even while another tab is active. @@ -241,7 +214,7 @@ impl DocView { /// The idle page box and unchanged-input lookup share the same label fallback. pub(crate) fn current_page_label(&self, label: Option<&str>) -> String { - label.filter(|l| !l.is_empty()).map(str::to_owned).unwrap_or_else(|| (self.current + 1).to_string()) + label.filter(|l| !l.is_empty()).map(str::to_owned).unwrap_or_else(|| (self.view.current + 1).to_string()) } /// Retain the current page when `typed` exactly matches its displayed label, even if @@ -251,7 +224,8 @@ impl DocView { pub fn go_to_typed(&mut self, typed: &str, labels: &[String]) -> bool { // Compare the displayed value before trimming: a label may itself contain spaces. // Repeated labels occur in restarted sections and prefix-only ranges. - if self.current < self.page_count && self.current_page_label(labels.get(self.current).map(String::as_str)) == typed { + let current = self.view.current; + if current < self.page_count && self.current_page_label(labels.get(current).map(String::as_str)) == typed { return true; } let t = typed.trim(); @@ -277,327 +251,9 @@ impl DocView { self.end_find_following(); let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) }; let Some(page) = from.pop() else { return false }; - to.push(self.current); + to.push(self.view.current); let page = page.min(self.page_count.saturating_sub(1)); - self.goto = Some((page, 0.0)); - self.current = page; - self.reset_coarse_state(); - // A find step's match belongs to the place left, as for any other jump. - self.find_hold = None; - true - } - - /// One wheel event in a non-continuous view, where the wheel turns pages or spreads (the - /// rules are in `wheel_pager`): `dy` is its vertical delta (negative scrolls down) and `now` - /// is egui time. With `can_turn` false the gesture is followed but the page stays. Returns - /// whether the page turned. - pub fn single_page_wheel(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool { - if self.continuous { - return false; - } - let Some(forward) = self.wheel.feed(unit, dy, phase, now, can_turn) else { return false }; - let before = self.current; - self.step_page(forward); - if self.current == before { - self.wheel.unturn(); - return false; - } - true - } - - /// One wheel event in a non-continuous view whose page is taller than the window, where the - /// wheel pans (#1924). Once the view is at the bottom (top) edge, scrolling on turns to the - /// next (previous) page, which shows its top (bottom). A smooth gesture that panned the page - /// has to end first (see `WheelPager::feed_edge`). `can_turn` is false when something else - /// owns the wheel. Returns whether the page turned. - pub fn single_page_wheel_edge(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool { - if self.continuous { - return false; - } - // Only an up-to-date view counts: the page drawn is the shown one, with no jump pending. - let edge = self.goto.is_none() - && self.goto_point.is_none() - && self.single_edges.is_some_and(|(page, top, bottom)| page == self.current && if dy < 0.0 { bottom } else { top }); - let Some(forward) = self.wheel.feed_edge(unit, dy, phase, now, can_turn && edge) else { return false }; - let before = self.current; - self.step_page(forward); - if self.current == before { - self.wheel.unturn(); - return false; - } - if !forward { - // Going back lands on the bottom of the previous page. - self.goto = Some((self.current, 1.0)); - } - self.single_edges = None; + self.view.go_to(page); true } } - -/// ⇧⌘+ / ⇧⌘−: rotate the view clockwise / counterclockwise. -fn rotation_shortcuts(view: &mut DocView, pressed: &impl Fn(egui::KeyboardShortcut) -> bool) { - use egui::{Key, KeyboardShortcut, Modifiers}; - let shift_cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k); - if pressed(shift_cmd(Key::Plus)) || pressed(shift_cmd(Key::Equals)) { - view.rotate_view(true); - } - if pressed(shift_cmd(Key::Minus)) { - view.rotate_view(false); - } -} - -/// ⌘+ / ⌘− / ⌘0 / ⌘1 / ⌘2: zoom the page, or size the pages in the page grid. -fn zoom_shortcuts(view: &mut DocView, pressed: &impl Fn(egui::KeyboardShortcut) -> bool) { - use egui::{Key, KeyboardShortcut, Modifiers}; - let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); - // In the page grid ⌘+ / ⌘− / ⌘0 size its pages instead (looking is always allowed). - let (zoom_in, zoom_out, zoom_reset) = (pressed(cmd(Key::Plus)) || pressed(cmd(Key::Equals)), pressed(cmd(Key::Minus)), pressed(cmd(Key::Num0))); - if view.organize { - if zoom_in { - view.grid_zoom_request = Some(view.grid_zoom * GRID_ZOOM_STEP); - } - if zoom_out { - view.grid_zoom_request = Some(view.grid_zoom / GRID_ZOOM_STEP); - } - if zoom_reset { - view.grid_zoom_request = Some(1.0); - } - } else { - if zoom_in { - view.zoom_step(true); - } - if zoom_out { - view.zoom_step(false); - } - if zoom_reset { - view.fit = Fit::Page; - view.goto = Some((view.current, 0.0)); - } - } - if pressed(cmd(Key::Num1)) { - view.set_zoom(1.0); - } - if pressed(cmd(Key::Num2)) { - view.fit = Fit::Width; - view.goto = Some((view.current, 0.0)); - } -} - -/// The view's keys: its chords, then its plain keys. `chords`: no menu of the menu bar has the -/// keyboard and nothing covers the pages, so chords may run (they wait for a menu, as the -/// registered commands' do). An open form field keeps the paging and scrolling keys for itself. -pub(crate) fn shortcuts( - view: &mut DocView, - ctx: &egui::Context, - keys: crate::page_keys::PageKeys, - chords: bool, - speed: crate::scroll_speed::ScrollSpeed, -) { - if let Some((arrows, field_open)) = view_chords(view, ctx, chords) { - view_keys(view, ctx, keys, speed, arrows, field_open); - } -} - -/// The view's chords: Find and its steps, rotation, zoom and the view history, unless a menu of the -/// menu bar has the keyboard or something covers the pages (`chords`). `None` while a text field -/// has the keyboard, and then it has the plain keys too; else whether the arrows are the view's (a -/// focused radio button keeps them), and whether an open form field (a drop-down's or a list box's -/// items) keeps the plain keys. -fn view_chords(view: &mut DocView, ctx: &egui::Context, chords: bool) -> Option<(bool, bool)> { - use egui::{Key, KeyboardShortcut, Modifiers}; - let pressed = |s: KeyboardShortcut| chords && ctx.input_mut(|i| i.consume_shortcut(&s)); - if pressed(KeyboardShortcut::new(Modifiers::COMMAND, Key::F)) { - view.open_find(); - } - let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); - // ⌘G / ⇧⌘G step through the matches from the find field too, as in Acrobat and Preview - // (#2669): ahead of the text-input check, but only while there is a search to step. - if view.find.is_some() { - if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) { - view.find_step(false); - } else if pressed(cmd(Key::G)) { - view.find_step(true); - } - } - // A focused check box or radio button holds egui's keyboard focus only for Space, and a - // radio button for the arrows that move within its group: the other page keys still work. - let form_box = view.forms.keys.filter(|(id, _)| ctx.memory(|m| m.focused()) == Some(*id)); - if ctx.egui_wants_keyboard_input() && form_box.is_none() { - return None; - } - let arrows = !form_box.is_some_and(|(_, radio)| radio); - // Rotation first: egui matches ⌘+ loosely with respect to Shift. - rotation_shortcuts(view, &pressed); - zoom_shortcuts(view, &pressed); - // Alt+← / Alt+→ (⌥ on macOS) too, as in Acrobat and browsers, back to where a link was - // followed from (#3632). Consumed here, before ← / → turn the page. egui matches the pattern - // logically, so an extra Shift is ignored and Shift+Alt+← goes back as well (harmless). - let alt = |k| KeyboardShortcut::new(Modifiers::ALT, k); - if pressed(cmd(Key::OpenBracket)) || pressed(alt(Key::ArrowLeft)) { - view.view_history(false); - } - if pressed(cmd(Key::CloseBracket)) || pressed(alt(Key::ArrowRight)) { - view.view_history(true); - } - // An open form field (a drop-down's or a list box's items) takes the arrows, Page Up / Page - // Down, Home, End and Escape. A focused check box or radio button uses none of them, so the - // page keys still work there. - let field_open = view.forms.focus.is_some() && form_box.is_none(); - Some((arrows, field_open)) -} - -/// The view's plain keys: Escape, Home and End, full screen's keys, the arrows and Page Up / Page -/// Down. Not while something is over the pages or a form field is open (`field_open`), which keeps -/// them. -fn view_keys( - view: &mut DocView, - ctx: &egui::Context, - keys: crate::page_keys::PageKeys, - speed: crate::scroll_speed::ScrollSpeed, - arrows: bool, - field_open: bool, -) { - use egui::Key; - let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && keys.pressed(ctx, k); - // An open menu takes Escape first and closes; the selection stays for the next one (#3535). - // So does an open field, whose list closes. - if key(Key::Escape) && !egui::Popup::is_any_open(ctx) && !field_open { - if view.camera.is_some() || view.camera_done.is_some() { - view.pending_action = Some(ViewAction::CancelCamera); - } else if view.selection.is_some() || view.all_text { - view.selection = None; - view.all_text = false; - } else { - view.find = None; - } - } - // The open field's keys leave the page under it where it is. - if field_open { - return; - } - // Home and End, and the keys listed with them for Go to first / last page: Shift+Ctrl - // (Shift+⌘ on macOS) with ↑ / ↓ or Page Up / Page Down (#6434; *Adobe Acrobat Help*, 2019, - // "Keys for navigating a PDF", p. 83). These take the key from the page turning and - // scrolling below. - let (mut to_start, mut to_end) = (false, false); - keys.take_presses(ctx, |k, m| { - let shift_cmd = m.matches_logically(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); - match k { - Key::ArrowUp | Key::PageUp if shift_cmd => to_start = true, - Key::ArrowDown | Key::PageDown if shift_cmd => to_end = true, - _ => return false, - } - true - }); - if key(Key::Home) || to_start { - view.go_to_page(0); - } - if key(Key::End) || to_end { - view.go_to_end(); - } - if to_end || to_start { - return; - } - let (command, shift) = ctx.input(|i| (i.modifiers.command, i.modifiers.shift)); - // Full screen: Space and Enter go forward a page, and Shift+Enter and Backspace back - // (*Adobe Acrobat Help*, 2019, "Read a document in Full Screen mode", p. 66: "To go to the - // previous page, press Shift+Enter"). The arrows and Page Up / Page Down already turn pages - // where nothing scrolls, below. - if view.presentation.is_some() { - if key(Key::Space) || (key(Key::Enter) && !shift) { - view.step_page(true); - } - if key(Key::Backspace) || (key(Key::Enter) && shift) { - view.step_page(false); - } - } - // As in Acrobat: → / ← go to the next / previous page in every layout (#185), and so do - // ⌘Page Down / ⌘Page Up, or plain Page Down / Page Up in single-page view. On a page wider - // than the window (a plan zoomed in) → / ← scroll sideways a line first, and turn the page - // once there is nothing left to scroll that way, as ↓ / ↑ do in single-page view; ⌘→ / ⌘← - // turn it at once. - let scrolls = view.continuous; - let line = KEY_SCROLL_LINE * speed.factor(); - // Only an up-to-date view counts: no jump pending. - let sideways = |view: &DocView, right: bool| { - !command && view.goto.is_none() && view.side_edges.is_some_and(|(left_edge, right_edge)| !if right { right_edge } else { left_edge }) - }; - // Turned at an edge, the next page starts at its left and the previous one at its right, as - // reading on across: on two wide pages → doesn't turn twice without showing the next one's left. - let at_edge = |view: &mut DocView, right: bool| { - if !command && view.goto.is_some() { - view.goto_side = Some(!right); - } - }; - if key(Key::ArrowRight) && sideways(view, true) { - view.key_side += line; - } else if key(Key::ArrowRight) || (key(Key::PageDown) && (command || !scrolls)) { - view.step_page(true); - if key(Key::ArrowRight) { - at_edge(view, true); - } - } - if key(Key::ArrowLeft) && sideways(view, false) { - view.key_side -= line; - } else if key(Key::ArrowLeft) || (key(Key::PageUp) && (command || !scrolls)) { - view.step_page(false); - if key(Key::ArrowLeft) { - at_edge(view, false); - } - } - // ↓ / ↑ scroll a line, and Page Down / Page Up a screen where the pages scroll. In - // single-page view, ↓ / ↑ turn the page once there is nothing left to scroll that way, as - // the wheel does (#273): always on a page that fits. - // The Scroll speed preference sets how far ↓ / ↑ go as well as the wheel (#985); Page Down / - // Page Up keep a screen. - if !command { - let screen = (view.viewport_h - KEY_SCROLL_LINE).max(KEY_SCROLL_LINE); - let steps = [(Key::ArrowDown, line), (Key::ArrowUp, -line), (Key::PageDown, screen), (Key::PageUp, -screen)]; - for (k, by) in steps { - let arrow = matches!(k, Key::ArrowDown | Key::ArrowUp); - if !key(k) || !(scrolls || arrow) { - continue; - } - let forward = k == Key::ArrowDown; - // Only an up-to-date view counts: the page drawn is the current one, with no jump pending. - let at_end = !scrolls - && view.goto.is_none() - && view.single_edges.is_some_and(|(page, top, bottom)| page == view.current && if forward { bottom } else { top }); - if at_end { - let before = view.current; - view.step_page(forward); - if !forward && view.current != before { - // Going back up lands on the bottom of the previous page. - view.goto = Some((view.current, 1.0)); - } - view.single_edges = None; - } else { - view.key_scroll += by; - } - } - } -} - -/// How far ↓ / ↑ scroll at Normal speed (Scroll speed halves or doubles it). Page Down / Page Up -/// keep this much of the previous screen in view. -const KEY_SCROLL_LINE: f32 = 40.0; -/// How much of a page must show at the window's top edge to count as the page there, in points: one -/// physical pixel, since page rectangles snap to whole pixels and less is rounding. -fn sliver(pixels_per_point: f32) -> f32 { - if pixels_per_point.is_finite() && pixels_per_point > 0.0 { 1.0 / pixels_per_point } else { 1.0 } -} - -#[cfg(test)] -mod tests { - use super::sliver; - - #[test] - fn a_sliver_is_one_physical_pixel() { - assert_eq!(sliver(1.0), 1.0); - assert_eq!(sliver(2.0), 0.5); - assert_eq!(sliver(0.5), 2.0); - for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] { - assert_eq!(sliver(bad), 1.0, "{bad}"); - } - } -} diff --git a/crates/ui-egui/src/canvas/scroll_speed.rs b/crates/ui-egui/src/canvas/scroll_speed.rs index ebb6a34c41..02d26389ac 100644 --- a/crates/ui-egui/src/canvas/scroll_speed.rs +++ b/crates/ui-egui/src/canvas/scroll_speed.rs @@ -1,11 +1,9 @@ //! How far a mouse-wheel notch scrolls (#444, #186), and ↓ / ↑ with it (#985). //! -//! egui scrolls `line_scroll_speed` points per wheel line: 40 on the desktop, 8 on the web. //! macOS already accelerates line deltas, and browsers there scroll about that far per line, //! but on Windows and Linux winit reports one line per notch, where browsers scroll about -//! 100 pixels, so 40 felt slow. Wheel input reported in points (most trackpads) keeps its own -//! speed, ⌘/Ctrl-wheel zoom keeps egui's rate, and wheel paging in Single page view still turns -//! one page per notch. +//! 100 pixels, so the desktop default is larger than a text line. The canvas reads the two +//! distances through its navigation options. /// The user's choice, relative to the platform's normal speed. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -17,9 +15,6 @@ pub enum ScrollSpeed { Fast, } -/// egui's own `line_scroll_speed`, which its wheel zoom rate is tuned against. -pub(crate) const EGUI_LINE_POINTS: f32 = if cfg!(target_arch = "wasm32") { 8.0 } else { 40.0 }; - /// Points one wheel line scrolls at Normal speed. const NORMAL_LINE_POINTS: f32 = if cfg!(target_arch = "wasm32") { // The browser's line deltas, which egui already scales for the web. @@ -30,6 +25,9 @@ const NORMAL_LINE_POINTS: f32 = if cfg!(target_arch = "wasm32") { 100.0 }; +/// Points one arrow-key step scrolls at Normal speed. +const KEY_LINE_POINTS: f32 = 40.0; + impl ScrollSpeed { pub const ALL: [Self; 3] = [Self::Slow, Self::Normal, Self::Fast]; @@ -51,76 +49,16 @@ impl ScrollSpeed { } /// Points one wheel line scrolls. - pub fn line_points(self) -> f32 { + pub fn wheel_line(self) -> f32 { NORMAL_LINE_POINTS * self.factor() } - /// Makes egui scroll this far per wheel line, from this frame's input on (call it before egui - /// reads `raw`). egui scales line deltas before turning ⌘/Ctrl-wheel motion into zoom, so - /// those events are scaled back to keep zooming at egui's own rate. - pub(crate) fn apply(self, ctx: &egui::Context, raw: &mut egui::RawInput) { - self.set_line_speed(ctx); - let points = self.line_points(); - let zoom_scale = EGUI_LINE_POINTS / points; - for event in &mut raw.events { - if let egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta, modifiers, .. } = event - && modifiers.command - { - *delta *= zoom_scale; - } - } - } - - /// Makes egui scroll this far per wheel line (from the next frame when called during one). - pub(crate) fn set_line_speed(self, ctx: &egui::Context) { - let points = self.line_points(); - if ctx.options(|o| o.input_options.line_scroll_speed) != points { - ctx.options_mut(|o| o.input_options.line_scroll_speed = points); - } + /// Points one arrow-key step scrolls. + pub fn key_line(self) -> f32 { + KEY_LINE_POINTS * self.factor() } pub fn parse(value: &str) -> Option { Self::ALL.into_iter().find(|s| s.label().eq_ignore_ascii_case(value)) } } - -#[cfg(test)] -mod tests { - use super::*; - - fn wheel(unit: egui::MouseWheelUnit, dy: f32, command: bool) -> egui::Event { - let modifiers = egui::Modifiers { command, ..egui::Modifiers::NONE }; - egui::Event::MouseWheel { - unit, - delta: egui::vec2(0.0, dy), - phase: egui::TouchPhase::Move, - modifiers, - source: egui::MouseWheelSource::Unknown, - } - } - - #[test] - fn zoom_keeps_egui_rate_and_scrolling_follows_the_choice() { - let ctx = egui::Context::default(); - for speed in ScrollSpeed::ALL { - let mut raw = egui::RawInput { - events: vec![ - wheel(egui::MouseWheelUnit::Line, 1.0, true), - wheel(egui::MouseWheelUnit::Line, 1.0, false), - wheel(egui::MouseWheelUnit::Point, 30.0, true), - ], - ..Default::default() - }; - speed.apply(&ctx, &mut raw); - assert_eq!(ctx.options(|o| o.input_options.line_scroll_speed), speed.line_points()); - let dy: Vec = - raw.events.iter().filter_map(|e| if let egui::Event::MouseWheel { delta, .. } = e { Some(delta.y) } else { None }).collect(); - // ⌘/Ctrl lines scaled back so egui's zoom sees EGUI_LINE_POINTS per line; plain lines - // and point deltas untouched. - assert!((dy[0] * speed.line_points() - EGUI_LINE_POINTS).abs() < 1e-3, "{speed:?}: {dy:?}"); - assert_eq!((dy[1], dy[2]), (1.0, 30.0)); - } - assert_eq!(ScrollSpeed::parse("FAST"), Some(ScrollSpeed::Fast)); - assert_eq!(ScrollSpeed::parse("warp"), None); - } -} diff --git a/crates/ui-egui/src/canvas/wheel_boost.rs b/crates/ui-egui/src/canvas/wheel_boost.rs deleted file mode 100644 index 981940bcb0..0000000000 --- a/crates/ui-egui/src/canvas/wheel_boost.rs +++ /dev/null @@ -1,775 +0,0 @@ -//! Bounded acceleration for coarse wheel input in the document viewport. -//! -//! Coarse line events use a bounded arrival-rate multiplier and one motion curve -//! for their whole distance. Isolated notches retain their distance. Fractional line -//! components stay direct on their own axes; explicitly continuous sources stay direct -//! on both axes. Fractional values alone do not identify the physical device. -//! Retained motion uses constant-size state. - -use egui::Vec2; - -/// Idle time after which a burst is forgotten, in seconds. -const RESET_GAP_SECS: f64 = 0.3; -/// Notch spacing at or below which input counts as a continuous spin, in seconds. -const FAST_GAP_SECS: f64 = 0.08; -/// Multiplier gained per fast consecutive notch. -const BOOST_PER_TICK: f32 = 0.4; -/// Hard limit for accelerated motion. -const MAX_BOOST: f32 = 6.0; -/// Ticks that affect the output. -const MAX_TICKS: u32 = 13; -/// Extra ticks retained beyond the ceiling. They absorb a few slow events -/// before the visible multiplier starts to fall. -const HYSTERESIS_TICKS: u32 = 4; -/// Per-axis bound for a normalized bucket, accelerated surplus or emitted motion step. -pub(crate) const MAX_FRAME_POINTS: f32 = 8192.0; -/// Per-axis motion input limit after combining base, surplus and Page distance. -const MAX_MOTION_INPUT_POINTS: f32 = 2.0 * MAX_FRAME_POINTS; -/// Retained motion permits a transient burst beyond one output frame. -const MAX_PENDING_POINTS: f32 = 2.0 * MAX_FRAME_POINTS; -/// Per-event clamp, in native units (lines or pages). Keeps one hostile event -/// bounded before points conversion. -pub(crate) const MAX_EVENT_UNITS: f32 = 10.0; - -/// Constant-size arrival-rate state for line wheel events. -#[derive(Debug, Default)] -pub(crate) struct WheelBoost { - last: f64, - burst: u32, - dir: i8, -} - -impl WheelBoost { - /// Returns the multiplier for one bucket of motion carrying `motion`. - /// - /// `motion` is signed in native units; only its sign matters. Zero means - /// no motion. Non-finite time returns 1.0 and leaves state unchanged; - /// backwards time resets the burst and returns 1.0. - pub(crate) fn multiplier(&mut self, now: f64, motion: f32) -> f32 { - if !now.is_finite() || !motion.is_finite() || motion == 0.0 { - return 1.0; - } - let dir = if motion > 0.0 { 1 } else { -1 }; - let idle = now - self.last; - if !idle.is_finite() || idle < 0.0 { - self.last = now; - self.burst = 0; - self.dir = dir; - return 1.0; - } - if idle > RESET_GAP_SECS || dir != self.dir { - self.burst = 0; - } else if idle <= FAST_GAP_SECS { - self.burst = self.burst.saturating_add(1).min(MAX_TICKS + HYSTERESIS_TICKS); - } else { - // Slow input in the same direction decays rather than extending the burst. - self.burst = self.burst.saturating_sub(1); - } - self.last = now; - self.dir = dir; - let ticks = self.burst.min(MAX_TICKS); - // MAX_TICKS is well within f32's exact integer range. - (1.0 + ticks as f32 * BOOST_PER_TICK).min(MAX_BOOST) - } - - /// Drops burst state. Call after a programmatic scroll jump. - pub(crate) fn reset(&mut self) { - *self = Self::default(); - } -} - -/// Caps a normalized bucket or output step, per axis. A non-finite axis -/// maps to zero; the other axis is preserved. -pub(crate) fn cap_frame(delta: Vec2) -> Vec2 { - cap_points(delta, MAX_FRAME_POINTS) -} - -/// Caps finite point distances independently; invalid axes contribute no distance. -fn cap_points(delta: Vec2, limit: f32) -> Vec2 { - Vec2::new( - if delta.x.is_finite() { delta.x.clamp(-limit, limit) } else { 0.0 }, - if delta.y.is_finite() { delta.y.clamp(-limit, limit) } else { 0.0 }, - ) -} - -/// Eases the whole coarse-wheel distance, including its unaccelerated part. -/// -/// The caller owns input once per egui frame, cancels old motion on direct-input -/// axes before stepping, and requests another frame while motion is pending. -/// Each axis admits up to 16384 input points and retains up to 16384 pending -/// points, emitting at most 8192 per frame. Input beyond those finite capacities -/// is dropped; isolated base-plus-surplus bursts are preserved when there is room. -#[derive(Debug, Default)] -pub(crate) struct Motion { - pending: Vec2, - last: Option, -} - -impl Motion { - /// Forgets owed distance and its clock when input ownership or navigation changes. - pub(crate) fn reset(&mut self) { - *self = Self::default(); - } - - /// Drops older coarse motion on axes carrying direct input. This must happen - /// before adding this frame's coarse input, so mixed input is retained. - pub(crate) fn cancel_axes(&mut self, direct: Vec2) { - if direct.x != 0.0 { - self.pending.x = 0.0; - } - if direct.y != 0.0 { - self.pending.y = 0.0; - } - } - - /// Whether another frame is needed to deliver admitted coarse movement. - pub(crate) fn has_pending(&self) -> bool { - self.pending != Vec2::ZERO - } - - /// Consumes a bounded frame bucket. Reversal cancels the older direction on - /// that axis. Disabling animation drains existing and new input immediately, - /// except for overflow beyond the frame cap. A stale clock cancels the old - /// tail; an invalid clock also limits fresh input to one output frame without - /// retaining it. Pending plus fresh input cannot exceed queue and output capacity. - pub(crate) fn step(&mut self, input: Vec2, now: f64, dt: f32, animate: bool) -> Vec2 { - let input = cap_points(input, MAX_MOTION_INPUT_POINTS); - let stale = !now.is_finite() || self.last.is_some_and(|last| now < last || now - last > RESET_GAP_SECS); - if stale { - self.pending = Vec2::ZERO; - } - self.last = now.is_finite().then_some(now); - if !now.is_finite() { - self.pending = Vec2::ZERO; - return cap_frame(input); - } - // Use a valid elapsed frame interval rather than letting invalid or very - // large intervals erase the distinction between animated and direct input. - let dt = if dt.is_finite() && dt > 0.0 { dt.min(0.1) } else { 1.0 / 60.0 }; - let fraction = if animate { 1.0 - 0.1_f32.powf(dt / 0.1) } else { 1.0 }; - Vec2::new(Self::step_axis(&mut self.pending.x, input.x, fraction), Self::step_axis(&mut self.pending.y, input.y, fraction)) - } - - /// Delivers one axis while bounding both the returned step and remaining distance. - fn step_axis(pending: &mut f32, input: f32, fraction: f32) -> f32 { - if input != 0.0 && input.signum() != pending.signum() { - *pending = 0.0; - } - let capacity = MAX_PENDING_POINTS + MAX_FRAME_POINTS; - let total = (*pending + input).clamp(-capacity, capacity); - // Emit enough overflow to keep both output and pending bounded, without - // discarding distance after the finite queue's admission boundary. - let magnitude = total.abs(); - let emitted = if magnitude <= 0.01 { magnitude } else { (magnitude * fraction).max(magnitude - MAX_PENDING_POINTS).min(MAX_FRAME_POINTS) }; - let output = total.signum() * emitted; - *pending = total - output; - output - } -} - -/// One frame of wheel input, normalized in a single pass. Line motion is in -/// points; page motion remains in native units until the viewport is known. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub(crate) struct FrameInput { - pub precise: Vec2, - pub line: Vec2, - pub page: Vec2, -} - -/// Folds raw wheel events into frame totals without consulting time or UI state. -/// Invalid scales contribute no line motion. -pub(crate) fn accumulate(events: &[egui::Event], line_points: f32, single_paging: bool) -> FrameInput { - let line_points = sanitize_scale(line_points); - let mut out = FrameInput::default(); - for event in events { - let egui::Event::MouseWheel { unit, delta, modifiers, source, .. } = event else { continue }; - if modifiers.command || modifiers.ctrl { - continue; // Zooming, not scrolling. - } - if !delta.is_finite() { - continue; - } - // Fractional native line components use a distance-preserving routing policy for - // high-resolution input, not evidence of a particular physical device. - // Inspect before clamping or axis folding, which can hide fractions. - let continuous = matches!(source, egui::MouseWheelSource::Trackpad | egui::MouseWheelSource::Momentum); - let direct_x = continuous || delta.x.fract() != 0.0 || (modifiers.shift && delta.y.fract() != 0.0); - let direct_y = continuous || delta.y.fract() != 0.0; - let delta = if modifiers.shift { Vec2::new(delta.x + delta.y, 0.0) } else { *delta }; - if !delta.is_finite() { - continue; - } - match unit { - egui::MouseWheelUnit::Point => out.precise += delta, - egui::MouseWheelUnit::Line => { - let mut points = delta.clamp(Vec2::splat(-MAX_EVENT_UNITS), Vec2::splat(MAX_EVENT_UNITS)) * line_points; - if single_paging { - points.y = 0.0; - } - if direct_x { - out.precise.x += points.x; - } else { - out.line.x += points.x; - } - if direct_y { - out.precise.y += points.y; - } else { - out.line.y += points.y; - } - } - egui::MouseWheelUnit::Page => { - out.page.x += delta.x.clamp(-MAX_EVENT_UNITS, MAX_EVENT_UNITS); - out.page.y += delta.y.clamp(-MAX_EVENT_UNITS, MAX_EVENT_UNITS); - } - } - } - // Bound batched events before acceleration is applied. - out.precise = cap_frame(out.precise); - out.line = cap_frame(out.line); - out.page = cap_frame(out.page); - out -} - -/// Converts the frame total to the accelerated surplus. -/// -/// The caller adds this to the base distance before passing the whole coarse -/// bucket to `Motion`, so an isolated notch adds no surplus. -/// Each axis advances once per frame; events batched into one frame cannot -/// accelerate one another. Output is frame-capped. -pub(crate) fn boost_extra(input: FrameInput, boost_x: &mut WheelBoost, boost_y: &mut WheelBoost, now: f64) -> Vec2 { - let mut extra = Vec2::ZERO; - if input.line.x != 0.0 && input.line.x.is_finite() { - extra.x += input.line.x * (boost_x.multiplier(now, input.line.x) - 1.0); - } - if input.line.y != 0.0 && input.line.y.is_finite() { - extra.y += input.line.y * (boost_y.multiplier(now, input.line.y) - 1.0); - } - cap_frame(extra) -} - -/// Maps a non-finite or non-positive points-per-unit scale to zero. -fn sanitize_scale(points: f32) -> f32 { - if points.is_finite() && points > 0.0 { points } else { 0.0 } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Easing preserves distance and terminates at each tested refresh rate. - #[test] - fn whole_distance_eases_and_settles_at_each_frame_rate() { - for hz in [30, 60, 144] { - let dt = 1.0 / hz as f32; - let mut motion = Motion::default(); - let first = motion.step(egui::vec2(0.0, -600.0), 1.0, dt, true); - assert!(first.y < 0.0 && first.y > -600.0); - let mut total = first.y; - for frame in 1..=hz * 2 { - let delta = motion.step(Vec2::ZERO, 1.0 + f64::from(frame) / f64::from(hz), dt, true); - assert!(delta.y <= 0.0); - total += delta.y; - } - assert!((total + 600.0).abs() < 0.002, "{hz} Hz: {total}"); - assert!(!motion.has_pending()); - } - } - - /// Timing follows elapsed seconds rather than a fixed number of frames. - #[test] - fn equal_elapsed_time_consumes_the_same_share_at_different_cadences() { - let expected = 600.0 * (1.0 - 0.1_f32.powf(5.0 / 3.0)); - for hz in [30, 60, 144] { - let mut motion = Motion::default(); - let mut total = 0.0; - for frame in 0..hz / 6 { - let input = if frame == 0 { egui::vec2(600.0, 0.0) } else { Vec2::ZERO }; - total += motion.step(input, 1.0 + f64::from(frame) / f64::from(hz), 1.0 / hz as f32, true).x; - } - assert!((total - expected).abs() < 0.01, "{hz} Hz: {total} versus {expected}"); - } - } - - /// Reversing one axis preserves the other axis's admitted distance. - #[test] - fn motion_reversal_cancels_only_the_reversed_axis() { - let mut motion = Motion::default(); - motion.step(egui::vec2(120.0, -600.0), 1.0, 0.01, true); - let retained_x = motion.pending.x; - let delta = motion.step(egui::vec2(0.0, 100.0), 1.01, 0.01, true); - assert!(delta.x > 0.0 && delta.y > 0.0); - assert!((delta.x + motion.pending.x - retained_x).abs() < 0.001); - assert!((delta.y + motion.pending.y - 100.0).abs() < 0.001); - } - - /// An isolated base-plus-surplus burst can settle without losing its requested distance. - #[test] - fn transient_burst_above_one_output_frame_preserves_distance() { - for distance in [9600.0, 2.0 * MAX_FRAME_POINTS] { - let mut motion = Motion::default(); - let mut total = 0.0; - for frame in 0..120 { - let input = if frame == 0 { egui::vec2(0.0, -distance) } else { Vec2::ZERO }; - let output = motion.step(input, 1.0 + f64::from(frame) / 60.0, 1.0 / 60.0, true); - assert!(output.is_finite() && output.y.abs() <= MAX_FRAME_POINTS); - total += output.y; - } - assert!((total + distance).abs() < 0.02, "requested {distance}, delivered {total}"); - assert!(!motion.has_pending()); - } - } - - /// Direct input interrupts older motion, while a current mixed event still contributes. - #[test] - fn precise_axes_cancel_old_tail_without_dropping_current_coarse_input() { - let mut motion = Motion::default(); - motion.step(egui::vec2(200.0, -500.0), 1.0, 0.01, true); - let retained_x = motion.pending.x; - motion.cancel_axes(egui::vec2(0.0, 0.25)); - let delta = motion.step(egui::vec2(0.0, -80.0), 1.01, 0.01, true); - assert!((delta.x + motion.pending.x - retained_x).abs() < 0.001); - assert!((delta.y + motion.pending.y + 80.0).abs() < 0.001); - } - - /// Saturation limits per-frame work without silently losing admitted movement. - #[test] - fn saturated_motion_bounds_output_and_queue_without_losing_distance() { - let mut motion = Motion::default(); - let mut admitted = 0.0; - let mut emitted = 0.0; - for frame in 0..80 { - let input = if frame < 20 { MAX_FRAME_POINTS } else { 0.0 }; - admitted += input; - let delta = motion.step(egui::vec2(input, 0.0), 1.0 + f64::from(frame) * 0.01, 0.01, true); - assert!((0.0..=MAX_FRAME_POINTS).contains(&delta.x)); - assert!((0.0..=MAX_PENDING_POINTS).contains(&motion.pending.x)); - emitted += delta.x; - assert!((admitted - emitted - motion.pending.x).abs() < 0.1); - } - } - - /// Sustained arrival above service capacity drops excess only at the finite admission boundary. - #[test] - fn sustained_double_frame_input_keeps_a_finite_queue_and_output() { - let mut motion = Motion::default(); - let mut requested = 0.0; - let mut admitted = 0.0; - let mut emitted = 0.0; - for frame in 0..160 { - let input = if frame < 20 { MAX_MOTION_INPUT_POINTS } else { 0.0 }; - let previous = motion.pending.x; - let total = (previous + input).min(MAX_PENDING_POINTS + MAX_FRAME_POINTS); - requested += input; - admitted += total - previous; - let output = motion.step(egui::vec2(input, -input), 1.0 + f64::from(frame) * 0.01, 0.01, true); - emitted += output.x; - assert!((0.0..=MAX_FRAME_POINTS).contains(&output.x)); - assert!((0.0..=MAX_PENDING_POINTS).contains(&motion.pending.x)); - assert_eq!(output.y, -output.x); - assert_eq!(motion.pending.y, -motion.pending.x); - assert!((output.x + motion.pending.x - total).abs() < 0.003); - assert!((admitted - emitted - motion.pending.x).abs() < 0.15); - } - assert!(requested > admitted, "a sustained overload must not create an unlimited queue"); - assert!((emitted - admitted).abs() < 0.15); - assert!(!motion.has_pending()); - } - - /// Input admission permits two output frames, while each emitted step stays independently bounded. - #[test] - fn oversized_motion_input_is_limited_before_entering_the_queue() { - for animate in [false, true] { - let mut motion = Motion::default(); - let mut delivered = 0.0; - for frame in 0..120 { - let input = if frame == 0 { egui::vec2(4.0 * MAX_FRAME_POINTS, 0.0) } else { Vec2::ZERO }; - let output = motion.step(input, 1.0 + f64::from(frame) / 60.0, 1.0 / 60.0, animate); - assert!(output.x <= MAX_FRAME_POINTS); - assert!(motion.pending.x <= MAX_PENDING_POINTS); - delivered += output.x; - } - assert!((delivered - MAX_MOTION_INPUT_POINTS).abs() < 0.02, "animations {animate}: {delivered}"); - assert!(!motion.has_pending()); - } - } - - /// A non-finite clock neither resumes old movement nor emits an oversized fresh step. - #[test] - fn invalid_clock_limits_a_fresh_burst_without_retaining_it() { - for now in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let mut motion = Motion::default(); - motion.step(egui::vec2(100.0, 100.0), 1.0, 0.01, true); - let output = motion.step(egui::vec2(MAX_MOTION_INPUT_POINTS, -MAX_MOTION_INPUT_POINTS), now, 0.01, true); - assert_eq!(output, egui::vec2(MAX_FRAME_POINTS, -MAX_FRAME_POINTS)); - assert!(!motion.has_pending()); - assert_eq!(motion.step(Vec2::ZERO, 2.0, 0.01, true), Vec2::ZERO); - } - } - - /// Turning animation off drains owed movement under the same output cap. - #[test] - fn disabling_animation_preserves_owed_distance_with_a_bounded_flush() { - let mut motion = Motion::default(); - let first = motion.step(egui::vec2(MAX_FRAME_POINTS, 0.0), 1.0, 0.01, true); - let second = motion.step(egui::vec2(MAX_FRAME_POINTS, 0.0), 1.01, 0.01, false); - assert_eq!(second.x, MAX_FRAME_POINTS); - let last = motion.step(Vec2::ZERO, 1.02, 0.01, false); - assert!((first.x + second.x + last.x - 2.0 * MAX_FRAME_POINTS).abs() < 0.002); - assert!(!motion.has_pending()); - assert_eq!(motion.step(egui::vec2(0.0, -100.0), 1.03, 0.01, false), egui::vec2(0.0, -100.0)); - assert!(!motion.has_pending()); - } - - /// Invalid input or a discontinuous clock cannot retain an unbounded or stale tail. - #[test] - fn reset_clock_gaps_and_invalid_values_cannot_reanimate_old_motion() { - for next in [0.5, 2.0, f64::NAN, f64::INFINITY] { - let mut motion = Motion::default(); - motion.step(egui::vec2(100.0, -200.0), 1.0, 0.01, true); - assert_eq!(motion.step(Vec2::ZERO, next, 0.01, true), Vec2::ZERO); - assert!(!motion.has_pending()); - } - for dt in [f32::NAN, f32::INFINITY, -1.0, 0.0, 1e9] { - let mut motion = Motion::default(); - let delta = motion.step(egui::vec2(100.0, f32::NAN), 1.0, dt, true); - assert!(delta.x.is_finite() && delta.x > 0.0 && delta.x < 100.0); - assert_eq!(delta.y, 0.0); - motion.reset(); - assert!(!motion.has_pending()); - } - } - - /// Normalization cannot hide fractional motion by clamping or combining its axes. - #[test] - fn fractional_lines_are_direct_before_clamping_or_axis_folding() { - use egui::MouseWheelUnit::Line; - let input = accumulate(&[wheel(Line, 0.0, -10.5), shifted(Line, 0.5, 0.5)], 100.0, false); - assert_eq!(input.precise, egui::vec2(100.0, -1000.0)); - assert_eq!(input.line, Vec2::ZERO); - let events: [egui::Event; 4] = core::array::from_fn(|_| wheel(Line, 0.0, -0.25)); - let input = accumulate(&events, 100.0, false); - assert_eq!(input.precise.y, -100.0); - } - - /// Source hints and partial-notch distances each independently select direct movement. - #[test] - fn known_continuous_sources_are_direct_even_for_integral_lines() { - for source in [egui::MouseWheelSource::Trackpad, egui::MouseWheelSource::Momentum] { - let mut event = wheel(egui::MouseWheelUnit::Line, 0.0, -1.0); - if let egui::Event::MouseWheel { source: slot, .. } = &mut event { - *slot = source; - } - let input = accumulate(&[event], 100.0, false); - assert_eq!(input.precise, egui::vec2(0.0, -100.0)); - assert_eq!(input.line, Vec2::ZERO); - let diagonal = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Line, - delta: egui::vec2(0.25, -1.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source, - }; - let input = accumulate(&[diagonal], 100.0, false); - assert_eq!(input.precise, egui::vec2(25.0, -100.0)); - assert_eq!(input.line, Vec2::ZERO); - } - let mut event = wheel(egui::MouseWheelUnit::Line, 0.0, -0.25); - if let egui::Event::MouseWheel { source, .. } = &mut event { - *source = egui::MouseWheelSource::Wheel; - } - assert_eq!(accumulate(&[event], 100.0, false).precise, egui::vec2(0.0, -25.0)); - } - - /// A fractional horizontal component does not change a vertical notch's distance policy. - #[test] - fn diagonal_fraction_keeps_the_other_axis_coarse() { - use egui::MouseWheelUnit::Line; - for source in [egui::MouseWheelSource::Unknown, egui::MouseWheelSource::Wheel] { - let mut diagonal = wheel(Line, 0.25, -1.0); - if let egui::Event::MouseWheel { source: slot, .. } = &mut diagonal { - *slot = source; - } - let mut bx = WheelBoost::default(); - let mut by = WheelBoost::default(); - let mut reference_bx = WheelBoost::default(); - let mut reference_by = WheelBoost::default(); - let mut motion = Motion::default(); - let mut reference_motion = Motion::default(); - for frame in 0..90 { - let (input, reference) = if frame < 12 { - let input = accumulate(std::slice::from_ref(&diagonal), 100.0, false); - assert_eq!(input.precise, egui::vec2(25.0, 0.0), "{source:?}: only the fractional axis is direct"); - assert_eq!(input.line, egui::vec2(0.0, -100.0)); - (input, accumulate(&[wheel(Line, 0.0, -1.0)], 100.0, false)) - } else { - (FrameInput::default(), FrameInput::default()) - }; - let now = 1.0 + f64::from(frame) / 60.0; - let coarse = input.line + boost_extra(input, &mut bx, &mut by, now); - let reference_coarse = reference.line + boost_extra(reference, &mut reference_bx, &mut reference_by, now); - motion.cancel_axes(input.precise); - reference_motion.cancel_axes(reference.precise); - assert_eq!(coarse, reference_coarse, "{source:?}: the vertical burst remains unchanged"); - assert_eq!(motion.step(coarse, now, 1.0 / 60.0, true), reference_motion.step(reference_coarse, now, 1.0 / 60.0, true)); - } - if let egui::Event::MouseWheel { delta, .. } = &mut diagonal { - *delta = egui::vec2(1.0, -0.25); - } - let transposed = accumulate(&[diagonal], 100.0, false); - assert_eq!(transposed.precise, egui::vec2(0.0, -25.0)); - assert_eq!(transposed.line, egui::vec2(100.0, 0.0)); - } - } - - /// Coarse and direct events in one frame keep their respective distance policies. - #[test] - fn mixed_coarse_and_direct_events_retain_both_buckets() { - use egui::MouseWheelUnit::{Line, Point}; - let input = accumulate(&[wheel(Line, 0.0, -1.0), wheel(Line, 0.0, -0.25), wheel(Point, 2.0, -3.0)], 100.0, false); - assert_eq!(input.line, egui::vec2(0.0, -100.0)); - assert_eq!(input.precise, egui::vec2(2.0, -28.0)); - let input = accumulate(&[wheel(Line, 2.0, -0.25)], 100.0, true); - assert_eq!(input.precise, Vec2::ZERO); - assert_eq!(input.line, egui::vec2(200.0, 0.0)); - } - - #[test] - fn single_and_slow_notches_stay_unboosted() { - let mut b = WheelBoost::default(); - assert_eq!(b.multiplier(0.0, -1.0), 1.0); - assert_eq!(b.multiplier(0.5, -1.0), 1.0); - assert_eq!(b.multiplier(1.0, -1.0), 1.0); - } - - #[test] - fn fast_spin_accelerates_then_caps() { - let mut b = WheelBoost::default(); - assert_eq!(b.multiplier(1.0, -1.0), 1.0); - let mut last = 1.0; - for (i, t) in (1..=20).map(|i| 1.0 + f64::from(i) * 0.02).enumerate() { - last = b.multiplier(t, -1.0); - if i < 2 { - assert!(last >= 1.0, "early burst must not jump, got {last}"); - } - } - assert!(last > 2.0, "a sustained fast spin must accelerate, got {last}"); - assert!(last <= MAX_BOOST, "boost must be capped, got {last}"); - assert_eq!(last, MAX_BOOST, "a long spin should reach the ceiling"); - for i in 1..=20 { - let m = b.multiplier(1.5 + f64::from(i) * 0.02, -1.0); - assert!(m <= MAX_BOOST, "boost must stay capped, got {m}"); - } - } - - #[test] - fn reversal_and_idle_reset_the_burst() { - let mut b = WheelBoost::default(); - b.multiplier(1.0, -1.0); - for i in 1..=6 { - b.multiplier(1.0 + f64::from(i) * 0.02, -1.0); - } - let boosted = b.multiplier(1.0 + 7.0 * 0.02, -1.0); - assert!(boosted > 1.0, "precondition: burst is boosted, got {boosted}"); - assert_eq!(b.multiplier(1.0 + 8.0 * 0.02, 1.0), 1.0); - for i in 9..=14 { - b.multiplier(1.0 + f64::from(i) * 0.02, 1.0); - } - assert_eq!(b.multiplier(5.0, 1.0), 1.0); - } - - #[test] - fn invalid_input_never_boosts_or_corrupts() { - let mut b = WheelBoost::default(); - for bad_now in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - assert_eq!(b.multiplier(bad_now, -1.0), 1.0); - } - for bad_motion in [0.0, -0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert_eq!(b.multiplier(1.0, bad_motion), 1.0); - } - assert_eq!(b.multiplier(2.0, -1.0), 1.0); - b.reset(); - assert_eq!(b.multiplier(3.0, -1.0), 1.0); - } - - #[test] - fn same_timestamp_events_count_as_a_burst() { - let mut b = WheelBoost::default(); - assert_eq!(b.multiplier(1.0, -1.0), 1.0); - for _ in 0..6 { - b.multiplier(1.0, -1.0); - } - assert!(b.multiplier(1.0, -1.0) > 1.0); - } - - #[test] - fn fractional_notches_share_the_burst() { - let mut b = WheelBoost::default(); - b.multiplier(1.0, -0.25); - for i in 1..=8 { - b.multiplier(1.0 + f64::from(i) * 0.02, -0.25); - } - assert!(b.multiplier(1.0 + 9.0 * 0.02, -0.25) > 1.0); - } - - #[test] - fn sleep_wake_resets_the_burst() { - let mut b = WheelBoost::default(); - b.multiplier(1.0, -1.0); - for i in 1..=6 { - b.multiplier(1.0 + f64::from(i) * 0.02, -1.0); - } - assert_eq!(b.multiplier(3600.0, -1.0), 1.0); - } - - #[test] - fn backwards_time_resets_without_corrupting() { - let mut b = WheelBoost::default(); - b.multiplier(1.0, -1.0); - b.multiplier(1.02, -1.0); - assert_eq!(b.multiplier(0.5, -1.0), 1.0); - assert_eq!(b.multiplier(0.52, -1.0), 1.4); - } - - #[test] - fn unhurried_spin_decays() { - let mut b = WheelBoost::default(); - b.multiplier(1.0, -1.0); - for i in 1..=8 { - b.multiplier(1.0 + f64::from(i) * 0.02, -1.0); - } - let peak = b.multiplier(1.0 + 9.0 * 0.02, -1.0); - assert!(peak > 1.0); - // Same direction but slower than the fast gap: each event sheds one tick. - let mut prev = peak; - for i in 10..=13 { - let m = b.multiplier(1.0 + f64::from(i) * 0.15, -1.0); - assert!(m <= prev, "decay must not grow: {m} > {prev}"); - prev = m; - } - } - - #[test] - fn hysteresis_holds_the_ceiling_briefly() { - let mut b = WheelBoost::default(); - let mut t = 1.0; - b.multiplier(t, -1.0); - for _ in 0..20 { - t += 0.02; - b.multiplier(t, -1.0); - } - assert_eq!(b.multiplier(t + 0.02, -1.0), MAX_BOOST); - // A couple of unhurried events consume hysteresis before output falls. - t += 0.15; - assert_eq!(b.multiplier(t, -1.0), MAX_BOOST); - t += 0.15; - assert_eq!(b.multiplier(t, -1.0), MAX_BOOST); - } - - #[test] - fn frame_cap_bounds_each_axis() { - use egui::vec2; - assert_eq!(cap_frame(vec2(40.0, -40.0)), vec2(40.0, -40.0)); - assert_eq!(cap_frame(vec2(1e9, -1e9)), vec2(MAX_FRAME_POINTS, -MAX_FRAME_POINTS)); - assert_eq!(cap_frame(vec2(f32::NAN, 40.0)), vec2(0.0, 40.0)); - assert_eq!(cap_frame(vec2(40.0, f32::INFINITY)), vec2(40.0, 0.0)); - } - - fn wheel(unit: egui::MouseWheelUnit, dx: f32, dy: f32) -> egui::Event { - egui::Event::MouseWheel { - unit, - delta: egui::vec2(dx, dy), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - } - } - - fn shifted(unit: egui::MouseWheelUnit, dx: f32, dy: f32) -> egui::Event { - egui::Event::MouseWheel { - unit, - delta: egui::vec2(dx, dy), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::SHIFT, - source: egui::MouseWheelSource::Unknown, - } - } - - #[test] - fn isolated_notch_adds_no_extra() { - use egui::MouseWheelUnit::Line; - for base in [50.0, 100.0, 200.0, 40.0, 8.0] { - let input = accumulate(&[wheel(Line, 0.0, -1.0)], base, false); - assert_eq!(input.line, egui::vec2(0.0, -base)); - let mut bx = WheelBoost::default(); - let mut by = WheelBoost::default(); - assert_eq!(boost_extra(input, &mut bx, &mut by, 1.0), egui::Vec2::ZERO); - } - } - - #[test] - fn fast_spin_adds_a_bounded_extra() { - use egui::MouseWheelUnit::Line; - let mut bx = WheelBoost::default(); - let mut by = WheelBoost::default(); - let mut peak = 0.0f32; - for i in 0..20 { - let input = accumulate(&[wheel(Line, 0.0, -1.0)], 100.0, false); - let extra = boost_extra(input, &mut bx, &mut by, 1.0 + f64::from(i) * 0.02); - assert!(extra.y <= 0.0, "extra follows the spin direction, got {extra:?}"); - peak = peak.min(extra.y); - } - assert!(peak < 0.0, "a sustained spin must add an extra"); - assert!(peak >= -MAX_FRAME_POINTS, "extra stays frame-capped, got {peak}"); - } - - #[test] - fn point_and_page_events_stay_out_of_the_line_boost() { - use egui::{MouseWheelUnit::Line, MouseWheelUnit::Page, MouseWheelUnit::Point}; - let input = accumulate(&[wheel(Page, 0.0, -1.0), wheel(Point, 0.0, -30.0)], 100.0, false); - assert_eq!(input.precise, egui::vec2(0.0, -30.0)); - assert_eq!(input.page, egui::vec2(0.0, -1.0)); - assert_eq!(input.line, egui::Vec2::ZERO); - let input = accumulate(&[wheel(Line, 0.0, -1.0), wheel(Page, 0.0, -1.0)], 100.0, false); - assert_eq!(input.line, egui::vec2(0.0, -100.0)); - assert_eq!(input.page, egui::vec2(0.0, -1.0)); - let mut bx = WheelBoost::default(); - let mut by = WheelBoost::default(); - assert_eq!(boost_extra(input, &mut bx, &mut by, 1.0), egui::Vec2::ZERO); - } - - #[test] - fn single_paging_drops_vertical_keeps_horizontal() { - use egui::MouseWheelUnit::Line; - let input = accumulate(&[wheel(Line, 5.0, -1.0)], 100.0, true); - assert_eq!(input.line, egui::vec2(500.0, 0.0)); - } - - #[test] - fn shift_merges_into_horizontal() { - use egui::MouseWheelUnit::{Line, Page}; - let input = accumulate(&[shifted(Line, 1.0, -2.0)], 100.0, false); - assert_eq!(input.line, egui::vec2(-100.0, 0.0)); - let input = accumulate(&[shifted(Page, 1.0, -2.0)], 100.0, false); - assert_eq!(input.page, egui::vec2(-1.0, 0.0)); - } - - /// Check that NaN, zero, negative or infinite scales and non-wheel events add nothing. - #[test] - fn invalid_scales_and_events_contribute_nothing() { - use egui::MouseWheelUnit::Line; - for bad in [f32::NAN, 0.0, -10.0, f32::INFINITY] { - let input = accumulate(&[wheel(Line, 0.0, -1.0)], bad, false); - assert_eq!(input.line, egui::Vec2::ZERO, "line scale {bad}"); - } - let zoom = egui::Event::MouseWheel { - unit: Line, - delta: egui::vec2(0.0, -1.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::COMMAND, - source: egui::MouseWheelSource::Unknown, - }; - let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let input = accumulate(&[zoom, key, wheel(Line, 0.0, f32::NAN)], 100.0, false); - assert_eq!(input, FrameInput::default()); - } -} diff --git a/crates/ui-egui/src/canvas/wheel_pager.rs b/crates/ui-egui/src/canvas/wheel_pager.rs deleted file mode 100644 index c8ce69c57d..0000000000 --- a/crates/ui-egui/src/canvas/wheel_pager.rs +++ /dev/null @@ -1,347 +0,0 @@ -//! Wheel paging in single-page view: when the whole page fits, the mouse wheel and the -//! trackpad turn pages instead of doing nothing. -//! -//! A wheel notch turns one page, however fast the notches come. That needs the raw -//! `MouseWheel` events: egui's smoothed scroll delta spreads one notch over several frames, so -//! notches in quick succession blur together. Smooth input (trackpads, high-resolution wheels) -//! turns one page per gesture and direction once it has moved as far as a notch scrolls. A -//! gesture is a touch from [`TouchPhase::Start`] to `End`, together with the momentum phase -//! the OS sends after it (macOS and Wayland report touch phases), or, without phases, a burst -//! of input with no pause longer than `BURST_GAP_SECS`. - -use egui::{MouseWheelUnit, TouchPhase}; - -/// One wheel notch, in points (egui's default desktop `line_scroll_speed`, fixed so paging -/// doesn't change with the scroll speed preference). Smooth input turns a page once it has -/// moved this far, so a light swipe turns and resting fingers don't; smooth line deltas count -/// this many points per line. -const NOTCH_POINTS: f32 = 40.0; -/// A phase-less point delta at least this big is a wheel notch: egui draws the same line -/// between wheel steps, which it smooths, and trackpad input, which it passes through. -const MIN_NOTCH_POINTS: f32 = 8.0; -/// Phase-less smooth input belongs to one gesture until it pauses this long, in seconds (egui -/// uses the same gap to decide that such a scroll has ended). -const BURST_GAP_SECS: f64 = 0.15; -/// A big point delta this soon (seconds) after another wheel event belongs to a fast trackpad -/// stream, not to a separate notch. -const DENSE_GAP_SECS: f64 = 0.02; -/// The OS starts its momentum phase this soon (seconds) after the finger lifts, so a touch -/// starting sooner continues the swipe rather than starting another. -const MOMENTUM_GAP_SECS: f64 = 0.1; -/// A touch with no events for this long (seconds) has ended unseen: its `End` went elsewhere. -const TOUCH_STALE_SECS: f64 = 1.0; - -/// The touch in progress. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Touch { - Finger, - /// The momentum phase after a finger touch: still the same swipe. - Momentum, -} - -/// Turns wheel and trackpad input into page turns; see the module docs. -pub(crate) struct WheelPager { - /// Smooth motion toward the next turn, in points (negative scrolls forward). - accum: f32, - /// The way the current gesture already turned (`true` = forward). - turned: Option, - /// The touch in progress, on platforms that report touch phases. - touch: Option, - /// When the last finger touch ended, so its momentum phase can be recognised. - finger_up: Option, - /// egui time of the last wheel event. - last_event: f64, - /// egui time of the last smooth (non-notch) motion. - last_smooth: f64, - /// The current smooth gesture already panned the page (edge paging only): it must end - /// before it can turn, so momentum that carries the view to the page's edge doesn't go on - /// to turn the page. - panned: bool, -} - -impl Default for WheelPager { - fn default() -> Self { - // Infinitely long ago, so the first event never looks like part of a stream. - Self { accum: 0.0, turned: None, touch: None, finger_up: None, last_event: f64::NEG_INFINITY, last_smooth: f64::NEG_INFINITY, panned: false } - } -} - -impl WheelPager { - /// Drop partial motion toward a turn (the view moved elsewhere). The gesture goes on: a - /// swipe that already turned doesn't turn again after a jump. - pub(crate) fn clear_motion(&mut self) { - self.accum = 0.0; - } - - /// Reset any turned state when a turn did not happen (e.g. at document boundary). - pub(crate) fn unturn(&mut self) { - self.turned = None; - } - - /// Whether the current gesture already turned a page: the rest of it must not pan the page - /// just shown away from its top (or bottom). - pub(crate) fn gesture_turned(&self) -> bool { - self.turned.is_some() - } - - /// Feed one `Event::MouseWheel`: `dy` is its vertical delta (negative scrolls forward) and - /// `now` is egui time. With `can_turn` false (the page doesn't fit, a dialog is open…) the - /// gesture is followed but never turns. Returns the way to turn (`true` = forward). - pub(crate) fn feed(&mut self, unit: MouseWheelUnit, dy: f32, phase: TouchPhase, now: f64, can_turn: bool) -> Option { - self.feed_inner(unit, dy, phase, now, can_turn, false) - } - - /// Like [`Self::feed`], for a page taller than the window, where `can_turn` means the view - /// is at the edge the motion pushes against. A smooth gesture that panned the page first - /// doesn't turn it: the user lifts and swipes again (a wheel notch still turns at once). - pub(crate) fn feed_edge(&mut self, unit: MouseWheelUnit, dy: f32, phase: TouchPhase, now: f64, can_turn: bool) -> Option { - self.feed_inner(unit, dy, phase, now, can_turn, true) - } - - fn feed_inner(&mut self, unit: MouseWheelUnit, dy: f32, phase: TouchPhase, now: f64, can_turn: bool, edge: bool) -> Option { - if !now.is_finite() { - return None; - } - let idle = now - self.last_event; - self.last_event = now; - if idle > TOUCH_STALE_SECS { - self.touch = None; - } - match phase { - TouchPhase::Start => { - let momentum = self.finger_up.take().is_some_and(|up| now - up <= MOMENTUM_GAP_SECS); - self.touch = Some(if momentum { Touch::Momentum } else { Touch::Finger }); - if !momentum { - self.new_gesture(); - } - None - } - TouchPhase::End | TouchPhase::Cancel => { - // Only a finger touch is followed by momentum. - self.finger_up = (self.touch == Some(Touch::Finger)).then_some(now); - self.touch = None; - None - } - TouchPhase::Move => self.motion(unit, dy, now, idle, can_turn, edge), - } - } - - fn new_gesture(&mut self) { - self.accum = 0.0; - self.turned = None; - self.panned = false; - } - - fn motion(&mut self, unit: MouseWheelUnit, dy: f32, now: f64, idle: f64, can_turn: bool, edge: bool) -> Option { - if !dy.is_finite() || dy == 0.0 { - return None; - } - let forward = dy < 0.0; - let smooth_stream = self.touch.is_some() || now - self.last_smooth <= BURST_GAP_SECS; - let notch = !smooth_stream - && match unit { - // macOS reports precise devices in points, so its line deltas are wheel notches, - // however small its acceleration makes them. Elsewhere a fraction of a line is - // touchpad motion. - MouseWheelUnit::Line => cfg!(target_os = "macos") || dy.abs() >= 1.0, - MouseWheelUnit::Page => true, - MouseWheelUnit::Point => dy.abs() >= MIN_NOTCH_POINTS && idle >= DENSE_GAP_SECS, - }; - if notch { - if !can_turn { - // A notch is a gesture of its own, so one that only pans ends the gesture a - // previous notch turned; otherwise `gesture_turned` keeps swallowing the wheel (#5713). - self.turned = None; - return None; - } - // Every notch turns a page; a smooth tail of the same gesture won't add another. - self.accum = 0.0; - self.turned = Some(forward); - return Some(forward); - } - if self.touch.is_none() && idle > BURST_GAP_SECS { - self.new_gesture(); - } - self.last_smooth = now; - if !can_turn { - // Panning a page that doesn't fit: that motion must not count toward a turn later. - self.accum = 0.0; - self.panned |= edge; - return None; - } - if self.panned { - return None; - } - if self.turned == Some(forward) { - return None; - } - let points = if unit == MouseWheelUnit::Point { dy } else { dy * NOTCH_POINTS }; - // One event never counts for more than a turn, which also bounds hostile deltas. Net - // motion counts, so trackpad jitter cancels out. - self.accum += points.clamp(-NOTCH_POINTS, NOTCH_POINTS); - if self.accum.abs() < NOTCH_POINTS { - return None; - } - self.accum = 0.0; - self.turned = Some(forward); - Some(forward) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use MouseWheelUnit::{Line, Point}; - use TouchPhase::{End, Move, Start}; - - /// Feeds `(unit, dy, phase, seconds)` events and returns the turns, in order. - fn turns(pager: &mut WheelPager, events: &[(MouseWheelUnit, f32, TouchPhase, f64)]) -> Vec { - events.iter().filter_map(|&(unit, dy, phase, at)| pager.feed(unit, dy, phase, at, true)).collect() - } - - /// A trackpad swipe at 60 fps from `t`: six finger frames of `dy`, then momentum decaying - /// to nothing, as macOS reports it (each phase its own Start…End). - fn swipe(t: f64, dy: f32) -> Vec<(MouseWheelUnit, f32, TouchPhase, f64)> { - let frame = 1.0 / 60.0; - let mut events = vec![(Point, 0.0, Start, t)]; - let mut at = t; - for _ in 0..6 { - at += frame; - events.push((Point, dy, Move, at)); - } - events.extend([(Point, 0.0, End, at), (Point, 0.0, Start, at)]); - let mut d = dy; - while d.abs() > 0.5 { - at += frame; - events.push((Point, d, Move, at)); - d *= 0.92; - } - events.push((Point, 0.0, End, at)); - events - } - - #[test] - fn every_notch_turns_one_page_however_fast() { - let mut p = WheelPager::default(); - // A brisk spin: five notches 50 ms apart, then one back. - let mut events: Vec<_> = (0..5).map(|i| (Line, -1.0, Move, 1.0 + f64::from(i) * 0.05)).collect(); - events.push((Line, 1.0, Move, 1.5)); - assert_eq!(turns(&mut p, &events), [true, true, true, true, true, false]); - // Pixel-unit wheels (a Logitech mouse on a Mac reports ~14 points a notch). - assert_eq!(turns(&mut p, &[(Point, -14.0, Move, 3.0), (Point, -14.0, Move, 3.1)]), [true, true]); - } - - #[test] - fn a_swipe_turns_one_page_momentum_included() { - let mut p = WheelPager::default(); - assert_eq!(turns(&mut p, &swipe(1.0, -25.0)), [true]); - // A slow, steady scroll is one gesture too. - let mut slow = vec![(Point, 0.0, Start, 3.0)]; - slow.extend((1..=60).map(|i| (Point, -3.0, Move, 3.0 + f64::from(i) / 60.0))); - slow.push((Point, 0.0, End, 4.0)); - assert_eq!(turns(&mut p, &slow), [true]); - // Resting fingers that drift a little don't turn. - let nudge: Vec<_> = [(Point, 0.0, Start, 6.0)].into_iter().chain((1..=5).map(|i| (Point, -2.0, Move, 6.0 + f64::from(i) / 60.0))).collect(); - assert!(turns(&mut p, &nudge).is_empty()); - } - - #[test] - fn each_new_swipe_turns_again_even_during_momentum() { - let mut p = WheelPager::default(); - let mut events = swipe(1.0, -25.0); - // Touching the trackpad again ends the momentum at once (End) and starts a new finger - // touch: the first swipe's momentum is over, so the second swipe turns. - let cut = events.iter().position(|e| e.3 > 1.3).unwrap(); - events.truncate(cut); - let t = events.last().unwrap().3; - events.push((Point, 0.0, End, t)); - events.extend(swipe(t, -25.0)); - assert_eq!(turns(&mut p, &events), [true, true]); - } - - #[test] - fn reversing_mid_gesture_turns_back_but_jitter_does_not() { - let mut p = WheelPager::default(); - let mut events = vec![(Point, 0.0, Start, 1.0), (Point, -45.0, Move, 1.02)]; - // Jitter right after the turn neither turns back nor re-arms the forward turn. - events.extend([(Point, 2.0, Move, 1.04), (Point, -20.0, Move, 1.06), (Point, -20.0, Move, 1.08)]); - // A deliberate push the other way turns back, once. - events.extend([(Point, 25.0, Move, 1.10), (Point, 25.0, Move, 1.12), (Point, 25.0, Move, 1.14)]); - assert_eq!(turns(&mut p, &events), [true, false]); - } - - #[test] - fn phase_less_streams_turn_once_per_burst() { - // Web and some touchpads send no touch phases: small dense deltas, possibly big ones - // in a fast flick, all one gesture until the input pauses. - let mut p = WheelPager::default(); - let mut burst: Vec<_> = (0..30).map(|i| (Point, -5.0, Move, 1.0 + f64::from(i) * 0.008)).collect(); - burst.extend((0..10).map(|i| (Point, -30.0, Move, 1.3 + f64::from(i) * 0.008))); - assert_eq!(turns(&mut p, &burst), [true]); - // A burst that starts big is one gesture too. - let fast: Vec<_> = (0..20).map(|i| (Point, -30.0, Move, 3.0 + f64::from(i) * 0.008)).collect(); - assert_eq!(turns(&mut p, &fast), [true]); - // After a pause, the next burst turns again. - let next: Vec<_> = (0..20).map(|i| (Point, -5.0, Move, 4.0 + f64::from(i) * 0.008)).collect(); - assert_eq!(turns(&mut p, &next), [true]); - } - - #[cfg(not(target_os = "macos"))] - #[test] - fn fractional_lines_are_touchpad_motion_off_macos() { - // Windows and X11 touchpads report many small line deltas. - let mut p = WheelPager::default(); - let stream: Vec<_> = (0..40).map(|i| (Line, -0.1, Move, 1.0 + f64::from(i) * 0.008)).collect(); - assert_eq!(turns(&mut p, &stream), [true]); - } - - #[test] - fn nothing_turns_while_it_cannot_and_that_motion_does_not_count_later() { - let mut p = WheelPager::default(); - assert_eq!(p.feed(Line, -1.0, Move, 1.0, false), None); - assert_eq!(p.feed(Point, 0.0, Start, 2.0, false), None); - assert_eq!(p.feed(Point, -30.0, Move, 2.02, false), None); - // The page fits now: the same touch has to move a full notch's worth again. - assert_eq!(p.feed(Point, -30.0, Move, 2.04, true), None); - assert_eq!(p.feed(Point, -30.0, Move, 2.06, true), Some(true)); - } - - #[test] - fn a_touch_whose_end_was_missed_expires() { - let mut p = WheelPager::default(); - assert!(turns(&mut p, &[(Point, 0.0, Start, 1.0)]).is_empty()); - // Seconds later a wheel notch is a notch again, not part of that touch. - assert_eq!(turns(&mut p, &[(Line, -1.0, Move, 3.0)]), [true]); - } - - #[test] - fn edge_paging_needs_a_gesture_that_did_not_pan() { - let mut p = WheelPager::default(); - // A swipe that pans first (not at the edge yet), then reaches it: no turn, momentum included. - let mut n = 0; - for (unit, dy, phase, at) in swipe(1.0, -25.0) { - n += usize::from(p.feed_edge(unit, dy, phase, at, at > 1.2).is_some()); - } - assert_eq!(n, 0); - // A fresh swipe that starts at the edge turns once. - let turned: Vec<_> = swipe(3.0, -25.0).into_iter().filter_map(|(u, dy, ph, at)| p.feed_edge(u, dy, ph, at, true)).collect(); - assert_eq!(turned, [true]); - // A wheel notch at the edge turns at once, even right after panning. - assert_eq!(p.feed_edge(Line, -1.0, Move, 5.0, false), None); - assert_eq!(p.feed_edge(Line, -1.0, Move, 5.3, true), Some(true)); - } - - #[test] - fn hostile_input_never_turns_more_than_once() { - let mut p = WheelPager::default(); - for dy in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -0.0] { - assert_eq!(p.feed(Point, dy, Move, 1.0, true), None, "dy={dy}"); - } - for now in [f64::NAN, f64::INFINITY] { - assert_eq!(p.feed(Point, -50.0, Move, now, true), None, "now={now}"); - } - // A huge notch is still one notch; a huge smooth delta is still one turn. - assert_eq!(turns(&mut p, &[(Point, -1e30, Move, 2.0)]), [true]); - assert_eq!(turns(&mut p, &[(Point, 0.0, Start, 3.0), (Point, -1e30, Move, 3.01), (Point, -1e30, Move, 3.02)]), [true]); - } -} diff --git a/crates/ui-egui/src/canvas/wheel_reset.rs b/crates/ui-egui/src/canvas/wheel_reset.rs deleted file mode 100644 index 5174dbfef3..0000000000 --- a/crates/ui-egui/src/canvas/wheel_reset.rs +++ /dev/null @@ -1,311 +0,0 @@ -//! Clear egui's retained copy of wheel input already owned by the document canvas. -//! -//! The reset precedes fresh events and all panels. Its synthetic event is hidden from app -//! motion routing; genuine input stays in its original order. No input is deferred or replayed. - -use egui::{Context, Event, Id, Modifiers, MouseWheelSource, MouseWheelUnit, Plugin, RawInput, TouchPhase, Ui, Vec2, ViewportId}; - -/// Schedule a reset of this viewport's hidden egui wheel state before its next frame. -pub(crate) fn consumed(ctx: &Context) { - let _ = ctx.plugin_or_default::(); - let key = pending(ctx.viewport_id()); - let frame = ctx.cumulative_frame_nr(); - ctx.data_mut(|data| data.insert_temp(key, frame)); -} - -/// Whether this viewport's old egui wheel state was reset at the start of the current pass. -pub(crate) fn reset_this_pass(ctx: &Context) -> bool { - let viewport = ctx.viewport_id(); - let pass = ctx.cumulative_pass_nr_for(viewport); - ctx.data(|data| data.get_temp::(applied(viewport)) == Some(pass)) -} - -/// Separates reset requests belonging to different native viewports. -fn pending(viewport: ViewportId) -> Id { - Id::unique(("pdfcraft-wheel-reset-pending", viewport)) -} - -/// Records whether this pass contains an internal reset that must be hidden from app routing. -fn injected(viewport: ViewportId) -> Id { - Id::unique(("pdfcraft-wheel-reset-injected", viewport)) -} - -/// Shares reset ownership with app wheel readers only during the pass that applied it. -fn applied(viewport: ViewportId) -> Id { - Id::unique(("pdfcraft-wheel-reset-applied", viewport)) -} - -/// A zero-distance cancellation clears egui's private wheel queue before fresh input arrives. -fn reset_event() -> Event { - Event::MouseWheel { - unit: MouseWheelUnit::Point, - delta: Vec2::ZERO, - phase: TouchPhase::Cancel, - modifiers: Modifiers::NONE, - source: MouseWheelSource::Unknown, - } -} - -/// Stateless plugin: per-viewport flags live in the context without retaining the context. -#[derive(Default)] -struct WheelReset; - -impl Plugin for WheelReset { - /// Identifies the input ownership hook in egui diagnostics. - fn debug_name(&self) -> &'static str { - "pdfcraft-wheel-reset" - } - - /// Cancel only the old wheel copy before egui processes this pass's fresh input. - fn input_hook(&mut self, ctx: &Context, raw: &mut RawInput) { - ctx.data_mut(|data| data.remove::(applied(raw.viewport_id))); - let key = pending(raw.viewport_id); - let Some(consumed_frame) = ctx.data(|data| data.get_temp::(key)) else { - return; - }; - // A flag can outlive a closed viewport. Create its replacement before querying the - // counter, and discard stale ownership if this viewport has not received input yet. - let initialized = ctx.viewport_for(raw.viewport_id, |viewport| viewport.input.raw.viewport_id == raw.viewport_id); - if !initialized { - ctx.data_mut(|data| data.remove::(key)); - return; - } - // run_pass snapshots begin-pass plugins before the frame, but refreshes input hooks - // on each discard pass. A lazily registered plugin must wait for the next frame. - if ctx.cumulative_frame_nr_for(raw.viewport_id) == consumed_frame { - return; - } - if raw.events.try_reserve(1).is_err() { - // Keep the pending flag so a later pass can retry without dropping fresh input. - return; - } - // Index zero is always valid; the fallible reservation above admits the extra event. - raw.events.insert(0, reset_event()); - ctx.data_mut(|data| { - data.remove::(key); - data.insert_temp(injected(raw.viewport_id), true); - }); - } - - /// Hide exactly our prepended reset before app motion or any panel inspects input events. - fn on_begin_pass(&mut self, ui: &mut Ui) { - let ctx = ui.ctx(); - let key = injected(ctx.viewport_id()); - let ours = ctx.data_mut(|data| data.remove_temp::(key).unwrap_or(false)); - if ours { - let removed = ctx.input_mut(|input| { - if input.events.first() == Some(&reset_event()) { - // The first-event check proves index zero exists and belongs to this reset. - input.events.remove(0); - true - } else { - false - } - }); - if removed { - let key = applied(ctx.viewport_id()); - let pass = ctx.cumulative_pass_nr(); - ctx.data_mut(|data| data.insert_temp(key, pass)); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use egui::{Pos2, Rect, vec2}; - - #[derive(Clone)] - struct Observed { - scroll: Vec2, - zoom: f32, - events: Vec, - reset: bool, - } - - fn context() -> Context { - let ctx = Context::default(); - ctx.options_mut(|options| { - options.max_passes = 3.try_into().unwrap(); - options.input_options.line_scroll_speed = 100.0; - }); - ctx - } - - fn wheel(unit: MouseWheelUnit, amount: f32, modifiers: Modifiers) -> Event { - Event::MouseWheel { unit, delta: vec2(0.0, amount), phase: TouchPhase::Move, source: MouseWheelSource::Unknown, modifiers } - } - - /// Run the actual hooks and input pipeline without an app raw-input hook. - fn frame(ctx: &Context, viewport: ViewportId, time: f64, events: Vec, consume: bool, passes: usize) -> Vec { - let mut raw = RawInput { - viewport_id: viewport, - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 800.0))), - time: Some(time), - predicted_dt: 1.0 / 60.0, - events, - ..Default::default() - }; - raw.viewports.entry(viewport).or_default(); - let mut observed = Vec::new(); - let output = ctx.run_ui(raw, |ui| { - let reset = reset_this_pass(ui.ctx()); - observed.push(ui.input(|input| Observed { - scroll: input.smooth_scroll_delta, - zoom: input.zoom_delta(), - events: input.events.clone(), - reset, - })); - if consume { - consumed(ui.ctx()); - // The canvas drains the public value after taking ownership of the raw wheel. - ui.input_mut(|input| input.smooth_scroll_delta = Vec2::ZERO); - } - if observed.len() < passes { - ui.ctx().request_discard("wheel reset multipass regression"); - } - }); - output.drop_without_applying_deltas(); - assert_eq!(observed.len(), passes); - observed - } - - /// Draining the public delta alone leaves a hidden tail; the plugin clears it before UI. - #[test] - fn consumed_wheel_does_not_leak_into_the_next_frame_elsewhere() { - let baseline = context(); - frame(&baseline, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], false, 1); - baseline.input_mut(|input| input.smooth_scroll_delta = Vec2::ZERO); - let elsewhere = vec![Event::PointerMoved(Pos2::new(10.0, 10.0))]; - assert!(frame(&baseline, ViewportId::ROOT, 1.0 / 60.0, elsewhere.clone(), false, 1)[0].scroll.y > 0.0); - - let reset = context(); - frame(&reset, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - let next = frame(&reset, ViewportId::ROOT, 1.0 / 60.0, elsewhere.clone(), false, 1); - assert_eq!(next[0].scroll, Vec2::ZERO); - assert_eq!(next[0].events, elsewhere); - } - - /// Resetting old motion preserves the complete distance of fresh Point and Line events. - #[test] - fn fresh_wheel_distance_is_preserved_after_the_reset() { - for (unit, amount, expected) in [(MouseWheelUnit::Point, 60.0, 60.0), (MouseWheelUnit::Line, 1.0, 100.0)] { - let ctx = context(); - frame(&ctx, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - let fresh = wheel(unit, amount, Modifiers::NONE); - let first = frame(&ctx, ViewportId::ROOT, 1.0 / 60.0, vec![fresh.clone()], false, 1); - assert_eq!(first[0].events, vec![fresh]); - let mut distance = first[0].scroll.y; - for index in 2..120 { - distance += frame(&ctx, ViewportId::ROOT, f64::from(index) / 60.0, Vec::new(), false, 1)[0].scroll.y; - } - assert!((distance - expected).abs() < 0.005, "{unit:?}: {distance}, expected {expected}"); - } - } - - /// A fresh Ctrl-wheel remains a zoom input after old non-zoom wheel state is cleared. - #[test] - fn fresh_ctrl_wheel_zoom_is_preserved() { - let ctx = context(); - frame(&ctx, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - let zoom = wheel(MouseWheelUnit::Point, 4.0, Modifiers::CTRL); - let next = frame(&ctx, ViewportId::ROOT, 1.0 / 60.0, vec![zoom.clone()], false, 1); - assert!(next[0].zoom > 1.0); - assert_eq!(next[0].scroll, Vec2::ZERO); - assert_eq!(next[0].events, vec![zoom]); - } - - /// A genuine zero-delta Cancel is retained, both with and without our preceding marker. - #[test] - fn genuine_cancel_events_are_not_removed() { - for schedule in [false, true] { - let ctx = context(); - let _ = ctx.plugin_or_default::(); - if schedule { - frame(&ctx, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - } - let events = vec![reset_event(), wheel(MouseWheelUnit::Point, 3.0, Modifiers::NONE)]; - let observed = frame(&ctx, ViewportId::ROOT, 1.0 / 60.0, events.clone(), false, 1); - assert_eq!(observed[0].events, events); - assert_eq!(observed[0].scroll.y, 3.0); - assert_eq!(observed[0].reset, schedule); - } - } - - /// Discard passes see no replay of wheel events or synthetic cancellation markers. - #[test] - fn discard_passes_do_not_replay_events_or_old_wheel_motion() { - let ctx = context(); - frame(&ctx, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - let fresh = wheel(MouseWheelUnit::Point, 4.0, Modifiers::NONE); - let passes = frame(&ctx, ViewportId::ROOT, 1.0 / 60.0, vec![fresh.clone()], false, 3); - assert_eq!(passes[0].events, vec![fresh]); - assert_eq!(passes[0].scroll.y, 4.0); - for pass in passes.iter().skip(1) { - assert!(pass.events.is_empty()); - assert_eq!(pass.scroll, Vec2::ZERO); - } - } - - /// Reset flags belong to a viewport, even when another viewport processes input first. - #[test] - fn another_viewport_does_not_consume_the_pending_reset() { - let ctx = context(); - let other = ViewportId::from_hash_of("wheel-reset-other"); - frame(&ctx, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - let other_events = vec![wheel(MouseWheelUnit::Point, 4.0, Modifiers::NONE)]; - let observed = frame(&ctx, other, 1.0 / 60.0, other_events.clone(), false, 1); - assert_eq!(observed[0].events, other_events); - assert_eq!(observed[0].scroll.y, 4.0); - assert!(ctx.data(|data| data.get_temp::(pending(ViewportId::ROOT)).is_some())); - let root = frame(&ctx, ViewportId::ROOT, 2.0 / 60.0, Vec::new(), false, 1); - assert_eq!(root[0].scroll, Vec2::ZERO); - assert!(root[0].events.is_empty()); - } - - /// First-use registration during a discarded pass must not expose the reset to later passes. - #[test] - fn first_consumed_frame_can_discard_without_exposing_the_reset() { - let ctx = context(); - let fresh = wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE); - let passes = frame(&ctx, ViewportId::ROOT, 0.0, vec![fresh.clone()], true, 3); - assert_eq!(passes[0].events, vec![fresh]); - for pass in passes.iter().skip(1) { - assert!(pass.events.is_empty(), "the newly registered input hook must not expose its reset before the begin-pass hook is active"); - } - let next = frame(&ctx, ViewportId::ROOT, 1.0 / 60.0, Vec::new(), false, 1); - assert_eq!(next[0].scroll, Vec2::ZERO); - assert!(next[0].events.is_empty()); - } - - /// App readers observe reset ownership only in the viewport and pass that applied it. - #[test] - fn reset_notification_is_scoped_to_the_pass_and_viewport() { - let ctx = context(); - let first = frame(&ctx, ViewportId::ROOT, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], true, 1); - assert!(!first[0].reset); - let other = ViewportId::from_hash_of("wheel-reset-notification-other"); - assert!(!frame(&ctx, other, 1.0 / 60.0, Vec::new(), false, 1)[0].reset); - let passes = frame(&ctx, ViewportId::ROOT, 2.0 / 60.0, Vec::new(), false, 3); - assert!(passes[0].reset); - assert!(passes.iter().skip(1).all(|pass| !pass.reset)); - assert!(!frame(&ctx, ViewportId::ROOT, 3.0 / 60.0, Vec::new(), false, 1)[0].reset); - } - - /// An old flag for a removed viewport must neither panic nor cancel a replacement's input. - #[test] - fn stale_reset_for_a_recreated_viewport_does_not_cancel_fresh_motion() { - let ctx = context(); - let other = ViewportId::from_hash_of("wheel-reset-recreated"); - let _ = ctx.plugin_or_default::(); - // Model the temporary flag surviving egui's removal of the old ViewportState. - ctx.data_mut(|data| data.insert_temp(pending(other), 0u64)); - let first = frame(&ctx, other, 0.0, vec![wheel(MouseWheelUnit::Point, 200.0, Modifiers::NONE)], false, 1); - assert!(!first[0].reset); - assert!(ctx.data(|data| data.get_temp::(pending(other)).is_none())); - let next = frame(&ctx, other, 1.0 / 60.0, Vec::new(), false, 1); - assert!(next[0].scroll.y > 0.0, "fresh unconsumed wheel motion still belongs to the replacement viewport"); - assert!(!next[0].reset); - } -} diff --git a/crates/ui-egui/tests/it/bookmark_position.rs b/crates/ui-egui/tests/it/bookmark_position.rs index 09fd1d4be8..2283249700 100644 --- a/crates/ui-egui/tests/it/bookmark_position.rs +++ b/crates/ui-egui/tests/it/bookmark_position.rs @@ -100,31 +100,6 @@ fn a_new_bookmark_goes_to_the_top_of_the_window_not_the_top_of_the_page() { assert_eq!(left, None, "the horizontal position is the reader's"); } -#[test] -fn a_bookmark_made_at_the_start_goes_to_the_top_of_the_first_page() { - let mut h = harness(0); - let (page, view) = new_bookmark(&mut h); - assert_eq!(page, Some(0)); - let (left, top) = xyz(view); - close(top, 400.0, "top is the page's top edge"); - assert_eq!(left, None); -} - -#[test] -fn a_bookmark_made_with_text_selected_goes_to_the_selections_corner() { - let mut h = harness(0); - // "quick brown": the selection starts after "The ", 40 pt in plus its width, on the line at 150. - h.state_mut().views[0].select_text(0, 4, 15); - h.run_steps(3); - let (page, view) = new_bookmark(&mut h); - assert_eq!(page, Some(0), "the selection's page"); - let (left, top) = xyz(view); - let left = left.expect("left is set from the selection"); - let top = top.expect("top is set from the selection"); - assert!((66.0..=70.0).contains(&left), "left is where 'q' starts: {left}"); - assert!((155.0..=168.0).contains(&top), "top is above the baseline at 150: {top}"); -} - #[test] fn a_bookmark_made_on_a_turned_page_pins_the_axis_the_window_scrolls_along() { // Page 1 is turned a quarter: its displayed top is a user x, so that is what is pinned. @@ -136,10 +111,12 @@ fn a_bookmark_made_on_a_turned_page_pins_the_axis_the_window_scrolls_along() { assert_eq!(top, None, "the displayed horizontal position is the reader's"); } -/// Turn the view a quarter at a time (View ▸ Rotate View) and let the layout settle. +/// Turn the view a quarter at a time (View ▸ Rotate View, clockwise) and let the layout settle. fn rotate_view(h: &mut Harness<'static, PdfCraftApp>, degrees: u16) { - h.state_mut().views[0].rotation = degrees; - h.run_steps(3); + for _ in 0..degrees / 90 { + crate::support::fire_menu(h, "view.rotate.cw"); + h.run_steps(3); + } crate::support::settle(h); } @@ -193,7 +170,6 @@ fn a_bookmark_made_with_text_selected_in_a_turned_view_goes_to_the_corner_shown_ #[test] fn a_bookmark_in_a_spread_of_unequal_pages_goes_to_the_page_crossing_the_top_of_the_window() { - use pdfcraft_ui_egui::canvas::PageLayout; // Pages 1 and 2 share a row; page 1 is shorter, so it is centred and starts below page 2's top. let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { let mut app = PdfCraftApp::new(); @@ -203,7 +179,7 @@ fn a_bookmark_in_a_spread_of_unequal_pages_goes_to_the_page_crossing_the_top_of_ app.set_option("panel", "bookmarks").unwrap(); app }); - h.state_mut().views[0].layout = PageLayout::TwoUp; + crate::support::fire_menu(&mut h, "view.layout.two_up"); h.run_steps(4); crate::support::settle(&mut h); // 20 pt below page 2's top is at the window's top, where page 1 has not started.