From a01a3eb2dedce6f802367e006eb7595564be0dbd Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:08:18 +0200 Subject: [PATCH] =?UTF-8?q?Canvas=20zoom:=20Photoshop's=20range,=20ladder?= =?UTF-8?q?=20and=20=E2=8C=A5-wheel=20step;=20no=20slide=20at=20the=20limi?= =?UTF-8?q?t=20(#1718)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Canvas zoom: Photoshop's range, ladder and ⌥-wheel step; no slide at the limit Measured on Photoshop 25.4 (exact zoom read by script, view position by screenshot registration): - ⌥ + wheel: ×1.1 a notch around the pointer (was ×1.05); - the zoom runs up to 12800 % and down to where the document's shorter side is 2 px; a wheel notch past a limit lands on it exactly and further notches change nothing; - Zoom In / Zoom Out and a Zoom tool click step along 0.1 … 66.67, 100, 200 … 800, 1200, 1600, 3200, 6400, 12800 %, from any zoom to the next rung; - with Overscroll off, an image smaller than the view stays where zooming put it, inside the view, instead of being re-centred. PhotoCraft capped the zoom at 3200 % without meaning to: the status bar's zoom field (and the Navigator's slider) clamped it and wrote it back every frame. Past 3200 % each ⌥-wheel notch zoomed around the pointer and the field pulled the zoom back, so the image slid towards the pointer. All zoom paths now share `zoom_levels` (range, ladder, clamp), and the fields always include the current zoom. Co-Authored-By: Claude Opus 5.5 (1M context) * Zoom: Print Size, 200 % and Fit Layers on Screen clamp through zoom_levels too Review of #1718: `view.twoHundredPercent` / `view.printSize` and `view.fitLayersOnScreen` still clamped to 1-6400 % on their own. They now use `zoom_levels::clamp` like every other zoom path: Print Size at 1 ppi gives 7200 % (it was cut to 6400 %), and fitting a 1 px layer stops at 12800 %. Co-Authored-By: Claude Opus 5.5 (1M context) * Wheel zoom: a notch applies on the frame it arrives (from #1490) Folded in from @Jeremy8776's #1490, as agreed in review: zooming reads this frame's wheel events (`Input::raw`) instead of egui's smoothed delta, so each notch is one ×1.1 step on the frame it arrives, with no easing over the next frames (his frame-by-frame recordings of Photoshop). The smoothed tail neither zooms nor turns into a pan when Alt is released; panning still uses the smoothed delta. Zoom with Scroll Wheel uses the same ×1.1 notch (assumed, not measured). The Filter Gallery's and Liquify's own preview zooms keep their 3200 % caps, now with a comment saying why: they aren't the canvas. Co-authored-by: Jeremy Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: Jeremy --- crates/ui-egui/src/actions.rs | 4 +- crates/ui-egui/src/artboard_ui.rs | 4 +- crates/ui-egui/src/canvas.rs | 29 ++--- crates/ui-egui/src/chrome_ui.rs | 4 +- crates/ui-egui/src/control.rs | 3 +- crates/ui-egui/src/gallery_ui.rs | 2 + crates/ui-egui/src/input_tests.rs | 74 +++++++++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/liquify_ui.rs | 3 + crates/ui-egui/src/panels.rs | 12 +- crates/ui-egui/src/scrollbars.rs | 36 +++--- crates/ui-egui/src/view_cmds.rs | 6 +- crates/ui-egui/src/view_cmds/tests.rs | 17 +++ crates/ui-egui/src/wheel_nav.rs | 116 ++++++++++++------- crates/ui-egui/src/zoom_levels.rs | 157 ++++++++++++++++++++++++++ crates/ui-egui/src/zoom_tool.rs | 36 +++--- 16 files changed, 391 insertions(+), 113 deletions(-) create mode 100644 crates/ui-egui/src/zoom_levels.rs diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index f43aece16c..82fb3bdc1e 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -120,11 +120,11 @@ pub(crate) fn run_view(app: &mut PhotocraftApp, id: &str, params: Value) -> Resu "view.fitOnScreen" => v.fit_pending = true, "view.zoomIn" => { v.fit_pending = false; - v.zoom = crate::canvas::zoom_step(v.zoom, 1); + v.zoom = crate::zoom_levels::step(v.zoom, 1, v.doc_size); } "view.zoomOut" => { v.fit_pending = false; - v.zoom = crate::canvas::zoom_step(v.zoom, -1); + v.zoom = crate::zoom_levels::step(v.zoom, -1, v.doc_size); } "view.actualPixels" => { v.fit_pending = false; diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/artboard_ui.rs index 8e74c8e0ca..02d1df9507 100644 --- a/crates/ui-egui/src/artboard_ui.rs +++ b/crates/ui-egui/src/artboard_ui.rs @@ -60,11 +60,13 @@ pub fn fit_artboard(app: &mut PhotocraftApp) -> Result { let st = app.session.active().ok_or("no document")?; let id = st.active_layer.and_then(|l| st.doc.artboard_of(l)).or_else(|| st.doc.artboards().last().map(|b| b.0)).ok_or("the document has no artboards")?; let b = st.doc.layer(id).and_then(Layer::artboard).map(|a| a.rect).ok_or("no artboard")?; + let size = [st.doc.size.width, st.doc.size.height]; let area = app.last_canvas_rect.size(); let area = if area.x > 50.0 { area } else { egui::vec2(1200.0, 800.0) }; let v = &mut app.ui.views[i]; // Leave room for the name above the board. - v.zoom = ((area.x - 60.0) / b.width().max(1) as f32).min((area.y - 80.0) / b.height().max(1) as f32).clamp(0.01, 64.0); + v.zoom = ((area.x - 60.0) / b.width().max(1) as f32).min((area.y - 80.0) / b.height().max(1) as f32); + v.zoom = crate::zoom_levels::clamp(v.zoom, size); // Widen before adding: a board near ±2^30, or one whose far edge saturated at i32::MAX, // overflows an i32 sum (#981). v.center = [((f64::from(b.x0) + f64::from(b.x1)) / 2.0) as f32, ((f64::from(b.y0) + f64::from(b.y1)) / 2.0) as f32]; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 666ab17a8a..d2434c38ef 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -626,7 +626,7 @@ impl ViewXform { pub fn fit_view(view: &mut View, doc: &Document, area: Vec2) { let (w, h) = (doc.size.width as f32, doc.size.height as f32); - let zoom = ((area.x - 40.0) / w).min((area.y - 40.0) / h).clamp(0.01, 1.0); + let zoom = crate::zoom_levels::clamp(((area.x - 40.0) / w).min((area.y - 40.0) / h).min(1.0), [doc.size.width, doc.size.height]); view.zoom = zoom; view.center = [w / 2.0, h / 2.0]; view.fit_pending = false; @@ -637,20 +637,13 @@ pub fn fit_view(view: &mut View, doc: &Document, area: Vec2) { /// viewport, matching the Hand tool's Fill Screen action. pub fn fill_view(view: &mut View, doc: &Document, area: Vec2) { let (w, h) = (doc.size.width as f32, doc.size.height as f32); - let zoom = (area.x / w).max(area.y / h).clamp(0.01, 32.0); + let zoom = crate::zoom_levels::clamp((area.x / w).max(area.y / h), [doc.size.width, doc.size.height]); view.zoom = zoom; view.center = [w / 2.0, h / 2.0]; view.fit_pending = false; view.fill_pending = false; } -/// Zoom steps like Photoshop's (⌘+ / ⌘−). -pub fn zoom_step(z: f32, dir: i32) -> f32 { - const STEPS: [f32; 22] = - [0.01, 0.02, 0.03, 0.05, 0.0667, 0.1, 0.125, 0.1667, 0.25, 0.333, 0.5, 0.6667, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 12.0, 16.0, 32.0]; - if dir > 0 { STEPS.iter().copied().find(|s| *s > z * 1.001).unwrap_or(32.0) } else { STEPS.iter().rev().copied().find(|s| *s < z * 0.999).unwrap_or(0.01) } -} - fn checker(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::TextureId { // Preferences › Transparency & Gamut colours (the texture is rebuilt when they change). let [ca, cb] = app.session.prefs().transparency_and_gamut.colors(); @@ -2286,8 +2279,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: 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, false); + // At a limit the view stays put, as in Photoshop: a notch past 12800 % neither + // zooms nor slides the image towards the pointer. + let nz = crate::zoom_levels::clamp(view.zoom * f, view.doc_size); + if nz != view.zoom { + zoom_about(&mut view, &xf, p, nz, false); + } } (Some(crate::wheel_nav::Wheel::Pan(scroll)), _) => { let d = xf.unmap_vec(scroll) / view.zoom; @@ -2570,7 +2567,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let d = xf.to_doc(p); match tool { Tool::Zoom => { - let nz = zoom_step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }); + let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); let center = app.session.prefs().tools.zoom_clicked_point_to_center; zoom_about(&mut view, &xf, p, nz, center); } @@ -4628,14 +4625,6 @@ mod tests { assert!(app.style_preview.is_none()); } - #[test] - fn zoom_steps_monotone() { - assert_eq!(zoom_step(1.0, 1), 2.0); - assert_eq!(zoom_step(1.0, -1), 0.6667); - assert_eq!(zoom_step(0.4, 1), 0.5); - assert_eq!(zoom_step(32.0, 1), 32.0); - } - #[test] fn fill_view_covers_the_canvas_and_centres_the_document() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/chrome_ui.rs b/crates/ui-egui/src/chrome_ui.rs index e36083bf8f..e1d58801b2 100644 --- a/crates/ui-egui/src/chrome_ui.rs +++ b/crates/ui-egui/src/chrome_ui.rs @@ -130,8 +130,8 @@ pub fn status_bar_pro(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }; let text = status_info_text(&st.doc, &app.ui.chrome.status_info, tl!(app.ui.tool.label()), &profile_name(&st.doc)); let mut pct = app.ui.views[i].zoom * 100.0; - if widgets::value_field(ui, &mut pct, 1.0..=3200.0, "%", 64.0).changed() { - app.ui.views[i].zoom = pct / 100.0; + if widgets::value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", 64.0).changed() { + app.ui.views[i].zoom = crate::zoom_levels::clamp(pct / 100.0, app.ui.views[i].doc_size); app.ui.views[i].fit_pending = false; } ui.add_space(12.0); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c834c82ac8..9d37090132 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -425,7 +425,8 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) } if let Some(i) = app.session.active_index() { if let Some(z) = zoom { - app.ui.views[i].zoom = (z as f32).clamp(0.01, 64.0); + let size = app.session.documents().get(i).map_or([0, 0], |st| [st.doc.size.width, st.doc.size.height]); + app.ui.views[i].zoom = crate::zoom_levels::clamp(z as f32, size); app.ui.views[i].fit_pending = false; app.ui.views[i].fill_pending = false; } diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rs index d29b196f18..642957b895 100644 --- a/crates/ui-egui/src/gallery_ui.rs +++ b/crates/ui-egui/src/gallery_ui.rs @@ -276,6 +276,8 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { } match ui.get("zoom") { Some(Value::String(s)) if s == "fit" => d.zoom = 0.0, + // The gallery's own preview zoom, not the canvas (`zoom_levels` doesn't apply): its − / + + // buttons and menu stop at 400 %, an agent may set up to 3200 %. Some(v) if v.is_number() => d.zoom = (v.as_f64().unwrap_or(1.0) as f32).clamp(0.01, 32.0), _ => {} } diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 01b338d3cd..727d3b2c5c 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -331,25 +331,87 @@ fn doc_at(h: &Harness<'static, PhotocraftApp>, p: Pos2) -> [f32; 2] { [v.center[0] + (p.x - c.x) / v.zoom, v.center[1] + (p.y - c.y) / v.zoom] } +/// The whole window (status bar and Navigator included) on a 400 × 300 document. +fn app_window() -> Harness<'static, PhotocraftApp> { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + h.run_steps(8); + h +} + +/// Photoshop 25.4: ⌥ + wheel goes on past 3200 % to exactly 12800 %, and further notches there +/// change nothing. The status bar's zoom field used to stop at 3200 %, clamping the zoom back +/// every frame: past it, each notch zoomed around the pointer and the field pulled the zoom +/// back, so the image slid towards the pointer. #[test] -fn alt_scroll_zooms_gently_around_the_pointer() { +fn the_wheel_reaches_12800_percent_and_stops_dead_there() { + let mut h = app_window(); + { + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (40.0, [200.0, 150.0], false); + } + h.run_steps(4); + assert_eq!(zoom(&h), 40.0, "4000 % holds: no zoom control clamps it back"); + let r = h.state().last_canvas_rect; + let p = pos2(r.center().x - 150.0, r.center().y - 90.0); + // The document point under `p`, through the canvas inside the rulers. + let doc_at = |h: &Harness<'static, PhotocraftApp>, p: Pos2| { + let (app, v) = (h.state(), &h.state().ui.views[0]); + let c = crate::rulers::content_rect(app, app.last_canvas_rect).center(); + [v.center[0] + (p.x - c.x) / v.zoom, v.center[1] + (p.y - c.y) / v.zoom] + }; + h.hover_at(p); + h.run_steps(2); + let d0 = doc_at(&h, p); + for _ in 0..14 { + wheel(&h, 1.0, Modifiers::ALT); + h.run_steps(30); + } + assert_eq!(zoom(&h), crate::zoom_levels::MAX, "a notch past the limit lands on it exactly"); + let d1 = doc_at(&h, p); + assert!((d1[0] - d0[0]).abs() < 0.02 && (d1[1] - d0[1]).abs() < 0.02, "zoomed around the pointer: {d0:?} -> {d1:?}"); + let c = h.state().ui.views[0].center; + for _ in 0..4 { + wheel(&h, 1.0, Modifiers::ALT); + h.run_steps(30); + } + assert_eq!(zoom(&h), crate::zoom_levels::MAX); + assert_eq!(h.state().ui.views[0].center, c, "at the limit the image doesn't move"); + // One notch back: 12800 / 1.1, still around the pointer. + wheel(&h, -1.0, Modifiers::ALT); + h.run_steps(30); + assert!((zoom(&h) - crate::zoom_levels::MAX / 1.1).abs() < 1e-2, "{}", zoom(&h)); + let d2 = doc_at(&h, p); + assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}"); +} + +#[test] +fn alt_scroll_zooms_in_steps_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. + // One notch with ⌥ held: ×1.1 (Photoshop), the point under the pointer stays put. The modifiers are + // released right after the event, while egui still smooths the notch over later frames, which + // must neither ease the zoom nor turn into a pan (#1490). wheel(&h, 1.0, Modifiers::ALT); + h.run_steps(2); + let at_once = zoom(&h); 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!((z1 / z0 - 1.1).abs() < 1e-3, "one ⌥ notch is ×1.1: {z0} -> {z1}"); + assert_eq!(at_once, z1, "the notch is applied the frame it arrives, with no easing"); 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)); + assert!((zoom(&h) / z1 - 1.1f32.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); @@ -385,7 +447,7 @@ fn alt_scroll_zooms_while_a_temporary_tool_is_held() { 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)); + assert!((zoom(&h) / z0 - 1.1f32.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); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb012b41c6..14c50b2302 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -149,6 +149,7 @@ pub mod wide_angle_ui; pub mod widgets; pub mod work_area; pub mod workspace_ui; +pub mod zoom_levels; pub mod zoom_tool; use std::collections::HashMap; diff --git a/crates/ui-egui/src/liquify_ui.rs b/crates/ui-egui/src/liquify_ui.rs index 33f31a4fac..f1b13fe4c6 100644 --- a/crates/ui-egui/src/liquify_ui.rs +++ b/crates/ui-egui/src/liquify_ui.rs @@ -715,6 +715,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { && let Some(hp) = resp.hover_pos() { let before = to_doc(d, area, hp); + // Liquify's own preview zoom, not the canvas (`zoom_levels` doesn't apply): the + // preview is a proxy of at most PROXY_SIDE px, so past 3200 % it would only magnify + // proxy pixels further. d.zoom = (d.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); let after = to_doc(d, area, hp); d.center = [d.center[0] + before[0] - after[0], d.center[1] + before[1] - after[1]]; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 8e1231e851..599a99608e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1101,8 +1101,8 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let (w, h, mode, bits, layers) = (st.doc.size.width, st.doc.size.height, crate::canvas::mode_label(&st.doc), st.doc.depth.bits(), st.doc.layer_count()); let mut pct = app.ui.views[i].zoom * 100.0; - if widgets::value_field(ui, &mut pct, 1.0..=3200.0, "%", 78.0).changed() { - app.ui.views[i].zoom = pct / 100.0; + if widgets::value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", 78.0).changed() { + app.ui.views[i].zoom = crate::zoom_levels::clamp(pct / 100.0, app.ui.views[i].doc_size); app.ui.views[i].fit_pending = false; } widgets::vline(ui, 16.0); @@ -1361,9 +1361,11 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); }); - let mut lz = v.zoom.max(0.01).log2(); - if widgets::slider(ui, &mut lz, -6.64..=5.0, None).changed() { - app.ui.views[idx].zoom = 2f32.powf(lz); + // The whole zoom range, and always the current zoom: a narrower slider would pull it back. + let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2()); + let mut lz = v.zoom.log2(); + if lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed() { + app.ui.views[idx].zoom = crate::zoom_levels::clamp(2f32.powf(lz), v.doc_size); app.ui.views[idx].fit_pending = false; } } diff --git a/crates/ui-egui/src/scrollbars.rs b/crates/ui-egui/src/scrollbars.rs index f8c22e79b2..48eba77126 100644 --- a/crates/ui-egui/src/scrollbars.rs +++ b/crates/ui-egui/src/scrollbars.rs @@ -71,20 +71,20 @@ impl Span { } } -/// Clamp one axis of the view centre with Overscroll off: the image can't leave its edges; an -/// image smaller than the view is centred. +/// Clamp one axis of the view centre with Overscroll off, as Photoshop 25.4 does: an image larger +/// than the view can't leave its edges, and one smaller than the view stays inside it, where +/// zooming put it (zooming out around the pointer doesn't re-centre it; Fit on Screen does). pub fn clamp_axis(center: f32, len: f32, size: f32, zoom: f32) -> f32 { if !(zoom.is_finite() && zoom > 0.0 && len.is_finite() && len > 0.0 && size.is_finite() && size > 0.0) { return center; } - let half = size / zoom / 2.0; - if 2.0 * half >= len { - len / 2.0 - } else if center.is_finite() { - center.clamp(half, len - half) - } else { - len / 2.0 + if !center.is_finite() { + return len / 2.0; } + let half = size / zoom / 2.0; + // Larger: the view stays within the image. Smaller: the image stays within the view. + let (a, b) = (half, len - half); + center.clamp(a.min(b), a.max(b)) } /// Apply Preferences › Tools › Overscroll (off) to `view` for a canvas of `size` points. True @@ -278,8 +278,12 @@ mod tests { assert_eq!(clamp_axis(-400.0, 1000.0, 500.0, 1.0), 250.0); assert_eq!(clamp_axis(4000.0, 1000.0, 500.0, 1.0), 750.0); assert_eq!(clamp_axis(600.0, 1000.0, 500.0, 1.0), 600.0); - // Smaller than the view: centred. - assert_eq!(clamp_axis(-90.0, 1000.0, 500.0, 0.2), 500.0); + // Smaller than the view (2500 doc px of view for 1000 of image): it stays where it is + // while it is inside the view, and is pushed back in at the edges. + assert_eq!(clamp_axis(-90.0, 1000.0, 500.0, 0.2), -90.0); + assert_eq!(clamp_axis(-400.0, 1000.0, 500.0, 0.2), -250.0, "the image's right edge on the view's"); + assert_eq!(clamp_axis(1400.0, 1000.0, 500.0, 0.2), 1250.0, "its left edge on the view's"); + assert_eq!(clamp_axis(500.0, 1000.0, 1000.0, 1.0), 500.0, "exactly the view's size: centred"); let mut v = View { zoom: 1.0, center: [-500.0, 20.0], fit_pending: false, fill_pending: false, doc_size: [1000, 800], rotation: 0.0 }; assert!(clamp_view(&mut v, vec2(500.0, 400.0))); assert_eq!(v.center, [250.0, 200.0]); @@ -458,10 +462,16 @@ mod tests { } else { assert!((x - w / 2.0).abs() < 1e-3, "clamped to the left edge: {x}"); } - // Zoomed out below fit: centred. + // Zoomed out below fit (Photoshop): the image is not re-centred, it stays where it + // is while it fits in the view, and is pushed back in at the view's edge. set_view(&mut h, 0.1, [-50.0, 9000.0]); if !overscroll { - assert_eq!(view(&h).center, [1000.0, 750.0]); + let r = h.state().last_canvas_rect; + let (hw, hh) = (r.width() / 0.1 / 2.0, r.height() / 0.1 / 2.0); + let c = view(&h).center; + assert_eq!(c[0], -50.0, "inside the view: left alone"); + assert!((c[1] - hh).abs() < 1e-2, "pushed back in: the image's top on the view's: {c:?}"); + assert!(c[0] - hw <= 0.0 && c[0] + hw >= 2000.0 && c[1] - hh <= 0.0 && c[1] + hh >= 1500.0, "{c:?}"); } } } diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 4856414bd8..9e2091d8a4 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -578,8 +578,9 @@ fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Res let i = app.session.active_index().ok_or("no document")?; // Print Size assumes Photoshop's default 72 ppi screen resolution. let dpi = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi.max(1.0)); + let size = app.session.active().map_or([0, 0], |d| [d.doc.size.width, d.doc.size.height]); let z = if id == "view.twoHundredPercent" { 2.0 } else { 72.0 / dpi }; - app.ui.views[i].zoom = z.clamp(0.01, 64.0); + app.ui.views[i].zoom = crate::zoom_levels::clamp(z, size); Ok(json!({"zoom": app.ui.views[i].zoom})) } "view.fitLayersOnScreen" => fit_layers(app), @@ -601,10 +602,11 @@ fn fit_layers(app: &mut PhotocraftApp) -> Result { if b.is_empty() { b = st.doc.bounds(); } + let size = [st.doc.size.width, st.doc.size.height]; let area = app.last_canvas_rect.size(); let area = if area.x > 50.0 { area } else { egui::vec2(1200.0, 800.0) }; let v = &mut app.ui.views[i]; - v.zoom = ((area.x - 40.0) / b.width().max(1) as f32).min((area.y - 40.0) / b.height().max(1) as f32).clamp(0.01, 64.0); + v.zoom = crate::zoom_levels::clamp(((area.x - 40.0) / b.width().max(1) as f32).min((area.y - 40.0) / b.height().max(1) as f32), size); v.center = [(b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0]; v.fit_pending = false; Ok(json!({"zoom": v.zoom, "bounds": [b.x0, b.y0, b.x1, b.y1]})) diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rs index 21c01fcdc6..cbf8bd05ac 100644 --- a/crates/ui-egui/src/view_cmds/tests.rs +++ b/crates/ui-egui/src/view_cmds/tests.rs @@ -75,6 +75,23 @@ fn zoom_presets_and_fit_layers() { assert!(app.ui.views[0].zoom > 10.0); } +/// #1718 review: Print Size and Fit Layers on Screen go through `zoom_levels` too, so they reach +/// past the old 6400 % cap and stop at 12800 %. +#[test] +fn print_size_and_fit_layers_use_the_whole_zoom_range() { + let (mut app, ctx) = app_with(1); + // 72 / 1 ppi = 7200 %: within the range now (it was cut to 6400 %). + app.run("image.imageSize", json!({"resolution": 1, "resample": "none"})).unwrap(); + menu(&mut app, &ctx, "view.printSize", json!({})).unwrap(); + assert_eq!(app.ui.views[0].zoom, 72.0); + // A 1 px layer fills the view only far beyond 12800 %: Fit stops at the limit. + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 40, "y": 30, "width": 1, "height": 1})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + menu(&mut app, &ctx, "view.fitLayersOnScreen", json!({})).unwrap(); + assert_eq!(app.ui.views[0].zoom, crate::zoom_levels::MAX); +} + #[test] fn arrange_layouts_floating_windows_and_matching() { let (mut app, ctx) = app_with(3); diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 49e428791a..1d94b53843 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -1,7 +1,7 @@ //! Mouse wheel and trackpad navigation over the canvas (#293, #635), as in Photoshop: //! //! - The wheel scrolls up and down; ⇧ or ⌘/Ctrl + wheel scrolls sideways. -//! - ⌥/Alt + wheel zooms around the pointer in gentle steps, about 5% per wheel notch. +//! - ⌥/Alt + wheel zooms around the pointer, 10% per wheel notch, applied the frame it arrives. //! - Preferences › General › Zoom with Scroll Wheel swaps the two: the wheel zooms and //! ⌥/Alt + wheel scrolls. //! - A trackpad pinch zooms around the pointer. @@ -13,14 +13,16 @@ //! before egui sees them, so Ctrl + a notched mouse wheel scrolls sideways and the pinch still //! zooms. //! -//! 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. +//! The target behaviour is exact ×1.1 steps, one per notch, with no easing in between +//! (measured frame by frame on a screen recording). egui smooths a wheel notch over several +//! frames, so zooming reads the wheel events themselves and ignores that smoothed tail; panning +//! keeps the smoothed delta. The Alt state is taken from the wheel events and kept until the next +//! wheel event: releasing Alt while the tail is still settling must not turn it into a pan. use egui::{Context, Event, Id, Modifiers, MouseWheelUnit, RawInput, Vec2}; -/// Zoom factor of one wheel notch with ⌥/Alt held. -pub const ALT_NOTCH: f32 = 1.05; +/// Zoom factor of one wheel notch: every step is exactly ×1.1. +pub const NOTCH: f32 = 1.1; /// A Ctrl + wheel event this soon (seconds) after a pinch step still belongs to the pinch, even /// when it happens to be a whole notch. @@ -38,8 +40,11 @@ pub enum Wheel { /// Inputs of one frame's wheel gesture. #[derive(Clone, Copy, Debug)] pub struct Input { - /// Smoothed scroll delta (points, content direction). + /// Smoothed scroll delta (points, content direction); what panning uses. pub scroll: Vec2, + /// This frame's wheel events for the gesture in progress, unsmoothed (points, content + /// direction); what zooming uses. + pub raw: Vec2, /// egui's pinch zoom factor (1 = none). pub zoom_delta: f32, /// ⌥/Alt was held for the wheel gesture in progress. @@ -55,20 +60,20 @@ pub fn classify(i: Input) -> Option { 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; - } - let f = match (i.alt, i.zoom_with_wheel) { - (true, false) => { - // 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 }; - ALT_NOTCH.powf((i.scroll.y + i.scroll.x) / notch) - } - // ⇧ and ⌘/Ctrl fold the wheel into x: those still scroll sideways. - (false, true) if i.scroll.y != 0.0 => (i.scroll.y / 200.0).exp(), - _ => return Some(Wheel::Pan(i.scroll)), + // One notch (`notch` points) is one ×1.1 step. + let step = |dy: f32| { + let notch = if i.notch.is_finite() && i.notch > 0.0 { i.notch } else { 40.0 }; + let f = NOTCH.powf(dy / notch); + (f.is_finite() && f > 0.0 && f != 1.0).then_some(Wheel::Zoom(f)) }; - (f.is_finite() && f > 0.0 && f != 1.0).then_some(Wheel::Zoom(f)) + match (i.alt, i.zoom_with_wheel) { + // egui folds a scroll with Alt held into y. The smoothed tail of a notch is ignored. + (true, false) => step(i.raw.y + i.raw.x), + // ⇧ and ⌘/Ctrl fold the wheel into x: those still scroll sideways. + (false, true) if i.raw.y != 0.0 || i.scroll.y != 0.0 => step(i.raw.y), + _ if !(i.scroll.x.is_finite() && i.scroll.y.is_finite()) || i.scroll == Vec2::ZERO => None, + _ => Some(Wheel::Pan(i.scroll)), + } } /// Set egui's wheel modifiers (once, at setup): ⌘/Ctrl + wheel scrolls sideways like ⇧ + wheel @@ -131,12 +136,20 @@ fn alt_id() -> Id { /// gesture follows the latest wheel event. pub fn read(ctx: &Context, zoom_with_wheel: bool) -> Option { let notch = ctx.options(|o| o.input_options.line_scroll_speed); - let (scroll, zoom_delta, latest) = ctx.input(|i| { + let (scroll, zoom_delta, latest, wheel, page) = 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 wheel: Vec<(MouseWheelUnit, Vec2, Modifiers)> = i + .events + .iter() + .filter_map(|e| match e { + Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, *modifiers)), + _ => None, + }) + .collect(); + (i.smooth_scroll_delta, i.zoom_delta(), latest, wheel, i.content_rect().height()) }); let alt = match latest { Some(a) => { @@ -145,7 +158,20 @@ pub fn read(ctx: &Context, zoom_with_wheel: bool) -> Option { } None => ctx.data(|d| d.get_temp::(alt_id())).unwrap_or(false), }; - classify(Input { scroll, zoom_delta, alt, zoom_with_wheel, notch }) + // The wheel events that belong to the gesture in progress: Alt ones, or plain ones (⇧ and + // ⌘/Ctrl wheel scroll sideways and never zoom). + let raw = wheel.iter().filter(|(_, _, m)| if alt { m.alt && !m.command && !m.ctrl } else { !m.alt && !m.shift && !m.command && !m.ctrl }).fold( + Vec2::ZERO, + |sum, (unit, delta, _)| { + sum + *delta + * match unit { + MouseWheelUnit::Point => 1.0, + MouseWheelUnit::Line => notch, + MouseWheelUnit::Page => page, + } + }, + ); + classify(Input { scroll, raw, zoom_delta, alt, zoom_with_wheel, notch }) } #[cfg(test)] @@ -155,7 +181,7 @@ 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 } + Input { scroll, raw: scroll, zoom_delta: 1.0, alt, zoom_with_wheel: false, notch: 40.0 } } fn wheel(delta: Vec2, modifiers: Modifiers) -> Event { @@ -199,21 +225,27 @@ mod tests { } #[test] - fn alt_scroll_zooms_five_percent_per_notch() { + fn alt_scroll_zooms_ten_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}"); + assert!((f - 1.1).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}"); + assert!((f - 1.0 / 1.1).abs() < 1e-5, "{f}"); + // Two notches in one frame are two steps, x1.1 each. + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 80.0), true)) else { panic!("zoom") }; + assert!((f - 1.21).abs() < 1e-4, "{f}"); + } + + #[test] + fn a_notch_zooms_the_frame_it_arrives_and_its_smoothed_tail_does_nothing() { + // egui keeps feeding a smoothed delta for several frames after the wheel event. Zooming + // must not follow it (that would ease the zoom), nor turn it into a pan. + let tail = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }; + assert_eq!(classify(tail), None); + let tail = Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(tail), None); + // Plain scrolling without the preference still pans from the smoothed delta. + let pan = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); } #[test] @@ -228,8 +260,8 @@ mod tests { #[test] fn zoom_with_scroll_wheel_preference_swaps_wheel_and_alt_wheel() { let pref = |scroll, alt| Input { zoom_with_wheel: true, ..input(scroll, alt) }; - let Some(Wheel::Zoom(f)) = classify(pref(Vec2::new(0.0, 200.0), false)) else { panic!("zoom") }; - assert!((f - std::f32::consts::E).abs() < 1e-4); + let Some(Wheel::Zoom(f)) = classify(pref(Vec2::new(0.0, 40.0), false)) else { panic!("zoom") }; + assert!((f - 1.1).abs() < 1e-5, "{f}"); assert_eq!(classify(pref(Vec2::new(0.0, 40.0), true)), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⌥ + wheel scrolls"); assert_eq!(classify(pref(Vec2::new(40.0, 0.0), false)), Some(Wheel::Pan(Vec2::new(40.0, 0.0))), "sideways still scrolls"); } @@ -245,12 +277,12 @@ mod tests { assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "{m:?} + wheel scrolls sideways: {pan:?} {zoom}"); } let (pan, zoom) = one(Modifiers::ALT); - assert!(pan == Vec2::ZERO && (zoom - 1.05).abs() < 1e-4, "⌥ + wheel zooms 5%: {pan:?} {zoom}"); + assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "⌥ + wheel zooms 10%, at once: {pan:?} {zoom}"); // Zoom with Scroll Wheel on: swapped. let (pan, zoom) = gesture(vec![vec![wheel(notch, Modifiers::ALT)]], true, false); assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "{pan:?} {zoom}"); let (pan, zoom) = gesture(vec![vec![wheel(notch, Modifiers::NONE)]], true, false); - assert!(pan == Vec2::ZERO && zoom > 1.1, "{pan:?} {zoom}"); + assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "{pan:?} {zoom}"); let (pan, zoom) = gesture(vec![vec![wheel(notch, CTRL)]], true, false); assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "⌘/Ctrl + wheel still scrolls sideways: {pan:?} {zoom}"); } @@ -294,7 +326,7 @@ mod tests { 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 }; + let i = Input { scroll: Vec2::new(0.0, s), raw: 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:?}"); } diff --git a/crates/ui-egui/src/zoom_levels.rs b/crates/ui-egui/src/zoom_levels.rs new file mode 100644 index 0000000000..8d87e92cea --- /dev/null +++ b/crates/ui-egui/src/zoom_levels.rs @@ -0,0 +1,157 @@ +//! The canvas zoom range and Photoshop's Zoom In / Zoom Out ladder, measured on Photoshop 25.4: +//! +//! - the zoom runs up to 12800 %, and down to where the document's shorter side is 2 px +//! (4 × 4 px: 50 %; 2000 × 1500 px: 0.1333 %); +//! - Zoom In / Zoom Out (⌘+ / ⌘−) and a Zoom tool click step along [`LADDER`], from any zoom to +//! the next step (880 %: in to 1200 %, out to 800 %); they go no lower than 0.1 %, or the +//! document's minimum when that is higher; +//! - ⌥ + wheel multiplies the zoom by 1.1 a notch (`wheel_nav`), and a notch that would pass a +//! limit stops exactly on it. +//! +//! Every way of setting the zoom (wheel, Zoom tool, menu, zoom fields, Navigator, control +//! channel) clamps through here, so no control can pull the zoom back to a narrower range of +//! its own. + +/// 12800 %. +pub const MAX: f32 = 128.0; + +/// Zoom In / Zoom Out steps (1 = 100 %). +pub const LADDER: [f32; 33] = [ + 0.001, + 0.002, + 0.003, + 0.004, + 0.005, + 0.007, + 0.01, + 0.015, + 0.02, + 0.03, + 0.04, + 0.05, + 0.0625, + 1.0 / 12.0, + 0.125, + 1.0 / 6.0, + 0.25, + 1.0 / 3.0, + 0.5, + 2.0 / 3.0, + 1.0, + 2.0, + 3.0, + 4.0, + 5.0, + 6.0, + 7.0, + 8.0, + 12.0, + 16.0, + 32.0, + 64.0, + 128.0, +]; + +/// The lowest zoom for a document of `size` px: its shorter side 2 px on screen. +pub fn min(size: [u32; 2]) -> f32 { + match size[0].min(size[1]) { + // No size known yet (a view before its first frame). + 0 => LADDER[0], + short => (2.0 / short as f32).min(MAX), + } +} + +/// `zoom` within the range for a document of `size` px (a non-finite zoom becomes 100 %). +pub fn clamp(zoom: f32, size: [u32; 2]) -> f32 { + if zoom.is_finite() { zoom.min(MAX).max(min(size)) } else { 1.0 } +} + +/// A zoom field's range in percent for `view`: the zoom range, and always the view's zoom (a +/// field narrower than the zoom would clamp it and write it back every frame, which once made +/// the wheel slide the image towards the pointer at 3200 %). +pub fn percent_range(view: &crate::state::View) -> std::ops::RangeInclusive { + let z = if view.zoom.is_finite() { view.zoom } else { 1.0 }; + (min(view.doc_size).min(z) * 100.0)..=(MAX.max(z) * 100.0) +} + +/// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `zoom`, for a document of `size` px. +pub fn step(zoom: f32, dir: i32, size: [u32; 2]) -> f32 { + let z = clamp(zoom, size); + let next = if dir > 0 { + LADDER.iter().copied().find(|s| *s > z * 1.001).unwrap_or(MAX) + } else { + // Below the ladder's lowest step (reached by the wheel), Zoom Out stays put. + LADDER.iter().rev().copied().find(|s| *s < z * 0.999).unwrap_or(z) + }; + clamp(next, size) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PHOTO: [u32; 2] = [2000, 1500]; + + fn pct(z: f32) -> f32 { + (z * 100.0 * 1000.0).round() / 1000.0 + } + + #[test] + fn the_ladder_is_photoshops() { + // Photoshop 25.4, View › Zoom In from 100 %, then Zoom Out from 100 % (2000 × 1500 px). + let mut z = 1.0; + let mut up = Vec::new(); + while z < MAX { + z = step(z, 1, PHOTO); + up.push(pct(z)); + } + assert_eq!(up, [200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 1200.0, 1600.0, 3200.0, 6400.0, 12800.0]); + assert_eq!(step(MAX, 1, PHOTO), MAX, "Zoom In stops at 12800 %"); + let mut z = 1.0; + let mut down = Vec::new(); + for _ in 0..20 { + z = step(z, -1, PHOTO); + down.push(pct(z)); + } + assert_eq!( + down, + [66.667, 50.0, 33.333, 25.0, 16.667, 12.5, 8.333, 6.25, 5.0, 4.0, 3.0, 2.0, 1.5, 1.0, 0.7, 0.5, 0.4, 0.3, 0.2, 0.133], + "the last step is the document's minimum (1500 px tall: 2 / 1500)" + ); + assert_eq!(step(z, -1, PHOTO), z, "Zoom Out stops at the minimum"); + } + + #[test] + fn off_ladder_zooms_step_to_the_next_rung() { + assert_eq!(step(8.8, 1, PHOTO), 12.0); + assert_eq!(step(8.8, -1, PHOTO), 8.0); + assert_eq!(step(1.331, 1, PHOTO), 2.0); + assert_eq!(step(1.331, -1, PHOTO), 1.0); + } + + #[test] + fn the_minimum_follows_the_shorter_side() { + assert_eq!(min([4, 4]), 0.5); + assert_eq!(pct(min([300, 1000])), 0.667); + assert_eq!(pct(min([1000, 300])), 0.667); + // A huge document: the wheel goes below 0.1 %, Zoom Out stops there. + let big = [12_000, 12_000]; + assert!(min(big) < 0.001); + assert_eq!(step(0.0015, -1, big), 0.001); + assert_eq!(step(0.001, -1, big), 0.001); + assert_eq!(step(0.0007, -1, big), 0.0007, "below the ladder Zoom Out stays put"); + // A 1 px document can't go below 200 %. + assert_eq!(min([1, 1]), 2.0); + assert_eq!(step(2.0, -1, [1, 1]), 2.0); + assert_eq!(min([0, 0]), 0.001, "unknown size"); + } + + #[test] + fn clamp_keeps_the_range_and_survives_bad_input() { + assert_eq!(clamp(500.0, PHOTO), MAX); + assert_eq!(clamp(0.0, PHOTO), min(PHOTO)); + assert_eq!(clamp(f32::NAN, PHOTO), 1.0); + assert_eq!(clamp(f32::INFINITY, PHOTO), 1.0); + assert_eq!(clamp(3.3, PHOTO), 3.3); + } +} diff --git a/crates/ui-egui/src/zoom_tool.rs b/crates/ui-egui/src/zoom_tool.rs index de8a16b448..bbfafaf04c 100644 --- a/crates/ui-egui/src/zoom_tool.rs +++ b/crates/ui-egui/src/zoom_tool.rs @@ -12,9 +12,6 @@ use crate::canvas::ViewXform; use crate::paint_mouse::Buttons; use crate::state::View; -/// Zoom limits of the canvas (1 % … 6400 %). -pub const MIN_ZOOM: f32 = 0.01; -pub const MAX_ZOOM: f32 = 64.0; /// Horizontal drag (screen points) that doubles, or halves, the zoom. pub const DOUBLING: f32 = 100.0; @@ -34,12 +31,12 @@ fn id() -> egui::Id { egui::Id::new("pc-zoom-tool-drag") } -/// The scrubby zoom for a horizontal drag of `dx` points from a press at zoom `zoom0`. -pub fn scrub_zoom(zoom0: f32, dx: f32) -> f32 { +/// The scrubby zoom for a horizontal drag of `dx` points from a press at zoom `zoom0`, on a +/// document of `size` px (`zoom_levels` sets the range). +pub fn scrub_zoom(zoom0: f32, dx: f32, size: [u32; 2]) -> f32 { // ±40 doublings already span far more than the zoom range; it keeps the power finite. let e = if dx.is_finite() { (dx / DOUBLING).clamp(-40.0, 40.0) } else { 0.0 }; - let z = zoom0 * e.exp2(); - if z.is_finite() { z.clamp(MIN_ZOOM, MAX_ZOOM) } else { 1.0 } + crate::zoom_levels::clamp(zoom0 * e.exp2(), size) } /// Set `view` to `zoom` with document point `doc` shown at screen point `screen`. @@ -65,7 +62,7 @@ pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &View if let Some(p) = pointer.filter(|_| b.dragged || b.stopped) { match z.rect_to.as_mut() { Some(to) => *to = p, - None => anchor_view(view, xf, z.anchor, z.doc, scrub_zoom(z.zoom0, p.x - z.anchor.x)), + None => anchor_view(view, xf, z.anchor, z.doc, scrub_zoom(z.zoom0, p.x - z.anchor.x, view.doc_size)), } ctx.data_mut(|d| d.insert_temp(id(), z)); } @@ -83,11 +80,11 @@ pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &View fn zoom_to_rect(view: &mut View, xf: &ViewXform, r: Rect, anchor: Pos2, out: bool) { if out || r.width() < 4.0 || r.height() < 4.0 { let doc = xf.to_doc(anchor); - anchor_view(view, xf, anchor, doc, crate::canvas::zoom_step(view.zoom, if out { -1 } else { 1 }).clamp(MIN_ZOOM, MAX_ZOOM)); + anchor_view(view, xf, anchor, doc, crate::zoom_levels::step(view.zoom, if out { -1 } else { 1 }, view.doc_size)); return; } let k = (xf.rect.width() / r.width()).min(xf.rect.height() / r.height()); - let zoom = (view.zoom * k).clamp(MIN_ZOOM, MAX_ZOOM); + let zoom = crate::zoom_levels::clamp(view.zoom * k, view.doc_size); let c = xf.to_doc(r.center()); anchor_view(view, xf, xf.rect.center(), c, zoom); } @@ -110,15 +107,16 @@ mod tests { #[test] fn scrub_zoom_is_continuous_and_clamped() { - assert_eq!(scrub_zoom(1.0, 0.0), 1.0); - assert!((scrub_zoom(1.0, DOUBLING) - 2.0).abs() < 1e-5); - assert!((scrub_zoom(1.0, -DOUBLING) - 0.5).abs() < 1e-5); + const DOC: [u32; 2] = [400, 300]; + assert_eq!(scrub_zoom(1.0, 0.0, DOC), 1.0); + assert!((scrub_zoom(1.0, DOUBLING, DOC) - 2.0).abs() < 1e-5); + assert!((scrub_zoom(1.0, -DOUBLING, DOC) - 0.5).abs() < 1e-5); // Monotone: every point of drag to the right zooms in a little more. - let zs: Vec = (0..50).map(|i| scrub_zoom(0.7, i as f32 * 3.0)).collect(); + let zs: Vec = (0..50).map(|i| scrub_zoom(0.7, i as f32 * 3.0, DOC)).collect(); assert!(zs.windows(2).all(|w| w[1] > w[0])); - assert_eq!(scrub_zoom(1.0, 1e6), MAX_ZOOM); - assert_eq!(scrub_zoom(1.0, -1e6), MIN_ZOOM); - assert_eq!(scrub_zoom(2.0, f32::NAN), 2.0); + assert_eq!(scrub_zoom(1.0, 1e6, DOC), crate::zoom_levels::MAX); + assert_eq!(scrub_zoom(1.0, -1e6, DOC), crate::zoom_levels::min(DOC)); + assert_eq!(scrub_zoom(2.0, f32::NAN, DOC), 2.0); } fn harness(scrubby: bool) -> Harness<'static, PhotocraftApp> { @@ -179,7 +177,7 @@ mod tests { h.event(Event::PointerMoved(p0 - vec2(60.0, 0.0))); h.step(); let z = h.state().current_zoom(); - assert!(z < z0 && (z - scrub_zoom(z0, -60.0)).abs() < 1e-4, "{z0} -> {z}"); + assert!(z < z0 && (z - scrub_zoom(z0, -60.0, h.state().ui.views[0].doc_size)).abs() < 1e-4, "{z0} -> {z}"); press(&mut h, p0 - vec2(60.0, 0.0), false); h.run_steps(2); // Release keeps the zoom; nothing was painted or recorded. @@ -192,7 +190,7 @@ mod tests { press(&mut h, p0, true); press(&mut h, p0, false); h.run_steps(2); - assert_eq!(h.state().current_zoom(), crate::canvas::zoom_step(zc, 1)); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(zc, 1, h.state().ui.views[0].doc_size)); } #[test]