nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Pooled, zero-allocation steady-state [`ParagraphStore`] compiling every paragraph root
//! (`text {}` with 1 or N inline runs) into flat publishable `NvParagraphSpan` / `NvTextRun` /
//! UTF-8 text slabs with O(1) `owner_paragraph` lift and split `layout_hash` / `paint_hash`.

mod compile;
pub mod measure;
mod sync;

use nativeview_abi::{
    NodeId, NvParagraphSpan, NvStrSlice, NvTextParagraphView, NvTextRun,
    NV_PARAGRAPH_FLAG_STORE_TEXT_SLAB, NV_PARAGRAPH_NONE,
};
use nativeview_store::{NodeStore, Rgba, Span, SpanPool};

use crate::measure::ResolvedTextStyle;
use crate::taffy_store::responsive::text::ResponsiveTextEnv;

/// Resolved inheritance paragraphs compile against: every box's resolved text style and
/// direction (indexed by node slot; empty = defaults), plus the active responsive environment
/// (`None` when no `@media` / `@container` rule exists).
#[derive(Clone, Copy, Default)]
pub struct InheritedText<'a> {
    pub text: &'a [ResolvedTextStyle],
    pub rtl: &'a [bool],
    pub responsive: Option<ResponsiveTextEnv<'a>>,
}

#[derive(Debug, Clone, Copy)]
pub(super) struct InlineDfsFrame {
    pub(super) id: NodeId,
    pub(super) style: ResolvedTextStyle,
    pub(super) background: Rgba,
    pub(super) hidden: bool,
    pub(super) display_none: bool,
    pub(super) is_interactive: bool,
    pub(super) depth: u16,
}

/// Internal per-paragraph metadata kept in one contiguous array parallel to `spans`
/// (reduces heap allocations and cache misses vs. 5 separate parallel `Vec`s).
#[derive(Debug, Clone, Copy)]
pub(super) struct ParagraphMeta {
    pub(super) run_span: Span<NvTextRun>,
    pub(super) text_span: Span<u8>,
    pub(super) layout_hash: u64,
    pub(super) paint_hash: u64,
    pub(super) base_style: ResolvedTextStyle,
    pub(super) base_rtl: bool,
}

/// Compact flat store of all compiled paragraphs for a surface.
///
/// Shared by `TaffyStoreLayout`, `YogaLayoutEngine`, `SkiaBackend`, and `nativeview-runtime`.
#[derive(Debug, Clone, Default)]
pub struct ParagraphStore {
    /// Dense `NodeIndex -> paragraph slot` (`NV_PARAGRAPH_NONE` = not a paragraph root).
    pub(super) node_to_para: Vec<u32>,
    /// Dense `NodeIndex -> owning paragraph root NodeId` (`NodeId::NULL` for non-inline nodes).
    pub(super) owner_paragraph: Vec<NodeId>,
    /// Dense `NodeIndex -> was inline on previous sync` (detects `box <-> inline` transitions).
    pub(super) was_inline: Vec<bool>,
    /// Compact live paragraph spans published in `NvSceneView::paragraphs`.
    pub(super) spans: Vec<NvParagraphSpan>,
    /// Parallel internal metadata (`run_span`, `text_span`, hashes, cached inherited base style).
    pub(super) meta: Vec<ParagraphMeta>,
    /// Pooled flat `NvTextRun` slab (`NvSceneView::paragraph_runs`).
    pub(super) runs: SpanPool<NvTextRun>,
    /// Pooled flat UTF-8 text slab (`NvSceneView::paragraph_text`).
    pub(super) text: SpanPool<u8>,
    /// Per-sync delta outputs (cleared on next `sync_changes` / `sync_interaction_dirty`).
    pub(super) dirty_layout_paras: Vec<NodeId>,
    pub(super) dirty_paint_paras: Vec<NodeId>,
    pub(super) box_to_inline: Vec<NodeId>,
    pub(super) inline_to_box: Vec<NodeId>,
    /// Reusable scratch buffers (0 allocs per frame after warm-up).
    pub(super) dirty_paras: Vec<NodeId>,
    pub(super) dirty_stamp: Vec<u32>,
    pub(super) dirty_epoch: u32,
    pub(super) paint_dirty_stamp: Vec<u32>,
    pub(super) paint_dirty_epoch: u32,
    pub(super) layout_dirty_stamp: Vec<u32>,
    pub(super) layout_dirty_epoch: u32,
    pub(super) created_stamp: Vec<u32>,
    pub(super) created_epoch: u32,
    pub(super) scratch_text: Vec<u8>,
    pub(super) scratch_runs: Vec<NvTextRun>,
    pub(super) dfs_stack: Vec<InlineDfsFrame>,
    pub(super) subtree_stack: Vec<NodeId>,
}

