diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 951facbca..046127e30 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -111,7 +111,7 @@ pub use sizing::{ControlMetrics, Metrics, Proposal}; pub use typing::{EditRun, Ended, EscapeRule, Escaped, Typed, TypingRun}; pub use value::{Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GesturePhase, Mixed, Validity, Value}; pub use value_drag::{DragWarp, ValueDrag, wrap_value}; -pub use wheel::{Wheel, WheelNotch, WheelPhase, WheelRoom, WheelTaker, WheelUnit}; +pub use wheel::{Wheel, WheelFocus, WheelNotch, WheelPhase, WheelRoom, WheelTaker, WheelUnit}; #[cfg(test)] extern crate self as craft_behavior; diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 39016592a..7b8ed030b 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -98,6 +98,9 @@ pub struct WheelTaker { /// A zoom zone: a vertical wheel over it goes to the innermost enclosing open taker of the zoom share, with /// `Wheel::zooms` set. A zone that takes no axis itself never takes a share. pub zooms_view: bool, + /// A value field: while it holds key focus it takes the field's share of the wheel wherever the pointer is + /// (`split`). + pub field: bool, } /// The scroll left in a region, in points of wheel scroll: `positive` is what a wheel with positive `scroll` can @@ -155,6 +158,7 @@ impl WheelTaker { notch: WheelNotch::DEFAULT, room: None, zooms_view: false, + field: false, } } @@ -178,6 +182,13 @@ impl WheelTaker { self } + /// Whether it is a value field (`WheelTaker::field`). + #[must_use] + pub const fn field(mut self, on: bool) -> Self { + self.field = on; + self + } + /// Whether it takes horizontal scroll. pub const fn horizontal(mut self, on: bool) -> Self { self.horizontal = on; @@ -241,12 +252,63 @@ impl WheelTaker { } } -/// The split rule: each axis of `wheel` goes to the innermost taker under `at` that takes it; a share no taker +/// Who holds key focus, as the split reads it. +#[derive(Clone, Copy, Debug, PartialEq, Default)] +#[non_exhaustive] +pub struct WheelFocus { + /// The taker that holds key focus. + pub taker: Option, + /// Key focus is in a text field the app drew itself, which reads its own wheel: its share goes to no taker. + pub app_field: bool, +} + +impl WheelFocus { + /// Focus on `taker`, or on nothing that takes the wheel. + pub const fn new(taker: Option) -> Self { + WheelFocus { taker, app_field: false } + } + + /// The same focus, in a text field the app drew itself when `on`. + #[must_use] + pub const fn app_field(mut self, on: bool) -> Self { + self.app_field = on; + self + } +} + +/// Whether `wheel` is a field's: a vertical scroll, or Shift's (which some devices send sideways), without Alt or +/// Cmd/Ctrl, which stay the view's. +fn for_field(wheel: &Wheel) -> bool { + let mods = wheel.mods; + !(mods.alt || mods.cmd || mods.ctrl) && (wheel.scroll.y != 0.0 || (mods.shift && wheel.scroll.x != 0.0)) +} + +/// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes +/// the field's share of the scroll wherever the pointer is: a vertical or Shift wheel without Alt or Cmd/Ctrl; an app's +/// field reads it itself, so no taker gets it. The rest splits by position: each axis of `wheel` goes to the innermost +/// taker under `at` that takes it; a share no taker /// takes, or that a scroll region at its end in that direction cannot move, passes to the next enclosing one. A gated taker takes no axis unless it is `focused` or /// `armed`. Shift turns a vertical wheel sideways when its vertical owner is a scroll region. When the innermost open /// taker under `at` for the vertical share is a zoom zone, the share goes to the innermost open zoom taker enclosing it, /// with `Wheel::zooms` set; without one the zone is passed over. Shares of one owner merge. -pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focused: Option, armed: Option) -> Vec<(O, Wheel)> { +pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option) -> Vec<(O, Wheel)> { + let field = focus.taker.filter(|focused| takers.iter().any(|taker| taker.field && taker.owner == *focused)); + if (field.is_some() || focus.app_field) && wheel.scroll != Vec2::ZERO && for_field(&wheel) { + let mut shares = if wheel.zoom == 1.0 { Vec::new() } else { split_at(takers, at, Wheel { scroll: Vec2::ZERO, ..wheel }, focus.taker, armed) }; + if let Some(owner) = field { + let scroll = Wheel { zoom: 1.0, ..wheel }; + match shares.iter_mut().find(|(o, _)| *o == owner) { + Some((_, share)) => share.scroll += scroll.scroll, + None => shares.push((owner, scroll)), + } + } + return shares; + } + split_at(takers, at, wheel, focus.taker, armed) +} + +/// The split by position. +fn split_at(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focused: Option, armed: Option) -> Vec<(O, Wheel)> { // Takers register outer first, so among equal areas the later one is the deeper (or the upper) and goes first. let mut under: Vec<&WheelTaker> = takers.iter().rev().filter(|taker| taker.rect.contains(at)).collect(); under.sort_by(|a, b| a.rect.area().total_cmp(&b.rect.area())); @@ -308,23 +370,42 @@ mod tests { let outer = WheelTaker::new(1u8, rect(200.0)).vertical(true).scrolls(true).room(WheelRoom::new(Vec2::splat(50.0), Vec2::splat(50.0))); let inner = WheelTaker::new(2u8, rect(100.0)).vertical(true).scrolls(true).room(WheelRoom::new(Vec2::ZERO, Vec2::splat(30.0))); let at = pos2(10.0, 10.0); - let owner = |y| split(&[outer, inner], at, wheel(0.0, y), None, None).first().map(|(o, _)| *o); + let owner = |y| split(&[outer, inner], at, wheel(0.0, y), WheelFocus::new(None), None).first().map(|(o, _)| *o); assert_eq!(owner(7.0), Some(1), "no room toward positive: the outer takes it"); assert_eq!(owner(-7.0), Some(2), "room toward negative: the inner keeps it"); } + #[test] + fn a_focused_field_takes_the_plain_wheel_wherever_the_pointer_is() { + let canvas = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).zoom(true); + let field = WheelTaker::new(2u8, Rect::from_min_size(pos2(400.0, 0.0), Vec2::splat(20.0))).vertical(true).gated(true).field(true); + let at = pos2(10.0, 10.0); + let owners = + |wheel: Wheel, focus: WheelFocus| split(&[canvas, field], at, wheel, focus, None).iter().map(|(o, _)| *o).collect::>(); + let focused = WheelFocus::new(Some(2)); + assert_eq!(owners(wheel(0.0, 5.0), WheelFocus::new(None)), [1], "no focus: the canvas under the pointer"); + assert_eq!(owners(wheel(0.0, 5.0), focused), [2], "the focused field, away from the pointer"); + let alt = Wheel { mods: Mods::ALT, ..wheel(0.0, 5.0) }; + let cmd = Wheel { mods: Mods::CMD, ..wheel(0.0, 5.0) }; + assert_eq!(owners(alt, focused), [1], "Alt stays the view's"); + assert_eq!(owners(cmd, focused), [1], "Cmd/Ctrl stays the view's"); + assert_eq!(owners(wheel(5.0, 0.0), focused), [1], "a sideways swipe stays the view's"); + assert_eq!(owners(wheel(0.0, 5.0), WheelFocus::new(None).app_field(true)), [] as [u8; 0], "an app's field reads its own"); + assert_eq!(owners(alt, WheelFocus::new(None).app_field(true)), [1]); + } + #[test] fn a_vertical_wheel_over_a_zoom_zone_zooms_the_enclosing_view() { let region = WheelTaker::new(1u8, rect(300.0)).vertical(true).scrolls(true); let view = WheelTaker::new(2u8, rect(200.0)).horizontal(true).zoom(true); let zone = WheelTaker::new(3u8, rect(100.0)).zooms_view(true); let at = pos2(10.0, 10.0); - let shares = split(&[region, view, zone], at, wheel(0.0, 5.0), None, None); + let shares = split(&[region, view, zone], at, wheel(0.0, 5.0), WheelFocus::new(None), None); assert_eq!(shares.len(), 1); assert_eq!((shares[0].0, shares[0].1.scroll.y, shares[0].1.zooms), (2, 5.0, true), "the view zooms by the vertical share"); - let shares = split(&[region, zone], at, wheel(0.0, 5.0), None, None); + let shares = split(&[region, zone], at, wheel(0.0, 5.0), WheelFocus::new(None), None); assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::>(), [(1, false)], "no zoom taker: the zone is passed over"); - let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), None, None); + let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), WheelFocus::new(None), None); assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::>(), [(2, false)], "the horizontal share passes the zone"); } } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index fa7251b36..137efd3ae 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -110,6 +110,7 @@ use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; use craft_behavior::{ CanvasTransform, CanvasView, EditEvent, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PointerButton, PressPhase, PressState, Sense, + WheelNotch, }; use egui::{Pos2, Rect, Response, Vec2}; use zoom_motion::{Steer, ViewMotion}; @@ -336,7 +337,7 @@ impl<'a> Canvas<'a> { } let mut jumped = false; if let Some(wheel) = cx.take_wheel() - && let Some(action) = motion.wheel.read(&wheel, &self.navigation) + && let Some(action) = motion.wheel.read(&wheel, WheelNavigation::LINE, cx.env.shell().os, &self.navigation) { let at = cx.response.hover_pos().unwrap_or_else(|| view.rect.center()); jumped |= WheelNavigation::apply(&mut view, action, at, size, pixels_per_point); @@ -510,6 +511,10 @@ impl Component for Canvas<'_> { Sense::FOCUS | Sense::TAKE_FOCUS | Sense::WHEEL } + fn wheel_notch(&self) -> WheelNotch { + WheelNotch::Points(WheelNavigation::LINE) + } + /// The view of this pass, kept for the body and `finish`. fn update(&mut self, cx: &mut Cx<'_, Self>) { // Left untaken: the canvas's generic context request is recorded as for a secondary click. diff --git a/crates/ui-canvas/src/canvas/navigate/wheel.rs b/crates/ui-canvas/src/canvas/navigate/wheel.rs index c022fa1d2..659fcd9a9 100644 --- a/crates/ui-canvas/src/canvas/navigate/wheel.rs +++ b/crates/ui-canvas/src/canvas/navigate/wheel.rs @@ -8,8 +8,8 @@ use super::NavigationOptions; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Size; -use craft_behavior::{CanvasView, Wheel, WheelNotch, ZoomLadder}; -use craft_keymap::Mods; +use craft_behavior::{CanvasView, Wheel, WheelNotch, WheelUnit, ZoomLadder}; +use craft_keymap::{Mods, Platform}; use egui::{Pos2, Vec2}; /// What the wheel or a pinch does to the view this pass. @@ -34,18 +34,19 @@ pub struct WheelInput { pub zoom: f32, /// The modifiers held. pub mods: Mods, - /// Points per wheel notch. + /// Points per zoom notch. pub notch: f32, + /// The OS, which decides where the Control key is among the modifiers. + pub os: Platform, } impl WheelInput { - /// The input of `wheel`, whose notch is the service's default distance. - pub fn of(wheel: &Wheel) -> Self { - let notch = match WheelNotch::DEFAULT { - WheelNotch::Points(points) => points, - _ => 1.0, - }; - WheelInput { scroll: wheel.scroll, zoom: wheel.zoom, mods: wheel.mods, notch } + /// The input of `wheel` for a taker whose wheel line is `line` points, on `os`. A line is one zoom notch; a + /// device that scrolls in points zooms a notch every default line ([`WheelNotch::DEFAULT`]), whatever the taker's + /// line. + pub fn of(wheel: &Wheel, line: f32, os: Platform) -> Self { + let notch = if wheel.unit == WheelUnit::Line { line } else { WheelNotch::DEFAULT.points(0.0) }; + WheelInput { scroll: wheel.scroll, zoom: wheel.zoom, mods: wheel.mods, notch, os } } /// The scroll along the wheel's axis whichever one the device reported it on (some systems send a modified wheel @@ -58,7 +59,9 @@ impl WheelInput { /// Mouse wheel and trackpad navigation, as in Photoshop: /// /// - The wheel scrolls up and down; Shift or Cmd/Ctrl + wheel scrolls sideways. -/// - Alt + wheel zooms about the pointer, 1.1 a notch; Shift + Alt + wheel steps the ladder. +/// - Alt + wheel zooms about the pointer, 1.1 a notch; Shift + Alt + wheel steps the ladder. Alt with the Control +/// key is the same zoom: on macOS Control may join it, elsewhere Ctrl (cmd) without Shift (production's #10488). +/// - A wheel line pans the canvas [`WheelNavigation::LINE`] points. /// - Zoom with Scroll Wheel swaps them: the wheel zooms, Alt + wheel scrolls, Shift + wheel steps the ladder. /// - A trackpad pinch zooms about the pointer (Zoom with Trackpad Pinch). /// @@ -72,12 +75,22 @@ impl WheelNavigation { /// The zoom factor of one wheel notch. pub const NOTCH: f64 = 1.1; + /// The points one wheel line pans the canvas: Photoshop's 16 (production's #12028). + pub const LINE: f32 = 16.0; + /// The most ladder steps one pass takes. const MOST_STEPS: f32 = 10.0; - /// The view change for `wheel` under `options`, if any. - pub fn read(&mut self, wheel: &Wheel, options: &NavigationOptions) -> Option { - self.classify(WheelInput::of(wheel), options) + /// The view change for `wheel`, given to a taker whose wheel line is `line` points, on `os`, under `options`, if + /// any. + pub fn read(&mut self, wheel: &Wheel, line: f32, os: Platform, options: &NavigationOptions) -> Option { + self.classify(WheelInput::of(wheel, line, os), options) + } + + /// Whether `mods` make the Alt zoom gesture on `os`: Alt, with the Control key allowed, which is `ctrl` on macOS + /// (⌘ keeps the wheel out of it) and `cmd` elsewhere, where Shift with it keeps the wheel a scroll. + fn alt_gesture(mods: Mods, os: Platform) -> bool { + mods.alt && (!mods.cmd || (!os.is_mac() && !mods.shift)) } /// The view change for one pass of `input` under `options`, if any. @@ -90,7 +103,7 @@ impl WheelNavigation { } let scroll_finite = input.scroll.x.is_finite() && input.scroll.y.is_finite(); let plain = !input.mods.cmd && !input.mods.ctrl; - let zooms = plain && input.mods.alt != options.zoom_with_wheel; + let zooms = if options.zoom_with_wheel { plain && !input.mods.alt } else { Self::alt_gesture(input.mods, input.os) }; if zooms && input.mods.shift { return scroll_finite.then(|| self.snap(input.along(), notch)).flatten().map(WheelAction::SnapZoom); } diff --git a/crates/ui-canvas/src/canvas/navigator/preview.rs b/crates/ui-canvas/src/canvas/navigator/preview.rs index 3fc8d93db..ad069c743 100644 --- a/crates/ui-canvas/src/canvas/navigator/preview.rs +++ b/crates/ui-canvas/src/canvas/navigator/preview.rs @@ -406,7 +406,8 @@ impl Component for Navigator<'_> { && !running { let options = NavigationOptions { zoom_with_wheel: true, ..self.navigation }; - let action = cx.memory::().read(&wheel, &options); + let (line, os) = (craft_behavior::WheelNotch::DEFAULT.points(0.0), cx.env.shell().os); + let action = cx.memory::().read(&wheel, line, os, &options); if let Some(action @ (WheelAction::Zoom(_) | WheelAction::SnapZoom(_))) = action { let before = next; WheelNavigation::apply(&mut next, action, before.rect.center(), document, ppp); diff --git a/crates/ui-canvas/tests/it/canvas/navigate.rs b/crates/ui-canvas/tests/it/canvas/navigate.rs index e98a00540..ce2ccae6d 100644 --- a/crates/ui-canvas/tests/it/canvas/navigate.rs +++ b/crates/ui-canvas/tests/it/canvas/navigate.rs @@ -3,12 +3,16 @@ use craft_behavior::kurbo::{Point, Size}; use craft_behavior::{Axis, CanvasView, Wheel, WheelPhase, WheelUnit}; use craft_keymap::{Mods, Platform}; -use craft_ui::canvas::{Canvas, Guide, GuideKey, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, TouchpadGlide}; +use craft_ui::canvas::{ + Canvas, Guide, GuideKey, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, TouchpadGlide, ViewCommands, WheelNavigation, +}; use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::runtime::access::Role; -use craft_ui::runtime::commands::FirePhase; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::runtime::commands::{self, CommandRef, FirePhase, FireSource}; +use craft_ui::runtime::frame; +use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::text::NumberField; use egui::{Key, Modifiers, Vec2}; use std::cell::Cell; use std::rc::Rc; @@ -162,3 +166,112 @@ fn at_a_whole_device_zoom_with_no_rotation_the_shown_view_puts_document_pixels_o let p = set.view.to_screen(Point::new(17.0, 29.0)) * set.pixels_per_point; assert!((p.x - p.x.round()).abs() < 1e-3 && (p.y - p.y.round()).abs() < 1e-3, "a view set at a whole zoom is shown aligned: {p:?}"); } + +/// A canvas over a large document at zoom 1 below a framework number field and an app's own text field, on `os`: the +/// fixture, the view it shows, the number and where the app's field is. +fn wheel_rig(os: Platform) -> (Fixture, Rc>, Rc>>, Rc>) { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let number = Rc::new(Cell::new(Some(10.0))); + let app_field = Rc::new(Cell::new(egui::Rect::NOTHING)); + let (shown, value, field_at) = (Rc::clone(&view), Rc::clone(&number), Rc::clone(&app_field)); + let mut text = String::from("Layer 1"); + let mut fixture = Fixture::new(move |ui| { + let mut current = value.get(); + NumberField::new("Smoothing", Bind::bound(&mut current)).show(ui); + value.set(current); + field_at.set(ui.add(egui::TextEdit::singleline(&mut text)).rect); + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |_, _| {}); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.os(os); + // As an app that gives ⌘/Ctrl + wheel to the canvas sets egui: no wheel modifier is egui's own zoom. + fixture.ctx().options_mut(|options| options.input_options.zoom_modifier = Modifiers::NONE); + fixture.settle(); + (fixture, view, number, app_field) +} + +/// One wheel line of `dy` with `modifiers` over the middle of the canvas. +fn wheel_line(fixture: &mut Fixture, view: &Cell, dy: f32, modifiers: Modifiers) { + let at = view.get().rect.center(); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: Vec2::new(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers, + source: egui::MouseWheelSource::Wheel, + }]); +} + +#[trial] +fn a_wheel_line_pans_the_canvas_photoshops_line_and_ctrl_alt_zooms_as_alt_does() { + for os in [Platform::Mac, Platform::Windows, Platform::Linux] { + let (mut fixture, view, _, _) = wheel_rig(os); + let before = view.get(); + wheel_line(&mut fixture, &view, -1.0, Modifiers::NONE); + let panned = view.get(); + assert!((panned.center.y - before.center.y - f64::from(WheelNavigation::LINE)).abs() < 1e-3, "{os:?}: {before:?} -> {panned:?}"); + wheel_line(&mut fixture, &view, 1.0, Modifiers::ALT); + let alt = view.get().zoom / panned.zoom; + assert!((alt - WheelNavigation::NOTCH).abs() < 1e-3, "{os:?}: Alt + a line zooms a notch: {alt}"); + // egui reports Ctrl as `ctrl` with `command` off macOS, and the Control key as `ctrl` alone on macOS. + let ctrl_alt = if os.is_mac() { + Modifiers { alt: true, ctrl: true, ..Modifiers::NONE } + } else { + Modifiers { alt: true, ctrl: true, command: true, ..Modifiers::NONE } + }; + let at = view.get(); + wheel_line(&mut fixture, &view, 1.0, ctrl_alt); + assert!((view.get().zoom / at.zoom - WheelNavigation::NOTCH).abs() < 1e-3, "{os:?}: Ctrl + Alt zooms as Alt does"); + if os.is_mac() { + let at = view.get(); + wheel_line(&mut fixture, &view, 1.0, Modifiers { alt: true, mac_cmd: true, command: true, ..Modifiers::NONE }); + assert_eq!(view.get().zoom, at.zoom, "⌘ + ⌥ is no zoom"); + } + } +} + +#[trial] +fn a_focused_field_takes_the_plain_wheel_over_the_canvas_and_leaves_it_the_view_keys() { + let (mut fixture, view, number, _) = wheel_rig(Platform::Linux); + let field = fixture.by_label("Smoothing").expect("the number field"); + fixture.click(&field); + let before = view.get(); + wheel_line(&mut fixture, &view, 1.0, Modifiers::NONE); + assert_eq!(view.get(), before, "the canvas neither pans nor zooms"); + assert_eq!(number.get(), Some(11.0), "the field stepped"); + wheel_line(&mut fixture, &view, 1.0, Modifiers::ALT); + assert!(view.get().zoom > before.zoom, "Alt + wheel is still the view's zoom"); + let zoomed = view.get(); + wheel_line(&mut fixture, &view, 1.0, Modifiers::COMMAND); + assert!(view.get().center.x != zoomed.center.x, "Cmd/Ctrl + wheel still scrolls the view sideways"); + assert_eq!(number.get(), Some(11.0), "the view's wheel does not step the field"); + + let (mut fixture, view, _, app_field) = wheel_rig(Platform::Linux); + fixture.click_at(app_field.get().center()); + let before = view.get(); + wheel_line(&mut fixture, &view, 1.0, Modifiers::NONE); + assert_eq!(view.get(), before, "an app's own focused text field keeps the plain wheel from the canvas"); + wheel_line(&mut fixture, &view, 1.0, Modifiers::ALT); + assert!(view.get().zoom > before.zoom, "Alt + wheel is still the view's zoom"); +} + +#[trial] +fn the_view_commands_a_canvas_runs_are_in_the_frame_output_whatever_fired_them() { + let (mut fixture, view, _, _) = wheel_rig(Platform::Linux); + let canvas = fixture.by_role(Role::CANVAS)[0]; + fixture.click(&canvas); + frame::take_output(fixture.ctx()); + let before = view.get(); + fixture.key(Key::Num0, Modifiers::COMMAND); + assert!(commands::fire(fixture.ctx(), ViewCommands::ZoomIn, FireSource::Menu), "a menu row fires the canvas's command"); + fixture.frame(vec![]); + assert_ne!(view.get(), before, "the canvas ran them"); + let delivered: Vec<_> = frame::take_output(fixture.ctx()).delivered.into_iter().map(|fired| (fired.command, fired.source)).collect(); + assert_eq!( + delivered, + [(CommandRef::from(ViewCommands::FitOnScreen), FireSource::Key), (CommandRef::from(ViewCommands::ZoomIn), FireSource::Menu)] + ); +} diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 0bbfd8c29..cba0dc69c 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -408,6 +408,12 @@ pub trait Component: Meta + Sized { if Self::CANVAS_CONTROL { Sense::empty() } else { ::DEFAULT_SENSE } } + /// The distance one wheel line scrolls the component when it senses the wheel itself: the service converts the + /// device's lines to points with it. A scroll region and a collection state theirs in their props. + fn wheel_notch(&self) -> craft_behavior::WheelNotch { + craft_behavior::WheelNotch::DEFAULT + } + /// Named sub-rects: thumbs, chevrons, handles, segments and the roving groups over them. fn parts(&mut self, _rect: Rect, _cx: &mut PartsCx<'_, Self>) {} diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f9fa245b5..59867c73d 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -523,6 +523,8 @@ pub(crate) trait ErasedPass<'a> { fn sense(&self) -> Sense; /// The component's own sense. fn comp_sense(&self) -> Sense; + /// `Component::wheel_notch`. + fn wheel_notch(&self) -> craft_behavior::WheelNotch; /// Whether the component is bound, and whether its binding has a reset value. fn bound(&mut self) -> (bool, bool); fn paint_outset(&self, tokens: &crate::style::UiTokens) -> f32; @@ -901,7 +903,8 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h ShapeKind::Item => !own.intersects(Sense::WHEELS), }; if !inert && registers { - steps::register_wheel(&ctx, id, rect, own, e.bound().0 && !facts.binds_view, env.wheel); + let sensed = craft_behavior::WheelTaker::for_sense(id, rect, own).map(|taker| taker.notch(e.wheel_notch())); + steps::register_wheel(&ctx, id, rect, sensed, e.bound().0 && !facts.binds_view, facts.text(), env.wheel); } // 8 sense p.trace.mark(Step::Sense); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 6dde04669..5ab1cd851 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -244,6 +244,10 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { self.comp.sense() } + fn wheel_notch(&self) -> craft_behavior::WheelNotch { + self.comp.wheel_notch() + } + fn bound(&mut self) -> (bool, bool) { self.comp.bind().map_or((false, false), |bind| (true, bind.reset_value().is_some())) } diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index 513d0eba5..9f2de23db 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -3,22 +3,29 @@ use crate::runtime::env::WheelScope; use crate::runtime::wheel; use crate::style::{Flags, StateSet}; -use craft_behavior::Sense; use craft_theme::{State, StateMix}; use egui::{Context, Id, Rect}; -/// Registers a wheel taker for next pass's split (8.6) from the wheel bits of `sense` (`WheelTaker::for_sense`). A +/// Registers a wheel taker for next pass's split (8.6): `sensed`, the taker the wheel bits of the component's sense +/// make (`WheelTaker::for_sense`). A value control with a text part is a field (`WheelTaker::field`). A /// value control takes the wheel only while focused or armed, on the axes it senses (the vertical one when it senses /// none); inside a `WheelScope::Free` scope one that senses the wheel takes it without focus. Inside a /// `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that takes no axis itself waits only /// for a gated scope: its wheel goes to the view around it. -pub(crate) fn register_wheel(ctx: &Context, id: Id, rect: Rect, sense: Sense, value_control: bool, scope: WheelScope) { - let sensed = craft_behavior::WheelTaker::for_sense(id, rect, sense); +pub(crate) fn register_wheel( + ctx: &Context, + id: Id, + rect: Rect, + sensed: Option>, + value_control: bool, + text: bool, + scope: WheelScope, +) { let free = sensed.is_some() && scope == WheelScope::Free; let zone = sensed.is_some_and(|taker| taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom)); let taker = sensed.or_else(|| value_control.then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); if let Some(taker) = taker { - wheel::register(ctx, taker.gated(scope == WheelScope::Gated || (value_control && !free && !zone))); + wheel::register(ctx, taker.field(value_control && text).gated(scope == WheelScope::Gated || (value_control && !free && !zone))); } } diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 46db0c4d0..9d29d81ee 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -74,6 +74,8 @@ pub(crate) struct Board { queue: Vec, /// App-scope commands for the next `FrameOutput`. out: Vec, + /// The commands instances took since the last `FrameOutput`, in order. + delivered: Vec, instances: Vec, /// The focused component of each viewport's last step 12 and the instances around it. chains: HashMap, @@ -502,6 +504,11 @@ pub(crate) fn take_fired(ctx: &Context) -> Vec { with(ctx, |board| std::mem::take(&mut board.out)) } +/// The commands instances took since the last call. +pub(crate) fn take_delivered(ctx: &Context) -> Vec { + with(ctx, |board| std::mem::take(&mut board.delivered)) +} + /// Whether the component that holds key focus sits inside the instance `id`. #[doc(hidden)] pub fn focus_within(ctx: &Context, id: Id) -> bool { @@ -776,13 +783,14 @@ pub(crate) fn take(ctx: &Context, instance: Option, app: bool, from_ref: return None; } with(ctx, |board| { - if app { + let fired = if app { let at = board.out.iter().position(|fired| from_ref(&fired.command).is_some())?; - let fired = board.out.remove(at); - return Some((from_ref(&fired.command)?, fired)); - } - let at = board.queue.iter().position(|fired| fired.target == Some(instance) && from_ref(&fired.command).is_some())?; - let fired = board.queue.remove(at); + board.out.remove(at) + } else { + let at = board.queue.iter().position(|fired| fired.target == Some(instance) && from_ref(&fired.command).is_some())?; + board.queue.remove(at) + }; + board.delivered.push(fired.clone()); Some((from_ref(&fired.command)?, fired)) }) } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 48ded016a..087a97c81 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -24,7 +24,7 @@ pub(crate) use board::take as take_for_instance; #[doc(hidden)] pub use board::take_around; pub(crate) use board::{ - begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_fired, window_shortcuts, + begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_delivered, take_fired, window_shortcuts, }; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 13fdacf43..72c402efd 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -92,6 +92,9 @@ pub enum OuterEdit { pub struct FrameOutput { /// The app-scope commands fired since the last call, in order. pub fired: Vec, + /// The commands components took since the last call, in order, whatever fired them (a key, a menu row, the + /// palette): what ran inside the framework, for an app that records the commands it runs (an action recorder). + pub delivered: Vec, /// Text for the live announcement region. pub announcements: Vec, /// The chrome toggles the windows asked for since the last call, in order: each names its viewport and whether the @@ -335,6 +338,7 @@ pub(crate) fn in_pass(ctx: &Context) -> bool { pub fn take_output(ctx: &Context) -> FrameOutput { let mut output = pass_state::with::(ctx, |state| std::mem::take(&mut state.output)); output.fired = commands::take_fired(ctx); + output.delivered = commands::take_delivered(ctx); // The menu, palette and automation fires of the chrome and nav commands reach the app as ordinary fires with no // window: the focused window's shell takes a toggle, and its focus service a pane move, in the next pass. A key fire // already acted in the key stage. diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index faee87b26..bb9b9dbbb 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -8,7 +8,7 @@ use crate::runtime::frame::PerViewport; use crate::runtime::pointer; use crate::runtime::sampler; use craft_behavior::wheel::split; -use craft_behavior::{PointerButton, PointerEvent, Wheel, WheelPhase, WheelTaker, WheelUnit}; +use craft_behavior::{PointerButton, PointerEvent, Wheel, WheelFocus, WheelPhase, WheelTaker, WheelUnit}; use egui::{Context, Id, Pos2, Rect, Vec2}; #[derive(Default)] @@ -50,6 +50,8 @@ pub(crate) fn begin(ctx: &Context) { let frame = pass_pointer.frame.clone(); let wheel_in = input::wheel_read(ctx, 1.0, 1.0); let focused = focus::focused_stop(ctx).map(|(owner, _)| owner); + // A text field the app drew itself holds key focus: it reads its own wheel. + let app_field = wheel_in.is_some() && focus::record(ctx, viewport).host_focus && ctx.text_edit_focused(); let hover = pass_pointer.hover.or(frame.as_ref().and_then(|frame| frame.pos)); let pressed_on = pass_pointer .events @@ -89,7 +91,7 @@ pub(crate) fn begin(ctx: &Context) { } let share = Wheel::new(scroll, mods, unit, phase).zoom(frame.zoom).at(at); // The device's lines and pages become points of each taker: the notch is the scroll owner's to choose. - let shares = split(&state.last, at, share, focused, state.armed); + let shares = split(&state.last, at, share, WheelFocus::new(focused).app_field(app_field), state.armed); state.shares = shares .into_iter() .map(|(owner, mut share)| {