Merge branch 'fw/press-route' into fw/mac1

# Conflicts:
#	crates/ui-contract/src/primitives/sensing.rs
This commit is contained in:
aiongg
2026-11-17 06:31:19 +00:00
4 changed files with 217 additions and 43 deletions
+46 -13
View File
@@ -35,7 +35,7 @@ pub const BOX: PartKey = PartKey::new("box");
/// outside.
const OUTSIDE: PartKey = PartKey::new("outside");
/// The pointer-only part of an edge: the whole side, beside the midpoint handle `BOX.at(Edge(k))` that the keyboard
/// The pointer-only part of an edge: the band along the whole side, outside it, beside the midpoint handle `BOX.at(Edge(k))` that the keyboard
/// and the focus ring use. One part key carries one shape, so the side cannot reuse the handle's key.
const EDGE: PartKey = PartKey::new("edge");
@@ -74,8 +74,13 @@ struct KeyPicked(Option<BoxPart>);
const NUDGE: f64 = 1.0;
const NUDGE_FAR: f64 = 10.0;
/// The handles' pointer distances, in standard handle sides (`size.handle.md`; at an 8 handle: a hit radius of 12, the
/// rotate pointer within 36 of a corner, the rotate band from 5 to 18 outside it).
/// The pointer distances, in standard handle sides (`size.handle.md`; at an 8 handle: a handle reaches 8 from its
/// point, inside the box as outside, each side's band reaches 11 outside it and none inside, the reference point and
/// the centre reach 12, the rotate pointer shows within 36 of a corner, the rotate band runs from 5 to 18 outside it).
/// The handle reach and the side bands are PhotoCraft's: inside the box only a handle's own reach is the box's, so a
/// press there off the handles reaches what lies under the box (a text editor under a paragraph frame).
const HANDLE_REACH_IN_HANDLES: f32 = 1.0;
const SIDE_BAND_IN_HANDLES: f32 = 1.375;
const HIT_IN_HANDLES: f32 = 1.5;
const ROTATE_REACH_IN_HANDLES: f32 = 4.5;
const BAND_INNER_IN_HANDLES: f32 = 0.625;
@@ -216,7 +221,11 @@ pub struct TransformBoxStyle {
handle: HandleLook,
line: StyleColor,
halo: StyleColor,
/// The hit radius of a handle.
/// The hit radius of a corner or side handle.
handle_reach: f32,
/// How far a side's band reaches outside the box.
side_band: f32,
/// The hit radius of the reference point and of the centre.
hit: f32,
/// How far from a corner the rotate pointer shows outside the box.
rotate_reach: f32,
@@ -884,6 +893,8 @@ impl Component for TransformBox<'_> {
handle: cx.handle(),
line: cx.color(overlay.line),
halo: cx.color(overlay.halo),
handle_reach: handle.md * HANDLE_REACH_IN_HANDLES,
side_band: handle.md * SIDE_BAND_IN_HANDLES,
hit: handle.md * HIT_IN_HANDLES,
rotate_reach: handle.md * ROTATE_REACH_IN_HANDLES,
band_inner: handle.md * BAND_INNER_IN_HANDLES,
@@ -911,10 +922,11 @@ impl Component for TransformBox<'_> {
}
/// The whole box, the corners, the edges and the reference point the rules allow, in keyboard order, then each
/// side as a pointer-only segment, the centre and the move strips where declared, and the outside. A handle, the
/// reference point and the centre rank alike, so the nearest wins where they overlap on a small box; they rank above
/// a side, which ranks above the inside, which ranks above the outside. A live line's controls declare its two
/// ends only.
/// side as a pointer-only band outside it, the centre and the move strips where declared, and the outside. A
/// handle, the reference point and the centre rank alike, so the nearest wins where they overlap on a small box;
/// they rank above a side, which ranks above the inside, which ranks above the outside. Every part takes a press's
/// click with its drag, so a press on the box is the box's alone, not split with what lies under it (8.3). A live
/// line's controls declare its two ends only.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let (Some(space), Some(state)) = (canvas_space(&cx.env), cx.value().copied()) else { return };
let style = cx.style;
@@ -935,15 +947,15 @@ impl Component for TransformBox<'_> {
}
BoxPart::Pivot => (
HitShape::circle(pos(screen.pivot), style.hit),
Sense::DRAG | Sense::TAKE_FOCUS,
Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS,
HitPriority::new(HitLevel::Handle, HANDLE_SUB),
FocusShape::Circle,
),
handle => {
let at = self.part_point(&state, handle).map_or(Pos2::ZERO, |at| space.view.to_screen(at));
(
HitShape::circle(at, style.hit),
Sense::DRAG | Sense::TAKE_FOCUS,
HitShape::circle(at, style.handle_reach),
Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS,
HitPriority::new(HitLevel::Handle, HANDLE_SUB),
FocusShape::Circle,
)
@@ -960,8 +972,8 @@ impl Component for TransformBox<'_> {
}
for k in (0..4u8).filter(|&k| self.rules.allows(BoxPart::Edge(k))) {
let side = usize::from(k);
cx.part(EDGE.at(u64::from(k)), HitShape::segment(quad[side], quad[(side + 1) % 4]))
.sense(Sense::DRAG | slop_sense(BoxPart::Edge(k)))
cx.part(EDGE.at(u64::from(k)), side_band(&quad, side, style.side_band))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)))
.priority(HitPriority::new(HitLevel::Handle, EDGE_SUB))
.pointer_only(EDGE_BY_KEY);
}
@@ -1189,6 +1201,27 @@ fn outside_regions(quad: &[Pos2; 4], within: Rect) -> [Vec<Pos2>; 4] {
})
}
/// The band outside side `side` of the box `quad` (from corner `side` to the next), `width` wide, with the side's
/// line itself: a press on the line or outside it within `width` takes the side; inside the box it does not. A side
/// with no length is its line.
fn side_band(quad: &[Pos2; 4], side: usize, width: f32) -> HitShape {
let (a, b) = (quad[side], quad[(side + 1) % 4]);
let along = b - a;
if along.length() < 1e-3 {
return HitShape::segment(a, b);
}
// The winding tells outside from inside, as `quad::outset` reads it.
let area: f32 = (0..4).map(|i| quad[i].x * quad[(i + 1) % 4].y - quad[(i + 1) % 4].x * quad[i].y).sum();
let d = along.normalized();
let out = Vec2::new(d.y, -d.x) * if area >= 0.0 { 1.0 } else { -1.0 };
// Half a point inside the line still counts as on it.
let (inner, outer) = (out * -SIDE_LINE_INSIDE, out * width);
HitShape::Polygon(vec![a + inner, b + inner, b + outer, a + outer])
}
/// How far inside the box a press still lies on a side's line, in screen points.
const SIDE_LINE_INSIDE: f32 = 0.5;
/// `polygon` clipped to `rect` (Sutherland-Hodgman, one rect side at a time).
fn clipped_to(polygon: &[Pos2], rect: Rect) -> Vec<Pos2> {
// How far a point lies inside each side of the rect.
+24 -7
View File
@@ -788,10 +788,11 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab
.cancel(cancel);
let mut machine = std::mem::take(&mut state.machine);
let step = machine.step(input, |at| {
// The press-target rule (8.3): exactly one root starts a press, the one whose shape is on top under it
// (`pointer::press_winner`). A root under a modal layer starts none; where egui names no target of the
// root's kind (its click target, its drag target for a drag-only root; a root whose widgets sense neither
// is never named), only a root the modal's canvas admits does.
// The press-target rule (8.3): a press's click and its drag each start on one root, the one whose shape
// is on top under it for that kind (`pointer::press_winners`); the root starts it for the kinds it won. A
// root under a modal layer starts none; where egui names no target of the root's kind (its click target,
// its drag target for a drag-only root; a root whose widgets sense neither is never named), only a root the
// modal's canvas admits does.
let root = state.root.map(|root| root.id);
let targets = pass_pointer.press_targets;
let untargeted = if union_sense.contains(Sense::CLICK) {
@@ -801,8 +802,19 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab
} else {
true
};
let allowed = crate::runtime::sampler::root_takes_press(ctx, root, layer, at, untargeted)
&& root.is_some_and(|own| pointer::press_winner(ctx, at, targets).is_some_and(|(_, winner)| winner == own));
let won_kinds = root.map_or(Sense::empty(), |own| pointer::press_winners(ctx, at, targets).senses_of(own));
let allowed = crate::runtime::sampler::root_takes_press(ctx, root, layer, at, untargeted) && !won_kinds.is_empty();
if let Some(test) = pointer::diag_test()
&& state.root.is_some_and(|own| own.rect.contains(at))
{
eprintln!(
"DIAG {test}: start root {:?} enabled {enabled} allowed {allowed} won {won_kinds:?} untargeted {untargeted} takes {} layer {layer:?} rect {:?} clip {:?}",
root.map(pointer::diag_id),
crate::runtime::sampler::root_takes_press(ctx, root, layer, at, untargeted),
state.root.map(|own| own.rect),
state.root.map(|own| own.clip),
);
}
if !enabled || !allowed {
return None;
}
@@ -810,7 +822,12 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab
// 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);
won.map(|hit| (hit, if drag_elsewhere { hit.sense.difference(Sense::DRAG) } else { hit.sense }))
// The kinds of press another root won are not this one's.
let lost = (Sense::CLICK | Sense::DRAG).difference(won_kinds);
won.map(|hit| {
let sense = hit.sense.difference(lost);
(hit, if drag_elsewhere { sense.difference(Sense::DRAG) } else { sense })
})
});
cancelled = matches!(step.phase, Some(PressPhase::Cancel { .. }));
release_held = machine.release_held();
+145 -21
View File
@@ -135,7 +135,7 @@ pub(crate) struct Shapes {
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, Option<(Winner<Id>, Id)>)>,
winner: Option<(Pos2, PressTargets, PressWinners)>,
}
/// The begin hook (H5): converts the pass's pointer input.
@@ -529,14 +529,36 @@ pub(crate) fn made_by_component(ctx: &Context, viewport: ViewportId, id: Id) ->
})
}
/// The root a press at `at` (screen points) belongs to, with the shape of it that wins the press: what the sensing
/// core starts the press on and the focus service classifies it by (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 root whose winning
/// shape was recorded last in the pass, the one painted on top, takes the press. 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) has no winner.
pub(crate) fn press_winner(ctx: &Context, at: Pos2, targets: PressTargets) -> Option<(Winner<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.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct PressWinners {
pub click: Option<(Winner<Id>, Id)>,
pub drag: Option<(Winner<Id>, Id)>,
}
impl PressWinners {
/// The root that starts the press for its kinds of press, with the kinds it takes.
pub(crate) fn senses_of(&self, root: Id) -> craft_behavior::Sense {
let mut sense = craft_behavior::Sense::empty();
if self.click.is_some_and(|(_, owner)| owner == root) {
sense |= craft_behavior::Sense::CLICK;
}
if self.drag.is_some_and(|(_, owner)| owner == root) {
sense |= craft_behavior::Sense::DRAG;
}
sense
}
}
pub(crate) fn press_winners(ctx: &Context, at: Pos2, targets: PressTargets) -> PressWinners {
let viewport = pass::current_viewport(ctx);
let found = PerViewport::<Shapes>::with(ctx, viewport, |record| {
record.winner.filter(|(point, asked, _)| *point == at && *asked == targets).map(|(_, _, found)| found)
@@ -544,21 +566,30 @@ pub(crate) fn press_winner(ctx: &Context, at: Pos2, targets: PressTargets) -> Op
if let Some(found) = found {
return found;
}
let found = find_press_winner(ctx, viewport, at, targets);
let found = find_press_winners(ctx, viewport, at, targets);
PerViewport::<Shapes>::with(ctx, viewport, |record| record.winner = Some((at, targets, found)));
found
}
fn find_press_winner(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTargets) -> Option<(Winner<Id>, Id)> {
let layer = areas::layer_at(ctx, at)?;
/// The root a press at `at` belongs to, with its winning shape: the click's root (`press_winners`), else the drag's.
/// What the focus service classifies a press by and a host asks a press about.
pub(crate) fn press_winner(ctx: &Context, at: Pos2, targets: PressTargets) -> Option<(Winner<Id>, Id)> {
let winners = press_winners(ctx, at, targets);
winners.click.or(winners.drag)
}
fn find_press_winners(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTargets) -> PressWinners {
let Some(layer) = areas::layer_at(ctx, at) else {
if let Some(test) = diag_test() {
eprintln!("DIAG {test}: press_winner at {at:?}: no layer");
}
return PressWinners::default();
};
let to_layer = |layer: Layer| areas::layer_map(ctx, layer).map_or(at, |map| map.to_layer(at));
let body = PerViewport::<Shapes>::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);
PerViewport::<Shapes>::with(ctx, viewport, |record| {
if targets.click.is_some_and(|widget| !registered_in(&record.last, widget)) {
return None;
}
let found = PerViewport::<Shapes>::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();
if let Some((root, parent, point)) = beneath
@@ -570,7 +601,37 @@ fn find_press_winner(ctx: &Context, viewport: ViewportId, at: Pos2, targets: Pre
stack.extend(roots.iter().map(|(root, entry)| (1, *root, entry, on_layer)));
}
let shown = stack.iter().any(|(_, _, entry, point)| entry.placed.iter().any(|placed| placed.clip.contains(*point)));
stack
if let Some(test) = diag_test() {
let hits: Vec<String> = stack
.iter()
.flat_map(|(tier, root, entry, point)| {
entry.shapes.iter().zip(&entry.placed).filter(|(shape, _)| shape.hits(*point)).map(move |(shape, placed)| {
format!(
"[tier {tier} root {} owner {} part {:?} sense {:?} level {:?} pos {} order {} clip_in {}]",
diag_id(*root),
diag_id(shape.owner),
shape.part,
shape.sense,
shape.priority.level,
shape.position,
placed.order,
placed.clip.contains(*point)
)
})
})
.collect();
let foreign = |widget: Option<Id>| widget.map(|widget| (diag_id(widget), !registered_in(&record.last, widget)));
eprintln!(
"DIAG {test}: press_winner at {at:?} layer {layer:?} body {:?} click {:?} drag {:?} shown {shown} hits {hits:?}",
beneath.map(|(root, parent, _)| (diag_id(root), parent)),
foreign(targets.click),
foreign(targets.drag)
);
}
if targets.click.is_some_and(|widget| !registered_in(&record.last, widget)) {
return PressWinners::default();
}
let mut ranked: Vec<_> = stack
.into_iter()
.filter_map(|(tier, root, entry, point)| {
let shows = |index: usize| {
@@ -583,11 +644,74 @@ fn find_press_winner(ctx: &Context, viewport: ViewportId, at: Pos2, targets: Pre
let shapes: Vec<Shape<Id>> = kept.iter().map(|&index| entry.shapes[index].clone()).collect();
let mut winner = resolve(&shapes, point, ResolveFor::Press)?;
winner.index = kept[winner.index];
Some(((tier, entry.placed[winner.index].order), winner, root))
Some(((tier, entry.placed[winner.index].order), winner, root, entry.click))
})
.max_by_key(|(rank, ..)| *rank)
.map(|(_, winner, root)| (winner, root))
})
.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,
}
}
winners
});
if let Some(test) = diag_test() {
let show = |found: Option<(Winner<Id>, Id)>| found.map(|(winner, root)| (diag_id(root), diag_id(winner.owner), winner.part, winner.sense));
eprintln!("DIAG {test}: press_winner at {at:?} -> click {:?} drag {:?}", show(found.click), show(found.drag));
}
found
}
/// DIAG: the test under study this thread runs, if any.
pub(crate) fn diag_test() -> Option<&'static str> {
const TESTS: [&str; 8] = [
"delete_removes_the_plane_and_escape_drops_a_half_plane_first",
"a_window_mounts_edges_resize_the_window_and_the_childs_press_keeps_its_click",
"gradient_map_stop_picker_closed_without_a_colour_changes_nothing",
"photo_filter_colour_picker_previews_live_cancel_restores_and_ok_is_one_step",
"every_paragraph_box_handle_resizes_the_box_with_snapping_on",
"click_inside_the_paragraph_box_off_the_glyphs_moves_the_caret",
"a_crop_drag_begun_before_the_dialog_still_ends_under_it",
"move_pointer_still_reaches_the_liquify_workspace",
];
// Trials run on unnamed pool threads: there the run names its trial in `CRAFT_DIAG_TEST`.
let thread = std::thread::current();
let name = std::env::var("CRAFT_DIAG_TEST").ok().or_else(|| thread.name().map(str::to_owned))?;
TESTS.into_iter().find(|test| name.ends_with(test))
}
/// DIAG: the tail of an id's path.
pub(crate) fn diag_id(id: Id) -> String {
let text = format!("{id:?}");
text.char_indices().rev().nth(90).map_or(text.clone(), |(at, _)| text[at..].to_owned())
}
/// Whether some root registered the egui widget `widget` in `layers`.
@@ -347,7 +347,7 @@ fn a_control_takes_its_press_under_a_later_body_sized_widget() {
/// 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.
/// 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");
@@ -357,7 +357,7 @@ fn one_root_starts_a_press_where_roots_overlap_on_a_layer() {
.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::DRAG).level(HitLevel::Handle, 1)),
.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]);
let mut frames = Frames::new();