impl ParagraphStore {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn reset(&mut self) {
        self.node_to_para.clear();
        self.owner_paragraph.clear();
        self.was_inline.clear();
        self.spans.clear();
        self.meta.clear();
        self.runs = SpanPool::default();
        self.text = SpanPool::default();
        self.dirty_layout_paras.clear();
        self.dirty_paint_paras.clear();
        self.box_to_inline.clear();
        self.inline_to_box.clear();
        self.dirty_paras.clear();
        self.dirty_stamp.clear();
        self.dirty_epoch = 0;
        self.paint_dirty_stamp.clear();
        self.paint_dirty_epoch = 0;
        self.layout_dirty_stamp.clear();
        self.layout_dirty_epoch = 0;
        self.created_stamp.clear();
        self.created_epoch = 0;
        self.scratch_text.clear();
        self.scratch_runs.clear();
        self.dfs_stack.clear();
        self.subtree_stack.clear();
    }

    pub fn ensure_capacity(&mut self, cap: usize) {
        if self.node_to_para.len() < cap {
            self.node_to_para.resize(cap, NV_PARAGRAPH_NONE);
            self.owner_paragraph.resize(cap, NodeId::NULL);
            self.was_inline.resize(cap, false);
            self.dirty_stamp.resize(cap, 0);
            self.paint_dirty_stamp.resize(cap, 0);
            self.layout_dirty_stamp.resize(cap, 0);
            self.created_stamp.resize(cap, 0);
        }
    }

    #[inline(always)]
    pub fn node_to_paragraph_slice(&self) -> &[u32] {
        &self.node_to_para
    }

    #[inline(always)]
    pub fn spans(&self) -> &[NvParagraphSpan] {
        &self.spans
    }

    #[inline(always)]
    pub fn runs_slab(&self) -> &[NvTextRun] {
        self.runs.data()
    }

    #[inline(always)]
    pub fn text_slab(&self) -> &[u8] {
        self.text.data()
    }

    /// O(1) indexed lookup returning the compact paragraph slot for paragraph root `id`.
    #[inline(always)]
    pub fn paragraph_slot(&self, id: NodeId) -> Option<u32> {
        let slot = *self.node_to_para.get(id.index())?;
        if slot == NV_PARAGRAPH_NONE {
            return None;
        }
        let span = self.spans.get(slot as usize)?;
        (span.owner_node_id == id).then_some(slot)
    }

    /// O(1) indexed lookup returning the compact [`NvParagraphSpan`] for paragraph root `id`.
    #[inline(always)]
    pub fn paragraph_of(&self, id: NodeId) -> Option<&NvParagraphSpan> {
        let slot = self.paragraph_slot(id)?;
        self.spans.get(slot as usize)
    }

    /// O(1) lift from any inline descendant `id` (at arbitrary nesting depth) to its owning
    /// paragraph root `NodeId` (`None` for box nodes).
    #[inline(always)]
    pub fn owner_paragraph(&self, id: NodeId) -> Option<NodeId> {
        let owner = *self.owner_paragraph.get(id.index())?;
        (!owner.is_null()).then_some(owner)
    }

    #[inline]
    pub fn layout_hash(&self, id: NodeId) -> Option<u64> {
        let slot = self.paragraph_slot(id)? as usize;
        self.meta.get(slot).map(|m| m.layout_hash)
    }

    #[inline]
    pub fn paint_hash(&self, id: NodeId) -> Option<u64> {
        let slot = self.paragraph_slot(id)? as usize;
        self.meta.get(slot).map(|m| m.paint_hash)
    }

    #[inline]
    pub fn paragraph_runs_slice(&self, id: NodeId) -> &[NvTextRun] {
        let Some(slot) = self.paragraph_slot(id) else {
            return &[];
        };
        self.runs.get(self.meta[slot as usize].run_span)
    }

    /// Resolves the contiguous UTF-8 text of paragraph root `id` (zero-copy from either
    /// `store.text_slab()` for 1-run paragraphs or `self.text` for multi-run paragraphs).
    #[inline]
    pub fn paragraph_text_str<'a>(&'a self, store: &'a NodeStore, id: NodeId) -> Option<&'a str> {
        let span = self.paragraph_of(id)?;
        let bytes = self.span_text_bytes(store, span);
        core::str::from_utf8(bytes).ok()
    }

