Skip to main content

nativeview_layout/taffy_store/
box_edges.rs

1//! Opt-in resolved box-edge capture (`ResolvedBoxEdges`) and [`StoreLayoutEngine`] trait impl
2//! for [`TaffyStoreLayout`].
3//!
4//! When disabled (`capture_box_edges == false`, the default), `box_edges` remains empty
5//! (`capacity() == 0`, 0 B allocated).
6
7use std::sync::Arc;
8
9use nativeview_engine::{InteractionTracker, LayoutRect, Viewport};
10use nativeview_store::{ChangeSet, NodeId, NodeStore, RowPatchView, TableSet, TableSlot};
11use nativeview_tables::media::{ConditionalTier, MediaEnv};
12
13use crate::{
14    LeafMeasureHook, ParagraphStore, ResolvedBoxEdges, ResolvedTextStyle, SizeConstraints,
15    StoreLayoutEngine, SurfaceMeasure, TextMeasurer, TopLayerIndex,
16};
17
18use super::container::scope::committed_container_env;
19use super::dry_run::InheritView;
20use super::{TaffyStoreLayout, gen_tag};
21use nativeview_tables::container::ContainerEnv;
22
23impl TaffyStoreLayout {
24    #[inline]
25    pub fn layout_generation(&self) -> u64 {
26        self.layout_gen
27    }
28
29    pub fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
30        self.measurer = measurer;
31        for c in &mut self.caches {
32            c.clear();
33        }
34        self.dry.invalidate();
35        self.layout_dirty = true;
36        self.full_layout_needed = true;
37    }
38
39    pub fn text_measurer(&self) -> &Arc<dyn TextMeasurer> {
40        &self.measurer
41    }
42
43    /// Registers an intrinsic [`LeafMeasureHook`] for nodes carrying `slot`, invalidating cached
44    /// layout entries so subsequent passes invoke it, and returns `true` if a prior hook at
45    /// `slot` was replaced.
46    pub fn register_measure_hook(&mut self, slot: TableSlot, hook: Arc<dyn LeafMeasureHook>) -> bool {
47        let replaced = self.measure_hooks.register(slot, hook, TableSet::EMPTY);
48        for c in &mut self.caches {
49            c.clear();
50        }
51        self.dry.invalidate();
52        self.layout_dirty = true;
53        self.full_layout_needed = true;
54        replaced
55    }
56
57    #[inline]
58    pub fn paragraphs(&self) -> &ParagraphStore {
59        &self.paragraphs
60    }
61
62    #[inline]
63    pub fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
64        let idx = id.index();
65        (idx < self.rect_gen.len()
66            && self.rect_valid_gen != 0
67            && self.rect_gen[idx] == self.rect_valid_gen
68            && self.node_gens[idx] == gen_tag(id))
69        .then(|| self.rects[idx])
70    }
71
72    #[inline]
73    pub fn resolved_rtl(&self, id: NodeId) -> bool {
74        let idx = id.index();
75        self.node_gens.get(idx).copied() == Some(gen_tag(id))
76            && self.resolved_rtl.get(idx).copied().unwrap_or(false)
77    }
78
79    #[inline]
80    pub fn resolved_text(&self, id: NodeId) -> ResolvedTextStyle {
81        let idx = id.index();
82        if self.node_gens.get(idx).copied() == Some(gen_tag(id)) {
83            self.resolved_text.get(idx).copied().unwrap_or_default()
84        } else {
85            ResolvedTextStyle::default()
86        }
87    }
88
89    #[inline]
90    pub fn resolved_container_env(&self, id: NodeId) -> ContainerEnv {
91        committed_container_env(&self.resolved_container_env, id)
92    }
93
94    /// Whether per-node container scope buffers are currently allocated.
95    #[inline]
96    pub fn has_container_scopes(&self) -> bool {
97        self.container_records.len() > 0
98    }
99
100    /// Whether per-node relayout-boundary buffers are currently allocated (0 B without
101    /// `ContainerType::Size` nodes).
102    #[inline]
103    pub fn has_boundary_records(&self) -> bool {
104        self.boundary_records.len() > 0
105    }
106
107    /// The top-layer index this engine hoists overlays from.
108    #[inline]
109    pub fn top_layer(&self) -> &TopLayerIndex {
110        &self.top_layer
111    }
112
113    /// Exact set of reachable live nodes whose committed `LayoutRect` changed or became newly
114    /// laid out in the latest layout pass (`Some(&[])` on a clean frame), or `None` when callers
115    /// must scan all live nodes (e.g. dead root or `top_layer_rerun` fallback).
116    #[inline]
117    pub fn changed_rects(&self) -> Option<&[NodeId]> {
118        (!self.all_rects_changed).then_some(self.changed_rects.as_slice())
119    }
120
121    /// Completed inheritance walks (both full-tree and subtree-scoped).
122    #[inline]
123    pub fn inherit_walk_count(&self) -> u64 {
124        self.inherit_walks
125    }
126
127    /// Completed full-tree inheritance walks from `root`.
128    #[inline]
129    pub fn full_inherit_walk_count(&self) -> u64 {
130        self.full_inherit_walks
131    }
132
133    /// Total box nodes processed across all inheritance walks.
134    #[inline]
135    pub fn inherit_nodes_visited(&self) -> u64 {
136        self.inherit_nodes_visited
137    }
138
139    /// Completed relayout-containment boundary fast-path passes.
140    #[inline]
141    pub fn boundary_pass_count(&self) -> u64 {
142        self.boundary_passes
143    }
144
145    /// Measures `root` under `constraints` (or unconstrained intrinsic sizing when `ideal` is
146    /// `true`) into isolated dry-run scratch without mutating committed caches, boxes, rects,
147    /// hoisted out-of-flow lists, resolved inheritance, `last_viewport`, or `layout_dirty`.
148    pub fn measure_root(
149        &mut self,
150        store: &NodeStore,
151        root: NodeId,
152        constraints: SizeConstraints,
153        ideal: bool,
154    ) -> SurfaceMeasure {
155        // Committed lists stay valid with hoisted overlays present: dry runs read the root's
156        // list without its appended top-layer roots (`BoxChildren::get_in_flow`).
157        let committed_inherit = (!self.inherit_dirty
158            && self.top_layer.root() == root
159            && !self.counts_dirty
160            && !self.responsive_tree_dirty
161            && !self.media_signature_dirty
162            && self.committed_store_rev == Some((store.instance_id(), store.frame()))
163            && self.resolved_rtl.len() >= store.capacity()
164            && self.last_viewport.is_some_and(|(r, _, _)| r == root))
165        .then_some(InheritView {
166            resolved_rtl: &self.resolved_rtl,
167            resolved_text: &self.resolved_text,
168            paragraphs: &self.paragraphs,
169            box_children: &self.box_children,
170            top_layer: &self.top_layer,
171            responsive_node_count: self.responsive_node_count,
172            container_node_count: self.container_node_count,
173            media_signature: self.media_signature,
174            subtree_has_responsive: &self.subtree_has_responsive,
175            has_responsive_typo: &self.has_responsive_typo,
176            style_flags: &self.style_flags,
177            resp_memo_slot: &self.resp_memo_slot,
178            resp_memo_len: self.resp_memo_len.0,
179        });
180        self.dry.measure_root(
181            store,
182            root,
183            constraints,
184            ideal,
185            self.media_env,
186            committed_inherit,
187            &*self.measurer,
188            &self.measure_hooks,
189        )
190    }
191
192    /// Enables or disables opt-in capture of exact Taffy resolved `margin`/`border`/`padding`/
193    /// `content_size` into `self.box_edges`.
194    ///
195    /// Turning capture OFF clears and shrinks `box_edges` to `capacity() == 0` (0 B).
196    /// Turning capture ON invalidates Taffy caches and marks layout dirty so the next
197    /// `compute_layout` populates exact edges for every live node.
198    pub fn set_capture_box_edges(&mut self, enabled: bool) {
199        if self.capture_box_edges == enabled {
200            return;
201        }
202        self.capture_box_edges = enabled;
203        self.box_edges_valid_gen = 0;
204        if !enabled {
205            self.box_edges.clear();
206            self.box_edges.shrink_to_fit();
207            return;
208        }
209        self.box_edges
210            .resize(self.boxes.len(), ResolvedBoxEdges::default());
211        for c in &mut self.caches {
212            c.clear();
213        }
214        self.layout_dirty = true;
215        self.full_layout_needed = true;
216    }
217
218    #[inline]
219    pub fn capture_box_edges(&self) -> bool {
220        self.capture_box_edges
221    }
222
223    /// Returns the allocated slot capacity of the opt-in `box_edges` buffer (guaranteed `0` when
224    /// capture is disabled).
225    #[inline]
226    pub fn box_edges_capacity(&self) -> usize {
227        self.box_edges.capacity()
228    }
229
230    #[inline]
231    pub fn box_edges_of(&self, id: NodeId) -> Option<ResolvedBoxEdges> {
232        if !self.capture_box_edges
233            || self.rect_valid_gen == 0
234            || self.box_edges_valid_gen != self.rect_valid_gen
235        {
236            return None;
237        }
238        let idx = id.index();
239        (idx < self.box_edges.len()
240            && idx < self.rect_gen.len()
241            && self.rect_gen[idx] == self.rect_valid_gen
242            && self.node_gens[idx] == gen_tag(id))
243        .then(|| self.box_edges[idx])
244    }
245}
246
247impl StoreLayoutEngine for TaffyStoreLayout {
248    fn name(&self) -> &'static str {
249        "taffy"
250    }
251
252    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet) {
253        TaffyStoreLayout::sync_changes(self, store, changes);
254    }
255
256    fn top_layer(&self) -> &TopLayerIndex {
257        TaffyStoreLayout::top_layer(self)
258    }
259
260    fn sync_changes_with_interaction(
261        &mut self,
262        store: &NodeStore,
263        changes: &ChangeSet,
264        interaction: Option<&InteractionTracker>,
265    ) {
266        TaffyStoreLayout::sync_changes_with_interaction(self, store, changes, interaction);
267    }
268
269    fn compute_layout(&mut self, store: &NodeStore, root: NodeId, viewport: Viewport) -> bool {
270        TaffyStoreLayout::compute_layout(self, store, root, viewport)
271    }
272
273    fn compute_layout_with_interaction(
274        &mut self,
275        store: &NodeStore,
276        root: NodeId,
277        viewport: Viewport,
278        interaction: Option<&InteractionTracker>,
279    ) -> bool {
280        TaffyStoreLayout::compute_layout_with_interaction(self, store, root, viewport, interaction)
281    }
282
283    fn sync_interaction_paragraphs(
284        &mut self,
285        store: &NodeStore,
286        interaction: &InteractionTracker,
287        dirty_nodes: &[NodeId],
288    ) -> (&[NodeId], &[NodeId]) {
289        TaffyStoreLayout::sync_interaction_paragraphs(self, store, interaction, dirty_nodes)
290    }
291
292    fn paragraphs(&self) -> Option<&ParagraphStore> {
293        Some(TaffyStoreLayout::paragraphs(self))
294    }
295
296    fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
297        Some(&mut self.paragraphs)
298    }
299
300    fn measure_root(
301        &mut self,
302        store: &NodeStore,
303        root: NodeId,
304        constraints: SizeConstraints,
305        ideal: bool,
306    ) -> SurfaceMeasure {
307        TaffyStoreLayout::measure_root(self, store, root, constraints, ideal)
308    }
309
310    fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
311        TaffyStoreLayout::layout_of(self, id)
312    }
313
314    fn changed_rects(&self) -> Option<&[NodeId]> {
315        TaffyStoreLayout::changed_rects(self)
316    }
317
318    fn set_capture_box_edges(&mut self, enabled: bool) {
319        TaffyStoreLayout::set_capture_box_edges(self, enabled);
320    }
321
322    fn capture_box_edges(&self) -> bool {
323        TaffyStoreLayout::capture_box_edges(self)
324    }
325
326    fn box_edges_of(&self, id: NodeId) -> Option<ResolvedBoxEdges> {
327        TaffyStoreLayout::box_edges_of(self, id)
328    }
329
330    fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
331        TaffyStoreLayout::set_text_measurer(self, measurer);
332    }
333
334    fn register_measure_hook(&mut self, slot: TableSlot, hook: Arc<dyn LeafMeasureHook>) -> bool {
335        TaffyStoreLayout::register_measure_hook(self, slot, hook)
336    }
337
338    fn reset(&mut self) {
339        TaffyStoreLayout::reset(self);
340    }
341
342    fn set_media_env(&mut self, env: MediaEnv) -> bool {
343        TaffyStoreLayout::set_media_env(self, env)
344    }
345
346    fn visit_responsive_patches<'a>(
347        &self,
348        store: &'a NodeStore,
349        id: NodeId,
350        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
351    ) {
352        TaffyStoreLayout::visit_responsive_patches(self, store, id, f);
353    }
354
355    fn responsive_epoch(&self) -> u64 {
356        self.responsive_epoch
357    }
358
359    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
360        self.responsive_node_count() > 0
361            && super::responsive::is_node_show_on_hidden(store, id, &self.media_env())
362    }
363}