Skip to main content

nativeview_layout/scene/scroll/
engine.rs

1//! Pluggable per-surface scroll physics engine trait ([`ScrollPhysicsEngine`]), zero-cost default
2//! ([`InstantScrollPhysics`]), input modality types, and cross-platform `Shift+Wheel`
3//! normalization.
4//!
5//! [`LaidOutScene`](crate::LaidOutScene) defaults to [`InstantScrollPhysics`] (0 B state, 0 CPU
6//! overhead) so `nativeview-runtime`, `HeadlessBackend`, and OS-native widget hosts pay nothing for
7//! synthetic scroll physics. Custom-drawn hosts (e.g. `hosts/skia-shell`) install a full physics
8//! engine such as `nativeview-scroll-physics` via
9//! [`LaidOutScene::set_scroll_physics`](crate::LaidOutScene::set_scroll_physics).
10
11use nativeview_store::{NodeId, NodeStore};
12use nativeview_tables::tables::OverscrollBehavior;
13
14use super::ScrollOffsets;
15
16/// Monotonic millisecond timestamp for scroll gesture velocity tracking and latch expiry.
17#[repr(transparent)]
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct ScrollTimestampMs(pub u64);
20
21impl ScrollTimestampMs {
22    #[inline]
23    pub const fn new(ms: u64) -> Self {
24        Self(ms)
25    }
26
27    #[inline]
28    pub const fn as_u64(self) -> u64 {
29        self.0
30    }
31
32    #[inline]
33    pub const fn saturating_sub(self, earlier: Self) -> u64 {
34        self.0.saturating_sub(earlier.0)
35    }
36}
37
38/// Normalized trackpad/touch gesture phase for smooth pixel deltas.
39#[repr(u8)]
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
41pub enum ScrollTouchPhase {
42    #[default]
43    None = 0,
44    Started = 1,
45    Moved = 2,
46    Ended = 3,
47    Cancelled = 4,
48}
49
50/// Scroll input modality driving chaining, wheel smoothing, and rubber-band/momentum physics.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum ScrollInputKind {
53    /// Discrete mouse-wheel detents (deltas already scaled into logical pixels).
54    DiscreteLines,
55    /// Continuous trackpad / touch pixel deltas with gesture phase and monotonic millisecond clock.
56    SmoothPixels {
57        phase: ScrollTouchPhase,
58        timestamp_ms: u64,
59    },
60    /// Immediate deterministic delta without wheel smoothing or rubber-band animation.
61    Instant,
62}
63
64/// Axis selector for per-axis scroll physics callbacks.
65#[repr(u8)]
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum ScrollAxis {
68    X = 0,
69    Y = 1,
70}
71
72/// Default logical pixels per discrete mouse-wheel line detent (`48.0` on Windows, `40.0`
73/// elsewhere).
74#[inline]
75pub const fn default_px_per_line() -> f32 {
76    #[cfg(target_os = "windows")]
77    {
78        48.0
79    }
80    #[cfg(not(target_os = "windows"))]
81    {
82        40.0
83    }
84}
85
86/// Cross-platform `Shift+Wheel` normalization (zero macOS double-swap):
87/// swaps `(0, dy) -> (dy, 0)` only when `shift` is held and `dx` is effectively zero.
88/// macOS AppKit pre-swaps `Shift+Wheel` to `(dx, 0)`, so `dx.abs() >= 1e-4` makes this a no-op;
89/// 2-axis trackpads and unshifted vertical wheels over horizontal carousels remain untouched.
90#[inline]
91pub fn normalize_shift_wheel(dx: f32, dy: f32, shift: bool) -> (f32, f32) {
92    let dx = if dx.is_finite() { dx } else { 0.0 };
93    let dy = if dy.is_finite() { dy } else { 0.0 };
94    if shift && dx.abs() < 1e-4 && dy.abs() >= 1e-4 {
95        (dy, 0.0)
96    } else {
97        (dx, dy)
98    }
99}
100
101/// Read-only per-container context passed to [`ScrollPhysicsEngine::on_scroll_delta`] during
102/// nested ancestor scroll chaining.
103#[derive(Clone, Copy)]
104pub struct ScrollContainerCtx<'a> {
105    pub store: &'a NodeStore,
106    pub node: NodeId,
107    pub viewport: (f32, f32),
108    pub offset: (f32, f32),
109    pub max_offset: (f32, f32),
110    pub allow_axes: (bool, bool),
111    pub overscroll_behavior: (OverscrollBehavior, OverscrollBehavior),
112    pub bounce_requested: bool,
113}
114
115/// Per-container delta consumption outcome written by [`ScrollPhysicsEngine::on_scroll_delta`].
116#[derive(Debug, Clone, Copy, Default)]
117pub struct ScrollDeltaResult {
118    /// Updated clamped scroll offset `(x, y)` (pre-initialized to `ctx.offset`).
119    pub next_offset: (f32, f32),
120    /// Remaining unconsumed delta `(rem_x, rem_y)` to propagate to ancestor containers
121    /// (already zeroed on axes blocked by `OverscrollBehavior::{Contain, None}`).
122    pub remaining: (f32, f32),
123    /// Whether X / Y consumed any delta (overscroll unwind, wheel easing, or clamped scroll).
124    pub consumed_x: bool,
125    pub consumed_y: bool,
126    /// Whether visual presentation (clamped offset, overscroll, or animation state) changed.
127    pub visual_changed: bool,
128    /// Whether the clamped scroll offset changed (emits `ScrollEvent::Scroll` & a11y updates).
129    pub clamped_changed: bool,
130    /// Whether this container is eligible to absorb leftover `Auto`-chain overscroll on X / Y
131    /// if no ancestor consumes the remaining delta.
132    pub auto_overscroll_x: bool,
133    pub auto_overscroll_y: bool,
134}
135
136/// Read-only scroll container bounds lookup passed to [`ScrollPhysicsEngine::on_gesture_start`]
137/// and [`ScrollPhysicsEngine::step`] so engines can resolve ancestor bounds and top-layer overlay
138/// boundaries without allocating.
139pub trait ScrollBoundsLookup {
140    /// Returns `(viewport_w, viewport_h, max_x, max_y)` for `node`, or `None` if unlaid-out.
141    fn scroll_bounds(&self, store: &NodeStore, node: NodeId) -> Option<(f32, f32, f32, f32)>;
142
143    /// Returns `true` when `node` is an open top-layer overlay root whose scroll chain must not
144    /// cross into DOM ancestors behind it.
145    #[inline]
146    fn is_top_layer_boundary(&self, _node: NodeId) -> bool {
147        false
148    }
149}
150
151/// Pluggable per-surface scroll physics engine (Tier 3 surface-level engine trait).
152///
153/// Any physics engine (analytical decay/spring, RK4 integrator, Flutter `Simulation`, external
154/// physics library) can implement this trait directly and install onto [`crate::LaidOutScene`]
155/// via [`crate::LaidOutScene::set_scroll_physics`].
156pub trait ScrollPhysicsEngine: Send {
157    /// Consumes `(dx, dy)` on one scroll container along the ancestor chain.
158    ///
159    /// `out` is pre-initialized with `next_offset = ctx.offset`, `remaining = (dx, dy)`, and
160    /// `false` flags. Implementations mutate `out` in-place with zero steady-state allocations.
161    fn on_scroll_delta(
162        &mut self,
163        ctx: &ScrollContainerCtx<'_>,
164        dx: f32,
165        dy: f32,
166        kind: ScrollInputKind,
167        out: &mut ScrollDeltaResult,
168    );
169
170    /// Called on `ScrollTouchPhase::Started` to latch `start`, catch in-flight animations on its
171    /// ancestor chain (stopping at top-layer overlay boundaries), and finalize abandoned drags on
172    /// other containers.
173    fn on_gesture_start(
174        &mut self,
175        _store: &NodeStore,
176        _bounds: &dyn ScrollBoundsLookup,
177        _start: NodeId,
178        _now_ms: ScrollTimestampMs,
179    ) {
180    }
181
182    /// Returns the currently latched gesture target node, if any.
183    fn latched_target(&self) -> Option<NodeId> {
184        None
185    }
186
187    /// Updates monotonic gesture timestamp on `ScrollTouchPhase::Moved`.
188    fn on_gesture_move(&mut self, _now_ms: ScrollTimestampMs) {}
189
190    /// Feeds leftover unconsumed `OverscrollBehavior::Auto` delta into the outermost eligible
191    /// container on `axis`. Returns `true` if visual overscroll changed.
192    fn on_outermost_overscroll(
193        &mut self,
194        _ctx: &ScrollContainerCtx<'_>,
195        _axis: ScrollAxis,
196        _rem: f32,
197        _kind: ScrollInputKind,
198    ) -> bool {
199        false
200    }
201
202    /// Called when a phased trackpad/touch gesture ends or is cancelled, transitioning active
203    /// drags into fling momentum, snap animations, or boundary return springs. Any immediate
204    /// clamped offset changes must push affected node IDs into both `out_visual` and `out_clamped`.
205    fn on_gesture_end(
206        &mut self,
207        _store: &NodeStore,
208        _scroll: &mut ScrollOffsets,
209        _now_ms: ScrollTimestampMs,
210        _cancelled: bool,
211        _out_visual: &mut Vec<NodeId>,
212        _out_clamped: &mut Vec<NodeId>,
213    ) {
214    }
215
216    /// Advances all active scroll animations by `dt_s` seconds, writing clamped offset updates
217    /// into `scroll` and pushing affected container IDs into `out_visual` / `out_clamped` with
218    /// zero steady-state heap allocations. Returns `true` while any animation remains active.
219    fn step(
220        &mut self,
221        _store: &NodeStore,
222        _bounds: &dyn ScrollBoundsLookup,
223        _scroll: &mut ScrollOffsets,
224        _dt_s: f32,
225        _out_visual: &mut Vec<NodeId>,
226        _out_clamped: &mut Vec<NodeId>,
227    ) -> bool {
228        false
229    }
230
231    /// Active visual overscroll `(ox, oy)` for `node` (`(0.0, 0.0)` when idle).
232    fn overscroll(&self, _node: NodeId) -> (f32, f32) {
233        (0.0, 0.0)
234    }
235
236    /// Whether any container currently has an active animation requiring vsync frames.
237    fn has_active(&self) -> bool {
238        false
239    }
240
241    /// Logical pixels per discrete mouse-wheel line detent.
242    fn px_per_line(&self) -> f32 {
243        default_px_per_line()
244    }
245
246    /// Cancels any active animation, drag, or overscroll state for `node`.
247    fn cancel_node(&mut self, _node: NodeId) {}
248
249    /// Reconciles active physics bounds/offsets across layout commits without killing active
250    /// momentum unless `explicit_seek` is `true`.
251    fn reconcile_node(
252        &mut self,
253        node: NodeId,
254        _new_pos: (f32, f32),
255        _max: (f32, f32),
256        _anchor_delta: (f32, f32),
257        explicit_seek: bool,
258    ) {
259        if explicit_seek {
260            self.cancel_node(node);
261        }
262    }
263
264    /// Prunes state for nodes that are no longer live `Scroll` containers in `store`.
265    fn prune_missing(&mut self, _store: &NodeStore) {}
266
267    /// Clears all internal physics and gesture state (called on [`crate::LaidOutScene::reset`]).
268    fn clear(&mut self) {}
269
270    /// Updates reduced-motion mode. When `reduced` is `true`, engines snap active smooth-wheel
271    /// animations to their targets, updating `scroll` and pushing snapped nodes into
272    /// `out_visual`/`out_clamped`. Returns `true` if any node snapped.
273    fn set_reduced_motion(
274        &mut self,
275        _reduced: bool,
276        _scroll: &mut ScrollOffsets,
277        _out_visual: &mut Vec<NodeId>,
278        _out_clamped: &mut Vec<NodeId>,
279    ) -> bool {
280        false
281    }
282
283    /// Controls whether phased trackpad/touch releases spawn synthetic momentum (`false` on macOS
284    /// by default because AppKit delivers native OS momentum via `PixelDelta`).
285    fn set_synthetic_momentum(&mut self, _enabled: bool) {}
286}
287
288/// Zero-size, zero-allocation default [`ScrollPhysicsEngine`]: immediate clamped scroll offsets
289/// honoring `Scroll::axes` and `OverscrollBehavior::{Auto, Contain, None}` with zero animations
290/// and zero memory overhead (`size_of::<InstantScrollPhysics>() == 0`).
291#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
292pub struct InstantScrollPhysics;
293
294const _: () = assert!(std::mem::size_of::<InstantScrollPhysics>() == 0);
295
296impl InstantScrollPhysics {
297    #[inline]
298    fn apply_axis(
299        allow: bool,
300        ob: OverscrollBehavior,
301        cur: f32,
302        max: f32,
303        mut rem: f32,
304    ) -> (f32, f32, bool) {
305        if !rem.is_finite() {
306            return (cur, 0.0, false);
307        }
308        if rem.abs() <= 1e-4 {
309            return (cur, rem, false);
310        }
311        let mut next = cur;
312        let mut consumed = false;
313        if allow && max > 0.0 {
314            let used = (cur + rem).clamp(0.0, max) - cur;
315            if used.abs() > 1e-4 {
316                next = cur + used;
317                rem -= used;
318                consumed = true;
319            }
320        }
321        if rem.abs() > 1e-4 && allow && ob != OverscrollBehavior::Auto {
322            rem = 0.0;
323        }
324        (next, rem, consumed)
325    }
326}
327
328impl ScrollPhysicsEngine for InstantScrollPhysics {
329    fn on_scroll_delta(
330        &mut self,
331        ctx: &ScrollContainerCtx<'_>,
332        dx: f32,
333        dy: f32,
334        _kind: ScrollInputKind,
335        out: &mut ScrollDeltaResult,
336    ) {
337        let (next_x, rem_x, consumed_x) = Self::apply_axis(
338            ctx.allow_axes.0,
339            ctx.overscroll_behavior.0,
340            ctx.offset.0,
341            ctx.max_offset.0,
342            dx,
343        );
344        let (next_y, rem_y, consumed_y) = Self::apply_axis(
345            ctx.allow_axes.1,
346            ctx.overscroll_behavior.1,
347            ctx.offset.1,
348            ctx.max_offset.1,
349            dy,
350        );
351        let changed = consumed_x || consumed_y;
352        out.next_offset = (next_x, next_y);
353        out.remaining = (rem_x, rem_y);
354        out.consumed_x = consumed_x;
355        out.consumed_y = consumed_y;
356        out.visual_changed = changed;
357        out.clamped_changed = changed;
358    }
359}