nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Opt-in resolved box-edge capture (`ResolvedBoxEdges`) and [`StoreLayoutEngine`] trait impl
//! for [`TaffyStoreLayout`].
//!
//! When disabled (`capture_box_edges == false`, the default), `box_edges` remains empty
//! (`capacity() == 0`, 0 B allocated).

use std::sync::Arc;

use nativeview_engine::{InteractionTracker, LayoutRect, Viewport};
use nativeview_store::{ChangeSet, NodeId, NodeStore, RowPatchView, TableSet, TableSlot};
use nativeview_tables::media::{ConditionalTier, MediaEnv};

use crate::{
    LeafMeasureHook, ParagraphStore, ResolvedBoxEdges, ResolvedTextStyle, SizeConstraints,
    StoreLayoutEngine, SurfaceMeasure, TextMeasurer, TopLayerIndex,
};

use super::container::scope::committed_container_env;
use super::dry_run::InheritView;
use super::{TaffyStoreLayout, gen_tag};
use nativeview_tables::container::ContainerEnv;

impl TaffyStoreLayout {
    #[inline]
    pub fn layout_generation(&self) -> u64 {
        self.layout_gen
    }

    pub fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
        self.measurer = measurer;
        for c in &mut self.caches {
            c.clear();
        }
        self.dry.invalidate();
        self.layout_dirty = true;
        self.full_layout_needed = true;
    }

    pub fn text_measurer(&self) -> &Arc<dyn TextMeasurer> {
        &self.measurer
    }

    /// Registers an intrinsic [`LeafMeasureHook`] for nodes carrying `slot`, invalidating cached
    /// layout entries so subsequent passes invoke it, and returns `true` if a prior hook at
    /// `slot` was replaced.
    pub fn register_measure_hook(&mut self, slot: TableSlot, hook: Arc<dyn LeafMeasureHook>) -> bool {
        let replaced = self.measure_hooks.register(slot, hook, TableSet::EMPTY);
        for c in &mut self.caches {
            c.clear();
        }
        self.dry.invalidate();
        self.layout_dirty = true;
        self.full_layout_needed = true;
        replaced
    }

    #[inline]
    pub fn paragraphs(&self) -> &ParagraphStore {
        &self.paragraphs
    }

    #[inline]
    pub fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
        let idx = id.index();
        (idx < self.rect_gen.len()
            && self.rect_valid_gen != 0
            && self.rect_gen[idx] == self.rect_valid_gen
            && self.node_gens[idx] == gen_tag(id))
        .then(|| self.rects[idx])
    }

    #[inline]
    pub fn resolved_rtl(&self, id: NodeId) -> bool {
        let idx = id.index();
        self.node_gens.get(idx).copied() == Some(gen_tag(id))
            && self.resolved_rtl.get(idx).copied().unwrap_or(false)
    }

    #[inline]
    pub fn resolved_text(&self, id: NodeId) -> ResolvedTextStyle {
        let idx = id.index();
        if self.node_gens.get(idx).copied() == Some(gen_tag(id)) {
            self.resolved_text.get(idx).copied().unwrap_or_default()
        } else {
            ResolvedTextStyle::default()
        }
    }

    #[inline]
    pub fn resolved_container_env(&self, id: NodeId) -> ContainerEnv {
        committed_container_env(&self.resolved_container_env, id)
    }

    /// Whether per-node container scope buffers are currently allocated.
    #[inline]
    pub fn has_container_scopes(&self) -> bool {
        self.container_records.len() > 0
    }

    /// Whether per-node relayout-boundary buffers are currently allocated (0 B without
    /// `ContainerType::Size` nodes).
    #[inline]
    pub fn has_boundary_records(&self) -> bool {
        self.boundary_records.len() > 0
    }

    /// The top-layer index this engine hoists overlays from.
    #[inline]
    pub fn top_layer(&self) -> &TopLayerIndex {
        &self.top_layer
    }

    /// Exact set of reachable live nodes whose committed `LayoutRect` changed or became newly
    /// laid out in the latest layout pass (`Some(&[])` on a clean frame), or `None` when callers
    /// must scan all live nodes (e.g. dead root or `top_layer_rerun` fallback).
    #[inline]
    pub fn changed_rects(&self) -> Option<&[NodeId]> {
        (!self.all_rects_changed).then_some(self.changed_rects.as_slice())
    }

    /// Completed inheritance walks (both full-tree and subtree-scoped).
    #[inline]
    pub fn inherit_walk_count(&self) -> u64 {
        self.inherit_walks
    }

    /// Completed full-tree inheritance walks from `root`.
    #[inline]
    pub fn full_inherit_walk_count(&self) -> u64 {
        self.full_inherit_walks
    }

    /// Total box nodes processed across all inheritance walks.
    #[inline]
    pub fn inherit_nodes_visited(&self) -> u64 {
        self.inherit_nodes_visited
    }

    /// Completed relayout-containment boundary fast-path passes.
    #[inline]
    pub fn boundary_pass_count(&self) -> u64 {
        self.boundary_passes
    }

    /// Measures `root` under `constraints` (or unconstrained intrinsic sizing when `ideal` is
    /// `true`) into isolated dry-run scratch without mutating committed caches, boxes, rects,
    /// hoisted out-of-flow lists, resolved inheritance, `last_viewport`, or `layout_dirty`.
    pub fn measure_root(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        constraints: SizeConstraints,
        ideal: bool,
    ) -> SurfaceMeasure {
        // Committed lists stay valid with hoisted overlays present: dry runs read the root's
        // list without its appended top-layer roots (`BoxChildren::get_in_flow`).
        let committed_inherit = (!self.inherit_dirty
            && self.top_layer.root() == root
            && !self.counts_dirty
            && !self.responsive_tree_dirty
            && !self.media_signature_dirty
            && self.committed_store_rev == Some((store.instance_id(), store.frame()))
            && self.resolved_rtl.len() >= store.capacity()
            && self.last_viewport.is_some_and(|(r, _, _)| r == root))
        .then_some(InheritView {
            resolved_rtl: &self.resolved_rtl,
            resolved_text: &self.resolved_text,
            paragraphs: &self.paragraphs,
            box_children: &self.box_children,
            top_layer: &self.top_layer,
            responsive_node_count: self.responsive_node_count,
            container_node_count: self.container_node_count,
            media_signature: self.media_signature,
            subtree_has_responsive: &self.subtree_has_responsive,
            has_responsive_typo: &self.has_responsive_typo,
            style_flags: &self.style_flags,
            resp_memo_slot: &self.resp_memo_slot,
            resp_memo_len: self.resp_memo_len.0,
        });
        self.dry.measure_root(
            store,
            root,
            constraints,
            ideal,
            self.media_env,
            committed_inherit,
            &*self.measurer,
            &self.measure_hooks,
        )
    }

    /// Enables or disables opt-in capture of exact Taffy resolved `margin`/`border`/`padding`/
    /// `content_size` into `self.box_edges`.
    ///
    /// Turning capture OFF clears and shrinks `box_edges` to `capacity() == 0` (0 B).
    /// Turning capture ON invalidates Taffy caches and marks layout dirty so the next
    /// `compute_layout` populates exact edges for every live node.
    pub fn set_capture_box_edges(&mut self, enabled: bool) {
        if self.capture_box_edges == enabled {
            return;
        }
        self.capture_box_edges = enabled;
        self.box_edges_valid_gen = 0;
        if !enabled {
            self.box_edges.clear();
            self.box_edges.shrink_to_fit();
            return;
        }
        self.box_edges
            .resize(self.boxes.len(), ResolvedBoxEdges::default());
        for c in &mut self.caches {
            c.clear();
        }
        self.layout_dirty = true;
        self.full_layout_needed = true;
    }

    #[inline]
    pub fn capture_box_edges(&self) -> bool {
        self.capture_box_edges
    }

    /// Returns the allocated slot capacity of the opt-in `box_edges` buffer (guaranteed `0` when
    /// capture is disabled).
    #[inline]
    pub fn box_edges_capacity(&self) -> usize {
        self.box_edges.capacity()
    }

    #[inline]
    pub fn box_edges_of(&self, id: NodeId) -> Option<ResolvedBoxEdges> {
        if !self.capture_box_edges
            || self.rect_valid_gen == 0
            || self.box_edges_valid_gen != self.rect_valid_gen
        {
            return None;
        }
        let idx = id.index();
        (idx < self.box_edges.len()
            && idx < self.rect_gen.len()
            && self.rect_gen[idx] == self.rect_valid_gen
            && self.node_gens[idx] == gen_tag(id))
        .then(|| self.box_edges[idx])
    }
}

