use std::cell::RefCell;
use std::sync::Arc;
use nativeview_engine::InteractionTracker;
use nativeview_engine::ext::slot_registry::SlotRegistry;
use nativeview_store::{NodeId, NodeStore, NvTable};
use nativeview_tables::media::MediaEnv;
use nativeview_tables::tables::{ContainerType, Display as NvDisplay, Layout as NvLayout};
use taffy::geometry::Size;
use taffy::style::{AvailableSpace, BoxSizing};
use taffy::tree::{Cache, Layout, LayoutInput, LayoutOutput, RunMode};
use taffy::util::ResolveOrZero;
use taffy::{
CacheTree, CoreStyle, LayoutContainingBlock, LayoutFlexboxContainer, LayoutGridContainer,
LayoutPartialTree, TraversePartialTree, TraverseTree, compute_hidden_layout,
};
use crate::scene::{EffectiveBox, NoResponsivePatches, StyleCascade};
use crate::{
LeafMeasureContext, LeafMeasureHook, ParagraphStore, ResolvedBoxEdges, ResolvedTextStyle,
TextMeasurer, TopLayerIndex,
};
use super::UnroundedBox;
use super::boundary::BoundaryRecord;
use super::container::scope::{ActiveContainer, ContainerRecord, GenSlots};
use super::contents::BoxChildren;
use super::node::NodeLists;
use super::responsive::{RespMemo, RespMemoSlot};
use super::responsive::sync::NodeStyleFlags;
use super::responsive::text::{MeasureParagraphs, ResponsiveTextEnv};
use super::style::{DEFAULT_LAYOUT_WORDS, LayoutSource, StyleView, StyleViewFlags};
pub(super) struct LayoutView<'s> {
pub(super) store: &'s NodeStore,
pub(super) root_index: u32,
pub(super) root_fills_viewport: bool,
pub(super) dry_run: bool,
pub(super) viewport: (f32, f32),
pub(super) media_env: MediaEnv,
pub(super) media_signature: u64,
pub(super) responsive_node_count: u32,
pub(super) container_node_count: u32,
pub(super) resolved_rtl: &'s [bool],
pub(super) resolved_text: &'s [ResolvedTextStyle],
pub(super) subtree_has_responsive: &'s [bool],
pub(super) has_responsive_typo: &'s [bool],
pub(super) style_flags: &'s [NodeStyleFlags],
pub(super) paragraphs: &'s ParagraphStore,
pub(super) caches: &'s mut [Cache],
pub(super) cached_env_hash: &'s mut [u64],
pub(super) container_records: &'s mut GenSlots<ContainerRecord>,
pub(super) boundary_records: Option<&'s mut GenSlots<BoundaryRecord>>,
pub(super) active_container: ActiveContainer,
pub(super) measure_paragraphs: RefCell<&'s mut MeasureParagraphs>,
pub(super) resp_memo_slot: &'s [RespMemoSlot],
pub(super) resp_memo: &'s [RefCell<RespMemo>],
pub(super) resp_pass_gen: u64,
pub(super) cache_gen: Option<(&'s mut [u64], u64)>,
pub(super) boxes: &'s mut [UnroundedBox],
pub(super) box_edges: Option<&'s mut [ResolvedBoxEdges]>,
pub(super) hoisted: Option<&'s mut NodeLists>,
pub(super) box_children: &'s BoxChildren,
pub(super) top_layer: &'s TopLayerIndex,
pub(super) interaction: Option<&'s InteractionTracker>,
pub(super) measurer: &'s dyn TextMeasurer,
pub(super) measure_hooks: &'s SlotRegistry<Arc<dyn LeafMeasureHook>>,
}
#[inline(always)]
pub(super) fn ix(n: taffy::NodeId) -> usize {
u64::from(n) as usize
}
#[inline(always)]
pub(super) fn tid_from_nv(id: NodeId) -> taffy::NodeId {
taffy::NodeId::from(id.index() as u64)
}
impl<'s> LayoutView<'s> {
#[inline(always)]
pub(super) fn id_of(&self, n: taffy::NodeId) -> NodeId {
self.store.id_at(ix(n)).unwrap_or(NodeId::NULL)
}
#[inline(always)]
pub(super) fn style(&self, n: taffy::NodeId) -> StyleView<'s> {
let i = ix(n);
let id = self.id_of(n);
let node_flags = self
.style_flags
.get(i)
.copied()
.unwrap_or(NodeStyleFlags::empty());
let responsive = if self.responsive_node_count > 0
&& node_flags.contains(NodeStyleFlags::RESPONSIVE)
{
self.resolved_responsive(id)
} else {
None
};
let is_root = i as u32 == self.root_index;
let (source, mut effective) = match responsive {
Some(r) => {
let layout = Some(self.store.row_from_words::<NvLayout>(&r.layout_words));
let base = EffectiveBox::from_layout(self.store, id, layout, r.show_on_hidden);
(LayoutSource::Responsive(r), base)
}
None => {
let raw = self
.store
.words(id, NvLayout::slot())
.and_then(|w| w.first_chunk::<26>());
let layout = raw.map(|w| self.store.row_from_words::<NvLayout>(w));
let base = EffectiveBox::from_layout(self.store, id, layout, false);
(
LayoutSource::Direct(raw.unwrap_or(DEFAULT_LAYOUT_WORDS)),
base,
)
}
};
if self.interaction.is_some() && node_flags.contains(NodeStyleFlags::HAS_STATE_BOX_PATCH) {
effective = StyleCascade {
responsive: &NoResponsivePatches,
interaction: self.interaction,
inert: None,
}
.apply_state(self.store, id, effective);
} else if effective.display == NvDisplay::None {
effective.container_type = ContainerType::Normal;
}
let mut flags = StyleViewFlags::empty();
flags.set(StyleViewFlags::IS_ROOT, is_root);
flags.set(StyleViewFlags::HOISTED, !is_root && self.top_layer.is_hoisted(id));
flags.set(StyleViewFlags::ROOT_FILLS_VIEWPORT, self.root_fills_viewport);
flags.set(StyleViewFlags::RTL, self.resolved_rtl[i]);
StyleView {
store: self.store,
source,
viewport: self.viewport,
id,
effective,
flags,
}
}
#[inline]
pub(super) fn bump_dry_cache_gen(&mut self) {
if let Some((gens, cur)) = self.cache_gen.as_mut() {
*cur = cur.wrapping_add(1);
if *cur == 0 {
gens.fill(0);
*cur = 1;
}
}
}
#[inline(always)]
pub(super) fn box_children(&self, parent: taffy::NodeId) -> &[NodeId] {
if self.dry_run {
self.box_children.get_in_flow(self.store, self.id_of(parent))
} else {
self.box_children.get(self.store, self.id_of(parent))
}
}
#[inline]
fn resolved_aspect_ratio(&self, n: taffy::NodeId, id: NodeId) -> Option<f32> {
let i = ix(n);
let is_responsive = self.responsive_node_count > 0
&& self
.style_flags
.get(i)
.is_some_and(|f| f.contains(NodeStyleFlags::RESPONSIVE));
if !is_responsive {
return self
.store
.try_row::<NvLayout>(id)
.and_then(|l| l.aspect_ratio())
.filter(|&r| r.is_finite() && r > 0.0);
}
self.style(n).aspect_ratio()
}
#[inline]
fn measure_leaf_hook(
&self,
n: taffy::NodeId,
id: NodeId,
known: Size<Option<f32>>,
available: Size<AvailableSpace>,
parent_width: Option<f32>,
) -> Option<Size<f32>> {
if self.measure_hooks.is_empty() {
return None;
}
let mask = self.store.node_tables(id).raw();
if (mask & self.measure_hooks.registered_mask()) == 0 {
return None;
}
let default_text = ResolvedTextStyle::default();
let resolved_text = self.resolved_text.get(id.index()).unwrap_or(&default_text);
let aspect_ratio = self.resolved_aspect_ratio(n, id);
let ctx = LeafMeasureContext {
store: self.store,
node: id,
known_dimensions: known,
available_space: available,
text_measurer: self.measurer,
resolved_text,
aspect_ratio,
};
let size = self
.measure_hooks
.find_map_in_mask(mask, |hook| hook.measure(&ctx))?;
let mut width = if size.width.is_finite() && size.width >= 0.0 {
size.width
} else {
0.0
};
let mut height = if size.height.is_finite() && size.height >= 0.0 {
size.height
} else {
0.0
};
if let Some(ratio) = aspect_ratio {
if known.width.is_some() != known.height.is_some() {
if let Some(ratio_size) = self.aspect_ratio_content_size(n, known, parent_width) {
return Some(ratio_size);
}
} else if known.width.is_none() && known.height.is_none() {
if width > 0.0 && height == 0.0 {
let h = width / ratio;
if h.is_finite() {
height = h;
}
} else if height > 0.0 && width == 0.0 {
let w = height * ratio;
if w.is_finite() {
width = w;
}
}
}
}
Some(Size { width, height })
}
#[inline]
fn measure_non_text_or_empty_leaf(
&self,
n: taffy::NodeId,
id: NodeId,
known: Size<Option<f32>>,
available: Size<AvailableSpace>,
parent_width: Option<f32>,
) -> Size<f32> {
if let Some(size) = self.measure_leaf_hook(n, id, known, available, parent_width) {
return size;
}
self.aspect_ratio_content_size(n, known, parent_width)
.unwrap_or(Size::ZERO)
}
pub(super) fn measure(
&self,
n: taffy::NodeId,
known: Size<Option<f32>>,
available: Size<AvailableSpace>,
parent_width: Option<f32>,
) -> Size<f32> {
let id = self.id_of(n);
let Some(para_view) = self.paragraphs.paragraph_view(self.store, id) else {
return self.measure_non_text_or_empty_leaf(n, id, known, available, parent_width);
};
if para_view.text.len == 0 || para_view.run_count == 0 {
return self.measure_non_text_or_empty_leaf(n, id, known, available, parent_width);
}
let ratio = self.aspect_ratio_content_size(n, known, parent_width);
let max_width = known
.width
.or(ratio.map(|r| r.width))
.or(match available.width {
AvailableSpace::Definite(w) => Some(w),
AvailableSpace::MinContent => Some(0.0),
AvailableSpace::MaxContent => None,
});
let idx = ix(n);
let (mw, mh) = if self.responsive_node_count > 0
&& self.has_responsive_typo.get(idx).copied().unwrap_or(false)
{
let mut scratch = self.measure_paragraphs.borrow_mut();
if scratch.needs_compile(id, self.responsive_cache_key(id)) {
let parent = self.store.parent(id);
let lookup = |nid: NodeId| self.env_seen_by(nid);
scratch.store.recompile_paragraph(
self.store,
id,
parent
.and_then(|p| self.resolved_text.get(p.index()).copied())
.unwrap_or_default(),
parent.is_some_and(|p| {
self.resolved_rtl.get(p.index()).copied().unwrap_or(false)
}),
None,
Some(ResponsiveTextEnv {
media: &self.media_env,
container_env_of: &lookup,
}),
);
}
match scratch.store.paragraph_view(self.store, id) {
Some(view) => self.measurer.measure_paragraph(&view, max_width),
None => self.measurer.measure_paragraph(¶_view, max_width),
}
} else {
self.measurer.measure_paragraph(¶_view, max_width)
};
let safe_w = if mw.is_finite() && mw >= 0.0 { mw } else { 0.0 };
let safe_h = if mh.is_finite() && mh >= 0.0 { mh } else { 0.0 };
let floor = ratio.unwrap_or(Size::ZERO);
Size {
width: known.width.unwrap_or(safe_w.max(floor.width)),
height: known.height.unwrap_or(safe_h.max(floor.height)),
}
}
fn aspect_ratio_content_size(
&self,
n: taffy::NodeId,
known: Size<Option<f32>>,
parent_width: Option<f32>,
) -> Option<Size<f32>> {
if known.width.is_some() == known.height.is_some() {
return None;
}
let i = ix(n);
let is_responsive = self.responsive_node_count > 0
&& self
.style_flags
.get(i)
.is_some_and(|f| f.contains(NodeStyleFlags::RESPONSIVE));
if !is_responsive {
let id = self.id_of(n);
let has_ratio = self
.store
.try_row::<NvLayout>(id)
.and_then(|l| l.aspect_ratio())
.is_some_and(|r| r.is_finite() && r > 0.0);
if !has_ratio {
return None;
}
}
let style = self.style(n);
let ratio = style.aspect_ratio()?;
let finite = |v: f32| if v.is_finite() && v >= 0.0 { v } else { 0.0 };
let no_calc = |_, _| 0.0;
let pb = (style.padding().resolve_or_zero(parent_width, no_calc)
+ style.border().resolve_or_zero(parent_width, no_calc))
.sum_axes();
let (width, height) = match (style.box_sizing(), known.width, known.height) {
(BoxSizing::BorderBox, Some(w), None) => {
let w = finite(w);
(w - pb.width, w / ratio - pb.height)
}
(BoxSizing::BorderBox, None, Some(h)) => {
let h = finite(h);
(h * ratio - pb.width, h - pb.height)
}
(BoxSizing::ContentBox, Some(w), None) => {
let cw = (finite(w) - pb.width).max(0.0);
(cw, cw / ratio)
}
(BoxSizing::ContentBox, None, Some(h)) => {
let ch = (finite(h) - pb.height).max(0.0);
(ch * ratio, ch)
}
_ => return None,
};
(width.is_finite() && height.is_finite()).then(|| Size {
width: width.max(0.0),
height: height.max(0.0),
})
}
}
type ChildIter<'a> =
core::iter::Map<core::iter::Copied<core::slice::Iter<'a, NodeId>>, fn(NodeId) -> taffy::NodeId>;
impl TraversePartialTree for LayoutView<'_> {
type ChildIter<'a>
= ChildIter<'a>
where
Self: 'a;
#[inline]
fn child_ids(&self, parent: taffy::NodeId) -> Self::ChildIter<'_> {
self.box_children(parent)
.iter()
.copied()
.map(tid_from_nv as fn(NodeId) -> taffy::NodeId)
}
#[inline]
fn child_count(&self, parent: taffy::NodeId) -> usize {
self.box_children(parent).len()
}
#[inline]
fn get_child_id(&self, parent: taffy::NodeId, child_index: usize) -> taffy::NodeId {
tid_from_nv(self.box_children(parent)[child_index])
}
}
impl TraverseTree for LayoutView<'_> {}
impl CacheTree for LayoutView<'_> {
#[inline]
fn cache_get(&self, n: taffy::NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
let i = ix(n);
if let Some((gens, cur)) = self.cache_gen.as_ref()
&& gens[i] != *cur
{
return None;
}
if self.responsive_node_count > 0
&& self.subtree_has_responsive.get(i).copied().unwrap_or(false)
{
let h = self.responsive_cache_key(self.id_of(n));
if self.cached_env_hash.get(i).copied().unwrap_or(0) != h {
return None;
}
}
self.caches[i].get(input)
}
#[inline]
fn cache_store(&mut self, n: taffy::NodeId, input: &LayoutInput, output: LayoutOutput) {
let i = ix(n);
if let Some((gens, cur)) = self.cache_gen.as_mut()
&& gens[i] != *cur
{
self.caches[i].clear();
gens[i] = *cur;
}
if self.responsive_node_count > 0
&& self.subtree_has_responsive.get(i).copied().unwrap_or(false)
{
let h = self.responsive_cache_key(self.id_of(n));
if let Some(slot) = self.cached_env_hash.get_mut(i)
&& *slot != h
{
self.caches[i].clear();
*slot = h;
}
}
self.caches[i].store(input, output);
}
#[inline]
fn cache_clear(&mut self, n: taffy::NodeId) {
let i = ix(n);
if let Some((gens, _)) = self.cache_gen.as_mut() {
gens[i] = 0;
} else {
self.caches[i].clear();
}
if let Some(slot) = self.cached_env_hash.get_mut(i) {
*slot = 0;
}
}
}
impl LayoutPartialTree for LayoutView<'_> {
type CoreContainerStyle<'a>
= StyleView<'a>
where
Self: 'a;
type CustomIdent = String;
#[inline]
fn get_core_container_style(&self, n: taffy::NodeId) -> Self::CoreContainerStyle<'_> {
self.style(n)
}
#[inline]
fn set_unrounded_layout(&mut self, n: taffy::NodeId, layout: &Layout) {
if self.dry_run {
return;
}
let i = ix(n);
self.boxes[i] = UnroundedBox {
x: layout.location.x,
y: layout.location.y,
w: layout.size.width,
h: layout.size.height,
};
if let Some(edges) = self.box_edges.as_deref_mut() {
let ov = layout.scrollable_overflow_rect.rect();
edges[i] = ResolvedBoxEdges {
margin: [
layout.margin.top,
layout.margin.right,
layout.margin.bottom,
layout.margin.left,
],
border: [
layout.border.top,
layout.border.right,
layout.border.bottom,
layout.border.left,
],
padding: [
layout.padding.top,
layout.padding.right,
layout.padding.bottom,
layout.padding.left,
],
content_w: (ov.right - ov.left).max(0.0),
content_h: (ov.bottom - ov.top).max(0.0),
};
}
}
fn compute_child_layout(&mut self, n: taffy::NodeId, inputs: LayoutInput) -> LayoutOutput {
if inputs.run_mode == RunMode::PerformHiddenLayout {
self.clear_hoisted_children(n);
return compute_hidden_layout(self, n);
}
if self.container_node_count > 0 && self.is_out_of_flow_candidate(self.id_of(n)) {
return self.compute_out_of_flow_child(n, inputs);
}
self.compute_child_layout_inner(n, inputs)
}
}
impl LayoutContainingBlock for LayoutView<'_> {
type OofItemStyle<'a>
= StyleView<'a>
where
Self: 'a;
#[inline]
fn get_oof_item_style(&self, n: taffy::NodeId) -> Self::OofItemStyle<'_> {
self.style(n)
}
#[inline]
fn clear_hoisted_children(&mut self, n: taffy::NodeId) {
if let Some(hoisted) = self.hoisted.as_deref_mut() {
hoisted.clear(ix(n));
}
}
#[inline]
fn add_hoisted_children(&mut self, n: taffy::NodeId, hoisted: &[taffy::NodeId]) {
if hoisted.is_empty() {
return;
}
if let Some(lists) = self.hoisted.as_deref_mut() {
let store = self.store;
lists.extend(ix(n), hoisted.iter().filter_map(|&c| store.id_at(ix(c))));
}
}
}
impl LayoutFlexboxContainer for LayoutView<'_> {
type FlexboxContainerStyle<'a>
= StyleView<'a>
where
Self: 'a;
type FlexboxItemStyle<'a>
= StyleView<'a>
where
Self: 'a;
#[inline]
fn get_flexbox_container_style(&self, n: taffy::NodeId) -> Self::FlexboxContainerStyle<'_> {
self.style(n)
}
#[inline]
fn get_flexbox_child_style(&self, n: taffy::NodeId) -> Self::FlexboxItemStyle<'_> {
self.style(n)
}
}
impl LayoutGridContainer for LayoutView<'_> {
type GridContainerStyle<'a>
= StyleView<'a>
where
Self: 'a;
type GridItemStyle<'a>
= StyleView<'a>
where
Self: 'a;
#[inline]
fn get_grid_container_style(&self, n: taffy::NodeId) -> Self::GridContainerStyle<'_> {
self.style(n)
}
#[inline]
fn get_grid_child_style(&self, n: taffy::NodeId) -> Self::GridItemStyle<'_> {
self.style(n)
}
}