diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 528d95f04..c1a1002cb 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -58,6 +58,9 @@ impl BodyHooks<'_> { } // The container's own `enabled(false)` greys everything inside it, as a scope would. scoped.enabled &= cx.core.resolved.enabled; + if let Some(collection) = props.fallback_collection { + scoped.fallback_collection = Some(collection); + } if let Some(window) = window { scoped.inherited_mut().commands = scoped.commands.pushed(WindowCommand::SCOPE, window); } diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 15adf9db8..d322f5fa6 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -743,6 +743,8 @@ pub struct ContainerProps { /// page and end moves and the reveals its children leave go to it (`Focus::take_scroll_moves`, /// `Focus::take_reveal`). A container with a `scroll` region is one already. pub scroll_owner: bool, + /// A collection that receives moves the focused control in this region leaves unused. + pub fallback_collection: Option, /// The container's value is a gate that disables its content while off. #[doc(hidden)] pub gates: bool, @@ -838,6 +840,7 @@ impl ContainerProps { child_glyphs: None, arena: false, scroll_owner: false, + fallback_collection: None, gates: false, transform: None, theme: None, @@ -1015,6 +1018,12 @@ impl ContainerProps { self } + /// Sends unused moves from this region's focused control to the named collection. + pub fn fallback_collection(mut self, collection: egui::Id) -> Self { + self.fallback_collection = Some(collection); + self + } + /// Shows the body through `transform` on its own egui layer. pub const fn transform(mut self, transform: CanvasTransform) -> Self { self.transform = Some(transform); diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 144f901ba..3cf0717cf 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -413,6 +413,10 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } self.drag_step(comp, cx, &layout, (rect, offset, rtl), &props); self.marquee_step(comp, cx, &layout, (rect, offset, rtl), &props); + let quiet = cx.core.memory.is_peek() || crate::runtime::measure::active(&cx.core.ctx); + for (mv, mods) in crate::contract::steps::scroll_moves(&cx.core.ctx, cx.core.id, quiet) { + cx.core.intents.push(craft_behavior::Intent::Move(mv, mods)); + } self.navigate(comp, cx, &layout, view, header_held); self.switch_page(comp, cx, &props, &layout); let lead_at = self.lead.key.as_ref().and_then(|key| self.index_of(key)).or(lead_at); diff --git a/crates/ui-contract/src/contract/steps/scroll_owner.rs b/crates/ui-contract/src/contract/steps/scroll_owner.rs index 9b6593666..84ce878dd 100644 --- a/crates/ui-contract/src/contract/steps/scroll_owner.rs +++ b/crates/ui-contract/src/contract/steps/scroll_owner.rs @@ -13,6 +13,15 @@ use egui::{Context, Id, Rect, Vec2}; pub(super) fn route_to_scroll_owner(core: &mut CxCore<'_>) { let scrolls = |mv: NavMove, _| matches!(mv, NavMove::PageUp | NavMove::PageDown | NavMove::Start | NavMove::End); let mut moves = Vec::new(); + if let Some(collection) = core.env.fallback_collection().filter(|id| *id != core.id) { + while let Some(mv) = core.intents.take_move() { + moves.push(mv); + } + if !moves.is_empty() { + pass_state::with::(&core.ctx, |queue| queue.0.extend(moves.drain(..).map(|(mv, mods)| (collection, mv, mods)))); + repaint::request(&core.ctx); + } + } while let Some(mv) = core.intents.take_move_where(scrolls) { moves.push(mv); } @@ -111,6 +120,11 @@ pub(crate) fn scroll_moves(ctx: &Context, owner: Id, quiet: bool) -> Vec<(NavMov }) } +/// Targets with queued moves, to wake settled regions containing them. +pub(crate) fn move_targets(ctx: &Context) -> Vec { + pass_state::with::(ctx, |moves| moves.0.iter().map(|(id, ..)| *id).collect()) +} + /// The smallest move of `view` that shows `rect`, per axis in screen points (positive: toward larger coordinates), and /// the part of `rect` the moved view shows: what a scroll owner moves for a reveal and passes on to the scroll owner /// around it. Along an axis the view has no extent on it moves nothing, and along an axis `rect` spans the view on diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 30ca13519..2dbb6a3d6 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -980,6 +980,12 @@ fn any_press_open(ctx: &Context) -> bool { PerViewport::::with(ctx, pass::current_viewport(ctx), |arenas| arenas.by_root.values().any(|state| state.machine.target().is_some())) } +pub(crate) fn pressed_part(ctx: &Context, owner: Id) -> Option { + PerViewport::::with(ctx, pass::current_viewport(ctx), |arenas| { + arenas.by_root.values().find_map(|state| state.machine.target().filter(|hit| hit.owner == owner).and_then(|hit| hit.part)) + }) +} + /// The arena's outcome of the running pass, idle when the root has not run yet. pub(crate) fn read_outcome(ctx: &Context, arena: ArenaId) -> Outcome { let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 788f7f7d5..c19125859 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -80,6 +80,8 @@ pub(crate) struct Board { queue: Vec, /// App-scope commands for the next `FrameOutput`. out: Vec, + /// The latest point-bearing clipboard request in each viewport. + pending_pastes: HashMap, /// App-scope commands a key pressed while only their own state disabled them, for the next `FrameOutput`. declined: Vec, /// The commands instances took since the last `FrameOutput`, in order. @@ -1018,6 +1020,42 @@ pub(crate) fn fire_from(ctx: &Context, command: &CommandRef, source: FireSource) fire_in(ctx, command, source, None) } +pub(crate) fn request_paste_at(ctx: &Context, at: egui::Pos2) { + let command = CommandRef::from(EditCommands::Paste); + let (app, instance) = with(ctx, |board| board.target_of(ctx, &command, &board.here)); + if !app && instance.is_none() { + return; + } + let (resolved, _) = resolve_in(ctx, &command, instance, Reach::Focus, None); + if !resolved.enabled { + return; + } + let target = if app { resolved.instance } else { instance }; + let fired = Fired { target, paste_at: Some(at), ..Fired::new(command, FireSource::Pointer, FirePhase::Press, pass::now(ctx)) }; + with(ctx, |board| { + board.pending_pastes.insert(pass::current_viewport(ctx), fired); + }); + crate::runtime::egui::clipboard::request_paste(ctx); +} + +pub(crate) fn has_pending_paste(ctx: &Context, viewport: ViewportId) -> bool { + with(ctx, |board| board.pending_pastes.contains_key(&viewport)) +} + +pub(crate) fn deliver_requested_paste(ctx: &Context, viewport: ViewportId, content: super::ClipContent) { + with(ctx, |board| { + if let Some(mut fired) = board.pending_pastes.remove(&viewport) { + fired.pasted = Some(content); + if fired.target.is_some() { + board.queue.push(fired); + } else { + board.out.push(fired); + } + } + }); + repaint::request_of(ctx, ViewportId::ROOT); +} + /// `fire_from` for a surface that closes before its command runs, from the window under the modal layer `layer` /// (`beneath`). pub(crate) fn fire_beneath(ctx: &Context, layer: Id, command: &CommandRef, source: FireSource) -> bool { @@ -1282,6 +1320,7 @@ pub(crate) fn begin(ctx: &Context) { alt_variant: false, time, pasted: None, + paste_at: None, }); } } @@ -1306,6 +1345,7 @@ pub(crate) fn begin(ctx: &Context) { alt_variant: hit.alt_variant, time, pasted: None, + paste_at: None, }; with(ctx, |board| board.declined.push(declined)); } @@ -1332,6 +1372,7 @@ pub(crate) fn begin(ctx: &Context) { alt_variant: hit.alt_variant, time, pasted: shortcuts.pasted.clone().filter(|_| pasted), + paste_at: None, }); } } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index f37437654..4bb6e5ce4 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -147,13 +147,15 @@ pub struct Fired { /// pastes what the event held in the pass it runs the command. `None` for every other command, and for a paste /// whose content the app reads from the clipboard itself. pub pasted: Option, + /// The screen point supplied when requesting this paste, if any. + pub paste_at: Option, } impl Fired { /// `command` fired from `source` in `phase` at the input time `time`, for the app scope (no target), without a group /// cycle, the Alt variant or paste content. pub fn new(command: CommandRef, source: FireSource, phase: FirePhase, time: f64) -> Fired { - Fired { command, target: None, source, phase, cycle: false, alt_variant: false, time, pasted: None } + Fired { command, target: None, source, phase, cycle: false, alt_variant: false, time, pasted: None, paste_at: None } } } @@ -480,6 +482,14 @@ pub fn fire(ctx: &Context, command: impl Into, source: FireSource) - board::fire_from(ctx, &command.into(), source) } +/// Requests a paste at a screen point; the delivered command carries the point with its content. The next clipboard +/// delivery in this viewport completes the request. A new request replaces any previous pending point there. +pub fn request_paste_at(ctx: &Context, at: egui::Pos2) { + if crate::runtime::measure::effect(ctx, "commands::request_paste_at") { + board::request_paste_at(ctx, at); + } +} + /// `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state /// and hint, against the instance that [`fire`] would deliver it to. A scoped command with no live instance /// resolves disabled. diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 4e4d00e0d..2db3c0308 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -154,6 +154,8 @@ pub struct Scoped { /// The innermost scrolling body that encloses the scope: a collection under it owns no scroll of its own, and /// page and end moves a component leaves untaken go to it. pub(crate) scroll_owner: Option, + /// The enclosing region's fallback collection for unused moves. + pub(crate) fallback_collection: Option, /// The axes (horizontal, vertical) the innermost scrolling body scrolls on: the room along them is unbounded, so /// a child that fills there takes its content size, except the children that fill the main axis of a body that /// shares it: they share what the view shows, at least their content size (`layout::view_room`). @@ -344,6 +346,7 @@ impl Scoped { self.roving = None; self.transform = None; self.scroll_owner = None; + self.fallback_collection = None; self.wheel = WheelScope::Plain; self.unbounded = (false, false); self.lazy = None; @@ -496,6 +499,7 @@ impl Env { offered: None, measure: None, scroll_owner: None, + fallback_collection: None, unbounded: (false, false), lazy: None, item: None, diff --git a/crates/ui-contract/src/runtime/env/view.rs b/crates/ui-contract/src/runtime/env/view.rs index 9870f3014..3643e1437 100644 --- a/crates/ui-contract/src/runtime/env/view.rs +++ b/crates/ui-contract/src/runtime/env/view.rs @@ -43,6 +43,10 @@ impl<'a> EnvView<'a> { self.scoped.scroll_owner.map(|owner| owner.id) } + pub(crate) fn fallback_collection(&self) -> Option { + self.scoped.fallback_collection + } + /// The view of the innermost scroll area around the scope. pub(crate) fn lazy_view(&self) -> Option { self.scoped.lazy diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 564c187c6..865b2ffb8 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -457,6 +457,8 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec; let (batch, visible, later) = with(ctx, viewport, |stage| { let mut claims = focused_claims(&record, stage); claims.extend(stage.captures.iter().map(|(_, chord)| *chord)); @@ -491,6 +493,12 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec, rou /// The components the running pass's intents are routed to (keys, AccessKit requests, edits): a settling region that /// holds one runs, so the component takes them. pub(crate) fn routed_to(ctx: &Context) -> Vec { - current(ctx, |stage| stage.routed.keys().flatten().copied().collect()) + let mut ids: Vec = current(ctx, |stage| stage.routed.keys().flatten().copied().collect()); + ids.extend(crate::contract::steps::scroll_owner::move_targets(ctx)); + ids } /// The member whose `Activate` the group `root` reads this pass. diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 3f3f9469b..1c1981941 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -905,6 +905,23 @@ pub fn shapes_at(ctx: &Context, at: Pos2) -> Vec<(Id, Option)> { }) } +/// The part of `owner` holding the pointer's hover or an open press in this viewport. +/// +/// An open press keeps its part while the pointer moves away, so callers can keep declaring it until release. +pub fn active_part(ctx: &Context, owner: Id) -> Option { + let viewport = pass::current_viewport(ctx); + with_hover(ctx, viewport, |under, captured| { + if captured { + return crate::primitives::sensing::pressed_part(ctx, owner); + } + let under = under?; + [under.press.click, under.press.drag, under.hover_top] + .into_iter() + .flatten() + .find_map(|(winner, _)| (winner.owner == owner).then_some(winner.part).flatten()) + }) +} + /// The clip the root of the arena `component` is in (its own, or that of the root it is a member of) was shown /// through, from its latest record in the running viewport: where its parts and members can be seen. `None` for a /// component no root recorded. diff --git a/crates/ui-contract/tests/it/collection/keys.rs b/crates/ui-contract/tests/it/collection/keys.rs index 73184a88b..c082b8282 100644 --- a/crates/ui-contract/tests/it/collection/keys.rs +++ b/crates/ui-contract/tests/it/collection/keys.rs @@ -207,3 +207,86 @@ fn end_skips_the_items_of_a_closed_group() { let rows = seen.rows.borrow(); assert!(rows.iter().all(|(key, rect)| *key < 5 && rect.is_finite()), "only shown items are built: {rows:?}"); } + +#[trial] +fn unused_moves_reach_the_regions_collection_in_either_declaration_order() { + use craft_ui::contract::{Show as _, ShowContainer as _}; + use craft_ui_test_kit::{body::Slab, contract::{Probe as Button, Seen as ButtonSeen}}; + for collection_first in [false, true] { + let (seen, layout) = (Seen::default(), Ragged { rows: vec![3, 2], hidden_from: 5 }); + let source = Count(5); + let button_seen = RefCell::new(ButtonSeen::default()); + let list_id = Id::unique("fallback collection"); + let button_id = Id::unique("fallback button"); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + Slab::new(ContainerProps::new().fallback_collection(list_id)).show(ui, |ui, _| { + let list = |ui: &mut Ui| { + seen.take(Probe::new(CollectionProps::new().select(SelectMode::Single), layout.clone(), &seen.digits) + .id(list_id).show_items(ui, &source, &mut |_, _| Row::new())); + }; + if collection_first { list(ui); } + Button::new(&button_seen).id(button_id).show(ui); + if !collection_first { list(ui); } + }); + }); + }; + frames.idle(3, &mut show); + request(&frames.ctx, FocusTarget::Id(button_id)); + frames.idle(2, &mut show); + press(&mut frames, Key::ArrowDown, &mut show); + frames.idle(2, &mut show); + assert_eq!(seen.lead_keys().len(), 1, "the move reaches the collection once across later passes"); + } +} + +#[derive(craft_ui::contract::Component)] +struct MoveControl<'a> { + #[common] + common: Common, + taken: &'a Cell, +} + +impl Component for MoveControl<'_> { + const ROLE: Role = Role::BUTTON; + type Style = PlainStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: MoveControlStyleKey) -> PlainStyle { PlainStyle::default() } + fn keys(&self) -> craft_ui::runtime::focus::KeyUse { + craft_ui::runtime::focus::KeyUse::of(craft_behavior::Input::Pointer).with_moves() + } + fn measure(&mut self, _: &craft_ui::contract::MeasureCx<'_, Self>) -> Vec2 { TILE } + fn sense(&self) -> craft_behavior::Sense { craft_behavior::Sense::CLICK | craft_behavior::Sense::FOCUS } + fn update(&mut self, cx: &mut Cx<'_, Self>) { + while cx.intents().take_move().is_some() { self.taken.set(self.taken.get() + 1); } + } + fn finish(self, cx: Cx<'_, Self>) -> Self::Output { cx.response.clone() } +} + +#[trial] +fn a_focused_control_keeps_the_moves_it_uses_before_the_fallback() { + use craft_ui::contract::{Show as _, ShowContainer as _}; + use craft_ui_test_kit::body::Slab; + let (seen, layout) = (Seen::default(), Ragged { rows: vec![3, 2], hidden_from: 5 }); + let source = Count(5); + let taken = Cell::new(0); + let list_id = Id::unique("fallback first refusal list"); + let control_id = Id::unique("fallback first refusal control"); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + Slab::new(ContainerProps::new().fallback_collection(list_id)).show(ui, |ui, _| { + MoveControl { common: Common::new(), taken: &taken }.id(control_id).show(ui); + seen.take(Probe::new(CollectionProps::new().select(SelectMode::Single), layout.clone(), &seen.digits) + .id(list_id).show_items(ui, &source, &mut |_, _| Row::new())); + }); + }); + frames.idle(3, &mut show); + request(&frames.ctx, FocusTarget::Id(control_id)); + frames.idle(2, &mut show); + press(&mut frames, Key::ArrowDown, &mut show); + frames.idle(2, &mut show); + assert_eq!(taken.get(), 1); + assert!(seen.lead_keys().is_empty(), "a move used by the control never reaches the fallback"); +} diff --git a/crates/ui-contract/tests/it/runtime/paste.rs b/crates/ui-contract/tests/it/runtime/paste.rs index 3b89e812b..78286993d 100644 --- a/crates/ui-contract/tests/it/runtime/paste.rs +++ b/crates/ui-contract/tests/it/runtime/paste.rs @@ -5,6 +5,25 @@ use craft_ui::runtime::frame::take_output; use craft_ui::testing::{Frames, trial}; use egui::{Event, Ui}; +#[trial] +fn requested_paste_keeps_its_point_until_clipboard_delivery() { + let mut frames = Frames::new(); + let mut show = |_: &mut Ui| {}; + frames.idle(2, &mut show); + take_output(&frames.ctx); + let point = egui::pos2(120.0, 180.0); + craft_ui::runtime::commands::request_paste_at(&frames.ctx, point); + frames.idle(1, &mut show); + frames.frame(vec![Event::Paste("content".into())], &mut show); + let mut delivered = Vec::new(); + for _ in 0..3 { + delivered.extend(take_output(&frames.ctx).fired.into_iter().filter(|fired| fired.pasted.is_some())); + frames.idle(1, &mut show); + } + assert_eq!(delivered.len(), 1); + assert_eq!(delivered[0].paste_at, Some(point)); +} + /// The content used to be dropped with the event, and the platform's offer of it lapsed a pass before the command ran, /// so the app's paste found nothing. #[trial] diff --git a/crates/ui-contract/tests/it/runtime/pointer.rs b/crates/ui-contract/tests/it/runtime/pointer.rs index f74070da2..72d0f38ba 100644 --- a/crates/ui-contract/tests/it/runtime/pointer.rs +++ b/crates/ui-contract/tests/it/runtime/pointer.rs @@ -10,6 +10,26 @@ use std::rc::Rc; const BACKGROUND: PartKey = PartKey::new("background"); +/// A hover-revealed part must remain identifiable when a drag leaves its shape. +#[trial] +fn active_part_survives_a_drag_outside_its_shape() { + let area = rect(100.0, 100.0, 80.0, 80.0); + let root = ProbeRoot::new("active-part", area, Sense::empty()) + .part(ProbePart::new(BACKGROUND, area, Sense::DRAG)); + let (mut show_frame, _) = scene(vec![root]); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + let point = area.center(); + frames.frame(vec![pointer::moved(point)], &mut show_frame); + assert_eq!(craft_ui::runtime::pointer::active_part(&frames.ctx, ProbeRoot::id("active-part")), Some(BACKGROUND.into())); + frames.frame(vec![pointer::press(point)], &mut show_frame); + frames.frame(vec![pointer::moved(point + Vec2::new(150.0, 0.0))], &mut show_frame); + assert_eq!(craft_ui::runtime::pointer::active_part(&frames.ctx, ProbeRoot::id("active-part")), Some(BACKGROUND.into())); + frames.frame(vec![pointer::release(point + Vec2::new(150.0, 0.0))], &mut show_frame); + frames.idle(1, &mut show_frame); + assert_eq!(craft_ui::runtime::pointer::active_part(&frames.ctx, ProbeRoot::id("active-part")), None); +} + fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect { Rect::from_min_size(Pos2::new(x, y), Vec2::new(w, h)) }