nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! [`LaidOutScene`]: one surface's laid-out view of a `NodeStore` shared by every native backend
//! and `nativeview-runtime` — the layout engine, viewport, text measurer, interaction pseudo-state
//! ([`InteractionTracker`]), scroll offsets, and reusable zero-alloc hit-walk scratch.
//!
//! Backends keep only what is theirs: `HeadlessBackend` adds mutation tracking and Frame-0
//! export, `SkiaBackend` adds painting, text focus, and motion, and `nativeview-runtime` adds the
//! zero-copy `NvSceneView` publisher (the only one) and C ABI.

mod close_request;
mod commit;
mod focus_recovery;
mod focus_traversal;
mod hit;
mod interaction;
mod light;
mod overlay;
pub mod pointer;
pub mod top_layer_conformance;
mod scroll;
mod snapshot;
pub mod stacking;
mod style_cascade;
#[cfg(test)]
mod style_cascade_tests;
pub(crate) use style_cascade::state_rules_of;
pub use style_cascade::{
    EffectiveBox, NoResponsivePatches, ResponsivePatches, StyleCascade, state_rules_patch_box,
};

use std::cell::Cell;
use std::sync::Arc;

use nativeview_engine::InteractionTracker;
use nativeview_engine::{LayoutRect, Viewport};
use nativeview_store::{ChangeSet, NodeId, NodeStore, NvTable};
use nativeview_tables::tables::{Interaction, Scroll};

use crate::{
    HeuristicTextMeasurer, ParagraphStore, SizeConstraints, StoreLayoutEngine, SurfaceMeasure,
    TaffyStoreLayout, TextMeasurer, TopLayerIndex,
};

pub use close_request::CloseRequestAction;
pub use commit::{CommitHooks, CommitOutcome, NoCommitHooks};
pub use focus_traversal::{
    FocusTraversalCtx, FocusTraversalOutcome, FocusTraversalPolicy, FocusTraversalScratch,
    FocusTraverseFlags, FocusTraverseOutFlags, TabOrderPolicy,
};
pub use pointer::SceneGeometry;
pub use interaction::InteractionChange;
pub use hit::helpers::paragraph_content_insets;
pub use light::{PressOutcome, PressedOverlay, TopLayerPress, hide_popovers_until, top_layer_press};
pub use overlay::scene::OverlayState;
pub use overlay::resolved::{ResolvedOverlay, close_request_owner, topmost_modal_index};
pub use scroll::{ScrollChainOutcome, ScrollOffsets, push_unique_node, scroll_axes_allow};
pub use scroll::engine::{
    InstantScrollPhysics, ScrollAxis, ScrollBoundsLookup, ScrollContainerCtx, ScrollDeltaResult,
    ScrollInputKind, ScrollPhysicsEngine, ScrollTimestampMs, ScrollTouchPhase,
    default_px_per_line, normalize_shift_wheel,
};
pub use scroll::extent::{
    compute_scroll_content_size, for_each_scrollbar_thumb_geom, intersect_rects, intersects_clip,
};
pub use snapshot::{layout_snapshot_of, visual_snapshot_of};
pub use stacking::{
    CS_CLIPS, CS_HAS_SCROLL, CS_IS_STICKY, CS_IS_TOP_LAYER, CS_IS_TRANSFORM, ClipScrollIdx,
    ClipScrollNode, ItemCount, ItemPaintPhase, SCOPE_HAS_SCROLL,
    SCOPE_IS_MODAL, SCOPE_IS_STICKY, SCOPE_IS_TOP_LAYER, SceneStackingStyleSource, ScopeIdx,
    ScopeKind, StackingBucket, StackingItem, StackingNodeRole, StackingOverrides, StackingPlan,
    StackingScope, StackingStyleSource, TopLayerScope, ZOrder, bucket_for_sc_z,
    classify_node_sc_with_parent_display, resolve_node_sc_state,
};

