diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index fa1539c59..90e16fc1b 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -46,6 +46,9 @@ pub const NO_DOCUMENT: &str = "no document canvas to place document coordinates /// The error of a document point whose place on the screen is beyond [`MAX_SCREEN_POINT`]. pub const OFF_SCREEN: &str = "the document point is too far off the screen"; +/// The error of a point that is not finite (NaN or infinite): refused at the request, never queued. +pub const NOT_FINITE: &str = "the point must be finite"; + /// The application's map from a document point to the screen point its canvas shows it at; `None` when no canvas /// shows a document. Applications without documents pass `&|_| None`. pub type DocumentMap<'a> = &'a dyn Fn(Pos2) -> Option; @@ -73,10 +76,12 @@ impl At { } /// The screen point, through `map` for a document point; [`NO_DOCUMENT`] when the map has none, and - /// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]. + /// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]; a point that is not finite is [`NOT_FINITE`]. pub fn resolve(self, map: DocumentMap<'_>) -> Result { match self { - Self::Screen(at) => Ok(at), + Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(at), + Self::Screen(_) => Err(NOT_FINITE.to_owned()), + Self::Document(at) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()), Self::Document(at) => { let on_screen = map(at).ok_or_else(|| NO_DOCUMENT.to_owned())?; let within = |v: f32| v.is_finite() && f64::from(v.abs()) <= MAX_SCREEN_POINT; diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 9701310a9..972bf5659 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -5,7 +5,7 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, input_method}; +use craft_automation::synthetic::{At, MAX_CLICKS, NOT_FINITE, MAX_SCREEN_POINT, NO_DOCUMENT, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -336,3 +336,14 @@ fn ui_ime_reaches_a_focused_text_field_as_a_preedit_then_a_commit_in_order() { assert!(matches!(both, Some(Err(_))), "{both:?}"); assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused request queued nothing"); } + +/// A NaN or infinite point of a request is an error at the request, in either coordinate space, not a panic in the pass. +#[trial] +fn a_point_that_is_not_finite_is_refused() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0))] { + assert_eq!(at.resolve(&|p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}"); + } + } + assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_| None), Ok(pos2(3.0, 4.0))); +} diff --git a/crates/behavior/src/geometry/snap.rs b/crates/behavior/src/geometry/snap.rs index 9daf8ad43..275a92936 100644 --- a/crates/behavior/src/geometry/snap.rs +++ b/crates/behavior/src/geometry/snap.rs @@ -334,6 +334,14 @@ impl SnapTargets { /// The offset that moves `rect` so its nearest edge or centre meets a target on each axis, /// with the lines to draw. Edges win over centres at equal distance. pub fn snap_rect(&self, rect: Rect, tolerance: f64) -> (Vec2, Vec) { + self.snap_rect_of(rect, tolerance, SnapKinds::ALL) + } + + /// [`snap_rect`](Self::snap_rect) to the targets of a kind in `kinds` only (moving a selection skips the selection's + /// own edges). + /// + /// Public: craft-ui-canvas's `Snap::rect` filters through it. + pub fn snap_rect_of(&self, rect: Rect, tolerance: f64, kinds: SnapKinds) -> (Vec2, Vec) { let mut delta = Vec2::ZERO; let mut lines = Vec::new(); let rect = rect.abs(); @@ -346,7 +354,7 @@ impl SnapTargets { let anchors = [lo, hi, (lo + hi) / 2.0]; let mut best: Option = None; for anchor in anchors { - if let Some(t) = self.nearest(along, anchor, tolerance) { + if let Some(t) = self.nearest_of(along, anchor, tolerance, kinds) { let d = t.position - anchor; if best.is_none_or(|b| d.abs() < b.abs() - TIE) { best = Some(d); @@ -363,7 +371,7 @@ impl SnapTargets { let hit = self .targets .iter() - .filter(|t| t.along == along && (t.position - moved).abs() < 1e-6) + .filter(|t| t.along == along && kinds.contains(t.kind) && (t.position - moved).abs() < 1e-6) .min_by_key(|t| u8::from(t.kind != SnapKind::Guide)); if let Some(t) = hit { lines.push(line(t, other.0, other.1)); diff --git a/crates/behavior/tests/geometry/snap.rs b/crates/behavior/tests/geometry/snap.rs index 165d98b58..3df1bcb57 100644 --- a/crates/behavior/tests/geometry/snap.rs +++ b/crates/behavior/tests/geometry/snap.rs @@ -1,7 +1,7 @@ //! Snapping to targets within a tolerance. use craft_behavior::Axis; -use craft_behavior::geometry::{SnapKind, SnapTarget, SnapTargets}; +use craft_behavior::geometry::{SnapKind, SnapKinds, SnapTarget, SnapTargets}; use kurbo::{Rect, Vec2}; fn guide(along: Axis, position: f64) -> SnapTarget { @@ -19,3 +19,15 @@ fn a_moving_rect_snaps_its_nearest_edge_or_centre() { assert_eq!(offset, Vec2::ZERO); assert!(lines.is_empty()); } + +#[test] +fn a_moving_rect_skips_the_kinds_left_out() { + let mut targets = SnapTargets::new(); + targets.add(SnapTarget::new(Axis::Y, 100.0, SnapKind::Selection)); + let rect = Rect::new(76.0, 53.0, 98.0, 90.0); + let (offset, lines) = targets.snap_rect(rect, 4.0); + assert_eq!(offset.x, 2.0, "the selection's edge snaps by default"); + assert_eq!(lines.len(), 1); + let (offset, lines) = targets.snap_rect_of(rect, 4.0, SnapKinds::ALL.without(SnapKind::Selection)); + assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a moved selection ignores the selection's edges"); +} diff --git a/crates/draw/src/geometry/fillet.rs b/crates/draw/src/geometry/fillet.rs index d90dbcf03..eac9ff1ae 100644 --- a/crates/draw/src/geometry/fillet.rs +++ b/crates/draw/src/geometry/fillet.rs @@ -56,18 +56,22 @@ pub fn fillet(prev: Point, vertex: Point, next: Point, radius: f64) -> Option) -> &mut Self { - if self.run.is_none() { + let host_ended = draft.is_none_or(|draft| draft.knots.is_empty()) && self.run.is_some() && self.drag.is_none(); + if self.run.is_none() || host_ended { + self.run = None; match draft.filter(|draft| !draft.knots.is_empty()) { Some(draft) => { self.shown = draft.clone(); @@ -215,6 +219,7 @@ impl PenTool { None => { self.shown = EditSubpath::default(); self.own = 0; + self.kept = 0; self.resume = false; } } diff --git a/crates/draw/src/ui/transform/session.rs b/crates/draw/src/ui/transform/session.rs index 7f6814bbc..f97c822dc 100644 --- a/crates/draw/src/ui/transform/session.rs +++ b/crates/draw/src/ui/transform/session.rs @@ -53,6 +53,14 @@ pub trait TransformWarp: Clone + PartialEq + Send + Sync + 'static { /// An app whose type layers commit an identity warp (a Warp Text set back to None) answers /// false for those. fn is_identity(&self) -> bool; + + /// The source frame the warp is made on, when it is not the session's: a stored smart warp is edited over the + /// unwarped source, whose frame differs from the bounds of its warped render the session opened on. The session + /// takes it as its frame, with the box on its corners, in the step that enters the warp, and gives the frame and + /// box back when the warp is left. `None` (the default): the warp follows the session's own frame and box. + fn frame(&self) -> Option { + None + } } /// No warp: a session that never enters the Warp phase (VectorCraft's Free Transform, Content-Aware @@ -156,6 +164,10 @@ pub struct TransformResult { /// and changing one of them is no undo step of its own. #[derive(Clone, Debug, PartialEq)] struct TransformDraft { + /// The source frame: the session's own, or a stored warp's ([`TransformWarp::frame`]) while it is open. + frame: Rect, + /// The frame and box the session had before a warp with its own frame replaced them, for `LeaveWarp`. + unwarped: Option<(Rect, BoxState)>, state: BoxState, skew_v: f64, warp: Option, @@ -173,8 +185,6 @@ struct TransformDraft { /// - No serde (LC7): the app builds its own record from the getters. #[derive(Clone, Debug)] pub struct TransformSession { - /// The source frame (the layer's bounds); fixed for the session. - rect: Rect, /// What the content allows (type refuses distort and perspective). allow: BoxAllow, draft: TransformDraft, @@ -207,9 +217,8 @@ impl TransformSession { /// A session on `rect` whose box starts at `state`: Content-Aware Move's placed box, a box /// reopened after a failed commit. pub fn with_state(rect: Rect, state: BoxState) -> Self { - let draft = TransformDraft { state, skew_v: 0.0, warp: None }; + let draft = TransformDraft { frame: rect, unwarped: None, state, skew_v: 0.0, warp: None }; Self { - rect, allow: BoxAllow::default(), history: EditHistory::new(&draft), rested: draft.clone(), @@ -252,9 +261,9 @@ impl TransformSession { self } - /// The source frame. + /// The source frame: the one the session opened on, or the open warp's own ([`TransformWarp::frame`]). pub fn rect(&self) -> Rect { - self.rect + self.draft.frame } /// The box. @@ -320,13 +329,13 @@ impl TransformSession { pub fn homography(&self) -> Option { // pc: crates/ui-egui/src/tools/transform_tool/draw.rs:113 (`Homography::rect_to_quad` of // the unit square, then the box). - let (w, h) = (self.rect.width(), self.rect.height()); + let (w, h) = (self.draft.frame.width(), self.draft.frame.height()); if !(w.abs() > 1e-9 && h.abs() > 1e-9) { return None; } let unit = Homography::unit_to_quad(self.draft.state.quad)?; // The box's map after the frame's affine map onto the unit square. - let (x0, y0) = (self.rect.x0, self.rect.y0); + let (x0, y0) = (self.draft.frame.x0, self.draft.frame.y0); let row = |i: usize| { let r = unit.row(i); [r[0] / w, r[1] / h, r[2] - r[0] * x0 / w - r[1] * y0 / h] @@ -353,7 +362,7 @@ impl TransformSession { // the frame's corners). match &self.draft.warp { Some(warp) => warp.is_identity(), - None => self.draft.state.quad == BoxState::from_rect(self.rect).quad, + None => self.draft.state.quad == BoxState::from_rect(self.draft.frame).quad, } } @@ -363,7 +372,7 @@ impl TransformSession { if self.is_untouched() { return None; } - Some(TransformResult { rect: self.rect, state: self.draft.state, interpolation: self.interpolation, warp: self.draft.warp.clone() }) + Some(TransformResult { rect: self.draft.frame, state: self.draft.state, interpolation: self.interpolation, warp: self.draft.warp.clone() }) } /// Applies one edit; `now` is the pass's input time in seconds (the nudge pause reads it). @@ -411,11 +420,26 @@ impl TransformSession { TransformEdit::Pivot(anchor) => self.draft.state.pivot = self.draft.state.point_at(anchor), TransformEdit::WarpRequested => { if self.allow.warp && self.draft.warp.is_none() { - return Some(TransformRequest::NeedWarp { rect: self.rect, state: self.draft.state }); + return Some(TransformRequest::NeedWarp { rect: self.draft.frame, state: self.draft.state }); } } - TransformEdit::Warp(warp) => self.draft.warp = Some(warp), - TransformEdit::LeaveWarp => self.draft.warp = None, + TransformEdit::Warp(warp) => { + if self.draft.warp.is_none() + && let Some(frame) = warp.frame() + { + self.draft.unwarped = Some((self.draft.frame, self.draft.state)); + self.draft.frame = frame; + self.draft.state = BoxState::from_rect(frame); + } + self.draft.warp = Some(warp); + } + TransformEdit::LeaveWarp => { + if let Some((frame, state)) = self.draft.unwarped.take() { + self.draft.frame = frame; + self.draft.state = state; + } + self.draft.warp = None; + } } None } diff --git a/crates/draw/tests/it/pen.rs b/crates/draw/tests/it/pen.rs index ef0bc47a6..41d111cc6 100644 --- a/crates/draw/tests/it/pen.rs +++ b/crates/draw/tests/it/pen.rs @@ -285,3 +285,18 @@ fn a_curvature_resume_keeps_the_carried_knots_and_replace_updates_the_draft() { } // ---- Path modes and Path Options ---- + +/// A host that ended the draft itself hands in no draft: the pen drops its run without an event, and the next press +/// starts a new draft rather than carrying on the ended one. +#[trial] +fn a_draft_the_host_ended_is_not_carried_on() { + let mut pen = pen(); + pen.click_doc(100.0, 100.0); + pen.click_doc(200.0, 100.0); + assert_eq!(pen.draft().knots.len(), 2); + pen.fixture.tool_mut().draft(None); + assert!(pen.fixture.tool_mut().take_events().is_empty(), "the host ended it: the pen reports nothing"); + pen.log.clear(); + pen.click_doc(100.0, 200.0); + assert_eq!(pen.draft().knots.len(), 1, "a new draft"); +} diff --git a/crates/draw/tests/it/transform_session.rs b/crates/draw/tests/it/transform_session.rs index 28f924597..04826599e 100644 --- a/crates/draw/tests/it/transform_session.rs +++ b/crates/draw/tests/it/transform_session.rs @@ -138,3 +138,34 @@ fn the_homography_maps_the_frame_onto_the_box() { s.apply(TransformEdit::Box(set(line)), 0.0); assert!(s.homography().is_none()); } + +#[derive(Clone, Debug, PartialEq)] +struct Framed(Rect); + +impl TransformWarp for Framed { + fn is_identity(&self) -> bool { + false + } + + fn frame(&self) -> Option { + Some(self.0) + } +} + +/// A warp with its own frame takes the session's frame and box in the step that enters it; leaving the warp, Undo and +/// Redo give the frame and the box back in step with the warp. +#[trial] +fn a_warp_with_its_own_frame_takes_the_frame_and_gives_it_back() { + let inner = Rect::new(20.0, 10.0, 120.0, 60.0); + let mut s = TransformSession::::new(FRAME); + s.apply(TransformEdit::Warp(Framed(inner)), 0.0); + s.settle(0.0, false); + assert_eq!((s.rect(), s.state().quad), (inner, BoxState::from_rect(inner).quad)); + assert!(!s.is_untouched()); + assert!(s.undo()); + assert_eq!((s.rect(), s.state().quad), (FRAME, BoxState::from_rect(FRAME).quad), "undo restores frame and box with the warp"); + assert!(s.redo()); + assert_eq!(s.rect(), inner); + s.apply(TransformEdit::LeaveWarp, 1.0); + assert_eq!((s.rect(), s.state().quad), (FRAME, BoxState::from_rect(FRAME).quad)); +} diff --git a/crates/imaging/src/ui/adjust/context.rs b/crates/imaging/src/ui/adjust/context.rs index d9d1d76a1..9d41329f6 100644 --- a/crates/imaging/src/ui/adjust/context.rs +++ b/crates/imaging/src/ui/adjust/context.rs @@ -176,7 +176,8 @@ impl ToneChannel { } /// The channels a Levels or Curves panel lists, in Channel-select order; a histogram, a Levels -/// value or a curve of the host is addressed by the same index. +/// value or a curve of the host is addressed by the same index. The list is empty for an action whose target is +/// unresolved ([`listed`](Self::listed) with no channel); the panels then draw no Channel select. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ToneChannels { channels: Vec, @@ -232,7 +233,8 @@ impl ToneChannels { self.channels.len() } - /// Whether the list is empty (never for [`of`](Self::of) and [`isolated`](Self::isolated)). + /// Whether the list is empty ([`listed`](Self::listed) with none); never for + /// [`of`](Self::of) and [`isolated`](Self::isolated). pub fn is_empty(&self) -> bool { self.channels.is_empty() } diff --git a/crates/imaging/src/ui/adjust/curves_panel.rs b/crates/imaging/src/ui/adjust/curves_panel.rs index 524cb3b80..5c6966e40 100644 --- a/crates/imaging/src/ui/adjust/curves_panel.rs +++ b/crates/imaging/src/ui/adjust/curves_panel.rs @@ -345,12 +345,15 @@ impl<'a> CurvesPanel<'a> { } let mut picked = channel; - Row::new().show(ui, |ui, _| { - Text::new(words.channel.clone()).shade(Shade::Muted).role(TypeRole::Label).show(ui); - if let Some(&at) = Select::new(words.channel.clone(), Bind::given(channel), &entries).show(ui).value() { - picked = at; - } - }); + // No channels (an action whose target is unresolved): no Channel select. + if !entries.is_empty() { + Row::new().show(ui, |ui, _| { + Text::new(words.channel.clone()).shade(Shade::Muted).role(TypeRole::Label).show(ui); + if let Some(&at) = Select::new(words.channel.clone(), Bind::given(channel), &entries).show(ui).value() { + picked = at; + } + }); + } let mut smooth = false; Row::new().show(ui, |ui, _| { for (target, icon, name) in diff --git a/crates/imaging/src/ui/adjust/levels_panel.rs b/crates/imaging/src/ui/adjust/levels_panel.rs index 8a67aabb5..9e5c44d1b 100644 --- a/crates/imaging/src/ui/adjust/levels_panel.rs +++ b/crates/imaging/src/ui/adjust/levels_panel.rs @@ -199,10 +199,13 @@ impl<'a> LevelsPanel<'a> { let mut picked = channel; let mut auto = false; Row::new().show(ui, |ui, _| { - Text::new(words.channel.clone()).shade(Shade::Muted).role(TypeRole::Label).show(ui); - let select = Select::new(words.channel.clone(), Bind::given(channel), &entries).sizing(Sizing::Content).show(ui); - if let Some(&at) = select.value() { - picked = at; + // No channels (an action whose target is unresolved): no Channel select. + if !entries.is_empty() { + Text::new(words.channel.clone()).shade(Shade::Muted).role(TypeRole::Label).show(ui); + let select = Select::new(words.channel.clone(), Bind::given(channel), &entries).sizing(Sizing::Content).show(ui); + if let Some(&at) = select.value() { + picked = at; + } } auto = clicked(&Button::new(words.auto.clone()).enabled(counts.is_some()).show(ui)); }); diff --git a/crates/imaging/src/ui/fill/mod.rs b/crates/imaging/src/ui/fill/mod.rs index 87ad0ccc9..d04f4aafe 100644 --- a/crates/imaging/src/ui/fill/mod.rs +++ b/crates/imaging/src/ui/fill/mod.rs @@ -927,7 +927,7 @@ impl FullWindowWorkspace for ContentAwareFillWorkspace { } /// A settings key, a bar key of [`json_fields`](Self::json_fields), or an action: `stroke` (`{points, size?, alt?}`), - /// `lasso` (`{points, op}`), `reset` (`"all"`, `"fillArea"`, `"sampling"`), `undo`, `redo` and `apply` (each `true`). + /// `lasso` (`{points, op}`), `expand` and `contract` (pixels, 1..=100: the fill area grows or shrinks by that), `reset` (`"all"`, `"fillArea"`, `"sampling"`), `undo`, `redo` and `apply` (each `true`). /// A stroke or lasso edit goes through the limits like the canvas's; one a limit refuses is rejected and the panel /// shows the limit. fn set_json_field(&mut self, ctx: &Context, _source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { @@ -952,6 +952,10 @@ impl FullWindowWorkspace for ContentAwareFillWorkspace { let by = value.as_f64().ok_or_else(|| rejects(&value))?; self.options.grow_by = by.clamp(FillAreaEdit::GROW_RANGE.0, FillAreaEdit::GROW_RANGE.1); } + "expand" | "contract" => { + let by = value.as_f64().filter(|by| by.is_finite()).ok_or_else(|| rejects(&value))?; + self.perform(FillOp::FillArea(FillAreaEdit::grow(field == "expand", by))).map_err(|limit| limit.message(&Env::of_root(ctx)))?; + } "sampling" => { let mode = serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?; self.perform(FillOp::Sampling(mode)).map_err(|limit| limit.message(&Env::of_root(ctx)))?; diff --git a/crates/imaging/src/ui/select/drag.rs b/crates/imaging/src/ui/select/drag.rs index 03f752adf..9888f8c2e 100644 --- a/crates/imaging/src/ui/select/drag.rs +++ b/crates/imaging/src/ui/select/drag.rs @@ -2,7 +2,7 @@ //! tools use it unchanged). Public for the app's own tools: the Magic Wand in New mode drags the outline like a //! marquee, so it takes [`PressRule::Drags`]. -use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, MoveValue, SelectionOperation}; +use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, MoveValue, SelectionOperation, SnapKind, SnapKinds}; use craft_behavior::{CancelReason, Cursor, CursorBadge, CursorIcon, EditEvent, GestureId, Mixed, PaintedCursor}; use craft_keymap::Mods; use kurbo::{Point, Vec2}; @@ -166,6 +166,12 @@ impl InsideDrag { } } +/// The offset that snaps the moved selection's bounds `rect` to the canvas's targets: every kind but the selection's own +/// edges, which move with it. +pub(super) fn moved_selection_snap(cx: &mut craft_ui::canvas::ToolContext<'_>, rect: kurbo::Rect) -> Vec2 { + cx.snap_rect_of(rect, SnapKinds::ALL.without(SnapKind::Selection)) +} + /// The value's offset plus the snap of the press `bounds` moved by it; the offset itself without bounds. A value that /// changed nothing (a click) is `Vec2::ZERO` and calls no `snap`. fn snapped(bounds: Option, value: &MoveValue, snap: &mut dyn FnMut(kurbo::Rect) -> Vec2) -> Vec2 { diff --git a/crates/imaging/src/ui/select/lasso.rs b/crates/imaging/src/ui/select/lasso.rs index 10fc6b013..d5e3c8607 100644 --- a/crates/imaging/src/ui/select/lasso.rs +++ b/crates/imaging/src/ui/select/lasso.rs @@ -8,7 +8,7 @@ use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon}; use egui::{Pos2, Vec2}; use kurbo::Rect; -use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind}; +use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind, moved_selection_snap}; use super::{DragKind, Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectWords, SelectionProbe, SelectionShape}; /// Where a lasso cursor's icon touches the document: the icon's own origin. @@ -330,7 +330,7 @@ impl CanvasTool for SelectToolPass<'_, LassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.as_mut() { - if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)) { + if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| moved_selection_snap(cx, rect)) { tool.report.push(event); } return; @@ -345,7 +345,7 @@ impl CanvasTool for SelectToolPass<'_, LassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.take() { - tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect))); + tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| moved_selection_snap(cx, rect))); return; } let event = tool.draft.release(sample(pointer, &place)); diff --git a/crates/imaging/src/ui/select/marquee.rs b/crates/imaging/src/ui/select/marquee.rs index b53ac2649..c6a9f6997 100644 --- a/crates/imaging/src/ui/select/marquee.rs +++ b/crates/imaging/src/ui/select/marquee.rs @@ -10,7 +10,7 @@ use craft_ui::primitives::Draw; use egui::Pos2; use kurbo::{Point, Rect, Vec2}; -use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind}; +use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind, moved_selection_snap}; use super::{Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectWords, SelectionProbe, SelectionShape}; /// The points that approximate an ellipse's ants. @@ -320,7 +320,7 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { let Some(place) = Place::of(cx) else { return }; let raw = place.doc(pointer.pos); if let Some(inside) = tool.inside.as_mut() { - if let Some(event) = inside.drag(raw, pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)) { + if let Some(event) = inside.drag(raw, pointer.mods, place.zoom(), &mut |rect| moved_selection_snap(cx, rect)) { tool.report.push(event); } return; @@ -341,7 +341,7 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { if let Some(inside) = tool.inside.take() { let line = tool.line.take(); let unmoved = inside.clone(); - let event = inside.end(raw, pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)); + let event = inside.end(raw, pointer.mods, place.zoom(), &mut |rect| moved_selection_snap(cx, rect)); let still = matches!(&event, SelectEvent::DragSelection(EditEvent::Commit { after, .. }) if after.delta == [0, 0]); let picked = line.filter(|_| still).and_then(|line| Some((single_line(tool.kind, line.size, line.at)?, line.operation))); match picked { diff --git a/crates/imaging/src/ui/select/polygon.rs b/crates/imaging/src/ui/select/polygon.rs index 87dc9d0ed..a6f9d4119 100644 --- a/crates/imaging/src/ui/select/polygon.rs +++ b/crates/imaging/src/ui/select/polygon.rs @@ -6,7 +6,7 @@ use craft_keymap::Mods; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::{Draw, ToolIcon}; -use super::drag::{InsideDrag, PressRule, drag_kind}; +use super::drag::{InsideDrag, PressRule, drag_kind, moved_selection_snap}; use super::lasso::{LassoCursor, apply, begin_inside, cursor, draft_key, outline_access, paint_outline, phase, reach, sample}; use super::{Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectionProbe}; @@ -160,7 +160,7 @@ impl CanvasTool for SelectToolPass<'_, PolygonLassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.as_mut() { - if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)) { + if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| moved_selection_snap(cx, rect)) { tool.report.push(event); } return; @@ -174,7 +174,7 @@ impl CanvasTool for SelectToolPass<'_, PolygonLassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.take() { - tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect))); + tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| moved_selection_snap(cx, rect))); return; } let event = tool.draft.release(sample(pointer, &place)); diff --git a/crates/imaging/tests/it/fill.rs b/crates/imaging/tests/it/fill.rs index 1f018ba88..9a6feed83 100644 --- a/crates/imaging/tests/it/fill.rs +++ b/crates/imaging/tests/it/fill.rs @@ -16,7 +16,7 @@ use craft_imaging::ui::fill::{ use craft_imaging::ui::select_mask::EditMode; use craft_imaging::ui::wide_angle::PreviewDone; use craft_ui::canvas::{PixelRect, RasterSource}; -use craft_ui::dialog::{DialogHost, DialogResult, HostedWorkspace}; +use craft_ui::dialog::{DialogHost, FullWindowWorkspace as _, DialogResult, HostedWorkspace}; use craft_ui::primitives::Revision; use craft_ui::runtime::access::Role; use craft_ui::runtime::memory::{SaveKey, saved_value}; @@ -290,3 +290,18 @@ fn fill_remembers_its_settings_at_cancel() { rig.fixture.idle(3); assert_eq!(rig.with(|work| work.settings().opacity), 10.0, "the next opening takes the stored settings"); } + +/// The automation keys `expand` and `contract` edit the fill area by that many pixels, like the bar's buttons; a +/// value that is not a number is refused. +#[trial] +fn expand_and_contract_keys_edit_the_fill_area() { + let rig = Rig::new(FillSettings::default(), FillLimits::new(10, 100)); + let ctx = rig.fixture.ctx().clone(); + let source: Arc = Arc::new(Source); + let set = |field: &str, value: serde_json::Value| rig.with(|workspace| workspace.set_json_field(&ctx, &*source, field, value)); + assert_eq!(set("expand", serde_json::json!(3)), Ok(())); + assert_eq!(set("contract", serde_json::json!(2)), Ok(())); + assert!(set("expand", serde_json::json!("wide")).is_err(), "text is not an amount"); + let edits = rig.with(|workspace| workspace.session().fill_edits.clone()); + assert_eq!(edits, vec![FillAreaEdit::grow(true, 3.0), FillAreaEdit::grow(false, 2.0)]); +} diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index 13c0f6ae9..8ae276da9 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -54,8 +54,13 @@ impl Snap { /// The offset that moves `rect` onto a snap target, with the lines to draw; zero when snapping is off. pub fn rect(&self, rect: craft_behavior::kurbo::Rect, mods: Mods) -> (Vec2, Vec) { + self.rect_of(rect, mods, craft_behavior::geometry::SnapKinds::ALL) + } + + /// [`rect`](Self::rect) to the targets of a kind in `kinds` only. + pub fn rect_of(&self, rect: craft_behavior::kurbo::Rect, mods: Mods, kinds: craft_behavior::geometry::SnapKinds) -> (Vec2, Vec) { match self.reach(mods, false) { - Some(tolerance) => self.targets.snap_rect(rect, tolerance), + Some(tolerance) => self.targets.snap_rect_of(rect, tolerance, kinds), None => (Vec2::ZERO, Vec::new()), } } diff --git a/crates/ui-canvas/src/canvas/tool.rs b/crates/ui-canvas/src/canvas/tool.rs index 9aed176f1..5f7fca608 100644 --- a/crates/ui-canvas/src/canvas/tool.rs +++ b/crates/ui-canvas/src/canvas/tool.rs @@ -10,7 +10,7 @@ use crate::primitives::{ContentPainterCx, Draw}; use crate::runtime::env::{Direction, Env, Label, MotionPolicy, PointSize, UnitWords, Units, WordSet, Words}; use crate::runtime::motion::loop_phase; use crate::style::StyleCx; -use craft_behavior::geometry::SnapLine; +use craft_behavior::geometry::{SnapKinds, SnapLine}; use craft_behavior::kurbo::{self, Point}; use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GestureId, PointerButton, PointerSample}; use craft_i18n::{Digits, Format, Region}; @@ -424,8 +424,14 @@ impl<'a> ToolContext<'a> { /// The offset that moves `rect` (document units) onto a View > Snap To target with the modifiers held now; zero /// when Control suspends snapping or the canvas has no snap. pub fn snap_rect(&mut self, rect: kurbo::Rect) -> kurbo::Vec2 { + self.snap_rect_of(rect, SnapKinds::ALL) + } + + /// [`snap_rect`](Self::snap_rect) to the targets of a kind in `kinds` only: moving a selection leaves out the + /// selection's own edges. + pub fn snap_rect_of(&mut self, rect: kurbo::Rect, kinds: SnapKinds) -> kurbo::Vec2 { let Some(snap) = self.snap else { return kurbo::Vec2::ZERO }; - let (offset, lines) = snap.rect(rect, self.mods); + let (offset, lines) = snap.rect_of(rect, self.mods, kinds); self.requests.snapped.extend(lines); offset } @@ -478,7 +484,7 @@ impl<'a> ToolContext<'a> { /// without an env. pub fn reach(&self) -> f32 { match self.env { - Some(env) => env.tokens.size.hit.target, + Some(env) => env.hit_reach(), None => crate::runtime::frame::resolved_hit(&craft_theme::AppSizes::default()).target, } } diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 52555f3c1..fd2bacf63 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -311,6 +311,11 @@ pub(crate) struct ScrollOwner { } impl Scoped { + /// How far from a handle, point or edge a press still takes it, in screen points: the theme's `size.hit.target`. + pub fn hit_reach(&self) -> f32 { + self.tokens.size.hit.target + } + /// Whether the scope is the body of a container with a view of its own, as the innermost scroll owner: its stops /// take the document key role (`KeyRole::document`). pub(crate) fn in_view_body(&self) -> bool { @@ -525,6 +530,13 @@ impl Env { found.unwrap_or_else(|| Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx))) } + /// How far from a handle, point or edge a press still takes it, in screen points: the theme's `size.hit.target` as + /// the running viewport's root env has it. `ToolContext::reach` reads the same + /// value; code with no tool context (a menu capture hit-testing a canvas point) reads it here. + pub fn root_hit_reach(ctx: &Context) -> f32 { + Self::of_root(ctx).hit_reach() + } + /// The `Host` of the running viewport's root env. pub(crate) fn host_of(ctx: &Context) -> Option> { PerViewport::::with(ctx, pass::current_viewport(ctx), |envs| envs.root.as_ref().and_then(|env| env.host.clone())) diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 7c02bc4f2..a1ec6b87c 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -110,7 +110,8 @@ impl WindowHost { screenshot::facts(&self.ctx, viewport) } - /// Queues a pointer move to `at` in `viewport` with `mods` held, delivered on a pass of its own; the modifiers + /// Queues a pointer move to `at` in `viewport`; `at` is finite (the request that carries it refuses a NaN or infinite + /// position) and the same holds for every `inject_*` position below with `mods` held, delivered on a pass of its own; the modifiers /// stay held after it, and a button held by earlier injected input stays down, so the move drags. With `rest` /// (seconds) the input counts as processed only once the pointer has rested that long. pub fn inject_move(&self, viewport: ViewportId, at: Pos2, mods: Mods, rest: f64) { diff --git a/crates/ui-contract/tests/it/runtime/env.rs b/crates/ui-contract/tests/it/runtime/env.rs index 1dd978c4e..d6155f189 100644 --- a/crates/ui-contract/tests/it/runtime/env.rs +++ b/crates/ui-contract/tests/it/runtime/env.rs @@ -57,3 +57,14 @@ fn scopes_merge_by_the_table_and_follow_the_ui_tree() { assert!(ui.is_enabled(), "the parent Ui is untouched by the scope"); }); } + +/// The pointer reach is the theme's hit target, read the same from a scope and from the context outside any `Ui`. +#[trial] +fn the_hit_reach_is_one_read_in_a_scope_and_from_the_context() { + let mut frames = Frames::new(); + frames.frame(vec![], |ui| { + let reach = Env::of(ui).hit_reach(); + assert!(reach > 0.0); + assert_eq!(Env::root_hit_reach(ui.ctx()), reach); + }); +}