One Shift-45° helper: turn_to_45 in geometry::lock keeps the length; the measure, gradient and pen copies go, and the gradient's angle_base with them

This commit is contained in:
aiongg
2026-11-12 14:32:42 +00:00
parent 08f208edbd
commit 9839432649
18 changed files with 58 additions and 79 deletions
+1 -12
View File
@@ -8,7 +8,7 @@
use craft_keymap::Mods;
use kurbo::Point;
use super::lock::{Directions, round_to_direction};
use super::lock::turn_to_45;
/// Which tool's rules an [`OutlineDraft`] follows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
@@ -421,14 +421,3 @@ impl OutlineDraft {
self.alt_from_press = false;
}
}
/// `point` turned about `from` to the nearest multiple of 45°, keeping its distance.
pub fn turn_to_45(from: Point, point: Point) -> Point {
let delta = point - from;
let length = delta.hypot();
if !length.is_finite() || length == 0.0 {
return point;
}
let angle = round_to_direction(delta.y.atan2(delta.x), Directions::Eight);
Point::new(from.x + length * angle.cos(), from.y + length * angle.sin())
}
+15 -3
View File
@@ -1,6 +1,6 @@
//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`] and [`round_to_direction`].
//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`] and [`turn_to_45`].
use kurbo::Vec2;
use kurbo::{Point, Vec2};
/// Extra angle in degrees the pointer must pass the half-way line between two directions by
/// before a locked direction switches, so it doesn't flicker near the diagonal.
@@ -30,12 +30,24 @@ impl Directions {
/// `angle` (radians, 0 = right, document y down) rounded to the nearest of `directions` evenly
/// spaced directions: the one angle-rounding rule behind [`lock_direction`] (projection) and
/// [`turn_to_45`](super::draft::turn_to_45) (rotation).
/// [`turn_to_45`] (rotation).
pub fn round_to_direction(angle: f64, directions: Directions) -> f64 {
let step = std::f64::consts::TAU / f64::from(directions.count());
(angle / step).round() * step
}
/// `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the one ⇧ rule for a line, a
/// handle or a segment drawn from a fixed point. `point` itself when it is on `from` or not finite.
pub fn turn_to_45(from: Point, point: Point) -> Point {
let delta = point - from;
let length = delta.hypot();
if !length.is_finite() || length == 0.0 {
return point;
}
let angle = round_to_direction(delta.atan2(), Directions::Eight);
from + Vec2::from_angle(angle) * length
}
/// `d` locked to the nearest of `directions` evenly spaced directions (0° = right, document y
/// down). `previous` is the offset this returned last in the same drag: its direction is kept
/// until `d` is more than half a step plus [`LOCK_HYSTERESIS_DEGREES`] away from it. The length
+1 -1
View File
@@ -16,7 +16,7 @@ pub mod snap;
pub use crop::{CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step};
pub use draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft};
pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, round_to_direction};
pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, 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 quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag};
+15
View File
@@ -0,0 +1,15 @@
//! The ⇧ rules for a drag from a fixed point.
use craft_behavior::geometry::turn_to_45;
use kurbo::Point;
#[test]
fn shift_turns_a_point_onto_the_nearest_45_degree_ray_keeping_its_distance() {
let from = Point::new(10.0, 10.0);
let point = from + kurbo::Vec2::from_angle(40f64.to_radians()) * 20.0;
let turned = turn_to_45(from, point);
let angle = (turned - from).atan2().to_degrees();
assert!((angle - 45.0).abs() < 1e-9, "on the 45° ray, got {angle}");
assert!(((turned - from).hypot() - 20.0).abs() < 1e-9, "the distance is kept");
assert_eq!(turn_to_45(from, from), from);
}
+3 -2
View File
@@ -1,8 +1,9 @@
//! Canvas geometry rules: the transform box, snapping, the outline draft, the marquee gesture
//! and the move gesture.
//! Canvas geometry rules: the transform box, snapping, the outline draft, the marquee gesture,
//! the move gesture and the ⇧ direction rules.
mod crop;
mod draft;
mod lock;
mod marquee;
mod move_gesture;
mod quad;
+1 -1
View File
@@ -2,7 +2,7 @@
//! in the canvas's arena, so a press on an end or a bend stays with the handles and one elsewhere
//! reaches the Connector tool.
use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::geometry::turn_to_45;
use craft_behavior::{Axis, CancelReason, CursorIcon, HitLevel, HitPriority, HitShape, Metrics, NavShape, PartKey, PressPhase, Roving, Sense};
use craft_keymap::Mods;
use craft_ui::canvas::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_snap, canvas_space};
+1 -1
View File
@@ -2,7 +2,7 @@
use std::sync::Arc;
use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::geometry::turn_to_45;
use craft_behavior::{CancelReason, CanvasView, Cursor, CursorIcon, EditEvent, GestureId, Mixed};
use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolContext, ToolPath, ToolPointer};
use craft_ui::primitives::Draw;
@@ -6,9 +6,8 @@
//! start (PhotoCraft's `u_of`), and every location read back from a point is turned back the same
//! way.
use craft_behavior::geometry::draft::turn_to_45;
use egui::Pos2;
use kurbo::{Point, Vec2};
use kurbo::Point;
use crate::ui::gradient::{GradientStops, StopRef, StopRow};
@@ -121,16 +120,6 @@ pub fn project(line: &GradientLine, p: Point, reverse: bool) -> (f32, f64) {
(along(u as f32, reverse), nearest.distance(p))
}
/// `moved` turned about `fixed` onto the nearest multiple of 45° counted from `base_deg`, keeping
/// its distance from `fixed`. Angles are those of the document's axes (y down).
pub fn snap45(fixed: Point, moved: Point, base_deg: f64) -> Point {
let base = Vec2::from_angle(base_deg.to_radians());
let turn = |v: Vec2, by: Vec2| Vec2::new(v.x * by.x - v.y * by.y, v.x * by.y + v.y * by.x);
let local = turn(moved - fixed, Vec2::new(base.x, -base.y));
let snapped = turn(turn_to_45(Point::ORIGIN, local.to_point()).to_vec2(), base);
fixed + snapped
}
/// The location of the midpoint diamond after colour stop `i`: its stop's location plus the
/// midpoint's share of the way to the next; `None` for the last stop and for stops no farther
/// apart than [`MIN_MIDPOINT_GAP`].
@@ -98,8 +98,7 @@ const TEAR_OFF: f32 = 36.0;
/// [`StopRows::Split`] and [`StopRows::ColorOnly`] a stop's disc is opaque; under [`StopRows::Combined`] its colour
/// shows its opacity over a backing. Nothing mirrors in a right-to-left interface.
/// - Pointer: the end, start, nearest stop, nearest midpoint and the line are parts in that priority. A drag begins past
/// the click slop. An end follows the pointer (Shift: 45 degree steps from [`angle_base`](Self::angle_base) about the
/// other end), the line moves both ends, a stop moves to the location under the pointer and is torn off, removed when
/// the click slop. An end follows the pointer (Shift: 45 degree steps about the other end), the line moves both ends, a stop moves to the location under the pointer and is torn off, removed when
/// the drag ends there, more than the style's tear-off distance from the line while its row is above `rules.min`, a
/// midpoint moves within its segment. Alt drags a copy of a stop with [`alt_copies`](Self::alt_copies). Every update is
/// the whole edit of the gradient at the press. Ends and the line snap through the canvas's `Snap`.
@@ -138,9 +137,6 @@ pub struct GradientOverlay<'a> {
/// Whether an Alt-drag on a stop drags a copy of it; off, Alt is the tool's.
#[prop(flag)]
alt_copies: bool,
/// The angle in degrees, along the document's axes, that Shift's 45 degree steps of a dragged end start from.
#[prop(quantity = "degrees")]
angle_base: f64,
/// Decimals of a stop's location in its accessible value.
#[prop(quantity = "decimals")]
location_decimals: u8,
@@ -177,7 +173,6 @@ impl<'a> GradientOverlay<'a> {
reverse: false,
extent: GradientExtent::None,
alt_copies: false,
angle_base: 0.0,
location_decimals: 0,
shared_selection: None,
value_text: None,
@@ -1,6 +1,7 @@
//! The overlay's pointer: the press on a part, the drag of an end, the line, a stop or a midpoint, the click that adds a
//! stop, double-clicks and secondary clicks.
use craft_behavior::geometry::turn_to_45;
use craft_behavior::kurbo::Point;
use craft_behavior::{Axis, CanvasView, PointerButton, PressPhase};
use craft_keymap::Mods;
@@ -10,7 +11,7 @@ use egui::Pos2;
use super::GradientOverlay;
use super::parts::{keyboard_order, part_ref, selection_of};
use crate::ui::gradient::gradient_line::{MIN_MIDPOINT_GAP, project, snap45};
use crate::ui::gradient::gradient_line::{MIN_MIDPOINT_GAP, project};
use crate::ui::gradient::stops::{self, round_location};
use crate::ui::gradient::{GradientLine, LineGradient, LinePart, Sampler, StopRef, StopRow, default_sampler};
@@ -154,7 +155,7 @@ impl GradientOverlay<'_> {
_ => (base.line.start, &mut out.value.line.end),
};
let to = view.to_doc(pointer);
let to = if mods.shift { snap45(fixed, to, self.angle_base) } else { to };
let to = if mods.shift { turn_to_45(fixed, to) } else { to };
*moved = snapped(snap, to, mods);
}
LinePart::Line => {
+2 -14
View File
@@ -3,7 +3,7 @@
use super::model::{RulerLine, RulerPart};
use super::words::RulerWords;
use craft_behavior::geometry::{Directions, round_to_direction};
use craft_behavior::geometry::turn_to_45;
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_behavior::{Granularity, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PartKey, PointerButton, PressPhase, Roving, Sense};
use craft_ui::canvas::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_space};
@@ -62,22 +62,10 @@ impl<'a> RulerOverlay<'a> {
}
}
/// `to` on the nearest 45° ray from `fixed`, at its distance from `fixed` (`to` itself when it is on `fixed` or not
/// finite). The ruler keeps the pointer's distance; a projection would shorten it.
pub(super) fn on_ray(fixed: Point, to: Point) -> Point {
let offset = to - fixed;
let length = offset.hypot();
if !length.is_finite() || length == 0.0 {
return to;
}
let angle = round_to_direction(offset.atan2(), Directions::Eight);
fixed + DocVec::new(angle.cos(), angle.sin()) * length
}
/// The line with the grabbed `part` moved to `to`, Shift on 45° rays about the fixed point: the end for the start, the
/// start for the end and the protractor.
pub(super) fn moved(line: RulerLine, part: RulerPart, to: Point, shift: bool) -> RulerLine {
let constrain = |fixed: Point| if shift { on_ray(fixed, to) } else { to };
let constrain = |fixed: Point| if shift { turn_to_45(fixed, to) } else { to };
let mut line = line;
match part {
RulerPart::Start => line.start = constrain(line.end),
+2 -7
View File
@@ -11,7 +11,7 @@ mod style;
mod tools;
mod words;
use craft_behavior::geometry::{Directions, SelectionOperation, lock_direction};
use craft_behavior::geometry::{SelectionOperation, turn_to_45};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2};
use craft_behavior::{
Axis, CanvasView, EditCommand, Granularity, HitLevel, HitPriority, HitShape, Intent, NavMove, NavShape, PartKey, PartRef, PointerButton,
@@ -552,7 +552,7 @@ impl<'a> BezierOverlay<'a> {
/// The edit of a press at `origin` dragged to `pointer`: the whole move from the press.
fn edit(view: &CanvasView, snap: Option<&Snap>, tool: BezierTool, target: &Target, origin: Pos2, pointer: Pos2, mods: Mods) -> Option<PathEdit> {
let delta = view.to_doc(pointer) - view.to_doc(origin);
let locked = |delta: Vec2| if mods.shift { constrain(Point::ZERO, Point::ZERO + delta).to_vec2() } else { delta };
let locked = |delta: Vec2| if mods.shift { turn_to_45(Point::ZERO, Point::ZERO + delta).to_vec2() } else { delta };
let snapped = |p: Point| match snap {
Some(snap) => Point::new(snap.apply(Axis::Y, p.x, mods), snap.apply(Axis::X, p.y, mods)),
None => p,
@@ -916,11 +916,6 @@ fn nudge_vector(view: &CanvasView, direction: egui::Vec2, distance: f64) -> Vec2
if length > 0.0 { doc / length * distance } else { Vec2::ZERO }
}
/// `to` turned onto the nearest 45° ray from `from` (PhotoCraft's `Edit::constrain`): its projection there.
pub(crate) fn constrain(from: Point, to: Point) -> Point {
from + lock_direction(to - from, None, Directions::Eight)
}
fn contains(r: DocRect, p: Point) -> bool {
(r.x0..=r.x1).contains(&p.x) && (r.y0..=r.y1).contains(&p.y)
}
+6 -13
View File
@@ -6,8 +6,8 @@ use std::sync::Arc;
use super::auto::AutoEdit;
use super::bezier::{EditSubpath, HandleSide, Knot, KnotRef};
use super::{PathOptionsSettings, PenMode, PenWords};
use craft_behavior::geometry::{Directions, lock_direction};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
use craft_behavior::geometry::turn_to_45;
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::{CancelReason, CanvasView, Cursor, CursorBadge, EditEvent, GestureId, Mixed, PaintedCursor, PointerButton};
use craft_keymap::Mods;
use craft_theme::Rgba;
@@ -366,7 +366,7 @@ impl PenTool {
Kind::Pull => {
let mut p = view.to_doc(pos);
if mods.shift && n > 0 {
p = draft.knots[n - 1].anchor + constrain(p - draft.knots[n - 1].anchor);
p = turn_to_45(draft.knots[n - 1].anchor, p);
}
draft.knots.push(Knot::corner(p));
p
@@ -430,19 +430,12 @@ pub(super) fn reach(cx: &ToolContext<'_>) -> f32 {
cx.slop
}
/// `offset` turned onto the nearest 45° ray.
fn constrain(offset: DocVec) -> DocVec {
lock_direction(offset, None, Directions::Eight)
}
/// A pulled knot: its handles follow `to`. A pull and a close drag put the out handle there and the in handle
/// opposite it, unless ⌥ keeps the in handle where it was; a retracted anchor's handle and a grabbed handle move
/// alone. ⇧ turns the handle to the nearest 45° ray.
fn pull(knot: &mut Knot, kind: Kind, to: Point, mods: Mods, in_ctrl: &mut Point) {
let mut v = to - knot.anchor;
if mods.shift {
v = constrain(v);
}
let to = if mods.shift { turn_to_45(knot.anchor, to) } else { to };
let v = to - knot.anchor;
match kind {
Kind::Pull | Kind::Close => {
knot.out_ctrl = knot.anchor + v;
@@ -601,7 +594,7 @@ impl PenTool {
{
let mut end = view.to_doc(pointer);
if cx.mods.shift {
end = last.anchor + constrain(end - last.anchor);
end = turn_to_45(last.anchor, end);
}
draw.dashed(&[view.to_screen(last.anchor), view.to_screen(end)], Dashes::new(look.dash, look.gap), StrokeWidth::Thin, look.line);
}
+1 -1
View File
@@ -2,7 +2,7 @@
use std::sync::Arc;
use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::geometry::turn_to_45;
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};
+1 -1
View File
@@ -1,6 +1,6 @@
//! [`PolygonLassoTool`]: the Polygonal Lasso, click by click.
use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::geometry::turn_to_45;
use craft_behavior::geometry::{DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation};
use craft_behavior::{CancelReason, Cursor, PointerButton};
use craft_keymap::Mods;
@@ -1,6 +1,7 @@
//! The Select and Mask canvas tool: the gesture state, the edits it builds and the `CanvasTool` impl.
use craft_behavior::geometry::draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, turn_to_45};
use craft_behavior::geometry::draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft};
use craft_behavior::geometry::turn_to_45;
use craft_behavior::kurbo::Point;
use craft_behavior::{CancelReason, Cursor, CursorBadge, CursorIcon, GestureId, PaintedCursor, PointerButton};
use craft_keymap::Mods;
+1 -1
View File
@@ -2,7 +2,7 @@
//! drawing or editing gesture reports (N5.03). Coordinates are page units (points, y down), as
//! the canvas tool host gives them.
use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::geometry::turn_to_45;
use kurbo::{Point, Rect, Vec2};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
+1 -1
View File
@@ -1,6 +1,6 @@
//! The canvas tool: presses, drags, the "New Annotation..." form and the [`CanvasTool`] implementation.
use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::geometry::turn_to_45;
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed, PointerButton, SelectionChange};
use craft_keymap::Mods;
use craft_theme::Srgba;