/// One surface's laid-out view of a `NodeStore`.
///
/// Holds zero copies of the tree: every query reads `&NodeStore` plus the engine's rects.
pub struct LaidOutScene<L: StoreLayoutEngine = TaffyStoreLayout> {
    pub(crate) layout: L,
    pub(crate) viewport: Viewport,
    pub(crate) text_measurer: Arc<dyn TextMeasurer>,
    pub(crate) interaction: InteractionTracker,
    pub(crate) interaction_epoch: u64,
    pub(crate) scroll: ScrollOffsets,
    pub(crate) scroll_physics: Box<dyn ScrollPhysicsEngine>,
    pub(crate) overlays: OverlayState,
    /// Cached reusable CSS 2.1 Appendix E stacking plan for hit-testing (retains capacity across
    /// rebuilds for 0 steady-state heap allocations). Keyed by [`StackingCacheKey`].
    pub(crate) stacking_cache: Cell<StackingPlan>,
    pub(crate) stacking_cache_key: Cell<StackingCacheKey>,
    pub(crate) stacking_cache_has_tf_override: Cell<bool>,
    pub(crate) last_layout_ran: bool,
    pub(crate) commit_changed_rects: Vec<NodeId>,
    pub(crate) commit_changed_marks: Vec<u32>,
    pub(crate) commit_changed_epoch: u32,
    pub(crate) commit_changed_override: Option<bool>,
    pub(crate) focus_dfs_scratch: Vec<NodeId>,
    pub(crate) focus_policy: Box<dyn FocusTraversalPolicy>,
    pub(crate) focus_scratch: FocusTraversalScratch,
    pub(crate) last_focus_transition: Option<(Option<NodeId>, Option<NodeId>, bool)>,
}

/// [`LaidOutScene::style_cascade`] from disjoint field borrows (callers also hold `&mut`
/// scratch or the focus anchor).
#[inline]
pub(crate) fn cascade_of<'a, L: StoreLayoutEngine>(
    layout: &'a L,
    interaction: &'a InteractionTracker,
) -> StyleCascade<'a, L> {
    StyleCascade {
        responsive: layout,
        interaction: Some(interaction),
        inert: None,
    }
}

/// Everything a cached [`StackingPlan`] depends on.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct StackingCacheKey {
    store: u64,
    commit_epoch: u64,
    interaction_epoch: u64,
    overlay_gen: u64,
    responsive_epoch: u64,
}

impl Default for LaidOutScene<TaffyStoreLayout> {
    fn default() -> Self {
        Self::new(TaffyStoreLayout::new())
    }
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Wraps `layout`, installing the deterministic [`HeuristicTextMeasurer`].
    pub fn new(layout: L) -> Self {
        Self::with_text_measurer(layout, Arc::new(HeuristicTextMeasurer))
    }

    /// Wraps `layout` and installs `text_measurer` into it.
    pub fn with_text_measurer(mut layout: L, text_measurer: Arc<dyn TextMeasurer>) -> Self {
        layout.set_text_measurer(Arc::clone(&text_measurer));
        Self {
            layout,
            viewport: Viewport::default(),
            text_measurer,
            interaction: InteractionTracker::new(),
            interaction_epoch: 1,
            scroll: ScrollOffsets::default(),
            scroll_physics: Box::new(InstantScrollPhysics),
            overlays: OverlayState::default(),
            stacking_cache: Cell::new(StackingPlan::default()),
            stacking_cache_key: Cell::new(StackingCacheKey::default()),
            stacking_cache_has_tf_override: Cell::new(false),
            last_layout_ran: false,
            commit_changed_rects: Vec::new(),
            commit_changed_marks: Vec::new(),
            commit_changed_epoch: 0,
            commit_changed_override: None,
            focus_dfs_scratch: Vec::new(),
            focus_policy: Box::new(TabOrderPolicy),
            focus_scratch: FocusTraversalScratch::default(),
            last_focus_transition: None,
        }
    }

