Skip to main content

nativeview_layout/scene/scroll/
mod.rs

1//! Per-surface scroll offsets, content bounds, per-axis `Scroll::axes` clamping, Layer-1 scroll
2//! anchoring integration, exact sequence-driven controlled scroll reconciliation, and the
3//! pluggable [`ScrollPhysicsEngine`] seam.
4
5use std::collections::HashMap;
6
7use nativeview_store::{ChangeSet, NodeId, NodeStore, NvTable};
8use nativeview_tables::tables::{Overflow, Scroll, ScrollAxes, Visual};
9
10use crate::StoreLayoutEngine;
11
12mod anchor;
13mod chain;
14pub use chain::push_unique_node;
15pub(crate) mod engine;
16pub(crate) mod extent;
17mod into_view;
18
19use extent::compute_scroll_content_size;
20
21use super::LaidOutScene;
22use anchor::CapturedScrollAnchor;
23use engine::ScrollPhysicsEngine;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26struct SeqSlot {
27    node: NodeId,
28    seq: u32,
29}
30
31const EMPTY_SEQ_SLOT: SeqSlot = SeqSlot {
32    node: NodeId::NULL,
33    seq: 0,
34};
35
36/// Returns `(allow_x, allow_y)` permitted scroll axes for `id`.
37#[inline]
38pub fn scroll_axes_allow(store: &NodeStore, id: NodeId) -> (bool, bool) {
39    match store.try_row::<Scroll>(id).map(|s| s.axes()) {
40        Some(ScrollAxes::Vertical) => (false, true),
41        Some(ScrollAxes::Horizontal) => (true, false),
42        Some(ScrollAxes::Both) => (true, true),
43        Some(ScrollAxes::None) => (false, false),
44        None => store.try_row::<Visual>(id).map_or((false, false), |v| {
45            (
46                matches!(v.overflow_x(), Overflow::Scroll | Overflow::Auto),
47                matches!(v.overflow_y(), Overflow::Scroll | Overflow::Auto),
48            )
49        }),
50    }
51}
52
53/// Summary outcome of [`LaidOutScene::apply_scroll_chain`].
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
55pub struct ScrollChainOutcome {
56    pub consumed_x: bool,
57    pub consumed_y: bool,
58    pub any_visual_changed: bool,
59    pub any_clamped_changed: bool,
60    pub active_physics: bool,
61}
62
63/// Per-surface scroll offset map plus generation-safe dense `requested_scroll_seq` deduplication
64/// and reusable Layer-1 scroll anchor / scratch buffers (0-alloc steady state).
65#[derive(Debug, Default, Clone)]
66pub struct ScrollOffsets {
67    offsets: HashMap<NodeId, (f32, f32)>,
68    last_requested_seq: Vec<SeqSlot>,
69    reconcile_scratch: Vec<ScrollReconcileEntry>,
70    pub(crate) changed_scratch: Vec<NodeId>,
71    /// `changed_scratch` of a commit's first scroll pass, unioned back after its second pass.
72    pub(crate) commit_changed: Vec<NodeId>,
73    pub(crate) captured_anchors: Vec<CapturedScrollAnchor>,
74    pub(crate) chain_changed_scratch: Vec<NodeId>,
75    pub(crate) chain_clamped_scratch: Vec<NodeId>,
76    pub(crate) step_visual_scratch: Vec<NodeId>,
77    pub(crate) step_clamped_scratch: Vec<NodeId>,
78    /// Set whenever an offset moves; consumed by the next overlay reconcile, so anchored
79    /// top-layer geometry follows scrolling exactly once per frame.
80    moved: bool,
81}
82
83impl ScrollOffsets {
84    /// Returns and clears whether any offset moved since the last call.
85    #[inline]
86    pub(crate) fn take_moved(&mut self) -> bool {
87        core::mem::take(&mut self.moved)
88    }
89
90    #[inline]
91    pub fn get(&self, id: NodeId) -> (f32, f32) {
92        self.offsets.get(&id).copied().unwrap_or((0.0, 0.0))
93    }
94
95    /// Every tracked `(node, (x, y))` offset, in unspecified order.
96    #[inline]
97    pub fn iter(&self) -> impl Iterator<Item = (NodeId, (f32, f32))> + '_ {
98        self.offsets.iter().map(|(&id, &xy)| (id, xy))
99    }
100
101    #[inline]
102    pub fn contains(&self, id: NodeId) -> bool {
103        self.offsets.contains_key(&id)
104    }
105
106    #[inline]
107    pub(crate) fn offsets_is_empty(&self) -> bool {
108        self.offsets.is_empty()
109    }
110
111    #[inline]
112    pub fn last_requested_seq(&self, id: NodeId) -> u32 {
113        self.last_requested_seq
114            .get(id.index())
115            .copied()
116            .filter(|slot| slot.node == id)
117            .map_or(0, |slot| slot.seq)
118    }
119
120    #[inline]
121    fn set_last_requested_seq(&mut self, id: NodeId, seq: u32) {
122        let idx = id.index();
123        if seq == 0 {
124            if let Some(slot) = self.last_requested_seq.get_mut(idx)
125                && slot.node == id
126            {
127                *slot = EMPTY_SEQ_SLOT;
128            }
129            return;
130        }
131        if idx >= self.last_requested_seq.len() {
132            self.last_requested_seq.resize(idx + 1, EMPTY_SEQ_SLOT);
133        }
134        self.last_requested_seq[idx] = SeqSlot { node: id, seq };
135    }
136
137    /// Nodes whose effective scroll offset changed during the most recent reconciliation pass.
138    #[inline]
139    pub fn last_changed(&self) -> &[NodeId] {
140        &self.changed_scratch
141    }
142
143    #[inline]
144    pub fn set_raw(&mut self, id: NodeId, x: f32, y: f32) {
145        if self.offsets.insert(id, (x, y)) != Some((x, y)) {
146            self.moved = true;
147        }
148    }
149
150    #[inline]
151    pub fn remove(&mut self, id: NodeId) {
152        self.offsets.remove(&id);
153        if let Some(slot) = self.last_requested_seq.get_mut(id.index())
154            && slot.node == id
155        {
156            *slot = EMPTY_SEQ_SLOT;
157        }
158    }
159
160    #[inline]
161    pub fn clear(&mut self) {
162        self.offsets.clear();
163        self.last_requested_seq.fill(EMPTY_SEQ_SLOT);
164        self.reconcile_scratch.clear();
165        self.changed_scratch.clear();
166        self.captured_anchors.clear();
167        self.chain_changed_scratch.clear();
168        self.chain_clamped_scratch.clear();
169        self.step_visual_scratch.clear();
170        self.step_clamped_scratch.clear();
171    }
172
173    /// Clamped visual child shift for `id`, subtracting any virtualized `Scroll::virtual_top_spacer`.
174    /// Pure clamped (zero synthetic overscroll) so OS-native scroll hosts never receive rubber-band
175    /// offsets through `NvScrollOffset`.
176    #[inline]
177    pub fn visual_shift(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
178        let (sx, sy) = self.get(id);
179        Self::visual_shift_with(store, id, sx, sy)
180    }
181
182    /// [`Self::visual_shift`] for an offset `(sx, sy)` already read (e.g. from [`Self::iter`]).
183    #[inline]
184    pub fn visual_shift_with(store: &NodeStore, id: NodeId, sx: f32, sy: f32) -> (f32, f32) {
185        match store
186            .try_row::<Scroll>(id)
187            .and_then(|scroll| scroll.virtual_top_spacer())
188            .filter(|&v| v.is_finite() && v > 0.0)
189        {
190            Some(top_spacer) => (sx, (sy - top_spacer).max(0.0)),
191            None => (sx, sy),
192        }
193    }
194}
195
196#[derive(Debug, Clone, Copy)]
197struct ScrollReconcileEntry {
198    id: NodeId,
199    x: f32,
200    y: f32,
201    max_x: f32,
202    max_y: f32,
203    anchor_dx: f32,
204    anchor_dy: f32,
205    seq: u32,
206    explicit_seek: bool,
207    changed: bool,
208}
209
210impl<L: StoreLayoutEngine> LaidOutScene<L> {
211    #[inline]
212    pub fn scroll_offsets(&self) -> &ScrollOffsets {
213        &self.scroll
214    }
215
216    #[inline]
217    pub fn last_reconciled_scroll_nodes(&self) -> &[NodeId] {
218        self.scroll.last_changed()
219    }
220
221    #[inline]
222    pub fn last_scroll_chain_changed(&self) -> &[NodeId] {
223        &self.scroll.chain_changed_scratch
224    }
225
226    #[inline]
227    pub fn last_scroll_chain_clamped_changed(&self) -> &[NodeId] {
228        &self.scroll.chain_clamped_scratch
229    }
230
231    #[inline]
232    pub fn last_physics_visual_changed(&self) -> &[NodeId] {
233        &self.scroll.step_visual_scratch
234    }
235
236    #[inline]
237    pub fn last_physics_clamped_changed(&self) -> &[NodeId] {
238        &self.scroll.step_clamped_scratch
239    }
240
241    #[inline]
242    pub fn set_scroll_offset_raw(&mut self, id: NodeId, dx: f32, dy: f32) {
243        self.scroll.set_raw(id, dx, dy);
244    }
245
246    #[inline]
247    pub fn scroll_offset(&self, id: NodeId) -> (f32, f32) {
248        self.scroll.get(id)
249    }
250
251    #[inline]
252    pub fn scroll_overscroll(&self, id: NodeId) -> (f32, f32) {
253        self.scroll_physics.overscroll(id)
254    }
255
256    /// Clamped visual scroll shift (without synthetic overscroll).
257    #[inline]
258    pub fn visual_scroll_shift(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
259        self.scroll.visual_shift(store, id)
260    }
261
262    /// Compositor scroll shift including active rubber-band `(overscroll_x, overscroll_y)` for
263    /// custom-drawn surfaces (`SkiaBackend`), hit-testing, and sticky header tracking.
264    #[inline]
265    pub fn compositor_scroll_shift(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
266        let (vx, vy) = self.scroll.visual_shift(store, id);
267        let (ox, oy) = self.scroll_physics.overscroll(id);
268        (vx + ox, vy + oy)
269    }
270
271    /// Raw scroll offset plus active rubber-band overscroll (used by sticky positioning).
272    #[inline]
273    pub(crate) fn compositor_scroll_offset(&self, id: NodeId) -> (f32, f32) {
274        let (sx, sy) = self.scroll.get(id);
275        let (ox, oy) = self.scroll_physics.overscroll(id);
276        (sx + ox, sy + oy)
277    }
278
279    /// Replaces this surface's active [`ScrollPhysicsEngine`].
280    #[inline]
281    pub fn set_scroll_physics(&mut self, engine: Box<dyn ScrollPhysicsEngine>) {
282        self.scroll_physics = engine;
283    }
284
285    #[inline]
286    pub fn scroll_physics(&self) -> &dyn ScrollPhysicsEngine {
287        self.scroll_physics.as_ref()
288    }
289
290    #[inline]
291    pub fn scroll_physics_mut(&mut self) -> &mut dyn ScrollPhysicsEngine {
292        self.scroll_physics.as_mut()
293    }
294
295    /// Logical pixels per discrete mouse-wheel line detent reported by the installed engine.
296    #[inline]
297    pub fn scroll_px_per_line(&self) -> f32 {
298        self.scroll_physics.px_per_line()
299    }
300
301    /// Updates the reduced-motion preference on the installed [`ScrollPhysicsEngine`].
302    /// Returns `true` if any active smooth-wheel animations snapped immediately to their target.
303    pub fn set_scroll_reduced_motion(&mut self, reduced: bool) -> bool {
304        self.scroll.step_visual_scratch.clear();
305        self.scroll.step_clamped_scratch.clear();
306        let mut out_visual = std::mem::take(&mut self.scroll.step_visual_scratch);
307        let mut out_clamped = std::mem::take(&mut self.scroll.step_clamped_scratch);
308        let snapped = self.scroll_physics.set_reduced_motion(
309            reduced,
310            &mut self.scroll,
311            &mut out_visual,
312            &mut out_clamped,
313        );
314        self.scroll.step_visual_scratch = out_visual;
315        self.scroll.step_clamped_scratch = out_clamped;
316        snapped
317    }
318
319    #[inline]
320    pub fn set_scroll_synthetic_momentum(&mut self, enabled: bool) {
321        self.scroll_physics.set_synthetic_momentum(enabled);
322    }
323
324    #[inline]
325    pub fn has_active_scroll_physics(&self) -> bool {
326        self.scroll_physics.has_active()
327    }
328
329    pub fn scroll_content_size(&self, store: &NodeStore, node_id: NodeId) -> Option<(f32, f32)> {
330        let cascade = self.style_cascade();
331        compute_scroll_content_size(
332            store,
333            |id| self.layout.layout_of(id),
334            |id| cascade.display(store, id),
335            node_id,
336        )
337    }
338
339    #[inline]
340    pub(crate) fn scroll_bounds(
341        &self,
342        store: &NodeStore,
343        id: NodeId,
344    ) -> Option<(f32, f32, f32, f32)> {
345        let rect = self.layout.layout_of(id)?;
346        let (cw, ch) = self
347            .scroll_content_size(store, id)
348            .unwrap_or((rect.width, rect.height));
349        let (allow_x, allow_y) = scroll_axes_allow(store, id);
350        let max_x = if allow_x {
351            (cw - rect.width).max(0.0)
352        } else {
353            0.0
354        };
355        let max_y = if allow_y {
356            (ch - rect.height).max(0.0)
357        } else {
358            0.0
359        };
360        Some((rect.width.max(1.0), rect.height.max(1.0), max_x, max_y))
361    }
362
363    /// Cancels any active scroll physics/overscroll on `node_id`. Returns `true` if the node had
364    /// non-zero rubber-band overscroll so callers can clear visual overscroll state immediately.
365    #[inline]
366    pub fn cancel_scroll_physics(&mut self, node_id: NodeId) -> bool {
367        let (ox, oy) = self.scroll_physics.overscroll(node_id);
368        self.scroll_physics.cancel_node(node_id);
369        ox.abs() > 1e-4 || oy.abs() > 1e-4
370    }
371
372    /// Sets `node_id`'s scroll offset clamped to `[0..=content - viewport]` per `Scroll::axes`,
373    /// cancelling any active scroll physics on `node_id`. Returns `(clamped_x, clamped_y, changed)`.
374    pub fn set_scroll_offset_clamped(
375        &mut self,
376        store: &NodeStore,
377        node_id: NodeId,
378        x: f32,
379        y: f32,
380    ) -> (f32, f32, bool) {
381        let Some((_, _, max_x, max_y)) = self.scroll_bounds(store, node_id) else {
382            return (0.0, 0.0, false);
383        };
384        self.set_scroll_offset_clamped_max(node_id, x, y, max_x, max_y)
385    }
386
387    /// [`Self::set_scroll_offset_clamped`] using pre-cached `(viewport_w, viewport_h, content_w,
388    /// content_h)` bounds so retained hosts avoid recomputing content extents on 120 Hz scrolls.
389    #[allow(clippy::too_many_arguments)]
390    pub fn set_scroll_offset_clamped_with_bounds(
391        &mut self,
392        store: &NodeStore,
393        node_id: NodeId,
394        x: f32,
395        y: f32,
396        vw: f32,
397        vh: f32,
398        cw: f32,
399        ch: f32,
400    ) -> (f32, f32, bool) {
401        let (allow_x, allow_y) = scroll_axes_allow(store, node_id);
402        let max_x = if allow_x { (cw - vw).max(0.0) } else { 0.0 };
403        let max_y = if allow_y { (ch - vh).max(0.0) } else { 0.0 };
404        self.set_scroll_offset_clamped_max(node_id, x, y, max_x, max_y)
405    }
406
407    #[inline]
408    fn set_scroll_offset_clamped_max(
409        &mut self,
410        node_id: NodeId,
411        x: f32,
412        y: f32,
413        max_x: f32,
414        max_y: f32,
415    ) -> (f32, f32, bool) {
416        let clamped_x = if x.is_finite() { x.clamp(0.0, max_x) } else { 0.0 };
417        let clamped_y = if y.is_finite() { y.clamp(0.0, max_y) } else { 0.0 };
418        let had_overscroll = self.cancel_scroll_physics(node_id);
419        let prev = self.scroll.get(node_id);
420        self.scroll.set_raw(node_id, clamped_x, clamped_y);
421        let changed = had_overscroll
422            || (prev.0 - clamped_x).abs() > 1e-4
423            || (prev.1 - clamped_y).abs() > 1e-4;
424        (clamped_x, clamped_y, changed)
425    }
426
427    /// Applies an incremental scroll delta `(dx, dy)` clamped against content bounds & `Scroll::axes`.
428    /// Returns `(clamped_x, clamped_y, changed)`.
429    pub fn apply_scroll_delta(
430        &mut self,
431        store: &NodeStore,
432        node_id: NodeId,
433        dx: f32,
434        dy: f32,
435    ) -> (f32, f32, bool) {
436        let (cur_x, cur_y) = self.scroll.get(node_id);
437        let nx = cur_x + if dx.is_finite() { dx } else { 0.0 };
438        let ny = cur_y + if dy.is_finite() { dy } else { 0.0 };
439        self.set_scroll_offset_clamped(store, node_id, nx, ny)
440    }
441
442    /// Fast-path guard around [`Self::reconcile_scroll_offsets`]: skips all work in `O(1)` when
443    /// layout did not run, no `Scroll` table row changed, and no nodes were removed.
444    #[inline]
445    pub(crate) fn reconcile_scroll_offsets_if_needed(
446        &mut self,
447        store: &NodeStore,
448        changes: &ChangeSet,
449        laid_out: bool,
450    ) -> &[NodeId] {
451        self.scroll.changed_scratch.clear();
452        if let Some(tc) = changes.table(Scroll::slot()) {
453            for &id in &tc.detached {
454                self.scroll.remove(id);
455                self.scroll_physics.cancel_node(id);
456            }
457        }
458        if !laid_out && changes.removed.is_empty() && changes.table(Scroll::slot()).is_none() {
459            self.scroll.captured_anchors.clear();
460            return &self.scroll.changed_scratch;
461        }
462        self.reconcile_scroll_offsets(store)
463    }
464
465    /// Prunes removed/detached scroll nodes, honors exact `Scroll::requested_scroll_seq`
466    /// transitions (`seq != 0 && seq != prev_seq`), applies Layer-1 scroll anchor compensation,
467    /// reconciles active physics entries across mid-fling commits, and re-clamps offsets per
468    /// `Scroll::axes` in `O(scroll_containers)` time with zero steady-state allocations.
469    pub fn reconcile_scroll_offsets(&mut self, store: &NodeStore) -> &[NodeId] {
470        self.scroll.changed_scratch.clear();
471        if !self.scroll.offsets.is_empty() {
472            let last_seq = &mut self.scroll.last_requested_seq;
473            let physics = self.scroll_physics.as_mut();
474            self.scroll.offsets.retain(|&id, _| {
475                let keep = store.is_live(id) && store.has::<Scroll>(id);
476                if !keep {
477                    physics.cancel_node(id);
478                    if let Some(slot) = last_seq.get_mut(id.index())
479                        && slot.node == id
480                    {
481                        *slot = EMPTY_SEQ_SLOT;
482                    }
483                }
484                keep
485            });
486        }
487        self.scroll_physics.prune_missing(store);
488
489        let Some(nativeview_store::TableStorage {
490            owners, row_count, ..
491        }) = store.table_storage(Scroll::slot())
492        else {
493            self.scroll.captured_anchors.clear();
494            return &self.scroll.changed_scratch;
495        };
496        if row_count == 0 {
497            self.scroll.captured_anchors.clear();
498            return &self.scroll.changed_scratch;
499        }
500
501        let mut updates = std::mem::take(&mut self.scroll.reconcile_scratch);
502        updates.clear();
503        if !owners.is_empty() {
504            for &id in &owners[..row_count.min(owners.len())] {
505                self.collect_scroll_node(store, id, &mut updates);
506            }
507        } else {
508            for idx in 1..store.capacity() {
509                if let Some(id) = store.id_at(idx) {
510                    self.collect_scroll_node(store, id, &mut updates);
511                }
512            }
513        }
514        for entry in updates.drain(..) {
515            self.scroll.set_last_requested_seq(entry.id, entry.seq);
516            if entry.x != 0.0 || entry.y != 0.0 || self.scroll.contains(entry.id) {
517                self.scroll.set_raw(entry.id, entry.x, entry.y);
518            }
519            self.scroll_physics.reconcile_node(
520                entry.id,
521                (entry.x, entry.y),
522                (entry.max_x, entry.max_y),
523                (entry.anchor_dx, entry.anchor_dy),
524                entry.explicit_seek,
525            );
526            if entry.changed {
527                self.scroll.changed_scratch.push(entry.id);
528            }
529        }
530        self.scroll.reconcile_scratch = updates;
531        self.scroll.captured_anchors.clear();
532        &self.scroll.changed_scratch
533    }
534
535    fn collect_scroll_node(
536        &self,
537        store: &NodeStore,
538        id: NodeId,
539        out: &mut Vec<ScrollReconcileEntry>,
540    ) {
541        if !store.is_live(id) {
542            return;
543        }
544        let Some(scroll) = store.try_row::<Scroll>(id) else {
545            return;
546        };
547        let Some(rect) = self.layout.layout_of(id) else {
548            return;
549        };
550        let (cw, ch) = self
551            .scroll_content_size(store, id)
552            .unwrap_or((rect.width, rect.height));
553        let (allow_x, allow_y) = scroll_axes_allow(store, id);
554        let max_x = if allow_x {
555            (cw - rect.width).max(0.0)
556        } else {
557            0.0
558        };
559        let max_y = if allow_y {
560            (ch - rect.height).max(0.0)
561        } else {
562            0.0
563        };
564
565        let (prev_x, prev_y) = self.scroll.get(id);
566        let (mut sx, mut sy) = (prev_x, prev_y);
567        let seq = scroll.requested_scroll_seq();
568        let prev_seq = self.scroll.last_requested_seq(id);
569        let explicit_seek = seq != 0 && seq != prev_seq;
570        let mut anchor_dx = 0.0f32;
571        let mut anchor_dy = 0.0f32;
572
573        if explicit_seek {
574            if let Some(req_x) = scroll.requested_scroll_x().filter(|v| v.is_finite()) {
575                sx = req_x;
576            }
577            if let Some(req_y) = scroll.requested_scroll_y().filter(|v| v.is_finite()) {
578                sy = req_y;
579            }
580        } else if !self.scroll.captured_anchors.is_empty() {
581            let (dx, dy) = self.scroll_anchor_delta(store, id, rect, allow_x, allow_y);
582            if dx != 0.0 || dy != 0.0 {
583                sx += dx;
584                sy += dy;
585                anchor_dx = dx;
586                anchor_dy = dy;
587            }
588        }
589
590        let nx = sx.clamp(0.0, max_x);
591        let ny = sy.clamp(0.0, max_y);
592        let (ox, oy) = self.scroll_physics.overscroll(id);
593        let had_overscroll = ox.abs() > 1e-4 || oy.abs() > 1e-4;
594        let changed = (nx - prev_x).abs() > 1e-4
595            || (ny - prev_y).abs() > 1e-4
596            || (explicit_seek && had_overscroll);
597        out.push(ScrollReconcileEntry {
598            id,
599            x: nx,
600            y: ny,
601            max_x,
602            max_y,
603            anchor_dx,
604            anchor_dy,
605            seq,
606            explicit_seek,
607            changed,
608        });
609    }
610}