F-16 WIP: ViewTarget and the data view commands, zoom::fit_rect, NavigateBar, zoom_out icon

This commit is contained in:
aiongg
2026-11-13 13:17:30 +00:00
parent e80cbd30ab
commit bd79d84e82
17 changed files with 532 additions and 69 deletions
+15 -3
View File
@@ -11,7 +11,7 @@
use super::view::CanvasView;
use emath::Pos2;
use kurbo::{Point, Size};
use kurbo::{Point, Rect, Size};
use std::ops::RangeInclusive;
/// A zoom within 0.1 % of a rung counts as on it.
@@ -139,12 +139,24 @@ pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64
/// [`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) {
let (shown_w, shown_h, sin, cos) = shown_extent(view, size);
fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, margin);
}
/// 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` points on each side, up to the zoom ceiling.
/// 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: f64) {
fit_rect_up_to(view, rect, size, pixels_per_point, ZoomLadder::MAX, margin);
}
fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, max_device: f64, margin: f64) {
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) / bw).min((f64::from(view.rect.height()) - 2.0 * margin) / bh);
let device = ZoomLadder::clamp((scale * f64::from(pixels_per_point)).min(max_device), size);
view.zoom = CanvasView::points_per_unit(device, pixels_per_point);
view.center = Point::new(size.width / 2.0, size.height / 2.0);
view.center = rect.center();
}
/// Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend
+24 -35
View File
@@ -72,9 +72,9 @@ mod tools;
mod zoom_motion;
pub use momentary::{Momentary, MomentaryCommands, MomentaryTool};
pub use navigate::{Autoscroll, FlickPan, NavigationOptions, PageKey, TouchpadGlide, WheelAction, WheelInput, WheelNavigation, pan};
pub use navigate::{Autoscroll, FlickPan, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, TouchpadGlide, WheelAction, WheelInput, WheelNavigation, pan};
pub use rotate::{RotateView, RotateViewOutput, RotateViewStyle, ViewTurn};
pub use tools::{HandTool, RotateViewTool, ViewCommands, ZoomTool};
pub use tools::{HandTool, RotateViewTool, ViewCommands, ViewTarget, ZoomTool};
pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag};
mod rulers;
@@ -113,18 +113,6 @@ use zoom_motion::{Steer, ViewMotion};
const BACKGROUND: PartKey = PartKey::new("background");
/// The view commands a canvas publishes the state of.
const VIEW_COMMANDS: [ViewCommands; 8] = [
ViewCommands::ZoomIn,
ViewCommands::ZoomOut,
ViewCommands::FitOnScreen,
ViewCommands::FillScreen,
ViewCommands::ActualPixels,
ViewCommands::RotateClockwise,
ViewCommands::RotateCounterclockwise,
ViewCommands::ResetRotation,
];
/// Why the background part is pointer-only: the keyboard path of the running tool is its command form
/// ([`CanvasTool::command_form`]), the one owner of that fact.
const TOOL_PATH: &str = "the running tool's command form";
@@ -163,12 +151,13 @@ pub struct Canvas<'a> {
view: Option<Bind<'a, CanvasView>>,
/// The view the binding held when the pass began.
given: Option<CanvasView>,
/// The document the view shows, in document units. With a view and a document, the canvas fits a view never
/// shown, keeps the wheel's zoom inside the document's zoom range, keeps the document in view with Overscroll off,
/// and applies the view commands routed to it ([`ViewCommands`]); without either, the view commands are disabled
/// for it.
#[prop(quantity = "document units")]
document: Option<Size>,
/// The document the view shows: its size in document units (a `Size` is enough), and the artboard, layer bounds
/// and resolution some view commands need ([`ViewTarget`]). With a view and a document, the canvas fits a view
/// never shown, keeps the wheel's zoom inside the document's zoom range, keeps the document in view with Overscroll
/// off, and applies the view commands routed to it ([`ViewCommands`]); without either, the view commands are
/// disabled for it, and so is each command whose fact the target lacks.
#[prop(into)]
document: Option<ViewTarget>,
/// The user's navigation options: how the wheel and a pinch move the view ([`WheelNavigation`]), whether a zoom
/// eases (Animated Zoom) and whether the view may leave the document (Overscroll).
#[prop]
@@ -267,23 +256,23 @@ impl<'a> Canvas<'a> {
self.props.command_scope?;
let pixels_per_point = cx.env.scale().0;
let target = view.zip(self.document);
for command in VIEW_COMMANDS {
// Zoom In and Zoom Out are disabled at the ends of the zoom range.
let enabled = target.is_some_and(|(mut view, document)| match command {
ViewCommands::ZoomIn | ViewCommands::ZoomOut => command.apply(&mut view, document, pixels_per_point),
_ => true,
});
for command in ViewCommands::ALL {
let enabled = target.is_some_and(|(view, document)| command.available(&view, &document, pixels_per_point));
cx.publish(command, CommandState::new().enabled(enabled));
}
let (view, document) = target?;
let (mut next, mut zoomed) = (view, false);
while let Some((command, _)) = cx.take_command::<ViewCommands>() {
command.apply(&mut next, document, pixels_per_point);
zoomed |= !matches!(command, ViewCommands::RotateClockwise | ViewCommands::RotateCounterclockwise | ViewCommands::ResetRotation);
zoomed |= command.apply(&mut next, &document, pixels_per_point) && command.zooms();
}
(next != view).then_some((next, zoomed))
}
/// The document's size, from the target the app gave.
fn document_size(&self) -> Option<Size> {
self.document.map(|target| target.document)
}
/// The rect the view lies in: the canvas's own, inside the rulers while they show.
fn view_rect(&self, rect: Rect, style: &CanvasStyle) -> Rect {
if self.show_rulers { Rect::from_min_max(rect.min + style.rulers, rect.max) } else { rect }
@@ -296,14 +285,14 @@ impl<'a> Canvas<'a> {
let id = cx.core.id;
let mut motion = ViewMotion::take(&ctx, id);
let pixels_per_point = cx.env.scale().0;
let size = self.document.unwrap_or(Size::ZERO);
let size = self.document_size().unwrap_or(Size::ZERO);
let mut view = given;
let area = self.view_rect(cx.content_rect, cx.style);
if area.width() > 0.0 && area.height() > 0.0 {
let never_shown = !(view.rect.width() > 0.0 && view.rect.height() > 0.0);
view.rect = area;
if never_shown && let Some(document) = self.document {
ViewCommands::FitOnScreen.apply(&mut view, document, pixels_per_point);
ViewCommands::FitOnScreen.apply(&mut view, &document, pixels_per_point);
}
}
let mut jumped = false;
@@ -334,7 +323,7 @@ impl<'a> Canvas<'a> {
for (step, mods) in moves {
if self.keys_to_body {
keys.page = Some((step, mods));
} else if let (Some(document), Some(key)) = (self.document, PageKey::of(step, mods, area.size())) {
} else if let (Some(document), Some(key)) = (self.document_size(), PageKey::of(step, mods, area.size())) {
jumped |= key.apply(&mut view, document);
}
}
@@ -355,7 +344,7 @@ impl<'a> Canvas<'a> {
steer = Some(Steer::Ease { from: before, anchor });
}
}
let target = clamped(view, self.document, &self.navigation);
let target = clamped(view, self.document_size(), &self.navigation);
let mut progress = cx.anim("zoom", motion.animation.target(), spec::MOVE);
match steer {
Some(Steer::Ease { mut from, anchor }) => {
@@ -387,7 +376,7 @@ impl<'a> Canvas<'a> {
None => (self.given?, self.given?, BodyKeys::default()),
};
let space = CanvasSpace::new(shown, pixels_per_point).with_target(target).with_keys(keys);
Some(space.with_document(self.document).with_rulers(self.rulers).with_background(background).with_canvas(id))
Some(space.with_document(self.document_size()).with_rulers(self.rulers).with_background(background).with_canvas(id))
}
/// The press on the background part as the canvas reports it, and the pan of a middle-button drag: a middle press
@@ -436,7 +425,7 @@ impl CanvasOutput {
/// `view` as the canvas keeps it: inside the document's edges with Overscroll off. The tool host passes a tool's
/// view through it.
pub(crate) fn clamped(&self, view: CanvasView) -> CanvasView {
clamped(view, self.document, &self.navigation)
clamped(view, self.document_size(), &self.navigation)
}
/// Where a press on the background was released without a drag. A tool that creates geometry opens its command
@@ -514,7 +503,7 @@ impl Component for Canvas<'_> {
let press = Self::background_press(&cx).0;
let space = self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key));
let view = self.settled.map(|settled| settled.target).filter(|target| Some(*target) != self.given);
CanvasOutput { response: cx.response.clone(), press, space, view, snap: self.snap, document: self.document, navigation: self.navigation }
CanvasOutput { response: cx.response.clone(), press, space, view, snap: self.snap, document: self.document_size(), navigation: self.navigation }
}
}
+157
View File
@@ -0,0 +1,157 @@
//! [`NavigateBar`]: the options of the Zoom, Rotate View and Hand tools, as members of the app's options bar.
use super::NavigationOptions;
use crate::buttons::Button;
use crate::canvas::{CanvasWords, ViewCommands};
use crate::choice::{Checkbox, Segmented};
use crate::contract::{Bind, BodyCx, Entry, Gap, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::display::Divider;
use crate::form::Field;
use crate::layout_components::Row;
use crate::runtime::env::{Env, UnitKind};
use crate::text::NumberField;
use craft_behavior::canvas::zoom;
use craft_behavior::geometry::crop::normalized_angle;
use craft_behavior::kurbo::Size;
use craft_behavior::{CanvasView, EditEvent, EditEvents, IconId, Mixed, ZoomLadder};
use egui::{Response, Ui};
/// What the navigate bar reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct NavigateBarOutput {
/// The strip's response.
pub response: Response,
/// The view changes of this pass from the Zoom and Angle fields, for a binding that does not write through.
pub view: EditEvents<CanvasView>,
}
impl Outcome for NavigateBarOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The members of one tool's bar.
enum Members<'a> {
Zoom { view: Bind<'a, CanvasView>, document: Size, options: &'a mut NavigationOptions, out: Bind<'a, bool> },
RotateView { view: Bind<'a, CanvasView> },
Hand { options: &'a mut NavigationOptions },
}
/// The options of a navigation tool (Zoom, Rotate View, Hand), shown as children of the app's options bar, as in
/// Photoshop.
///
/// The members:
///
/// - **Zoom:** Zoom In and Zoom Out as icon segments over the tool's direction, the Zoom field, then Resize Windows to
/// Fit and Scrubby Zoom, then 100%, Fit Screen and Fill Screen.
/// - **Rotate View:** the Angle field, then Reset View.
/// - **Hand:** Scroll All Windows, then 100%, Fit Screen and Fill Screen.
///
/// The fields edit the bound view: Zoom in percent, its range the document's zoom range widened to include the current
/// zoom, its arrows stepping the zoom ladder, the centre kept; Angle in degrees from -180 to 180. The buttons are the
/// [`ViewCommands`]: they act on the canvas that holds the key focus (else the one that held it last), which applies
/// them with its document and eases them under Animated Zoom; their enabled state comes from that canvas. The check
/// boxes write into the [`NavigationOptions`].
#[must_use = "show the bar's children with `show`"]
#[derive(crate::contract::Pattern)]
pub struct NavigateBar<'a> {
members: Members<'a>,
}
impl<'a> NavigateBar<'a> {
/// The Zoom tool's options over `view`, a document of `document` units, the user's `options` and the tool's
/// direction `out` (Zoom Out picked).
pub fn zoom(view: Bind<'a, CanvasView>, document: Size, options: &'a mut NavigationOptions, out: Bind<'a, bool>) -> Self {
NavigateBar { members: Members::Zoom { view, document, options, out } }
}
/// The Rotate View tool's options over `view`.
pub fn rotate_view(view: Bind<'a, CanvasView>) -> Self {
NavigateBar { members: Members::RotateView { view } }
}
/// The Hand tool's options over the user's `options`.
pub fn hand(options: &'a mut NavigationOptions) -> Self {
NavigateBar { members: Members::Hand { options } }
}
/// Shows the bar's children.
pub fn show(self, ui: &mut Ui) -> NavigateBarOutput {
let NavigateBar { members } = self;
let env = Env::of(ui);
let words = env.words::<CanvasWords>();
let units = env.units();
let pixels_per_point = env.scale.0;
let mut events = EditEvents::new();
let row = Row::new().gap(Gap::Item);
let shown = match members {
Members::Zoom { mut view, document, options, mut out } => row.show(ui, |ui, cx| {
let directions = [
Entry::new(false, words.navigate_zoom_in.clone()).icon(IconId::new("zoom_in")),
Entry::new(true, words.navigate_zoom_out.clone()).icon(IconId::new("zoom_out")),
];
Segmented::new(words.navigate_direction.clone(), out.reborrowed(), &directions).show(ui);
if let Some(Mixed::Same(current)) = view.reborrow().read(cx) {
let device = zoom::device(&current, pixels_per_point);
let ladder = |percent: f64, dir: i32| ZoomLadder::step(percent / 100.0, dir, document) * 100.0;
let field = NumberField::new(words.navigate_zoom.clone(), Bind::given(Some(device * 100.0)))
.codec(units.zoom_codec())
.range(ZoomLadder::percent_range(device, document))
.stepper(ladder)
.show(ui);
let at = |percent: Option<f64>| percent.map_or(current, |percent| zoom::with_device(&current, percent / 100.0, document, pixels_per_point));
events = write(&mut view, cx, field.edit.events.clone().map(at));
}
Divider::vertical().show(ui);
Checkbox::new(Bind::bound(&mut options.zoom_resizes_windows)).label(words.navigate_resize_windows.clone()).show(ui);
Checkbox::new(Bind::bound(&mut options.scrubby_zoom)).label(words.navigate_scrubby_zoom.clone()).show(ui);
Divider::vertical().show(ui);
view_buttons(ui, &words);
}),
Members::RotateView { mut view } => row.show(ui, |ui, cx| {
if let Some(Mixed::Same(current)) = view.reborrow().read(cx) {
let angle = Field::new(words.navigate_angle.clone()).show(ui, |ui, _| {
NumberField::new(words.navigate_angle.clone(), Bind::given(Some(current.rotation)))
.unit_kind(UnitKind::Degrees)
.range(-180.0..=180.0)
.show(ui)
});
if let Some(field) = angle.inner {
let at = |angle: Option<f64>| {
let mut turned = current;
turned.rotation = angle.map_or(current.rotation, normalized_angle);
turned
};
events = write(&mut view, cx, field.edit.events.clone().map(at));
}
}
Button::command(ViewCommands::ResetRotation).label(words.navigate_reset_view.clone()).show(ui);
}),
Members::Hand { options } => row.show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut options.scroll_all_windows)).label(words.navigate_scroll_all.clone()).show(ui);
Divider::vertical().show(ui);
view_buttons(ui, &words);
}),
};
NavigateBarOutput { response: shown.output, view: events }
}
}
/// Writes the field's view `edits` through `view` and returns them.
fn write(view: &mut Bind<'_, CanvasView>, cx: &mut BodyCx<'_>, edits: EditEvents<CanvasView>) -> EditEvents<CanvasView> {
for edit in edits.iter() {
view.reborrow().write(cx, edit);
}
edits
}
/// 100%, Fit Screen and Fill Screen: the view commands the Zoom and Hand bars share.
fn view_buttons(ui: &mut Ui, words: &CanvasWords) {
Button::command(ViewCommands::ActualPixels).show(ui);
Button::command(ViewCommands::FitOnScreen).label(words.navigate_fit_screen.clone()).show(ui);
Button::command(ViewCommands::FillScreen).label(words.navigate_fill_screen.clone()).show(ui);
}
@@ -6,12 +6,14 @@
//! `craft_behavior::canvas::zoom` and clamp to the [`ZoomLadder`](craft_behavior::ZoomLadder). With Overscroll off
//! the caller clamps the result with the canvas's scroll limits.
mod bar;
mod keys;
mod options;
#[cfg(feature = "testing")]
mod stories;
mod wheel;
pub use bar::{NavigateBar, NavigateBarOutput};
pub use keys::PageKey;
pub use options::NavigationOptions;
pub use wheel::{WheelAction, WheelInput, WheelNavigation};
@@ -20,6 +20,8 @@ pub struct NavigationOptions {
pub overscroll: bool,
/// The Zoom tool's Scrubby Zoom option: a Zoom tool drag zooms continuously instead of drawing a rectangle. On.
pub scrubby_zoom: bool,
/// The Hand tool's Scroll All Windows option: a Hand drag scrolls every open document's view by the same amount. Off.
pub scroll_all_windows: bool,
/// Enhanced Controls, Zoom with Trackpad Pinch. On.
pub pinch_zooms: bool,
/// Enhanced Controls, Rotate View with Trackpad. Off.
@@ -38,6 +40,7 @@ impl Default for NavigationOptions {
flick_panning: true,
overscroll: false,
scrubby_zoom: true,
scroll_all_windows: false,
pinch_zooms: true,
trackpad_rotate: false,
touch_gestures: true,
@@ -1,13 +1,15 @@
//! Stories of the compass.
//! Stories of the compass and the navigate bar.
use crate::canvas::rotate::RIM;
use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with};
use crate::canvas::{Canvas, RotateView, RotateViewOutput};
use crate::contract::{Bind, Show as _, Validity};
use crate::bars::{Bar, BarKind};
use crate::canvas::{Canvas, NavigateBar, NavigationOptions, RotateView, RotateViewOutput};
use crate::contract::{Bind, Show as _, ShowContainer as _, Validity};
use crate::runtime::env::Message;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::Mixed;
use egui::{Ui, Vec2};
use craft_behavior::kurbo::{Point, Size};
use craft_behavior::{CanvasView, Mixed};
use egui::{Rect, Ui, Vec2};
/// The angle the stories start at, in degrees.
const TURNED: f64 = 30.0;
@@ -56,3 +58,48 @@ fn too_far(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
RotateView::new("Rotation", Bind::bound(&mut *angle).check(near), false).show_at(ui, at)
})
}
/// Shows a navigation tool's options bar from `bar` over the view `view` above a canvas on the story document that
/// shows the same view, and returns the bar's output. The canvas fits the view on its first pass and is the instance
/// the bar's view commands reach.
fn bar_over_canvas(ui: &mut Ui, view: &mut CanvasView, mut bar: impl FnMut(&mut Ui, Bind<'_, CanvasView>) -> StoryOutput) -> StoryOutput {
let shown = Bar::new("Options", BarKind::Options).show(ui, |ui, _| bar(ui, Bind::bound(&mut *view)));
let room = crate::testing::stage(ui);
let document = StoryDocument::STANDARD.rect().size();
on_canvas_with(ui, room, Canvas::new("Document").view(Bind::bound(view)).document(document), Some(&StoryDocument::STANDARD), |_, _| ());
shown.inner.unwrap_or_default()
}
/// What a navigate bar story keeps between passes.
#[derive(Clone, Copy, PartialEq)]
struct Navigation {
view: CanvasView,
options: NavigationOptions,
out: bool,
}
impl Default for Navigation {
/// A view no canvas has shown yet (the canvas fits it), the default options and Zoom In.
fn default() -> Self {
Navigation { view: CanvasView::new(Rect::ZERO, Point::ORIGIN, 1.0), options: NavigationOptions::default(), out: false }
}
}
#[story(NavigateBar<'static>, covers = [], drive = Drive::Never)]
fn zoom_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let Navigation { view, options, out } = data.value("navigation", Navigation::default());
let document: Size = StoryDocument::STANDARD.rect().size();
bar_over_canvas(ui, view, |ui, bound| NavigateBar::zoom(bound, document, &mut *options, Bind::bound(&mut *out)).show(ui).into())
}
#[story(NavigateBar<'static>, covers = [], drive = Drive::Never)]
fn rotate_view_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let Navigation { view, .. } = data.value("navigation", Navigation::default());
bar_over_canvas(ui, view, |ui, bound| NavigateBar::rotate_view(bound).show(ui).into())
}
#[story(NavigateBar<'static>, covers = [], drive = Drive::Never)]
fn hand_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let Navigation { view, options, .. } = data.value("navigation", Navigation::default());
bar_over_canvas(ui, view, |ui, _| NavigateBar::hand(&mut *options).show(ui).into())
}
+12 -14
View File
@@ -50,8 +50,8 @@ pub fn proxy_quad(view: &CanvasView, size: Size, preview: Rect) -> [Pos2; 4] {
/// - `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).
/// - Otherwise the point zoom is `min(canvas.w / (r.w * aspect), canvas.h / r.h)`, converted to the ladder's device
/// zoom with `pixels_per_point` and clamped with [`ZoomLadder::clamp`]; a zoom that is not finite does nothing.
/// - 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 {
let edges = [doc_rect.x0, doc_rect.y0, doc_rect.x1, doc_rect.y1];
@@ -65,21 +65,19 @@ pub fn zoom_to_document_rect(view: &mut CanvasView, doc_rect: DocRect, size: Siz
if width < 0.0 || height < 0.0 {
return false;
}
let aspect = if view.aspect.is_finite() && view.aspect > 0.0 { view.aspect } else { 1.0 };
let ppp = if pixels_per_point.is_finite() && pixels_per_point > 0.0 { pixels_per_point } else { 1.0 };
let canvas = view.rect.size();
let device = if width < MIN_ZOOM_BOX || height < MIN_ZOOM_BOX || canvas.x <= 0.0 || canvas.y <= 0.0 {
ZoomLadder::step(zoom::device(view, ppp), 1, size)
} else {
let point_zoom = (f64::from(canvas.x) / (width * aspect)).min(f64::from(canvas.y) / height);
point_zoom * f64::from(ppp)
};
if !device.is_finite() {
return false;
}
let before = *view;
view.zoom = CanvasView::points_per_unit(ZoomLadder::clamp(device, size), ppp);
view.center = Point::new(x0 + width / 2.0, y0 + height / 2.0);
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);
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, 0.0);
}
*view != before
}
+155 -11
View File
@@ -13,7 +13,7 @@ use super::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}
use crate::primitives::Draw;
use craft_behavior::canvas::zoom;
use craft_behavior::geometry::crop::normalized_angle;
use craft_behavior::kurbo::Size;
use craft_behavior::kurbo::{Rect, Size};
use craft_behavior::{CancelReason, CanvasView, Cursor, PaintedCursor, ZoomLadder};
use craft_keymap::Mods;
use egui::Pos2;
@@ -21,11 +21,90 @@ use egui::Pos2;
/// The rotation step of the Rotate View commands, in degrees.
const ROTATE_STEP_DEG: f64 = 15.0;
/// The view commands: the keyboard path of the view tools and of the navigation menu. [`apply`](Self::apply) is the
/// one place that says what each does to a view. The commands are scoped: a canvas container and a full-window
/// dialog can be instances of the `canvasView` scope, and a fired command goes to the instance that holds the key focus,
/// else the one that held it last, so a chord acts on the dialog's view while the dialog is open. The zoom commands
/// also fire inside a dialog.
/// The room Fit Artboard on Screen leaves around the board, in points: the board's name sits above it.
const ARTBOARD_MARGIN: f64 = 40.0;
/// The room Fit Layers on Screen leaves around the layers' bounds, in points.
const LAYERS_MARGIN: f64 = 20.0;
/// Photoshop's default Screen Resolution (Preferences, Units & Rulers), in pixels per inch.
const SCREEN_PPI: f64 = 72.0;
/// What the view commands act on: the document's size and the facts some commands need. The app gives it to
/// [`Canvas::document`](super::Canvas::document); a command whose fact is absent is disabled
/// ([`ViewCommands::available`]).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct ViewTarget {
/// The document's size, in document units.
pub document: Size,
/// The artboard Fit Artboard on Screen shows (the active layer's board, else the last one), in document units.
pub artboard: Option<Rect>,
/// The bounds Fit Layer(s) on Screen shows (the selected layers' content), in document units.
pub layers: Option<Rect>,
/// The document's resolution in pixels per inch, for Print Size.
pub ppi: Option<f64>,
/// The screen resolution Print Size shows the document at, in pixels per inch (Preferences, Units & Rulers).
/// Default: 72.
pub screen_ppi: f64,
}
impl ViewTarget {
/// A document of `size` with no artboard, no layer bounds and no resolution.
pub fn new(document: Size) -> Self {
Self { document, artboard: None, layers: None, ppi: None, screen_ppi: SCREEN_PPI }
}
/// The artboard Fit Artboard on Screen shows.
#[must_use]
pub fn artboard(mut self, artboard: Rect) -> Self {
self.artboard = Some(artboard);
self
}
/// The bounds Fit Layer(s) on Screen shows.
#[must_use]
pub fn layers(mut self, layers: Rect) -> Self {
self.layers = Some(layers);
self
}
/// The document's resolution, for Print Size.
#[must_use]
pub fn ppi(mut self, ppi: f64) -> Self {
self.ppi = Some(ppi);
self
}
/// The screen resolution Print Size shows the document at.
#[must_use]
pub fn screen_ppi(mut self, screen_ppi: f64) -> Self {
self.screen_ppi = screen_ppi;
self
}
/// Print Size's device zoom: the screen resolution over the document's.
fn print_zoom(&self) -> Option<f64> {
self.ppi.filter(|ppi| ppi.is_finite() && *ppi > 0.0).map(|ppi| self.screen_ppi / ppi).filter(|zoom| zoom.is_finite() && *zoom > 0.0)
}
}
impl From<Size> for ViewTarget {
fn from(document: Size) -> Self {
Self::new(document)
}
}
/// A rect with area, or none.
fn with_area(rect: Option<Rect>) -> Option<Rect> {
rect.map(|rect| rect.abs()).filter(|rect| rect.width() > 0.0 && rect.height() > 0.0)
}
/// The view commands: the keyboard path of the view tools, of the navigation menu and of the navigation bar's buttons.
/// [`apply`](Self::apply) is the one place that says what each does to a view, and [`available`](Self::available) when
/// each can run. The commands are scoped: a canvas container and a full-window dialog can be instances of the
/// `canvasView` scope, and a fired command goes to the instance that holds the key focus, else the one that held it
/// last, so a chord acts on the dialog's view while the dialog is open. The zoom commands also fire inside a dialog.
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)]
#[command(prefix = "canvasView", scope = "canvasView")]
#[non_exhaustive]
@@ -45,6 +124,19 @@ pub enum ViewCommands {
/// Show the document at 100 percent: one document pixel per device pixel, about the view's centre.
#[command(label = "100%", modal = "in_dialogs", default = "Cmd+1")]
ActualPixels,
/// Show the document at 200 percent about the view's centre.
#[command(label = "200%")]
TwoHundredPercent,
/// Show the document at its print size: the screen resolution over the document's, about the view's centre.
/// Disabled without the document's resolution.
#[command(label = "Print Size")]
PrintSize,
/// Show the whole artboard, centred, with room for its name. Disabled without an artboard.
#[command(label = "Fit Artboard on Screen")]
FitArtboard,
/// Show the selected layers' bounds, centred. Disabled without them.
#[command(label = "Fit Layer(s) on Screen")]
FitLayers,
/// Turn the view clockwise by 15 degrees.
#[command(label = "Rotate View Clockwise")]
RotateClockwise,
@@ -57,10 +149,30 @@ pub enum ViewCommands {
}
impl ViewCommands {
/// Applies the command to `view` for a document of `size` at `pixels_per_point`. Returns whether the view
/// changed.
pub fn apply(self, view: &mut CanvasView, size: Size, pixels_per_point: f32) -> bool {
/// Every view command, in menu order.
pub const ALL: [ViewCommands; 12] = [
ViewCommands::ZoomIn,
ViewCommands::ZoomOut,
ViewCommands::FitOnScreen,
ViewCommands::FillScreen,
ViewCommands::ActualPixels,
ViewCommands::TwoHundredPercent,
ViewCommands::PrintSize,
ViewCommands::FitArtboard,
ViewCommands::FitLayers,
ViewCommands::RotateClockwise,
ViewCommands::RotateCounterclockwise,
ViewCommands::ResetRotation,
];
/// Applies the command to `view` for `target` at `pixels_per_point`. Returns whether the view changed: a command
/// whose fact `target` lacks changes nothing.
pub fn apply(self, view: &mut CanvasView, target: &ViewTarget, pixels_per_point: f32) -> bool {
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);
};
match self {
ViewCommands::ZoomIn => {
zoom::step(view, 1, size, pixels_per_point);
@@ -71,8 +183,22 @@ impl ViewCommands {
// Photoshop fits the image to the view, with no margin.
ViewCommands::FitOnScreen => zoom::fit(view, size, pixels_per_point, 0.0),
ViewCommands::FillScreen => zoom::fill(view, size, pixels_per_point),
ViewCommands::ActualPixels => {
zoom::about(view, view.rect.center(), ZoomLadder::clamp(1.0, size), false, pixels_per_point);
ViewCommands::ActualPixels => zoom_about_centre(view, 1.0),
ViewCommands::TwoHundredPercent => zoom_about_centre(view, 2.0),
ViewCommands::PrintSize => {
if let Some(device) = target.print_zoom() {
zoom_about_centre(view, device);
}
}
ViewCommands::FitArtboard => {
if let Some(board) = with_area(target.artboard) {
zoom::fit_rect(view, board, size, pixels_per_point, ARTBOARD_MARGIN);
}
}
ViewCommands::FitLayers => {
if let Some(bounds) = with_area(target.layers) {
zoom::fit_rect(view, bounds, size, pixels_per_point, LAYERS_MARGIN);
}
}
ViewCommands::RotateClockwise => view.rotation = normalized_angle(view.rotation + ROTATE_STEP_DEG),
ViewCommands::RotateCounterclockwise => view.rotation = normalized_angle(view.rotation - ROTATE_STEP_DEG),
@@ -80,6 +206,24 @@ impl ViewCommands {
}
*view != before
}
/// Whether the command can run on `view` for `target`: Zoom In and Zoom Out stop at the ends of the zoom range,
/// Print Size needs the document's resolution, Fit Artboard an artboard and Fit Layers the layers' bounds.
pub fn available(self, view: &CanvasView, target: &ViewTarget, pixels_per_point: f32) -> bool {
match self {
ViewCommands::ZoomIn | ViewCommands::ZoomOut => self.apply(&mut view.clone(), target, pixels_per_point),
ViewCommands::PrintSize => target.print_zoom().is_some(),
ViewCommands::FitArtboard => with_area(target.artboard).is_some(),
ViewCommands::FitLayers => with_area(target.layers).is_some(),
_ => true,
}
}
/// Whether the command changes the zoom or the centre, so it eases under Animated Zoom; the rotate commands only
/// turn the view.
pub fn zooms(self) -> bool {
!matches!(self, ViewCommands::RotateClockwise | ViewCommands::RotateCounterclockwise | ViewCommands::ResetRotation)
}
}
/// The Hand tool: a drag pans the view with the document under the pointer; a release while still moving glides on
+12
View File
@@ -28,6 +28,18 @@ craft_ui::words! {
scroll_horizontal: "canvasScrollbars.horizontal" = "Horizontal scroll bar";
scroll_vertical: "canvasScrollbars.vertical" = "Vertical scroll bar";
navigate_zoom: "navigateBar.zoom" = "Zoom";
navigate_direction: "navigateBar.direction" = "Zoom direction";
navigate_zoom_in: "navigateBar.zoomIn" = "Zoom In";
navigate_zoom_out: "navigateBar.zoomOut" = "Zoom Out";
navigate_resize_windows: "navigateBar.resizeWindows" = "Resize Windows to Fit";
navigate_scrubby_zoom: "navigateBar.scrubbyZoom" = "Scrubby Zoom";
navigate_scroll_all: "navigateBar.scrollAllWindows" = "Scroll All Windows";
navigate_angle: "navigateBar.angle" = "Angle";
navigate_reset_view: "navigateBar.resetView" = "Reset View";
navigate_fit_screen: "navigateBar.fitScreen" = "Fit Screen";
navigate_fill_screen: "navigateBar.fillScreen" = "Fill Screen";
// canvas-navigator-a
navigator_horizontal: "navigator.horizontal" = "Visible area horizontal position";
navigator_vertical: "navigator.vertical" = "Visible area vertical position";
+41 -1
View File
@@ -1,6 +1,9 @@
//! The view tools: what a gesture asks the app's view to become, and the checks every tool owes the canvas.
use craft_ui::canvas::{HandTool, NavigationOptions, RotateViewTool, ZoomTool};
use craft_behavior::CanvasView;
use craft_behavior::canvas::zoom;
use craft_behavior::kurbo::{Point, Rect, Size};
use craft_ui::canvas::{HandTool, NavigationOptions, RotateViewTool, ViewCommands, ViewTarget, ZoomTool};
use craft_ui::testing::{ToolFixture, trial};
#[trial]
@@ -9,3 +12,40 @@ fn each_view_tool_owes_the_canvas_its_checks() {
ToolFixture::new("Zoom", ZoomTool::new(NavigationOptions::default())).check();
ToolFixture::new("Rotate View", RotateViewTool::default()).check();
}
/// The view commands that read a fact of the document beyond its size: each runs with its fact, and without it is
/// disabled and leaves the view as it is.
#[trial]
fn view_commands_run_with_their_facts_and_are_disabled_without() {
let ppp = 2.0;
let size = Size::new(4000.0, 3000.0);
let board = Rect::new(2500.0, 400.0, 3500.0, 1200.0);
let layers = Rect::new(100.0, 2000.0, 300.0, 2900.0);
let full = ViewTarget::new(size).artboard(board).layers(layers).ppi(300.0);
let bare = ViewTarget::from(size);
let start = CanvasView::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0)), Point::new(2000.0, 1500.0), 0.1);
let device = |view: &CanvasView| zoom::device(view, ppp);
let shows = |view: &CanvasView, rect: Rect| {
[rect.origin(), Point::new(rect.x1, rect.y1)].iter().all(|corner| view.rect.expand(0.5).contains(view.to_screen(*corner)))
};
// What each command owes the view it changed.
let rows: [(ViewCommands, &dyn Fn(&CanvasView) -> bool); 4] = [
(ViewCommands::TwoHundredPercent, &|view| (device(view) - 2.0).abs() < 1e-9 && view.center == start.center),
// Print Size: the screen's 72 ppi over the document's 300.
(ViewCommands::PrintSize, &|view| (device(view) - 72.0 / 300.0).abs() < 1e-9 && view.center == start.center),
(ViewCommands::FitArtboard, &|view| view.center == board.center() && shows(view, board) && device(view) > device(&start)),
(ViewCommands::FitLayers, &|view| view.center == layers.center() && shows(view, layers) && device(view) > device(&start)),
];
for (command, owed) in rows {
let mut view = start;
assert!(command.available(&start, &full, ppp), "{command:?} runs with its fact");
assert!(command.apply(&mut view, &full, ppp) && owed(&view), "{command:?} gives {view:?}");
if command == ViewCommands::TwoHundredPercent {
assert!(command.available(&start, &bare, ppp), "200% needs no fact");
continue;
}
let mut view = start;
assert!(!command.available(&start, &bare, ppp), "{command:?} is disabled without its fact");
assert!(!command.apply(&mut view, &bare, ppp) && view == start, "{command:?} leaves the view without its fact");
}
}
@@ -0,0 +1,12 @@
<svg id="icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<defs>
<style>
.cls-1 {
fill: none;
}
</style>
</defs>
<rect x="8" y="12" width="10" height="2"/>
<path d="M21.4479,20A10.856,10.856,0,0,0,24,13,11,11,0,1,0,13,24a10.856,10.856,0,0,0,7-2.5521L27.5859,29,29,27.5859ZM13,22a9,9,0,1,1,9-9A9.01,9.01,0,0,1,13,22Z"/>
<rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" class="cls-1" width="32" height="32"/>
</svg>

After

Width:  |  Height:  |  Size: 516 B

+8
View File
@@ -170,6 +170,14 @@ phosphor = "magnifying-glass-plus"
carbon = "zoom--in"
tabler = "zoom-in"
[[icon]]
name = "zoom_out"
directional = false
lucide = "zoom-out"
phosphor = "magnifying-glass-minus"
carbon = "zoom--out"
tabler = "zoom-out"
[[icon]]
name = "settings"
directional = false
@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="11" cy="11" r="8" />
<line x1="21" x2="16.65" y1="21" y2="16.65" />
<line x1="8" x2="14" y1="11" y2="11" />
</svg>

After

Width:  |  Height:  |  Size: 334 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M152,112a8,8,0,0,1-8,8H80a8,8,0,0,1,0-16h64A8,8,0,0,1,152,112Zm77.66,117.66a8,8,0,0,1-11.32,0l-50.06-50.07a88.11,88.11,0,1,1,11.31-11.31l50.07,50.06A8,8,0,0,1,229.66,229.66ZM112,184a72,72,0,1,0-72-72A72.08,72.08,0,0,0,112,184Z"/></svg>

After

Width:  |  Height:  |  Size: 326 B

@@ -0,0 +1,21 @@
<!--
tags: [zoom-out, magnify, shrink, minus, magnifier, magnifying-glass, scale, zooming, zoom, out]
category: Map
version: "1.0"
unicode: "eb57"
-->
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0" />
<path d="M7 10l6 0" />
<path d="M21 21l-6 -6" />
</svg>

After

Width:  |  Height:  |  Size: 464 B

@@ -101,6 +101,7 @@ pub(super) const SURFACES: &[(&str, &str, Surface)] = &[
("craft_ui", "Marquee", Canvas),
("craft_ui", "MenuBar", Chrome),
("craft_ui", "ModalDragStrip", Own),
("craft_ui", "NavigateBar", Chrome),
("craft_ui", "Navigator", Canvas),
("craft_ui", "NavigatorOptionsDialog", Own),
("craft_ui", "NavigatorZoomRow", Canvas),
+1
View File
@@ -180,6 +180,7 @@ Grouped by gallery level, then shape, then name.
| `MetadataTable` | Pattern | `craft_ui_widgets::table::metadata` | A key and value table in groups: a search field over the rows keeps the fields whose name or value matches the typed text, and a check column marks the keys the app shows as columns |
| `NamedPresetRow` | Pattern | `craft_ui_patterns::patterns::presets::named` | A preset picker with the commands that make, rename and delete presets |
| `NavigatorOptionsDialog` | Pattern | `craft_ui_patterns::patterns::form_dialogs::navigator_options` | Panel Options of the Navigator: the colour of the proxy rectangle |
| `NavigateBar` | Pattern | `craft_ui_canvas::canvas::navigate::bar` | The options of a navigation tool (Zoom, Rotate View, Hand), shown as children of the app's options bar, as in Photoshop |
| `NavigatorPanel` | Pattern | `craft_ui_canvas::canvas::navigator_panel` | The Navigator panel (Photoshop's Window, Navigator): the [`Navigator`] preview box over the [`NavigatorZoomRow`], both bound to one view |
| `NavigatorZoomRow` | Pattern | `craft_ui_canvas::canvas::navigator::zoom_row` | The Navigator's zoom row: a percent field, Zoom Out, a slider over the whole zoom range and Zoom In, in reading order |
| `NewDocumentDialog` | Pattern | `craft_ui_patterns::patterns::form_dialogs::new_document` | File > New: category tabs over a grid of preset cards, a details column and Create and Close |