From a4e2c92fe96573a447edf4025a774230cffa8127 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 21:26:17 +0700 Subject: [PATCH] canvas-w1: net change of 2 commits - canvas-w1: written from its sheet - canvas-w1: repair 1 --- crates/behavior/src/canvas/mod.rs | 2 +- crates/behavior/src/canvas/zoom.rs | 220 ++++++++---------- crates/behavior/src/hold_repeat.rs | 19 +- crates/behavior/src/lib.rs | 2 +- crates/behavior/tests/canvas_view.rs | 34 ++- crates/imaging/src/ui/fill/preview_pane.rs | 5 +- crates/pages/src/ui/fixtures.rs | 3 +- crates/pages/src/ui/view.rs | 11 +- .../src/canvas/full_window_parts/canvas.rs | 3 +- .../src/canvas/full_window_parts/view.rs | 36 +-- crates/ui-canvas/src/canvas/mod.rs | 17 +- crates/ui-canvas/src/canvas/momentary.rs | 10 +- crates/ui-canvas/src/canvas/navigate/mod.rs | 2 +- crates/ui-canvas/src/canvas/navigate/wheel.rs | 12 +- .../ui-canvas/src/canvas/navigator/preview.rs | 10 +- .../ui-canvas/src/canvas/navigator/proxy.rs | 10 +- .../src/canvas/navigator/zoom_row.rs | 13 +- crates/ui-canvas/src/canvas/space.rs | 1 - crates/ui-canvas/src/canvas/split/stories.rs | 2 +- crates/ui-canvas/src/canvas/tools.rs | 41 ++-- crates/ui-canvas/src/canvas/zoom_motion.rs | 21 +- crates/ui-canvas/tests/it/canvas/navigate.rs | 49 +++- crates/ui-canvas/tests/it/canvas/tools.rs | 44 +++- .../ui-canvas/tests/it/full_window_parts.rs | 8 +- crates/ui-widgets/src/text/zoom_field.rs | 21 +- migration/api-map/canvas-core.toml | 6 +- 26 files changed, 344 insertions(+), 258 deletions(-) diff --git a/crates/behavior/src/canvas/mod.rs b/crates/behavior/src/canvas/mod.rs index f53b7201d7..c2beaba566 100644 --- a/crates/behavior/src/canvas/mod.rs +++ b/crates/behavior/src/canvas/mod.rs @@ -10,7 +10,7 @@ pub mod zoom; pub use history::{ViewHistory, ViewPlace}; pub use units::{RulerUnits, Ticks}; pub use view::{CanvasView, resize_cursor}; -pub use zoom::{ZoomFloor, ZoomLadder, ZoomScheme}; +pub use zoom::{ZoomFloor, ZoomScheme}; /// A canvas body's mapping from canvas coordinates to its layer: `screen = canvas * scale + offset`. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/behavior/src/canvas/zoom.rs b/crates/behavior/src/canvas/zoom.rs index 0a9a2507e7..ed9fe4dd38 100644 --- a/crates/behavior/src/canvas/zoom.rs +++ b/crates/behavior/src/canvas/zoom.rs @@ -1,4 +1,4 @@ -//! Zoom rules as pure functions on a [`CanvasView`]: Photoshop's zoom range and Zoom In / Zoom Out ladder, Fit on +//! Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zoom In / Zoom Out rungs, Fit on //! Screen and Fill Screen, a zoom about a point and the anchors of wheel zoom. //! //! Zoom levels here are **device zoom**: device pixels per document unit, so 1 is 100 % at any interface scale. @@ -7,7 +7,7 @@ //! `zoom` back into its own view type. //! //! Every way of setting the zoom (wheel, Zoom tool, menu, zoom field, navigator, automation) clamps through -//! [`ZoomLadder::clamp`], so no control can pull the zoom into a narrower range of its own. +//! [`ZoomScheme::clamp`], so no control can pull the zoom into a narrower range of its own. use super::view::CanvasView; use emath::{Pos2, Rect as ScreenRect, Vec2 as ScreenVec}; @@ -18,94 +18,42 @@ use std::ops::RangeInclusive; const RUNG_TOLERANCE_UP: f64 = 1.001; const RUNG_TOLERANCE_DOWN: f64 = 0.999; -/// Photoshop's zoom range and the Zoom In / Zoom Out ladder, measured on Photoshop 25.4: up to -/// 12800 %, down to where the document's shorter side is 2 px on screen (no lower than 0.1 % for -/// a ladder step). A ladder step goes from any zoom to the next rung (880 %: in to 1200 %, out to -/// 800 %). -pub struct ZoomLadder; - -impl ZoomLadder { - /// 12800 %. - pub const MAX: f64 = 128.0; - - /// Zoom In / Zoom Out rungs (1 = 100 %). - pub const STEPS: [f64; 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` units: its shorter side 2 device pixels. An empty - /// size (a view before its first frame) gives the lowest rung. - pub fn min(size: Size) -> f64 { - match size.width.min(size.height) { - short if short.is_finite() && short > 0.0 => (2.0 / short).min(Self::MAX), - _ => Self::STEPS[0], - } - } - - /// `zoom` within the range for a document of `size`; a zoom that is not a finite number - /// becomes 100 %. - pub fn clamp(zoom: f64, size: Size) -> f64 { - if zoom.is_finite() { zoom.min(Self::MAX).max(Self::min(size)) } else { 1.0 } - } - - /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `zoom`: the next rung past it (a zoom - /// within 0.1 % of a rung counts as on it), within the document's range. - pub fn step(zoom: f64, dir: i32, size: Size) -> f64 { - Self::step_in_range(zoom, dir, Self::min(size)..=Self::MAX) - } - - /// [`step`](Self::step) within an explicit range (a navigator or a zoom field with bounds of - /// its own). - pub fn step_in_range(zoom: f64, dir: i32, range: RangeInclusive) -> f64 { - let (lo, hi) = range.into_inner(); - let z = if zoom.is_finite() { zoom.min(hi).max(lo) } else { 1.0 }; - let next = if dir > 0 { - Self::STEPS.iter().copied().find(|s| *s > z * RUNG_TOLERANCE_UP).unwrap_or(hi) - } else { - Self::STEPS.iter().rev().copied().find(|s| *s < z * RUNG_TOLERANCE_DOWN).unwrap_or(z) - }; - if next.is_finite() { next.min(hi).max(lo) } else { z } - } - - /// A zoom field's range in percent: the document's range widened to include `zoom` itself. - /// A field narrower than the zoom would clamp it and write it back every pass. - pub fn percent_range(zoom: f64, size: Size) -> RangeInclusive { - let z = if zoom.is_finite() { zoom } else { 1.0 }; - (Self::min(size).min(z) * 100.0)..=(Self::MAX.max(z) * 100.0) - } -} +/// Photoshop's Zoom In / Zoom Out rungs (1 = 100 %), measured on Photoshop 25.4. +const PHOTOSHOP_RUNGS: [f64; 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 least zoom: the document's shorter side that many device pixels, or a fixed zoom in scheme units. #[derive(Clone, Copy, Debug, PartialEq)] @@ -118,7 +66,7 @@ pub enum ZoomFloor { } /// A zoom range and its Zoom In and Out rungs in scheme units (1 = its 100 %); `hundred` is the device zoom of -/// 100 %. +/// 100 %. A step goes from any zoom to the next rung (880 %: in to 1200 %, out to 800 %). #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct ZoomScheme { @@ -133,9 +81,9 @@ pub struct ZoomScheme { } impl ZoomScheme { - /// Photoshop's: [`ZoomLadder::STEPS`], up to 12800 %, the shorter side 2 px at the least. + /// Photoshop's: 33 rungs, up to 12800 %, the shorter side 2 px at the least. pub const PHOTOSHOP: ZoomScheme = - ZoomScheme { rungs: &ZoomLadder::STEPS, max: ZoomLadder::MAX, floor: ZoomFloor::ShorterSide(2.0), hundred: 1.0 }; + ZoomScheme { rungs: &PHOTOSHOP_RUNGS, max: 128.0, floor: ZoomFloor::ShorterSide(2.0), hundred: 1.0 }; /// Illustrator's: 26 stops from 3.13 % to 64000 %. pub const ILLUSTRATOR: ZoomScheme = ZoomScheme { @@ -153,52 +101,63 @@ impl ZoomScheme { ZoomScheme { hundred: device, ..self } } - /// The least device zoom for a document of `size`. + /// The least device zoom for a document of `size`. An empty size (a view before its first frame) gives the lowest + /// rung. pub fn min(&self, size: Size) -> f64 { - let _ = size; - todo!("cv.F1") + match self.floor { + ZoomFloor::ShorterSide(pixels) => match size.width.min(size.height) { + short if short.is_finite() && short > 0.0 => (pixels / short).min(self.max_device()), + _ => self.rungs.first().map_or(self.hundred, |rung| rung * self.hundred), + }, + ZoomFloor::Fixed(zoom) => zoom * self.hundred, + } } /// The greatest device zoom. pub fn max_device(&self) -> f64 { - todo!("cv.F1") + self.max * self.hundred } /// `device` within the range for a document of `size`; a zoom that is not a finite number becomes 100 %. pub fn clamp(&self, device: f64, size: Size) -> f64 { - let _ = (device, size); - todo!("cv.F1") + if device.is_finite() { device.min(self.max_device()).max(self.min(size)) } else { self.hundred } } - /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it, within the document's - /// range. + /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it (a zoom within 0.1 % of a rung + /// counts as on it), within the document's range. pub fn step(&self, device: f64, dir: i32, size: Size) -> f64 { - let _ = (device, dir, size); - todo!("cv.F1") + self.step_in_range(device, dir, self.min(size)..=self.max_device()) } - /// [`step`](Self::step) within an explicit range of device zoom. + /// [`step`](Self::step) within an explicit range of device zoom (a navigator or a zoom field with bounds of its + /// own). pub fn step_in_range(&self, device: f64, dir: i32, range: RangeInclusive) -> f64 { - let _ = (device, dir, range); - todo!("cv.F1") + let (lo, hi) = range.into_inner(); + let z = if device.is_finite() { device.min(hi).max(lo) } else { self.hundred }; + let rungs = self.rungs.iter().map(|rung| rung * self.hundred); + let next = if dir > 0 { + rungs.clone().find(|s| *s > z * RUNG_TOLERANCE_UP).unwrap_or(hi) + } else { + rungs.rev().find(|s| *s < z * RUNG_TOLERANCE_DOWN).unwrap_or(z) + }; + if next.is_finite() { next.min(hi).max(lo) } else { z } } - /// A zoom field's range in percent: the document's range widened to include `device` itself. + /// A zoom field's range in percent: the document's range widened to include `device` itself. A field narrower than + /// the zoom would clamp it and write it back every pass. pub fn percent_range(&self, device: f64, size: Size) -> RangeInclusive { - let _ = (device, size); - todo!("cv.F1") + let z = if device.is_finite() { device } else { self.hundred }; + self.percent(self.min(size).min(z))..=self.percent(self.max_device().max(z)) } /// `device` zoom as percent of the scheme's 100 %. pub fn percent(&self, device: f64) -> f64 { - let _ = device; - todo!("cv.F1") + device / self.hundred * 100.0 } /// The device zoom of `percent` of the scheme's 100 %. pub fn device(&self, percent: f64) -> f64 { - let _ = percent; - todo!("cv.F1") + percent / 100.0 * self.hundred } } @@ -209,9 +168,8 @@ pub fn device(view: &CanvasView, pixels_per_point: f32) -> f64 { /// `view` at `device` zoom (1 = 100 %), clamped to the zoom range of a document of `size`, with its centre kept. pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> CanvasView { - let _ = scheme; // P3(canvas-w1): cv.F3 let mut next = *view; - next.zoom = CanvasView::points_per_unit(ZoomLadder::clamp(device, size), pixels_per_point); + next.zoom = CanvasView::points_per_unit(scheme.clamp(device, size), pixels_per_point); next } @@ -229,31 +187,37 @@ fn shown_extent(view: &CanvasView, size: Size) -> (f64, f64, f64, f64) { /// documents magnified). `size` is in document units; the view's [`aspect`](CanvasView::aspect) and rotation /// are taken into account. pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64, scheme: &ZoomScheme) { - fit_up_to(view, size, pixels_per_point, 1.0, margin, scheme); + fit_up_to(view, size, pixels_per_point, scheme.hundred, margin, scheme); } /// [`fit`] with the device zoom allowed up to `max_device` (1 = 100 %) instead of 100 %: a small document is /// magnified to fill the canvas, as Photoshop's Fit on Screen does. pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64, scheme: &ZoomScheme) { - let _ = scheme; // P3(canvas-w1): cv.F3 - fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin)); + fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin), scheme); } /// Fit a part of the document on screen (an artboard, the selected layers' bounds): centre `rect`, in document /// units, and zoom so all of it shows inside `view.rect` less `margin.x` points at the left and right and `margin.y` -/// at the top and bottom, up to the zoom ceiling. +/// at the top and bottom, up to the scheme's greatest zoom. /// The zoom stays inside the range of a document of `size`; an empty `rect` zooms to that ceiling about its centre. pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2, scheme: &ZoomScheme) { - let _ = scheme; // P3(canvas-w1): cv.F3 - fit_rect_up_to(view, rect, size, pixels_per_point, ZoomLadder::MAX, margin); + fit_rect_up_to(view, rect, size, pixels_per_point, scheme.max_device(), margin, scheme); } -fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, max_device: f64, margin: Vec2) { +fn fit_rect_up_to( + view: &mut CanvasView, + rect: Rect, + size: Size, + pixels_per_point: f32, + max_device: f64, + margin: Vec2, + scheme: &ZoomScheme, +) { let rect = rect.abs(); let (shown_w, shown_h, sin, cos) = shown_extent(view, rect.size()); let (bw, bh) = (shown_w * cos + shown_h * sin, shown_w * sin + shown_h * cos); let scale = ((f64::from(view.rect.width()) - 2.0 * margin.x) / bw).min((f64::from(view.rect.height()) - 2.0 * margin.y) / bh); - let device = ZoomLadder::clamp((scale * f64::from(pixels_per_point)).min(max_device), size); + let device = scheme.clamp((scale * f64::from(pixels_per_point)).min(max_device), size); view.zoom = CanvasView::points_per_unit(device, pixels_per_point); view.center = rect.center(); } @@ -269,12 +233,11 @@ pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> /// Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend /// past the canvas. pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) { - let _ = scheme; // P3(canvas-w1): cv.F3 let (shown_w, shown_h, sin, cos) = shown_extent(view, size); let (rw, rh) = (f64::from(view.rect.width()), f64::from(view.rect.height())); // The canvas rectangle's extent along the document's axes, which the document must cover. let (ex, ey) = (rw * cos + rh * sin, rw * sin + rh * cos); - let device = ZoomLadder::clamp((ex / shown_w).max(ey / shown_h) * f64::from(pixels_per_point), size); + let device = scheme.clamp((ex / shown_w).max(ey / shown_h) * f64::from(pixels_per_point), size); view.zoom = CanvasView::points_per_unit(device, pixels_per_point); view.center = Point::new(size.width / 2.0, size.height / 2.0); } @@ -312,13 +275,12 @@ pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2 { if nearest == d { screen } else { view.to_screen(nearest) } } -/// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next ladder rung -/// ([`ZoomLadder::step`]), the view's centre unchanged. Returns whether the zoom changed (it does +/// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next rung of the scheme +/// ([`ZoomScheme::step`]), the view's centre unchanged. Returns whether the zoom changed (it does /// not at a limit). pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { - let _ = scheme; // P3(canvas-w1): cv.F3 let current = device(view, pixels_per_point); - let next = ZoomLadder::step(current, dir, size); + let next = scheme.step(current, dir, size); let changed = next.is_finite() && (next / current - 1.0).abs() > 1e-9; if changed { view.zoom = CanvasView::points_per_unit(next, pixels_per_point); diff --git a/crates/behavior/src/hold_repeat.rs b/crates/behavior/src/hold_repeat.rs index 6436f62253..dd9fdf1670 100644 --- a/crates/behavior/src/hold_repeat.rs +++ b/crates/behavior/src/hold_repeat.rs @@ -10,26 +10,33 @@ pub const INTERVAL: f64 = 0.05; /// nothing). A different concept from `HoldZoom`, which zooms continuously at a rate. #[derive(Clone, Copy, Debug, Default)] pub struct HoldRepeat { - #[allow(dead_code)] // P3(widgets-w2): wg.W35 held_for: f64, - #[allow(dead_code)] // P3(widgets-w2): wg.W35 fired: u32, } impl HoldRepeat { /// Starts a press: the one step due now. pub fn press(&mut self) -> u32 { - todo!("wg.W35") + *self = Self::default(); + 1 } /// The steps due after `elapsed` more seconds of the press. pub fn hold(&mut self, elapsed: f64) -> u32 { - let _ = elapsed; - todo!("wg.W35") + self.held_for += elapsed.max(0.0); + let due = if self.held_for >= DELAY { + // Saturating float-to-int cast: a huge elapsed cannot panic. + ((self.held_for - DELAY) / INTERVAL).floor() as u32 + 1 + } else { + 0 + }; + let new = due.saturating_sub(self.fired); + self.fired = self.fired.max(due); + new } /// Ends the press. pub fn release(&mut self) { - todo!("wg.W35") + *self = Self::default(); } } diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 145790506d..71fda600c7 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -65,7 +65,7 @@ pub use anchor::Anchor9; pub use arrangement::Arrangement; pub use canvas::CanvasTransform; -pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomLadder, ZoomScheme, resize_cursor}; +pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomScheme, resize_cursor}; /// The f64 geometry crate the canvas view and its callers share. pub use kurbo; diff --git a/crates/behavior/tests/canvas_view.rs b/crates/behavior/tests/canvas_view.rs index e5e161a2da..2b71090371 100644 --- a/crates/behavior/tests/canvas_view.rs +++ b/crates/behavior/tests/canvas_view.rs @@ -55,22 +55,44 @@ fn fit_and_fill_measure_the_stretched_document() { // Fit keeps 20 points of margin per side: 1000 points across for a 1000 px wide document, 2000 shown at aspect 2. let (mut square, mut wide) = (stage(1.0, rect(1040.0, 800.0)), stage(2.0, rect(1040.0, 800.0))); - zoom::fit(&mut square, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 - zoom::fit(&mut wide, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fit(&mut square, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); + zoom::fit(&mut wide, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.5), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); // On a square rect the height limits fill at both aspects; the 1000 by 400 rect below is where the stretched width decides. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 1000.0)), stage(2.0, rect(1000.0, 1000.0))); - zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 - zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 2.0) && near(wide.zoom, 2.0), "{} {}", square.zoom, wide.zoom); // A wide rect: the unstretched document is limited by its width, the stretched one by its height. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 400.0)), stage(2.0, rect(1000.0, 400.0))); - zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 - zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.8), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); } + +#[test] +fn a_scheme_steps_and_clamps_in_its_own_units_about_its_hundred() { + let (small, big) = (Size::new(100.0, 100.0), Size::new(10_000.0, 10_000.0)); + + let illustrator = ZoomScheme::ILLUSTRATOR; + let up = illustrator.step(1.0, 1, big); + assert!(near(up, 1.5), "{up}"); + assert!(near(illustrator.step(up, -1, big), 1.0), "a step in then out returns to the rung"); + assert!(near(illustrator.min(small), 0.0313) && near(illustrator.min(big), 0.0313), "a fixed floor ignores the document"); + + let photoshop = ZoomScheme::PHOTOSHOP; + assert!(near(photoshop.min(small), 0.02), "{}", photoshop.min(small)); + assert!(photoshop.min(big) < photoshop.min(small), "the floor follows the shorter side"); + + let doubled = photoshop.with_hundred(2.0); + for device in [0.5, 3.0, 40.0] { + assert!(near(doubled.device(doubled.percent(device)), device), "{device}"); + } + assert!(near(doubled.step(2.0, 1, small), 4.0), "the rung after the scheme's 100 % is the next rung times it"); + assert!(near(photoshop.clamp(f64::NAN, small), 1.0) && near(doubled.clamp(f64::NAN, small), 2.0), "a non-finite zoom is 100 %"); +} diff --git a/crates/imaging/src/ui/fill/preview_pane.rs b/crates/imaging/src/ui/fill/preview_pane.rs index 558646e7ab..1dbc20ea5b 100644 --- a/crates/imaging/src/ui/fill/preview_pane.rs +++ b/crates/imaging/src/ui/fill/preview_pane.rs @@ -3,13 +3,14 @@ use egui::{Response, Ui}; use craft_behavior::kurbo::{Point, Rect, Size}; -use craft_behavior::{CanvasView, ZoomLadder}; +use craft_behavior::{CanvasView, ZoomScheme}; use craft_ui::canvas::{NavigationOptions, RasterSource, ViewCommands}; use craft_ui::contract::{Bind, Pattern, ShowContainer as _}; use craft_ui::dialog::{FullWindowCanvas, FullWindowStatus, FullWindowView, FullWindowZoomBar}; use craft_ui::layout_components::Stack; use craft_ui::primitives::Checker; use craft_ui::runtime::commands::CommandSet as _; +use craft_ui::runtime::env::Env; use craft_ui::runtime::pending::Pending; use crate::ui::wide_angle::PreviewDone; @@ -110,7 +111,7 @@ fn frame_view(ui: &Ui, view: &mut FullWindowView, framing: &mut PreviewFraming, let ppp = ui.pixels_per_point(); let device_room = |side: f32| f64::from(side) * f64::from(ppp); let fit = (device_room(room.width()) / frame.width().max(1.0)).min(device_room(room.height()) / frame.height().max(1.0)); - let device = ZoomLadder::clamp(fit, Size::new(f64::from(size.width), f64::from(size.height))); + let device = Env::of_root(ui.ctx()).view().get::().clamp(fit, Size::new(f64::from(size.width), f64::from(size.height))); let center = Point::new((frame.x0 + frame.x1) / 2.0, (frame.y0 + frame.y1) / 2.0); let mut next = current; next.center = center; diff --git a/crates/pages/src/ui/fixtures.rs b/crates/pages/src/ui/fixtures.rs index 3b257bc072..8849d78a2b 100644 --- a/crates/pages/src/ui/fixtures.rs +++ b/crates/pages/src/ui/fixtures.rs @@ -21,8 +21,7 @@ const FIT_MARGIN: f64 = 24.0; /// screen whatever the size of `view.rect`. pub fn fitted_page(view: &mut CanvasView, pixels_per_point: f32) -> PlacedPage { let size = Size::new(LETTER_WIDTH, LETTER_HEIGHT); - // P3(canvas-w1): cv.F3 - craft_behavior::canvas::zoom::fit(view, size, pixels_per_point, FIT_MARGIN, &craft_behavior::canvas::zoom::ZoomScheme::PHOTOSHOP); + craft_behavior::canvas::zoom::fit(view, size, pixels_per_point, FIT_MARGIN, &craft_behavior::ZoomScheme::PHOTOSHOP); let rect = Rect::from_min_max(view.to_screen(kurbo::Point::ZERO), view.to_screen(kurbo::Point::new(LETTER_WIDTH, LETTER_HEIGHT))); PlacedPage::new(0, rect, view.zoom, (0.0, rect.height())) } diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 478ecd3b9c..9e46f2c9ef 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -28,7 +28,7 @@ use crate::layout::{ Fit, LayoutOptions, PageDisplay, PageSpacing, PagedLayout, SCREEN_POINTS_PER_POINT, ViewDefaults, ZOOM_RANGE, fit_scale, place_pages, shown_row, }; use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; -use craft_behavior::{CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder}; +use craft_behavior::{CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomScheme}; use craft_ui::canvas::{ BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, PageKey, Pasteboard, PasteboardOutput, ToolPass, canvas_space, tool_pass, @@ -128,12 +128,11 @@ impl PageViewState { self.current = page; } - /// Zoom In / Zoom Out: the next rung of craft-ui's [`ZoomLadder`] above (or below) the shown zoom, within - /// [`ZOOM_RANGE`] (Photoshop's rungs, the suite's one zoom ladder); a fit ends. The zoom a fit showed is the - /// start. - pub fn zoom_step(&mut self, larger: bool) { + /// Zoom In / Zoom Out: the next rung of `scheme` above (or below) the shown zoom, within [`ZOOM_RANGE`]; a fit + /// ends. The zoom a fit showed is the start. + pub fn zoom_step(&mut self, larger: bool, scheme: &ZoomScheme) { self.fit = Fit::None; - self.zoom = ZoomLadder::step_in_range(self.zoom, if larger { 1 } else { -1 }, ZOOM_RANGE); + self.zoom = scheme.step_in_range(self.zoom, if larger { 1 } else { -1 }, ZOOM_RANGE); } } diff --git a/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs b/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs index adfd14c9a9..66aca9312e 100644 --- a/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs +++ b/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs @@ -212,7 +212,8 @@ impl<'a> FullWindowCanvas<'a> { // flow; the canvas itself has no content size, so a content-sized column around it (a preview pane in a // side column) sizes from its other content instead of taking the whole room the canvas is offered. let rect = ui.available_rect_before_wrap(); - let shown = given.settled(rect, size, ppp); + let scheme = Env::of_root(ui.ctx()).view().get::(); + let shown = given.settled(rect, size, ppp, &scheme); // What the tool host did; none in a measuring run, where it does not run. let mut hosted = None; let canvas = Canvas::new(label.clone()).view(shown.view()).document(shown.size()).navigation(navigation).outer_view_commands().show_at( diff --git a/crates/ui-canvas/src/canvas/full_window_parts/view.rs b/crates/ui-canvas/src/canvas/full_window_parts/view.rs index 73ab925846..52c349d7d9 100644 --- a/crates/ui-canvas/src/canvas/full_window_parts/view.rs +++ b/crates/ui-canvas/src/canvas/full_window_parts/view.rs @@ -4,7 +4,7 @@ use crate::canvas::{ViewCommands, ViewTarget}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, PixelSize, ZoomLadder, ZoomScheme}; +use craft_behavior::{CanvasView, PixelSize, ZoomScheme}; use egui::Rect; /// Zooms closer than this are the same zoom (a round trip through points per unit and back differs in the last @@ -24,13 +24,15 @@ const FIT_MAX: f64 = 4.0; /// 400 %). /// - A zoom (wheel, pinch, commands, the Zoom tool, the zoom bar) or a pan (Space, the middle button, the Hand tool) /// by the user ends the fit; [`ViewCommands::FitOnScreen`] returns to it. -/// - Zooms stay inside `ZoomLadder`'s range for the image's size. +/// - Zooms stay inside the zoom scheme's range for the image's size; the scheme is the one the canvas last settled the +/// view with. #[derive(Clone, Copy, Debug, PartialEq)] pub struct FullWindowView { fit: bool, view: CanvasView, size: Size, pixels_per_point: f32, + scheme: ZoomScheme, } impl Default for FullWindowView { @@ -42,7 +44,13 @@ impl Default for FullWindowView { impl FullWindowView { /// A fitted view of an image not yet shown. pub fn new() -> Self { - Self { fit: true, view: CanvasView::new(Rect::ZERO, Point::ZERO, 1.0), size: Size::ZERO, pixels_per_point: 1.0 } + Self { + fit: true, + view: CanvasView::new(Rect::ZERO, Point::ZERO, 1.0), + size: Size::ZERO, + pixels_per_point: 1.0, + scheme: ZoomScheme::PHOTOSHOP, + } } /// Whether the view fits the image: until the user zooms or pans, and after `ViewCommands::FitOnScreen`. @@ -68,15 +76,17 @@ impl FullWindowView { /// The zoom on screen as a percentage (66.7 for 66.7 %), the fitted zoom while fitted: the title's and the zoom /// bar's value. pub fn zoom_percent(&self) -> f64 { - self.device_zoom() * 100.0 + self.scheme.percent(self.device_zoom()) } - /// The view on `rect` for an image of `size` pixels at `pixels_per_point`: fitted while [`is_fit`](Self::is_fit), - /// else the zoom and centre kept. Records `size` and, while fitted, the zoom it fitted to. + /// The view on `rect` for an image of `size` pixels at `pixels_per_point`, zooming by `scheme`: fitted while + /// [`is_fit`](Self::is_fit), else the zoom and centre kept. Records `size`, `scheme` and, while fitted, the zoom it + /// fitted to. #[must_use] - pub fn settled(mut self, rect: Rect, size: PixelSize, pixels_per_point: f32) -> Self { + pub fn settled(mut self, rect: Rect, size: PixelSize, pixels_per_point: f32, scheme: &ZoomScheme) -> Self { self.size = Size::new(f64::from(size.width), f64::from(size.height)); self.pixels_per_point = pixels_per_point; + self.scheme = *scheme; self.view.rect = rect; self.refit(); self @@ -91,7 +101,7 @@ impl FullWindowView { fn refit(&mut self) { if self.fit && self.size.width > 0.0 && self.size.height > 0.0 { let target = self.target(); - ViewCommands::FitOnScreen.apply(&mut self.view, &target, None, self.pixels_per_point, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F8 + ViewCommands::FitOnScreen.apply(&mut self.view, &target, None, self.pixels_per_point, &self.scheme); } } @@ -109,13 +119,13 @@ impl FullWindowView { /// Whether a zoom step in (`dir` > 0) or out would change the zoom. pub fn can_step(&self, dir: i32) -> bool { let command = if dir > 0 { ViewCommands::ZoomIn } else { ViewCommands::ZoomOut }; - command.available(&self.view, &self.target(), None, self.pixels_per_point, &ZoomScheme::PHOTOSHOP) // P3(canvas-w1): cv.F8 + command.available(&self.view, &self.target(), None, self.pixels_per_point, &self.scheme) } - /// Sets the device zoom (kept inside the ladder's range) about the view's centre and ends the fit. Returns whether + /// Sets the device zoom (kept inside the scheme's range) about the view's centre and ends the fit. Returns whether /// anything changed. pub fn set_device_zoom(&mut self, device: f64) -> bool { - let device = ZoomLadder::clamp(device, self.size); + let device = self.scheme.clamp(device, self.size); let changed = self.fit || (device / self.device_zoom() - 1.0).abs() > SAME; let center = self.view.rect.center(); zoom::about(&mut self.view, center, device, false, self.pixels_per_point); @@ -131,7 +141,7 @@ impl FullWindowView { match command { ViewCommands::ZoomIn | ViewCommands::ZoomOut => { let target = self.target(); - let changed = command.apply(&mut self.view, &target, None, self.pixels_per_point, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F8 + let changed = command.apply(&mut self.view, &target, None, self.pixels_per_point, &self.scheme); self.fit &= !changed; changed } @@ -143,7 +153,7 @@ impl FullWindowView { } ViewCommands::ActualPixels => { let target = self.target(); - let changed = command.apply(&mut self.view, &target, None, self.pixels_per_point, &ZoomScheme::PHOTOSHOP) || self.fit; // P3(canvas-w1): cv.F8 + let changed = command.apply(&mut self.view, &target, None, self.pixels_per_point, &self.scheme) || self.fit; self.fit = false; changed } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 9f8568e753..71bc6fe1a6 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -103,7 +103,7 @@ use crate::contract::{ Bind, Common, Component, Container, ContainerProps, Cx, Focus as _, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, Sizing, }; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; -use crate::runtime::env::Label; +use crate::runtime::env::{Env, Label}; use crate::runtime::focus::KeyUse; use crate::runtime::lock_keys; use crate::runtime::measure; @@ -345,7 +345,7 @@ impl<'a> Canvas<'a> { fn view_commands(&self, cx: &mut Cx<'_, Self>, view: Option) -> Option<(CanvasView, CommandMotion)> { self.props.command_scope?; let pixels_per_point = cx.env.scale().0; - let scheme = ZoomScheme::PHOTOSHOP; // P3(canvas-w1): cv.F8 + let scheme = Env::of_root(&cx.core.ctx).view().get::(); let target = view.zip(self.document); for command in ViewCommands::ALL { let enabled = target.is_some_and(|(view, document)| command.available(&view, &document, self.layer_bounds, pixels_per_point, &scheme)); @@ -393,7 +393,7 @@ impl<'a> Canvas<'a> { let mut motion = ViewMotion::take(&ctx, id); let pixels_per_point = cx.env.scale().0; let size = self.document_size().unwrap_or(Size::ZERO); - let scheme = ZoomScheme::PHOTOSHOP; // P3(canvas-w1): cv.F7 + let scheme = Env::of_root(&ctx).view().get::(); let mut view = given; let area = self.view_rect(cx.content_rect, cx.style); if area.width() > 0.0 && area.height() > 0.0 { @@ -497,7 +497,7 @@ impl<'a> Canvas<'a> { } /// The space the body and the tool see in this pass; `caps_lock` is whether Caps Lock is on in it. - fn space(&self, id: egui::Id, pixels_per_point: f32, background: BackgroundPress, caps_lock: bool) -> Option { + fn space(&self, id: egui::Id, pixels_per_point: f32, background: BackgroundPress, caps_lock: bool, scheme: ZoomScheme) -> Option { let (shown, target, easing, keys) = match self.settled { Some(settled) => (settled.shown, settled.target, settled.easing, settled.keys), None => (self.given?, self.given?, false, BodyKeys::default()), @@ -514,6 +514,7 @@ impl<'a> Canvas<'a> { .with_pasteboard(self.pasteboard) .with_background(background) .with_precise(self.precise_cursors != caps_lock) + .with_zoom_scheme(scheme) .with_canvas(id); Some(match self.picture { Some(slot) => space.with_picture(slot), @@ -548,7 +549,8 @@ impl<'a> Canvas<'a> { fn tool_pass(&self, cx: &Cx<'_, Self>) -> ToolPass { let press = self.background_press(cx).0; let caps_lock = lock_keys::caps_lock(&cx.response.ctx); - let space = self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key), caps_lock); + let scheme = Env::of_root(&cx.response.ctx).view().get::(); + let space = self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key), caps_lock, scheme); ToolPass { id: cx.response.id, rect: cx.response.rect, @@ -725,9 +727,10 @@ impl Component for Canvas<'_> { } } - fn finish(self, cx: Cx<'_, Self>) -> CanvasOutput { + fn finish(self, mut cx: Cx<'_, Self>) -> CanvasOutput { let pass = self.tool_pass(&cx); - CanvasOutput { response: cx.response.clone(), press: pass.press, space: pass.space, view: pass.view, multi_tap: None } + let multi_tap = cx.take_multi_tap(); + CanvasOutput { response: cx.response.clone(), press: pass.press, space: pass.space, view: pass.view, multi_tap } } } diff --git a/crates/ui-canvas/src/canvas/momentary.rs b/crates/ui-canvas/src/canvas/momentary.rs index b134a61a90..4e634a8b74 100644 --- a/crates/ui-canvas/src/canvas/momentary.rs +++ b/crates/ui-canvas/src/canvas/momentary.rs @@ -1,7 +1,8 @@ //! Momentary tools, as in Photoshop: tools in effect only while a key is held. //! //! Space is the Hand while held, Cmd+Space (Ctrl+Space off the Mac) Zoom In, Alt+Space Zoom Out; Alt added to a held -//! Zoom In zooms out. The keys are the [`MomentaryCommands`] set (`Kind::Momentary`): the board fires a press when the +//! Zoom In zooms out. Rotate View is a command of its own, and with [`MomentaryShift::RotateView`] Shift added to the +//! held Hand is Rotate View. The keys are the [`MomentaryCommands`] set (`Kind::Momentary`): the board fires a press when the //! key goes down and a release when it comes up. The set is scoped to the canvas (`canvasView`), so the commands go //! to the canvas that holds the key focus or surrounds it, else the one that held it last. //! [`ToolHost::run`](super::ToolHost::run) takes them for its canvas and folds them into [`Momentary`], which picks @@ -92,7 +93,6 @@ pub struct Momentary { zoom: ZoomTool, rotate: RotateViewTool, /// What a held Shift does to the Hand. - #[allow(dead_code)] // P3(canvas-w1): cv.F10 shift: MomentaryShift, /// The selected tool is the Hand: Cmd and Alt at a press then give Zoom In and Zoom Out. hand_selected: bool, @@ -173,10 +173,14 @@ impl Momentary { match held { Some(held) => { let tool = MomentaryTool::from(held); - Some(if mods.alt { + Some(if tool == MomentaryTool::RotateView { + tool + } else if mods.alt { MomentaryTool::ZoomOut } else if tool == MomentaryTool::Hand && (mods.cmd || mods.ctrl) { MomentaryTool::ZoomIn + } else if tool == MomentaryTool::Hand && mods.shift && self.shift == MomentaryShift::RotateView { + MomentaryTool::RotateView } else { tool }) diff --git a/crates/ui-canvas/src/canvas/navigate/mod.rs b/crates/ui-canvas/src/canvas/navigate/mod.rs index 93b3a32637..a620348db4 100644 --- a/crates/ui-canvas/src/canvas/navigate/mod.rs +++ b/crates/ui-canvas/src/canvas/navigate/mod.rs @@ -3,7 +3,7 @@ //! //! Each piece is a pure rule over a [`CanvasView`]: the app (or the canvas's body) reads the pass's input from the //! runtime, asks the rule for the new view and copies it back into its own view. Zooms go through -//! `craft_behavior::canvas::zoom` and clamp to the [`ZoomLadder`](craft_behavior::ZoomLadder). With Overscroll off +//! `craft_behavior::canvas::zoom` and clamp to the [`ZoomScheme`](craft_behavior::ZoomScheme). With Overscroll off //! the caller clamps the result with the canvas's scroll limits. mod bar; diff --git a/crates/ui-canvas/src/canvas/navigate/wheel.rs b/crates/ui-canvas/src/canvas/navigate/wheel.rs index 3f94d7d85a..bb85260dce 100644 --- a/crates/ui-canvas/src/canvas/navigate/wheel.rs +++ b/crates/ui-canvas/src/canvas/navigate/wheel.rs @@ -8,7 +8,7 @@ use super::NavigationOptions; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Size; -use craft_behavior::{CanvasView, Wheel, WheelNotch, WheelUnit, ZoomLadder, ZoomScheme}; +use craft_behavior::{CanvasView, Wheel, WheelNotch, WheelUnit, ZoomScheme}; use craft_keymap::{Mods, Platform}; use egui::{Pos2, Vec2}; @@ -138,6 +138,11 @@ impl WheelNavigation { self.residual = 0.0; return Some(WheelAction::Zoom(f64::from(factor))); } + // Two fingers moving together pan before any modifier rule reads the pass; the content follows them. + if options.touch_gestures && input.touch_pan != Vec2::ZERO && input.touch_pan.is_finite() { + self.residual = 0.0; + return Some(WheelAction::Pan(input.touch_pan)); + } let scroll_finite = input.scroll.x.is_finite() && input.scroll.y.is_finite(); let plain = !input.mods.cmd && !input.mods.ctrl; let zooms = if options.zoom_with_wheel { plain && !input.mods.alt } else { Self::alt_gesture(input.mods, input.os) }; @@ -174,12 +179,11 @@ impl WheelNavigation { /// zoom limit the view stays put. With Overscroll off the canvas clamps the result to the document. Returns /// whether the view changed. pub fn apply(view: &mut CanvasView, action: WheelAction, pointer: Pos2, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { - let _ = scheme; // P3(canvas-w1): cv.F11 let before = *view; match action { WheelAction::Zoom(factor) => { let current = zoom::device(view, pixels_per_point); - let next = ZoomLadder::clamp(current * factor, size); + let next = scheme.clamp(current * factor, size); if factor.is_finite() && factor > 0.0 && (next / current - 1.0).abs() > 1e-12 { let at = zoom::wheel_anchor(view, pointer, size); zoom::about(view, at, next, false, pixels_per_point); @@ -188,7 +192,7 @@ impl WheelNavigation { WheelAction::SnapZoom(steps) => { let dir = steps.signum(); let current = zoom::device(view, pixels_per_point); - let next = (0..steps.unsigned_abs()).fold(current, |z, _| ZoomLadder::step(z, dir, size)); + let next = (0..steps.unsigned_abs()).fold(current, |z, _| scheme.step(z, dir, size)); if dir != 0 && (next / current - 1.0).abs() > 1e-12 { zoom::about(view, pointer, next, false, pixels_per_point); } diff --git a/crates/ui-canvas/src/canvas/navigator/preview.rs b/crates/ui-canvas/src/canvas/navigator/preview.rs index 5b3796658a..73ff509803 100644 --- a/crates/ui-canvas/src/canvas/navigator/preview.rs +++ b/crates/ui-canvas/src/canvas/navigator/preview.rs @@ -15,14 +15,14 @@ use crate::primitives::PaintShape; use crate::primitives::textures::CachedTexture; use crate::runtime::access::Numeric; use crate::runtime::commands; -use crate::runtime::env::Label; +use crate::runtime::env::{Env, Label}; use crate::runtime::focus::{ActivateKeys, KeepKeys, KeyUse}; use crate::style::{ComponentStyle, FocusLook, StyleCx, UiTokens}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; use craft_behavior::{ AccessAction, AccessData, CancelReason, CanvasView, CursorIcon, CursorPriority, HitLevel, HitPriority, HitShape, Metrics, NavMove, PartKey, - PressCancel, PressPhase, Sense, + PressCancel, PressPhase, Sense, ZoomScheme, }; use craft_keymap::{Chord, Key, Mods}; use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, pos2}; @@ -348,6 +348,7 @@ impl Component for Navigator<'_> { } } } + let scheme = Env::of_root(&cx.core.ctx).view().get::(); // The view the zoom rectangle asks for at its release. let mut boxed = None; if held.active { @@ -376,6 +377,7 @@ impl Component for Navigator<'_> { craft_behavior::kurbo::Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)), document, ppp, + &scheme, ) { boxed = Some(next); } @@ -410,7 +412,7 @@ impl Component for Navigator<'_> { let action = cx.memory::().read(&wheel, line, os, &options); if let Some(action @ (WheelAction::Zoom(_) | WheelAction::SnapZoom(_))) = action { let before = next; - WheelNavigation::apply(&mut next, action, before.rect.center(), document, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F11 + WheelNavigation::apply(&mut next, action, before.rect.center(), document, ppp, &scheme); next.center = before.center; zoomed |= next.zoom != before.zoom; } @@ -418,7 +420,7 @@ impl Component for Navigator<'_> { for (chord, dir) in ZOOM_KEYS { while cx.take_claimed(chord) { if !running { - zoomed |= zoom::step(&mut next, dir, document, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoomed |= zoom::step(&mut next, dir, document, ppp, &scheme); } } cx.claim(chord); diff --git a/crates/ui-canvas/src/canvas/navigator/proxy.rs b/crates/ui-canvas/src/canvas/navigator/proxy.rs index 968a153c79..c885961957 100644 --- a/crates/ui-canvas/src/canvas/navigator/proxy.rs +++ b/crates/ui-canvas/src/canvas/navigator/proxy.rs @@ -4,7 +4,7 @@ use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Rect as DocRect, Size, Vec2 as DocVec}; -use craft_behavior::{CanvasView, ZoomLadder}; +use craft_behavior::{CanvasView, ZoomScheme}; use egui::{Pos2, Rect, pos2, vec2}; /// A zoom rectangle under this many document units on a side steps one rung in instead. @@ -49,11 +49,11 @@ pub fn proxy_quad(view: &CanvasView, size: Size, preview: Rect) -> [Pos2; 4] { /// would turn a NaN edge into a document edge. /// - `doc_rect` is intersected with the document `(0, 0)..size`; a negative width or height after that (a rectangle /// off the document) does nothing. -/// - Under 2 document units on a side, or an empty canvas: one ladder rung in ([`ZoomLadder::step`] with `dir` 1). +/// - Under 2 document units on a side, or an empty canvas: one rung of `scheme` in ([`ZoomScheme::step`] with `dir` 1). /// - Otherwise [`zoom::fit_rect`] with no margin: the whole clipped rectangle shows, with the view's pixel aspect and /// rotation. /// - The centre becomes the clipped rectangle's centre. -pub fn zoom_to_document_rect(view: &mut CanvasView, doc_rect: DocRect, size: Size, pixels_per_point: f32) -> bool { +pub fn zoom_to_document_rect(view: &mut CanvasView, doc_rect: DocRect, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { let edges = [doc_rect.x0, doc_rect.y0, doc_rect.x1, doc_rect.y1]; if !edges.iter().all(|edge| edge.is_finite()) { return false; @@ -69,14 +69,14 @@ pub fn zoom_to_document_rect(view: &mut CanvasView, doc_rect: DocRect, size: Siz let canvas = view.rect.size(); let before = *view; if width < MIN_ZOOM_BOX || height < MIN_ZOOM_BOX || canvas.x <= 0.0 || canvas.y <= 0.0 { - let device = ZoomLadder::step(zoom::device(view, ppp), 1, size); + let device = scheme.step(zoom::device(view, ppp), 1, size); if !device.is_finite() { return false; } view.zoom = CanvasView::points_per_unit(device, ppp); view.center = Point::new(x0 + width / 2.0, y0 + height / 2.0); } else { - zoom::fit_rect(view, DocRect::new(x0, y0, x1, y1), size, ppp, DocVec::ZERO, &craft_behavior::ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fit_rect(view, DocRect::new(x0, y0, x1, y1), size, ppp, DocVec::ZERO, scheme); } *view != before } diff --git a/crates/ui-canvas/src/canvas/navigator/zoom_row.rs b/crates/ui-canvas/src/canvas/navigator/zoom_row.rs index ae68a28066..13ce65ada8 100644 --- a/crates/ui-canvas/src/canvas/navigator/zoom_row.rs +++ b/crates/ui-canvas/src/canvas/navigator/zoom_row.rs @@ -9,7 +9,7 @@ use crate::text::{InvalidZoom, ZoomField}; use crate::value_drag::{Slider, SliderScale}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Size; -use craft_behavior::{CanvasView, EditEvent, EditEvents, IconId, Mixed, ZoomLadder}; +use craft_behavior::{CanvasView, EditEvent, EditEvents, IconId, Mixed, ZoomScheme}; use egui::{Response, Ui}; /// What the zoom row reports. @@ -44,7 +44,7 @@ impl Outcome for NavigatorZoomRowOutput { /// - The slider is logarithmic over the same range, so equal distances are equal ratios and it always holds the /// current zoom. It follows the interface direction like every slider, so in right-to-left the value grows toward /// the left, where Zoom In sits. -/// - Every zoom goes through [`ZoomLadder::clamp`] and keeps the view's centre. +/// - Every zoom goes through [`ZoomScheme::clamp`] and keeps the view's centre. /// - A disabled container around the row disables its field, buttons and slider. #[must_use = "show the zoom row with `show`"] #[derive(crate::contract::Pattern)] @@ -66,6 +66,7 @@ impl<'a> NavigatorZoomRow<'a> { let words = env.words::(); let units = env.units(); let pixels_per_point = env.scale.0; + let scheme = env.view().get::(); let zoom_label = words.navigator_zoom.clone(); let mut events = EditEvents::new(); @@ -73,7 +74,7 @@ impl<'a> NavigatorZoomRow<'a> { let shown = Row::new().show(ui, |ui, cx| { let Some(Mixed::Same(current)) = view.reborrow().read(cx) else { return }; let device = zoom::device(¤t, pixels_per_point); - let at = |device: f64| zoom::with_device(¤t, device, document, pixels_per_point, &craft_behavior::ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + let at = |device: f64| zoom::with_device(¤t, device, document, pixels_per_point, &scheme); let mut edits: Vec> = Vec::new(); let field = ZoomField::new(zoom_label.clone(), Some(current), document).stepper(true).show(ui); @@ -82,12 +83,12 @@ impl<'a> NavigatorZoomRow<'a> { IconButton::command(IconId::new("minus"), ViewCommands::ZoomOut).show(ui); - let low = ZoomLadder::min(document).min(device); - let high = ZoomLadder::MAX.max(device); + let low = scheme.min(document).min(device); + let high = scheme.max_device().max(device); let slider = Slider::new(Bind::given(device), low..=high) .scale(SliderScale::Log) .label(zoom_label.clone()) - .value_text(units.zoom_percent(device * 100.0)) + .value_text(units.zoom_percent(scheme.percent(device))) .show(ui); edits.extend(slider.events.clone().map(at)); diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 4ac1855bd9..05c5f6c832 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -165,7 +165,6 @@ impl CanvasSpace { /// This space with the root env's zoom `scheme`. #[must_use] - #[allow(dead_code)] // P3(canvas-w1): cv.F6 pub(crate) fn with_zoom_scheme(mut self, scheme: ZoomScheme) -> Self { self.zoom_scheme = scheme; self diff --git a/crates/ui-canvas/src/canvas/split/stories.rs b/crates/ui-canvas/src/canvas/split/stories.rs index 6bfdda1f80..2124284964 100644 --- a/crates/ui-canvas/src/canvas/split/stories.rs +++ b/crates/ui-canvas/src/canvas/split/stories.rs @@ -30,7 +30,7 @@ fn split(ui: &mut Ui, layout: SplitLayout, count: usize, main: usize, at: Bind<' let views = SplitViews::new("Views", layout, at).count(count).active(main).show(ui, |ui, body| { for (pane, rect) in shown.placed(layout, count, body.rect, body.env.direction().is_rtl()).into_iter().enumerate() { let mut view = CanvasView::new(rect, document.centre(), 1.0); - zoom::fit(&mut view, Size::new(f64::from(size.width), f64::from(size.height)), ppp, 0.0, &craft_behavior::ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fit(&mut view, Size::new(f64::from(size.width), f64::from(size.height)), ppp, 0.0, &craft_behavior::ZoomScheme::PHOTOSHOP); let name = if pane == main { "Main view" } else { "View" }; Canvas::new(name).view(view).show_at(ui, rect, |ui, body| show_document(ui, body.rect, document)); } diff --git a/crates/ui-canvas/src/canvas/tools.rs b/crates/ui-canvas/src/canvas/tools.rs index 6590b3ad4b..70b6a2f23b 100644 --- a/crates/ui-canvas/src/canvas/tools.rs +++ b/crates/ui-canvas/src/canvas/tools.rs @@ -9,13 +9,14 @@ use super::navigate::{FlickPan, NavigationOptions, pan}; use super::rotate::ViewTurn; use super::zoom_motion::{HoldZoom, ZoomDrag}; -use super::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; +use super::readout::angle_row; +use super::{CanvasTool, CanvasWords, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; use crate::primitives::Draw; use craft_behavior::PointerButton; use craft_behavior::canvas::zoom; use craft_behavior::geometry::crop::normalized_angle; use craft_behavior::kurbo::{Rect, Size, Vec2}; -use craft_behavior::{CancelReason, CanvasView, Cursor, PaintedCursor, ZoomLadder, ZoomScheme}; +use craft_behavior::{CancelReason, CanvasView, Cursor, PaintedCursor, ZoomScheme}; use craft_keymap::Mods; use egui::Pos2; @@ -190,7 +191,7 @@ impl ViewCommands { let before = *view; let size = target.document; let zoom_about_centre = |view: &mut CanvasView, device: f64| { - zoom::about(view, view.rect.center(), ZoomLadder::clamp(device, size), false, pixels_per_point); + zoom::about(view, view.rect.center(), scheme.clamp(device, size), false, pixels_per_point); }; match self { ViewCommands::ZoomIn => { @@ -201,8 +202,8 @@ impl ViewCommands { } ViewCommands::FitOnScreen => zoom::fit_up_to(view, size, pixels_per_point, target.fit_ceiling, FIT_MARGIN, scheme), ViewCommands::FillScreen => zoom::fill(view, size, pixels_per_point, scheme), - ViewCommands::ActualPixels => zoom_about_centre(view, 1.0), - ViewCommands::TwoHundredPercent => zoom_about_centre(view, 2.0), + ViewCommands::ActualPixels => zoom_about_centre(view, scheme.hundred), + ViewCommands::TwoHundredPercent => zoom_about_centre(view, 2.0 * scheme.hundred), ViewCommands::PrintSize => { if let Some(device) = target.print_zoom() { zoom_about_centre(view, device); @@ -461,12 +462,13 @@ impl ZoomTool { let (Some(drag), Some(space)) = (self.drag.as_mut(), cx.space()) else { return }; let Some(size) = space.document() else { return }; let ppp = space.pixels_per_point; + let scheme = space.zoom_scheme(); let mut view = space.view; let before = view; let mut waiting = false; let held = match self.hold.as_mut() { Some(hold) => { - let held = hold.advance(&mut view, time, out, size, ppp); + let held = hold.advance(&mut view, time, out, size, ppp, &scheme); // The press asks for passes while it waits out the delay and while it zooms. waiting = held || hold.waiting(time); held @@ -474,7 +476,7 @@ impl ZoomTool { None => false, }; if !held { - drag.drag(&mut view, at, size, ppp); + drag.drag(&mut view, at, size, ppp, &scheme); } if waiting { cx.request_repaint(); @@ -485,11 +487,19 @@ impl ZoomTool { } } -/// The view after a Zoom tool click at `screen`: one ladder rung in (or `out`) about the point, or centred on it with -/// Zoom Clicked Point to Center. `None` at a zoom limit. -fn click_step(view: &CanvasView, screen: Pos2, out: bool, size: Size, options: &NavigationOptions, pixels_per_point: f32) -> Option { +/// The view after a Zoom tool click at `screen`: one rung of `scheme` in (or `out`) about the point, or centred on it +/// with Zoom Clicked Point to Center. `None` at a zoom limit. +fn click_step( + view: &CanvasView, + screen: Pos2, + out: bool, + size: Size, + options: &NavigationOptions, + pixels_per_point: f32, + scheme: &ZoomScheme, +) -> Option { let current = zoom::device(view, pixels_per_point); - let next = ZoomLadder::step(current, if out { -1 } else { 1 }, size); + let next = scheme.step(current, if out { -1 } else { 1 }, size); if !next.is_finite() || (next / current - 1.0).abs() <= 1e-9 { return None; } @@ -542,6 +552,7 @@ impl CanvasTool for ZoomTool { let hold = self.hold.take(); let Some(size) = space.document() else { return }; let ppp = space.pixels_per_point; + let scheme = space.zoom_scheme(); let out = self.zooms_out(pointer.mods); // A hold that zoomed has already changed the view; the release is no click. if hold.is_some_and(|hold| hold.zooming()) { @@ -549,7 +560,7 @@ impl CanvasTool for ZoomTool { } if !self.dragged { // A click steps from the view the press found. - match click_step(&start, anchor, out, size, &self.options, ppp) { + match click_step(&start, anchor, out, size, &self.options, ppp, &scheme) { Some(next) if self.options.animated_zoom => { let anchored = (!self.options.zoom_clicked_point_to_center).then(|| (start.to_doc(anchor), anchor)); cx.ease_view(next, anchored); @@ -561,8 +572,8 @@ impl CanvasTool for ZoomTool { } let mut view = space.view; let mut drag = drag; - drag.drag(&mut view, pointer.pos, size, ppp); - drag.release(&mut view, out, size, ppp, cx.slop, &space.zoom_scheme()); // P3(canvas-w1): cv.F12 + drag.drag(&mut view, pointer.pos, size, ppp, &scheme); + drag.release(&mut view, out, size, ppp, cx.slop, &scheme); cx.set_view(view); } @@ -615,7 +626,9 @@ impl CanvasTool for RotateViewTool { let Some((turn, start)) = &self.drag else { return }; let mut view = *start; view.rotation = turn.drag(pointer.pos, pointer.mods.shift, start.flip_x); + let rows = angle_row(&cx.words::(), &cx.units(), view.rotation); cx.set_view(view); + cx.readout(rows); } fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { diff --git a/crates/ui-canvas/src/canvas/zoom_motion.rs b/crates/ui-canvas/src/canvas/zoom_motion.rs index 175045c002..e72cd2970c 100644 --- a/crates/ui-canvas/src/canvas/zoom_motion.rs +++ b/crates/ui-canvas/src/canvas/zoom_motion.rs @@ -11,7 +11,7 @@ use crate::runtime::frame; use crate::runtime::memory::{global, with_session}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, ZoomLadder, ZoomScheme}; +use craft_behavior::{CanvasView, ZoomScheme}; use egui::{Context, Id, Pos2, Rect}; /// How far the app's view may differ from the zoom anchor, in document units, before the anchor is dropped. @@ -191,7 +191,7 @@ impl HoldZoom { /// Advances the hold for the pass at `time`: once past the delay, zooms `view` about the press point (out when /// `out`). Returns `true` while the hold zooms, so the tool skips its scrub and its click step. - pub fn advance(&mut self, view: &mut CanvasView, time: f64, out: bool, size: Size, pixels_per_point: f32) -> bool { + pub fn advance(&mut self, view: &mut CanvasView, time: f64, out: bool, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { if self.last.is_none() { let begin = self.pressed_at + Self::DELAY; if time < begin { @@ -201,7 +201,7 @@ impl HoldZoom { } let dt = frame_step(time - self.last.unwrap_or(time)); let current = zoom::device(view, pixels_per_point); - let next = Self::zoom_after(current, dt, out, size, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F12 + let next = Self::zoom_after(current, dt, out, size, scheme); // At a limit the view stays as it is. if (next / current - 1.0).abs() > 1e-12 { zoom::anchor(view, self.anchor, self.doc, next, pixels_per_point); @@ -223,10 +223,9 @@ impl HoldZoom { /// The zoom after holding for a frame step of `dt` seconds at `zoom`, within the document's range. A non-finite /// or negative `dt` changes nothing, and `dt` is capped at [`FRAME_STEP_MAX`](super::FRAME_STEP_MAX). pub fn zoom_after(zoom: f64, dt: f64, out: bool, size: Size, scheme: &ZoomScheme) -> f64 { - let _ = scheme; // P3(canvas-w1): cv.F12 let dt = frame_step(dt); let doublings = if out { -Self::RATE * dt } else { Self::RATE * dt }; - ZoomLadder::clamp(zoom * doublings.exp2(), size) + scheme.clamp(zoom * doublings.exp2(), size) } } @@ -253,11 +252,11 @@ impl ZoomDrag { /// The pointer moved to `pointer`: a scrub zooms `view` about the press point; a rectangle moves its corner (the /// view is unchanged). - pub fn drag(&mut self, view: &mut CanvasView, pointer: Pos2, size: Size, pixels_per_point: f32) { + pub fn drag(&mut self, view: &mut CanvasView, pointer: Pos2, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) { match self.corner.as_mut() { Some(corner) => *corner = pointer, None => { - let next = Self::scrub_zoom(self.zoom0, pointer.x - self.anchor.x, size, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F12 + let next = Self::scrub_zoom(self.zoom0, pointer.x - self.anchor.x, size, scheme); if (next / zoom::device(view, pixels_per_point) - 1.0).abs() > 1e-12 { zoom::anchor(view, self.anchor, self.doc, next, pixels_per_point); } @@ -269,7 +268,6 @@ impl ZoomDrag { /// a scrub has nothing left to do. A rectangle narrower or shorter than `least` points is too small to zoom to: /// the view stays. pub fn release(self, view: &mut CanvasView, out: bool, size: Size, pixels_per_point: f32, least: f32, scheme: &ZoomScheme) { - let _ = scheme; // P3(canvas-w1): cv.F12 let Some(corner) = self.corner else { return }; let rect = Rect::from_two_pos(self.anchor, corner); if rect.width() < least || rect.height() < least || rect.width() <= 0.0 || rect.height() <= 0.0 { @@ -277,13 +275,13 @@ impl ZoomDrag { } let current = zoom::device(view, pixels_per_point); if out { - let next = ZoomLadder::step(current, -1, size); + let next = scheme.step(current, -1, size); zoom::anchor(view, self.anchor, self.doc, next, pixels_per_point); return; } // The ratio of two screen lengths scales the zoom in any unit. let k = f64::from((view.rect.width() / rect.width()).min(view.rect.height() / rect.height())); - let next = ZoomLadder::clamp(current * k, size); + let next = scheme.clamp(current * k, size); let target = view.to_doc(rect.center()); let middle = view.rect.center(); zoom::anchor(view, middle, target, next, pixels_per_point); @@ -296,9 +294,8 @@ impl ZoomDrag { /// The scrubby zoom for a horizontal drag of `dx` points from a press at `zoom0`, within the document's range. pub fn scrub_zoom(zoom0: f64, dx: f32, size: Size, scheme: &ZoomScheme) -> f64 { - let _ = scheme; // P3(canvas-w1): cv.F12 // 40 doublings already span far more than the zoom range; the bound keeps the power finite. let doublings = if dx.is_finite() { f64::from(dx / Self::DOUBLING).clamp(-40.0, 40.0) } else { 0.0 }; - ZoomLadder::clamp(zoom0 * doublings.exp2(), size) + scheme.clamp(zoom0 * doublings.exp2(), size) } } diff --git a/crates/ui-canvas/tests/it/canvas/navigate.rs b/crates/ui-canvas/tests/it/canvas/navigate.rs index 3bab71e461..1ad8a6e9e5 100644 --- a/crates/ui-canvas/tests/it/canvas/navigate.rs +++ b/crates/ui-canvas/tests/it/canvas/navigate.rs @@ -2,7 +2,7 @@ use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{Axis, CanvasView, GESTURE_GAP, MotionMode, Wheel, WheelPhase, WheelUnit, ZoomLadder}; +use craft_behavior::{Axis, CanvasView, GESTURE_GAP, MotionMode, Wheel, WheelPhase, WheelUnit, ZoomScheme}; use craft_keymap::{Mods, Platform}; use craft_ui::canvas::{ Autoscroll, Canvas, CanvasSpace, Guide, GuideKey, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, TouchpadGlide, ViewCommands, @@ -349,7 +349,7 @@ fn a_canvas_runs_the_view_commands_its_app_queues_before_the_fired_ones_and_repo queue.borrow_mut().extend([ViewRequest::Command(ViewCommands::ZoomIn), ViewRequest::Command(ViewCommands::ZoomIn)]); assert!(commands::fire(fixture.ctx(), ViewCommands::ZoomOut, FireSource::Menu)); fixture.frame(vec![]); - let one_in = ZoomLadder::step(start, 1, DOCUMENT); + let one_in = ZoomScheme::PHOTOSHOP.step(start, 1, DOCUMENT); assert!((zoom::device(&view.get(), ppp) / one_in - 1.0).abs() < 1e-6, "in, in, out: one rung in"); let delivered: Vec<_> = frame::take_output(fixture.ctx()).delivered.into_iter().map(|fired| fired.command).collect(); assert_eq!(delivered, [CommandRef::from(ViewCommands::ZoomOut)], "a queued command is the app's, not delivered"); @@ -424,9 +424,15 @@ fn fingers(phase: TouchPhase, center: Pos2, half: Vec2) -> Vec { .into() } -/// The zoom ratio and the rotation of the view a canvas shows after the frames of `input` over its middle, under -/// `options`, from a view turned `rotation` degrees and mirrored when `flip`. -fn gestured(options: NavigationOptions, rotation: f64, flip: bool, input: &dyn Fn(Pos2) -> Vec>) -> (f64, f64) { +/// The view a canvas shows before and after the frames of `input` over its middle, under `options` with `held` +/// modifiers down, from a view turned `rotation` degrees and mirrored when `flip`. +fn views_after( + options: NavigationOptions, + rotation: f64, + flip: bool, + held: Modifiers, + input: &dyn Fn(Pos2) -> Vec>, +) -> (CanvasView, CanvasView) { // A view with a rect is shown as given: no first fit. let start = CanvasView::new(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0)), Point::new(2000.0, 2000.0), 1.0); let view = Rc::new(Cell::new(start.rotation(rotation).flip_x(flip))); @@ -440,11 +446,19 @@ fn gestured(options: NavigationOptions, rotation: f64, flip: bool, input: &dyn F fixture.settle(); let middle = view.get().rect.center(); fixture.frame(vec![pointer::moved(middle)]); + if held != Modifiers::NONE { + fixture.hold(held); + } let before = view.get(); for events in input(middle) { fixture.frame(events); } - let after = view.get(); + (before, view.get()) +} + +/// The zoom ratio and the rotation of the view a canvas shows after the frames of `input`, as [`views_after`]. +fn gestured(options: NavigationOptions, rotation: f64, flip: bool, input: &dyn Fn(Pos2) -> Vec>) -> (f64, f64) { + let (before, after) = views_after(options, rotation, flip, Modifiers::NONE, input); (after.zoom / before.zoom, after.rotation) } @@ -498,6 +512,29 @@ fn pinch_and_rotation_follow_the_gesture_options_and_the_flip() { assert!(wrapped > -180.0 && wrapped <= 180.0 && (wrapped + 177.0).abs() < 0.05, "178° turned 5° more is -177°: {wrapped}"); } +#[trial] +fn two_fingers_moving_together_pan_the_view_only_with_enable_gestures_and_before_the_modifier_rules() { + let shift = Vec2::new(30.0, 0.0); + let half = Vec2::new(50.0, 0.0); + let drag: &dyn Fn(Pos2) -> Vec> = + &|at| vec![fingers(TouchPhase::Start, at, half), fingers(TouchPhase::Move, at + shift, half), fingers(TouchPhase::End, at + shift, half)]; + // (case, Enable Gestures, modifiers held, pans) + let cases = [ + ("with Enable Gestures", true, Modifiers::NONE, true), + ("without Enable Gestures", false, Modifiers::NONE, false), + ("with Cmd held", true, Modifiers::COMMAND, true), + ]; + for (case, gestures, held, pans) in cases { + let (before, after) = views_after(navigation(true, gestures, false), 0.0, false, held, drag); + if pans { + assert!(after.center.x < before.center.x - 1.0 && (after.center.y - before.center.y).abs() < 1e-3, "{case}: the content follows the fingers: {before:?} -> {after:?}"); + } else { + assert_eq!(after.center, before.center, "{case}: the view stays"); + } + assert!((after.zoom / before.zoom - 1.0).abs() < 1e-4, "{case}: a pan is no zoom"); + } +} + #[trial] fn fractional_shift_alt_scrolls_add_up_to_whole_rungs_per_canvas() { let views = Rc::new([ diff --git a/crates/ui-canvas/tests/it/canvas/tools.rs b/crates/ui-canvas/tests/it/canvas/tools.rs index 11d2fbafb0..921d7e1372 100644 --- a/crates/ui-canvas/tests/it/canvas/tools.rs +++ b/crates/ui-canvas/tests/it/canvas/tools.rs @@ -4,12 +4,14 @@ use craft_behavior::CanvasView; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Vec2 as DocVec; use craft_behavior::kurbo::{Point, Rect, Size}; +use craft_keymap::Mods; use craft_ui::canvas::{ - Canvas, CanvasTool, HandTool, LayerBounds, NavigationOptions, RotateViewTool, ToolHost, ViewCommands, ViewTarget, ZoomTool, tool_pass, + Canvas, CanvasTool, HandTool, LayerBounds, Momentary, MomentaryCommands, MomentaryShift, MomentaryTool, NavigationOptions, RotateViewTool, + ToolHost, ViewCommands, ViewTarget, ZoomTool, tool_pass, }; use craft_ui::contract::{Bind, ShowContainer as _}; use craft_ui::runtime::access::Role; -use craft_ui::runtime::commands::{self, FireSource}; +use craft_ui::runtime::commands::{self, FirePhase, FireSource}; use craft_ui::testing::{Fixture, ToolFixture, pointer, trial}; use egui::{Event, Modifiers, Pos2}; use std::cell::{Cell, RefCell}; @@ -167,18 +169,18 @@ fn view_commands_run_with_their_facts_and_are_disabled_without() { ]; for (command, owed) in rows { let mut view = start; - assert!(command.available(&start, &full, given, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP), "{command:?} runs with its fact"); // P3(canvas-w1): cv.F8 - assert!(command.apply(&mut view, &full, given, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP) && owed(&view), "{command:?} gives {view:?}"); // P3(canvas-w1): cv.F8 + assert!(command.available(&start, &full, given, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP), "{command:?} runs with its fact"); + assert!(command.apply(&mut view, &full, given, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP) && owed(&view), "{command:?} gives {view:?}"); if command == ViewCommands::TwoHundredPercent { - assert!(command.available(&start, &bare, None, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP), "200% needs no fact"); // P3(canvas-w1): cv.F8 + assert!(command.available(&start, &bare, None, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP), "200% needs no fact"); continue; } let mut view = start; - assert!(!command.available(&start, &bare, None, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP), "{command:?} is disabled without its fact"); // P3(canvas-w1): cv.F8 + assert!(!command.available(&start, &bare, None, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP), "{command:?} is disabled without its fact"); assert!( !command.apply(&mut view, &bare, None, ppp, &craft_behavior::ZoomScheme::PHOTOSHOP) && view == start, "{command:?} leaves the view without its fact" - ); // P3(canvas-w1): cv.F8 + ); } } @@ -301,7 +303,7 @@ fn the_rotate_commands_step_fifteen_degrees_on_screen_in_a_flipped_view_too() { for (command, screen_turn) in [(ViewCommands::RotateClockwise, 15.0), (ViewCommands::RotateCounterclockwise, -15.0)] { let before = turned(room, 20.0, flip_x); let mut view = before; - assert!(command.apply(&mut view, &target, None, 1.0, &craft_behavior::ZoomScheme::PHOTOSHOP), "{command:?} turns the view"); // P3(canvas-w1): cv.F8 + assert!(command.apply(&mut view, &target, None, 1.0, &craft_behavior::ZoomScheme::PHOTOSHOP), "{command:?} turns the view"); let turned_by = (angle(&view) - angle(&before) + 540.0).rem_euclid(360.0) - 180.0; assert!( (turned_by - screen_turn).abs() < 0.01, @@ -420,6 +422,32 @@ fn a_held_zoom_press_zooms_about_its_point_at_a_frame_rate_independent_rate() { assert!((rig.device() / device - 2.0).abs() < 1e-3, "a drag scrubs one doubling per 100 points: {}", rig.device() / device); } +#[trial] +fn space_then_shift_turns_the_view_only_where_the_app_asks_for_it() { + let shift = Mods { shift: true, ..Mods::NONE }; + let cmd_shift = Mods { cmd: true, shift: true, ..Mods::NONE }; + let hand = |momentary: Momentary| { + let mut momentary = momentary; + momentary.fired(MomentaryCommands::Hand, FirePhase::Press); + momentary + }; + + let mut plain = hand(Momentary::new(NavigationOptions::default())); + assert_eq!(plain.tool(shift, false), Some(MomentaryTool::Hand), "by default Space+Shift pans"); + + let mut turning = hand(Momentary::new(NavigationOptions::default()).shift(MomentaryShift::RotateView)); + assert_eq!(turning.tool(Mods::NONE, false), Some(MomentaryTool::Hand), "Space alone pans"); + assert_eq!(turning.tool(shift, false), Some(MomentaryTool::RotateView), "Space then Shift turns the view"); + assert_eq!(turning.tool(Mods::NONE, true), Some(MomentaryTool::RotateView), "a drag keeps its tool when Shift is let go"); + assert_eq!(turning.tool(cmd_shift, false), Some(MomentaryTool::ZoomIn), "Cmd is checked before Shift"); + assert_eq!(turning.tool(Mods { alt: true, shift: true, ..Mods::NONE }, false), Some(MomentaryTool::ZoomOut), "Alt is checked before Shift"); + + let mut bound = Momentary::new(NavigationOptions::default()); + bound.fired(MomentaryCommands::RotateView, FirePhase::Press); + assert_eq!(bound.tool(Mods::NONE, false), Some(MomentaryTool::RotateView), "a bound Rotate View command turns the view"); + assert_eq!(bound.tool(Mods::ALT, false), Some(MomentaryTool::RotateView), "the held command comes first"); +} + /// A canvas asks the app for the layers' bounds only in the pass that runs Fit Layers: passes that only show the /// command enabled never walk the layers. #[trial] diff --git a/crates/ui-canvas/tests/it/full_window_parts.rs b/crates/ui-canvas/tests/it/full_window_parts.rs index a803f723d0..9c49d65fea 100644 --- a/crates/ui-canvas/tests/it/full_window_parts.rs +++ b/crates/ui-canvas/tests/it/full_window_parts.rs @@ -1,7 +1,7 @@ //! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom, Escape on a focused canvas, the //! close of the dialog's own window and the mapped overlay. -use craft_behavior::PixelSize; +use craft_behavior::{PixelSize, ZoomScheme}; use craft_ui::canvas::ViewCommands; use craft_ui::dialog::FullWindowView; use craft_ui::testing::trial; @@ -20,7 +20,7 @@ const SCALE: f32 = 1.0; const SAME: f64 = 1e-6; fn fitted() -> FullWindowView { - FullWindowView::new().settled(Rect::from_min_size(Pos2::ZERO, CANVAS), IMAGE, SCALE) + FullWindowView::new().settled(Rect::from_min_size(Pos2::ZERO, CANVAS), IMAGE, SCALE, &ZoomScheme::PHOTOSHOP) } #[trial] @@ -32,10 +32,10 @@ fn a_zoom_command_ends_the_fit_and_fit_returns_to_it() { assert!(!view.apply(ViewCommands::FitOnScreen), "fitting a fitted view changes nothing"); assert!(view.apply(ViewCommands::ZoomIn)); assert!(!view.is_fit() && view.device_zoom() > fit); - let kept = view.settled(rect, IMAGE, SCALE); + let kept = view.settled(rect, IMAGE, SCALE, &ZoomScheme::PHOTOSHOP); assert!((kept.device_zoom() - view.device_zoom()).abs() < SAME, "a view that does not fit keeps its zoom when settled"); assert!(view.apply(ViewCommands::FitOnScreen)); - assert!((view.settled(rect, IMAGE, SCALE).device_zoom() - fit).abs() < SAME, "settling a fitted view fits again"); + assert!((view.settled(rect, IMAGE, SCALE, &ZoomScheme::PHOTOSHOP).device_zoom() - fit).abs() < SAME, "settling a fitted view fits again"); } /// The canvas's navigation: the wheel, the middle button and the Hand tool it falls back to. diff --git a/crates/ui-widgets/src/text/zoom_field.rs b/crates/ui-widgets/src/text/zoom_field.rs index 15ef85aa56..4cfb08ac70 100644 --- a/crates/ui-widgets/src/text/zoom_field.rs +++ b/crates/ui-widgets/src/text/zoom_field.rs @@ -6,7 +6,7 @@ use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _}; use crate::runtime::env::{Env, Label, UnitKind}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Size; -use craft_behavior::{CanvasView, EditEvents, ZoomLadder}; +use craft_behavior::{CanvasView, EditEvents, ZoomScheme}; use egui::{Response, Ui}; #[cfg(feature = "testing")] @@ -15,7 +15,7 @@ mod stories; /// The decimals the zoom range's ends are written with in the message, as the field shows a zoom. const MESSAGE_DECIMALS: usize = 2; -/// A zoom field: a `NumberField` over the view's device zoom in percent, with the zoom codec and the zoom ladder's +/// A zoom field: a `NumberField` over the view's device zoom in percent, with the zoom codec and the zoom scheme's /// range. With no view it shows a disabled empty field. An edit writes the zoom about the view's centre; an empty /// commit keeps the view. /// @@ -40,7 +40,7 @@ impl ZoomField { ZoomField { label: label.into(), view, document, stepper: false, scrub: false, enabled: true } } - /// The arrow keys and the wheel step along the zoom ladder. + /// The arrow keys and the wheel step along the zoom scheme's rungs. #[must_use] pub fn stepper(mut self, on: bool) -> Self { self.stepper = on; @@ -65,11 +65,12 @@ impl ZoomField { pub fn show(self, ui: &mut Ui) -> ZoomFieldOutput { let env = Env::of(ui); let pixels_per_point = env.scale.0; + let scheme = env.view().get::(); let document = self.document; let device = self.view.as_ref().map(|view| zoom::device(view, pixels_per_point)); // The document's zoom range widened to the current zoom, so the field never pulls the zoom back. - let range = device.map(|device| ZoomLadder::percent_range(device, document)); - let mut field = NumberField::new(self.label, Bind::given(device.map(|device| device * 100.0))) + let range = device.map(|device| scheme.percent_range(device, document)); + let mut field = NumberField::new(self.label, Bind::given(device.map(|device| scheme.percent(device)))) .codec(env.units().zoom_codec()) .unit_kind(UnitKind::Percent) .zoom_typing() @@ -78,8 +79,7 @@ impl ZoomField { field = field.range(range); } if self.stepper { - // P3(canvas-w1): ap.AP15 - field = field.stepper(move |percent: f64, dir: i32, _scale: f64| ZoomLadder::step(percent / 100.0, dir, document) * 100.0); + field = field.stepper(move |percent: f64, dir: i32, _scale: f64| scheme.percent(scheme.step(scheme.device(percent), dir, document))); } if self.scrub { field = field.scrub_by_label(); @@ -91,12 +91,7 @@ impl ZoomField { .edit .events .clone() - // P3(canvas-w1): cv.F3 - .map(|percent| { - percent.map_or(current, |percent| { - zoom::with_device(¤t, percent / 100.0, document, pixels_per_point, &craft_behavior::ZoomScheme::PHOTOSHOP) - }) - }), + .map(|percent| percent.map_or(current, |percent| zoom::with_device(¤t, scheme.device(percent), document, pixels_per_point, &scheme))), None => EditEvents::new(), }; ZoomFieldOutput { response: shown.edit.response.clone(), view, invalid_zoom } diff --git a/migration/api-map/canvas-core.toml b/migration/api-map/canvas-core.toml index 5529bc4724..bd7081f827 100644 --- a/migration/api-map/canvas-core.toml +++ b/migration/api-map/canvas-core.toml @@ -386,6 +386,7 @@ name = "zoom_to_document_rect" old = "craft_ui::canvas::navigator::proxy::zoom_to_document_rect" new = "craft_ui::canvas::zoom_to_document_rect" status = "moved" +note = "Takes a last `scheme: &craft_behavior::ZoomScheme` argument." [[type]] name = "view_center_for" @@ -402,8 +403,9 @@ status = "moved" [[type]] name = "ZoomLadder" old = "craft_ui::canvas::zoom::ZoomLadder" -new = "craft_behavior::ZoomLadder" -status = "moved" +new = "craft_behavior::ZoomScheme" +status = "replaced" +note = "A scheme of rungs, range and 100 % (`PHOTOSHOP`, `ILLUSTRATOR`) with a `ZoomFloor`, read from the root env; the zoom functions take it as their last argument." [[type]] name = "ViewHistory"