    #[inline]
    fn span_text_bytes<'a>(&'a self, store: &'a NodeStore, span: &NvParagraphSpan) -> &'a [u8] {
        let len = span.text_len.as_usize();
        if len == 0 {
            return &[];
        }
        let off = span.text_off.as_usize();
        let Some(end) = off.checked_add(len) else {
            return &[];
        };
        let slab = if (span.flags & NV_PARAGRAPH_FLAG_STORE_TEXT_SLAB) != 0 {
            store.text_slab()
        } else {
            self.text.data()
        };
        slab.get(off..end).unwrap_or(&[])
    }

    /// Builds a zero-copy [`NvTextParagraphView`] for paragraph root `id`.
    #[inline]
    pub fn paragraph_view<'a>(
        &'a self,
        store: &'a NodeStore,
        id: NodeId,
    ) -> Option<NvTextParagraphView> {
        let slot = self.paragraph_slot(id)?;
        self.paragraph_view_by_slot(store, slot)
    }

    /// Builds a zero-copy [`NvTextParagraphView`] directly from compact `slot`.
    #[inline]
    pub fn paragraph_view_by_slot<'a>(
        &'a self,
        store: &'a NodeStore,
        slot: u32,
    ) -> Option<NvTextParagraphView> {
        let span = self.spans.get(slot as usize)?;
        let text_bytes = self.span_text_bytes(store, span);
        let families = store.text_slab();
        let runs = self.runs.get(self.meta[slot as usize].run_span);
        Some(NvTextParagraphView {
            max_lines: span.max_lines,
            run_count: runs.len() as u32,
            text_align: span.text_align,
            white_space: span.white_space,
            word_break: span.word_break,
            overflow_wrap: span.overflow_wrap,
            base_direction: span.base_direction,
            flags: span.flags,
            _reserved: 0,
            text: NvStrSlice {
                ptr: nativeview_abi::slab_ptr(text_bytes),
                len: text_bytes.len(),
            },
            font_families_slab: NvStrSlice {
                ptr: nativeview_abi::slab_ptr(families),
                len: families.len(),
            },
            runs: nativeview_abi::slab_ptr(runs),
        })
    }

    #[inline]
    pub fn dirty_layout_paragraphs(&self) -> &[NodeId] {
        &self.dirty_layout_paras
    }

    #[inline]
    pub fn dirty_paint_paragraphs(&self) -> &[NodeId] {
        &self.dirty_paint_paras
    }

    #[inline]
    pub fn box_to_inline_transitions(&self) -> &[NodeId] {
        &self.box_to_inline
    }

    #[inline]
    pub fn inline_to_box_transitions(&self) -> &[NodeId] {
        &self.inline_to_box
    }

    #[inline]
    pub(super) fn bump_epoch(epoch: &mut u32, stamps: &mut [u32]) -> u32 {
        *epoch = epoch.wrapping_add(1);
        if *epoch == 0 {
            stamps.fill(0);
            *epoch = 1;
        }
        *epoch
    }

    #[inline]
    pub(super) fn queue_dirty(&mut self, id: NodeId, push_list: bool) {
        let idx = id.index();
        if idx < self.dirty_stamp.len() && self.dirty_stamp[idx] != self.dirty_epoch {
            self.dirty_stamp[idx] = self.dirty_epoch;
            if push_list {
                self.dirty_paras.push(id);
            }
        }
    }

    #[inline]
    pub(super) fn record_layout_dirty(&mut self, id: NodeId) {
        let idx = id.index();
        if idx < self.layout_dirty_stamp.len()
            && self.layout_dirty_stamp[idx] != self.layout_dirty_epoch
        {
            self.layout_dirty_stamp[idx] = self.layout_dirty_epoch;
            self.dirty_layout_paras.push(id);
        }
    }

    #[inline]
    pub(super) fn record_paint_dirty(&mut self, id: NodeId) {
        let idx = id.index();
        if idx < self.paint_dirty_stamp.len()
            && self.paint_dirty_stamp[idx] != self.paint_dirty_epoch
        {
            self.paint_dirty_stamp[idx] = self.paint_dirty_epoch;
            self.dirty_paint_paras.push(id);
        }
    }

    #[inline]
    pub(super) fn is_created_this_frame(&self, id: NodeId) -> bool {
        let idx = id.index();
        idx < self.created_stamp.len() && self.created_stamp[idx] == self.created_epoch
    }

    pub(super) fn reset_frame_deltas(&mut self) {
        self.dirty_layout_paras.clear();
        self.dirty_paint_paras.clear();
        self.box_to_inline.clear();
        self.inline_to_box.clear();
        self.dirty_paras.clear();
        Self::bump_epoch(&mut self.dirty_epoch, &mut self.dirty_stamp);
        Self::bump_epoch(&mut self.paint_dirty_epoch, &mut self.paint_dirty_stamp);
        Self::bump_epoch(&mut self.layout_dirty_epoch, &mut self.layout_dirty_stamp);
    }
}