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 b818fdfb2..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, 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; @@ -257,6 +257,9 @@ struct Held { start: Vec, /// Past the click slop: the gesture began. began: bool, + /// 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, } /// Where a press is in a pass: the view and snap it maps through, the press, the pointer and the modifiers held. @@ -424,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(); @@ -704,6 +714,24 @@ 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). + 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 { @@ -713,7 +741,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 { @@ -730,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, @@ -758,7 +788,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 => { @@ -766,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, _ => {} } } @@ -775,21 +806,27 @@ 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; - *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 { .. }); 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); @@ -807,9 +844,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 { @@ -817,13 +854,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); @@ -835,29 +875,20 @@ 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 { - let rect = DocRect::from_points(view.to_doc(start.origin), view.to_doc(pos)); - self.report.select = self.marquee_selection(paths, rect, mods); - } else if *self.selection != PathSelection::default() { - self.report.select = Some(PathSelection::default()); + 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.anchors.is_empty() || self.selection.segment.is_some() { + self.report.select = Some(self.deselected()); } return; } @@ -873,7 +904,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 }); @@ -1126,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 }; @@ -1163,6 +1195,7 @@ 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 }; + self.press_tool(cx.press_slot::().as_ref()); let scene = self.scene(&paths, &space.view, cx.rect, cx.style.reach); 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 f879bfd41..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; @@ -797,3 +798,128 @@ 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"); +} + +// 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); +} + +// 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(); + 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)); + 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(); + 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); +} 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.