From abf5962ac41da6c681b2b81ae7a86d1c369c0978 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 10:17:17 +0000 Subject: [PATCH] Hover follows the press winner: one resolution of what lies under the pointer pointer::Under, found once per pass at the begin hook over last pass's shape record, answers both the press and the hover: the press winners hover, plus the topmost shape when it takes no press; roots with a shape under the point contain the pointer. While a press is open only its target hovers. Arenas read their hover and their press hit from it; the per-root layer check and the arena's own hover and press resolves are gone, and withheld members are dropped in the one resolution. Toasts pause on contains_pointer. Trials for hover/press agreement, nested controls, held presses and one resolution per pass. --- .../ui-contract/src/contract/body/window.rs | 8 +- .../ui-contract/src/contract/items/hooks.rs | 2 +- .../ui-contract/src/contract/items/members.rs | 4 +- .../ui-contract/src/contract/items/press.rs | 7 +- crates/ui-contract/src/primitives/sensing.rs | 173 ++++++------ .../ui-contract/src/runtime/egui/response.rs | 13 +- crates/ui-contract/src/runtime/pointer.rs | 267 +++++++++++++----- crates/ui-contract/src/testing/fixture.rs | 2 +- crates/ui-contract/src/testing/pointer.rs | 6 + crates/ui-contract/src/testing/sensing.rs | 10 + .../ui-contract/tests/it/runtime/pointer.rs | 151 +++++++++- crates/ui-widgets/src/notices/toasts.rs | 2 +- 12 files changed, 449 insertions(+), 196 deletions(-) diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index f06a06628..9fd863124 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -7,7 +7,7 @@ use crate::contract::overlay::{PlacementChange, PlacementKind, ResizeEdges}; use crate::contract::{Container, ContainerProps, Cx, Mount, PartsCx}; use crate::runtime::commands::{self, CommandSet as _, WindowCommand}; use crate::runtime::egui::pass; -use crate::runtime::egui::{input, viewports}; +use crate::runtime::egui::viewports; use crate::runtime::env::{EnvView, ShellEntry}; use crate::runtime::memory::sub; use crate::runtime::windows::{self, ResizeEdge, WindowAction, WindowHit}; @@ -674,9 +674,9 @@ impl BodyHooks<'_> { return; } let takes_press = band.hovered - && pointer::pass_pointer(ctx).hover.is_some_and(|at| { - let (click, drag) = input::hit_targets(ctx); - pointer::press_winner(ctx, at, pointer::PressTargets { click, drag }) + && pointer::with_hover(ctx, pass::current_viewport(ctx), |under, _| { + under + .and_then(|under| under.press.click.or(under.press.drag)) .is_some_and(|(winner, root)| root == cx.core.id && winner.part.is_some_and(|part| part.key == MOVE_BAND)) }); let this_pass = viewports::pass_number(ctx); diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 1e55f76a7..fbdeaeba8 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -501,7 +501,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } // The pointer counts as over a row only while the sensing pass puts it on this collection, so a popup or another // widget above it takes the hover as it does for the rows' parts. - let hover_at = crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)).hover.and(ctx.pointer_latest_pos()); + let hover_at = ctx.pointer_latest_pos().filter(|_| crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)).hover.any()); let menu_open = self.drags.menu.is_some() && crate::contract::overlay::container_open::opened_from(&ctx, cx.core.id); // A double click on a column's edge fits the column to its widest cell among the rows built here, in view. let fit = self.header.fit.as_ref().map(|(column, _)| column.clone()); diff --git a/crates/ui-contract/src/contract/items/members.rs b/crates/ui-contract/src/contract/items/members.rs index cf7433882..57f68e22b 100644 --- a/crates/ui-contract/src/contract/items/members.rs +++ b/crates/ui-contract/src/contract/items/members.rs @@ -47,7 +47,7 @@ impl<'r, C: Collection> ItemsHooks<'_, 'r, C> { ) { let enabled = cx.core.resolved.enabled; let parent = access::fold::owner_of(ctx, id).unwrap_or(id); - let hover = sensing::read_outcome(ctx, ArenaId::new(id)).hover.map(|hit| hit.owner); + let hover = sensing::read_outcome(ctx, ArenaId::new(id)).hover; let mut prepared: Vec>> = members .into_iter() .map(|member| { @@ -55,7 +55,7 @@ impl<'r, C: Collection> ItemsHooks<'_, 'r, C> { let member_id = item_id(id, &key); let on = enabled && item.common_mut(Internal::new()).enabled.unwrap_or(true); let item_sense = item.sense(); - let prep = run::member_prepare(ui, env, member_id, row, hover == Some(member_id), item); + let prep = run::member_prepare(ui, env, member_id, row, hover.find(|hit| hit.owner == member_id).is_some(), item); let member = Member { at, key, item: (), row, clip, flags, position, renaming, openers, shown }; (member, member_id, on, item_sense, prep) }) diff --git a/crates/ui-contract/src/contract/items/press.rs b/crates/ui-contract/src/contract/items/press.rs index 79ddf7268..a9c7d67f1 100644 --- a/crates/ui-contract/src/contract/items/press.rs +++ b/crates/ui-contract/src/contract/items/press.rs @@ -222,7 +222,8 @@ impl ItemsHooks<'_, '_, C> { && start.button == craft_behavior::PointerButton::Primary && crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)) .hover - .is_none_or(|hit| hit.part.is_none() || !hit.sense.takes_press()) + .find(|hit| hit.part.is_some() && hit.sense.takes_press()) + .is_none() && let Some(row) = layout.hit(local(pos), offset).filter(|&row| self.source.enabled(row) && layout.shown(row)) { let request = self.menu_request(layout, Placement { rect, offset, rtl }, row, local(pos)); @@ -280,7 +281,7 @@ impl ItemsHooks<'_, '_, C> { let hover = crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)).hover; let menu_at = if released.release == Some(craft_behavior::PointerButton::Secondary) && cx.core.response.hovered() - && hover.is_none_or(|hit| hit.part.is_none() || !hit.sense.takes_press() || hit.sense.contains(Sense::PICKS_ITEM)) + && hover.find(|hit| hit.part.is_some() && hit.sense.takes_press() && !hit.sense.contains(Sense::PICKS_ITEM)).is_none() { released.pos.filter(|pos| rect.contains(xf.map_or(*pos, |map| map.to_layer(*pos)))) } else { @@ -364,7 +365,7 @@ impl ItemsHooks<'_, '_, C> { let on_part = |hit: Option| hit.is_some_and(|hit| hit.owner == opener.item && hit.part == Some(opener.part)); let view = response::MemberView { - hovered: on_part(outcome.hover), + hovered: outcome.hover.find(|hit| on_part(Some(*hit))).is_some(), press: response::PressView { pressed: on_part(outcome.target) && outcome.phase.is_some_and(|phase| phase.button_down()), clicked: on_part(outcome.activated), diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 0b57b2820..5e9471488 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -1,8 +1,9 @@ //! The sensing core (1.9, 8.2, 8.3): the arena's registrations, the press lifecycle over last pass's shapes, and //! the part results and member responses built from them. //! -//! A component's root senses through one egui widget; its parts and its members have none. The root resolves -//! hover and presses itself against the shapes registered last pass, so the winner never depends on show order. +//! A component's root senses through one egui widget; its parts and its members have none. What lies under the +//! pointer is resolved once per point for the whole viewport, over the shapes registered last pass (`pointer::Under`), +//! and every root reads its hover and its press from that answer, so the winner never depends on show order. //! Every root runs the lifecycle, arena root or not: a leaf is an arena of its own id with no members. use crate::runtime::edit::{RemovalWatch, gesture_key}; @@ -15,8 +16,7 @@ use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::pointer; use crate::runtime::pointer::PassPointer; use craft_behavior::{ - Cursor, HitLevel, HitPriority, HitShape, PartKey, PartRef, PassInput, PointerSample, PressMachine, PressPhase, PressState, ResolveFor, Sense, - Shape, resolve_mapped, + Cursor, HitLevel, HitPriority, HitShape, PartKey, PartRef, PassInput, PointerSample, PressMachine, PressPhase, PressState, Sense, Shape, Winner, }; use craft_keymap::Mods; use craft_theme::Flags; @@ -173,16 +173,11 @@ impl MemberDecl { } } -/// What a root registers at step 8: its rect and its own sense. +/// What a root registers at step 8: its id and rect. #[derive(Clone, Copy, Debug)] struct RootInfo { id: Id, rect: Rect, - /// The part of `rect` inside the root's clip: where its own background lies. - shown: Rect, - /// The root's clip: where its parts and members can be seen. - clip: Rect, - own_sense: Sense, } /// A shape's owner and, for a part, its key. @@ -200,11 +195,43 @@ impl Hit { } } +impl From> for Hit { + fn from(winner: Winner) -> Self { + Hit { owner: winner.owner, part: winner.part, sense: winner.sense, local: winner.local } + } +} + +/// The arena's shapes that show hover this pass, from what lies under the pointer (`pointer::Under`): the shape a +/// press at the pointer goes to, and the topmost shape under the pointer when it is the arena's and takes no press. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Hovered { + press: Option, + only: Option, +} + +impl Hovered { + /// The hovered shape `pick` takes, the press's first. + pub(crate) fn find(&self, pick: impl Fn(&Hit) -> bool) -> Option { + self.press.into_iter().chain(self.only).find(|hit| pick(hit)) + } + + /// Whether any shape of the arena shows hover. + pub(crate) fn any(&self) -> bool { + self.press.is_some() || self.only.is_some() + } + + fn filter(self, keep: impl Fn(&Hit) -> bool) -> Self { + Hovered { press: self.press.filter(&keep), only: self.only.filter(&keep) } + } +} + /// What the arena resolved this pass; the root computes it once, members and the root read it. #[derive(Clone, Copy, Debug, Default)] pub(crate) struct Outcome { pass: u64, - pub hover: Option, + pub hover: Hovered, + /// A shape of the arena lies under the pointer, on top or not. + pub contains: bool, /// The press winner while a press is open, or the one released or cancelled this pass. pub target: Option, pub phase: Option, @@ -225,7 +252,6 @@ struct ArenaState { /// The stack position of the root's own `over` parts: above the members its body showed and below the ones /// `paint_over` shows (`place_over_widgets`). Above everything until the owner has placed them. own_over_at: u32, - previous_own_over_at: u32, /// The senses and bounds of the members that joined this pass and last pass. union_sense: Sense, previous_union_sense: Sense, @@ -278,7 +304,6 @@ fn rotate(state: &mut ArenaState, pass_nr: u64) { state.members.clear(); std::mem::swap(&mut state.previous_own, &mut state.own); state.own.clear(); - state.previous_own_over_at = state.own_over_at; state.own_over_at = u32::MAX; state.previous_union_sense = std::mem::take(&mut state.union_sense); state.pass = pass_nr; @@ -332,23 +357,6 @@ fn background_shape(root: Id, rect: Rect, sense: Sense) -> Shape { Shape::new(rect.into(), sense, root, None, HitPriority::new(HitLevel::Background, 0), 0) } -/// The shapes of last pass in resolution order: the root's own background over its shown rect, which hovers and takes -/// a press when the root senses one itself, own parts, then members in show order, each member's `over` parts above -/// the members its body showed, and the own `over` parts at their position among them. `members` is false while the -/// root's host withholds its members (`pointer::withhold_members`). -fn candidates(state: &ArenaState, members: bool, target: f32) -> Vec> { - let root = state.root.map_or(Id::NULL, |root| root.id); - let background = state.root.map(|info| background_shape(info.id, info.shown, info.own_sense | Sense::HOVER)); - let mut shapes: Vec> = background.into_iter().chain(own_shapes(&state.previous_own, root, target)).collect(); - let shown = if members { state.previous.as_slice() } else { &[] }; - for (at, member) in shown.iter().enumerate() { - shapes.extend(member_shapes(member, member_position(at), target)); - shapes.extend(member_over_shapes(member, target)); - } - shapes.extend(own_over_shapes(&state.previous_own, root, state.previous_own_over_at, target)); - shapes -} - /// The members of `arena` in `viewport` as of its latest run: while the root's run of this pass is under way, the /// members of last pass and those registered so far; empty for an arena that has not run. A read creates no arena. pub(crate) fn members(ctx: &Context, viewport: ViewportId, arena: ArenaId) -> SmallVec<[Id; 8]> { @@ -363,18 +371,6 @@ pub(crate) fn members(ctx: &Context, viewport: ViewportId, arena: ArenaId) -> Sm }) } -/// The clip of the arena `component` is in (its own, or the one of the root it is a member of), as that root -/// registered it in its latest run in the current viewport: where its parts and members can be seen. `None` for a -/// component in no arena that has run. -#[cfg(feature = "testing")] -pub(crate) fn arena_clip(ctx: &Context, component: Id) -> Option { - PerViewport::::with(ctx, pass::current_viewport(ctx), |arenas| { - let joined = |state: &ArenaState| state.members.iter().chain(&state.previous).any(|member| member.id == component); - let state = arenas.by_root.get(&component).or_else(|| arenas.by_root.values().find(|state| joined(state)))?; - state.root.map(|info| info.clip) - }) -} - /// Whether a member of the arena root `arena` (a canvas control in a canvas, say) has a running gesture, in /// `viewport`: begun and not yet committed, cancelled or removed. It reads each member's own gesture record, so a /// reader before or after the arena's pass reads the same fact. @@ -429,7 +425,7 @@ fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], }); } -/// A replayed root's step-8 registration: its own parts, rect, clip, widgets, layer and sense, with no press run. +/// A replayed root's step-8 registration: its own parts, rect, widgets, layer and sense, with no press run. fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistration) { journal_root(ctx, arena, registration.info, ®istration.own, ®istration.widgets, (registration.layer, registration.sense)); let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); @@ -604,9 +600,11 @@ pub(crate) fn sense_root(ui: &Ui, spec: RootSpec<'_>) -> RootResult { widgets.push(id); } widgets.extend(over_parts(spec.own).map(|part| over_widget(spec.id, part))); - let background = (!spec.own_sense.is_empty()).then(|| background_shape(spec.id, spec.rect, spec.own_sense)); + // The root's background lies below its parts and members and hovers wherever nothing of the root above it takes + // the pointer; it takes a press when the root senses one itself. + let background = background_shape(spec.id, spec.rect, spec.own_sense | Sense::HOVER); pointer::record_widgets_in(ctx, read.viewport, layer, spec.id, &widgets, sense.contains(Sense::CLICK)); - let info = RootInfo { id: spec.id, rect: spec.rect, shown, clip, own_sense: spec.own_sense }; + let info = RootInfo { id: spec.id, rect: spec.rect }; journal_root(ctx, arena, info, spec.own, &widgets, (layer, sense)); // The parts last pass registered, which this pass's results read. let known = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { @@ -623,12 +621,19 @@ pub(crate) fn sense_root(ui: &Ui, spec: RootSpec<'_>) -> RootResult { } known_in(state, spec.id) }); - pointer::record_shapes_in(ctx, read.viewport, layer, spec.id, clip, own_shapes(spec.own, spec.id, read.target()).chain(background)); + pointer::record_shapes_in( + ctx, + read.viewport, + layer, + spec.id, + clip, + std::iter::once(background).chain(own_shapes(spec.own, spec.id, read.target())), + ); let mut response = response; let outcome = outcome_in(ctx, &read, arena, layer, spec.enabled, sense); - // The root is hovered while the arena's hover resolve finds anything under the pointer: its background, its parts - // or its members, whichever egui widget lies on top there. - response::hover_flags(&mut response, outcome.hover.is_some()); + // The root is hovered while a shape of its arena shows hover (`pointer::Under`): its background, a part or a member; + // it contains the pointer while any shape of the arena lies under it. + response::hover_flags(&mut response, outcome.hover.any(), outcome.contains); // The root's response reports the presses on the root and on every part of its own, whichever egui widget took // them; the part results say which part. A member reports in its own response. let on_root = |hit: &Hit| hit.owner == spec.id; @@ -791,7 +796,7 @@ pub(crate) fn sense_members(ui: &Ui, arena: ArenaId, specs: &[MemberSpec<'_>]) - fn member_view(outcome: &Outcome, id: Id, local: bool, pointer_pos: Option) -> MemberView { MemberView { - hovered: outcome.hover.is_some_and(|hit| hit.owner == id), + hovered: outcome.hover.find(|hit| hit.owner == id).is_some(), press: press_view(outcome, |hit| hit.owner == id, |hit| hit.owner == id && hit.part.is_none()), pointer: pointer_pos.map(|at| if local { outcome.xf.map_or(at, |map| map.to_layer(at)) } else { at }), } @@ -809,34 +814,6 @@ fn press_view(outcome: &Outcome, holds: impl Fn(&Hit) -> bool, clicks: impl Fn(& } } -/// The resolve rule over last pass's shapes at `point`. -fn resolve_in(state: &ArenaState, members: bool, xf: Option, point: Pos2, kind: ResolveFor, target: f32) -> Option { - let shapes = candidates(state, members, target); - let won = resolve_mapped(&shapes, point, kind, |p| xf.map_or(p, |map| map.to_layer(p))); - won.map(|winner| Hit { owner: winner.owner, part: winner.part, sense: winner.sense, local: winner.local }) -} - -/// The press's winner at `point`. Past the root's clip, where only automation presses (a document point an agent -/// names off the window), the winner takes the press only when some of it shows inside the clip: a part the clip hides -/// wholly (a handle past the window's edge) is not pressed, and nothing under it is either. -fn resolve_press_in(state: &ArenaState, members: bool, xf: Option, point: Pos2, target: f32) -> Option { - let shapes = candidates(state, members, target); - let won = resolve_mapped(&shapes, point, ResolveFor::Press, |p| xf.map_or(p, |map| map.to_layer(p)))?; - let clip = state.root.map_or(Rect::NOTHING, |root| root.clip); - if !clip.contains(point) { - let shape = &shapes[won.index]; - let bounds = shape.shape.bounds(); - let bounds = match xf.filter(|_| shape.local) { - Some(map) => Rect::from_two_pos(map.to_screen(bounds.min), map.to_screen(bounds.max)), - None => bounds, - }; - if !bounds.intersects(clip) { - return None; - } - } - Some(Hit { owner: won.owner, part: won.part, sense: won.sense, local: won.local }) -} - /// Runs the press lifecycle for this pass, once: later calls in the pass return the same outcome. A repeated /// pass has no events, so phases hold and a release, click or activation does not repeat. `union_sense` is /// what the root's egui widgets sense. @@ -847,10 +824,10 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab return outcome; } let pass_pointer = &*read.pointer; - let (slop, delta, pos, buttons, target) = - 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 (slop, delta, pos, buttons) = pass_pointer + .frame + .as_ref() + .map_or((0.0, egui::Vec2::ZERO, None, craft_behavior::Buttons::empty()), |frame| (frame.slop, frame.delta, frame.pos, frame.buttons)); 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)) @@ -858,12 +835,19 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab 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)); - let hover_layer_ok = top.is_some_and(|top| top == layer || Some(top) == body_layer); - let members = !pointer::members_withheld(ctx, read.viewport, pass_nr, arena.0); + // What the viewport's one resolution of the pointer puts on this arena (`pointer::Under`): hover shows where a press + // would go. + let (under, contains, captured) = pointer::with_hover(ctx, read.viewport, |under, captured| { + let hovered = under.map_or(Hovered::default(), |under| Hovered { + press: under.press.hit_of(arena.0).map(Hit::from), + only: under.hover_only_of(arena.0).map(Hit::from), + }); + (hovered, under.is_some_and(|under| under.contains(arena.0)), captured) + }); let (mut cancelled, mut release_held) = (false, false); let outcome = with_arena(ctx, arena, pass_nr, |state| { + // A press open when the pass began, on another arena, takes the hover from this one. + let others_press = captured && state.machine.target().is_none(); let pos = pos.unwrap_or(Pos2::ZERO); let input = PassInput::new( &pass_pointer.events, @@ -889,7 +873,8 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab } else { true }; - let won_kinds = root.map_or(Sense::empty(), |own| pointer::press_winners(ctx, at, targets).senses_of(own)); + let winners = pointer::press_winners(ctx, at, targets); + let won_kinds = root.map_or(Sense::empty(), |own| winners.senses_of(own)); let allowed = crate::runtime::sampler::root_takes_press(ctx, root, layer, at, untargeted) && !won_kinds.is_empty(); if !enabled || !allowed { return None; @@ -897,7 +882,7 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab // egui gives no click target where a drag-only widget is on top (a resize grip over a layer's or a // window's edge): a root under a raw egui one keeps its click there, but a drag is that widget's. let drag_elsewhere = targets.click.is_none() && targets.drag.is_some_and(|id| pointer::foreign_target(ctx, id)); - let won = resolve_press_in(state, members, xf, at, target); + let won = root.and_then(|own| winners.hit_of(own)).map(Hit::from); // The kinds of press another root won are not this one's. let lost = (Sense::CLICK | Sense::DRAG).difference(won_kinds); won.map(|hit| { @@ -910,14 +895,14 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab let open = machine.target(); let dragging = step.dragging; state.machine = machine; - let under = pass_pointer.hover.filter(|_| hover_layer_ok).and_then(|at| resolve_in(state, members, xf, at, ResolveFor::Hover, target)); // While a press is open only its target hovers, and only while the pointer is over it or dragging. let hover = match open { - Some(target) if dragging => Some(target), - Some(target) => under.filter(|under| under.same(&target)), + Some(target) if dragging => Hovered { press: Some(target), only: None }, + Some(target) => under.filter(|hit| hit.same(&target)), + None if others_press => Hovered::default(), None => under, }; - let outcome = Outcome { pass: pass_nr, hover, target: step.target, phase: step.phase, dragging, activated: step.activated, xf }; + let outcome = Outcome { pass: pass_nr, hover, contains, target: step.target, phase: step.phase, dragging, activated: step.activated, xf }; state.outcome = Some(outcome); outcome }); @@ -1028,7 +1013,7 @@ fn part_press_in( let is_known = known.contains(&(part.key, part.index)); let mine = |hit: &Hit| hit.owner == owner && hit.part == Some(part); let won = outcome.target.filter(|target| is_known && mine(target)); - let hover = outcome.hover.filter(|hit| is_known && mine(hit)); + let hover = outcome.hover.find(|hit| is_known && mine(hit)); let hovered = hover.is_some(); let hover_pos = hover.zip(at).map(|(hit, at)| if hit.local { outcome.xf.map_or(at, |map| map.to_layer(at)) } else { at }); let phase = match (won, outcome.phase) { @@ -1046,7 +1031,7 @@ fn shape_press_in(outcome: &Outcome, mods: Mods, sample: Option, let won = outcome.target.filter(|target| target.owner == owner && target.part.is_none()); let phase = match (won, outcome.phase) { (Some(target), Some(phase)) => in_owner_space(phase, &target, outcome.xf), - _ if outcome.hover.is_some_and(|hit| hit.owner == owner && hit.part.is_none()) => PressPhase::Hover, + _ if outcome.hover.find(|hit| hit.owner == owner && hit.part.is_none()).is_some() => PressPhase::Hover, _ => PressPhase::Idle, }; let captured = won.is_some() && phase.is_drag(); diff --git a/crates/ui-contract/src/runtime/egui/response.rs b/crates/ui-contract/src/runtime/egui/response.rs index b62abdd66..342292d53 100644 --- a/crates/ui-contract/src/runtime/egui/response.rs +++ b/crates/ui-contract/src/runtime/egui/response.rs @@ -107,14 +107,13 @@ fn member_on(ctx: &egui::Context, layer_id: LayerId, clip: Rect, id: Id, rect: R response } -/// Sets the hover of a root's `Response` from the framework's hover resolve, in place of egui's: egui reports a -/// widget that senses a click hovered only where it is egui's click winner, and a root's widget senses the clicks -/// of its parts and members. -pub(crate) fn hover_flags(response: &mut Response, hovered: bool) { +/// Sets the hover of a root's `Response` from what lies under the pointer (`pointer::Under`), in place of egui's: egui +/// reports a widget that senses a click hovered only where it is egui's click winner, and a root's widget senses the +/// clicks of its parts and members. `hovered`: a shape of the root's arena shows hover; `contains`: one lies under the +/// pointer, on top or not. +pub(crate) fn hover_flags(response: &mut Response, hovered: bool, contains: bool) { response.flags.set(Flags::HOVERED, hovered); - if hovered { - response.flags |= Flags::CONTAINS_POINTER; - } + response.flags.set(Flags::CONTAINS_POINTER, contains); } /// Sets the press flags of a component's `Response` from the press lifecycle, in place of egui's: a component clicks diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 9b338c23c..dc6de4ed8 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -14,6 +14,7 @@ use craft_behavior::{ use craft_keymap::Mods; use craft_theme::HitSizes; use egui::{Context, Id, IdMap, Pos2, Rect, Vec2, ViewportId}; +use smallvec::SmallVec; use std::collections::HashMap; use std::sync::Arc; @@ -133,9 +134,17 @@ pub(crate) struct Shapes { last_bodies: BodyRecord, /// The paint order the running pass's next registration takes. next: u32, - /// The press winner found over `last`, for the point and targets it was asked for: every root asks for the - /// same press. - winner: Option<(Pos2, PressTargets, PressWinners)>, + /// What lies under the pass's hover point, found over `last` at the begin hook with the pass's egui targets: + /// every root's hover reads it, and a press at the same point and targets reuses it. + hover: Option<(Pos2, PressTargets, Under)>, + /// A press was open when the pass began: only its target hovers. + captured: bool, + /// What lies under another point a press asked for in the pass, with its targets: every root asks for the same + /// press. + winner: Option<(Pos2, PressTargets, Under)>, + /// The resolutions the running pass made (`find_under`), for the count trials. + #[cfg(feature = "testing")] + resolutions: u32, } /// The begin hook (H5): converts the pass's pointer input. @@ -199,12 +208,27 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { focus_lost: read.focus_lost, stirred: read.stirred, }; + let hover_at = pass_pointer.hover; PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { shapes.last = std::mem::take(&mut shapes.this); shapes.last_bodies = std::mem::take(&mut shapes.this_bodies); shapes.next = 0; + shapes.hover = None; shapes.winner = None; + #[cfg(feature = "testing")] + { + shapes.resolutions = 0; + } + }); + // The pointer's hover is resolved once for the pass, over last pass's complete record, with the targets egui's hit + // test gives at the pointer now. + let hover_targets = PressTargets { click: hits.0, drag: hits.1 }; + let hover = hover_at.map(|at| (at, hover_targets, find_under(ctx, viewport, at, hover_targets))); + let captured = press_captured(ctx); + PerViewport::::with(ctx, viewport, |shapes| { + shapes.hover = hover; + shapes.captured = captured; }); } @@ -296,10 +320,13 @@ pub fn withhold_members(ctx: &Context, root: Id, withheld: bool) { }); } -/// Whether the arena of `root` resolves the running pass of `viewport` (`pass_nr`) without its members: its host +/// The arena roots of `viewport` whose presses and hover the running pass resolves without their members: their host /// asked so in this pass or the one before, the pass whose shapes this one resolves over. -pub(crate) fn members_withheld(ctx: &Context, viewport: ViewportId, pass_nr: u64, root: Id) -> bool { - PerViewport::::with(ctx, viewport, |memory| memory.withheld.get(&root).is_some_and(|asked| asked + 1 >= pass_nr)) +fn withheld_roots(ctx: &Context, viewport: ViewportId) -> SmallVec<[Id; 2]> { + let pass_nr = pass::pass_nr(ctx, viewport); + PerViewport::::with(ctx, viewport, |memory| { + memory.withheld.iter().filter(|(_, asked)| **asked + 1 >= pass_nr).map(|(root, _)| *root).collect() + }) } /// Registers how the viewport tells that a press is captured. Sensing owns the arenas' machines. @@ -529,15 +556,12 @@ pub(crate) fn made_by_component(ctx: &Context, viewport: ViewportId, id: Id) -> }) } -/// The roots a press at `at` (screen points) goes to, each with the shape of it that wins it: its click's and its -/// drag's (8.3, H7). On the topmost layer under the press, each root recorded there in the last pass resolves its own -/// shapes by the arena rule, and the roots rank by their winning shapes' place in the pass's paint order, top first. The -/// top one takes every kind of press its shape senses. Under a top shape that only drags (a window's resize grip), the -/// click goes to the first root below whose shape clicks; under one that only clicks (a button), the drag goes to the -/// first root below whose shape drags, when that root takes no click anywhere. A transformed body's layer shows its root's own shapes -/// beneath everything on it. A shape counts only where its clip shows it; at a point no clip on the layer holds (one -/// automation names past the window), a shape counts when some of it shows inside its clip. A press egui's hit test -/// gives to a widget no component registered (a raw egui widget on top) goes to no root. +/// The roots a press at a point goes to, each with the shape of it that wins it: its click's and its drag's (8.3, H7). +/// Among the roots under the point ([`Under`]), each resolves its own shapes by the arena rule, and the roots rank by +/// their winning shapes' place in the pass's paint order, top first. The top one takes every kind of press its shape +/// senses. Under a top shape that only drags (a window's resize grip), the click goes to the first root below whose +/// shape clicks; under one that only clicks (a button), the drag goes to the first root below whose shape drags, when +/// that root takes no click anywhere. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(crate) struct PressWinners { pub click: Option<(Winner, Id)>, @@ -556,18 +580,62 @@ impl PressWinners { } sense } + + /// The shape of `root` a press goes to: its click's, else its drag's. + pub(crate) fn hit_of(&self, root: Id) -> Option> { + [self.click, self.drag].into_iter().flatten().find(|(_, owner)| *owner == root).map(|(winner, _)| winner) + } } +/// What lies under one point of a viewport, from last pass's shape record: the one answer a press and the hover read +/// (8.3). On the topmost layer under the point, the roots recorded there in the last pass stack in paint order; a +/// transformed body's layer shows its root's own shapes beneath everything on it. A shape counts only where its clip +/// shows it; at a point no clip on the layer holds (one automation names past the window), a shape counts when some of +/// it shows inside its clip. The members of an arena whose host withholds them (`withhold_members`) do not count. +/// Where egui's hit test gives the point to a widget no component registered (a raw egui widget on top), nothing is +/// under it. +/// +/// Hover shows where a press goes: the press winners' shapes hover, and so does the topmost shape under the point when +/// it takes no press (a label with a tooltip over a clickable row). A shape that takes a press and loses it does not. +#[derive(Clone, Debug, Default)] +pub(crate) struct Under { + /// The roots a press at the point starts on. + pub press: PressWinners, + /// The topmost shape under the point, with its root, when it takes no press. + pub hover_only: Option<(Winner, Id)>, + /// Every root with a shape under the point, on top or not: the roots that contain the pointer. + pub over: SmallVec<[Id; 4]>, +} + +impl Under { + /// The topmost shape under the point when it is `root`'s and takes no press. + pub(crate) fn hover_only_of(&self, root: Id) -> Option> { + self.hover_only.filter(|(_, owner)| *owner == root).map(|(winner, _)| winner) + } + + /// Whether a shape of `root` lies under the point. + pub(crate) fn contains(&self, root: Id) -> bool { + self.over.contains(&root) + } +} + +/// The press winners at `at` for egui's press targets `targets` ([`Under::press`]): the pass's hover answer when the +/// press is at the hover point, else found once per point and targets. pub(crate) fn press_winners(ctx: &Context, at: Pos2, targets: PressTargets) -> PressWinners { let viewport = pass::current_viewport(ctx); let found = PerViewport::::with(ctx, viewport, |record| { - record.winner.filter(|(point, asked, _)| *point == at && *asked == targets).map(|(_, _, found)| found) + [&record.hover, &record.winner] + .into_iter() + .flatten() + .find(|(point, asked, _)| *point == at && *asked == targets) + .map(|(_, _, under)| under.press) }); if let Some(found) = found { return found; } - let found = find_press_winners(ctx, viewport, at, targets); - PerViewport::::with(ctx, viewport, |record| record.winner = Some((at, targets, found))); + let under = find_under(ctx, viewport, at, targets); + let found = under.press; + PerViewport::::with(ctx, viewport, |record| record.winner = Some((at, targets, under))); found } @@ -578,14 +646,30 @@ pub(crate) fn press_winner(ctx: &Context, at: Pos2, targets: PressTargets) -> Op winners.click.or(winners.drag) } -fn find_press_winners(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTargets) -> PressWinners { +/// Reads what lies under the running pass's hover point in `viewport` (`None` while the pointer is not in the window), +/// and whether a press was open when the pass began: then only that press's target hovers. `f` runs inside the shape +/// record's borrow. +pub(crate) fn with_hover(ctx: &Context, viewport: ViewportId, f: impl FnOnce(Option<&Under>, bool) -> R) -> R { + PerViewport::::with(ctx, viewport, |record| f(record.hover.as_ref().map(|(_, _, under)| under), record.captured)) +} + +/// The resolutions of what lies under a point the running viewport's latest pass made. +#[cfg(feature = "testing")] +pub(crate) fn resolutions(ctx: &Context) -> u32 { + PerViewport::::with(ctx, pass::current_viewport(ctx), |record| record.resolutions) +} + +fn find_under(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTargets) -> Under { + #[cfg(feature = "testing")] + PerViewport::::with(ctx, viewport, |record| record.resolutions += 1); let Some(layer) = areas::layer_at(ctx, at).or_else(|| layer_past_window(ctx, viewport, at)) else { - return PressWinners::default(); + return Under::default(); }; let to_layer = |layer: Layer| areas::layer_map(ctx, layer).map_or(at, |map| map.to_layer(at)); let body = PerViewport::::with(ctx, viewport, |record| record.last_bodies.get(&layer).copied()); let beneath = body.map(|(root, parent)| (root, parent, to_layer(parent))); let on_layer = to_layer(layer); + let withheld = withheld_roots(ctx, viewport); PerViewport::::with(ctx, viewport, |record| { // Bottom to top: the body layer's root on its own layer, then the roots on the layer in paint order. let mut stack: Vec<(u8, Id, &RootRecord, Pos2)> = Vec::new(); @@ -599,62 +683,88 @@ fn find_press_winners(ctx: &Context, viewport: ViewportId, at: Pos2, targets: Pr } let shown = stack.iter().any(|(_, _, entry, point)| entry.placed.iter().any(|placed| placed.clip.contains(*point))); if targets.click.is_some_and(|widget| !registered_in(&record.last, widget)) { - return PressWinners::default(); + return Under::default(); } - let mut ranked: Vec<_> = stack - .into_iter() - .filter_map(|(tier, root, entry, point)| { - let shows = |index: usize| { - let (shape, placed) = (&entry.shapes[index], entry.placed[index]); - if shown { placed.clip.contains(point) } else { shape.shape.bounds().intersects(placed.clip) } - }; - let kept: Vec = (0..entry.shapes.len()) - .filter(|&index| entry.shapes[index].sense.takes_press() && entry.shapes[index].hits(point) && shows(index)) - .collect(); - let shapes: Vec> = kept.iter().map(|&index| entry.shapes[index].clone()).collect(); - let mut winner = resolve(&shapes, point, ResolveFor::Press)?; + let mut under = Under::default(); + // The topmost shape under the point, and each root's topmost shape that takes a press, ranked by tier and then + // by the place in paint order of the registration that recorded it. + let mut top: Option<((u8, u32), Winner, Id)> = None; + let mut ranked = Vec::new(); + for (tier, root, entry, point) in stack { + let members = !withheld.contains(&root); + let shows = |index: usize| { + let (shape, placed) = (&entry.shapes[index], entry.placed[index]); + if shown { placed.clip.contains(point) } else { shape.shape.bounds().intersects(placed.clip) } + }; + let kept: Vec = (0..entry.shapes.len()) + .filter(|&index| (members || entry.shapes[index].owner == root) && entry.shapes[index].hits(point) && shows(index)) + .collect(); + if kept.is_empty() { + continue; + } + if !under.over.contains(&root) { + under.over.push(root); + } + let shapes: Vec> = kept.iter().map(|&index| entry.shapes[index].clone()).collect(); + let placed = |mut winner: Winner| { winner.index = kept[winner.index]; - Some(((tier, entry.placed[winner.index].order), winner, root, entry.click)) - }) - .collect(); - ranked.sort_by(|a, b| b.0.cmp(&a.0)); - let mut winners = PressWinners::default(); - for (_, winner, root, root_clicks) in ranked { - let (clicks, drags) = (winner.sense.contains(craft_behavior::Sense::CLICK), winner.sense.contains(craft_behavior::Sense::DRAG)); - match (winners.click.is_some(), winners.drag.is_some()) { - // The top root takes what its shape senses; one that takes both kinds takes the whole press. - (false, false) => { - winners.click = clicks.then_some((winner, root)); - winners.drag = drags.then_some((winner, root)); - if clicks && drags { - break; - } - } - // Under a top shape that only drags, the first one below that clicks takes the click. - (false, true) => { - if clicks { - winners.click = Some((winner, root)); - break; - } - } - // Under a top shape that only clicks, the first root below whose shape drags takes the drag, unless the - // root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. - (true, false) => { - if clicks || root_clicks { - break; - } - if drags { - winners.drag = Some((winner, root)); - break; - } - } - (true, true) => break, + ((tier, entry.placed[winner.index].order), winner) + }; + if let Some((rank, winner)) = resolve(&shapes, point, ResolveFor::Hover).map(placed) + && top.as_ref().is_none_or(|(best, ..)| rank > *best) + { + top = Some((rank, winner, root)); + } + if let Some((rank, winner)) = resolve(&shapes, point, ResolveFor::Press).map(placed) { + ranked.push((rank, winner, root, entry.click)); } } - winners + under.press = winners_of(ranked); + under.hover_only = top.filter(|(_, winner, _)| !winner.sense.takes_press()).map(|(_, winner, root)| (winner, root)); + under }) } +/// The press winners among `ranked`, each root's topmost shape under a point that takes a press with its rank and +/// whether the root takes clicks anywhere: by the per-kind rule of [`PressWinners`]. +fn winners_of(mut ranked: Vec<((u8, u32), Winner, Id, bool)>) -> PressWinners { + ranked.sort_by(|a, b| b.0.cmp(&a.0)); + let mut winners = PressWinners::default(); + for (_, winner, root, root_clicks) in ranked { + let (clicks, drags) = (winner.sense.contains(craft_behavior::Sense::CLICK), winner.sense.contains(craft_behavior::Sense::DRAG)); + match (winners.click.is_some(), winners.drag.is_some()) { + // The top root takes what its shape senses; one that takes both kinds takes the whole press. + (false, false) => { + winners.click = clicks.then_some((winner, root)); + winners.drag = drags.then_some((winner, root)); + if clicks && drags { + break; + } + } + // Under a top shape that only drags, the first one below that clicks takes the click. + (false, true) => { + if clicks { + winners.click = Some((winner, root)); + break; + } + } + // Under a top shape that only clicks, the first root below whose shape drags takes the drag, unless the + // root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. + (true, false) => { + if clicks || root_clicks { + break; + } + if drags { + winners.drag = Some((winner, root)); + break; + } + } + (true, true) => break, + } + } + winners +} + /// The layer a press past the window goes to, where egui has none (only automation names such a point: a document /// point off the window): the topmost layer of last pass's shape record with a shape there that takes a press and /// shows some of itself inside its clip. @@ -708,6 +818,25 @@ pub fn shapes_at(ctx: &Context, at: Pos2) -> Vec<(Id, Option)> { }) } +/// 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. +#[cfg(feature = "testing")] +pub(crate) fn arena_clip(ctx: &Context, component: Id) -> Option { + PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { + [&record.this, &record.last].into_iter().find_map(|layers| { + let holds = |root: Id, entry: &RootRecord| root == component || entry.shapes.iter().any(|shape| shape.owner == component); + let root = layers.values().find_map(|roots| roots.iter().find(|(root, entry)| holds(**root, *entry)).map(|(root, _)| *root))?; + let background = + |shape: &Shape| shape.owner == root && shape.part.is_none() && shape.priority.level == craft_behavior::HitLevel::Background; + layers + .values() + .filter_map(|roots| roots.get(&root)) + .find_map(|entry| entry.shapes.iter().zip(&entry.placed).find(|(shape, _)| background(*shape)).map(|(_, placed)| placed.clip)) + }) + }) +} + /// The screen bounds of the root `root` from its shape record, with the viewport and layer they were recorded in: the /// running pass's shapes when the root has registered in it, else the previous pass's. Searched over the live /// viewports, so the input hook reads it before the pass begins. diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index b0bc5856f..79cd3eb21 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -545,7 +545,7 @@ impl Fixture { /// press on it lands; `None` when none of it is visible. A part past the window's edge is pressed on its visible /// piece, and one wholly past it cannot be pressed. pub fn visible(&self, target: &Target) -> Option { - let clip = self.root_id().and_then(|root| crate::primitives::sensing::arena_clip(self.ctx(), root)); + let clip = self.root_id().and_then(|root| crate::runtime::pointer::arena_clip(self.ctx(), root)); let rect = clip.map_or(target.rect, |clip| target.rect.intersect(clip)); (rect.width() >= 0.0 && rect.height() >= 0.0).then_some(Target { node: target.node, rect }) } diff --git a/crates/ui-contract/src/testing/pointer.rs b/crates/ui-contract/src/testing/pointer.rs index 0eb2b291c..50a9354e7 100644 --- a/crates/ui-contract/src/testing/pointer.rs +++ b/crates/ui-contract/src/testing/pointer.rs @@ -118,3 +118,9 @@ pub fn part_rect_of_node( pub fn press_captured(ctx: &egui::Context) -> bool { crate::runtime::pointer::press_captured(ctx) } + +/// How many times the running viewport's latest pass resolved what lies under a point: once for the hover, and again +/// only for a press at another point or with other egui targets. For count trials. +pub fn resolutions(ctx: &egui::Context) -> u32 { + crate::runtime::pointer::resolutions(ctx) +} diff --git a/crates/ui-contract/src/testing/sensing.rs b/crates/ui-contract/src/testing/sensing.rs index bc50b646f..f9d54b99c 100644 --- a/crates/ui-contract/src/testing/sensing.rs +++ b/crates/ui-contract/src/testing/sensing.rs @@ -213,6 +213,8 @@ pub struct SenseReport { pub clicked: bool, /// The `Response` reports a hover. pub hovered: bool, + /// The `Response` reports the pointer over the component, on top or not. + pub contains_pointer: bool, } impl SenseReport { @@ -220,6 +222,11 @@ impl SenseReport { pub fn phase(&self, key: PartKey) -> PressPhase { self.parts.iter().find(|part| part.key == key).map_or(PressPhase::Idle, |part| part.press.phase) } + + /// Whether the part `key` reads the pointer over it. + pub fn part_hovered(&self, key: PartKey) -> bool { + self.parts.iter().any(|part| part.key == key && part.hovered) + } } /// What a root and its members read this pass. @@ -291,6 +298,7 @@ fn show_members(ui: &mut Ui, arena: ArenaId, root: &ProbeRoot, ctx: &Context) -> activated: result.activated, clicked: fixture::clicked(&result.response), hovered: result.response.hovered(), + contains_pointer: result.response.contains_pointer(), } }) .collect() @@ -313,6 +321,7 @@ fn show_leaf(ui: &mut Ui, root: &ProbeRoot, member: &ProbeMember, ctx: &Context) activated: result.activation || fixture::clicked(&result.response), clicked: fixture::clicked(&result.response), hovered: result.response.hovered(), + contains_pointer: result.response.contains_pointer(), } } @@ -364,6 +373,7 @@ fn show_root(ui: &mut Ui, ctx: &Context, root: &ProbeRoot) -> RootReport { activated: result.activation, clicked: fixture::clicked(&result.response), hovered: result.response.hovered(), + contains_pointer: result.response.contains_pointer(), }, activated_member: result.activated_member, members, diff --git a/crates/ui-contract/tests/it/runtime/pointer.rs b/crates/ui-contract/tests/it/runtime/pointer.rs index 7f4d09d97..f5ebb8b9c 100644 --- a/crates/ui-contract/tests/it/runtime/pointer.rs +++ b/crates/ui-contract/tests/it/runtime/pointer.rs @@ -30,7 +30,11 @@ fn press_phases(report: &SenseReport, key: Option) -> Vec { impl Log { fn last(&self) -> &RootReport { - &self.frames[self.frames.len() - 1][0] + self.last_root(0) + } + + fn last_root(&self, root: usize) -> &RootReport { + &self.frames[self.frames.len() - 1][root] } fn root_phases(&self, root: usize, key: Option) -> Vec { @@ -310,6 +314,12 @@ fn downs(phases: &[PressPhase]) -> usize { phases.iter().filter(|phase| matches!(phase, PressPhase::Down { .. })).count() } +/// The pointer moving to `at`, then one idle frame: the frames after it read the hover at `at`. +fn move_to(frames: &mut Frames, at: Pos2, show: &mut impl FnMut(&mut Ui)) { + frames.frame(vec![pointer::moved(at)], &mut *show); + frames.idle(1, show); +} + /// A press that enters and goes down in one frame, as an automation click does, then its release. fn enter_and_click(frames: &mut Frames, at: Pos2, show: &mut impl FnMut(&mut Ui)) { frames.frame(vec![pointer::moved(at), pointer::press(at)], &mut *show); @@ -345,28 +355,33 @@ fn a_control_takes_its_press_under_a_later_body_sized_widget() { assert!(log.member_phases(0, "body", None).is_empty(), "the body's own shape saw no press"); } -/// Over a canvas's background part, a root nested in its body (a text editor) and a member shown after it (a text -/// frame with a corner handle at the editor's corner): exactly one of them starts each press, the one whose shape is -/// on top under it and takes both its click and its drag. -#[trial] -fn one_root_starts_a_press_where_roots_overlap_on_a_layer() { - const CORNER: PartKey = PartKey::new("corner"); - let canvas = ProbeRoot::new("canvas", rect(100.0, 100.0, 500.0, 300.0), Sense::empty()) +const CORNER: PartKey = PartKey::new("corner"); +const OVER_CORNER: Pos2 = Pos2::new(202.0, 152.0); +const OVER_EDITOR: Pos2 = Pos2::new(300.0, 200.0); +const OVER_CANVAS: Pos2 = Pos2::new(150.0, 350.0); + +/// A canvas with a background part, a root nested in its body (a text editor) and a member shown after it (a text +/// frame with a corner handle at the editor's corner). +fn overlapping_canvas() -> ProbeRoot { + ProbeRoot::new("canvas", rect(100.0, 100.0, 500.0, 300.0), Sense::empty()) .arena() .part(ProbePart::new(BACKGROUND, rect(100.0, 100.0, 500.0, 300.0), Sense::CLICK | Sense::DRAG).level(HitLevel::Background, 0)) .member(ProbeMember::new("editor", rect(200.0, 150.0, 200.0, 100.0), Sense::CLICK | Sense::DRAG).nested()) .member( ProbeMember::new("frame", rect(100.0, 100.0, 500.0, 300.0), Sense::empty()) .part(ProbePart::new(CORNER, rect(194.0, 144.0, 12.0, 12.0), Sense::CLICK | Sense::DRAG).level(HitLevel::Handle, 1)), - ); - let (mut show_frame, log) = scene(vec![canvas]); + ) +} + +/// Over the overlapping canvas: exactly one of the canvas background, the editor and the frame's corner starts each +/// press, the one whose shape is on top under it and takes both its click and its drag. +#[trial] +fn one_root_starts_a_press_where_roots_overlap_on_a_layer() { + let (mut show_frame, log) = scene(vec![overlapping_canvas()]); let mut frames = Frames::new(); frames.idle(2, &mut show_frame); - let corner = Pos2::new(202.0, 152.0); - let inside = Pos2::new(300.0, 200.0); - let free = Pos2::new(150.0, 350.0); - for (at, expected) in [(corner, [0, 0, 1]), (inside, [0, 1, 0]), (free, [1, 0, 0])] { + for (at, expected) in [(OVER_CORNER, [0, 0, 1]), (OVER_EDITOR, [0, 1, 0]), (OVER_CANVAS, [1, 0, 0])] { log.borrow_mut().clear(); enter_and_click(&mut frames, at, &mut show_frame); let log = log.borrow(); @@ -378,3 +393,111 @@ fn one_root_starts_a_press_where_roots_overlap_on_a_layer() { assert_eq!(started, expected, "at {at:?}: presses started on [canvas background, editor, frame corner]"); } } + +/// Hover shows where a press goes: over the overlapping canvas, the shapes that read the pointer over them before a +/// press are the ones the press then starts on, and nothing a press would not reach hovers. +#[trial] +fn hover_shows_where_a_press_goes_where_roots_overlap() { + let (mut show_frame, log) = scene(vec![overlapping_canvas()]); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + + for at in [OVER_CORNER, OVER_EDITOR, OVER_CANVAS] { + move_to(&mut frames, at, &mut show_frame); + let hovered = { + let log = log.borrow(); + let report = log.last_root(0); + let editor = report.member("editor").expect("the editor shows"); + let frame = report.member("frame").expect("the frame shows"); + [report.root.part_hovered(BACKGROUND), editor.hovered, frame.part_hovered(CORNER)] + }; + log.borrow_mut().clear(); + enter_and_click(&mut frames, at, &mut show_frame); + let log = log.borrow(); + let started = [ + downs(&log.root_phases(0, Some(BACKGROUND))) > 0, + downs(&log.member_phases(0, "editor", None)) > 0, + downs(&log.member_phases(0, "frame", Some(CORNER))) > 0, + ]; + assert_eq!(hovered, started, "at {at:?}: [canvas background, editor, frame corner] hovered as a press there starts"); + assert_eq!(hovered.iter().filter(|hovered| **hovered).count(), 1, "at {at:?}: one shape hovers"); + } +} + +/// A clickable row with a nested button and a nested label that only shows a tooltip: over the button only the button +/// hovers, though the row contains the pointer; over the label both the label and the row hover, and the click goes to +/// the row. +#[trial] +fn a_root_under_a_nested_control_hovers_only_where_its_press_lands() { + let row = ProbeRoot::new("row", rect(100.0, 100.0, 300.0, 40.0), Sense::CLICK) + .member(ProbeMember::new("button", rect(320.0, 108.0, 60.0, 24.0), Sense::CLICK)) + .member(ProbeMember::new("label", rect(110.0, 108.0, 120.0, 24.0), Sense::HOVER)); + let (mut show_frame, log) = scene(vec![row]); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + + let hovered = |log: &Log| { + let report = log.last_root(0); + let (button, label) = (report.member("button").expect("the button shows"), report.member("label").expect("the label shows")); + [report.root.hovered, button.hovered, label.hovered] + }; + move_to(&mut frames, Pos2::new(350.0, 120.0), &mut show_frame); + assert_eq!(hovered(&log.borrow()), [false, true, false], "over the button: [row, button, label] hovered"); + assert!(log.borrow().last_root(0).root.contains_pointer, "the row contains the pointer over its button"); + move_to(&mut frames, Pos2::new(150.0, 120.0), &mut show_frame); + assert_eq!(hovered(&log.borrow()), [true, false, true], "over the label: [row, button, label] hovered"); + move_to(&mut frames, Pos2::new(260.0, 120.0), &mut show_frame); + assert_eq!(hovered(&log.borrow()), [true, false, false], "over the row alone: [row, button, label] hovered"); + + log.borrow_mut().clear(); + enter_and_click(&mut frames, Pos2::new(150.0, 120.0), &mut show_frame); + let log = log.borrow(); + assert_eq!(downs(&log.root_phases(0, None)), 1, "a press on the label starts on the row"); + assert!(log.member_phases(0, "label", None).is_empty(), "the label takes no press"); +} + +/// Hover and presses read one resolution of what lies under the pointer per pass, however many roots stack there. +#[trial] +fn one_pointer_resolution_per_pass_whatever_the_number_of_roots() { + const NAMES: [&str; 8] = ["r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7"]; + let counts = |roots: usize| { + let stack = NAMES[..roots].iter().map(|name| ProbeRoot::new(*name, rect(100.0, 100.0, 200.0, 100.0), Sense::CLICK)).collect(); + let (mut show_frame, _log) = scene(stack); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + let at = Pos2::new(200.0, 150.0); + let mut counts = Vec::new(); + for events in [vec![pointer::moved(at)], vec![pointer::press(at)], vec![pointer::release(at)], Vec::new()] { + frames.frame(events, &mut show_frame); + counts.push(pointer::resolutions(&frames.ctx)); + } + counts + }; + let (one, eight) = (counts(1), counts(8)); + assert_eq!(one, eight, "resolutions per pass with one root and with eight stacked roots"); + assert!(one.iter().all(|count| *count <= 1), "at most one resolution per pass: {one:?}"); + assert!(one.contains(&1), "the pointer in the window is resolved: {one:?}"); +} + +/// While a press on one root is held, another root the pointer moves over does not hover; it hovers once the press +/// ends. +#[trial] +fn a_held_press_keeps_hover_off_other_roots() { + let a = ProbeRoot::new("a", rect(100.0, 100.0, 100.0, 40.0), Sense::CLICK); + let b = ProbeRoot::new("b", rect(250.0, 100.0, 100.0, 40.0), Sense::CLICK); + let (mut show_frame, log) = scene(vec![a, b]); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + let (on_a, on_b) = (Pos2::new(150.0, 120.0), Pos2::new(300.0, 120.0)); + + frames.frame(vec![pointer::moved(on_a), pointer::press(on_a)], &mut show_frame); + log.borrow_mut().clear(); + frames.frame(vec![pointer::moved(on_b)], &mut show_frame); + frames.idle(1, &mut show_frame); + assert!(log.borrow().frames.iter().all(|reports| !reports[1].root.hovered), "b does not hover while a's press is held"); + assert!(log.borrow().last_root(1).root.contains_pointer, "b contains the pointer"); + + frames.frame(vec![pointer::release(on_b)], &mut show_frame); + frames.idle(1, &mut show_frame); + assert!(log.borrow().last_root(1).root.hovered, "b hovers once the press ends"); +} diff --git a/crates/ui-widgets/src/notices/toasts.rs b/crates/ui-widgets/src/notices/toasts.rs index 451fcac1f..01113b365 100644 --- a/crates/ui-widgets/src/notices/toasts.rs +++ b/crates/ui-widgets/src/notices/toasts.rs @@ -30,7 +30,7 @@ impl ToastStack { (None, true) => Some(ToastEnd::Dismissed), (None, false) => None, }; - CardOutcome::new(out.response.hovered(), end) + CardOutcome::new(out.response.contains_pointer(), end) }); } }