    #[inline]
    pub fn layout_engine_name(&self) -> &'static str {
        self.layout.name()
    }

    #[inline]
    pub fn layout_engine(&self) -> &L {
        &self.layout
    }

    #[inline]
    pub fn layout_engine_mut(&mut self) -> &mut L {
        &mut self.layout
    }

    #[inline]
    pub fn viewport(&self) -> Viewport {
        self.viewport
    }

    /// Sets the viewport; returns `true` when it changed (the next pass re-runs layout).
    pub fn set_viewport(&mut self, viewport: Viewport) -> bool {
        let changed = self.viewport != viewport;
        self.viewport = viewport;
        changed
    }

    /// Sets the `@media` environment (color scheme, reduced motion, pointer; the viewport size
    /// comes from [`Self::set_viewport`]). Returns `true` when it changed (the next pass
    /// re-resolves `@media` / `@container` rules).
    pub fn set_media_env(&mut self, env: nativeview_tables::media::MediaEnv) -> bool {
        self.layout.set_media_env(env)
    }

    #[inline]
    pub fn text_measurer(&self) -> &Arc<dyn TextMeasurer> {
        &self.text_measurer
    }

    pub fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
        self.text_measurer = Arc::clone(&measurer);
        self.layout.set_text_measurer(measurer);
    }

    /// Hot-swaps the layout engine, keeping viewport, text measurer, scroll, and interaction
    /// state. Resolved overlays belong to the old engine's top-layer index and are dropped; follow
    /// with [`Self::commit_frame`] (empty or full `ChangeSet`) to lay out and re-resolve them.
    pub fn swap_layout_engine<L2: StoreLayoutEngine>(mut self, mut next: L2) -> LaidOutScene<L2> {
        next.set_text_measurer(Arc::clone(&self.text_measurer));
        self.overlays.clear();
        LaidOutScene {
            layout: next,
            viewport: self.viewport,
            text_measurer: self.text_measurer,
            interaction: self.interaction,
            interaction_epoch: self.interaction_epoch,
            scroll: self.scroll,
            scroll_physics: self.scroll_physics,
            overlays: self.overlays,
            stacking_cache: self.stacking_cache,
            stacking_cache_key: self.stacking_cache_key,
            stacking_cache_has_tf_override: self.stacking_cache_has_tf_override,
            last_layout_ran: self.last_layout_ran,
            commit_changed_rects: Vec::new(),
            commit_changed_marks: Vec::new(),
            commit_changed_epoch: 0,
            commit_changed_override: None,
            focus_dfs_scratch: self.focus_dfs_scratch,
            focus_policy: self.focus_policy,
            focus_scratch: self.focus_scratch,
            last_focus_transition: self.last_focus_transition,
        }
    }

    /// Whether the most recent [`Self::recompute_layout`] / commit actually ran a layout pass.
    #[inline]
    pub fn last_layout_ran(&self) -> bool {
        self.last_layout_ran
    }

    /// Replaces the layout engine in-place when keeping the same engine type `L` (e.g.,
    /// `DynLayoutEngine`), avoiding any intermediate allocation.
    pub fn replace_layout_engine(&mut self, mut next: L) {
        next.set_text_measurer(Arc::clone(&self.text_measurer));
        self.layout = next;
        self.overlays.clear();
        self.commit_changed_override = None;
    }

    /// Absolute (surface-space) rect of `id` from the latest layout pass.
    #[inline]
    pub fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
        self.layout.layout_of(id)
    }

    /// Exact nodes whose committed absolute layout rect changed during the latest layout pass (or
    /// the union across both layout passes of a focus-recovery commit), or `None` when callers
    /// must fall back to scanning all live nodes (e.g. dead root or an engine without incremental
    /// rect tracking).
    #[inline]
    pub fn changed_rects(&self) -> Option<&[NodeId]> {
        match self.commit_changed_override {
            None => self.layout.changed_rects(),
            Some(true) => Some(&self.commit_changed_rects),
            Some(false) => None,
        }
    }

    /// Borrowed compiled [`ParagraphStore`] from the active layout engine.
    #[inline]
    pub fn paragraphs(&self) -> Option<&ParagraphStore> {
        self.layout.paragraphs()
    }

    /// Mutable borrow of the compiled [`ParagraphStore`] from the active layout engine.
    #[inline]
    pub fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
        self.layout.paragraphs_mut()
    }

    /// The layout engine's [`TopLayerIndex`]: which overlay roots are hoisted, in paint order.
    #[inline]
    pub fn top_layer(&self) -> &TopLayerIndex {
        self.layout.top_layer()
    }

    /// The topmost (last painted) resolved modal overlay: what hit-testing blocks below and what
    /// accessibility (`A11yGeometryProvider::topmost_modal`) emits from.
    #[inline]
    pub fn topmost_modal(&self) -> Option<NodeId> {
        self.overlays.topmost_modal()
    }

    /// `true` when a modal is open and `id` is neither inside the topmost modal's subtree nor
    /// inside a top-layer overlay painted above it. The one modal-inertness rule shared by
    /// scroll chaining, hit-testing, focus, and accessibility (all read resolved overlays).
    #[inline]
    pub fn is_inert_under_modal(&self, store: &NodeStore, id: NodeId) -> bool {
        self.overlays.is_inert_under_modal(store, id)
    }

    /// Syncs interaction removals/disabled state, scroll removals, and layout changes without
    /// running the layout pass yet.
    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet) {
        for &id in &changes.removed {
            let _ = self.interaction.remove_node_slice(id);
            self.scroll.remove(id);
            self.scroll_physics.cancel_node(id);
            self.bump_interaction_epoch();
        }
        if let Some(tc) = changes.table(Scroll::slot()) {
            for &id in &tc.detached {
                self.scroll.remove(id);
                self.scroll_physics.cancel_node(id);
            }
        }
        for &id in changes.created.iter().chain(&changes.touched) {
            if !store.is_live(id) {
                continue;
            }
            let disabled = store
                .try_row::<Interaction>(id)
                .is_some_and(|i| i.disabled());
            if self.interaction.is_disabled(id) != disabled {
                let _ = self.interaction.set_disabled_slice(id, disabled);
                self.bump_interaction_epoch();
            }
        }
        if self.interaction.prune_disconnected(|id| store.is_connected(id)) {
            self.bump_interaction_epoch();
        }
        if self.prune_invalid_captures(store) {
            self.bump_interaction_epoch();
        }
        self.layout
            .sync_changes_with_interaction(store, changes, Some(&self.interaction));
    }

    /// Runs the engine's self-gated layout pass for the store root at the current viewport
    /// (state-rule re-layouts between commits; commits go through [`Self::commit_frame`]).
    pub fn recompute_layout(&mut self, store: &NodeStore) -> bool {
        self.commit_changed_override = None;
        self.capture_scroll_anchors(store);
        let ran = self.layout.compute_layout_with_interaction(
            store,
            NodeId::ROOT,
            self.viewport,
            Some(&self.interaction),
        );
        if !ran {
            self.scroll.captured_anchors.clear();
        }
        self.last_layout_ran = ran;
        ran
    }

    /// Pure sizing pass over the store root without mutating committed layout boxes or rects.
    pub fn measure_root(
        &mut self,
        store: &NodeStore,
        constraints: SizeConstraints,
        ideal: bool,
    ) -> SurfaceMeasure {
        self.layout
            .measure_root(store, NodeId::ROOT, constraints, ideal)
    }

    /// Clears layout, interaction, scroll, and overlay state (keeps viewport and text measurer).
    pub fn reset(&mut self) {
        self.layout.reset();
        self.interaction.clear();
        self.bump_interaction_epoch();
        self.scroll.clear();
        self.scroll_physics.clear();
        self.overlays.clear();
        let mut plan = self.stacking_cache.take();
        plan.clear();
        self.stacking_cache.set(plan);
        self.stacking_cache_key.set(StackingCacheKey::default());
        self.stacking_cache_has_tf_override.set(false);
        self.last_layout_ran = false;
        self.commit_changed_rects.clear();
        self.commit_changed_marks.clear();
        self.commit_changed_epoch = 0;
        self.commit_changed_override = None;
        self.focus_dfs_scratch.clear();
        self.focus_scratch.clear();
        self.last_focus_transition = None;
    }

    /// Current length and high-water capacity of the reusable stacking-plan item buffer.
    #[inline]
    pub fn hit_scratch_stats(&self) -> (usize, usize) {
        let plan = self.stacking_cache.take();
        let stats = (plan.ordered_items.len(), plan.ordered_items.capacity());
        self.stacking_cache.set(plan);
        stats
    }
}