diff --git a/crates/draw/src/ui/mod.rs b/crates/draw/src/ui/mod.rs index c99f44526..cd45c5ddf 100644 --- a/crates/draw/src/ui/mod.rs +++ b/crates/draw/src/ui/mod.rs @@ -5,7 +5,7 @@ //! [`GradientMapEditor`] and the [`GradientFillEditor`]. The stop bar and the stop rules are //! craft-color's (`craft_color::ui::gradient`). //! - [`pen`]: the `PenDraft` of the Pen tool and the [`BezierOverlay`] that edits paths, with the -//! path model they share ([`EditPath`]), and the [`PathOptionsPopover`]. +//! path model they share ([`EditPath`]), the anchor tools' [`AnchorTool`], and the [`PathOptionsPopover`]. //! - [`stroke`]: the [`StrokeEditor`], the [`StrokeButton`] that opens it and the [`StrokePreview`]. //! - [`corner`]: the [`CornerWidgets`] for corner radii. //! - [`crop`]: the [`PerspectiveCropQuad`], the [`CropTool`] with its [`CropSession`], and the [`CropBar`]. @@ -90,7 +90,7 @@ pub use paths::{PathKind, PathRow, PathsCommands, PathsEvent, PathsFooterButton, pub use pattern::{ PatternColors, PatternFillDialog, PatternFillEditor, PatternFillOptions, PatternFillOutput, PatternSwatch, PatternWords, SwatchPainter, }; -pub use pen::{AnchorDelete, PenEnd}; +pub use pen::{AnchorDelete, AnchorTool, PenEnd}; pub use pen::{AnchorsShown, HitMark, PATH_OPTIONS_COLOR_KEY, PathMode, PathOptionsPopover, PathOptionsSettings, PathTool, PenMode, SegmentMark}; pub use pen::{ BezierHit, BezierOverlay, BezierStyle, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, MAX_ANCHORS, PathEdit, diff --git a/crates/draw/src/ui/pen/anchor_tool.rs b/crates/draw/src/ui/pen/anchor_tool.rs new file mode 100644 index 000000000..2303f8c5b --- /dev/null +++ b/crates/draw/src/ui/pen/anchor_tool.rs @@ -0,0 +1,110 @@ +//! [`AnchorTool`]: the canvas tool of the anchor tools and Direct Selection, whose presses are the +//! [`BezierOverlay`](super::BezierOverlay)'s. + +use super::tool::ICON_BOX; +use super::{PathTool, PenTool}; +use craft_behavior::{CancelReason, Cursor, CursorBadge, PaintedCursor, PointerButton}; +use craft_keymap::Mods; +use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; +use craft_ui::primitives::{Draw, ToolIcon}; +use egui::Vec2; + +/// The apex of the Convert Point icon's caret, in the units of the icon's box. +const CONVERT_TIP: Vec2 = Vec2::new(ICON_BOX / 2.0, 5.5); + +/// The canvas tool of Add Anchor Point, Delete Anchor Point, Convert Point and Direct Selection. Every press of these +/// tools is the path overlay's ([`PathMode::resolve`](super::PathMode::resolve) gives its tool); a press off the +/// overlay does nothing, so it never starts a path. +/// +/// - The open pen draft ([`draft`](Self::draft)), when the host passes it, is drawn and keeps its keys (Enter, +/// Escape, and Delete unless [`PenTool::deletes`] leaves it to the app) as [`PathMode`](super::PathMode) +/// describes; it takes no press. +/// - Cursor off the overlay's parts: the crosshair under the canvas's precise cursor +/// ([`CanvasSpace::precise`](craft_ui::canvas::CanvasSpace::precise)); with ⌘ Direct Selection's arrow; else Add +/// Anchor the arrow (a click there adds nothing; with ⌥, Delete Anchor, the pen with "-"), Delete Anchor the pen +/// with "-" (with ⌥, Add Anchor, the pen with "+"), Convert Point its icon, Direct Selection the arrow. Over a part +/// the overlay sets its own cursor. +#[derive(Debug)] +pub struct AnchorTool<'a> { + tool: PathTool, + draft: Option<&'a mut PenTool>, +} + +impl<'a> AnchorTool<'a> { + /// The canvas tool of `tool`, with no pen draft. + pub fn new(tool: PathTool) -> Self { + Self { tool, draft: None } + } + + /// The open pen draft, drawn and keyed while the tool runs: `pen` stops sensing. + #[must_use] + pub fn draft(mut self, pen: &'a mut PenTool) -> Self { + pen.sensing(false); + self.draft = Some(pen); + self + } +} + +/// The cursor of `tool` off the overlay's parts with `mods` held; `precise` is the canvas's precise cursor. +fn cursor_of(tool: PathTool, mods: Mods, precise: bool) -> PaintedCursor { + // The pen's tip is the bottom left corner of the icon's box. + let pen = |badge| PaintedCursor::tool(ToolIcon::Pen.icon(), Vec2::Y * ICON_BOX, Some(badge)); + match tool { + _ if precise => PaintedCursor::Crosshair, + _ if mods.cmd => PaintedCursor::arrow(false), + PathTool::AddAnchor if mods.alt => pen(CursorBadge::Subtract), + PathTool::DeleteAnchor if mods.alt => pen(CursorBadge::Add), + PathTool::DeleteAnchor => pen(CursorBadge::Subtract), + PathTool::ConvertPoint => PaintedCursor::tool(ToolIcon::ConvertPoint.icon(), CONVERT_TIP, None), + _ => PaintedCursor::arrow(false), + } +} + +impl CanvasTool for AnchorTool<'_> { + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { + if let Some(pen) = self.draft.as_deref_mut() { + pen.each_pass(cx); + } + } + + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Ignored + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + /// The tool never holds a gesture, so a cancel has nothing to end. + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool { + self.draft.as_deref_mut().is_some_and(|pen| pen.key(key, cx)) + } + + fn claims(&self) -> ToolClaims { + self.draft.as_deref().map_or(ToolClaims::NONE, |pen| pen.claims()) + } + + fn takes(&self, _: PointerButton, _: Mods) -> bool { + false + } + + fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { + if let Some(pen) = self.draft.as_deref() { + pen.paint(draw, cx); + } + } + + fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + Cursor::Painted(cursor_of(self.tool, cx.mods, cx.precise())) + } + + fn access(&self, cx: &ToolContext<'_>) -> Option { + self.draft.as_deref()?.access(cx) + } + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Direct Selection tool's anchor keys") + } +} diff --git a/crates/draw/src/ui/pen/mod.rs b/crates/draw/src/ui/pen/mod.rs index b97a1354e..99d91b9a6 100644 --- a/crates/draw/src/ui/pen/mod.rs +++ b/crates/draw/src/ui/pen/mod.rs @@ -1,7 +1,9 @@ //! [`PenTool`]: the path being drawn with the Pen and the Curvature Pen, as PhotoCraft's tools draw it; +//! [`AnchorTool`]: the canvas tool of the anchor tools and Direct Selection; //! [`PathMode`]: which path overlay a tool and the held keys run; the pen's Path Options //! ([`PathOptionsSettings`], [`PathOptionsPopover`]). +mod anchor_tool; mod auto; pub(crate) mod bezier; mod curvature_mode; @@ -12,6 +14,7 @@ pub(crate) mod stories; mod tool; mod words; +pub use anchor_tool::AnchorTool; pub use bezier::{ AnchorDelete, AnchorsShown, BezierHit, BezierOutput, BezierOverlay, BezierStyle, BezierTool, BezierWords, EditPath, EditSubpath, HandleSide, HandlesShown, HitMark, Knot, KnotRef, MAX_ANCHORS, PathEdit, PathSelection, SegmentMark, diff --git a/crates/draw/src/ui/pen/tool.rs b/crates/draw/src/ui/pen/tool.rs index c8788e3e8..9a9e5b8f6 100644 --- a/crates/draw/src/ui/pen/tool.rs +++ b/crates/draw/src/ui/pen/tool.rs @@ -132,8 +132,8 @@ struct Run { /// [`PenEvent::Resumed`]. /// - Keys while a draft is open: Enter and Escape end it open and keep it (a draft of one anchor is discarded, as no /// path has fewer than two anchors); Backspace and Delete remove the last anchor, the only one discarding the -/// draft; the host's Undo does the same through [`remove_last`](Self::remove_last). Each ending is -/// [`PenEvent::Finished`]. +/// draft, unless the host gives them to another tool ([`deletes`](Self::deletes)); the host's Undo does the same +/// through [`remove_last`](Self::remove_last). Each ending is [`PenEvent::Finished`]. /// - Look: the path so far, a dashed rubber band from the last anchor to where a click would land (with Path /// Options' Rubber Band), the last anchor's handles, the anchors with the last one filled, and over the first /// anchor the close cue. @@ -156,6 +156,7 @@ struct Run { pub struct PenTool { pub(super) mode: PenMode, pub(super) sensing: bool, + deletes: bool, pub(super) auto_add_delete: bool, options: PathOptionsSettings, pub(super) ends: Vec<(u64, KnotRef, Point)>, @@ -186,6 +187,7 @@ impl PenTool { Self { mode: PenMode::default(), sensing: true, + deletes: true, auto_add_delete: false, options: PathOptionsSettings::default(), ends: Vec::new(), @@ -268,6 +270,13 @@ impl PenTool { self } + /// Whether Backspace and Delete remove the draft's last anchor; true by default. False leaves them to the app, for + /// a draft whose anchors are not the selected tool's to take back (a refused draft kept after a tool switch). + pub fn deletes(&mut self, on: bool) -> &mut Self { + self.deletes = on; + self + } + /// The Pen's Auto Add/Delete on the open draft; false by default. No effect in Curvature mode. pub fn auto_add_delete(&mut self, on: bool) -> &mut Self { self.auto_add_delete = on; @@ -617,7 +626,7 @@ impl CanvasTool for PenTool { self.end(CancelReason::Escape, PenEnd::Escape); true } - ToolKey::Delete { .. } => { + ToolKey::Delete { .. } if self.deletes => { self.remove_last_anchor(CancelReason::UndoDuringGesture); true } @@ -626,7 +635,7 @@ impl CanvasTool for PenTool { } fn claims(&self) -> ToolClaims { - if !self.shown.knots.is_empty() && self.drag.is_none() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE } + if self.deletes && !self.shown.knots.is_empty() && self.drag.is_none() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE } } fn takes(&self, button: PointerButton, mods: Mods) -> bool { diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 97dad1893..f879bfd41 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -3,10 +3,10 @@ use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::ui::{ - AnchorDelete, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, PathEdit, - PathSelection, SegmentMark, + AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, + PathEdit, PathSelection, PathTool, SegmentMark, }; -use craft_ui::canvas::{Canvas, Guide}; +use craft_ui::canvas::{Canvas, Guide, ToolHost}; use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft_ui::testing::{Fixture, pointer, trial}; @@ -172,6 +172,10 @@ struct State { lone_selects: usize, /// Presses the overlay left to the canvas's tool. tool_clicks: usize, + /// The anchor tool the canvas runs under the overlay, if any. + canvas_tool: Option, + /// Passes in which that tool ran a gesture. + tool_gestures: usize, } struct Harness { @@ -234,6 +238,8 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { hover: None, lone_selects: 0, tool_clicks: 0, + canvas_tool: None, + tool_gestures: 0, })); let shown = Rc::clone(&state); let mut fixture = Fixture::new(move |ui| { @@ -269,6 +275,10 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { if canvas.output.click_at().is_some() { st.tool_clicks += 1; } + if let Some(tool) = st.canvas_tool { + let reply = ToolHost::new().run(ui, &canvas.output, &mut AnchorTool::new(tool)); + st.tool_gestures += usize::from(reply.gesture.is_some()); + } if st.pans { st.view = canvas.output.view.or(st.view); } @@ -728,3 +738,62 @@ fn add_anchor_shows_the_pen_with_plus_over_a_segment_and_the_arrow_over_an_ancho assert_eq!(cursor_at(&mut h, at, egui::Modifiers::NONE), Some(Cursor::Painted(PaintedCursor::Crosshair)), "{at:?}"); } } + +// The anchor tools' canvas tool: a press off the paths begins nothing (it never starts a path), and off the paths the +// cursor says what a click does: the arrow for Add Anchor (the pen with "-" under ⌥, where a click deletes), the pen +// with "-" for Delete Anchor, the Convert Point icon, the arrow for Direct Selection and under ⌘, the crosshair when +// the canvas's cursor is precise. +#[trial] +fn the_anchor_tools_take_no_press_off_the_paths_and_show_their_own_cursor() { + use craft_behavior::{Cursor, CursorBadge, PaintedCursor}; + let empty = p(320.0, 250.0); + let cursor_at = |h: &mut Harness, mods: egui::Modifiers| { + let at = h.screen(empty); + h.fixture.hold(mods); + h.fixture.frame(vec![pointer::moved(at)]); + h.fixture.frame(Vec::new()); + h.fixture.hold(egui::Modifiers::NONE); + craft_ui::runtime::cursor::current(h.fixture.ctx()) + }; + let pen = |badge: CursorBadge, cursor: &Option| matches!(cursor, Some(Cursor::Painted(PaintedCursor::Tool { badge: b, .. })) if *b == Some(badge)); + let arrow = Some(Cursor::Painted(PaintedCursor::arrow(false))); + + let mut h = two_paths(); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + }); + let before = h.state.borrow().paths.clone(); + let at = h.screen(empty); + h.press_at(at); + h.fixture.frame(vec![pointer::release(at)]); + h.fixture.settle(); + assert_eq!(h.state.borrow().tool_gestures, 0, "a press off the paths begins no gesture"); + assert_eq!(h.state.borrow().paths, before); + + assert_eq!(cursor_at(&mut h, egui::Modifiers::NONE), arrow); + let with_alt = cursor_at(&mut h, egui::Modifiers::ALT); + assert!(pen(CursorBadge::Subtract, &with_alt), "{with_alt:?}"); + assert_eq!(cursor_at(&mut h, egui::Modifiers::COMMAND), arrow); + + h.update(|st| { + st.tool = BezierTool::DeleteAnchor; + st.canvas_tool = Some(PathTool::DeleteAnchor); + }); + let delete = cursor_at(&mut h, egui::Modifiers::NONE); + assert!(pen(CursorBadge::Subtract, &delete), "{delete:?}"); + + h.update(|st| { + st.tool = BezierTool::Convert; + st.canvas_tool = Some(PathTool::ConvertPoint); + }); + let convert = cursor_at(&mut h, egui::Modifiers::NONE); + assert!(matches!(convert, Some(Cursor::Painted(PaintedCursor::Tool { badge: None, .. }))), "{convert:?}"); + + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.precise = true; + }); + assert_eq!(cursor_at(&mut h, egui::Modifiers::NONE), Some(Cursor::Painted(PaintedCursor::Crosshair))); +} diff --git a/crates/draw/tests/it/pen.rs b/crates/draw/tests/it/pen.rs index 194fd097b..b55205608 100644 --- a/crates/draw/tests/it/pen.rs +++ b/crates/draw/tests/it/pen.rs @@ -173,6 +173,20 @@ fn remove_last_waits_for_a_press_that_is_still_down() { assert_eq!(pen.draft().knots.len(), 3, "one request removes one anchor"); } +// Delete takes back the draft's last anchor; with `deletes` off (the anchors are not the selected tool's to take back) +// the key is left to the app and the draft stays. +#[trial] +fn delete_removes_the_last_anchor_unless_the_host_keeps_the_key() { + let mut pen = Pen::three(); + pen.fixture.fixture().key(egui::Key::Delete, Modifiers::NONE); + pen.sync(); + assert_eq!(pen.draft().knots.len(), 2); + pen.fixture.tool_mut().deletes(false); + pen.fixture.fixture().key(egui::Key::Delete, Modifiers::NONE); + pen.sync(); + assert_eq!(pen.draft().knots.len(), 2, "the key is the app's"); +} + #[trial] fn a_quick_drag_in_one_frame_pulls_the_handles() { let mut pen = pen();