impl StoreLayoutEngine for TaffyStoreLayout {
    fn name(&self) -> &'static str {
        "taffy"
    }

    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet) {
        TaffyStoreLayout::sync_changes(self, store, changes);
    }

    fn top_layer(&self) -> &TopLayerIndex {
        TaffyStoreLayout::top_layer(self)
    }

    fn sync_changes_with_interaction(
        &mut self,
        store: &NodeStore,
        changes: &ChangeSet,
        interaction: Option<&InteractionTracker>,
    ) {
        TaffyStoreLayout::sync_changes_with_interaction(self, store, changes, interaction);
    }

    fn compute_layout(&mut self, store: &NodeStore, root: NodeId, viewport: Viewport) -> bool {
        TaffyStoreLayout::compute_layout(self, store, root, viewport)
    }

    fn compute_layout_with_interaction(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        viewport: Viewport,
        interaction: Option<&InteractionTracker>,
    ) -> bool {
        TaffyStoreLayout::compute_layout_with_interaction(self, store, root, viewport, interaction)
    }

    fn sync_interaction_paragraphs(
        &mut self,
        store: &NodeStore,
        interaction: &InteractionTracker,
        dirty_nodes: &[NodeId],
    ) -> (&[NodeId], &[NodeId]) {
        TaffyStoreLayout::sync_interaction_paragraphs(self, store, interaction, dirty_nodes)
    }

    fn paragraphs(&self) -> Option<&ParagraphStore> {
        Some(TaffyStoreLayout::paragraphs(self))
    }

    fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
        Some(&mut self.paragraphs)
    }

    fn measure_root(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        constraints: SizeConstraints,
        ideal: bool,
    ) -> SurfaceMeasure {
        TaffyStoreLayout::measure_root(self, store, root, constraints, ideal)
    }

    fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
        TaffyStoreLayout::layout_of(self, id)
    }

    fn changed_rects(&self) -> Option<&[NodeId]> {
        TaffyStoreLayout::changed_rects(self)
    }

    fn set_capture_box_edges(&mut self, enabled: bool) {
        TaffyStoreLayout::set_capture_box_edges(self, enabled);
    }

    fn capture_box_edges(&self) -> bool {
        TaffyStoreLayout::capture_box_edges(self)
    }

    fn box_edges_of(&self, id: NodeId) -> Option<ResolvedBoxEdges> {
        TaffyStoreLayout::box_edges_of(self, id)
    }

    fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
        TaffyStoreLayout::set_text_measurer(self, measurer);
    }

    fn register_measure_hook(&mut self, slot: TableSlot, hook: Arc<dyn LeafMeasureHook>) -> bool {
        TaffyStoreLayout::register_measure_hook(self, slot, hook)
    }

    fn reset(&mut self) {
        TaffyStoreLayout::reset(self);
    }

    fn set_media_env(&mut self, env: MediaEnv) -> bool {
        TaffyStoreLayout::set_media_env(self, env)
    }

    fn visit_responsive_patches<'a>(
        &self,
        store: &'a NodeStore,
        id: NodeId,
        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    ) {
        TaffyStoreLayout::visit_responsive_patches(self, store, id, f);
    }

    fn responsive_epoch(&self) -> u64 {
        self.responsive_epoch
    }

    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
        self.responsive_node_count() > 0
            && super::responsive::is_node_show_on_hidden(store, id, &self.media_env())
    }
}