From 661abbb67eb837e6f43e91a77bb3eb13f77b56c5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 21:09:44 +0000 Subject: [PATCH 1/5] Direct Selection marquee is a gesture: Escape cancels it and the cancelled marquee selects nothing --- crates/draw/src/ui/pen/bezier/mod.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index b818fdfb2..eb9d3ff19 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -14,8 +14,8 @@ mod words; use craft_behavior::geometry::{SelectionOperation, axis_or_diagonal}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; use craft_behavior::{ - Axis, CanvasView, CursorPriority, EditCommand, Granularity, HitLevel, HitPriority, HitShape, Intent, MoveMods, NavMove, NavShape, PartKey, - PartRef, PointerButton, PressPhase, PressStart, Roving, Sense, + Axis, CanvasView, CursorPriority, EditCommand, GesturePhase, Granularity, HitLevel, HitPriority, HitShape, Intent, MoveMods, NavMove, NavShape, + PartKey, PartRef, PointerButton, PressPhase, PressStart, Roving, Sense, }; use craft_keymap::{Chord, Key, Mods}; use craft_theme::Srgba; @@ -817,13 +817,16 @@ impl<'a> BezierOverlay<'a> { 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(); - } + cx.begin(); } if held.began { match held.target { - Target::Marquee => self.marquee = Some(DocRect::from_points(view.to_doc(start.origin), view.to_doc(pos))), + // A marquee is a gesture like the other drags: Escape cancels it and the cancelled one selects nothing. + Target::Marquee => { + if matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) { + self.marquee = Some(DocRect::from_points(view.to_doc(start.origin), view.to_doc(pos))); + } + } _ => { if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) { self.propose(cx, &held.start, edit); @@ -854,8 +857,11 @@ impl<'a> BezierOverlay<'a> { }; if held.target == Target::Marquee { if held.began { - let rect = DocRect::from_points(view.to_doc(start.origin), view.to_doc(pos)); - self.report.select = self.marquee_selection(paths, rect, mods); + if matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) { + let rect = DocRect::from_points(view.to_doc(start.origin), view.to_doc(pos)); + self.report.select = self.marquee_selection(paths, rect, mods); + cx.commit(); + } } else if *self.selection != PathSelection::default() { self.report.select = Some(PathSelection::default()); } From 6317e47925a240a78d79765d92e12cc0e1c3054c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 21:11:57 +0000 Subject: [PATCH 2/5] Convert Point click on an anchor is reported as the click's edit even when the anchor already is a corner --- crates/draw/src/ui/pen/bezier/mod.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index eb9d3ff19..3f407e94f 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -704,6 +704,16 @@ impl<'a> BezierOverlay<'a> { } } + /// A one-shot `edit` of `paths` that is reported even when it changes nothing: a Convert Point click on an anchor + /// that already is a corner is still the click's edit, and the host decides what it makes of it (a live shape + /// becomes a path, the click is a History step). + fn set_always(&mut self, cx: &mut Cx<'_, Self>, paths: &[EditPath], edit: PathEdit) { + let mut next = paths.to_vec(); + edit.apply_all(&mut next); + cx.set(next); + self.report.change = Some(edit); + } + /// The selection a marquee over `rect` makes with `mods`: the anchors inside it on the frontmost path that has /// any, combined with the selection as ⇧, ⌥ and ⇧⌥ say (Photoshop's add, subtract and intersect). fn marquee_selection(&self, paths: &[EditPath], rect: DocRect, mods: Mods) -> Option { @@ -879,7 +889,7 @@ impl<'a> BezierOverlay<'a> { return; } match held.target { - Target::Convert { path, knot } => self.set(cx, &held.start, PathEdit::Convert { path, knot, out: None }), + Target::Convert { path, knot } => self.set_always(cx, &held.start, PathEdit::Convert { path, knot, out: None }), 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 }); From 35d4413ffd71ced969ab0fc66d92d63446b7e9ac Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 21:14:45 +0000 Subject: [PATCH 3/5] Direct Selection: a click on empty canvas keeps the path being edited; trials for the marquee gesture, the deselect click, the Convert click edit and the arrow nudges --- crates/draw/src/ui/pen/bezier/mod.rs | 14 ++++-- crates/draw/tests/it/bezier.rs | 74 ++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 3 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 3f407e94f..1866cb9ba 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -704,6 +704,14 @@ impl<'a> BezierOverlay<'a> { } } + /// The selection with no anchor or segment selected: the path stays the one being edited. + fn deselected(&self) -> PathSelection { + match self.selection.path { + Some(path) => self.selecting(path, Vec::new(), None), + None => PathSelection::default(), + } + } + /// A one-shot `edit` of `paths` that is reported even when it changes nothing: a Convert Point click on an anchor /// that already is a corner is still the click's edit, and the host decides what it makes of it (a live shape /// becomes a path, the click is a History step). @@ -723,7 +731,7 @@ impl<'a> BezierOverlay<'a> { }); let operation = SelectionOperation::from_mods(mods); let Some((path, knots)) = inside else { - return (operation == SelectionOperation::New).then(PathSelection::default); + return (operation == SelectionOperation::New).then(|| self.deselected()); }; let current: Vec = if self.selection.path == Some(path) { self.selection.anchors.clone() } else { Vec::new() }; let anchors = match operation { @@ -872,8 +880,8 @@ impl<'a> BezierOverlay<'a> { self.report.select = self.marquee_selection(paths, rect, mods); cx.commit(); } - } else if *self.selection != PathSelection::default() { - self.report.select = Some(PathSelection::default()); + } else if !self.selection.anchors.is_empty() || self.selection.segment.is_some() { + self.report.select = Some(self.deselected()); } return; } diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index f879bfd41..944b54d39 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -797,3 +797,77 @@ fn the_anchor_tools_take_no_press_off_the_paths_and_show_their_own_cursor() { }); assert_eq!(cursor_at(&mut h, egui::Modifiers::NONE), Some(Cursor::Painted(PaintedCursor::Crosshair))); } + +// A Direct Selection marquee is a gesture like the other drags: it begins with its drag, a release commits it with the +// anchors inside selected, and Escape cancels it and selects nothing. +#[trial] +fn a_marquee_is_one_gesture_that_escape_cancels() { + let from = |h: &Harness| h.screen(p(30.0, 30.0)); + let to = |h: &Harness| h.screen(p(180.0, 80.0)); + + let mut h = two_paths(); + let (start, end) = (from(&h), to(&h)); + h.drag(start, end - start); + { + let st = h.state.borrow(); + assert_eq!(st.selection, sel(1, &[(0, 0), (0, 1)])); + assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit)), "{:?}", st.seen); + } + + let mut h = two_paths(); + h.update(|st| st.selection = sel(2, &[(0, 0)])); + let (start, end) = (from(&h), to(&h)); + h.press_at(start); + h.move_to(start + (end - start) * 0.5); + h.move_to(end); + h.fixture.key(egui::Key::Escape, egui::Modifiers::NONE).settle(); + h.release_at(end); + let st = h.state.borrow(); + assert!(st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Commit), "{:?}", st.seen); + assert_eq!(st.selection, sel(2, &[(0, 0)]), "the cancelled marquee selects nothing"); +} + +// A click on empty canvas deselects the anchors and keeps the path they belong to as the one being edited. +#[trial] +fn a_click_on_empty_canvas_deselects_the_anchors_and_keeps_the_path() { + let mut h = two_paths(); + h.update(|st| st.selection = sel(1, &[(0, 1)])); + let empty = h.screen(p(30.0, 30.0)); + h.press_at(empty); + h.release_at(empty); + assert_eq!(h.state.borrow().selection, sel(1, &[])); +} + +// Convert Point on an anchor that already is a corner still reports the click's edit: the host decides what it makes +// of it. +#[trial] +fn a_convert_click_on_a_corner_reports_its_edit() { + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::Convert); + let corner = h.screen(p(60.0, 60.0)); + h.press_at(corner); + h.release_at(corner); + let st = h.state.borrow(); + assert!(matches!(st.changes.last(), Some(PathEdit::Convert { path: 1, out: None, .. })), "{:?}", st.changes); + assert!(st.seen.contains(&Seen::Set), "{:?}", st.seen); +} + +// The arrow keys nudge the selected anchors, ⇧ by a larger step; each press is one edit, and with no anchor selected +// they move nothing. +#[trial] +fn arrow_keys_nudge_the_selected_anchors_and_shift_nudges_farther() { + let mut h = two_paths(); + // The canvas, then the overlay. + h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + h.fixture.key(egui::Key::ArrowRight, egui::Modifiers::NONE).settle(); + assert!(h.state.borrow().changes.is_empty(), "nothing selected, nothing moves: {:?}", h.state.borrow().changes); + h.update(|st| st.selection = sel(1, &[(0, 1), (0, 2)])); + h.fixture.key(egui::Key::ArrowRight, egui::Modifiers::NONE).settle(); + let Some(PathEdit::MoveAnchors { anchors, by: small, .. }) = h.last_change() else { panic!("{:?}", h.last_change()) }; + assert_eq!(anchors, vec![kr(1), kr(2)]); + assert!(small.x > 0.0 && small.y == 0.0, "{small:?}"); + h.fixture.key(egui::Key::ArrowRight, egui::Modifiers::SHIFT).settle(); + let Some(PathEdit::MoveAnchors { by: far, .. }) = h.last_change() else { panic!("{:?}", h.last_change()) }; + assert!(far.x > small.x, "{small:?} {far:?}"); + assert_eq!(h.state.borrow().changes.len(), 2, "one edit per press"); +} From de2c2972c272e1ad36ee2f22a8f5a490fa173606 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 21:17:55 +0000 Subject: [PATCH 4/5] BezierOverlay: an open press keeps the tool it began under; the host can cancel the open press --- crates/draw/src/ui/pen/bezier/mod.rs | 29 ++++++++++++++++----- crates/draw/tests/it/bezier.rs | 38 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 1866cb9ba..e80b884d2 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -14,8 +14,8 @@ mod words; use craft_behavior::geometry::{SelectionOperation, axis_or_diagonal}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; use craft_behavior::{ - Axis, CanvasView, CursorPriority, EditCommand, GesturePhase, Granularity, HitLevel, HitPriority, HitShape, Intent, MoveMods, NavMove, NavShape, - PartKey, PartRef, PointerButton, PressPhase, PressStart, Roving, Sense, + Axis, CancelReason, CanvasView, CursorPriority, EditCommand, GesturePhase, Granularity, HitLevel, HitPriority, HitShape, Intent, MoveMods, NavMove, NavShape, + PartKey, PartRef, PointerButton, PressCancel, PressPhase, PressStart, Roving, Sense, }; use craft_keymap::{Chord, Key, Mods}; use craft_theme::Srgba; @@ -257,6 +257,8 @@ struct Held { start: Vec, /// Past the click slop: the gesture began. began: bool, + /// The tool the press began under: the press stays that tool's until it ends, whatever the host's tool becomes. + tool: BezierTool, } /// Where a press is in a pass: the view and snap it maps through, the press, the pointer and the modifiers held. @@ -398,6 +400,10 @@ pub struct BezierOverlay<'a> { /// thickness replaces the line width (and the selected segment grows by the same amount). #[prop] path_options: Option<&'a PathOptionsSettings>, + /// The host ended what the open press was editing (its target changed): the press is cancelled in this pass and + /// reports nothing more. + #[prop] + cancelled: bool, report: Report, marquee: Option, hover_mark: Option, @@ -415,6 +421,7 @@ impl<'a> BezierOverlay<'a> { anchors: AnchorsShown::default(), segment_mark: SegmentMark::default(), path_options: None, + cancelled: false, report: Report::default(), marquee: None, hover_mark: None, @@ -776,7 +783,7 @@ impl<'a> BezierOverlay<'a> { tools::anchor_click(self.tool, hit, press.mods, self.selection, &mut self.report); *cx.press_slot::() = None; } else { - *cx.press_slot::() = Some(Held { origin: start.origin, target, start: paths.to_vec(), began: false }); + *cx.press_slot::() = Some(Held { origin: start.origin, target, start: paths.to_vec(), began: false, tool: self.tool }); } } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { @@ -796,7 +803,7 @@ impl<'a> BezierOverlay<'a> { 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 }); + *cx.press_slot::() = Some(Held { origin: start.origin, target: Target::Marquee, start: Vec::new(), began: false, tool: self.tool }); } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { let first = matches!(press.phase, PressPhase::DragStart { .. }); @@ -825,9 +832,9 @@ impl<'a> BezierOverlay<'a> { (Some(held), _) => held, (None, Some(item)) => { 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 } + Held { origin: start.origin, target, start: paths.to_vec(), began: false, tool: self.tool } } - (None, None) => Held { origin: start.origin, target: Target::Marquee, start: Vec::new(), began: false }, + (None, None) => Held { origin: start.origin, target: Target::Marquee, start: Vec::new(), began: false, tool: self.tool }, }; let moves = !matches!(held.target, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. }); if first && moves { @@ -1187,8 +1194,16 @@ impl Component for BezierOverlay<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; let Some(paths) = cx.value().cloned() else { return }; + if let Some(held) = cx.press_slot::().as_ref() { + self.tool = held.tool; + } let scene = self.scene(&paths, &space.view, cx.rect, cx.style.reach); - self.run_pointer(cx, &space, &scene, &paths); + if self.cancelled && cx.press_slot::().take().is_some() { + cx.cancel(CancelReason::HostChanged); + cx.cancel_press(PressCancel::Disabled); + } else { + self.run_pointer(cx, &space, &scene, &paths); + } self.run_keys(cx, &space, &scene, &paths); } diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 944b54d39..327f7204b 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -174,6 +174,8 @@ struct State { tool_clicks: usize, /// The anchor tool the canvas runs under the overlay, if any. canvas_tool: Option, + /// The host ended what the open press was editing. + cancelled: bool, /// Passes in which that tool ran a gesture. tool_gestures: usize, } @@ -239,6 +241,7 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { lone_selects: 0, tool_clicks: 0, canvas_tool: None, + cancelled: false, tool_gestures: 0, })); let shown = Rc::clone(&state); @@ -270,6 +273,7 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { .handles(st.handles) .anchors(st.anchors) .segment_mark(st.segment_mark) + .cancelled(st.cancelled) .show_at(ui, body.rect) }); if canvas.output.click_at().is_some() { @@ -871,3 +875,37 @@ fn arrow_keys_nudge_the_selected_anchors_and_shift_nudges_farther() { assert!(far.x > small.x, "{small:?} {far:?}"); assert_eq!(h.state.borrow().changes.len(), 2, "one edit per press"); } + +// A press belongs to the tool it began under: switching the host's tool in the middle of a drag leaves the drag its +// own, and it commits as that tool's edit. +#[trial] +fn a_press_keeps_the_tool_it_began_under_across_a_tool_switch() { + let mut h = two_paths(); + let anchor = h.screen(p(160.0, 60.0)); + h.press_at(anchor); + h.move_to(anchor + vec2(FAR * 0.5, FAR * 0.5)); + h.update(|st| st.tool = BezierTool::Anchors); + h.move_to(anchor + vec2(FAR, FAR)); + h.release_at(anchor + vec2(FAR, FAR)); + let st = h.state.borrow(); + assert_eq!(st.seen.last(), Some(&Seen::Commit), "{:?}", st.seen); + assert!(matches!(st.changes.last(), Some(PathEdit::MoveAnchors { path: 1, .. })), "{:?}", st.changes); +} + +// A press the host cancels reports nothing more: no commit, no one-shot edit from its release, and the paths stay. +#[trial] +fn a_cancelled_press_reports_nothing_on_release() { + let mut h = two_paths(); + let before = h.state.borrow().paths.clone(); + let anchor = h.screen(p(160.0, 60.0)); + h.press_at(anchor); + h.move_to(anchor + vec2(FAR * 0.5, FAR * 0.5)); + h.update(|st| st.cancelled = true); + h.update(|st| st.cancelled = false); + h.move_to(anchor + vec2(FAR, FAR)); + h.release_at(anchor + vec2(FAR, FAR)); + let st = h.state.borrow(); + assert!(st.seen.contains(&Seen::Cancel), "{:?}", st.seen); + assert!(!st.seen.contains(&Seen::Commit) && !st.seen.contains(&Seen::Set), "{:?}", st.seen); + assert_eq!(st.paths, before); +} From edd7a2afcda6919c17266ee0b2e0b14477100268 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 21:29:20 +0000 Subject: [PATCH 5/5] A host cancels an open press by its owner through the press lifecycle Escape uses; BezierOverlay's parts follow the press's tool cancel_press_of(ctx, owner) marks the arena holding the owner's open press; its next lifecycle run ends the press with PressCancel::Host, which step 9 turns into a HostChanged cancel of the gesture. PartsCx reads the component's press slot, so BezierOverlay declares its parts under the tool the press began with, as it handles them. The overlay lets go of a press that is cancelled or that none of its parts carries, and a release with nothing held does nothing. --- crates/behavior/src/press.rs | 2 + crates/draw/src/ui/pen/bezier/mod.rs | 64 +++++++++---------- crates/draw/tests/it/bezier.rs | 28 ++++++-- crates/ui-canvas/src/canvas/tool_host.rs | 1 + crates/ui-contract/src/contract/cx/parts.rs | 9 +++ crates/ui-contract/src/contract/run/typed.rs | 2 + .../ui-contract/src/contract/steps/update.rs | 1 + crates/ui-contract/src/primitives/mod.rs | 2 +- crates/ui-contract/src/primitives/sensing.rs | 25 +++++++- crates/ui-contract/src/runtime/frame.rs | 5 ++ crates/ui-contract/src/runtime/memory.rs | 13 ++++ 11 files changed, 107 insertions(+), 45 deletions(-) diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index 89b1ea56e..625fcf1da 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -155,6 +155,8 @@ pub enum PressCancel { Disabled, /// The owner was not drawn for a pass. Removed, + /// The host ended what the press acted on (`primitives::cancel_press_of`). + Host, } /// One part's press state in one pass. diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index e80b884d2..0f06eef9a 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -14,8 +14,8 @@ mod words; use craft_behavior::geometry::{SelectionOperation, axis_or_diagonal}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; use craft_behavior::{ - Axis, CancelReason, CanvasView, CursorPriority, EditCommand, GesturePhase, Granularity, HitLevel, HitPriority, HitShape, Intent, MoveMods, NavMove, NavShape, - PartKey, PartRef, PointerButton, PressCancel, PressPhase, PressStart, Roving, Sense, + Axis, CanvasView, CursorPriority, EditCommand, GesturePhase, Granularity, HitLevel, HitPriority, HitShape, Intent, MoveMods, NavMove, NavShape, + PartKey, PartRef, PointerButton, PressPhase, PressStart, Roving, Sense, }; use craft_keymap::{Chord, Key, Mods}; use craft_theme::Srgba; @@ -257,7 +257,8 @@ struct Held { start: Vec, /// Past the click slop: the gesture began. began: bool, - /// The tool the press began under: the press stays that tool's until it ends, whatever the host's tool becomes. + /// The tool the press began under: the overlay's parts and handling stay that tool's until the press ends, + /// whatever the host's tool becomes. tool: BezierTool, } @@ -400,10 +401,6 @@ pub struct BezierOverlay<'a> { /// thickness replaces the line width (and the selected segment grows by the same amount). #[prop] path_options: Option<&'a PathOptionsSettings>, - /// The host ended what the open press was editing (its target changed): the press is cancelled in this pass and - /// reports nothing more. - #[prop] - cancelled: bool, report: Report, marquee: Option, hover_mark: Option, @@ -421,7 +418,6 @@ impl<'a> BezierOverlay<'a> { anchors: AnchorsShown::default(), segment_mark: SegmentMark::default(), path_options: None, - cancelled: false, report: Report::default(), marquee: None, hover_mark: None, @@ -431,6 +427,13 @@ impl<'a> BezierOverlay<'a> { /// The parts a pass declares for `paths`: the anchors and shown handles inside `rect` grown by `reach`, and the /// segments that tool takes and that cross it. + /// An open press keeps the tool it began under: the parts and the handling of every pass of the press follow it. + fn press_tool(&mut self, held: Option<&Held>) { + if let Some(held) = held { + self.tool = held.tool; + } + } + fn scene(&self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32) -> Scene { let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::() > MAX_ANCHORS; let mut items = Vec::new(); @@ -755,12 +758,14 @@ impl<'a> BezierOverlay<'a> { let snap = canvas_snap(&cx.env); let view = &space.view; let mut hovered: Option<(u8, BezierHit, Mods)> = None; + let mut pressed = false; for item in &scene.items { if !self.takes(item) { continue; } let Some(result) = cx.part_if_declared(item.part()) else { continue }; let (press, hover) = (result.press, result.hover_pos); + pressed |= press.phase.is_press(); if let Some(at) = hover { let rank = match item.kind { Kind::Handle(_) => 2, @@ -791,8 +796,9 @@ impl<'a> BezierOverlay<'a> { self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, Some(item), paths, first); } PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { - self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, Some(item), click, paths); + self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths); } + PressPhase::Cancel { .. } => *cx.press_slot::() = None, _ => {} } } @@ -800,6 +806,7 @@ impl<'a> BezierOverlay<'a> { && let Some(result) = cx.part_if_declared(MARQUEE) { let press = result.press; + pressed |= press.phase.is_press(); match press.phase { PressPhase::Down { start, .. } if start.button == PointerButton::Primary => { self.report.pressed_empty = true; @@ -810,11 +817,16 @@ impl<'a> BezierOverlay<'a> { self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, None, paths, first); } PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { - self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, None, click, paths); + self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths); } + PressPhase::Cancel { .. } => *cx.press_slot::() = None, _ => {} } } + // A press none of the parts carries any more (its part went with the paths) is over for the overlay. + if !pressed && cx.press_slot::().is_some() { + *cx.press_slot::() = None; + } if let Some((_, hit, mods)) = hovered { self.report.hover = Some(hit); self.hover_mark = tools::hover_mark(self.tool, hit, mods, self.selection); @@ -863,23 +875,11 @@ impl<'a> BezierOverlay<'a> { } /// The release of a press at `pos`: a drag commits, a click does what its tool's click does. - fn release(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, item: Option<&Item>, click: bool, paths: &[EditPath]) { + fn release(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, click: bool, paths: &[EditPath]) { 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 && 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); - match target { - Target::Insert { path, segment, .. } => self.report.select = Some(self.inserted(path, segment)), - Target::Duplicate { path, subpath, .. } => self.report.select = Some(self.copied(paths, path, subpath)), - _ => {} - } - } - } - return; - }; + // A press reports its Down, and its drag start, before its release, and the overlay holds the press from + // either: a release with nothing held is of a press the overlay let go (a cancelled one), and does nothing. + let Some(held) = cx.press_slot::().take().filter(|held| held.origin == start.origin) else { return }; if held.target == Target::Marquee { if held.began { if matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) { @@ -1157,6 +1157,7 @@ impl Component for BezierOverlay<'_> { /// below them all for the marquee. The anchors and handles are one roving group in keyboard order: one Tab stop, /// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves. fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) { + self.press_tool(cx.press_slot::().as_ref()); let Some(space) = canvas_space(&cx.env) else { return }; let reach = cx.style.reach; let Some(scene) = cx.value().map(|paths| self.scene(paths, &space.view, rect, reach)) else { return }; @@ -1194,16 +1195,9 @@ impl Component for BezierOverlay<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; let Some(paths) = cx.value().cloned() else { return }; - if let Some(held) = cx.press_slot::().as_ref() { - self.tool = held.tool; - } + self.press_tool(cx.press_slot::().as_ref()); let scene = self.scene(&paths, &space.view, cx.rect, cx.style.reach); - if self.cancelled && cx.press_slot::().take().is_some() { - cx.cancel(CancelReason::HostChanged); - cx.cancel_press(PressCancel::Disabled); - } else { - self.run_pointer(cx, &space, &scene, &paths); - } + self.run_pointer(cx, &space, &scene, &paths); self.run_keys(cx, &space, &scene, &paths); } diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 327f7204b..0d1eec658 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -9,6 +9,7 @@ use craft_draw::ui::{ 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::primitives::cancel_press_of; use craft_ui::testing::{Fixture, pointer, trial}; use egui::{Id, Pos2, Vec2 as ScreenVec, vec2}; use std::cell::RefCell; @@ -174,8 +175,6 @@ struct State { tool_clicks: usize, /// The anchor tool the canvas runs under the overlay, if any. canvas_tool: Option, - /// The host ended what the open press was editing. - cancelled: bool, /// Passes in which that tool ran a gesture. tool_gestures: usize, } @@ -241,7 +240,6 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { lone_selects: 0, tool_clicks: 0, canvas_tool: None, - cancelled: false, tool_gestures: 0, })); let shown = Rc::clone(&state); @@ -273,7 +271,6 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { .handles(st.handles) .anchors(st.anchors) .segment_mark(st.segment_mark) - .cancelled(st.cancelled) .show_at(ui, body.rect) }); if canvas.output.click_at().is_some() { @@ -892,7 +889,24 @@ fn a_press_keeps_the_tool_it_began_under_across_a_tool_switch() { assert!(matches!(st.changes.last(), Some(PathEdit::MoveAnchors { path: 1, .. })), "{:?}", st.changes); } -// A press the host cancels reports nothing more: no commit, no one-shot edit from its release, and the paths stay. +// The parts follow the press's tool too: a marquee begun under Direct Selection keeps its part when the host switches +// to a tool that declares none, and its release selects the anchors it encloses. +#[trial] +fn a_tool_switch_mid_press_keeps_the_parts_the_press_began_with() { + let mut h = two_paths(); + let (start, end) = (h.screen(p(30.0, 30.0)), h.screen(p(180.0, 80.0))); + h.press_at(start); + h.move_to(start + (end - start) * 0.5); + h.update(|st| st.tool = BezierTool::Anchors); + h.move_to(end); + h.release_at(end); + let st = h.state.borrow(); + assert_eq!(st.seen.last(), Some(&Seen::Commit), "{:?}", st.seen); + assert_eq!(st.selection, sel(1, &[(0, 0), (0, 1)])); +} + +// A press the host cancels (its target went away) ends as Escape ends one: the gesture is cancelled, its release +// reports nothing, and the paths stay. #[trial] fn a_cancelled_press_reports_nothing_on_release() { let mut h = two_paths(); @@ -900,8 +914,8 @@ fn a_cancelled_press_reports_nothing_on_release() { let anchor = h.screen(p(160.0, 60.0)); h.press_at(anchor); h.move_to(anchor + vec2(FAR * 0.5, FAR * 0.5)); - h.update(|st| st.cancelled = true); - h.update(|st| st.cancelled = false); + let overlay = h.state.borrow().id; + cancel_press_of(h.fixture.ctx(), overlay); h.move_to(anchor + vec2(FAR, FAR)); h.release_at(anchor + vec2(FAR, FAR)); let st = h.state.borrow(); diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index bbcdb4eb4..1ac3befdc 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -857,6 +857,7 @@ fn cancel_reason(reason: PressCancel) -> CancelReason { PressCancel::Escape => CancelReason::Escape, PressCancel::FocusLost => CancelReason::Blur, PressCancel::Disabled => CancelReason::Dismissed, + PressCancel::Host => CancelReason::HostChanged, _ => CancelReason::Removed, } } diff --git a/crates/ui-contract/src/contract/cx/parts.rs b/crates/ui-contract/src/contract/cx/parts.rs index 6aa318dd0..1a5a6d59e 100644 --- a/crates/ui-contract/src/contract/cx/parts.rs +++ b/crates/ui-contract/src/contract/cx/parts.rs @@ -4,6 +4,7 @@ use super::measure::MeasureCx; use super::scroll::{ScrollDecl, THUMB, thumb_covers_centre}; use crate::contract::{Component, Tooltip}; use crate::primitives::sensing::PartDecl; +use crate::runtime::memory::{MemoryStage, Slot}; use crate::runtime::focus::FocusShape; use craft_behavior::{Axis, Cursor, CursorIcon, Flow, HitLevel, HitPriority, HitShape, PartKey, PartRef, Roving, ScrollSpan, Sense}; use craft_theme::Flags; @@ -277,6 +278,8 @@ pub struct PartsCx<'a, C: Component> { /// What the shape laid out before `parts`: a collection's rows as the item step places them this pass, a /// container's header slots. pub(crate) items: Option>, + /// The component's memory and id, for `press_slot`; none for a collection's member. + pub(crate) stage: Option<(&'a MemoryStage, Id)>, } impl PartsCx<'_, C> { @@ -348,6 +351,12 @@ impl PartsCx<'_, C> { self.gesture_running } + /// A copy of the component's press slot as `update` left it (`Remember::press_slot`), so the parts can follow + /// the open press as its handling does. `None` with nothing held, and for a collection's member. + pub fn press_slot(&self) -> Option { + self.stage.and_then(|(stage, id)| stage.recall_press::(id)) + } + /// Declares a part; a repeated part is named with its index: `cx.part(POINT.at(id), shape)`. pub fn part(&mut self, part: impl Into, shape: impl Into) -> PartBuilder<'_> { let part = part.into(); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 1ef59e1ad..4befe0fe9 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -286,6 +286,7 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { gesture_running: self.cx.core.memory.recall::>>(gesture_key(id)).is_running(), measure, items: geometry, + stage: Some((&*self.cx.core.memory, id)), }; self.comp.parts(rect, &mut pcx); self.hooks.parts(self.comp, rect, &mut pcx); @@ -754,6 +755,7 @@ pub(crate) fn member_prepare(ui: &Ui, env: &Env, id: Id, row: Rect, hov gesture_running: false, measure: steps::measure_cx::(&input, &style, &resolved, shown.as_deref()), items: None, + stage: None, }; item.parts(row, &mut pcx); } diff --git a/crates/ui-contract/src/contract/steps/update.rs b/crates/ui-contract/src/contract/steps/update.rs index 0fd57c316..372c9155d 100644 --- a/crates/ui-contract/src/contract/steps/update.rs +++ b/crates/ui-contract/src/contract/steps/update.rs @@ -55,6 +55,7 @@ pub(crate) fn edit_intents(comp: &mut C, cx: &mut Cx<'_, C>) { cx.core.press_cancelled().map(|reason| match reason { PressCancel::Escape => CancelReason::Escape, PressCancel::Removed => CancelReason::Removed, + PressCancel::Host => CancelReason::HostChanged, _ => CancelReason::Blur, }) }; diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index c633c2674..4d05a8124 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -48,7 +48,7 @@ pub use paint_slot::PaintSlot; pub use reset_mark::ResetMark; pub use rule::{RectSide, Rule, RuleKind}; pub use scroll_bar::{HiddenContent, ScrollBar}; -pub use sensing::{PartResult, TextOutcome, member_gesture_running}; +pub use sensing::{PartResult, TextOutcome, cancel_press_of, member_gesture_running}; pub use state_layer::{StateLayer, StateLayerKind}; pub use surface::Surface; pub(crate) use surface::SurfaceSlot; diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index bc7bc63cc..ffba6ca30 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -239,6 +239,8 @@ struct ArenaState { /// egui widgets lie over the members shown before them; a member shown after one of them over its rect gets an /// egui widget of its own, so egui's press target there is the member's (8.3). nested: Vec, + /// The host asked to end the open press (`cancel_press_of`): the arena's next lifecycle run ends it. + host_cancel: bool, } #[derive(Default)] @@ -381,6 +383,20 @@ pub fn member_gesture_running(ctx: &Context, viewport: ViewportId, arena: Id) -> .any(|member| MemoryStage::peek_with::(ctx, gesture_key(member), RemovalWatch::armed)) } +/// Ends the press `owner` holds open the way Escape ends a captured press: the next lifecycle run of the arena it is +/// open in reports `PressPhase::Cancel` with `PressCancel::Host`, and step 9 cancels the gesture the press carries +/// (`CancelReason::HostChanged`). For a host whose own state no longer matches what the press acts on; it may ask +/// inside or outside a pass. Nothing happens when `owner` holds no open press. +pub fn cancel_press_of(ctx: &Context, owner: Id) { + PerViewport::::each(ctx, |arenas| { + for state in arenas.by_root.values_mut() { + if state.machine.target().is_some_and(|target| target.owner == owner) { + state.host_cancel = true; + } + } + }); +} + /// Notes a root shown in the body of `arena` that is not one of its members and takes a press, over `rect`: the /// members shown after it over that rect stack above it. pub(crate) fn note_nested(ctx: &Context, arena: ArenaId, rect: Rect) { @@ -751,8 +767,12 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab pass_pointer.frame.as_ref().map_or((0.0, egui::Vec2::ZERO, None, craft_behavior::Buttons::empty(), 0.0), |frame| { (frame.slop, frame.delta, frame.pos, frame.buttons, frame.target) }); - let cancel = if enabled { pointer::cancel_of_pass(ctx) } else { Some(craft_behavior::PressCancel::Disabled) }; - let body_layer = with_arena(ctx, arena, pass_nr, |state| state.layer); + let (body_layer, host_cancel) = with_arena(ctx, arena, pass_nr, |state| (state.layer, std::mem::take(&mut state.host_cancel))); + let cancel = if enabled { + pointer::cancel_of_pass(ctx).or(host_cancel.then_some(craft_behavior::PressCancel::Host)) + } else { + Some(craft_behavior::PressCancel::Disabled) + }; let xf = body_layer.and_then(|layer| areas::layer_map(ctx, layer)); // Hover needs the root's layer on top under the pointer, or egui's layer cover (a popup) would be ignored. let top = pass_pointer.hover.and_then(|at| areas::layer_at(ctx, at)); @@ -844,6 +864,7 @@ fn sweep_undrawn(ctx: &Context) { }; if orphaned(state) { state.machine = PressMachine::default(); + state.host_cancel = false; gone = true; } } diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 9f7a93826..5cf26e8c5 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -240,6 +240,11 @@ impl PerViewport { out } + /// Runs `f` on the record of every viewport that has one. + pub(crate) fn each(ctx: &Context, mut f: impl FnMut(&mut T)) { + T::records(ctx, |records| records.records.iter_mut().for_each(|(_, record)| f(record))); + } + fn register_prune(ctx: &Context) { fn prune(ctx: &Context, live: &[ViewportId]) { T::records(ctx, |records| records.records.retain(|(viewport, _)| live.contains(viewport))); diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 641a9a3b3..3b2ddfd5f 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -605,6 +605,19 @@ impl MemoryStage { } } + /// A read-only copy of the press slot of `id`, as `recall` reads a shown one. + pub(crate) fn recall_press(&self, id: Id) -> Option { + let open = self + .entries + .iter() + .find(|entry| entry.key == (PRESS, TypeId::of::>(), id)) + .and_then(|entry| entry.value.downcast_ref::>>()); + match open { + Some(wrapped) => wrapped.0.clone(), + None => store::peek_clone::>>(&self.ctx, id).and_then(|wrapped| wrapped.0), + } + } + /// Step 17, after `finish` returned: every slot goes back to context data, and the registry gains a record /// for each slot and `Seen` mark it lacks. A slot the stage found in context data is recorded already; a stage /// owned by another component than its base records everything it wrote under that owner.