From e28bb2d2b51c66284575c5597fcdd5ae4ab18350 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 04:46:09 +0000 Subject: [PATCH] tools-w9: net change of 3 commits - tools-w9: written by an agent - tools-w9: review fixes (review-1) - tools-w9: the add_anchor_tool story drives nothing, as Add Anchor takes a press on an anchor without moving it (tools run round) --- crates/draw/src/geometry/curvature.rs | 46 +++++- crates/draw/src/geometry/curvature_tests.rs | 41 ++++- crates/draw/src/ui/pen/bezier/mod.rs | 168 ++++++++++++++------ crates/draw/src/ui/pen/bezier/model.rs | 8 +- crates/draw/src/ui/pen/bezier/ops.rs | 22 ++- crates/draw/src/ui/pen/bezier/stories.rs | 22 ++- crates/draw/src/ui/pen/bezier/tools.rs | 56 +++++-- crates/draw/src/ui/pen/curvature_mode.rs | 26 +-- crates/draw/src/ui/pen/mode.rs | 8 +- crates/draw/src/ui/pen/tool.rs | 134 ++++++++++++---- crates/draw/tests/it/bezier.rs | 138 +++++++++++++++- crates/draw/tests/it/pen.rs | 97 ++++++++++- 12 files changed, 635 insertions(+), 131 deletions(-) diff --git a/crates/draw/src/geometry/curvature.rs b/crates/draw/src/geometry/curvature.rs index 0086e9fc9..c4f4f84ba 100644 --- a/crates/draw/src/geometry/curvature.rs +++ b/crates/draw/src/geometry/curvature.rs @@ -19,8 +19,50 @@ pub const CURVATURE_T_RANGE: RangeInclusive = 0.01..=0.99; /// knot 0's in handle (put in line with its kept out handle, else with the next kept knot's in /// handle, else its anchor). One entry per anchor. pub fn carried_handles(anchors: &[Point], corners: &[bool], closed: bool, kept: &[(Point, Point)]) -> Vec<(Point, Point)> { - let _ = (anchors, corners, closed, kept); - todo!("tl.T33") + // pc: crates/ui-egui/src/tools/vector_ui/curvature.rs:11-56 `curvature_refresh` (#10726, #10744). + let mut handles = curvature_handles(anchors, corners, closed); + let corner = |i: usize| corners.get(i).copied().unwrap_or(false); + let last = kept.len().saturating_sub(1); + let extended = anchors.len() > kept.len(); + if extended && !closed && !kept.is_empty() { + // As in Photoshop, a path carried on is a new Curvature run from its end. + let run = curvature_handles(anchors.get(last..).unwrap_or_default(), corners.get(last..).unwrap_or_default(), false); + for (slot, fresh) in handles.iter_mut().skip(last).zip(run) { + *slot = fresh; + } + } + for (i, &(was_in, was_out)) in kept.iter().enumerate() { + let Some(slot) = handles.get_mut(i) else { break }; + let (keep_in, keep_out) = (!(closed && i == 0), !(extended && i == last)); + if keep_in { + slot.0 = was_in; + } + if keep_out { + slot.1 = was_out; + } + if !keep_in && keep_out && !corner(i) { + // An out handle on its anchor gives no direction: the kept segment leaves towards its next control point, + // else the next anchor, so the bent in handle comes from the far side and the knot stays smooth. + let across = kept.get(i + 1).zip(anchors.get(i + 1)).map(|(next, &anchor)| [next.0, anchor]); + let toward = std::iter::once(slot.1).chain(across.into_iter().flatten()); + if let Some(h) = toward.filter_map(|from| in_line(anchors[i], from, slot.0)).next() { + slot.0 = h; + } + } + } + handles +} + +/// A handle as long as `bent` from `anchor`, on the far side of it from `kept`; `None` when `kept` lies on the anchor +/// and gives no direction. +fn in_line(anchor: Point, kept: Point, bent: Point) -> Option { + let d = anchor - kept; + let len = d.hypot(); + if !(len > 1e-9 && len.is_finite()) { + return None; + } + let reach = bent.distance(anchor); + reach.is_finite().then(|| anchor + d / len * reach) } /// The Curvature Pen's handles for `anchors`: for each anchor its (in, out) handle points, so the diff --git a/crates/draw/src/geometry/curvature_tests.rs b/crates/draw/src/geometry/curvature_tests.rs index 237f449de..287153604 100644 --- a/crates/draw/src/geometry/curvature_tests.rs +++ b/crates/draw/src/geometry/curvature_tests.rs @@ -3,7 +3,7 @@ use craft_ui::testing::trial; use kurbo::Point; -use super::curvature::curvature_handles; +use super::curvature::{carried_handles, curvature_handles}; fn p(x: f64, y: f64) -> Point { Point::new(x, y) @@ -26,5 +26,40 @@ fn curvature_handles_are_collinear_and_one_third_of_the_neighbour_distance() { assert!((a[1] - i).dot(o - a[1]) > 0.0); } -// `corners[i]` keeps anchor i's handles on the anchor; one or two anchors give straight segments, -// open or closed. +// A path carried on keeps its kept knots: extended and open, the run restarts at the last kept knot, whose out handle +// is the new run's; closed, knot 0's in handle bends into the closing segment and goes back in line with its kept out +// handle, else with the next kept knot's in handle (#10726, #10744). +#[trial] +fn a_carried_run_keeps_the_kept_knots_and_bends_knot_0_in_line_when_closed() { + let anchors = [p(0.0, 0.0), p(100.0, 0.0), p(100.0, 100.0), p(0.0, 100.0)]; + let kept = [(p(-10.0, 5.0), p(30.0, -5.0)), (p(70.0, -3.0), p(130.0, 3.0))]; + + let open = carried_handles(&anchors, &[], false, &kept); + assert_eq!(open.len(), 4); + assert_eq!(open[0], kept[0], "knots before the last kept one keep both handles"); + assert_eq!(open[1].0, kept[1].0, "the last kept knot keeps its in handle"); + // The new run is open from knot 1: its first anchor's out handle and the knots after it are the run's. + let run = curvature_handles(&anchors[1..], &[], false); + assert_eq!(open[1].1, run[0].1, "the last kept knot's out handle starts the new run"); + assert_ne!(open[1].1, kept[1].1); + assert_eq!(&open[2..], &run[1..]); + + // Closed: not extended, so the kept out handles stay; knot 0's in handle is recomputed, then put in line with its + // kept out handle at the recomputed handle's length. + let all = [(p(-10.0, 5.0), p(30.0, -5.0)), (p(70.0, -3.0), p(130.0, 3.0)), (p(100.0, 70.0), p(100.0, 130.0)), (p(30.0, 100.0), p(-30.0, 100.0))]; + let closed = carried_handles(&anchors, &[], true, &all); + assert_eq!(closed[0].1, all[0].1); + assert_eq!(closed[1], all[1]); + let bent = curvature_handles(&anchors, &[], true)[0].0; + let (anchor, out) = (anchors[0], all[0].1); + let want = anchor + (anchor - out) / anchor.distance(out) * anchor.distance(bent); + assert!(closed[0].0.distance(want) < 1e-9, "{:?} vs {want:?}", closed[0].0); + + // An out handle on its anchor gives no direction: the next kept knot's in handle does. + let mut flat = all; + flat[0].1 = anchors[0]; + let closed = carried_handles(&anchors, &[], true, &flat); + let toward = flat[1].0; + let want = anchor + (anchor - toward) / anchor.distance(toward) * anchor.distance(bent); + assert!(closed[0].0.distance(want) < 1e-9, "{:?} vs {want:?}", closed[0].0); +} diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index c1979824a..81a4f03cf 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -58,15 +58,17 @@ pub enum BezierTool { #[default] Direct, /// Convert Point (also the Pen with ⌥): a click on an anchor makes a corner, a drag from it pulls out smooth - /// handles; a handle drag moves that handle alone. + /// handles; a handle drag moves that handle alone; a drag on a straight segment bends it, or moves the whole path + /// when every anchor is selected. Convert, /// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). Anchors, - /// Add Anchor Point: a click on a segment reports [`insert`](BezierOutput::insert) at the hit's `t`; ⌥ makes it - /// Delete Anchor Point. Hover: the segment mark with the anchor a click adds ([`HitMark`]). + /// Add Anchor Point: a press on a segment inserts an anchor at the hit's `t` ([`PathEdit::InsertAnchor`]); a drag + /// moves the new anchor, which is selected; ⌥ makes it Delete Anchor Point. Hover: the segment mark with the + /// anchor a click adds ([`HitMark`]). AddAnchor, /// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it - /// Add Anchor Point. Hover: the anchor mark. + /// Add Anchor Point, except that a ⌥ click on an anchor selects its whole subpath. Hover: the anchor mark. DeleteAnchor, /// The Pen's Auto Add/Delete while no path is being drawn: Add on a segment, Delete on an anchor that is not an /// open subpath's end (the pen draft takes those), no ⌥ swap, no marquee. Presses on empty canvas are left to the @@ -168,6 +170,7 @@ struct Report { select: Option, insert: Option<(u64, KnotRef, f64)>, delete: Option, + pressed_empty: bool, context: Option<(BezierHit, Pos2)>, hover: Option, } @@ -214,6 +217,20 @@ enum Target { t: f64, from: Point, }, + /// Add Anchor's insert (also Auto Add/Delete's) into `segment` at `t`, dragged from `from`, the point of the curve + /// at `t`: the new anchor goes where the pointer takes it. + Insert { + path: u64, + segment: KnotRef, + t: f64, + from: Point, + }, + /// ⌥ with Delete Anchor on an anchor: a click picks the anchor's whole subpath, a drag does nothing. + /// Reported on the click's release, so a drag selects nothing. + Pick { + path: u64, + knot: KnotRef, + }, /// The second click of a double-click on an anchor: a toggle on release, never a drag. Toggle { path: u64, @@ -265,6 +282,8 @@ struct Item { shape: HitShape, /// An anchor that is not the first or last of an open subpath. interior: bool, + /// A segment with both handles retracted. + straight: bool, /// An anchor's place among the path's anchors, from 1, and their number. ordinal: (usize, usize), } @@ -334,8 +353,9 @@ struct Scene { /// followed by its shown handles, in then out), Home and End the first and last; picking an anchor selects it alone. /// ⇧ Page Down and ⇧ Page Up add the next and previous anchor; ⌘A selects every anchor of the path. The arrows move /// the selected anchors or the picked handle (⌥ alone); Delete and Backspace report -/// [`delete`](BezierOutput::delete), Insert [`insert`](BezierOutput::insert) halfway along the segment leaving the -/// picked anchor; Escape deselects. +/// [`delete`](BezierOutput::delete) under the tools that delete anchors (Direct, Convert, Curvature, Add Anchor, +/// Delete Anchor), Insert [`insert`](BezierOutput::insert) halfway along the segment leaving the picked anchor; +/// Escape deselects. /// - The anchor tools ([`BezierTool::AddAnchor`], [`BezierTool::DeleteAnchor`], [`BezierTool::AutoAddDelete`]) and /// [`BezierTool::Curvature`] take only a press that hits what they edit, and draw the [`HitMark`] of what a press /// would take under the pointer. [`segment_mark`](Self::segment_mark), [`anchors`](Self::anchors) and @@ -417,6 +437,7 @@ impl<'a> BezierOverlay<'a> { at: anchor, shape: HitShape::circle(anchor, reach), interior, + straight: false, ordinal: (n + 1, count), }); } @@ -430,13 +451,14 @@ impl<'a> BezierOverlay<'a> { at: end, shape: HitShape::circle(end, reach), interior, + straight: false, ordinal: (n + 1, count), }); } } } } - if self.tool.takes(&BezierHit::Segment { path: 0, segment: KnotRef::new(0, 0), t: 0.0 }, true) { + if self.tool.takes(&BezierHit::Segment { path: 0, segment: KnotRef::new(0, 0), t: 0.0 }, true, true) { for (at, path) in paths.iter().enumerate() { for (s, sub) in path.subpaths.iter().enumerate() { for i in 0..sub.segment_count() { @@ -459,6 +481,7 @@ impl<'a> BezierOverlay<'a> { at: corners[0], shape: HitShape::polyline(points, false), interior: true, + straight: sub.is_straight(i), ordinal: (0, 0), }); } @@ -470,7 +493,7 @@ impl<'a> BezierOverlay<'a> { /// Whether the press on `item` is the tool's. fn takes(&self, item: &Item) -> bool { - self.tool.takes(&item.proxy(), item.interior) + self.tool.takes(&item.proxy(), item.interior, item.straight) } fn path(paths: &[EditPath], key: u64) -> Option<&EditPath> { @@ -483,6 +506,34 @@ impl<'a> BezierOverlay<'a> { .map_or_else(Vec::new, |s| (0..s.knots.len()).map(|k| KnotRef::new(subpath, k)).collect()) } + /// The point of `path`'s segment leaving `segment` at `t`. + fn segment_point(paths: &[EditPath], path: u64, segment: KnotRef, t: f64) -> Point { + Self::path(paths, path) + .and_then(|p| p.subpaths.get(segment.subpath)) + .and_then(|s| s.segment(segment.knot)) + .map_or(Point::ZERO, |c| c.eval(t)) + } + + /// The selection that has only the anchor a segment insert adds. + fn inserted(path: u64, segment: KnotRef) -> PathSelection { + PathSelection { path: Some(path), anchors: vec![KnotRef::new(segment.subpath, segment.knot + 1)], segment: None } + } + + /// The target a press drags: for the tools that act on the press ([`BezierTool::clicks`]) an insert into a + /// segment they add to, or the ⌥ pick of a subpath, else nothing; for the others [`target`](Self::target). + fn press_target(&mut self, hit: BezierHit, start: PressStart, mods: Mods, paths: &[EditPath]) -> Target { + if !self.tool.clicks() { + return self.target(hit, start, mods, paths); + } + match hit { + BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => { + Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) } + } + BezierHit::Anchor { path, knot } if self.tool.picks_subpath(mods) => Target::Pick { path, knot }, + _ => Target::Nothing, + } + } + /// The target a press `start` on `hit` with `mods` drags, and the selection it makes. fn target(&mut self, hit: BezierHit, start: PressStart, mods: Mods, paths: &[EditPath]) -> Target { let knot_at = |path: u64, knot: KnotRef| Self::path(paths, path).and_then(|p| p.knot(knot)); @@ -500,11 +551,26 @@ impl<'a> BezierOverlay<'a> { } (BezierTool::Curvature, BezierHit::Segment { path, segment, t }) => { let t = tools::curvature_t(t); - let from = Self::path(paths, path) - .and_then(|p| p.subpaths.get(segment.subpath)) - .and_then(|s| s.segment(segment.knot)) - .map_or(Point::ZERO, |c| c.eval(t)); - Target::CurvatureInsert { path, segment, t, from } + Target::CurvatureInsert { path, segment, t, from: Self::segment_point(paths, path, segment, t) } + } + // A straight segment: with nothing of the path selected a drag bends it, with every anchor selected it + // moves the path; ⇧, ⌥ or a partial selection do nothing. + (BezierTool::Convert, BezierHit::Segment { path, segment, t }) => { + let Some(shown) = Self::path(paths, path) else { return Target::Nothing }; + if mods.alt || mods.shift { + return Target::Nothing; + } + let from = Self::segment_point(paths, path, segment, t); + let chosen: &[KnotRef] = if self.selection.path == Some(path) { &self.selection.anchors } else { &[] }; + let all: Vec = shown.knot_refs().collect(); + if chosen.is_empty() { + self.report.select = Some(PathSelection { path: Some(path), anchors: Vec::new(), segment: Some(segment) }); + Target::Bend { path, segment, t, from } + } else if all.iter().all(|k| chosen.contains(k)) { + Target::Anchors { path, anchors: all, from } + } else { + Target::Nothing + } } (BezierTool::Convert, BezierHit::Anchor { path, knot }) => Target::Convert { path, knot }, (_, BezierHit::Anchor { path, knot }) => { @@ -529,20 +595,14 @@ impl<'a> BezierOverlay<'a> { Target::Anchors { path, anchors, from } } (_, BezierHit::Segment { path, segment, t }) => { - let sub = Self::path(paths, path).and_then(|p| p.subpaths.get(segment.subpath)); - let from = sub.and_then(|s| s.segment(segment.knot)).map_or(Point::ZERO, |c| c.eval(t)); + let from = Self::segment_point(paths, path, segment, t); if mods.alt { let anchors = Self::subpath_anchors(paths, path, segment.subpath); self.report.select = Some(PathSelection { path: Some(path), anchors: anchors.clone(), segment: None }); Target::Anchors { path, anchors, from } } else { self.report.select = Some(PathSelection { path: Some(path), anchors: Vec::new(), segment: Some(segment) }); - match sub.and_then(|s| s.is_straight(segment.knot).then(|| s.segment_ends(segment.knot)).flatten()) { - Some((a, b)) => { - Target::Anchors { path, anchors: vec![KnotRef::new(segment.subpath, a), KnotRef::new(segment.subpath, b)], from } - } - None => Target::Bend { path, segment, t, from }, - } + Target::Bend { path, segment, t, from } } } (_, BezierHit::Handle { .. }) => Target::Nothing, @@ -572,7 +632,8 @@ impl<'a> BezierOverlay<'a> { &Target::CurvatureInsert { path, segment, t, from } => { PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from } } - Target::Nothing | Target::Toggle { .. } | Target::Marquee => return None, + &Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from }, + Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None, }) } @@ -641,11 +702,12 @@ impl<'a> BezierOverlay<'a> { match press.phase { PressPhase::Down { start, .. } if start.button == PointerButton::Primary => { let hit = item.hit(paths, view, start.origin); - if self.tool.clicks() { + let target = self.press_target(hit, start, press.mods, paths); + if target == Target::Nothing && self.tool.clicks() { + // Delete Anchor and Auto Add/Delete act on an anchor at the press. tools::anchor_click(self.tool, hit, press.mods, &mut self.report); *cx.press_slot::() = None; } else { - let target = self.target(hit, start, press.mods, paths); *cx.press_slot::() = Some(Held { origin: start.origin, target, start: paths.to_vec(), began: false }); } } @@ -665,6 +727,7 @@ impl<'a> BezierOverlay<'a> { let press = result.press; match press.phase { PressPhase::Down { start, .. } if start.button == PointerButton::Primary => { + self.report.pressed_empty = true; *cx.press_slot::() = Some(Held { origin: start.origin, target: Target::Marquee, start: Vec::new(), began: false }); } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { @@ -690,17 +753,16 @@ impl<'a> BezierOverlay<'a> { let mut held = match (kept, item) { (Some(held), _) => held, (None, Some(item)) => { - let target = self.target(item.hit(paths, view, start.origin), start, mods, paths); + let target = self.press_target(item.hit(paths, view, start.origin), start, mods, paths); Held { origin: start.origin, target, start: paths.to_vec(), began: false } } (None, None) => Held { origin: start.origin, target: Target::Marquee, start: Vec::new(), began: false }, }; - let moves = !matches!(held.target, Target::Nothing | Target::Toggle { .. }); + let moves = !matches!(held.target, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. }); if first && moves { held.began = true; - if let Target::CurvatureInsert { path, segment, .. } = held.target { - self.report.select = - Some(PathSelection { path: Some(path), anchors: vec![KnotRef::new(segment.subpath, segment.knot + 1)], segment: None }); + if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } = held.target { + self.report.select = Some(Self::inserted(path, segment)); } if held.target != Target::Marquee { cx.begin(); @@ -724,13 +786,13 @@ impl<'a> BezierOverlay<'a> { let Pointing { view, snap, start, pos, mods } = at; let Some(held) = cx.press_slot::().take().filter(|held| held.origin == start.origin) else { // A press and its drag in one pass: one edit from the press. - if !click - && !self.tool.clicks() - && let Some(item) = item - { - let target = self.target(item.hit(paths, view, start.origin), start, mods, paths); + if !click && let Some(item) = item { + let target = self.press_target(item.hit(paths, view, start.origin), start, mods, paths); if let Some(edit) = Self::edit(view, snap, self.tool, &target, start.origin, pos, mods) { self.set(cx, paths, edit); + if let Target::Insert { path, segment, .. } = target { + self.report.select = Some(Self::inserted(path, segment)); + } } } return; @@ -756,8 +818,16 @@ impl<'a> BezierOverlay<'a> { Target::Toggle { path, knot } => self.set(cx, &held.start, PathEdit::ToggleCurvature { path, knot }), Target::CurvatureInsert { path, segment, t, .. } => { self.set(cx, &held.start, PathEdit::InsertCurvature { path, segment, t, by: Vec2::ZERO }); - self.report.select = - Some(PathSelection { path: Some(path), anchors: vec![KnotRef::new(segment.subpath, segment.knot + 1)], segment: None }); + self.report.select = Some(Self::inserted(path, segment)); + } + Target::Insert { path, segment, t, .. } => { + self.set(cx, &held.start, PathEdit::InsertAnchor { path, segment, t, by: Vec2::ZERO }); + self.report.select = Some(Self::inserted(path, segment)); + } + // A click without a drag (a press past the slop is no click) picks the anchor's whole subpath. + Target::Pick { path, knot } if click => { + let anchors = Self::subpath_anchors(paths, path, knot.subpath); + self.report.select = Some(PathSelection { path: Some(path), anchors, segment: None }); } _ => {} } @@ -853,13 +923,17 @@ impl<'a> BezierOverlay<'a> { { self.report.insert = Some((*key, *knot, 0.5)); } - let forward = cx.intents().take_exact(&Intent::delete(true, Granularity::Unit)); - let backward = cx.intents().take_exact(&Intent::delete(false, Granularity::Unit)); - if (forward || backward) + // Delete is the overlay's only under the tools that delete anchors, and only with anchors selected: under + // Anchors and Auto Add/Delete it is left for the pen draft. + if self.tool.deletes() && let Some(path) = self.selection.path && !self.selection.anchors.is_empty() { - self.report.delete = Some(AnchorDelete::new(path, self.selection.anchors.clone(), false)); // P3(tools-w9): tl.T32 + let forward = cx.intents().take_exact(&Intent::delete(true, Granularity::Unit)); + let backward = cx.intents().take_exact(&Intent::delete(false, Granularity::Unit)); + if forward || backward { + self.report.delete = Some(AnchorDelete::new(path, self.selection.anchors.clone(), true)); + } } if keyed && cx.gesture().is_none() && cx.intents().take(Intent::Cancel) && *self.selection != PathSelection::default() { self.report.select = Some(PathSelection::default()); @@ -934,11 +1008,13 @@ pub struct BezierOutput { pub change: Option, /// The selection the overlay asks for. pub select: Option, - /// Add an anchor to the segment leaving a knot of a path, at `t` (PhotoCraft's Add Anchor Point): a click of an - /// anchor tool on a segment, or Insert on a picked anchor (`t` 0.5). + /// Add an anchor to the segment leaving a knot of a path, at `t` (PhotoCraft's Add Anchor Point): Insert on a + /// picked anchor (`t` 0.5). A click or drag of an anchor tool on a segment is the [`change`](Self::change) + /// [`PathEdit::InsertAnchor`] instead. pub insert: Option<(u64, KnotRef, f64)>, - /// Delete or Backspace: remove these anchors of a path (Delete Anchor Point). - /// Delete or Backspace: remove these anchors of a path (Delete Anchor Point). + /// Delete or Backspace with anchors selected under a tool that deletes (Direct, Convert, Curvature, Add Anchor, + /// Delete Anchor): remove these anchors of a path (Delete Anchor Point), `segments` true; a Delete Anchor click + /// on an anchor reports that one anchor with `segments` false. pub delete: Option, /// A press landed on empty canvas, outside every path. pub pressed_empty: bool, @@ -1150,7 +1226,7 @@ impl Component for BezierOverlay<'_> { } fn finish(self, cx: Cx<'_, Self>) -> BezierOutput { - let Report { change, select, insert, delete, context, hover } = self.report; - BezierOutput { edit: cx.edit_response(), change, select, insert, delete, pressed_empty: false, context, hover } // P3(tools-w9): tl.T32 + let Report { change, select, insert, delete, pressed_empty, context, hover } = self.report; + BezierOutput { edit: cx.edit_response(), change, select, insert, delete, pressed_empty, context, hover } } } diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index acd2d2033..0c208eddd 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -20,6 +20,10 @@ pub struct Knot { pub smooth: bool, } +/// How close a handle lies to its anchor and still counts as retracted, in document units: PhotoCraft's straightness +/// tolerance, so a segment whose handles sit a hair off their anchors is straight for every reader. +const RETRACTED: f64 = 1e-9; + impl Knot { /// A knot with its anchor, both handles and whether it is smooth. pub fn new(anchor: Point, in_ctrl: Point, out_ctrl: Point, smooth: bool) -> Self { @@ -44,9 +48,9 @@ impl Knot { } } - /// Whether the handle on `side` lies on the anchor. + /// Whether the handle on `side` lies on the anchor, within 1e-9 document units. pub fn retracted(&self, side: HandleSide) -> bool { - self.handle(side) == self.anchor + self.handle(side).distance(self.anchor) < RETRACTED } } diff --git a/crates/draw/src/ui/pen/bezier/ops.rs b/crates/draw/src/ui/pen/bezier/ops.rs index 1a7d7250c..6a0e4d4dc 100644 --- a/crates/draw/src/ui/pen/bezier/ops.rs +++ b/crates/draw/src/ui/pen/bezier/ops.rs @@ -5,7 +5,7 @@ use kurbo::{ParamCurve, Point, Vec2}; use super::model::{EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit}; -use crate::geometry::curvature::curvature_handles; +use crate::geometry::curvature::carried_handles; fn lerp(a: Point, b: Point, t: f64) -> Point { a + (b - a) * t @@ -100,13 +100,14 @@ impl EditSubpath { self.reflow_kept(0); } - /// The reflow with the first `kept` knots left as they are. + /// The reflow of a subpath whose first `kept` knots keep their handles + /// ([`carried_handles`](crate::geometry::curvature::carried_handles)): a path the Curvature Pen + /// carries on does not bend the knots it had. pub fn reflow_kept(&mut self, kept: usize) { - let _ = kept; - // P3(tools-w9): tl.T32 let anchors: Vec = self.knots.iter().map(|k| k.anchor).collect(); let corners: Vec = self.knots.iter().map(|k| !k.smooth).collect(); - let fresh = curvature_handles(&anchors, &corners, self.closed); + let held: Vec<(Point, Point)> = self.knots.iter().take(kept).map(|k| (k.in_ctrl, k.out_ctrl)).collect(); + let fresh = carried_handles(&anchors, &corners, self.closed, &held); for (k, (in_ctrl, out_ctrl)) in self.knots.iter_mut().zip(fresh) { if k.smooth { k.in_ctrl = in_ctrl; @@ -134,6 +135,8 @@ impl PathEdit { /// - `InsertCurvature`: [`EditSubpath::insert_at`] (the new knot made smooth, on a straight /// segment too, as Photoshop's Curvature Pen adds a smooth point), the new knot moved by /// `by`, then the subpath reflowed. + /// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no + /// reflow and no smoothing, so a straight segment gets a corner knot. /// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner /// becomes smooth, then the subpath reflows. pub fn apply(&self, path: &mut EditPath) -> bool { @@ -190,7 +193,14 @@ impl PathEdit { keep_smooth(&mut sp.knots[b], HandleSide::In); } } - PathEdit::InsertAnchor { .. } => todo!("tl.T32"), + PathEdit::InsertAnchor { segment, t, by, .. } => { + let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false }; + let Some(at) = sp.insert_at(segment.knot, *t) else { return false }; + let k = &mut sp.knots[at]; + k.anchor += *by; + k.in_ctrl += *by; + k.out_ctrl += *by; + } PathEdit::Convert { knot, out, .. } => { if !knot_ok(path, *knot) { return false; diff --git a/crates/draw/src/ui/pen/bezier/stories.rs b/crates/draw/src/ui/pen/bezier/stories.rs index 94c1f0055..3e51df010 100644 --- a/crates/draw/src/ui/pen/bezier/stories.rs +++ b/crates/draw/src/ui/pen/bezier/stories.rs @@ -1,7 +1,8 @@ //! Stories of `BezierOverlay`. use super::{ - ANCHOR, AnchorsShown, BezierOutput, BezierOverlay, BezierTool, EditPath, EditSubpath, HandlesShown, Knot, KnotRef, PathSelection, index, + ANCHOR, AnchorsShown, BezierOutput, BezierOverlay, BezierTool, EditPath, EditSubpath, HandlesShown, Knot, KnotRef, PathSelection, SEGMENT, + index, }; use craft_behavior::kurbo::Point; use craft_theme::Srgba; @@ -48,7 +49,8 @@ fn curvature_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { on_canvas(ui, |ui, at| BezierOverlay::new("Paths", Bind::bound(&mut *paths), &selected()).tool(BezierTool::Curvature).show_at(ui, at)) } -#[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ANCHOR.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::X)))] +/// Add Anchor takes a press on an anchor and moves nothing: the drag is `add_anchor_tool_dragged`'s, on a segment. +#[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Never)] fn add_anchor_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let paths = data.value("paths", paths()); on_canvas(ui, |ui, at| { @@ -56,6 +58,22 @@ fn add_anchor_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { }) } +#[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(SEGMENT.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::Y)))] +fn add_anchor_tool_dragged(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let paths = data.value("paths", paths()); + on_canvas(ui, |ui, at| { + BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()).tool(BezierTool::AddAnchor).show_at(ui, at) + }) +} + +#[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(SEGMENT.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::Y)))] +fn convert_tool_straight_segment(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let paths = data.value("paths", paths()); + on_canvas(ui, |ui, at| { + BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()).tool(BezierTool::Convert).show_at(ui, at) + }) +} + #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Never)] fn outlines_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let paths = data.value("paths", paths()); diff --git a/crates/draw/src/ui/pen/bezier/tools.rs b/crates/draw/src/ui/pen/bezier/tools.rs index 7ce06a7b9..ce40e11fd 100644 --- a/crates/draw/src/ui/pen/bezier/tools.rs +++ b/crates/draw/src/ui/pen/bezier/tools.rs @@ -18,9 +18,11 @@ impl BezierTool { } } - /// Whether the tool takes a press on `hit`; `interior` is whether an anchor is neither end of an open subpath. + /// Whether the tool takes a press on `hit`; `interior` is whether an anchor is neither end of an open subpath and + /// `straight` whether a segment has both handles retracted. /// - /// - Direct: every part. Convert: anchors and handles. + /// - Direct: every part. Convert: anchors and handles, and a straight segment (a drag bends it, or moves a fully + /// selected path); never a curved one. /// - Add Anchor: a segment, or an anchor (the press is taken so it starts no path; it reports nothing). Delete /// Anchor: an anchor, or a segment (taken, nothing reported). Handles are never taken. /// - Auto Add/Delete: a segment, or an anchor that is not the first or last of an open subpath (those are the @@ -28,12 +30,12 @@ impl BezierTool { /// canvas. /// - Curvature: an anchor or a segment, never a handle or empty canvas. /// - Anchors: none. - pub(super) fn takes(self, hit: &BezierHit, interior: bool) -> bool { + pub(super) fn takes(self, hit: &BezierHit, interior: bool, straight: bool) -> bool { // pc: crates/ui-egui/src/tools/anchor_tools.rs:37-48 `target`, :57-84 `pen_auto` (ends excluded :74-78); // crates/ui-egui/src/tools/direct_select.rs:368-376 `curvature_target`. match self { BezierTool::Direct => true, - BezierTool::Convert => !matches!(hit, BezierHit::Segment { .. }), + BezierTool::Convert => straight || !matches!(hit, BezierHit::Segment { .. }), BezierTool::Anchors => false, // The swap with ⌥ changes what a press reports, not what it takes. BezierTool::AddAnchor | BezierTool::DeleteAnchor | BezierTool::Curvature => !matches!(hit, BezierHit::Handle { .. }), @@ -56,24 +58,38 @@ impl BezierTool { matches!(self, BezierTool::Direct | BezierTool::Convert | BezierTool::Curvature) } + /// Whether Delete and Backspace report [`AnchorDelete`](super::AnchorDelete) for the selection. Under Anchors and + /// Auto Add/Delete the key goes on to the pen draft. + pub(super) fn deletes(self) -> bool { + matches!(self, BezierTool::Direct | BezierTool::Convert | BezierTool::Curvature | BezierTool::AddAnchor | BezierTool::DeleteAnchor) + } + + /// Whether a click with ⌥ on an anchor picks its whole subpath: Delete Anchor with ⌥, where the swapped Add + /// Anchor has nothing to do on an anchor. + pub(super) fn picks_subpath(self, mods: Mods) -> bool { + self == BezierTool::DeleteAnchor && mods.alt + } + + /// Whether a press on a segment adds an anchor: Add Anchor, or Auto Add/Delete, unless ⌥ swaps Add for Delete. + pub(super) fn adds(self, mods: Mods) -> bool { + matches!(self.acting(mods), BezierTool::AddAnchor | BezierTool::AutoAddDelete) + } + /// Whether the tool shows the hover mark of what a press would take. pub(super) fn marks(self) -> bool { matches!(self, BezierTool::AddAnchor | BezierTool::DeleteAnchor | BezierTool::AutoAddDelete | BezierTool::Curvature) } } -/// A click of Add, Delete or Auto Add/Delete on `hit`, reported on press as PhotoCraft does: a segment sets -/// `insert` with the hit's `t`; an anchor sets `delete` with that one anchor. One undo step each. The pen draft, when -/// the host passes it as one more path ([`PathMode::resolve`](crate::ui::pen::PathMode::resolve)), is hit and -/// reported like any path, under the key the host gave it. +/// A click of Delete Anchor or Auto Add/Delete on an anchor, reported on press as PhotoCraft does: `delete` of that one +/// anchor, one undo step. A segment press is the overlay's own ([`BezierTool::adds`]: an anchor that drags into +/// place). The pen draft, when the host passes it as one more path +/// ([`PathMode::resolve`](crate::ui::pen::PathMode::resolve)), is hit and reported like any path, under the key the +/// host gave it. pub(super) fn anchor_click(tool: BezierTool, hit: BezierHit, mods: Mods, report: &mut Report) { // pc: crates/ui-egui/src/tools/anchor_tools.rs:88-114 `pointer`, `click`; :130-150 `apply`. - match (hit, tool.acting(mods)) { - (BezierHit::Segment { path, segment, t }, BezierTool::AddAnchor | BezierTool::AutoAddDelete) => report.insert = Some((path, segment, t)), - (BezierHit::Anchor { path, knot }, BezierTool::DeleteAnchor | BezierTool::AutoAddDelete) => { - report.delete = Some(AnchorDelete::new(path, vec![knot], false)) - } // P3(tools-w9): tl.T32 - _ => {} + if let (BezierHit::Anchor { path, knot }, BezierTool::DeleteAnchor | BezierTool::AutoAddDelete) = (hit, tool.acting(mods)) { + report.delete = Some(AnchorDelete::new(path, vec![knot], false)); } } @@ -91,9 +107,15 @@ pub(super) fn hover_mark(tool: BezierTool, hit: BezierHit, mods: Mods) -> Option other => other, }); } - let mut would = Report::default(); - anchor_click(tool, hit, mods, &mut would); - (would.insert.is_some() || would.delete.is_some()).then_some(hit) + let marked = match hit { + BezierHit::Segment { .. } => tool.adds(mods), + _ => { + let mut would = Report::default(); + anchor_click(tool, hit, mods, &mut would); + would.delete.is_some() + } + }; + marked.then_some(hit) } /// `t` clamped to the range the Curvature tool inserts at. diff --git a/crates/draw/src/ui/pen/curvature_mode.rs b/crates/draw/src/ui/pen/curvature_mode.rs index d782f54f6..496e389ad 100644 --- a/crates/draw/src/ui/pen/curvature_mode.rs +++ b/crates/draw/src/ui/pen/curvature_mode.rs @@ -3,7 +3,7 @@ use super::PenTool; use super::bezier::{EditSubpath, Knot}; -use super::tool::{Drag, Kind, PenStyle, paint_anchors, paint_close_cue, paint_path}; +use super::tool::{Drag, Kind, PenEnd, PenEvent, PenStyle, paint_anchors, paint_close_cue, paint_path}; use craft_behavior::CanvasView; use craft_behavior::kurbo::BezPath; use craft_ui::canvas::{ToolAction, ToolContext, ToolPointer}; @@ -13,13 +13,15 @@ use egui::Pos2; impl PenTool { /// A press in Curvature mode against the draft now: /// + /// - with no draft, on the end point of an open path ([`ends`](PenTool::ends)): [`PenEvent::Resumed`], as the Pen; /// - on the first anchor of a draft with 3 or more anchors: closes at once (`closed` set, `Commit`, `Finished`); /// the Pen closes on release instead; /// - on another anchor: grabs it; past the click slop it follows the pointer and the draft reflows on every /// move; /// - elsewhere: a new smooth anchor at the press, which follows the pointer while the button is down. The first /// two anchors give straight segments; from three on the handles follow - /// [`curvature_handles`](crate::geometry::curvature::curvature_handles); + /// [`carried_handles`](crate::geometry::curvature::carried_handles), which keeps the first + /// [`kept`](PenTool::kept) knots' handles; /// - the second click of a double click on an anchor toggles it between smooth and corner and reflows; on empty /// canvas the first click's anchor is under it, so a double click places a corner point. pub(super) fn press_curve(&mut self, pointer: &ToolPointer, view: &CanvasView, reach: f32) -> ToolAction { @@ -33,12 +35,18 @@ impl PenTool { .filter(|&(_, d)| d <= reach) .min_by(|a, b| a.1.total_cmp(&b.1)) .map(|(i, _)| i); + if n == 0 + && let Some(&(path, knot, _)) = self.ends.iter().find(|(_, _, p)| view.to_screen(*p).distance(pointer.pos) <= reach) + { + self.events.push(PenEvent::Resumed(path, knot)); + return ToolAction::Done; + } if under == Some(0) && n >= 3 && !draft.closed { draft.closed = true; - draft.reflow(); + draft.reflow_kept(self.kept); self.change(draft); self.commit(); - self.finish(super::tool::PenEnd::Closed); // P3(tools-w9): tl.T31 + self.finish(PenEnd::Closed); return ToolAction::Done; } let index = match under { @@ -58,10 +66,10 @@ impl PenTool { n } }; - draft.reflow(); + draft.reflow_kept(self.kept); let in_ctrl = draft.knots[index].in_ctrl; self.change(draft); - self.drag = Some(Drag { origin: pointer.pos, kind: Kind::Move(index), moved: false, in_ctrl }); + self.drag = Some(Drag { origin: pointer.pos, kind: Kind::Move(index), last: pointer.pos, moved: false, in_ctrl }); ToolAction::Claimed } @@ -74,7 +82,7 @@ impl PenTool { && self.drag.is_none() && !draft.closed { - let line = next_segment(draft, view, pointer); + let line = next_segment(draft, self.kept, view, pointer); draw.dashed(&line, Dashes::new(look.dash, look.gap), StrokeWidth::Thin, look.line); } paint_anchors(draw, look, view, draft); @@ -88,10 +96,10 @@ impl PenTool { /// The screen line of the segment the next click would add: the curve through the anchors and the pointer, from the /// last anchor to the pointer. -fn next_segment(draft: &EditSubpath, view: &CanvasView, pointer: Pos2) -> Vec { +fn next_segment(draft: &EditSubpath, kept: usize, view: &CanvasView, pointer: Pos2) -> Vec { let mut next = draft.clone(); next.knots.push(Knot { smooth: true, ..Knot::corner(view.to_doc(pointer)) }); - next.reflow(); + next.reflow_kept(kept); let mut line = Vec::new(); if let [.., a, b] = next.knots.as_slice() { let mut segment = BezPath::new(); diff --git a/crates/draw/src/ui/pen/mode.rs b/crates/draw/src/ui/pen/mode.rs index 5a51f678f..9a1223e7e 100644 --- a/crates/draw/src/ui/pen/mode.rs +++ b/crates/draw/src/ui/pen/mode.rs @@ -56,12 +56,12 @@ impl PathMode { /// | Tool | Keys | `bezier` | `draft` | `draft_senses` | /// |---|---|---|---|---| /// | any pen or anchor tool, Convert Point | ⌘ | `Direct` | the tool's draft mode if `drawing`, else `None` | false | - /// | Pen | none, drawing | `Show` | `Pen` | true | - /// | Pen | none, not drawing | `AutoAddDelete` if `auto_add_delete`, else `Show` | `Pen` | true | + /// | Pen | none, drawing | `Anchors` | `Pen` | true | + /// | Pen | none, not drawing | `AutoAddDelete` if `auto_add_delete`, else `Anchors` | `Pen` | true | /// | Pen | ⌥, not drawing | `Convert` | `Pen` | true | - /// | Pen | ⇧ or ⌥, drawing; ⇧, not drawing | `Show` | `Pen` | true | + /// | Pen | ⇧ or ⌥, drawing; ⇧, not drawing | `Anchors` | `Pen` | true | /// | Curvature | none or ⇧ or ⌥, not drawing | `Curvature` | `Curvature` | true | - /// | Curvature | drawing | `Show` | `Curvature` | true | + /// | Curvature | drawing | `Anchors` | `Curvature` | true | /// | Add Anchor, Delete Anchor | no ⌘ | `AddAnchor`, `DeleteAnchor` (the overlay swaps them with ⌥) | `Pen` if `drawing` (shown, not sensing), else `None` | false | /// | Convert Point | no ⌘ | `Convert` | as Add Anchor | false | /// | Direct Selection | any | `Direct` | as Add Anchor | false | diff --git a/crates/draw/src/ui/pen/tool.rs b/crates/draw/src/ui/pen/tool.rs index 98d89e8f6..ae9cdeef8 100644 --- a/crates/draw/src/ui/pen/tool.rs +++ b/crates/draw/src/ui/pen/tool.rs @@ -9,7 +9,7 @@ use super::{PathOptionsSettings, PenMode, PenWords}; 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_keymap::{Key, Mods}; use craft_theme::Rgba; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolAnchor, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::canvas_controls::path_runs; @@ -106,6 +106,8 @@ pub(super) enum Kind { pub(super) struct Drag { pub(super) origin: Pos2, pub(super) kind: Kind, + /// The pointer of the last sample, for what Space moves. + pub(super) last: Pos2, /// Past the click slop. pub(super) moved: bool, /// The in handle as the last pass left it: ⌥ keeps it there while the out handle follows. @@ -124,7 +126,7 @@ struct Run { /// /// - Pointer, with the Pen ([`PenMode::Pen`]): a click adds a corner anchor (⇧ on the nearest 45° ray from the last /// one); a drag pulls out symmetric handles (⇧ at 45°); ⌥ during the drag breaks the pair, so only the out handle -/// follows. A press on the last anchor retracts its out handle and a drag sets it alone; ⌥ on one of its handles +/// follows; Space moves the pulled anchor with its handles. A press on the last anchor retracts its out handle and a drag sets it alone; ⌥ on one of its handles /// grabs that handle alone. A press on the first anchor closes the path on release, a drag there pulling out that /// anchor's handles. With no draft, a press on an open path's end point ([`ends`](Self::ends)) reports /// [`PenEvent::Resumed`]. @@ -141,8 +143,9 @@ struct Run { /// - [`PenMode::Curvature`] ([`mode`](Self::mode)): a click adds a smooth anchor the curve flows through, which /// follows the pointer while the button is down (past the click slop); a press on the first anchor of 3 or more /// closes at once; a press on another anchor grabs and drags it; the second click of a double click on an anchor -/// toggles it between smooth and corner. Every change reflows the handles ([`EditSubpath::reflow`]). ⇧ and ⌥ do -/// nothing; the keys and the gesture are the Pen's; there is no resume. Hover: with two or more anchors a dashed +/// toggles it between smooth and corner. Every change reflows the handles ([`EditSubpath::reflow_kept`] with +/// [`kept`](Self::kept)). ⇧ and ⌥ do nothing; the keys and the gesture are the Pen's, and a press on an open path's +/// end point resumes it. Hover: with two or more anchors a dashed /// preview of the curve the next click makes, with one a dashed line; always drawn, whatever the rubber band /// setting. /// - [`sensing`](Self::sensing) false: drawn, keys kept, no press taken (the host's Direct Selection acts). @@ -155,7 +158,7 @@ pub struct PenTool { pub(super) sensing: bool, pub(super) auto_add_delete: bool, options: PathOptionsSettings, - ends: Vec<(u64, KnotRef, Point)>, + pub(super) ends: Vec<(u64, KnotRef, Point)>, /// The draft being drawn; empty between drafts. pub(super) shown: EditSubpath, run: Option, @@ -164,7 +167,11 @@ pub struct PenTool { next: GestureId, label: Arc, pub(super) drag: Option, - events: Vec, + pub(super) events: Vec, + /// The anchors of the draft the host handed in: undo never removes them. + own: usize, + /// The leading anchors of the draft that keep their handles when the Curvature mode reflows it. + pub(super) kept: usize, } impl Default for PenTool { @@ -189,6 +196,8 @@ impl PenTool { label: Arc::from(""), drag: None, events: Vec::new(), + own: 0, + kept: 0, } } @@ -200,10 +209,12 @@ impl PenTool { match draft.filter(|draft| !draft.knots.is_empty()) { Some(draft) => { self.shown = draft.clone(); + self.own = draft.knots.len(); self.resume = true; } None => { self.shown = EditSubpath::default(); + self.own = 0; self.resume = false; } } @@ -211,22 +222,32 @@ impl PenTool { self } - /// Ends the run with `Edit(Cancel)` back to the run's start, then `Finished(Discarded)`; false when no run is - /// open. + /// Throws the draft away: `Edit(Cancel)` back to the run's start (the handed-in path of a resumed draft, nothing + /// for a new one), then `Finished(Discarded)`. False, and nothing changes, with no draft or while a press is + /// down. pub fn discard(&mut self) -> bool { - todo!("tl.T31") + if self.shown.knots.is_empty() || self.drag.is_some() { + return false; + } + self.drop_run(CancelReason::Dismissed); + true } - /// The number of leading anchors of the draft that are kept when the draft is rebuilt. + /// The number of leading anchors of the handed-in draft that keep their handles when the Curvature mode reflows + /// the draft (the anchors of the path a press continued). Reset to 0 when the draft ends. pub fn kept(&mut self, kept: usize) -> &mut Self { - let _ = kept; - todo!("tl.T31") + self.kept = kept; + self } - /// Replaces the draft with `draft` while a run is open; false when none is. + /// Replaces the draft with `draft`: one `Update`, beginning a run when none is open. False, and nothing + /// changes, while a press is down. pub fn replace(&mut self, draft: &EditSubpath) -> bool { - let _ = draft; - todo!("tl.T31") + if self.drag.is_some() { + return false; + } + self.change(draft.clone()); + true } /// The Pen or the Curvature Pen; [`PenMode::Pen`] by default. @@ -283,6 +304,17 @@ impl PenTool { self.sensing && self.drag.is_none() && self.closes_at(&self.shown, pointer.pos, &space.view, reach(cx)) } + /// Whether a press at the pointer would continue an open path: sensing, no draft, no button down and the pointer + /// over an end point of [`ends`](Self::ends). + fn continues(&self, cx: &ToolContext<'_>) -> bool { + let (Some(space), Some(pointer)) = (cx.space(), cx.pointer) else { return false }; + let reach = reach(cx); + self.sensing + && self.shown.knots.is_empty() + && self.drag.is_none() + && self.ends.iter().any(|(_, _, at)| space.view.to_screen(*at).distance(pointer.pos) <= reach) + } + // ---- the draft gesture ---- fn begin(&mut self) -> GestureId { @@ -314,7 +346,7 @@ impl PenTool { /// Ends a draft too short to be a path. The gesture's start is what the host holds of the draft: when that is /// empty a cancel leaves nothing behind; when it holds anchors (a resumed path) the empty draft is committed, so /// the host removes them. - fn discard_short(&mut self, reason: CancelReason) { + fn drop_short(&mut self, reason: CancelReason) { let Some(run) = self.run.take() else { return }; if run.before.knots.is_empty() { self.events.push(PenEvent::Edit(EditEvent::cancel(run.id, reason, Some(Mixed::Same(run.before))))); @@ -332,22 +364,38 @@ impl PenTool { self.run = None; self.drag = None; self.resume = false; + self.own = 0; + self.kept = 0; } - /// Ends the draft open: a path of two anchors or more is kept, a shorter one discarded. - fn end(&mut self, reason: CancelReason) { + /// Cancels the run back to its start (the handed-in path of a resumed draft) and ends the draft as `Discarded`. + /// A resume still waiting for its first pass has no run: the host holds the path as it was. + fn drop_run(&mut self, reason: CancelReason) { + if let Some(run) = self.run.take() { + self.events.push(PenEvent::Edit(EditEvent::cancel(run.id, reason, Some(Mixed::Same(run.before))))); + } + self.finish(PenEnd::Discarded); + } + + /// Ends the draft open as `end`: a path of two anchors or more is kept, a shorter one dropped. `reason` is what a + /// dropped draft's cancel says. + fn end(&mut self, reason: CancelReason, end: PenEnd) { if self.shown.knots.len() < 2 { - self.discard_short(reason); + self.drop_short(reason); } else { self.commit(); } - // P3(tools-w9): tl.T31 - self.finish(if reason == CancelReason::Escape { PenEnd::Escape } else { PenEnd::Interrupted }); + self.finish(end); } fn remove_last_anchor(&mut self, reason: CancelReason) { + if self.own > 0 && self.shown.knots.len() <= self.own { + // Undo never eats the anchors of the path the draft resumed. + self.drop_run(reason); + return; + } if self.shown.knots.len() <= 1 { - self.discard_short(reason); + self.drop_short(reason); self.finish(PenEnd::Removed); return; } @@ -355,7 +403,7 @@ impl PenTool { draft.knots.pop(); if self.mode == PenMode::Curvature { // Removing the last anchor changes the curve through the rest. - draft.reflow(); + draft.reflow_kept(self.kept); } self.change(draft); } @@ -417,13 +465,16 @@ impl PenTool { Kind::Close | Kind::Grab(_) | Kind::Move(_) => draft.knots[at].in_ctrl, }; self.change(draft); - self.drag = Some(Drag { origin: pos, kind, moved: false, in_ctrl }); + self.drag = Some(Drag { origin: pos, kind, last: pos, moved: false, in_ctrl }); ToolAction::Claimed } - /// One sample of a press the tool owns: past the click slop the held part follows the pointer. - fn track(&mut self, pos: Pos2, mods: Mods, view: &CanvasView, slop: f32) { + /// One sample of a press the tool owns: past the click slop the held part follows the pointer. With `space` + /// held past the slop the pulled anchor and its handles move by the pointer's travel since the last sample + /// instead, so a sample that repeats a position (a second pass of a frame) moves nothing. + fn track(&mut self, pos: Pos2, mods: Mods, view: &CanvasView, slop: f32, space: bool) { let Some(mut drag) = self.drag.take() else { return }; + let was_moved = drag.moved; drag.moved |= pos.distance(drag.origin) > slop; if drag.moved { let mut draft = self.shown.clone(); @@ -435,19 +486,28 @@ impl PenTool { k.anchor += by; k.in_ctrl += by; k.out_ctrl += by; - draft.reflow(); + draft.reflow_kept(self.kept); self.change(draft); } } kind => { let at = if kind == Kind::Close { 0 } else { draft.knots.len().saturating_sub(1) }; if let Some(k) = draft.knots.get_mut(at) { - pull(k, kind, to, mods, &mut drag.in_ctrl); + if space && was_moved { + let by = to - view.to_doc(drag.last); + k.anchor += by; + k.in_ctrl += by; + k.out_ctrl += by; + drag.in_ctrl += by; + } else { + pull(k, kind, to, mods, &mut drag.in_ctrl); + } self.change(draft); } } } } + drag.last = pos; self.drag = Some(drag); } @@ -514,13 +574,13 @@ impl CanvasTool for PenTool { fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { if let Some(space) = cx.space() { - self.track(pointer.pos, pointer.mods, &space.view, cx.slop); + self.track(pointer.pos, pointer.mods, &space.view, cx.slop, cx.held(Key::Space)); } } fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { if let Some(space) = cx.space() { - self.track(pointer.pos, pointer.mods, &space.view, cx.slop); + self.track(pointer.pos, pointer.mods, &space.view, cx.slop, cx.held(Key::Space)); } let Some(drag) = self.drag.take() else { return }; if drag.kind == Kind::Close { @@ -528,14 +588,14 @@ impl CanvasTool for PenTool { draft.closed = true; self.change(draft); self.commit(); - self.finish(PenEnd::Closed); // P3(tools-w9): tl.T31 + self.finish(PenEnd::Closed); } } fn cancel(&mut self, reason: CancelReason, _: &mut ToolContext<'_>) { self.drag = None; if !self.shown.knots.is_empty() { - self.end(reason); + self.end(reason, PenEnd::Interrupted); } } @@ -544,8 +604,12 @@ impl CanvasTool for PenTool { return false; } match key { - ToolKey::Submit | ToolKey::Cancel => { - self.end(CancelReason::Escape); + ToolKey::Submit => { + self.end(CancelReason::Escape, PenEnd::Submit); + true + } + ToolKey::Cancel => { + self.end(CancelReason::Escape, PenEnd::Escape); true } ToolKey::Delete { .. } => { @@ -582,7 +646,7 @@ impl CanvasTool for PenTool { PenMode::Curvature => ToolIcon::CurvaturePen, }; // The pen's tip is the bottom left corner of the icon's box. - let badge = self.closes(cx).then_some(CursorBadge::Close); + let badge = if self.closes(cx) { Some(CursorBadge::Close) } else { self.continues(cx).then_some(CursorBadge::Continue) }; Cursor::Painted(PaintedCursor::tool(icon.icon(), Vec2::Y * ICON_BOX, badge)) } diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 369cb8389..58e8ac647 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -3,7 +3,7 @@ use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::ui::{ - AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, PathEdit, PathSelection, + AnchorDelete, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, PathEdit, PathSelection, SegmentMark, }; use craft_ui::canvas::{Canvas, Guide}; @@ -128,6 +128,7 @@ fn path_edit_apply_matches_the_kernel_for_every_existing_edit() { PathEdit::convert(7, kr(5), None), PathEdit::toggle_curvature(7, kr(5)), PathEdit::insert_curvature(7, kr(0), 0.0, by), + PathEdit::insert_anchor(7, kr(5), 0.5, by), ]; for e in edits { assert!(!e.apply(&mut ep)); @@ -163,7 +164,7 @@ struct State { seen: Vec, changes: Vec, inserts: Vec<(u64, KnotRef, f64)>, - deletes: Vec<(u64, Vec)>, + deletes: Vec, hover: Option, /// Passes that reported a selection and no edit event. lone_selects: usize, @@ -283,8 +284,8 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { } } if let Some(delete) = output.delete { - let (path, mut knots) = (delete.path, delete.anchors); // P3(tools-w9): tl.T32 - st.deletes.push((path, knots.clone())); + let (path, mut knots) = (delete.path, delete.anchors.clone()); + st.deletes.push(delete); knots.sort_by(|a, b| b.cmp(a)); if let Some(entry) = st.paths.iter_mut().find(|e| e.key == path) { for k in knots { @@ -397,6 +398,135 @@ fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_n assert_eq!(h.state.borrow().selection, picked, "the page key picks no part"); } +// Add Anchor on a segment: a press, a drag and a release are one gesture that inserts the anchor and moves it, with the +// new anchor selected; a click inserts it where the segment was pressed and moves nothing. +#[trial] +fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() { + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::AddAnchor); + let on = h.screen(p(110.0, 60.0)); + h.drag(on, vec2(0.0, FAR)); + { + let st = h.state.borrow(); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen); + assert_eq!(st.seen.first(), Some(&Seen::Begin)); + assert_eq!(st.seen.last(), Some(&Seen::Commit)); + assert!(!st.seen.contains(&Seen::Set), "{:?}", st.seen); + let Some(PathEdit::InsertAnchor { path: 1, segment, by, .. }) = st.changes.last().cloned() else { panic!("{:?}", st.changes) }; + assert_eq!(segment, kr(0)); + assert!(by.y > 10.0 && by.x.abs() < 1e-6, "{by:?}"); + let knots = &st.paths[0].subpaths[0].knots; + assert_eq!(knots.len(), 5); + assert!((knots[1].anchor.y - (60.0 + by.y)).abs() < 1e-6, "the new anchor moved with the pointer: {:?}", knots[1].anchor); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert!(st.inserts.is_empty(), "the Insert key's report is not used"); + } + + // A click inserts without moving. + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::AddAnchor); + let on = h.screen(p(110.0, 60.0)); + h.press_at(on); + h.release_at(on); + let st = h.state.borrow(); + assert!(matches!(st.changes.last(), Some(PathEdit::InsertAnchor { by, .. }) if *by == Vec2::ZERO), "{:?}", st.changes); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); +} + +// Convert on a segment: a drag on a straight one bends it when nothing of the path is selected and moves the path when +// every anchor is, a partial selection and a curved segment do nothing; handles within the straightness tolerance of +// their anchors still make the segment straight. +#[trial] +fn convert_bends_a_straight_segment_and_moves_a_fully_selected_path() { + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::Convert); + let straight = h.screen(p(110.0, 60.0)); + h.drag(straight, vec2(0.0, FAR)); + assert!(matches!(h.last_change(), Some(PathEdit::BendSegment { path: 1, .. })), "{:?}", h.last_change()); + let moved = h.state.borrow().paths[0].subpaths[0].knots.iter().take(2).map(|k| k.anchor.y).collect::>(); + assert!(moved.iter().all(|y| *y > 70.0), "both ends of a straight segment move: {moved:?}"); + + // A curved segment stays untaken. + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::Convert); + let curved_at = h.state.borrow().paths[0].subpaths[0].segment(1).expect("segment").eval(0.5); + let curved = h.screen(curved_at); + let before = h.state.borrow().paths.clone(); + h.drag(curved, vec2(0.0, FAR)); + assert!(h.state.borrow().changes.is_empty(), "{:?}", h.last_change()); + assert_eq!(h.state.borrow().paths, before); + + // A part of the path selected: nothing; every anchor selected: the whole path moves. + let mut h = two_paths(); + let straight = h.screen(p(110.0, 60.0)); + h.update(|st| (st.tool, st.selection) = (BezierTool::Convert, sel(1, &[(0, 0)]))); + h.drag(straight, vec2(0.0, FAR)); + assert!(h.state.borrow().changes.is_empty(), "{:?}", h.last_change()); + h.update(|st| st.selection = sel(1, &[(0, 0), (0, 1), (0, 2), (0, 3)])); + h.drag(straight, vec2(0.0, FAR)); + assert!(matches!(h.last_change(), Some(PathEdit::MoveAnchors { path: 1, anchors, .. }) if anchors.len() == 4), "{:?}", h.last_change()); + + // Handles a hair off their anchors: the segment is straight all the same. + let mut h = two_paths(); + h.update(|st| { + st.tool = BezierTool::Convert; + let knots = &mut st.paths[0].subpaths[0].knots; + knots[0].out_ctrl.x += 1e-12; + knots[1].in_ctrl.x -= 1e-12; + }); + h.drag(straight, vec2(0.0, FAR)); + assert!(matches!(h.last_change(), Some(PathEdit::BendSegment { path: 1, .. })), "{:?}", h.last_change()); +} + +// Delete reports the selected anchors with `segments` true under the tools that delete anchors; under Anchors and Auto +// Add/Delete it stays with the pen draft. A Delete Anchor click reports one anchor with `segments` false. +#[trial] +fn delete_keys_report_segments_and_only_deleting_tools_take_them() { + for (tool, takes) in [(BezierTool::Direct, true), (BezierTool::AutoAddDelete, false), (BezierTool::Anchors, false)] { + let mut h = two_paths(); + h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)]))); + h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE); + h.fixture.key(egui::Key::Delete, egui::Modifiers::NONE).settle(); + let st = h.state.borrow(); + if takes { + assert_eq!(st.deletes, [AnchorDelete::new(1, vec![kr(1)], true)], "{tool:?}"); + } else { + assert!(st.deletes.is_empty(), "{tool:?} leaves Delete to the pen draft: {:?}", st.deletes); + } + } + + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::DeleteAnchor); + let anchor = h.screen(p(160.0, 60.0)); + h.press_at(anchor); + h.release_at(anchor); + assert_eq!(h.state.borrow().deletes, [AnchorDelete::new(1, vec![kr(1)], false)]); +} + +// ⌥ with Delete Anchor on an anchor: a click picks the anchor's whole subpath and edits nothing; a drag selects +// nothing. +#[trial] +fn alt_under_delete_anchor_picks_the_subpath_on_a_click_and_nothing_on_a_drag() { + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::DeleteAnchor); + let anchor = h.screen(p(160.0, 60.0)); + h.fixture.hold(egui::Modifiers::ALT); + h.press_at(anchor); + h.release_at(anchor); + { + let st = h.state.borrow(); + assert_eq!(st.selection, sel(1, &[(0, 0), (0, 1), (0, 2), (0, 3)])); + assert!(st.deletes.is_empty() && st.changes.is_empty() && st.seen.is_empty(), "{:?} {:?} {:?}", st.deletes, st.changes, st.seen); + } + + h.update(|st| st.selection = PathSelection::default()); + h.drag(anchor, vec2(FAR, FAR)); + let st = h.state.borrow(); + assert_eq!(st.selection, PathSelection::default()); + assert!(st.deletes.is_empty() && st.changes.is_empty() && st.seen.is_empty()); +} + #[trial] fn insert_on_a_picked_anchor_adds_one_halfway_along_the_segment_leaving_it() { let mut h = two_paths(); diff --git a/crates/draw/tests/it/pen.rs b/crates/draw/tests/it/pen.rs index 83c763663..ef0bc47a6 100644 --- a/crates/draw/tests/it/pen.rs +++ b/crates/draw/tests/it/pen.rs @@ -3,7 +3,7 @@ use craft_behavior::kurbo::Point; use craft_behavior::{CanvasView, EditEvent}; -use craft_draw::ui::pen::{EditSubpath, Knot, PenEvent, PenTool}; +use craft_draw::ui::pen::{EditSubpath, Knot, PenEnd, PenEvent, PenMode, PenTool}; use craft_ui::testing::{ToolFixture, trial}; use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; @@ -68,6 +68,13 @@ impl Pen { 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(); + } + fn click(&mut self, at: Pos2, modifiers: Modifiers) { self.press(at, modifiers); self.release(at, modifiers); @@ -187,6 +194,94 @@ fn the_pen_is_a_tool_every_canvas_accepts() { fixture.check(); } +// With Space held mid-drag the anchor and both handles move by the pointer's travel; released, the handle follows +// the pointer again. A pass that repeats the pointer moves nothing. +#[trial] +fn space_moves_the_anchor_with_its_handles() { + let mut pen = pen(); + pen.click_doc(60.0, 60.0); + let from = pen.at(160.0, 60.0); + pen.press(from, Modifiers::NONE); + pen.move_to(from + vec2(40.0, 30.0), Modifiers::NONE); + assert_eq!(pen.draft().knots[1], Knot::smooth(doc(160.0, 60.0), doc(200.0, 90.0))); + + pen.space(true); + pen.move_to(from + vec2(60.0, 30.0), Modifiers::NONE); + assert_eq!(pen.draft().knots[1], Knot::smooth(doc(180.0, 60.0), doc(220.0, 90.0)), "the anchor took the 20 points of travel"); + pen.move_to(from + vec2(60.0, 30.0), Modifiers::NONE); + assert_eq!(pen.draft().knots[1].anchor, doc(180.0, 60.0), "a repeated pointer moves nothing"); + + pen.space(false); + pen.move_to(from + vec2(60.0, 50.0), Modifiers::NONE); + let knot = pen.draft().knots[1]; + assert_eq!(knot.anchor, doc(180.0, 60.0)); + assert_eq!(knot.out_ctrl, doc(220.0, 110.0), "the handle follows the pointer again"); + pen.release(from + vec2(60.0, 50.0), Modifiers::NONE); +} + +// A draft the host hands in gains one anchor; the first removal updates the draft, the next goes back to the handed-in +// path and ends the draft as discarded, never as an empty commit. +#[trial] +fn removing_a_resumed_drafts_own_anchor_restores_the_path_and_ends_the_draft() { + let mut pen = pen(); + let own = EditSubpath::new(vec![Knot::corner(doc(60.0, 60.0)), Knot::corner(doc(160.0, 60.0))], false); + pen.fixture.tool_mut().draft(Some(&own)); + pen.fixture.fixture().settle(); + pen.sync(); + assert_eq!(pen.kinds(), ["begin"], "the handed-in draft begins its gesture at once"); + + pen.click_doc(260.0, 160.0); + assert_eq!(pen.draft().knots.len(), 3); + assert!(pen.fixture.tool_mut().remove_last()); + pen.sync(); + assert_eq!(pen.draft(), own, "the added anchor is gone"); + assert!(pen.fixture.tool_mut().remove_last()); + pen.sync(); + assert_eq!(pen.log.last(), Some(&PenEvent::Finished(PenEnd::Discarded))); + assert!(pen.kinds().ends_with(&["cancel", "finished"]), "{:?}", pen.kinds()); + assert!(!pen.kinds().contains(&"commit"), "no empty commit removes the path: {:?}", pen.kinds()); + assert_eq!(pen.draft(), EditSubpath::default()); +} + // ---- Curvature mode ---- +// Curvature mode with `kept(2)`: a handed-in draft resumes, a new click keeps knots 0 and 1's handles but bends knot +// 1's out handle, and `replace` is one `Update`, refused while a press is down. +#[trial] +fn a_curvature_resume_keeps_the_carried_knots_and_replace_updates_the_draft() { + let mut pen = pen(); + let carried = EditSubpath::new(vec![Knot::smooth(doc(60.0, 60.0), doc(80.0, 70.0)), Knot::smooth(doc(160.0, 60.0), doc(180.0, 40.0))], false); + { + let mut tool = pen.fixture.tool_mut(); + tool.mode(PenMode::Curvature); + tool.kept(2); + tool.draft(Some(&carried)); + } + pen.fixture.fixture().settle(); + pen.sync(); + assert_eq!(pen.kinds(), ["begin"]); + + pen.click_doc(260.0, 160.0); + let draft = pen.draft(); + assert_eq!(draft.knots.len(), 3); + assert_eq!(draft.knots[0], carried.knots[0], "the first knot keeps its handles"); + assert_eq!(draft.knots[1].anchor, carried.knots[1].anchor); + assert_eq!(draft.knots[1].in_ctrl, carried.knots[1].in_ctrl, "the last kept knot keeps its in handle"); + assert_eq!(draft.knots[1].out_ctrl, carried.knots[1].anchor, "the last kept knot's out handle starts the new run"); + + let before = pen.log.len(); + assert!(pen.fixture.tool_mut().replace(&carried)); + pen.sync(); + assert_eq!(pen.log.len(), before + 1, "one event"); + assert!(matches!(pen.log.last(), Some(PenEvent::Edit(EditEvent::Update { value, .. })) if *value == carried)); + + let at = pen.at(300.0, 100.0); + pen.press(at, Modifiers::NONE); + let during = pen.log.len(); + assert!(!pen.fixture.tool_mut().replace(&carried), "refused while the press is down"); + pen.sync(); + assert_eq!(pen.log.len(), during); + pen.release(at, Modifiers::NONE); +} + // ---- Path modes and Path Options ----