From 73d68241d75df871b2d69e50375613b747a298ce Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:37:51 +0000 Subject: [PATCH 1/8] =?UTF-8?q?merge-c:=201.2:=20Line=20=E2=87=A7=20snaps?= =?UTF-8?q?=20to=20the=20axis=20within=2030=C2=B0=20(keeping=20the=20along?= =?UTF-8?q?-axis=20offset,=20at=20least=201=20px)=20or=20the=20diagonal=20?= =?UTF-8?q?at=20the=20shorter=20offset,=20one=20rule=20in=20craft-behavior?= =?UTF-8?q?=20(axis=5For=5Fdiagonal)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/behavior/src/geometry/lock.rs | 30 +++++- crates/behavior/src/geometry/mod.rs | 2 +- crates/behavior/tests/geometry/lock.rs | 28 +++++- crates/draw/src/ui/shape_drag/tool.rs | 29 ++++-- crates/draw/tests/it/shape_drag.rs | 126 ++++++++++++++++++++++++- 5 files changed, 200 insertions(+), 15 deletions(-) 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..4a268861f 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -18,7 +18,7 @@ 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/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index 4ee333c9a..0a71c6cc0 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -2,18 +2,18 @@ use std::sync::Arc; -use craft_behavior::geometry::turn_to_45; +use craft_behavior::geometry::axis_or_diagonal; use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed}; use craft_keymap::{Key, Mods}; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::canvas_controls::path_runs; use craft_ui::primitives::{Draw, PaintShape, StrokeWidth}; use craft_ui::runtime::env::Label; -use kurbo::Point; +use kurbo::{Point, Vec2}; use super::words::ShapeDragWords; use super::{ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind}; -use crate::geometry::shape::{RadialFrame, SIDES, ShapeGeometry, box_drag, line_drag}; +use crate::geometry::shape::{MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, line_drag}; /// The flattening tolerance of the outline being drawn, in screen points. const OUTLINE_TOLERANCE: f32 = 0.25; @@ -28,7 +28,8 @@ const OUTLINE_TOLERANCE: f32 = 0.25; /// the shape it would draw; release commits it. /// - A side under 1 px makes nothing: the gesture is cancelled as `Dismissed`. /// - A press and release inside the slop is a [`Click`](ShapeDragEvent::Click) at the press. -/// - ⇧ makes a square or circle (a Line: 45° steps keeping its length); ⌥ draws from the centre. +/// - ⇧ makes a square or circle from the drag's shorter side (a Line: onto the axis within 30° of it, keeping the +/// offset along it, else onto the diagonal at the shorter offset); ⌥ draws from the centre. /// Both may go down or up mid-drag; the shape follows the modifiers held now. /// - Space held moves the shape being drawn without resizing it: the press point moves with the /// pointer while Space is down, and the box snaps as a whole. @@ -144,7 +145,7 @@ impl ShapeDragTool { /// when a side is under 1 px: [`box_drag`] for the box kinds (Rectangle with four equal radii when /// `corner_radius` > 0, Rounded Rectangle always with them, Triangle a 3-sided polygon, Polygon and /// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧), - /// [`line_drag`] for a Line (weight at least 1, ⇧ turning the end to 45° steps), and + /// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and /// [`RadialFrame::drag`] in the radial frame. fn shape_of(&self, drag: &Drag, mods: Mods) -> Option { // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:50-82 `shape_geometry`. @@ -152,8 +153,9 @@ impl ShapeDragTool { let o = &drag.options; let radii = [o.corner_radius.max(0.0); 4]; if o.kind == ShapeKind::Line { - let end = if mods.shift { turn_to_45(drag.start, drag.at) } else { drag.at }; - let to = line_drag(drag.start, end)?; + // The drag's own length decides whether a line is drawn, before ⇧ shortens a diagonal. + line_drag(drag.start, drag.at)?; + let to = if mods.shift { line_shift(drag.start, drag.at) } else { drag.at }; return Some(ShapeGeometry::Line { from: drag.start, to, weight: o.line_weight.max(1.0) }); } if self.radial(o.kind) { @@ -239,6 +241,19 @@ impl ShapeDragTool { } } +/// The end of a ⇧ Line drag from `from` to `to`: [`axis_or_diagonal`], with a line on an axis at least +/// [`MIN_SIDE`] long (a drag of a pixel can keep less than that along its axis). +fn line_shift(from: Point, to: Point) -> Point { + // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs `shape_geometry` (#13243: `dx.abs().max(1.0).copysign(dx)` on + // an axis). + let d = axis_or_diagonal(from, to) - from; + if d.x != 0.0 && d.y != 0.0 { + return from + d; + } + let at_least = |v: f64| if v == 0.0 { 0.0 } else { v.abs().max(MIN_SIDE).copysign(v) }; + from + Vec2::new(at_least(d.x), at_least(d.y)) +} + impl CanvasTool for ShapeDragTool { fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { // pc: crates/ui-egui/src/canvas/gesture.rs:84 (a shape drag that stays inside diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index b1551888d..69b97d005 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -1,11 +1,14 @@ //! The Shape tools and the Create Shape dialog. The view maps one document unit to one screen point. -use craft_behavior::CanvasView; -use craft_behavior::kurbo::{Point, Rect}; +use craft_behavior::kurbo::{Point, Rect, Vec2}; +use craft_behavior::{CanvasView, EditEvent}; use craft_draw::geometry::shape::ShapeGeometry; -use craft_draw::ui::shape_drag::{CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragOptions, ShapeDragTool, ShapeKind}; +use craft_draw::ui::shape_drag::{ + CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragEvent, ShapeDragOptions, ShapeDragTool, ShapeKind, +}; use craft_ui::dialog::{DialogHost, DialogId, DialogResult}; use craft_ui::testing::{ToolFixture, trial}; +use egui::{Event, Modifiers, PointerButton, Pos2}; use serde_json::{Value, json}; /// The view of a canvas filling `room`, with its middle at the document's middle. @@ -19,6 +22,123 @@ fn tool(kind: ShapeKind) -> ShapeDragTool { tool } +/// A Shape tool on a canvas, with the events it reported so far. +struct Shapes { + fixture: ToolFixture, + log: Vec, +} + +impl Shapes { + fn new(options: ShapeDragOptions) -> Self { + let mut tool = ShapeDragTool::new(); + tool.options(options); + Shapes { fixture: ToolFixture::with_view("Shape", tool, room_view, |_, _| {}), log: Vec::new() } + } + + fn sync(&mut self) { + let events = self.fixture.tool_mut().take_events(); + self.log.extend(events); + } + + /// The screen point of the document point `p`. + fn at(&self, p: Point) -> Pos2 { + room_view(self.fixture.canvas().rect).to_screen(p) + } + + fn button(&mut self, p: Point, pressed: bool, modifiers: Modifiers) { + let pos = self.at(p); + self.fixture.fixture().frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }]); + self.sync(); + } + + fn press(&mut self, p: Point, modifiers: Modifiers) { + self.fixture.fixture().hold(modifiers); + let pos = self.at(p); + self.fixture.fixture().frame(vec![Event::PointerMoved(pos)]); + self.button(p, true, modifiers); + } + + fn move_to(&mut self, p: Point, modifiers: Modifiers) { + self.fixture.fixture().hold(modifiers); + let pos = self.at(p); + self.fixture.fixture().frame(vec![Event::PointerMoved(pos)]); + self.sync(); + } + + fn release(&mut self, p: Point, modifiers: Modifiers) { + self.button(p, false, modifiers); + self.fixture.fixture().hold(Modifiers::NONE); + self.fixture.fixture().frame(Vec::new()); + self.sync(); + } + + /// Space goes down or up. + fn space(&mut self, down: bool) { + let key = Event::Key { key: egui::Key::Space, physical_key: None, pressed: down, repeat: false, modifiers: Modifiers::NONE }; + self.fixture.fixture().frame(vec![key]); + self.sync(); + } + + /// Press at `from`, move past the press slop, then to `to`, and release there, all with `modifiers`. + fn drag(&mut self, from: Point, to: Point, modifiers: Modifiers) { + self.press(from, modifiers); + self.move_to(from + Vec2::new(40.0, 30.0), modifiers); + self.move_to(to, modifiers); + self.release(to, modifiers); + } + + /// The shape the last drag committed. + fn committed(&self) -> Option { + self.log.iter().rev().find_map(|event| match event { + ShapeDragEvent::Draw(EditEvent::Commit { after, .. }) => Some(after.clone()), + _ => None, + }) + } + + /// The shape of the last `Update`. + fn proposed(&self) -> Option { + self.log.iter().rev().find_map(|event| match event { + ShapeDragEvent::Draw(EditEvent::Update { value, .. }) => Some(value.clone()), + _ => None, + }) + } + + /// The box the last drag committed. + fn committed_box(&self) -> Option { + self.committed().map(|shape| shape.bounds()) + } + + /// Whether the last gesture ended as a click. + fn clicked(&self) -> bool { + matches!(self.log.last(), Some(ShapeDragEvent::Click { .. })) + } + + fn forget(&mut self) { + self.log.clear(); + } +} + +const PRESS: Point = Point::new(100.0, 100.0); + +/// A ⇧ Line drag snaps onto the axis within 30° of it, keeping the offset along it and at least a pixel long, and +/// onto the diagonal at the shorter offset past that; the drag's last proposal is the line it commits. +#[trial] +fn a_shift_line_snaps_to_the_axis_or_the_diagonal_and_commits_what_it_proposed() { + let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Line)); + let line_end = |shape: Option| match shape { + Some(ShapeGeometry::Line { from, to, .. }) => Some(to - from), + _ => None, + }; + shapes.drag(PRESS, PRESS + Vec2::new(0.95, 0.4), Modifiers::SHIFT); + assert_eq!(line_end(shapes.committed()), Some(Vec2::new(1.0, 0.0)), "a short drag still draws a 1 px horizontal line"); + assert_eq!(shapes.proposed(), shapes.committed(), "the last proposal is the committed line"); + + shapes.forget(); + shapes.drag(PRESS, PRESS + Vec2::new(-60.0, 50.0), Modifiers::SHIFT); + assert_eq!(line_end(shapes.committed()), Some(Vec2::new(-50.0, 50.0)), "past 30° the line takes the diagonal"); + assert_eq!(shapes.proposed(), shapes.committed()); +} + #[trial] fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); From 6540f19ff284a39c7be9ea6713a19e4bb9e91263 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:38:04 +0000 Subject: [PATCH 2/8] =?UTF-8?q?merge-c:=201.1:=20=E2=87=A7=20squares=20a?= =?UTF-8?q?=20box=20drag=20from=20the=20drag's=20shorter=20side,=20?= =?UTF-8?q?=E2=87=A7=E2=8C=A5=20the=20same=20from=20the=20centre=20(#13222?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/draw/src/geometry/shape.rs | 8 ++++---- crates/draw/tests/it/shape_drag.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index 8b3bfca1e..b3c522b13 100644 --- a/crates/draw/src/geometry/shape.rs +++ b/crates/draw/src/geometry/shape.rs @@ -155,16 +155,16 @@ impl ShapeGeometry { /// The box a drag from `start` to `end` draws, in whole pixels, or `None` when a side is under /// [`MIN_SIDE`]. /// -/// - `square` (⇧): both sides take the larger absolute extent, each keeping its direction. +/// - `square` (⇧): both sides take the drag's shorter extent, each keeping its direction. /// - `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(), …, + // 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), `shape_geometry` (`[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()); + let m = w.abs().min(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) }; diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 69b97d005..0e429a3ad 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -139,6 +139,22 @@ fn a_shift_line_snaps_to_the_axis_or_the_diagonal_and_commits_what_it_proposed() assert_eq!(shapes.proposed(), shapes.committed()); } +/// ⇧ squares the box from the drag's shorter side, ⇧⌥ from the press as the centre; an Ellipse becomes a circle. +#[trial] +fn shift_squares_the_box_from_the_shorter_side() { + let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Rectangle)); + shapes.drag(PRESS, PRESS + Vec2::new(60.0, 20.0), Modifiers::SHIFT); + assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 120.0, 120.0)), "the square takes the shorter side at the press"); + + shapes.forget(); + shapes.drag(PRESS, PRESS + Vec2::new(-60.0, 20.0), Modifiers::SHIFT | Modifiers::ALT); + assert_eq!(shapes.committed_box(), Some(Rect::new(80.0, 80.0, 120.0, 120.0)), "⇧⌥ centres the square on the press"); + + let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Ellipse)); + shapes.drag(PRESS, PRESS + Vec2::new(20.0, 60.0), Modifiers::SHIFT); + assert_eq!(shapes.committed(), Some(ShapeGeometry::Ellipse { rect: Rect::new(100.0, 100.0, 120.0, 120.0) }), "a circle of the shorter side"); +} + #[trial] fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); From c3f113a5c5b654d9af6806f146617e450a60f8d7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:39:18 +0000 Subject: [PATCH 3/8] =?UTF-8?q?merge-c:=201.4a:=20Rectangle=20gear=20const?= =?UTF-8?q?raints=20in=20the=20drag=20(Square,=20Fixed=20Size,=20Proportio?= =?UTF-8?q?nal,=20From=20Center;=20=E2=87=A7=20and=20=E2=8C=A5=20turn=20Sq?= =?UTF-8?q?uare=20and=20From=20Center=20off)=20through=20one=20BoxRule=20f?= =?UTF-8?q?or=20box=5Fdrag=20(#13343)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/draw/src/geometry/shape.rs | 56 +++++++++++++++++----- crates/draw/src/ui/shape/mod.rs | 2 +- crates/draw/src/ui/shape_drag/mod.rs | 69 ++++++++++++++++++++++++++- crates/draw/src/ui/shape_drag/tool.rs | 20 ++++++-- crates/draw/tests/it/shape_drag.rs | 41 +++++++++++++++- 5 files changed, 167 insertions(+), 21 deletions(-) diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index b3c522b13..112fc4d2d 100644 --- a/crates/draw/src/geometry/shape.rs +++ b/crates/draw/src/geometry/shape.rs @@ -152,27 +152,57 @@ impl ShapeGeometry { } } -/// 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 drag's shorter 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 { +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), `shape_geometry` (`[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().min(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) }; + // 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 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/mod.rs b/crates/draw/src/ui/shape_drag/mod.rs index 24ae362e8..e62f7e5f6 100644 --- a/crates/draw/src/ui/shape_drag/mod.rs +++ b/crates/draw/src/ui/shape_drag/mod.rs @@ -11,9 +11,12 @@ mod dialog; mod tool; mod words; +use std::ops::RangeInclusive; + use craft_behavior::EditEvent; use craft_keymap::Mods; use kurbo::Point; +use serde::{Deserialize, Serialize}; use crate::geometry::shape::ShapeGeometry; @@ -57,6 +60,52 @@ pub enum ShapeFrame { Radial, } +/// What the Rectangle tool's gear keeps a box drag to ([`BoxConstraints::constraint`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum BoxConstraint { + /// The dragged box. + #[default] + Unconstrained, + /// A square; ⇧ draws the dragged box instead. + Square, + /// The gear's width and height, with the top left at the release. + FixedSize, + /// The largest box of the gear's width to height ratio inside the drag, from the press. + Proportional, +} + +/// The Rectangle tool's gear: a constraint, its sizes, and From Center. A Fixed Size or Proportional pair with an +/// empty field (`None`) or a 0 draws as Unconstrained. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +#[non_exhaustive] +pub struct BoxConstraints { + /// The constraint chosen. + pub constraint: BoxConstraint, + /// Fixed Size's width and height in pixels, in [`FIXED`](Self::FIXED); empty to start. + pub fixed: (Option, Option), + /// Proportional's width and height, in [`RATIO`](Self::RATIO); 1 : 1 to start. + pub ratio: (Option, Option), + /// The press is the box's centre; ⌥ draws from the corner instead. + pub from_center: bool, +} + +impl BoxConstraints { + /// The range of a Fixed Size field, in whole pixels. + pub const FIXED: RangeInclusive = 0.0..=300_000.0; + /// The range of a Proportional field. + pub const RATIO: RangeInclusive = 0.0..=99_999.0; +} + +impl Default for BoxConstraints { + /// Unconstrained, Fixed Size empty, Proportional 1 : 1, From Center off. + fn default() -> Self { + BoxConstraints { constraint: BoxConstraint::Unconstrained, fixed: (None, None), ratio: (Some(1.0), Some(1.0)), from_center: false } + } +} + /// The tool options a drag reads each pass: the kind from the selected tool, the rest from the /// options bar (PhotoCraft's `ToolOptions`). [`ShapeToolSettings::drag_options`](super::shape::ShapeToolSettings::drag_options) /// builds it from the stored settings. @@ -73,6 +122,8 @@ pub struct ShapeDragOptions { pub star_ratio: f64, /// The Line's weight, at least 1. pub line_weight: f64, + /// The gear's constraints for a box drag; ⇧ and ⌥ turn its Square and From Center off. + pub constraints: BoxConstraints, } impl ShapeDragOptions { @@ -108,12 +159,26 @@ impl ShapeDragOptions { self.line_weight = weight; self } + + /// The gear's constraints for a box drag (Photoshop shows the gear for the Rectangle only). + #[must_use] + pub fn constraints(mut self, constraints: BoxConstraints) -> Self { + self.constraints = constraints; + self + } } impl Default for ShapeDragOptions { - /// Rectangle, square corners, 5 sides, a plain polygon, weight 3 (PhotoCraft's defaults). + /// Rectangle, square corners, 5 sides, a plain polygon, weight 3, unconstrained (PhotoCraft's defaults). fn default() -> Self { - ShapeDragOptions { kind: ShapeKind::Rectangle, corner_radius: 0.0, sides: 5, star_ratio: 1.0, line_weight: 3.0 } + ShapeDragOptions { + kind: ShapeKind::Rectangle, + corner_radius: 0.0, + sides: 5, + star_ratio: 1.0, + line_weight: 3.0, + constraints: BoxConstraints::default(), + } } } diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index 0a71c6cc0..d676bb04d 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -12,8 +12,8 @@ use craft_ui::runtime::env::Label; use kurbo::{Point, Vec2}; use super::words::ShapeDragWords; -use super::{ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind}; -use crate::geometry::shape::{MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, line_drag}; +use super::{BoxConstraint, ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind}; +use crate::geometry::shape::{BoxRule, MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, line_drag}; /// The flattening tolerance of the outline being drawn, in screen points. const OUTLINE_TOLERANCE: f32 = 0.25; @@ -31,6 +31,9 @@ const OUTLINE_TOLERANCE: f32 = 0.25; /// - ⇧ makes a square or circle from the drag's shorter side (a Line: onto the axis within 30° of it, keeping the /// offset along it, else onto the diagonal at the shorter offset); ⌥ draws from the centre. /// Both may go down or up mid-drag; the shape follows the modifiers held now. +/// - The options' [`BoxConstraints`](super::BoxConstraints) (the Rectangle tool's gear) keep a box drag square, at a +/// fixed size at the release, or at a ratio, and From Center draws from the press as the centre; with Square or +/// From Center on, ⇧ or ⌥ turns it off. /// - Space held moves the shape being drawn without resizing it: the press point moves with the /// pointer while Space is down, and the box snaps as a whole. /// - Esc cancels (the host calls [`cancel`](CanvasTool::cancel)); so does a tool switch: `Cancel` @@ -142,7 +145,8 @@ impl ShapeDragTool { } /// The shape a drag from `start` to `at` with `mods` draws under the options and rules, or `None` - /// when a side is under 1 px: [`box_drag`] for the box kinds (Rectangle with four equal radii when + /// when a side is under 1 px: [`box_drag`] for the box kinds under the options' constraints, ⇧ + /// toggling Square and ⌥ From Center (Rectangle with four equal radii when /// `corner_radius` > 0, Rounded Rectangle always with them, Triangle a 3-sided polygon, Polygon and /// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧), /// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and @@ -173,7 +177,15 @@ impl ShapeDragTool { }; return Some(frame.geometry(drag.sides, star_ratio)); } - let rect = box_drag(drag.start, drag.at, mods.shift, mods.alt)?; + let c = &o.constraints; + let pair = |(w, h): (Option, Option)| w.zip(h); + let rule = BoxRule { + square: mods.shift != (c.constraint == BoxConstraint::Square), + from_centre: mods.alt != c.from_center, + fixed: (c.constraint == BoxConstraint::FixedSize).then(|| pair(c.fixed)).flatten(), + ratio: (c.constraint == BoxConstraint::Proportional).then(|| pair(c.ratio)).flatten(), + }; + let rect = box_drag(drag.start, drag.at, rule)?; Some(match o.kind { ShapeKind::Rectangle if o.corner_radius > 0.0 => ShapeGeometry::Rect { rect, radii }, ShapeKind::Rectangle => ShapeGeometry::Rect { rect, radii: [0.0; 4] }, diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 0e429a3ad..e90906931 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -4,7 +4,7 @@ use craft_behavior::kurbo::{Point, Rect, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::geometry::shape::ShapeGeometry; use craft_draw::ui::shape_drag::{ - CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragEvent, ShapeDragOptions, ShapeDragTool, ShapeKind, + BoxConstraint, BoxConstraints, CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragEvent, ShapeDragOptions, ShapeDragTool, ShapeKind, }; use craft_ui::dialog::{DialogHost, DialogId, DialogResult}; use craft_ui::testing::{ToolFixture, trial}; @@ -155,6 +155,45 @@ fn shift_squares_the_box_from_the_shorter_side() { assert_eq!(shapes.committed(), Some(ShapeGeometry::Ellipse { rect: Rect::new(100.0, 100.0, 120.0, 120.0) }), "a circle of the shorter side"); } +/// A Rectangle drag under the gear `constraint` with `change` applied to the gear's values. +fn gear(constraint: BoxConstraint, change: impl FnOnce(&mut BoxConstraints)) -> Shapes { + let mut constraints = BoxConstraints::default(); + constraints.constraint = constraint; + change(&mut constraints); + Shapes::new(ShapeDragOptions::new(ShapeKind::Rectangle).constraints(constraints)) +} + +/// The gear's Square and From Center hold without ⇧ or ⌥, which turn them off; Fixed Size puts its size at the +/// release; Proportional draws the largest box of its ratio inside the drag; an empty Fixed Size field draws the +/// dragged box. +#[trial] +fn the_rectangle_gear_constrains_the_drag_and_shift_and_alt_turn_it_off() { + let to = PRESS + Vec2::new(60.0, 20.0); + let mut shapes = gear(BoxConstraint::Square, |_| {}); + shapes.drag(PRESS, to, Modifiers::NONE); + assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 120.0, 120.0)), "Square holds without ⇧"); + shapes.drag(PRESS, to, Modifiers::SHIFT); + assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 120.0)), "⇧ turns Square off"); + + let mut shapes = gear(BoxConstraint::Unconstrained, |c| c.from_center = true); + shapes.drag(PRESS, to, Modifiers::NONE); + assert_eq!(shapes.committed_box(), Some(Rect::new(40.0, 80.0, 160.0, 120.0)), "From Center draws about the press"); + shapes.drag(PRESS, to, Modifiers::ALT); + assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 120.0)), "⌥ turns From Center off"); + + let mut shapes = gear(BoxConstraint::FixedSize, |c| c.fixed = (Some(30.0), Some(10.0))); + shapes.drag(PRESS, to, Modifiers::NONE); + assert_eq!(shapes.committed_box(), Some(Rect::new(160.0, 120.0, 190.0, 130.0)), "Fixed Size puts its top left at the release"); + + let mut shapes = gear(BoxConstraint::FixedSize, |c| c.fixed = (Some(30.0), None)); + shapes.drag(PRESS, to, Modifiers::NONE); + assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 120.0)), "an empty field draws the dragged box"); + + let mut shapes = gear(BoxConstraint::Proportional, |c| c.ratio = (Some(2.0), Some(1.0))); + shapes.drag(PRESS, PRESS + Vec2::new(60.0, 50.0), Modifiers::NONE); + assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 130.0)), "the largest 2 : 1 box inside the drag"); +} + #[trial] fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); From f8054eedb03cb6428644eca283184bf5e687e9db Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:40:03 +0000 Subject: [PATCH 4/8] =?UTF-8?q?merge-c:=201.3:=20Triangle=20fills=20its=20?= =?UTF-8?q?box=20(apex=20top=20centre),=20=E2=87=A7=20the=20equilateral=20?= =?UTF-8?q?triangle=20in=20the=20square's=20circle,=20=E2=87=A7=E2=8C=A5?= =?UTF-8?q?=20centred=20on=20the=20press;=20Create=20Triangle=20answers=20?= =?UTF-8?q?the=20same=20kind=20(#13350,=20#13351)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/draw/src/geometry/shape.rs | 37 +++++++++++++++++++++---- crates/draw/src/ui/shape_drag/dialog.rs | 2 +- crates/draw/src/ui/shape_drag/tool.rs | 7 +++-- crates/draw/tests/it/shape_drag.rs | 31 +++++++++++++++++++++ 4 files changed, 67 insertions(+), 10 deletions(-) diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index 112fc4d2d..fff27a2bd 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,7 +156,11 @@ 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), } @@ -203,6 +218,16 @@ 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_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index 554900769..2237176ed 100644 --- a/crates/draw/src/ui/shape_drag/dialog.rs +++ b/crates/draw/src/ui/shape_drag/dialog.rs @@ -209,7 +209,7 @@ fn answer(o: &CreateShapeOptions, words: &CreateShapeWords, units: &Units) -> Re ShapeGeometry::Rect { rect, radii } } ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect }, - ShapeKind::Triangle => ShapeGeometry::Polygon { rect, sides: 3, star_ratio: 1.0 }, + ShapeKind::Triangle => ShapeGeometry::Triangle { rect }, ShapeKind::Polygon | ShapeKind::Star => { let ratio = if o.star_ratio.is_finite() { o.star_ratio.clamp(0.01, 1.0) } else { 1.0 }; ShapeGeometry::Polygon { rect, sides, star_ratio: ratio } diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index d676bb04d..13ae40ccf 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -13,7 +13,7 @@ use kurbo::{Point, Vec2}; use super::words::ShapeDragWords; use super::{BoxConstraint, ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind}; -use crate::geometry::shape::{BoxRule, MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, line_drag}; +use crate::geometry::shape::{BoxRule, MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, equilateral_in, line_drag}; /// The flattening tolerance of the outline being drawn, in screen points. const OUTLINE_TOLERANCE: f32 = 0.25; @@ -147,7 +147,8 @@ impl ShapeDragTool { /// The shape a drag from `start` to `at` with `mods` draws under the options and rules, or `None` /// when a side is under 1 px: [`box_drag`] for the box kinds under the options' constraints, ⇧ /// toggling Square and ⌥ From Center (Rectangle with four equal radii when - /// `corner_radius` > 0, Rounded Rectangle always with them, Triangle a 3-sided polygon, Polygon and + /// `corner_radius` > 0, Rounded Rectangle always with them, Triangle filling the box (⇧: the equilateral + /// triangle in the square's circle), Polygon and /// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧), /// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and /// [`RadialFrame::drag`] in the radial frame. @@ -191,7 +192,7 @@ impl ShapeDragTool { ShapeKind::Rectangle => ShapeGeometry::Rect { rect, radii: [0.0; 4] }, ShapeKind::RoundedRectangle => ShapeGeometry::Rect { rect, radii }, ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect }, - ShapeKind::Triangle => ShapeGeometry::Polygon { rect, sides: 3, star_ratio: 1.0 }, + ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect } }, ShapeKind::Polygon => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: 1.0 }, ShapeKind::Star => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: o.star_ratio }, ShapeKind::Custom | ShapeKind::Line => ShapeGeometry::Custom { rect, keep_proportions: mods.shift }, diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index e90906931..8eedbf1b7 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -194,6 +194,37 @@ fn the_rectangle_gear_constrains_the_drag_and_shift_and_alt_turn_it_off() { assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 130.0)), "the largest 2 : 1 box inside the drag"); } +/// The corners of the triangle `shape` draws, from the apex clockwise. +fn corners(shape: Option) -> Vec { + let Some(shape @ ShapeGeometry::Triangle { .. }) = shape else { return Vec::new() }; + shape.to_path(0.1).elements().iter().filter_map(|el| el.end_point()).collect() +} + +/// A Triangle drag fills its box, apex on top; ⇧ draws the equilateral triangle in the circle of the shorter +/// side's square; ⇧⌥ centres it on the press. +#[trial] +fn a_triangle_fills_its_box_and_shift_makes_it_equilateral() { + let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Triangle)); + let to = PRESS + Vec2::new(60.0, 40.0); + shapes.drag(PRESS, to, Modifiers::NONE); + let plain = corners(shapes.committed()); + assert_eq!(plain.first(), Some(&Point::new(130.0, 100.0)), "the apex is the box's top centre: {plain:?}"); + assert!(plain.len() >= 3 && plain[1..].iter().all(|p| p.y == 140.0), "the base lies on the bottom edge: {plain:?}"); + + shapes.drag(PRESS, to, Modifiers::SHIFT); + let equal = corners(shapes.committed()); + assert!(equal.len() >= 3, "a triangle: {equal:?}"); + let sides = [(equal[0] - equal[1]).hypot(), (equal[1] - equal[2]).hypot(), (equal[2] - equal[0]).hypot()]; + assert!(sides.iter().all(|side| (side - 20.0 * 3f64.sqrt()).abs() < 1e-9), "three equal sides in the 40 px square's circle: {sides:?}"); + assert_eq!(equal[0], Point::new(120.0, 100.0), "the apex is the top of the circle"); + + shapes.drag(PRESS, to, Modifiers::SHIFT | Modifiers::ALT); + let centred = corners(shapes.committed()); + assert!(centred.len() >= 3, "a triangle: {centred:?}"); + let centre = (centred[0].to_vec2() + centred[1].to_vec2() + centred[2].to_vec2()) / 3.0; + assert!((centre.to_point() - PRESS).hypot() < 1e-9, "⇧⌥ puts the centre on the press, got {centre:?}"); +} + #[trial] fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); From 6b1ab75129f09fd7aac38e83962539e80e4457a8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:40:39 +0000 Subject: [PATCH 5/8] merge-c: 1.5: a Rectangle in Shape mode ends a click within 1 screen point (ShapeDragOptions::mode) (#13340) --- crates/draw/src/ui/shape_drag/mod.rs | 15 ++++++++++++++- crates/draw/src/ui/shape_drag/tool.rs | 11 +++++++++-- crates/draw/tests/it/shape_drag.rs | 20 ++++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/draw/src/ui/shape_drag/mod.rs b/crates/draw/src/ui/shape_drag/mod.rs index e62f7e5f6..9d24fe969 100644 --- a/crates/draw/src/ui/shape_drag/mod.rs +++ b/crates/draw/src/ui/shape_drag/mod.rs @@ -19,6 +19,7 @@ use kurbo::Point; use serde::{Deserialize, Serialize}; use crate::geometry::shape::ShapeGeometry; +use crate::ui::shape::VectorMode; pub use dialog::{CreateShapeDialog, CreateShapeOptions, CreatedShape}; pub use tool::ShapeDragTool; @@ -124,6 +125,9 @@ pub struct ShapeDragOptions { pub line_weight: f64, /// The gear's constraints for a box drag; ⇧ and ⌥ turn its Square and From Center off. pub constraints: BoxConstraints, + /// What the drag makes: a Rectangle in Shape mode ends a click within 1 screen point, every other drag within + /// the press slop. + pub mode: VectorMode, } impl ShapeDragOptions { @@ -166,10 +170,18 @@ impl ShapeDragOptions { self.constraints = constraints; self } + + /// What the drag makes (the options bar's mode). + #[must_use] + pub fn mode(mut self, mode: VectorMode) -> Self { + self.mode = mode; + self + } } impl Default for ShapeDragOptions { - /// Rectangle, square corners, 5 sides, a plain polygon, weight 3, unconstrained (PhotoCraft's defaults). + /// Rectangle, square corners, 5 sides, a plain polygon, weight 3, unconstrained, Shape mode (PhotoCraft's + /// defaults). fn default() -> Self { ShapeDragOptions { kind: ShapeKind::Rectangle, @@ -178,6 +190,7 @@ impl Default for ShapeDragOptions { star_ratio: 1.0, line_weight: 3.0, constraints: BoxConstraints::default(), + mode: VectorMode::Shape, } } } diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index 13ae40ccf..e65af57a1 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -12,6 +12,7 @@ use craft_ui::runtime::env::Label; use kurbo::{Point, Vec2}; use super::words::ShapeDragWords; +use crate::ui::shape::VectorMode; use super::{BoxConstraint, ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind}; use crate::geometry::shape::{BoxRule, MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, equilateral_in, line_drag}; @@ -27,7 +28,8 @@ const OUTLINE_TOLERANCE: f32 = 0.25; /// - The press starts at the snapped point; past the press slop the drag begins and each pass reports /// the shape it would draw; release commits it. /// - A side under 1 px makes nothing: the gesture is cancelled as `Dismissed`. -/// - A press and release inside the slop is a [`Click`](ShapeDragEvent::Click) at the press. +/// - A press and release inside the slop is a [`Click`](ShapeDragEvent::Click) at the press; a Rectangle in +/// Shape mode has a slop of 1 screen point, so a 2 × 1 point drag draws. /// - ⇧ makes a square or circle from the drag's shorter side (a Line: onto the axis within 30° of it, keeping the /// offset along it, else onto the diagonal at the shorter offset); ⌥ draws from the centre. /// Both may go down or up mid-drag; the shape follows the modifiers held now. @@ -82,6 +84,8 @@ struct Drag { options: ShapeDragOptions, /// The press on screen, for the press slop. press: egui::Pos2, + /// How far the pointer may move from the press, in screen points, before the drag begins. + click_slop: f32, /// The press as the pointer made it, snapped. origin: Point, /// The press, moved by Space. @@ -219,7 +223,7 @@ impl ShapeDragTool { drag.space = space_held; drag.at = at; if !drag.began { - if pos.distance(drag.press) < cx.slop { + if pos.distance(drag.press) < drag.click_slop { self.drag = Some(drag); return; } @@ -274,12 +278,15 @@ impl CanvasTool for ShapeDragTool { let Some(space) = cx.space() else { return ToolAction::Ignored }; let options = self.options; let origin = cx.snap(space.view.to_doc(pointer.pos)); + // pc: crates/ui-egui/src/dialogs/shape_dialog.rs `is_tool_click` (#13340). + let click_slop = if options.kind == ShapeKind::Rectangle && options.mode == VectorMode::Shape { 1.0 } else { cx.slop }; self.next = self.next.next(); self.drag = Some(Drag { id: self.next, label: Arc::from(cx.words::().draw.as_str()), options, press: pointer.pos, + click_slop, origin, start: origin, at: origin, diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 8eedbf1b7..ed9b69da1 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -3,6 +3,7 @@ use craft_behavior::kurbo::{Point, Rect, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::geometry::shape::ShapeGeometry; +use craft_draw::ui::shape::VectorMode; use craft_draw::ui::shape_drag::{ BoxConstraint, BoxConstraints, CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragEvent, ShapeDragOptions, ShapeDragTool, ShapeKind, }; @@ -225,6 +226,25 @@ fn a_triangle_fills_its_box_and_shift_makes_it_equilateral() { assert!((centre.to_point() - PRESS).hypot() < 1e-9, "⇧⌥ puts the centre on the press, got {centre:?}"); } +/// A press moved 2 × 1 points and released: a Rectangle in Shape mode draws it, in Path mode it is a click, and an +/// Ellipse in Shape mode keeps the press slop. +#[trial] +fn a_shape_mode_rectangle_ends_a_click_within_one_point() { + let nudge = |kind: ShapeKind, mode: VectorMode| { + let mut shapes = Shapes::new(ShapeDragOptions::new(kind).mode(mode)); + let to = PRESS + Vec2::new(2.0, 1.0); + shapes.press(PRESS, Modifiers::NONE); + shapes.move_to(to, Modifiers::NONE); + shapes.release(to, Modifiers::NONE); + shapes + }; + let drawn = nudge(ShapeKind::Rectangle, VectorMode::Shape); + assert!(!drawn.clicked(), "the Rectangle in Shape mode drew: {:?}", drawn.log); + assert_eq!(drawn.committed_box(), Some(Rect::new(100.0, 100.0, 102.0, 101.0))); + assert!(nudge(ShapeKind::Rectangle, VectorMode::Path).clicked(), "in Path mode the press slop holds"); + assert!(nudge(ShapeKind::Ellipse, VectorMode::Shape).clicked(), "other kinds keep the press slop"); +} + #[trial] fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); From 3c3264f6f0c6d63d12bfb52fd10ba40b37c8058a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:40:57 +0000 Subject: [PATCH 6/8] merge-c: 5.2: Space moves the shape being drawn by the full pointer motion, the first move after Space included (#13867) --- crates/draw/src/ui/shape_drag/tool.rs | 12 ++++-------- crates/draw/tests/it/shape_drag.rs | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index e65af57a1..b390d8cdf 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -36,8 +36,8 @@ const OUTLINE_TOLERANCE: f32 = 0.25; /// - The options' [`BoxConstraints`](super::BoxConstraints) (the Rectangle tool's gear) keep a box drag square, at a /// fixed size at the release, or at a ratio, and From Center draws from the press as the centre; with Square or /// From Center on, ⇧ or ⌥ turns it off. -/// - Space held moves the shape being drawn without resizing it: the press point moves with the -/// pointer while Space is down, and the box snaps as a whole. +/// - Space held moves the shape being drawn without resizing it: every move while Space is down, the first one +/// included, moves the press point by the pointer's motion, and the box snaps as a whole. /// - Esc cancels (the host calls [`cancel`](CanvasTool::cancel)); so does a tool switch: `Cancel` /// goes out when a drag had begun. /// @@ -94,8 +94,6 @@ struct Drag { at: Point, /// Past the press slop: `Begin` went out. began: bool, - /// Whether Space was held in the last call. - space: bool, /// A radial star's inner radius held by Ctrl/Cmd. inner: Option, /// Sides or points as changed by ↑ and ↓ during this drag. @@ -216,11 +214,10 @@ impl ShapeDragTool { self.drag = Some(drag); return; } - let space_held = cx.held(Key::Space); - if space_held && drag.space { + // pc: #13867 (the Frame tool: every move with Space held, the first included, moves the box by the motion). + if cx.held(Key::Space) { drag.start += at - drag.at; } - drag.space = space_held; drag.at = at; if !drag.began { if pos.distance(drag.press) < drag.click_slop { @@ -291,7 +288,6 @@ impl CanvasTool for ShapeDragTool { start: origin, at: origin, began: false, - space: cx.held(Key::Space), inner: None, sides: options.sides.clamp(*SIDES.start(), *SIDES.end()), shape: None, diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index ed9b69da1..988f2cb2c 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -245,6 +245,27 @@ fn a_shape_mode_rectangle_ends_a_click_within_one_point() { assert!(nudge(ShapeKind::Ellipse, VectorMode::Shape).clicked(), "other kinds keep the press slop"); } +/// Space held moves the box by the pointer's whole motion, the first move after Space went down included; released, +/// the drag resizes again. +#[trial] +fn space_moves_the_box_by_the_full_motion() { + let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Rectangle)); + let corner = PRESS + Vec2::new(40.0, 30.0); + shapes.press(PRESS, Modifiers::NONE); + shapes.move_to(corner, Modifiers::NONE); + assert_eq!(shapes.proposed().map(|shape| shape.bounds()), Some(Rect::new(100.0, 100.0, 140.0, 130.0))); + + shapes.space(true); + shapes.move_to(corner + Vec2::new(10.0, 5.0), Modifiers::NONE); + assert_eq!(shapes.proposed().map(|shape| shape.bounds()), Some(Rect::new(110.0, 105.0, 150.0, 135.0)), "the first move moves the box"); + + shapes.space(false); + let end = corner + Vec2::new(30.0, 25.0); + shapes.move_to(end, Modifiers::NONE); + shapes.release(end, Modifiers::NONE); + assert_eq!(shapes.committed_box(), Some(Rect::new(110.0, 105.0, 170.0, 155.0)), "without Space the drag resizes from the moved press"); +} + #[trial] fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); From 95c557733f4e07a27c2aed3d3ed39eb489b15e58 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:43:17 +0000 Subject: [PATCH 7/8] merge-c: 1.8: Create Shape raises the range alert for a width or height typed past 1..300,000 px, every kind (UnitSelectOutput.out_of_range; CreateShapeDialog::alert_title, take_range_alert) (#13358) --- crates/draw/src/ui/shape_drag/dialog.rs | 92 +++++++++++++------- crates/draw/tests/it/shape_drag.rs | 43 ++++++++- crates/ui-widgets/src/pickers/unit_select.rs | 27 ++++-- 3 files changed, 122 insertions(+), 40 deletions(-) diff --git a/crates/draw/src/ui/shape_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index 2237176ed..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