From 21e77e2b58f8f5ac0cc2cfbbf8f376ffe23d013e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 11:07:38 -0500 Subject: [PATCH] Framework follow-ups F-29, F-30, F-32, F-34, F-35 (app red 6, L-236, L-237): Shift/Cmd page keys go to the ends; PageViewOutput::scrolled; ToolPass::hide_pointer; the arena gives a secondary press only to CONTEXT_CLICK targets (scroll bars take theirs); BoxRules::with_edge_band --- crates/behavior/src/geometry/quad.rs | 11 ++++ crates/behavior/src/press.rs | 29 +++++---- crates/behavior/src/sense.rs | 3 +- crates/draw/src/ui/transform/transform_box.rs | 16 ++++- .../src/ui/transform/transform_box/stories.rs | 16 +++-- crates/draw/tests/it/transform_box.rs | 27 ++++++++ crates/pages/src/ui/view.rs | 41 +++++++++++-- crates/pages/tests/it/views.rs | 61 ++++++++++++++++++- crates/ui-canvas/src/canvas/mod.rs | 11 ++++ crates/ui-canvas/src/canvas/space.rs | 4 +- crates/ui-canvas/tests/it/canvas/tool.rs | 40 ++++++++++++ crates/ui-contract/src/contract/cx/parts.rs | 8 ++- crates/ui-contract/src/contract/cx/scroll.rs | 4 +- crates/ui-contract/src/primitives/sensing.rs | 6 +- crates/ui-contract/src/runtime/pointer.rs | 34 ++++++++--- .../ui-contract/tests/it/runtime/pointer.rs | 38 +++++++++++- 16 files changed, 305 insertions(+), 44 deletions(-) diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index 82e36e283..4c70ff25d 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -202,6 +202,10 @@ pub struct BoxRules { pub min_side: f64, /// Which handles the box shows and takes keys and drags for. pub handles: BoxHandles, + /// How far either side of a side's line a press grabs that side, in screen points, along the whole side and as + /// far past its ends: a paragraph frame whose edges rewrap it. Inside the box the band reaches at most a quarter of + /// the way across, so a narrow box keeps its middle. 0, the default, leaves each side its band outside the box. + pub edge_band: f32, } /// Which handles of a box are shown. @@ -227,6 +231,7 @@ impl Default for BoxRules { rotate_step: 15.0, min_side: 0.0, handles: BoxHandles::default(), + edge_band: 0.0, } } } @@ -268,6 +273,12 @@ impl BoxRules { self } + /// The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)). + pub fn with_edge_band(mut self, points: f32) -> BoxRules { + self.edge_band = points; + self + } + /// Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides /// and no corner. The inside, the outside and the reference point always show. pub fn shows(&self, part: BoxPart) -> bool { diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index 42cafe8bd..79304a22e 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -568,9 +568,10 @@ impl PressMachine { self.open.is_some_and(|open| open.released_at.is_some()) } - /// Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` - /// when no shape of this root takes the press. - pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option>) -> PressStep { + /// Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed + /// there; it returns `None` when no shape of this root takes the press. A secondary press goes only to a shape that + /// senses `Sense::CONTEXT_CLICK`, so `pick` passes over the others for it, to the next shape under the press. + pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep { let mut pos = input.pos; // The press released or cancelled in this pass, and whether it was silent: one that ends silent reports nothing. let mut released: Option<(T, PressStart, Pos2, bool, bool, bool)> = None; @@ -631,15 +632,15 @@ impl PressMachine { } // An open press keeps the pointer until its button comes up: no press starts over it, of its own // button (a repeated Down, as a window never sends one) or another. Its moves and its release still - // reach it when a modal opened over its target since. A middle or secondary press captures for a - // drag (a canvas pan, a drag with the secondary button) and never clicks. A target that senses - // `MIDDLE_CLICK` also takes a middle press that can click (a tab closes on it), and one that senses - // `CONTEXT_CLICK` takes a secondary press, which a click-only target would not capture. + // reach it when a modal opened over its target since. A middle press captures for a drag (a canvas + // pan) and never clicks, unless its target senses `MIDDLE_CLICK` (a tab closes on it). A secondary + // press is only a target's that senses `CONTEXT_CLICK`, which clicks and drags with it; a target that + // only drags (a transform box) leaves it to the context target under it. let capture_only = button != PointerButton::Primary; if !matches!(button, PointerButton::Primary | PointerButton::Middle | PointerButton::Secondary) || self.open.is_some() { continue; } - self.open = pick(at) + self.open = pick(at, button) .map(|pick| { let clicks = match button { PointerButton::Middle => pick.sense.contains(Sense::MIDDLE_CLICK), @@ -649,7 +650,11 @@ impl PressMachine { let sense = if capture_only && !clicks { pick.sense - Sense::CLICK } else { pick.sense }; (pick, sense, clicks) }) - .filter(|(_, sense, clicks)| !capture_only || *clicks || sense.contains(Sense::DRAG)) + .filter(|(_, sense, clicks)| match button { + PointerButton::Primary => true, + PointerButton::Middle => *clicks || sense.contains(Sense::DRAG), + _ => *clicks, + }) .map(|(pick, sense, _)| { // A silent press owes no `Down`: its first phase is its `DragStart`. let silent = pick.passed && sense.contains(Sense::DRAG); @@ -761,7 +766,7 @@ mod tests { fn pass(machine: &mut PressMachine, events: &[PointerEvent], sense: Sense) -> PressStep { let held = machine.open.is_some() || matches!(events.last(), Some(PointerEvent::Pressed { .. })); - machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_| Some(PressPick::new(1, sense))) + machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_, _| Some(PressPick::new(1, sense))) } fn press(x: f32, time: f64) -> PointerEvent { @@ -814,7 +819,7 @@ mod tests { let first = pos2(0.0, 0.0); let mut machine = PressMachine::new(); let mut step = |events: &[PointerEvent]| { - machine.step(PassInput::new(events, SLOP, first, true), |at| (at == first).then_some(PressPick::new(1u8, Sense::DRAG))) + machine.step(PassInput::new(events, SLOP, first, true), |at, _| (at == first).then_some(PressPick::new(1u8, Sense::DRAG))) }; step(&[press(0.0, 1.0)]); step(&[PointerEvent::Moved { at: pos2(40.0, 0.0), sample: None }]); @@ -856,7 +861,7 @@ mod tests { /// One pass with the button held at its end, over a root whose press winner is target 1 and passes its drag. fn passing_pass(machine: &mut PressMachine, events: &[PointerEvent]) -> PressStep { - machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), true), |_| Some(PressPick::new(1, PASSES))) + machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), true), |_, _| Some(PressPick::new(1, PASSES))) } fn moved(x: f32) -> PointerEvent { diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index 3d3faca04..c64efa2fb 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -30,7 +30,8 @@ bitflags! { /// The zoom share (Ctrl or Cmd with the wheel, pinch), taken without scroll; the split rule passes both scroll shares on. const WHEEL_ZOOM = 1024; /// A secondary press captures the part and its release is reported to it, so a part that senses only a click - /// still gets its context click. Without this bit a secondary press only captures for a drag. + /// still gets its context click, and one that drags drags with the secondary button too. Without this bit the + /// shape takes no secondary press: it goes to the next shape under it that senses this bit. const CONTEXT_CLICK = 2048; /// A container root learns of a primary press on its own surface: inside its rect, on its layer, where no /// shape takes the press. The root takes no press and no focus by it, so it is no click target. diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 0b9dbfe4c..89d8c958d 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -988,7 +988,7 @@ 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 band outside it, each corner's stretch of the two bands beside it, the centre and the move + /// side as a pointer-only band outside it (either side of its line with the rules' edge band), each corner's stretch of the two bands beside it, the centre and the move /// strips where declared, and the outside. A handle, a corner's stretch, 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 @@ -1039,7 +1039,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)), side_band(&quad, side, style.side_band)) + let band = if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) }; + cx.part(EDGE.at(u64::from(k)), band) .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k))) .priority(HitPriority::new(HitLevel::Handle, EDGE_SUB)) .pointer_only(EDGE_BY_KEY); @@ -1309,6 +1310,17 @@ fn side_band(quad: &[Pos2; 4], side: usize, width: f32) -> HitShape { } } +/// The grab band of side `side` of the box `quad` by [`BoxRules::edge_band`]: `reach` out from the line and past each +/// end, and as far in, but no more than a quarter of the way to the opposite side. A side with no length is its line. +fn edge_band(quad: &[Pos2; 4], side: usize, reach: f32) -> HitShape { + let (a, b) = (quad[side], quad[(side + 1) % 4]); + let Some(out) = outward(quad, side) else { return HitShape::segment(a, b) }; + let along = (b - a).normalized() * reach; + let across = (quad[(side + 2) % 4] - b).length(); + let (inner, outer) = (out * -reach.min(across / 4.0).max(SIDE_LINE_INSIDE), out * reach); + HitShape::Polygon(vec![a - along + inner, b + along + inner, b + along + outer, a - along + outer]) +} + /// The stretch of side `side`'s band next to its end `corner`: a quarter of the side, at most `width` along it, as far /// out as the band. `None` for a side with no length. fn corner_reach(quad: &[Pos2; 4], side: usize, corner: usize, width: f32) -> Option { diff --git a/crates/draw/src/ui/transform/transform_box/stories.rs b/crates/draw/src/ui/transform/transform_box/stories.rs index d5394d24b..e31819bb7 100644 --- a/crates/draw/src/ui/transform/transform_box/stories.rs +++ b/crates/draw/src/ui/transform/transform_box/stories.rs @@ -1,9 +1,9 @@ //! Stories of the transform box: Free Transform with its reference point, the Move tool's controls, Distort, the -//! Ellipse tool's centre mark, the Line tool's live-line controls, the corner-only and side-only handle sets and the -//! rotate knob. +//! Ellipse tool's centre mark, the Line tool's live-line controls, the corner-only and side-only handle sets, sides +//! grabbed along an edge band, and the rotate knob. -use super::{BOX, LineLook, RotateZone, TransformBox}; -use craft_behavior::geometry::quad::{BoxHandles, BoxPart, BoxRules, BoxState, TransformMode}; +use super::{BOX, EDGE, LineLook, RotateZone, TransformBox}; +use craft_behavior::geometry::quad::{BoxHandles, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec}; use craft_ui::canvas::Canvas; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; @@ -78,6 +78,14 @@ fn sides_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { on_canvas(ui, data, |state| free_box(state).rules(BoxRules::default().with_handles(BoxHandles::Sides))) } +/// A paragraph frame whose right and left sides are grabbed anywhere along their length within 8 points either side of +/// the line (`BoxRules::edge_band`), not only at their handles; the middle of the frame is the tool's. +#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(EDGE.at(1)).toward(vec2(1.0, 0.0))))] +fn sides_edge_band(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let rules = BoxRules::default().with_scale(ScaleRule::Free).with_aspect_linked(false).with_handles(BoxHandles::Sides).with_edge_band(8.0); + on_canvas(ui, data, |state| free_box(state).rules(rules).inside_moves(false).reference_point(false)) +} + /// A box that turns by a round knob on a stem above its top side; the rest of the outside is the tool's. #[story(TransformBox<'static>, covers = [Default])] fn rotate_knob(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 9438d82de..84620d2e1 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -349,6 +349,33 @@ fn an_edge_takes_a_press_along_its_side_and_a_corner_wins_where_both_reach() { assert!((quad[0].x - RECT.x0).abs() < 1e-6 && (quad[3].x - RECT.x0).abs() < 1e-6, "the far side stayed: {quad:?}"); } +#[trial] +fn an_edge_band_grabs_a_side_from_inside_the_box_along_its_whole_length() { + // A frame like a paragraph's: nothing inside moves it, so a press inside is the side's or nothing's. + let paragraph = |band: f32| { + harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules().with_edge_band(band); + config.inside_moves = false; + config.reference_point = false; + }) + }; + // The right edge runs from (300, 80) to (300, 220); 6 points inside it, away from its middle handle. + let inside = Point::new(294.0, 110.0); + let mut plain = paragraph(0.0); + hover(&mut plain, inside); + assert_ne!(plain.host.borrow().hovered, Some(BoxPart::Edge(1)), "without a band the side reaches outside only"); + + let mut h = paragraph(8.0); + hover(&mut h, inside); + assert_eq!(h.host.borrow().hovered, Some(BoxPart::Edge(1)), "within the band inside the box, the side"); + hover(&mut h, Point::new(200.0, 110.0)); + assert_eq!(h.host.borrow().hovered, None, "the middle of the box is past the band"); + drag(&mut h, inside, Point::new(314.0, 110.0)); + let quad = h.state().quad; + assert!((quad[1].x - 314.0).abs() < 1e-6 && (quad[2].x - 314.0).abs() < 1e-6, "the grab dragged the side as its handle: {quad:?}"); + assert!((quad[0].x - RECT.x0).abs() < 1e-6, "the far side stayed: {quad:?}"); +} + #[trial] fn the_arrows_move_the_whole_box_after_a_handle_drag_leaves_focus_on_the_handle() { let mut h = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules()); diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index d158b31c3..dd546a29e 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -288,6 +288,10 @@ pub struct PageViewOutput { pub visible: Range, /// The current page changed (scrolling, the wheel turning a page, a tool's view). pub current_changed: bool, + /// The reader scrolled the view this pass: the wheel (its scroll, or the page it turned), a drag or a press on a + /// scroll bar, or the view's page and arrow keys. A zoom, a go-to and a view the app or a tool set are not the + /// reader's scroll, so an app that follows something with the view (search results) stops following on this. + pub scrolled: bool, /// A double-click on the gap between pages: the app toggles Hide White Space (Word). pub toggle_white_space: bool, /// The pasteboard outside the pages (`None` when the pass drew nothing): a secondary press or the Menu key there asks the app for Photoshop's @@ -476,6 +480,7 @@ impl<'a> PageView<'a> { layout: seen.geo.layout.clone(), visible: seen.visible, current_changed: seen.current_changed, + scrolled: seen.scrolled, toggle_white_space, pasteboard: seen.pasteboard, textures: seen.textures, @@ -506,6 +511,7 @@ struct Seen { pages: Vec, visible: Range, current_changed: bool, + scrolled: bool, pasteboard: Option, textures: TextureStatistics, /// What the caller stores after the real run. @@ -531,6 +537,7 @@ impl Seen { pages: Vec::new(), visible: 0..0, current_changed: false, + scrolled: false, pasteboard: None, textures: TextureStatistics::default(), next: None, @@ -655,6 +662,7 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> } } let keys = KeyMoves::of(space.keys(), &state, &geo, rect, f64::from(navigation.key_line)); + let mut scrolled = keys.moves() || wheel.is_some_and(|wheel| !zooming && wheel.scroll != Vec2::ZERO); want.0 += keys.pan.0; want.1 = if keys.to_end { f64::INFINITY } else { want.1 + keys.pan.1 }; @@ -753,6 +761,7 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> let bars = CanvasScrollbars::new(words.scroll_bars.clone(), Bind::given(target), DocRect::from_origin_size(Point::ZERO, document)).show_at(ui, cx.rect); let bar_drag = bars.view.value().is_some(); + scrolled |= bar_drag; if let Some(moved) = bars.view.value() { want = drawn_frame.offset_of(moved.center, vw, vh); } @@ -785,6 +794,7 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> pages, visible, current_changed, + scrolled, pasteboard: Some(pasteboard), textures, next: Some(Next { started, state, mem, edit: words.edit.as_str().to_owned() }), @@ -898,13 +908,23 @@ struct KeyMoves { impl KeyMoves { /// Page Up and Down a screen less a key line (a row when not continuous), Home and End the first and last page, Up /// and Down a key line (not continuous, a turn once the row is at its edge that way), Left and Right a page when - /// the page fits the width, else a key line sideways. + /// the page fits the width, else a key line sideways. Home and End with Shift or Cmd, and Page Up, Page Down, Up and + /// Down with Shift and Cmd together, go to the first or last page; Alt, and Shift or Cmd alone with the other keys, + /// leave them to nothing. fn of(keys: BodyKeys, state: &PageViewState, geo: &Placed, rect: Rect, line: f64) -> KeyMoves { let last = geo.layout.rects.len().saturating_sub(1); let top = |page: usize| Some(GoTo::Top { page, fraction: 0.0 }); let mut moves = KeyMoves::default(); - // Shift, Cmd and Alt leave the keys to nothing, as in the old view. + let end = |forward: bool| if forward && state.continuous { (true, None) } else { (false, top(if forward { last } else { 0 })) }; let plain = |mods: &MoveMods| !mods.extend && !mods.lead && !mods.fine; + let to_end = match keys.page { + Some((step @ (NavMove::Start | NavMove::End), mods)) if !mods.fine => Some(step == NavMove::End), + Some((step @ (NavMove::PageUp | NavMove::PageDown), mods)) if mods.extend && mods.lead && !mods.fine => Some(step == NavMove::PageDown), + _ => None, + }; + if let Some(forward) = to_end { + (moves.to_end, moves.go_to) = end(forward); + } match keys.page.filter(|(_, mods)| plain(mods)).map(|(step, _)| step) { Some(step @ (NavMove::PageUp | NavMove::PageDown)) => { let forward = step == NavMove::PageDown; @@ -916,11 +936,17 @@ impl KeyMoves { moves.turn = Some(forward); } } - Some(NavMove::Start) => moves.go_to = top(0), - Some(NavMove::End) if state.continuous => moves.to_end = true, - Some(NavMove::End) => moves.go_to = top(last), _ => {} } + if let Some((direction, mods)) = keys.nudge + && direction.y != 0.0 + && mods.shift + && (mods.cmd || mods.ctrl) + && !mods.alt + { + (moves.to_end, moves.go_to) = end(direction.y > 0.0); + return moves; + } let Some((direction, _)) = keys.nudge.filter(|(_, mods)| mods.is_none()) else { return moves }; if direction.y != 0.0 { moves.line_down(direction.y > 0.0, state, geo, rect, line); @@ -938,6 +964,11 @@ impl KeyMoves { moves } + /// Whether the keys move the view. + fn moves(&self) -> bool { + self.pan != (0.0, 0.0) || self.to_end || self.turn.is_some() || self.go_to.is_some() + } + /// Up or Down (`forward`): a key line, or, not continuous with the row at its edge that way, a turn. fn line_down(&mut self, forward: bool, state: &PageViewState, geo: &Placed, rect: Rect, line: f64) { if !state.continuous && edge_ahead(geo, state.offset.1, f64::from(rect.height()), forward).is_some() { diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 4ed94e503..12ca7adc5 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -37,11 +37,13 @@ struct Out { visible: Range, /// The view on screen. view: egui::Rect, + /// Some pass since the trial last cleared it reported the reader's scroll. + scrolled: bool, } impl Default for Out { fn default() -> Self { - Out { offset: (0.0, 0.0), rects: Vec::new(), pages: Vec::new(), visible: 0..0, view: egui::Rect::NOTHING } + Out { offset: (0.0, 0.0), rects: Vec::new(), pages: Vec::new(), visible: 0..0, view: egui::Rect::NOTHING, scrolled: false } } } @@ -89,8 +91,9 @@ fn rig_over(source: impl PageSource + 'static, start: PageViewState, navigation: let keep = held.borrow().clone(); let shown = PageView::new("Pages", &source, &mut now, PAPER).options(LayoutOptions::ACROBAT).navigation(navigation).keep(&keep).show(ui, |_, _| ()); + let scrolled = seen.borrow().scrolled || shown.scrolled; *seen.borrow_mut() = - Out { offset, rects: shown.layout.rects.clone(), pages: shown.pages, visible: shown.visible, view: shown.canvas.response.rect }; + Out { offset, rects: shown.layout.rects.clone(), pages: shown.pages, visible: shown.visible, view: shown.canvas.response.rect, scrolled }; *kept.borrow_mut() = now; }); fixture.room(vec2(900.0, 600.0)); @@ -305,6 +308,28 @@ fn page_keys_turn_and_go_to_the_ends_in_a_view_that_is_not_continuous() { assert_eq!(state.borrow().current, 0, "Home goes to the first page"); } +#[trial] +fn shift_and_command_with_the_page_keys_and_arrows_go_to_the_ends() { + let both = Modifiers::COMMAND | Modifiers::SHIFT; + for continuous in [false, true] { + let (mut fixture, state, _) = layout_rig( + 5, + state_with(|s| { + s.continuous = continuous; + s.fit = Fit::Page; + }), + ); + focus_canvas(&mut fixture); + let keys = [(Key::PageDown, both, 4), (Key::PageUp, both, 0), (Key::ArrowDown, both, 4), (Key::ArrowUp, both, 0)]; + let ends = [(Key::End, Modifiers::SHIFT, 4), (Key::Home, Modifiers::SHIFT, 0), (Key::End, Modifiers::COMMAND, 4), (Key::Home, Modifiers::COMMAND, 0)]; + for (key, mods, want) in keys.into_iter().chain(ends) { + fixture.key(key, mods); + fixture.idle(2); + assert_eq!(state.borrow().current, want, "{key:?} with {mods:?}, continuous {continuous}"); + } + } +} + #[trial] fn arrows_go_to_the_next_page_and_scroll_a_line_in_a_continuous_view() { // Right, then Down, in a view whose key line is `key_line`: the page reached and how far Down scrolled. @@ -796,3 +821,35 @@ fn a_scroll_bar_drag_holds_the_sharp_renders_of_the_part_in_view_in_its_own_pass fixture.settle(); assert!(*parts.borrow() > before, "the part in view is rendered once the drag ends"); } + +#[trial] +fn the_view_reports_the_readers_wheel_and_scroll_bar_but_not_a_go_to_or_a_zoom() { + let Rig { mut fixture, state, out, .. } = rig(5, state_with(|s| s.fit = Fit::Width)); + let scrolled_by =|fixture: &mut Fixture, what: &mut dyn FnMut(&mut Fixture)| { + out.borrow_mut().scrolled = false; + what(fixture); + fixture.settle(); + out.borrow().scrolled + }; + let go_to = scrolled_by(&mut fixture, &mut |fixture| { + state.borrow_mut().go_to = Some(GoTo::Top { page: 3, fraction: 0.0 }); + fixture.idle(2); + }); + assert!(!go_to, "the app's go-to is not the reader's scroll"); + assert_eq!(state.borrow().current, 3, "precondition: the go-to moved the view"); + let zoom = scrolled_by(&mut fixture, &mut |fixture| { + fixture.key(Key::Equals, Modifiers::COMMAND); + }); + assert!(!zoom, "a zoom is not a scroll"); + let wheeled = scrolled_by(&mut fixture, &mut |fixture| wheel(fixture, -1.0)); + assert!(wheeled, "the wheel's scroll is the reader's"); + let bar = + fixture.by_role(Role::SCROLL_BAR).into_iter().max_by(|a, b| a.rect.height().total_cmp(&b.rect.height())).expect("the view has scroll bars"); + let dragged = scrolled_by(&mut fixture, &mut |fixture| { + let grab = pos2(bar.rect.center().x, bar.rect.max.y - 4.0); + fixture.frame(vec![craft_ui::testing::pointer::moved(grab)]); + fixture.frame(vec![craft_ui::testing::pointer::press(grab)]); + fixture.frame(vec![craft_ui::testing::pointer::release(grab)]); + }); + assert!(dragged, "a press on the scroll bar's track is the reader's scroll"); +} diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 241a505de..0e824598d 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -774,6 +774,17 @@ impl ToolPass { pub(crate) fn clamped(&self, view: CanvasView) -> CanvasView { clamped(view, self.document, &self.navigation) } + + /// Hides the pointer for this pass while it is over the canvas, over every other request, links and the tool's + /// cursor included (`CursorPriority::Hidden`): a body that hides a still pointer (a full-screen presentation) asks + /// in each pass the pointer should stay hidden, and stops asking when it moves. A measuring run publishes no pass, + /// so only the real run asks. + pub fn hide_pointer(&self, ui: &egui::Ui) { + if ui.ctx().pointer_hover_pos().is_some_and(|at| self.rect.contains(at)) { + let hidden = craft_behavior::Cursor::Painted(craft_behavior::PaintedCursor::Hidden); + crate::runtime::cursor::request(ui.ctx(), hidden, CursorPriority::Hidden); + } + } } impl Outcome for CanvasOutput { diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 09d7d6179..2830eec46 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -337,8 +337,8 @@ impl BackgroundPress { } /// Where `press` is the release of a secondary press: the one reading of a context press from a part's press. The press -/// machine captures a secondary press only for a part that senses a drag or a `CONTEXT_CLICK`, so the release is the -/// request whether or not the pointer moved. +/// machine gives a secondary press only to a part that senses `CONTEXT_CLICK`, so the release is the request whether +/// or not the pointer moved. pub fn context_click(press: &PressState) -> Option { match press.phase { PressPhase::Release { start, pos, .. } if start.button == PointerButton::Secondary => Some(pos), diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index 74513f6d0..6d53210ab 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -238,6 +238,46 @@ fn a_gesture_cancelled_by_the_app_starts_no_new_one_while_the_button_stays_down( assert_eq!(fixture.tool().count(Call::Press), 2, "the next press starts a gesture again: {:?}", fixture.tool().calls); } +#[trial] +fn a_body_hides_the_pointer_over_the_canvas_over_the_tools_cursor_while_it_asks() { + let hide = Rc::new(Cell::new(false)); + let asks = Rc::clone(&hide); + let room = Rc::new(Cell::new(Rect::NOTHING)); + let shown_room = Rc::clone(&room); + let tool = RefCell::new(Recorder::default()); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + shown_room.set(room); + let view = CanvasView::new(room, Point::new(600.0, 450.0), 1.0); + Canvas::new("Document").document(DOCUMENT).view(view).show_at(ui, room.shrink(40.0), |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()); + if asks.get() { + pass.hide_pointer(ui); + } + } + }); + }); + fixture.settle(); + let hidden = |fixture: &Fixture| { + craft_ui::runtime::cursor::current(fixture.ctx()) == Some(Cursor::Painted(craft_behavior::PaintedCursor::Hidden)) + }; + let (over, beside) = (room.get().center(), room.get().min + Vec2::splat(10.0)); + fixture.frame(vec![pointer::moved(over)]); + fixture.frame(Vec::new()); + assert!(!hidden(&fixture), "precondition: the tool's cursor shows over the canvas"); + hide.set(true); + fixture.frame(Vec::new()); + assert!(hidden(&fixture), "the body's request hides the pointer over the canvas"); + fixture.frame(vec![pointer::moved(beside)]); + fixture.frame(Vec::new()); + assert!(!hidden(&fixture), "beside the canvas the pointer shows"); + fixture.frame(vec![pointer::moved(over)]); + hide.set(false); + fixture.frame(Vec::new()); + assert!(!hidden(&fixture), "once the body stops asking, the pointer shows again"); +} + /// A tool with a rubber band that follows the hovering pointer, which asks for the hover autoscroll when `scrolls`. struct Band { scrolls: bool, diff --git a/crates/ui-contract/src/contract/cx/parts.rs b/crates/ui-contract/src/contract/cx/parts.rs index 3e6c223d6..223d4325f 100644 --- a/crates/ui-contract/src/contract/cx/parts.rs +++ b/crates/ui-contract/src/contract/cx/parts.rs @@ -403,18 +403,20 @@ impl PartsCx<'_, C> { /// Declares one axis's scroll bar: the track as part `key` and the thumb as part `key.at(THUMB)`, inside /// `rect`. The pipeline runs thumb drag, end drag when the span resizes its ends, and page press on the - /// track; `Pointer::scroll_moved(key)` reads the range the part moved to. + /// track; `Pointer::scroll_moved(key)` reads the range the part moved to. Both parts take a secondary press + /// (`Sense::CONTEXT_CLICK`), which pages nothing: a right-click on a bar is its component's, not the content's + /// beneath it. pub fn scroll(&mut self, key: PartKey, rect: Rect, axis: Axis, span: ScrollSpan) { let rtl = self.flow.is_rtl(); let min_thumb = crate::style::min_thumb(self.measure.tokens); let thumb = crate::primitives::ScrollBar::thumb(min_thumb, rect, axis, rtl, &span); self.part(key, rect) - .sense(Sense::CLICK) + .sense(Sense::CLICK | Sense::CONTEXT_CLICK) .access_click(!thumb_covers_centre(rect, thumb, axis)) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only("Page Up and Page Down scroll the region"); self.part(key.at(THUMB), thumb) - .sense(Sense::DRAG) + .sense(Sense::DRAG | Sense::CONTEXT_CLICK) .priority(HitPriority::new(HitLevel::Body, 1)) .pointer_only("Page Up and Page Down scroll the region"); self.scrolls.push(ScrollDecl { key, axis, rtl, track: rect, thumb, span, min_thumb }); diff --git a/crates/ui-contract/src/contract/cx/scroll.rs b/crates/ui-contract/src/contract/cx/scroll.rs index 673998b0b..95395377b 100644 --- a/crates/ui-contract/src/contract/cx/scroll.rs +++ b/crates/ui-contract/src/contract/cx/scroll.rs @@ -58,7 +58,9 @@ pub(crate) fn scroll_moves(decls: &[ScrollDecl], results: &PartResults) -> Vec Some(craft_behavior::scroll::drag(&decl.span, length, decl.min_thumb, along(delta))), - (_, Some(PressPhase::Down { start, .. })) => Some(page_toward(axis_pos(start.origin))), + (_, Some(PressPhase::Down { start, .. })) if start.button == craft_behavior::PointerButton::Primary => { + Some(page_toward(axis_pos(start.origin))) + } _ => None, }; let middle = decl.track.center(); diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index d45f5c0a1..24b06a831 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -865,7 +865,7 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab .delta(delta) .cancel(cancel); let mut machine = std::mem::take(&mut state.machine); - let step = machine.step(input, |at| { + let step = machine.step(input, |at, button| { // 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, @@ -880,7 +880,7 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab } else { true }; - let winners = pointer::press_winners(ctx, at, targets); + let winners = pointer::press_winners(ctx, at, targets, button); 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 { @@ -908,7 +908,7 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab let step = match step.passes { Some(start) => { let root = state.root.map(|root| root.id); - let winners = pointer::press_winners(ctx, start.origin, pass_pointer.press_targets); + let winners = pointer::press_winners(ctx, start.origin, pass_pointer.press_targets, start.button); winners .drag .filter(|(_, owner)| Some(*owner) == root) diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 121d07ac9..3f3f9469b 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -234,7 +234,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { // 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 hover = hover_at.map(|at| (at, hover_targets, find_under(ctx, viewport, at, hover_targets, false))); let captured = press_captured(ctx); PerViewport::::with(ctx, viewport, |shapes| { shapes.hover = hover; @@ -653,9 +653,14 @@ impl Under { } /// 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 { +/// press is at the hover point, else found once per point and targets. A secondary press (`button`) is resolved among +/// the shapes that sense `Sense::CONTEXT_CLICK` alone: a shape on top that takes no context click passes it to the next +/// one under it, so a box that only drags leaves a right-click to the page beneath. +pub(crate) fn press_winners(ctx: &Context, at: Pos2, targets: PressTargets, button: PointerButton) -> PressWinners { let viewport = pass::current_viewport(ctx); + if button == PointerButton::Secondary { + return find_under(ctx, viewport, at, targets, true).press; + } let found = PerViewport::::with(ctx, viewport, |record| { [&record.hover, &record.winner] .into_iter() @@ -666,7 +671,7 @@ pub(crate) fn press_winners(ctx: &Context, at: Pos2, targets: PressTargets) -> P if let Some(found) = found { return found; } - let under = find_under(ctx, viewport, at, targets); + let under = find_under(ctx, viewport, at, targets, false); let found = under.press; PerViewport::::with(ctx, viewport, |record| record.winner = Some((at, targets, under))); found @@ -675,7 +680,7 @@ pub(crate) fn press_winners(ctx: &Context, at: Pos2, targets: PressTargets) -> P /// 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)> { - let winners = press_winners(ctx, at, targets); + let winners = press_winners(ctx, at, targets, PointerButton::Primary); winners.click.or(winners.drag) } @@ -692,7 +697,9 @@ 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 { +/// What lies under `at` ([`Under`]); with `context`, for a secondary press: its press winners only among the shapes +/// that sense `Sense::CONTEXT_CLICK`. +fn find_under(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTargets, context: bool) -> 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 { @@ -760,14 +767,25 @@ fn find_under(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTarge { top = Some((rank, winner, root)); } - if let Some((rank, winner)) = pick(&kept, ResolveFor::Press) { + let takes_context = |index: &usize| { + let sense = entry.shapes[*index].sense; + !sense.takes_press() || sense.contains(craft_behavior::Sense::CONTEXT_CLICK) + }; + let context_kept: Vec; + let pressable: &[usize] = if context { + context_kept = kept.iter().copied().filter(takes_context).collect(); + &context_kept + } else { + &kept + }; + if let Some((rank, winner)) = pick(pressable, ResolveFor::Press) { // A shape that passes its drag keeps the click; the root's next shape under it that drags follows it // in the ranking, at its rank: the stable sort in `winners_of` keeps it right after the winner. let passes = winner.sense.contains(craft_behavior::Sense::CLICK | craft_behavior::Sense::PASSES_DRAG) && !winner.sense.contains(craft_behavior::Sense::DRAG); let below = passes .then(|| { - let dragging: Vec = kept + let dragging: Vec = pressable .iter() .copied() .filter(|&index| index != winner.index && entry.shapes[index].sense.contains(craft_behavior::Sense::DRAG)) diff --git a/crates/ui-contract/tests/it/runtime/pointer.rs b/crates/ui-contract/tests/it/runtime/pointer.rs index 61e3b9b50..14beeb940 100644 --- a/crates/ui-contract/tests/it/runtime/pointer.rs +++ b/crates/ui-contract/tests/it/runtime/pointer.rs @@ -1,6 +1,6 @@ //! The sensing core over probe roots: the press lifecycle, arenas, press targets, parts and the shape record. -use craft_behavior::{CanvasTransform, HitLevel, PartKey, PressPhase, Sense}; +use craft_behavior::{CanvasTransform, HitLevel, PartKey, PointerButton, PressPhase, Sense}; use craft_ui::testing::pointer::{self, drag}; use craft_ui::testing::sensing::{ProbeMember, ProbePart, ProbeRoot, RootReport, SenseReport, egui_click_target, show}; use craft_ui::testing::{Frames, trial}; @@ -525,6 +525,42 @@ fn a_press_over_a_passing_click_part_hands_its_drag_to_the_shape_below_in_its_ro } } +/// A secondary press over a part that drags and clicks but takes no context click (a transform box's) goes to the +/// context target under it, in its own root or in the root below, and the box sees none of it; a primary press there +/// is still the box's. +#[trial] +fn a_right_click_over_a_drag_only_part_reaches_the_context_target_under_it() { + let page = rect(100.0, 100.0, 400.0, 300.0); + let box_rect = rect(150.0, 150.0, 120.0, 80.0); + let handle = || ProbePart::new(CORNER, box_rect, Sense::DRAG | Sense::CLICK).level(HitLevel::Handle, 0); + let surface = || ProbePart::new(SURFACE, page, Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK).level(HitLevel::Background, 0); + let own = vec![ProbeRoot::new("page", page, Sense::empty()).part(surface()).part(handle())]; + let stacked = vec![ProbeRoot::new("page", page, Sense::empty()).part(surface()), ProbeRoot::new("box", box_rect, Sense::empty()).part(handle())]; + for (case, roots, box_root) in [("in its own root", own, 0), ("in the root below", stacked, 1)] { + let (mut show_frame, log) = scene(roots); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + let on_box = box_rect.center(); + move_to(&mut frames, on_box, &mut show_frame); + log.borrow_mut().clear(); + frames.frame(vec![pointer::secondary(on_box, true)], &mut show_frame); + frames.frame(vec![pointer::secondary(on_box, false)], &mut show_frame); + frames.idle(1, &mut show_frame); + { + let log = log.borrow(); + let below = log.root_phases(0, Some(SURFACE)); + let released = below.iter().any(|phase| matches!(phase, PressPhase::Release { start, .. } if start.button == PointerButton::Secondary)); + assert!(released, "{case}: the context target under the box takes the right-click: {below:?}"); + let on = log.root_phases(box_root, Some(CORNER)); + assert!(on.is_empty(), "{case}: the box sees none of it: {on:?}"); + } + log.borrow_mut().clear(); + enter_and_click(&mut frames, on_box, &mut show_frame); + let log = log.borrow(); + assert_eq!(downs(&log.root_phases(box_root, Some(CORNER))), 1, "{case}: a primary press is still the box's"); + } +} + /// While a press on one root is held, another root the pointer moves over does not hover; it hovers once the press /// ends. #[trial]