PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Alt+scroll zooms the canvas in 5% steps around the pointer (#293) (#371) (#371)
Brandon Thomasba9272be7dd3
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 8d060fc72..f5611afb7 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1477,27 +1477,23 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:// Under an open dialog the canvas widget is inert, but the image still pans and zooms.let under_dialog = !app.ui.dialogs.is_empty();let free_hover = under_dialog && crate::dialogs::free_pointer_over(&ctx, rect).is_some();- // Navigation: scroll pans, pinch / ⌘-scroll zooms around the pointer.+ // Navigation (wheel_nav.rs): scroll pans; pinch, ⌘-scroll and ⌥-scroll zoom around the pointer.+ let wheel = crate::wheel_nav::read(&ctx, app.session.prefs().general.zoom_with_scroll_wheel);// The wheel also scrolls over the scrollbars drawn on top of the canvas (last frame's hover).let bars_id = egui::Id::new(("pc-canvas-bars-hover", idx));let over_bars = ctx.data(|d| d.get_temp::<bool>(bars_id)).unwrap_or(false);if response.hovered() || free_hover || over_bars {- let (scroll, zoom_delta, pointer) = ui.input(|i| (i.smooth_scroll_delta, i.zoom_delta(), i.pointer.hover_pos()));- if zoom_delta != 1.0- && let Some(p) = pointer- {- let nz = (view.zoom * zoom_delta).clamp(0.01, 64.0);- zoom_about(&mut view, &xf, p, nz);- } else if scroll.y != 0.0- && app.session.prefs().general.zoom_with_scroll_wheel- && let Some(p) = pointer- {- // Preferences › General › Zoom with Scroll Wheel.- let nz = (view.zoom * (scroll.y / 200.0).exp()).clamp(0.01, 64.0);- zoom_about(&mut view, &xf, p, nz);- } else if scroll != Vec2::ZERO {- view.center[0] -= scroll.x / view.zoom * if flip { -1.0 } else { 1.0 };- view.center[1] -= scroll.y / view.zoom;+ let pointer = ui.input(|i| i.pointer.hover_pos());+ match (wheel, pointer) {+ (Some(crate::wheel_nav::Wheel::Zoom(f)), Some(p)) => {+ let nz = (view.zoom * f).clamp(0.01, 64.0);+ zoom_about(&mut view, &xf, p, nz);+ }+ (Some(crate::wheel_nav::Wheel::Pan(scroll)), _) => {+ view.center[0] -= scroll.x / view.zoom * if flip { -1.0 } else { 1.0 };+ view.center[1] -= scroll.y / view.zoom;+ }+ _ => {}}}diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rsindex 69bbcd320..5e81bddbc 100644--- a/crates/ui-egui/src/input_tests.rs+++ b/crates/ui-egui/src/input_tests.rs@@ -136,6 +136,68 @@ fn clicking_outside_a_dialog_keeps_it_open_and_the_canvas_pans_and_zooms() {/// Type tool (#206): Alt+←/→ at a collapsed caret kerns the pair before it by 20/1000 em (100/// with ⌘/Ctrl), one history step per press; ⌘/Ctrl+←/→ moves by word; Alt+Shift+→ extends/// the selection by a word.+fn wheel(h: &Harness<'static, PhotocraftApp>, dy: f32, modifiers: Modifiers) {+ h.event_modifiers(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, dy), phase: egui::TouchPhase::Move, modifiers }, modifiers);+}++/// The document point under screen point `p` (no flip).+fn doc_at(h: &Harness<'static, PhotocraftApp>, p: Pos2) -> [f32; 2] {+ let v = &h.state().ui.views[0];+ let c = h.state().last_canvas_rect.center();+ [v.center[0] + (p.x - c.x) / v.zoom, v.center[1] + (p.y - c.y) / v.zoom]+}++#[test]+fn alt_scroll_zooms_gently_around_the_pointer() {+ let mut h = harness();+ let r = h.state().last_canvas_rect;+ let p = pos2(r.center().x + 120.0, r.center().y - 70.0);+ h.hover_at(p);+ h.run_steps(2);+ let (z0, d0) = (zoom(&h), doc_at(&h, p));+ // One notch with ⌥ held: +5%, the point under the pointer stays put. The modifiers are+ // released right after the event, while egui still smooths the notch over later frames.+ wheel(&h, 1.0, Modifiers::ALT);+ h.run_steps(40);+ let (z1, d1) = (zoom(&h), doc_at(&h, p));+ assert!((z1 / z0 - 1.05).abs() < 1e-3, "one ⌥ notch is 5%: {z0} -> {z1}");+ assert!((d1[0] - d0[0]).abs() < 0.05 && (d1[1] - d0[1]).abs() < 0.05, "centred on the pointer: {d0:?} -> {d1:?}");+ // Three notches back out.+ wheel(&h, -3.0, Modifiers::ALT);+ h.run_steps(40);+ assert!((zoom(&h) / z1 - 1.05f32.powi(-3)).abs() < 1e-3, "{z1} -> {}", zoom(&h));++ // A plain notch still pans, and does not zoom.+ let (z2, c2) = (zoom(&h), h.state().ui.views[0].center);+ wheel(&h, -1.0, Modifiers::NONE);+ h.run_steps(40);+ assert_eq!(zoom(&h), z2, "a plain scroll never zooms");+ assert!(h.state().ui.views[0].center[1] > c2[1], "a plain scroll pans");++ // ⌘/Ctrl + scroll is still the faster gesture zoom.+ wheel(&h, 1.0, Modifiers::COMMAND);+ h.run_steps(40);+ assert!(zoom(&h) / z2 > 1.05, "⌘-scroll zooms in bigger steps: {z2} -> {}", zoom(&h));+}++#[test]+fn alt_scroll_zooms_while_a_temporary_tool_is_held() {+ let mut h = harness();+ let p = h.state().last_canvas_rect.center();+ h.hover_at(p);+ // Space (the temporary Hand, #249) is down: ⌥ + scroll still zooms by notches, and the+ // held key never changes the current tool.+ h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });+ h.run_steps(2);+ let z0 = zoom(&h);+ wheel(&h, 2.0, Modifiers::ALT);+ h.run_steps(40);+ assert!((zoom(&h) / z0 - 1.05f32.powi(2)).abs() < 1e-3, "{z0} -> {}", zoom(&h));+ h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });+ h.run_steps(2);+ assert_eq!(h.state().ui.tool, crate::state::Tool::Brush);+}+#[test]fn type_tool_alt_arrows_kern_the_pair() {use photocraft_doc::text::Kerning;diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex af6ab5b92..deff3fa87 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -115,6 +115,7 @@ pub mod type_tool;mod variables_ui;pub mod vector_ui;pub mod view_cmds;+pub mod wheel_nav;pub mod wide_angle_ui;pub mod widgets;pub mod work_area;diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rsnew file mode 100644index 000000000..1ae9a92c4--- /dev/null+++ b/crates/ui-egui/src/wheel_nav.rs@@ -0,0 +1,152 @@+//! Mouse wheel and trackpad navigation over the canvas (#293).+//!+//! - Scrolling pans (Shift scrolls sideways; egui folds that in).+//! - Pinch, or ⌘/Ctrl + scroll, zooms around the pointer (egui's zoom gesture).+//! - ⌥/Alt + scroll zooms around the pointer in gentle steps, about 5% per wheel notch, as in+//! Photoshop with Preferences › General › Zoom with Scroll Wheel off.+//! - With Zoom with Scroll Wheel on, a plain scroll zooms too.+//!+//! egui smooths a wheel notch over several frames, so the Alt state is taken from the wheel+//! events themselves and kept until the next wheel event: releasing Alt while the last notch+//! is still settling must not turn the rest of it into a pan.++use egui::{Context, Event, Id, Vec2};++/// Zoom factor of one wheel notch with ⌥/Alt held.+pub const ALT_NOTCH: f32 = 1.05;++/// What the wheel does to the view this frame.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Wheel {+ /// Multiply the zoom by this factor around the pointer.+ Zoom(f32),+ /// Move the image by this many screen points (egui's content direction).+ Pan(Vec2),+}++/// Inputs of one frame's wheel gesture.+#[derive(Clone, Copy, Debug)]+pub struct Input {+ /// Smoothed scroll delta (points, content direction).+ pub scroll: Vec2,+ /// egui's pinch / ⌘-scroll zoom factor (1 = none).+ pub zoom_delta: f32,+ /// ⌥/Alt was held for the wheel gesture in progress.+ pub alt: bool,+ /// Preferences › General › Zoom with Scroll Wheel.+ pub zoom_with_wheel: bool,+ /// Points per wheel notch (egui's `line_scroll_speed`).+ pub notch: f32,+}++/// The view change for one frame of wheel input, if any.+pub fn classify(i: Input) -> Option<Wheel> {+ if i.zoom_delta.is_finite() && i.zoom_delta > 0.0 && i.zoom_delta != 1.0 {+ return Some(Wheel::Zoom(i.zoom_delta));+ }+ if !(i.scroll.x.is_finite() && i.scroll.y.is_finite()) || i.scroll == Vec2::ZERO {+ return None;+ }+ if i.alt {+ // egui folds a scroll with Alt held into y. One notch (`notch` points) is 5%.+ let notch = if i.notch.is_finite() && i.notch > 0.0 { i.notch } else { 40.0 };+ let dy = i.scroll.y + i.scroll.x;+ let f = ALT_NOTCH.powf(dy / notch);+ return (f.is_finite() && f > 0.0 && f != 1.0).then_some(Wheel::Zoom(f));+ }+ if i.zoom_with_wheel && i.scroll.y != 0.0 {+ let f = (i.scroll.y / 200.0).exp();+ return f.is_finite().then_some(Wheel::Zoom(f));+ }+ Some(Wheel::Pan(i.scroll))+}++fn alt_id() -> Id {+ Id::new("pc-wheel-alt")+}++/// Read this frame's wheel input. Call it every frame (hovered or not) so the Alt state of the+/// gesture follows the latest wheel event.+pub fn read(ctx: &Context, zoom_with_wheel: bool) -> Option<Wheel> {+ let notch = ctx.options(|o| o.input_options.line_scroll_speed);+ let (scroll, zoom_delta, latest) = ctx.input(|i| {+ let latest = i.events.iter().rev().find_map(|e| match e {+ Event::MouseWheel { modifiers, .. } => Some(modifiers.alt && !modifiers.command && !modifiers.ctrl),+ _ => None,+ });+ (i.smooth_scroll_delta, i.zoom_delta(), latest)+ });+ let alt = match latest {+ Some(a) => {+ ctx.data_mut(|d| d.insert_temp(alt_id(), a));+ a+ }+ None => ctx.data(|d| d.get_temp::<bool>(alt_id())).unwrap_or(false),+ };+ classify(Input { scroll, zoom_delta, alt, zoom_with_wheel, notch })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn input(scroll: Vec2, alt: bool) -> Input {+ Input { scroll, zoom_delta: 1.0, alt, zoom_with_wheel: false, notch: 40.0 }+ }++ #[test]+ fn plain_scroll_pans() {+ assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0))));+ assert_eq!(classify(input(Vec2::ZERO, false)), None);+ }++ #[test]+ fn alt_scroll_zooms_five_percent_per_notch() {+ let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 40.0), true)) else { panic!("zoom") };+ assert!((f - 1.05).abs() < 1e-5, "{f}");+ let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, -40.0), true)) else { panic!("zoom") };+ assert!((f - 1.0 / 1.05).abs() < 1e-5, "{f}");+ // Smoothed over frames, the parts multiply back to one notch.+ let parts = [12.0, 16.0, 8.0, 4.0];+ let total: f32 = parts+ .iter()+ .map(|d| match classify(input(Vec2::new(0.0, *d), true)) {+ Some(Wheel::Zoom(f)) => f,+ _ => 1.0,+ })+ .product();+ assert!((total - 1.05).abs() < 1e-4, "{total}");+ }++ #[test]+ fn pinch_and_command_scroll_still_zoom() {+ let i = Input { zoom_delta: 1.2, ..input(Vec2::ZERO, false) };+ assert_eq!(classify(i), Some(Wheel::Zoom(1.2)));+ // The gesture zoom wins over Alt (⌘⌥ + scroll).+ let i = Input { zoom_delta: 0.8, ..input(Vec2::new(0.0, 40.0), true) };+ assert_eq!(classify(i), Some(Wheel::Zoom(0.8)));+ }++ #[test]+ fn zoom_with_scroll_wheel_preference() {+ let i = Input { zoom_with_wheel: true, ..input(Vec2::new(0.0, 200.0), false) };+ let Some(Wheel::Zoom(f)) = classify(i) else { panic!("zoom") };+ assert!((f - std::f32::consts::E).abs() < 1e-4);+ }++ #[test]+ fn hostile_numbers_never_produce_a_bad_zoom() {+ for s in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30] {+ for alt in [false, true] {+ for notch in [0.0, -1.0, f32::NAN, 40.0] {+ for zd in [f32::NAN, 0.0, -1.0, f32::INFINITY, 1.0] {+ let i = Input { scroll: Vec2::new(0.0, s), zoom_delta: zd, alt, zoom_with_wheel: alt, notch };+ if let Some(Wheel::Zoom(f)) = classify(i) {+ assert!(f.is_finite() && f > 0.0, "{f} from {i:?}");+ }+ }+ }+ }+ }+ }+}