diff --git a/crates/behavior/src/geometry/lock.rs b/crates/behavior/src/geometry/lock.rs index dab4fbb43..a41e3ed8b 100644 --- a/crates/behavior/src/geometry/lock.rs +++ b/crates/behavior/src/geometry/lock.rs @@ -1,5 +1,5 @@ -//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`] and -//! [`polygon_step`]. +//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`], +//! [`polygon_step`] and [`axis_or_diagonal`]. use kurbo::{Point, Vec2}; @@ -7,6 +7,10 @@ use kurbo::{Point, Vec2}; /// before a locked direction switches, so it doesn't flicker near the diagonal. pub const LOCK_HYSTERESIS_DEGREES: f64 = 8.0; +/// How near an axis, in degrees, a ⇧ line or anchor drag must point to snap onto the axis rather than the diagonal +/// ([`axis_or_diagonal`]). +pub const AXIS_BAND_DEGREES: f64 = 30.0; + /// The directions ⇧ locks a move to. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] @@ -56,6 +60,28 @@ pub fn polygon_step(from: Point, point: Point) -> Point { from + Vec2::new(shorter.copysign(delta.x), shorter.copysign(delta.y)) } +/// Shift's rule for the Line tool and anchor drags: within [`AXIS_BAND_DEGREES`] of an axis, `point` moves onto the +/// axis through `from` and keeps its offset along it; otherwise onto the 45° diagonal, at the shorter of its two +/// offsets on both axes. `point` itself for a zero or non-finite offset. +pub fn axis_or_diagonal(from: Point, point: Point) -> Point { + // Photoshop flattens a 26.6° drag and keeps a 39.8° one diagonal (#13243); anchors stay on the axis at a 5:12 + // slope (22.6°) and go diagonal at 45° (#13207). + let delta = point - from; + if !delta.x.is_finite() || !delta.y.is_finite() || delta == Vec2::ZERO { + return point; + } + let tan = AXIS_BAND_DEGREES.to_radians().tan(); + let (ax, ay) = (delta.x.abs(), delta.y.abs()); + if ay < ax * tan { + return Point::new(point.x, from.y); + } + if ax < ay * tan { + return Point::new(from.x, point.y); + } + let shorter = ax.min(ay); + from + Vec2::new(shorter.copysign(delta.x), shorter.copysign(delta.y)) +} + /// `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle /// or a segment drawn from a fixed point. A polygon's vertex takes [`polygon_step`] instead. `point` itself when it /// is on `from` or not finite. diff --git a/crates/behavior/src/geometry/mod.rs b/crates/behavior/src/geometry/mod.rs index c36222821..24886f10d 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -18,7 +18,9 @@ pub mod snap; pub use crop::{AspectHold, CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step, turn_grid}; pub use draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft}; -pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, polygon_step, round_to_direction, turn_to_45}; +pub use lock::{ + AXIS_BAND_DEGREES, Directions, LOCK_HYSTERESIS_DEGREES, axis_or_diagonal, lock_direction, polygon_step, round_to_direction, turn_to_45, +}; pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels}; pub use move_gesture::{ConstrainStyle, MoveGesture, MoveValue, StrokeLock}; pub use outside::outside_pieces; diff --git a/crates/behavior/tests/geometry/lock.rs b/crates/behavior/tests/geometry/lock.rs index 805809d7e..4c731d422 100644 --- a/crates/behavior/tests/geometry/lock.rs +++ b/crates/behavior/tests/geometry/lock.rs @@ -1,7 +1,7 @@ //! The ⇧ rules for a drag from a fixed point. -use craft_behavior::geometry::turn_to_45; -use kurbo::Point; +use craft_behavior::geometry::{axis_or_diagonal, turn_to_45}; +use kurbo::{Point, Vec2}; #[test] fn shift_turns_a_point_onto_the_nearest_45_degree_ray_keeping_its_distance() { @@ -13,3 +13,27 @@ fn shift_turns_a_point_onto_the_nearest_45_degree_ray_keeping_its_distance() { assert!(((turned - from).hypot() - 20.0).abs() < 1e-9, "the distance is kept"); assert_eq!(turn_to_45(from, from), from); } + +/// A drag of `(dx, dy)` from `from`, reflected into each octant: the rule must not depend on the direction. +fn octants(dx: f64, dy: f64) -> [Vec2; 8] { + [(dx, dy), (dy, dx), (-dx, dy), (-dy, dx), (dx, -dy), (dy, -dx), (-dx, -dy), (-dy, -dx)].map(|(x, y)| Vec2::new(x, y)) +} + +#[test] +fn shift_snaps_a_line_to_the_axis_within_30_degrees_and_to_the_diagonal_past_it() { + let from = Point::new(10.0, 10.0); + // 26.6° from the axis: onto the axis, keeping the offset along it. + for d in octants(40.0, 20.0) { + let snapped = axis_or_diagonal(from, from + d) - from; + let along = if d.x.abs() > d.y.abs() { Vec2::new(d.x, 0.0) } else { Vec2::new(0.0, d.y) }; + assert_eq!(snapped, along, "{d:?} lies within 30° of an axis"); + } + // 39.8° from the axis: onto the diagonal at the shorter offset, both signs kept. + for d in octants(60.0, 50.0) { + let snapped = axis_or_diagonal(from, from + d) - from; + assert_eq!(snapped, Vec2::new(50f64.copysign(d.x), 50f64.copysign(d.y)), "{d:?} is past 30° from the axes"); + } + // An anchor at a 5:12 slope, with the noise a stored path carries, stays on the axis. + assert_eq!(axis_or_diagonal(from, from + Vec2::new(60.0, -25.0 + 5e-5)), Point::new(70.0, 10.0)); + assert_eq!(axis_or_diagonal(from, from), from, "no offset, no change"); +} diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index 8b3bfca1e..3a8ce7a58 100644 --- a/crates/draw/src/geometry/shape.rs +++ b/crates/draw/src/geometry/shape.rs @@ -40,9 +40,14 @@ pub enum ShapeGeometry { /// The bounds of the ellipse. rect: Rect, }, - /// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Triangle and - /// Polygon). `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon. - /// The Triangle tool is 3 sides. + /// A triangle filling `rect`: the apex at the top centre, the base on the bottom edge (PhotoCraft's Triangle + /// tool and Create Triangle). + Triangle { + /// The triangle's bounds. + rect: Rect, + }, + /// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Polygon). + /// `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon. Polygon { /// The box whose inscribed ellipse holds the polygon. rect: Rect, @@ -93,9 +98,10 @@ impl ShapeGeometry { /// to half the shorter side, as kurbo's `RoundedRect` does); all radii 0 is the plain /// rectangle. /// - `Ellipse`: kurbo's `Ellipse::from_rect`. + /// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`. /// - `Polygon`: the outline of [`RadialPolygon`](Self::RadialPolygon) with the first point /// straight up, its outer points on the ellipse inscribed in `rect` (PhotoCraft's engine: - /// a triangle's base lies a quarter of the height below the centre, not on the bottom + /// a 3-sided polygon's base lies a quarter of the height below the centre, not on the bottom /// edge); a star alternates outer and inner points, the inner ones on the ellipse /// scaled by `star_ratio`. /// - `RadialPolygon`: `sides` outer points on the circle of `radius`, the first at `rotation` @@ -105,7 +111,7 @@ impl ShapeGeometry { /// - `Custom`: the box itself (the app draws the preset). pub fn to_path(&self, tolerance: f64) -> BezPath { // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:73-79 (the kinds: `roundedRect` with four - // equal radii, ellipse, a polygon of 3 sides for the Triangle, `polygon_sides.max(3)`). + // equal radii, ellipse, `triangle` filling its rect, `polygon_sides.max(3)`). // new: PhotoCraft's engine draws the outline; here it is kurbo's `RoundedRect`, `Ellipse` // and a point list, so engines without one share it. let tolerance = tolerance.max(f64::EPSILON); @@ -119,6 +125,11 @@ impl ShapeGeometry { } } Self::Ellipse { rect } => Ellipse::from_rect(rect.abs()).to_path(tolerance), + Self::Triangle { rect } => { + // pc: #13350 (the triangle fills its box, apex on top). + let rect = rect.abs(); + closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]) + } Self::Polygon { rect, sides, star_ratio } => { let rect = rect.abs(); let (c, rx, ry) = (rect.center(), rect.width() / 2.0, rect.height() / 2.0); @@ -145,34 +156,76 @@ impl ShapeGeometry { pub fn bounds(&self) -> Rect { // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:85-96 `shape_bounds` (a line's ends' box). match *self { - Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => rect.abs(), + Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Triangle { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => { + rect.abs() + } Self::RadialPolygon { center, radius, .. } => Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius), Self::Line { from, to, .. } => Rect::from_points(from, to), } } } -/// The box a drag from `start` to `end` draws, in whole pixels, or `None` when a side is under +/// How a box drag turns the press and the pointer into a box ([`box_drag`]). The default draws the dragged box. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct BoxRule { + /// Both sides take the drag's shorter extent, each keeping its direction (⇧). + pub square: bool, + /// The press is the centre: the box is twice the extent (⌥). With `fixed`, the release is the centre. + pub from_centre: bool, + /// A fixed width and height: the box has this size with its top left at the release, whatever the drag. + pub fixed: Option<(f64, f64)>, + /// A width to height ratio: the largest box of this ratio inside the dragged one, from the press. + pub ratio: Option<(f64, f64)>, +} + +/// The box a drag from `start` to `end` draws under `rule`, in whole pixels, or `None` when a side is under /// [`MIN_SIDE`]. /// -/// - `square` (⇧): both sides take the larger absolute extent, each keeping its direction. -/// - `from_centre` (⌥): `start` is the centre; the box is twice the extent. +/// - `fixed` (both sides finite and above 0): that size at the release; `square` and `ratio` do not apply. +/// - `square`: both sides take the drag's shorter extent, each keeping its direction. +/// - `ratio` (both parts finite and above 0): the largest box of that ratio inside the (squared) drag. +/// - `from_centre`: `start` is the centre; the box is twice the extent. /// - The top left and the size round to whole pixels, as PhotoCraft rounds `[x, y, w, h]`. -pub fn box_drag(start: Point, end: Point, square: bool, from_centre: bool) -> Option { - // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:63-72 (⇧: `m = w.abs().max(h.abs())` with the - // signs kept; ⌥: origin `start - (w, h)`, size doubled; `[x0.min(x0 + w).round(), …, - // w.abs().round(), …]`; `rect[2] < 1.0 || rect[3] < 1.0` draws nothing). - let (mut w, mut h) = (end.x - start.x, end.y - start.y); - if square { - let m = w.abs().max(h.abs()); - (w, h) = (m * sign(w), m * sign(h)); - } - let (x0, y0) = if from_centre { (start.x - w, start.y - h) } else { (start.x, start.y) }; - let (w, h) = if from_centre { (w * 2.0, h * 2.0) } else { (w, h) }; +pub fn box_drag(start: Point, end: Point, rule: BoxRule) -> Option { + // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs `drag_box` (⇧: `m = w.abs().min(h.abs())` with the + // signs kept, #13222; ⌥: origin `start - (w, h)`, size doubled; the Rectangle gear's Fixed Size and + // Proportional, #13343), `shape_geometry` (`[x0.min(x0 + w).round(), …, w.abs().round(), …]`; + // `rect[2] < 1.0 || rect[3] < 1.0` draws nothing). + let (x0, y0, w, h) = if let Some((fw, fh)) = rule.fixed.and_then(positive) { + // From Center with Fixed Size is not measured: the size is centred on the release. + if rule.from_centre { (end.x - fw / 2.0, end.y - fh / 2.0, fw, fh) } else { (end.x, end.y, fw, fh) } + } else { + let (mut w, mut h) = (end.x - start.x, end.y - start.y); + if rule.square { + let m = w.abs().min(h.abs()); + (w, h) = (m * sign(w), m * sign(h)); + } + if let Some((rw, rh)) = rule.ratio.and_then(positive) { + let s = (w.abs() / rw).min(h.abs() / rh); + (w, h) = (rw * s * sign(w), rh * s * sign(h)); + } + if rule.from_centre { (start.x - w, start.y - h, w * 2.0, h * 2.0) } else { (start.x, start.y, w, h) } + }; let (x, y, w, h) = (x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round()); (w >= MIN_SIDE && h >= MIN_SIDE).then(|| Rect::new(x, y, x + w, y + h)) } +/// `pair` when both parts are finite and above 0 (a gear field that is not empty). +fn positive(pair: (f64, f64)) -> Option<(f64, f64)> { + (pair.0.is_finite() && pair.1.is_finite() && pair.0 > 0.0 && pair.1 > 0.0).then_some(pair) +} + +/// The tight box of the equilateral triangle, apex up, inscribed in the circle of `square`: what ⇧ draws with the +/// Triangle tool (#13350). With the square centred on the press (⇧⌥), the triangle's centre is the press. +pub fn equilateral_in(square: Rect) -> Rect { + let square = square.abs(); + let r = square.width() / 2.0; + let half_base = r * 3f64.sqrt() / 2.0; + let x = square.center().x - half_base; + Rect::new(x, square.y0, x + 2.0 * half_base, square.y0 + 1.5 * r) +} + /// The end of a line dragged from `from` to `to`, or `None` when it is shorter than /// [`MIN_SIDE`]. pub fn line_drag(from: Point, to: Point) -> Option { diff --git a/crates/draw/src/ui/shape/mod.rs b/crates/draw/src/ui/shape/mod.rs index 6bc13edea..fa12d2631 100644 --- a/crates/draw/src/ui/shape/mod.rs +++ b/crates/draw/src/ui/shape/mod.rs @@ -293,6 +293,6 @@ impl Default for ShapeToolSettings { impl ShapeToolSettings { /// The drag options of `kind` with these values. pub fn drag_options(&self, kind: ShapeKind) -> ShapeDragOptions { - ShapeDragOptions { kind, corner_radius: self.corner_radius, sides: self.sides, star_ratio: self.star_ratio, line_weight: self.line_weight } + ShapeDragOptions::new(kind).corner_radius(self.corner_radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight) } } diff --git a/crates/draw/src/ui/shape_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index 554900769..c10d7fa24 100644 --- a/crates/draw/src/ui/shape_drag/dialog.rs +++ b/crates/draw/src/ui/shape_drag/dialog.rs @@ -9,7 +9,7 @@ use craft_behavior::Mixed; use craft_theme::variant::Tone; use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, Entry, Props as _, Remember as _, Show as _, ShowContainer as _}; -use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft_ui::dialog::{Alert, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::notices::{Notice, NoticeLayout}; use craft_ui::patterns::form_dialogs::{FormDialog, GuideUnits}; @@ -17,7 +17,7 @@ use craft_ui::pickers::UnitSelect; use craft_ui::runtime::env::{Env, Label, UnitKind, Units}; use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft_ui::sections::DialogRole; -use craft_ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; +use craft_ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField, RangeAlert}; use egui::Ui; use kurbo::{Point, Rect}; use serde::{Deserialize, Serialize}; @@ -151,9 +151,10 @@ struct Memory { /// "Radius" label, with the "Link radii" toggle between the columns (`LinkMode::Equal`, on by /// default). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon drag /// keeps ratio 1. Then "From Center". -/// - A width or height outside [`CreateShapeOptions::SIZE`] shows [`CreateShapeWords::bad_size`] under -/// the fields and disables OK; so does a click farther than 300,000 px from the origin -/// ([`CreateShapeWords::bad_position`]). +/// - A width or height typed past [`CreateShapeOptions::SIZE`] keeps the nearest end and raises the range alert, +/// which the app opens from [`take_range_alert`](Self::take_range_alert) (#13358). A size set out of range +/// through automation shows [`CreateShapeWords::bad_size`] under the fields and disables OK; so does a click +/// farther than 300,000 px from the origin ([`CreateShapeWords::bad_position`]). /// - OK answers [`CreatedShape`] at the click (centred on it with From Center, unrounded) and /// remembers width, height, From Center and the star ratio per kind; Cancel answers nothing and /// remembers nothing. @@ -165,6 +166,10 @@ pub struct CreateShapeDialog { units: [UnitKind; 2], /// Whether the dialog is open: bound to the form's open state, so the host's dialog closes with it. open: bool, + /// The title of the range alert; the dialog's own title when `None`. + alert_title: Option