mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 04:04:25 +00:00
merge-c: 1.2: Line ⇧ snaps to the axis within 30° (keeping the along-axis offset, at least 1 px) or the diagonal at the shorter offset, one rule in craft-behavior (axis_or_diagonal)
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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<ShapeGeometry> {
|
||||
// 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
|
||||
|
||||
@@ -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<ShapeDragTool>,
|
||||
log: Vec<ShapeDragEvent>,
|
||||
}
|
||||
|
||||
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<ShapeGeometry> {
|
||||
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<ShapeGeometry> {
|
||||
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<Rect> {
|
||||
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<ShapeGeometry>| 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();
|
||||
|
||||
Reference in New Issue
Block a user