Skip to main content

cranpose_ui/layout/
mod.rs

1pub mod core;
2pub mod policies;
3
4use std::{
5    cell::{Cell, RefCell},
6    fmt,
7    mem::size_of,
8    rc::Rc,
9    sync::OnceLock,
10};
11
12use cranpose_core::{
13    Applier, ApplierHost, Composer, ConcreteApplierHost, MemoryApplier, Node, NodeError, NodeId,
14    Phase, RuntimeHandle, SlotTable, SlotsHost, SnapshotStateObserver,
15};
16
17use self::core::Measurable;
18use self::core::Placeable;
19#[cfg(test)]
20use self::core::{HorizontalAlignment, VerticalAlignment};
21use crate::modifier::{
22    collect_semantics_from_modifier, DimensionConstraint, EdgeInsets, Modifier, ModifierNodeSlices,
23    ModifierNodeSlicesDebugStats, Point, Rect as GeometryRect, ResolvedModifiers, Size,
24};
25
26use crate::subcompose_layout::{CachedBatchMeasureInputs, SubcomposeLayoutNode};
27use crate::widgets::nodes::{IntrinsicKind, LayoutNode, LayoutNodeCacheHandles, LayoutState};
28use cranpose_foundation::{
29    text::TextRange, InvalidationKind, ModifierNodeContext, NodeCapabilities,
30    SemanticsConfiguration,
31};
32use cranpose_ui_layout::{Constraints, MeasurePolicy, Placement};
33use web_time::Instant;
34
35/// Runtime context for modifier nodes during measurement.
36///
37/// Unlike `BasicModifierNodeContext`, this context accumulates invalidations
38/// that can be processed after measurement to set dirty flags on the LayoutNode.
39#[derive(Default)]
40pub(crate) struct LayoutNodeContext {
41    invalidations: Vec<InvalidationKind>,
42    update_requested: bool,
43    active_capabilities: Vec<NodeCapabilities>,
44}
45
46impl LayoutNodeContext {
47    pub(crate) fn new() -> Self {
48        Self::default()
49    }
50
51    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationKind> {
52        std::mem::take(&mut self.invalidations)
53    }
54}
55
56impl ModifierNodeContext for LayoutNodeContext {
57    fn invalidate(&mut self, kind: InvalidationKind) {
58        if !self.invalidations.contains(&kind) {
59            self.invalidations.push(kind);
60        }
61    }
62
63    fn request_update(&mut self) {
64        self.update_requested = true;
65    }
66
67    fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
68        self.active_capabilities.push(capabilities);
69    }
70
71    fn pop_active_capabilities(&mut self) {
72        self.active_capabilities.pop();
73    }
74}
75
76/// Forces all layout caches to be invalidated on the next measure by incrementing the epoch.
77///
78/// # ⚠️ Internal Use Only - NOT Public API
79///
80/// **This function is hidden from public documentation and MUST NOT be called by external code.**
81///
82/// Only `cranpose-app-shell` may call this for rare global events:
83/// - Window/viewport resize
84/// - Global font scale or density changes
85/// - Debug toggles that affect all layout
86///
87/// **This is O(entire app size) - extremely expensive!**
88///
89/// # For Local Changes
90///
91/// **Do NOT use this for scroll, single-node mutations, or any local layout change.**
92/// Instead, use the scoped repass mechanism:
93/// ```text
94/// cranpose_ui::schedule_layout_repass(node_id);
95/// ```
96///
97/// The scoped path bubbles dirty flags without invalidating all caches, giving you O(subtree) instead of O(app).
98#[doc(hidden)]
99pub fn invalidate_all_layout_caches() {
100    crate::render_state::invalidate_layout_cache_epoch();
101}
102
103fn layout_measure_telemetry_threshold_ms() -> Option<f64> {
104    static THRESHOLD_MS: OnceLock<Option<f64>> = OnceLock::new();
105    *THRESHOLD_MS.get_or_init(|| {
106        std::env::var("CRANPOSE_LAYOUT_MEASURE_TELEMETRY_MS")
107            .ok()
108            .and_then(|value| value.parse::<f64>().ok())
109            .filter(|value| value.is_finite() && *value >= 0.0)
110            .or_else(|| {
111                std::env::var_os("CRANPOSE_LAYOUT_MEASURE_TELEMETRY")
112                    .is_some()
113                    .then_some(4.0)
114            })
115    })
116}
117
118struct LayoutMeasureTelemetry {
119    root: NodeId,
120    start: Instant,
121    after_repasses: Instant,
122    after_guard: Instant,
123    after_builder: Instant,
124    after_measure: Instant,
125    after_root_place: Instant,
126    after_aux: Instant,
127    after_builder_drop: Instant,
128    after_guard_drop: Instant,
129}
130
131fn log_layout_measure_telemetry(times: LayoutMeasureTelemetry) {
132    let Some(threshold_ms) = layout_measure_telemetry_threshold_ms() else {
133        return;
134    };
135
136    let total_ms = times
137        .after_guard_drop
138        .duration_since(times.start)
139        .as_secs_f64()
140        * 1000.0;
141    if total_ms < threshold_ms {
142        return;
143    }
144
145    let repass_ms = times
146        .after_repasses
147        .duration_since(times.start)
148        .as_secs_f64()
149        * 1000.0;
150    let guard_ms = times
151        .after_guard
152        .duration_since(times.after_repasses)
153        .as_secs_f64()
154        * 1000.0;
155    let builder_ms = times
156        .after_builder
157        .duration_since(times.after_guard)
158        .as_secs_f64()
159        * 1000.0;
160    let measure_ms = times
161        .after_measure
162        .duration_since(times.after_builder)
163        .as_secs_f64()
164        * 1000.0;
165    let root_place_ms = times
166        .after_root_place
167        .duration_since(times.after_measure)
168        .as_secs_f64()
169        * 1000.0;
170    let aux_ms = times
171        .after_aux
172        .duration_since(times.after_root_place)
173        .as_secs_f64()
174        * 1000.0;
175    let builder_drop_ms = times
176        .after_builder_drop
177        .duration_since(times.after_aux)
178        .as_secs_f64()
179        * 1000.0;
180    let guard_drop_ms = times
181        .after_guard_drop
182        .duration_since(times.after_builder_drop)
183        .as_secs_f64()
184        * 1000.0;
185    log::warn!(
186        "[layout-measure-telemetry] root={} total_ms={total_ms:.2} repass_ms={repass_ms:.2} guard_ms={guard_ms:.2} builder_ms={builder_ms:.2} measure_ms={measure_ms:.2} root_place_ms={root_place_ms:.2} aux_ms={aux_ms:.2} builder_drop_ms={builder_drop_ms:.2} guard_drop_ms={guard_drop_ms:.2}",
187        times.root
188    );
189}
190
191fn log_node_measure_telemetry(
192    kind: &'static str,
193    node_id: NodeId,
194    constraints: Constraints,
195    size: Size,
196    children: usize,
197    start: Instant,
198) {
199    let Some(threshold_ms) = layout_measure_telemetry_threshold_ms() else {
200        return;
201    };
202
203    let total_ms = start.elapsed().as_secs_f64() * 1000.0;
204    if total_ms < threshold_ms {
205        return;
206    }
207
208    log::warn!(
209        "[layout-node-telemetry] kind={kind} node={} total_ms={total_ms:.2} constraints=({:.1},{:.1},{:.1},{:.1}) size=({:.1},{:.1}) children={children}",
210        node_id,
211        constraints.min_width,
212        constraints.max_width,
213        constraints.min_height,
214        constraints.max_height,
215        size.width,
216        size.height,
217    );
218}
219
220/// RAII guard that:
221/// - moves the current MemoryApplier into a ConcreteApplierHost
222/// - holds a shared handle to the `SlotTable` used by `LayoutBuilder`
223/// - on Drop, always:
224///   * restores slots into the host from the shared handle
225///   * moves the original MemoryApplier back into the Composition
226///
227/// This makes `measure_layout` panic/Err-safe wrt both the applier and slots.
228/// The key invariant: guard and builder share the same `Rc<RefCell<SlotTable>>`,
229/// so the guard never loses access to the authoritative slots even on panic.
230struct ApplierSlotGuard<'a> {
231    /// The `MemoryApplier` inside the Composition::applier that we must restore into.
232    target: &'a mut MemoryApplier,
233    /// Host that owns the original MemoryApplier while layout is running.
234    host: Rc<ConcreteApplierHost<MemoryApplier>>,
235    /// Shared handle to the slot table. Both the guard and the builder hold a clone.
236    /// On Drop, we write whatever is in this handle back into the applier.
237    slots: Rc<RefCell<SlotTable>>,
238}
239
240impl<'a> ApplierSlotGuard<'a> {
241    /// Creates a new guard:
242    /// - moves the current MemoryApplier out of `target` into a host
243    /// - takes the current slots out of the host and wraps them in a shared handle
244    fn new(target: &'a mut MemoryApplier) -> Self {
245        // Move the original applier into a host; leave `target` with a fresh one
246        let original_applier = std::mem::replace(target, MemoryApplier::new());
247        let host = Rc::new(ConcreteApplierHost::new(original_applier));
248
249        // Take slots from the host into a shared handle
250        let slots = {
251            let mut applier_ref = host.borrow_typed();
252            std::mem::take(applier_ref.slots())
253        };
254        let slots = Rc::new(RefCell::new(slots));
255
256        Self {
257            target,
258            host,
259            slots,
260        }
261    }
262
263    /// Rc to pass into LayoutBuilder::new_with_epoch
264    fn host(&self) -> Rc<ConcreteApplierHost<MemoryApplier>> {
265        Rc::clone(&self.host)
266    }
267
268    /// Returns the shared handle to slots for the builder to use.
269    /// The builder clones this Rc, so both guard and builder share the same slots.
270    fn slots_handle(&self) -> Rc<RefCell<SlotTable>> {
271        Rc::clone(&self.slots)
272    }
273}
274
275impl Drop for ApplierSlotGuard<'_> {
276    fn drop(&mut self) {
277        // 1) Restore slots into the host's MemoryApplier from the shared handle.
278        // This works correctly whether we're on the success path or panic/error path,
279        // because we always have the shared handle.
280        {
281            let mut applier_ref = self.host.borrow_typed();
282            *applier_ref.slots() = std::mem::take(&mut *self.slots.borrow_mut());
283        }
284
285        // 2) Move the original MemoryApplier (with restored/updated slots) back into `target`
286        {
287            let mut applier_ref = self.host.borrow_typed();
288            let original_applier = std::mem::take(&mut *applier_ref);
289            let _ = std::mem::replace(self.target, original_applier);
290        }
291        // No Rc::try_unwrap in Drop → no "panic during panic" risk.
292    }
293}
294
295/// Result of measuring through the modifier node chain.
296struct ModifierChainMeasurement {
297    size: Size,
298    /// Content offset for scroll/inner transforms - NOT padding semantics
299    content_offset: Point,
300    /// Node's own offset (from OffsetNode, affects position in parent)
301    offset: Point,
302}
303
304type LayoutModifierNodeData = (
305    usize,
306    Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
307);
308
309struct ScratchVecPool<T> {
310    available: Vec<Vec<T>>,
311}
312
313impl<T> ScratchVecPool<T> {
314    fn acquire(&mut self) -> Vec<T> {
315        self.available.pop().unwrap_or_default()
316    }
317
318    fn release(&mut self, mut values: Vec<T>) {
319        values.clear();
320        self.available.push(values);
321    }
322
323    #[cfg(test)]
324    fn available_count(&self) -> usize {
325        self.available.len()
326    }
327}
328
329impl<T> Default for ScratchVecPool<T> {
330    fn default() -> Self {
331        Self {
332            available: Vec::new(),
333        }
334    }
335}
336
337#[derive(Default)]
338pub(crate) struct FrameLayoutArena {
339    tmp_records: ScratchVecPool<(NodeId, ChildRecord)>,
340    tmp_child_ids: ScratchVecPool<NodeId>,
341    tmp_layout_node_data: ScratchVecPool<LayoutModifierNodeData>,
342    tmp_placements: ScratchVecPool<Placement>,
343}
344
345#[cfg(test)]
346impl FrameLayoutArena {
347    pub(crate) fn available_placement_scratch_count(&self) -> usize {
348        self.tmp_placements.available_count()
349    }
350
351    pub(crate) fn seed_placement_scratch_for_test(&mut self) {
352        self.tmp_placements.release(Vec::with_capacity(1));
353    }
354}
355
356/// Discrete event callback reference produced during semantics extraction.
357#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct SemanticsCallback {
359    node_id: NodeId,
360}
361
362impl SemanticsCallback {
363    pub fn new(node_id: NodeId) -> Self {
364        Self { node_id }
365    }
366
367    pub fn node_id(&self) -> NodeId {
368        self.node_id
369    }
370}
371
372/// Semantics action exposed to the input system.
373#[derive(Clone, Debug, PartialEq, Eq)]
374pub enum SemanticsAction {
375    Click { handler: SemanticsCallback },
376}
377
378/// Semantic role describing how a node should participate in accessibility and hit testing.
379/// Roles are now derived from SemanticsConfiguration rather than widget types.
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub enum SemanticsRole {
382    /// Generic container or layout node
383    Layout,
384    /// Subcomposition boundary
385    Subcompose,
386    /// Text content derived from the text node semantics payload.
387    Text { value: String },
388    /// Spacer (non-interactive)
389    Spacer,
390    /// Button (derived from is_button semantics flag)
391    Button,
392    /// Unknown or unspecified role
393    Unknown,
394}
395
396/// A single node within the semantics tree.
397#[derive(Clone, Debug, PartialEq, Eq)]
398pub struct SemanticsNode {
399    pub node_id: NodeId,
400    pub role: SemanticsRole,
401    pub actions: Vec<SemanticsAction>,
402    pub children: Vec<SemanticsNode>,
403    pub description: Option<String>,
404    pub editable_text: bool,
405    pub text_selection: Option<TextRange>,
406}
407
408impl SemanticsNode {
409    fn new(
410        node_id: NodeId,
411        role: SemanticsRole,
412        actions: Vec<SemanticsAction>,
413        children: Vec<SemanticsNode>,
414        description: Option<String>,
415        editable_text: bool,
416        text_selection: Option<TextRange>,
417    ) -> Self {
418        Self {
419            node_id,
420            role,
421            actions,
422            children,
423            description,
424            editable_text,
425            text_selection,
426        }
427    }
428}
429
430/// Rooted semantics tree extracted after layout.
431#[derive(Clone, Debug, PartialEq, Eq)]
432pub struct SemanticsTree {
433    root: SemanticsNode,
434}
435
436impl SemanticsTree {
437    fn new(root: SemanticsNode) -> Self {
438        Self { root }
439    }
440
441    pub fn root(&self) -> &SemanticsNode {
442        &self.root
443    }
444}
445
446#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
447pub struct LayoutAllocationDebugStats {
448    pub layout_box_count: usize,
449    pub layout_box_child_count: usize,
450    pub layout_box_child_capacity: usize,
451    pub layout_box_heap_bytes: usize,
452    pub modifier_slice_count: usize,
453    pub modifier_slice_heap_bytes: usize,
454    pub modifier_draw_command_count: usize,
455    pub modifier_draw_command_capacity: usize,
456    pub modifier_pointer_input_count: usize,
457    pub modifier_pointer_input_capacity: usize,
458    pub modifier_click_handler_count: usize,
459    pub modifier_click_handler_capacity: usize,
460    pub modifier_text_content_count: usize,
461    pub modifier_text_style_count: usize,
462    pub modifier_text_layout_options_count: usize,
463    pub modifier_prepared_text_layout_count: usize,
464    pub modifier_graphics_layer_count: usize,
465    pub modifier_graphics_layer_resolver_count: usize,
466    pub semantics_node_count: usize,
467    pub semantics_action_count: usize,
468    pub semantics_action_capacity: usize,
469    pub semantics_child_count: usize,
470    pub semantics_child_capacity: usize,
471    pub semantics_description_count: usize,
472    pub semantics_description_bytes: usize,
473    pub semantics_text_role_bytes: usize,
474    pub semantics_heap_bytes: usize,
475}
476
477impl LayoutAllocationDebugStats {
478    fn add_modifier_slice(&mut self, stats: ModifierNodeSlicesDebugStats) {
479        self.modifier_slice_count += 1;
480        self.modifier_slice_heap_bytes += stats.heap_bytes;
481        self.modifier_draw_command_count += stats.draw_command_count;
482        self.modifier_draw_command_capacity += stats.draw_command_capacity;
483        self.modifier_pointer_input_count += stats.pointer_input_count;
484        self.modifier_pointer_input_capacity += stats.pointer_input_capacity;
485        self.modifier_click_handler_count += stats.click_handler_count;
486        self.modifier_click_handler_capacity += stats.click_handler_capacity;
487        self.modifier_text_content_count += usize::from(stats.has_text_content);
488        self.modifier_text_style_count += usize::from(stats.has_text_style);
489        self.modifier_text_layout_options_count += usize::from(stats.has_text_layout_options);
490        self.modifier_prepared_text_layout_count += usize::from(stats.has_prepared_text_layout);
491        self.modifier_graphics_layer_count += usize::from(stats.has_graphics_layer);
492        self.modifier_graphics_layer_resolver_count +=
493            usize::from(stats.has_graphics_layer_resolver);
494    }
495}
496
497/// Result of running layout for a Compose tree.
498#[derive(Debug, Clone)]
499pub struct LayoutTree {
500    root: LayoutBox,
501}
502
503impl LayoutTree {
504    pub fn new(root: LayoutBox) -> Self {
505        Self { root }
506    }
507
508    pub fn root(&self) -> &LayoutBox {
509        &self.root
510    }
511
512    pub fn root_mut(&mut self) -> &mut LayoutBox {
513        &mut self.root
514    }
515
516    pub fn into_root(self) -> LayoutBox {
517        self.root
518    }
519
520    pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
521        let mut stats = LayoutAllocationDebugStats::default();
522        record_layout_box_allocation_stats(&self.root, &mut stats);
523        stats
524    }
525}
526
527/// Layout information for a single node.
528#[derive(Debug, Clone)]
529pub struct LayoutBox {
530    pub node_id: NodeId,
531    pub rect: GeometryRect,
532    /// Content offset for scroll/inner transforms (applies to children, NOT this node's position)
533    pub content_offset: Point,
534    pub node_data: LayoutNodeData,
535    pub children: Vec<LayoutBox>,
536}
537
538impl LayoutBox {
539    pub fn new(
540        node_id: NodeId,
541        rect: GeometryRect,
542        content_offset: Point,
543        node_data: LayoutNodeData,
544        children: Vec<LayoutBox>,
545    ) -> Self {
546        Self {
547            node_id,
548            rect,
549            content_offset,
550            node_data,
551            children,
552        }
553    }
554}
555
556/// Snapshot of the data required to render a layout node.
557#[derive(Debug, Clone)]
558pub struct LayoutNodeData {
559    pub modifier: Modifier,
560    pub resolved_modifiers: ResolvedModifiers,
561    pub modifier_slices: Rc<ModifierNodeSlices>,
562    pub kind: LayoutNodeKind,
563}
564
565impl LayoutNodeData {
566    pub fn new(
567        modifier: Modifier,
568        resolved_modifiers: ResolvedModifiers,
569        modifier_slices: Rc<ModifierNodeSlices>,
570        kind: LayoutNodeKind,
571    ) -> Self {
572        Self {
573            modifier,
574            resolved_modifiers,
575            modifier_slices,
576            kind,
577        }
578    }
579
580    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
581        self.resolved_modifiers
582    }
583
584    pub fn modifier_slices(&self) -> &ModifierNodeSlices {
585        &self.modifier_slices
586    }
587}
588
589/// Classification of the node captured inside a [`LayoutBox`].
590///
591/// Note: Text content is no longer represented as a distinct LayoutNodeKind.
592/// Text nodes now use `LayoutNodeKind::Layout` with their content stored in
593/// `modifier_slices.text_content()` via TextModifierNode, following Jetpack
594/// Compose's pattern where text is a modifier node capability.
595#[derive(Clone)]
596pub enum LayoutNodeKind {
597    Layout,
598    Subcompose,
599    Spacer,
600    Button { on_click: Rc<RefCell<dyn FnMut()>> },
601    Unknown,
602}
603
604impl fmt::Debug for LayoutNodeKind {
605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606        match self {
607            LayoutNodeKind::Layout => f.write_str("Layout"),
608            LayoutNodeKind::Subcompose => f.write_str("Subcompose"),
609            LayoutNodeKind::Spacer => f.write_str("Spacer"),
610            LayoutNodeKind::Button { .. } => f.write_str("Button"),
611            LayoutNodeKind::Unknown => f.write_str("Unknown"),
612        }
613    }
614}
615
616/// Extension trait that equips `MemoryApplier` with layout computation.
617pub trait LayoutEngine {
618    fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError>;
619}
620
621impl LayoutEngine for MemoryApplier {
622    fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError> {
623        let measurements = measure_layout(self, root, max_size)?;
624        measurements
625            .into_layout_tree()
626            .ok_or(NodeError::MissingContext {
627                id: root,
628                reason: "layout tree was not requested",
629            })
630    }
631}
632
633/// Result of running the measure pass for a Compose layout tree.
634#[derive(Debug, Clone)]
635pub struct LayoutMeasurements {
636    root: Rc<MeasuredNode>,
637    semantics: Option<SemanticsTree>,
638    layout_tree: Option<LayoutTree>,
639}
640
641impl LayoutMeasurements {
642    fn new(
643        root: Rc<MeasuredNode>,
644        semantics: Option<SemanticsTree>,
645        layout_tree: Option<LayoutTree>,
646    ) -> Self {
647        Self {
648            root,
649            semantics,
650            layout_tree,
651        }
652    }
653
654    /// Returns the measured size of the root node.
655    pub fn root_size(&self) -> Size {
656        self.root.size
657    }
658
659    pub fn semantics_tree(&self) -> Option<&SemanticsTree> {
660        self.semantics.as_ref()
661    }
662
663    pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
664        let mut stats = self
665            .layout_tree
666            .as_ref()
667            .map(LayoutTree::debug_allocation_stats)
668            .unwrap_or_default();
669        if let Some(semantics) = &self.semantics {
670            record_semantics_allocation_stats(semantics.root(), &mut stats);
671        }
672        stats
673    }
674
675    /// Consumes the measurements and returns the built [`LayoutTree`], if requested.
676    pub fn into_layout_tree(self) -> Option<LayoutTree> {
677        self.layout_tree
678    }
679
680    /// Returns a cloned [`LayoutTree`] for rendering/debug consumers, if requested.
681    pub fn layout_tree(&self) -> Option<LayoutTree> {
682        self.layout_tree.clone()
683    }
684}
685
686/// Builds a semantics tree from an existing [`LayoutTree`].
687///
688/// This is useful for consumers that need semantics on demand without forcing
689/// every layout pass to eagerly allocate a full [`SemanticsTree`].
690pub fn build_semantics_tree_from_layout_tree(layout_tree: &LayoutTree) -> SemanticsTree {
691    SemanticsTree::new(build_semantics_node_from_layout_box(layout_tree.root()))
692}
693
694/// Builds a layout snapshot from retained layout state in the live applier tree.
695///
696/// Renderers use retained node state directly. This function exists for debug,
697/// robot, and tests that need an owned [`LayoutTree`] without forcing every
698/// layout pass to allocate one.
699pub fn build_layout_tree_from_applier(
700    applier: &mut MemoryApplier,
701    root: NodeId,
702) -> Result<Option<LayoutTree>, NodeError> {
703    fn snapshot(
704        applier: &mut MemoryApplier,
705        node_id: NodeId,
706    ) -> Result<Option<(crate::widgets::nodes::layout_node::LayoutState, Vec<NodeId>)>, NodeError>
707    {
708        match applier.with_node::<LayoutNode, _>(node_id, |node| {
709            (node.layout_state(), node.children.clone())
710        }) {
711            Ok(snapshot) => return Ok(Some(snapshot)),
712            Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {}
713            Err(err) => return Err(err),
714        }
715
716        match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
717            (node.layout_state(), node.active_children())
718        }) {
719            Ok(snapshot) => Ok(Some(snapshot)),
720            Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => Ok(None),
721            Err(err) => Err(err),
722        }
723    }
724
725    fn place(
726        applier: &mut MemoryApplier,
727        node_id: NodeId,
728        parent_content_origin: Point,
729    ) -> Result<Option<LayoutBox>, NodeError> {
730        let Some((state, child_ids)) = snapshot(applier, node_id)? else {
731            return Ok(None);
732        };
733        if !state.is_placed {
734            return Ok(None);
735        }
736
737        let top_left = Point {
738            x: parent_content_origin.x + state.position.x,
739            y: parent_content_origin.y + state.position.y,
740        };
741        let rect = GeometryRect {
742            x: top_left.x,
743            y: top_left.y,
744            width: state.size.width,
745            height: state.size.height,
746        };
747        let info = runtime_metadata_for(applier, node_id)?;
748        let kind = layout_kind_from_metadata(node_id, &info);
749        let RuntimeNodeMetadata {
750            modifier,
751            resolved_modifiers,
752            modifier_slices,
753            ..
754        } = info;
755        let data = LayoutNodeData::new(modifier, resolved_modifiers, modifier_slices, kind);
756        let child_origin = Point {
757            x: top_left.x + state.content_offset.x,
758            y: top_left.y + state.content_offset.y,
759        };
760        let mut children = Vec::with_capacity(child_ids.len());
761        for child_id in child_ids {
762            if let Some(child) = place(applier, child_id, child_origin)? {
763                children.push(child);
764            }
765        }
766
767        Ok(Some(LayoutBox::new(
768            node_id,
769            rect,
770            state.content_offset,
771            data,
772            children,
773        )))
774    }
775
776    place(applier, root, Point::default()).map(|root| root.map(LayoutTree::new))
777}
778
779/// Builds a semantics snapshot from retained layout state in the live applier tree.
780///
781/// This is the on-demand counterpart to [`build_layout_tree_from_applier`].
782/// It follows the currently placed child set, including subcompose active
783/// children, and clears semantics dirty flags for nodes it visits.
784pub fn build_semantics_tree_from_applier(
785    applier: &mut MemoryApplier,
786    root: NodeId,
787) -> Result<Option<SemanticsTree>, NodeError> {
788    fn node(
789        applier: &mut MemoryApplier,
790        node_id: NodeId,
791    ) -> Result<Option<SemanticsNode>, NodeError> {
792        match applier.with_node::<LayoutNode, _>(node_id, |layout| {
793            let state = layout.layout_state();
794            if !state.is_placed {
795                return None;
796            }
797            let role = role_from_modifier_slices(&layout.modifier_slices_snapshot());
798            let config = layout.semantics_configuration();
799            let children = layout.children.clone();
800            layout.clear_needs_semantics();
801            Some((role, config, children))
802        }) {
803            Ok(Some((role, config, child_ids))) => {
804                let mut children = Vec::with_capacity(child_ids.len());
805                for child_id in child_ids {
806                    if let Some(child) = node(applier, child_id)? {
807                        children.push(child);
808                    }
809                }
810                return Ok(Some(semantics_node_from_parts(
811                    node_id, role, config, children,
812                )));
813            }
814            Ok(None) => return Ok(None),
815            Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {}
816            Err(err) => return Err(err),
817        }
818
819        match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |subcompose| {
820            let state = subcompose.layout_state();
821            if !state.is_placed {
822                return None;
823            }
824            let config = collect_semantics_from_modifier(&subcompose.modifier());
825            let children = subcompose.active_children();
826            subcompose.clear_needs_semantics();
827            Some((config, children))
828        }) {
829            Ok(Some((config, child_ids))) => {
830                let mut children = Vec::with_capacity(child_ids.len());
831                for child_id in child_ids {
832                    if let Some(child) = node(applier, child_id)? {
833                        children.push(child);
834                    }
835                }
836                Ok(Some(semantics_node_from_parts(
837                    node_id,
838                    SemanticsRole::Subcompose,
839                    config,
840                    children,
841                )))
842            }
843            Ok(None) | Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
844                Ok(None)
845            }
846            Err(err) => Err(err),
847        }
848    }
849
850    node(applier, root).map(|root| root.map(SemanticsTree::new))
851}
852
853#[derive(Clone, Copy, Debug, PartialEq, Eq)]
854pub struct MeasureLayoutOptions {
855    pub collect_semantics: bool,
856    pub build_layout_tree: bool,
857}
858
859impl Default for MeasureLayoutOptions {
860    fn default() -> Self {
861        Self {
862            collect_semantics: true,
863            build_layout_tree: true,
864        }
865    }
866}
867
868/// Check if a node or any of its descendants needs measure (selective measure optimization).
869/// This can be used by the app shell to skip layout when the tree is clean.
870///
871/// O(1) check - just looks at root's dirty flag.
872/// Works because all mutation paths bubble dirty flags to root via composer commands.
873///
874/// Returns Result to force caller to handle errors explicitly. No more unwrap_or(true) safety net.
875pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
876    Ok(applier.get_mut(root)?.needs_layout())
877}
878
879/// Check if the root semantics snapshot is dirty.
880///
881/// Semantics invalidations bubble to the root the same way layout invalidations do,
882/// so a root check is sufficient to determine whether the next layout pass needs to
883/// rebuild semantic data even when geometry is otherwise unchanged.
884pub fn tree_needs_semantics(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
885    Ok(applier.get_mut(root)?.needs_semantics())
886}
887
888/// Test helper: bubbles layout dirty flag to root.
889#[cfg(test)]
890pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
891    cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
892}
893
894/// Runs the measure phase for the subtree rooted at `root`.
895pub fn measure_layout(
896    applier: &mut MemoryApplier,
897    root: NodeId,
898    max_size: Size,
899) -> Result<LayoutMeasurements, NodeError> {
900    measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
901}
902
903pub fn measure_layout_with_options(
904    applier: &mut MemoryApplier,
905    root: NodeId,
906    max_size: Size,
907    options: MeasureLayoutOptions,
908) -> Result<LayoutMeasurements, NodeError> {
909    let telemetry_start = Instant::now();
910    process_pending_layout_repasses(applier, root)?;
911    let after_repasses = Instant::now();
912
913    let constraints = Constraints {
914        min_width: 0.0,
915        max_width: max_size.width,
916        min_height: 0.0,
917        max_height: max_size.height,
918    };
919
920    // Selective measure: only increment epoch if something needs MEASURING (not just layout)
921    // O(1) check - just look at root's dirty flag (bubbling ensures correctness)
922    //
923    // CRITICAL: We check needs_MEASURE, not needs_LAYOUT!
924    // - needs_measure: size may change, caches must be invalidated
925    // - needs_layout: position may change but size is cached (e.g., scroll)
926    //
927    // Scroll operations bubble needs_layout to ancestors, but NOT needs_measure.
928    // Using needs_layout here would wipe ALL caches on every scroll frame, causing
929    // O(N) full remeasurement instead of O(changed nodes).
930    let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
931        .with_node::<LayoutNode, _>(root, |node| {
932            (
933                node.needs_measure(), // CORRECT: check needs_measure, not needs_layout
934                node.needs_semantics(),
935                node.cache_handles().epoch(),
936            )
937        }) {
938        Ok(tuple) => tuple,
939        Err(NodeError::TypeMismatch { .. }) => {
940            let node = applier.get_mut(root)?;
941            // Non-LayoutNode roots still expose Node dirty flags.
942            // Use needs_measure here so layout-only subtree repasses can reuse
943            // the existing cache epoch instead of invalidating the whole tree.
944            let measure_dirty = node.needs_measure();
945            let semantics_dirty = node.needs_semantics();
946            (measure_dirty, semantics_dirty, 0)
947        }
948        Err(err) => return Err(err),
949    };
950
951    let epoch = if needs_remeasure {
952        crate::render_state::next_layout_cache_epoch()
953    } else if cached_epoch != 0 {
954        cached_epoch
955    } else {
956        // Fallback when caller root isn't a LayoutNode (e.g. tests using Spacer directly).
957        crate::render_state::current_layout_cache_epoch()
958    };
959
960    // Move the current applier into a host and set up a guard that will
961    // ALWAYS restore:
962    // - the MemoryApplier back into `applier`
963    // - the SlotTable back into that MemoryApplier
964    //
965    // IMPORTANT: Declare the guard *before* the builder so the builder
966    // is dropped first (both on Ok and on unwind).
967    let guard = ApplierSlotGuard::new(applier);
968    let applier_host = guard.host();
969    let slots_handle = guard.slots_handle();
970    let after_guard = Instant::now();
971
972    // Give the builder the shared slots handle - both guard and builder
973    // now share access to the same SlotTable via Rc<RefCell<_>>.
974    let frame_arena = crate::render_state::take_layout_frame_arena();
975    let mut builder = LayoutBuilder::new_with_epoch(
976        Rc::clone(&applier_host),
977        epoch,
978        Rc::clone(&slots_handle),
979        frame_arena,
980    );
981    let after_builder = Instant::now();
982
983    // ---- Measurement -------------------------------------------------------
984    // If measurement fails, the guard will restore slots from the shared handle
985    // on drop - this is safe because the handle always contains valid slots.
986
987    let measured = builder.measure_node(root, normalize_constraints(constraints))?;
988    let after_measure = Instant::now();
989
990    // Root node has no parent to place it, so we must explicitly place it at (0,0).
991    // This ensures is_placed=true, allowing the renderer to traverse the tree.
992    // Handle both LayoutNode and SubcomposeLayoutNode as potential roots.
993    if let Ok(mut applier) = applier_host.try_borrow_typed() {
994        if applier
995            .with_node::<LayoutNode, _>(root, |node| {
996                node.set_position(Point::default());
997            })
998            .is_err()
999        {
1000            let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
1001                node.set_position(Point::default());
1002            });
1003        }
1004    }
1005    let after_root_place = Instant::now();
1006
1007    let (layout_tree, semantics) = {
1008        let mut applier_ref = applier_host.borrow_typed();
1009        let layout_tree = if options.build_layout_tree {
1010            Some(build_layout_tree(&mut applier_ref, &measured)?)
1011        } else {
1012            None
1013        };
1014        let semantics = if options.collect_semantics {
1015            let semantics_tree = if let Some(layout_tree) = layout_tree.as_ref() {
1016                clear_semantics_dirty_flags(&mut applier_ref, &measured)?;
1017                build_semantics_tree_from_layout_tree(layout_tree)
1018            } else {
1019                build_semantics_tree_from_live_nodes(&mut applier_ref, &measured)?
1020            };
1021            Some(semantics_tree)
1022        } else {
1023            None
1024        };
1025        (layout_tree, semantics)
1026    };
1027    let after_aux = Instant::now();
1028
1029    // Drop builder before guard - slots are already in the shared handle.
1030    // Guard's Drop will write them back to the applier.
1031    drop(builder);
1032    let after_builder_drop = Instant::now();
1033
1034    // DO NOT manually unwrap `applier_host` or replace `applier` here.
1035    // `ApplierSlotGuard::drop` will restore everything when this function returns.
1036    drop(guard);
1037    let after_guard_drop = Instant::now();
1038
1039    log_layout_measure_telemetry(LayoutMeasureTelemetry {
1040        root,
1041        start: telemetry_start,
1042        after_repasses,
1043        after_guard,
1044        after_builder,
1045        after_measure,
1046        after_root_place,
1047        after_aux,
1048        after_builder_drop,
1049        after_guard_drop,
1050    });
1051
1052    Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
1053}
1054
1055fn process_pending_layout_repasses(
1056    applier: &mut MemoryApplier,
1057    root: NodeId,
1058) -> Result<(), NodeError> {
1059    for node_id in crate::render_state::take_modifier_slice_repass_nodes() {
1060        if let Ok(node) = applier.get_mut(node_id) {
1061            let any = node.as_any_mut();
1062            if let Some(layout) = any.downcast_mut::<crate::widgets::nodes::LayoutNode>() {
1063                layout.mark_modifier_slices_dirty();
1064            } else if let Some(subcompose) =
1065                any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
1066            {
1067                subcompose.mark_modifier_slices_dirty();
1068            }
1069        }
1070    }
1071    let repass_nodes = crate::take_layout_repass_nodes();
1072    if repass_nodes.is_empty() {
1073        return Ok(());
1074    }
1075    for node_id in repass_nodes {
1076        cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
1077    }
1078    applier.get_mut(root)?.mark_needs_layout();
1079    Ok(())
1080}
1081
1082struct LayoutBuilder {
1083    state: Rc<RefCell<LayoutBuilderState>>,
1084}
1085
1086impl LayoutBuilder {
1087    fn new_with_epoch(
1088        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1089        epoch: u64,
1090        slots: Rc<RefCell<SlotTable>>,
1091        frame_arena: FrameLayoutArena,
1092    ) -> Self {
1093        Self {
1094            state: Rc::new(RefCell::new(LayoutBuilderState::new_with_epoch(
1095                applier,
1096                epoch,
1097                slots,
1098                frame_arena,
1099            ))),
1100        }
1101    }
1102
1103    fn measure_node(
1104        &mut self,
1105        node_id: NodeId,
1106        constraints: Constraints,
1107    ) -> Result<Rc<MeasuredNode>, NodeError> {
1108        LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
1109    }
1110
1111    fn set_runtime_handle(&mut self, handle: Option<RuntimeHandle>) {
1112        self.state.borrow_mut().runtime_handle = handle;
1113    }
1114}
1115
1116impl Drop for LayoutBuilder {
1117    fn drop(&mut self) {
1118        if Rc::strong_count(&self.state) != 1 {
1119            return;
1120        }
1121        let Ok(mut state) = self.state.try_borrow_mut() else {
1122            return;
1123        };
1124        crate::render_state::replace_layout_frame_arena(std::mem::take(&mut state.frame_arena));
1125    }
1126}
1127
1128struct LayoutBuilderState {
1129    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1130    runtime_handle: Option<RuntimeHandle>,
1131    /// Shared handle to the slot table. This is shared with ApplierSlotGuard
1132    /// to ensure panic-safety: even if we panic, the guard can restore slots.
1133    slots: Rc<RefCell<SlotTable>>,
1134    cache_epoch: u64,
1135    frame_arena: FrameLayoutArena,
1136}
1137
1138struct LayoutRuntimeFrameBindingCleanup {
1139    state: Rc<RefCell<LayoutRuntimeState>>,
1140}
1141
1142impl LayoutRuntimeFrameBindingCleanup {
1143    fn new(state: Rc<RefCell<LayoutRuntimeState>>) -> Self {
1144        Self { state }
1145    }
1146}
1147
1148impl Drop for LayoutRuntimeFrameBindingCleanup {
1149    fn drop(&mut self) {
1150        self.state.borrow().clear_frame_bindings();
1151    }
1152}
1153
1154impl LayoutBuilderState {
1155    fn new_with_epoch(
1156        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1157        epoch: u64,
1158        slots: Rc<RefCell<SlotTable>>,
1159        frame_arena: FrameLayoutArena,
1160    ) -> Self {
1161        let runtime_handle = applier.borrow_typed().runtime_handle();
1162
1163        Self {
1164            applier,
1165            runtime_handle,
1166            slots,
1167            cache_epoch: epoch,
1168            frame_arena,
1169        }
1170    }
1171
1172    fn try_with_applier_result<R>(
1173        state_rc: &Rc<RefCell<Self>>,
1174        f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
1175    ) -> Option<Result<R, NodeError>> {
1176        let host = {
1177            let state = state_rc.borrow();
1178            Rc::clone(&state.applier)
1179        };
1180
1181        // Try to borrow - if already borrowed (nested call), return None
1182        let Ok(mut applier) = host.try_borrow_typed() else {
1183            return None;
1184        };
1185
1186        Some(f(&mut applier))
1187    }
1188
1189    fn with_applier_result<R>(
1190        state_rc: &Rc<RefCell<Self>>,
1191        f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
1192    ) -> Result<R, NodeError> {
1193        Self::try_with_applier_result(state_rc, f).unwrap_or_else(|| {
1194            Err(NodeError::MissingContext {
1195                id: NodeId::default(),
1196                reason: "applier already borrowed",
1197            })
1198        })
1199    }
1200
1201    /// Clears the is_placed flag for a node at the start of measurement.
1202    /// This ensures nodes that drop out of placement won't render with stale geometry.
1203    fn clear_node_placed(state_rc: &Rc<RefCell<Self>>, node_id: NodeId) {
1204        let host = {
1205            let state = state_rc.borrow();
1206            Rc::clone(&state.applier)
1207        };
1208        let Ok(mut applier) = host.try_borrow_typed() else {
1209            return;
1210        };
1211        // Try LayoutNode first, then SubcomposeLayoutNode
1212        if applier
1213            .with_node::<LayoutNode, _>(node_id, |node| {
1214                node.clear_placed();
1215            })
1216            .is_err()
1217        {
1218            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1219                node.clear_placed();
1220            });
1221        }
1222    }
1223
1224    fn measure_node(
1225        state_rc: Rc<RefCell<Self>>,
1226        node_id: NodeId,
1227        constraints: Constraints,
1228    ) -> Result<Rc<MeasuredNode>, NodeError> {
1229        let telemetry_start = Instant::now();
1230        // Clear is_placed at the start of measurement.
1231        // Nodes that are placed will have is_placed set to true via Placeable::place().
1232        // Nodes that drop out of placement (not placed this pass) will remain is_placed=false.
1233        Self::clear_node_placed(&state_rc, node_id);
1234
1235        // Try SubcomposeLayoutNode first
1236        if let Some(subcompose) =
1237            Self::try_measure_subcompose(Rc::clone(&state_rc), node_id, constraints)?
1238        {
1239            log_node_measure_telemetry(
1240                "subcompose",
1241                node_id,
1242                constraints,
1243                subcompose.size,
1244                subcompose.children.len(),
1245                telemetry_start,
1246            );
1247            return Ok(subcompose);
1248        }
1249
1250        // Try LayoutNode (the primary modern path)
1251        if let Some(result) = Self::try_with_applier_result(&state_rc, |applier| {
1252            match applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1253                LayoutNodeSnapshot::from_layout_node(layout_node)
1254            }) {
1255                Ok(snapshot) => Ok(Some(snapshot)),
1256                Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => Ok(None),
1257                Err(err) => Err(err),
1258            }
1259        }) {
1260            // Applier was available, process the result
1261            if let Some(snapshot) = result? {
1262                let measured = Self::measure_layout_node(
1263                    Rc::clone(&state_rc),
1264                    node_id,
1265                    snapshot,
1266                    constraints,
1267                )?;
1268                log_node_measure_telemetry(
1269                    "layout",
1270                    node_id,
1271                    constraints,
1272                    measured.size,
1273                    measured.children.len(),
1274                    telemetry_start,
1275                );
1276                return Ok(measured);
1277            }
1278        }
1279        // If applier was busy (None) or snapshot was None, fall through to fallback
1280
1281        // No alternate fallbacks - all widgets use LayoutNode or SubcomposeLayoutNode
1282        // If we reach here, it's an unknown node type (shouldn't happen in normal use)
1283        let measured = Rc::new(MeasuredNode::new(
1284            node_id,
1285            Size::default(),
1286            Point { x: 0.0, y: 0.0 },
1287            Point::default(), // No content offset for fallback nodes
1288            Vec::new(),
1289        ));
1290        log_node_measure_telemetry(
1291            "fallback",
1292            node_id,
1293            constraints,
1294            measured.size,
1295            measured.children.len(),
1296            telemetry_start,
1297        );
1298        Ok(measured)
1299    }
1300
1301    fn cached_measure_node_with_applier(
1302        applier: &mut MemoryApplier,
1303        node_id: NodeId,
1304        constraints: Constraints,
1305    ) -> Result<Option<Rc<MeasuredNode>>, NodeError> {
1306        let Some(data) = Self::layout_child_measure_data(applier, node_id)? else {
1307            return Ok(None);
1308        };
1309        if data.needs_measure || data.cache.epoch() == 0 {
1310            return Ok(None);
1311        }
1312
1313        let Some(measured) = data.cache.get_measurement(constraints) else {
1314            return Ok(None);
1315        };
1316
1317        if let Some(layout_state) = data.layout_state {
1318            let mut layout_state = layout_state.borrow_mut();
1319            layout_state.size = measured.size;
1320            layout_state.measurement_constraints = constraints;
1321            drop(layout_state);
1322            let _ = applier.with_node::<LayoutNode, _>(node_id, |node| {
1323                if data.needs_layout {
1324                    node.clear_needs_layout();
1325                }
1326            });
1327        } else {
1328            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1329                node.set_measured_size(measured.size);
1330                if data.needs_layout {
1331                    node.clear_needs_layout();
1332                }
1333            });
1334        }
1335
1336        Ok(Some(measured))
1337    }
1338
1339    fn try_measure_subcompose(
1340        state_rc: Rc<RefCell<Self>>,
1341        node_id: NodeId,
1342        constraints: Constraints,
1343    ) -> Result<Option<Rc<MeasuredNode>>, NodeError> {
1344        let applier_host = {
1345            let state = state_rc.borrow();
1346            Rc::clone(&state.applier)
1347        };
1348
1349        let (node_handle, resolved_modifiers) = {
1350            // Try to borrow - if already borrowed (nested measurement), return None
1351            let Ok(mut applier) = applier_host.try_borrow_typed() else {
1352                return Ok(None);
1353            };
1354            let node = match applier.get_mut(node_id) {
1355                Ok(node) => node,
1356                Err(NodeError::Missing { .. }) => return Ok(None),
1357                Err(err) => return Err(err),
1358            };
1359            let any = node.as_any_mut();
1360            if let Some(subcompose) =
1361                any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
1362            {
1363                let handle = subcompose.handle();
1364                let resolved_modifiers = handle.resolved_modifiers();
1365                (handle, resolved_modifiers)
1366            } else {
1367                return Ok(None);
1368            }
1369        };
1370
1371        let runtime_handle = {
1372            let mut state = state_rc.borrow_mut();
1373            if state.runtime_handle.is_none() {
1374                // Try to borrow - if already borrowed, we can't get runtime handle
1375                if let Ok(applier) = applier_host.try_borrow_typed() {
1376                    state.runtime_handle = applier.runtime_handle();
1377                }
1378            }
1379            state
1380                .runtime_handle
1381                .clone()
1382                .ok_or(NodeError::MissingContext {
1383                    id: node_id,
1384                    reason: "runtime handle required for subcomposition",
1385                })?
1386        };
1387
1388        let props = resolved_modifiers.layout_properties();
1389        let padding = resolved_modifiers.padding();
1390        let offset = resolved_modifiers.offset();
1391        let mut inner_constraints = normalize_constraints(subtract_padding(constraints, padding));
1392
1393        if let DimensionConstraint::Points(width) = props.width() {
1394            let constrained_width = width - padding.horizontal_sum();
1395            inner_constraints.max_width = inner_constraints.max_width.min(constrained_width);
1396            inner_constraints.min_width = inner_constraints.min_width.min(constrained_width);
1397        }
1398        if let DimensionConstraint::Points(height) = props.height() {
1399            let constrained_height = height - padding.vertical_sum();
1400            inner_constraints.max_height = inner_constraints.max_height.min(constrained_height);
1401            inner_constraints.min_height = inner_constraints.min_height.min(constrained_height);
1402        }
1403
1404        let mut slots_guard = SlotsGuard::take(Rc::clone(&state_rc));
1405        let slots_host = slots_guard.host();
1406        let applier_host_dyn: Rc<dyn ApplierHost> = applier_host.clone();
1407        let observer = SnapshotStateObserver::new(|callback| callback());
1408        let composer = Composer::new(
1409            Rc::clone(&slots_host),
1410            applier_host_dyn,
1411            runtime_handle.clone(),
1412            observer,
1413            Some(node_id),
1414        );
1415        composer.enter_phase(Phase::Measure);
1416
1417        let state_rc_clone = Rc::clone(&state_rc);
1418        let measure_error = RefCell::new(None);
1419        let state_rc_for_subcompose = Rc::clone(&state_rc_clone);
1420        let error_for_subcompose = &measure_error;
1421        let measured_children = node_handle.measured_children_scratch();
1422        let measured_children_for_subcompose = Rc::clone(&measured_children);
1423        let state_rc_for_cached = Rc::clone(&state_rc_clone);
1424        let error_for_cached = &measure_error;
1425        let measured_children_for_cached = Rc::clone(&measured_children);
1426        let measured_children_for_lookup = Rc::clone(&measured_children);
1427        let measured_children_for_retained = Rc::clone(&measured_children);
1428
1429        let measure_result = node_handle.measure_with_cached_batch(
1430            &composer,
1431            node_id,
1432            inner_constraints,
1433            CachedBatchMeasureInputs {
1434                measurer: Box::new(
1435                    move |child_id: NodeId, child_constraints: Constraints| -> Size {
1436                        match Self::measure_node(
1437                            Rc::clone(&state_rc_for_subcompose),
1438                            child_id,
1439                            child_constraints,
1440                        ) {
1441                            Ok(measured) => {
1442                                measured_children_for_subcompose
1443                                    .borrow_mut()
1444                                    .insert(child_id, Rc::clone(&measured));
1445                                measured.size
1446                            }
1447                            Err(err) => {
1448                                let mut slot = error_for_subcompose.borrow_mut();
1449                                if slot.is_none() {
1450                                    *slot = Some(err);
1451                                }
1452                                Size::default()
1453                            }
1454                        }
1455                    },
1456                ),
1457                cached_measure_batch_registrar: Box::new(
1458                    move |child_ids: &[NodeId],
1459                          child_constraints: Constraints,
1460                          out: &mut Vec<Option<Size>>| {
1461                        out.clear();
1462                        out.resize(child_ids.len(), None);
1463
1464                        let applier_host = {
1465                            let state = state_rc_for_cached.borrow();
1466                            Rc::clone(&state.applier)
1467                        };
1468                        let Ok(mut applier) = applier_host.try_borrow_typed() else {
1469                            return;
1470                        };
1471
1472                        let mut measured_children = measured_children_for_cached.borrow_mut();
1473                        for (index, &child_id) in child_ids.iter().enumerate() {
1474                            match Self::cached_measure_node_with_applier(
1475                                &mut applier,
1476                                child_id,
1477                                child_constraints,
1478                            ) {
1479                                Ok(Some(measured)) => {
1480                                    out[index] = Some(measured.size);
1481                                    measured_children.insert(child_id, Rc::clone(&measured));
1482                                }
1483                                Ok(None) => {}
1484                                Err(err) => {
1485                                    let mut slot = error_for_cached.borrow_mut();
1486                                    if slot.is_none() {
1487                                        *slot = Some(err);
1488                                    }
1489                                    break;
1490                                }
1491                            }
1492                        }
1493                    },
1494                ),
1495                retained_measure_lookup: Box::new(move |child_id| {
1496                    measured_children_for_lookup
1497                        .borrow()
1498                        .get(&child_id)
1499                        .cloned()
1500                }),
1501                retained_measure_registrar: Box::new(move |measurements| {
1502                    let mut measured_children = measured_children_for_retained.borrow_mut();
1503                    for measured in measurements {
1504                        measured_children.insert(measured.node_id(), Rc::clone(measured));
1505                    }
1506                }),
1507                error: &measure_error,
1508            },
1509        )?;
1510        drop(composer);
1511        slots_guard.restore(slots_host.into_table()?);
1512
1513        if let Some(err) = measure_error.borrow_mut().take() {
1514            return Err(err);
1515        }
1516
1517        // NOTE: Children are now managed by the composer via insert_child commands
1518        // (from parent_stack initialization with root). set_active_children is no longer used.
1519
1520        let cranpose_ui_layout::MeasureResult {
1521            size: measured_size,
1522            placements,
1523        } = measure_result;
1524
1525        let mut width = measured_size.width + padding.horizontal_sum();
1526        let mut height = measured_size.height + padding.vertical_sum();
1527
1528        width = resolve_dimension(
1529            width,
1530            props.width(),
1531            props.min_width(),
1532            props.max_width(),
1533            constraints.min_width,
1534            constraints.max_width,
1535        );
1536        height = resolve_dimension(
1537            height,
1538            props.height(),
1539            props.min_height(),
1540            props.max_height(),
1541            constraints.min_height,
1542            constraints.max_height,
1543        );
1544
1545        let mut children = Vec::with_capacity(placements.len());
1546        let mut measured_children_by_id = measured_children.borrow_mut();
1547
1548        // Update the SubcomposeLayoutNode's size (position will be set by parent's placement)
1549        if let Ok(mut applier) = applier_host.try_borrow_typed() {
1550            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |parent_node| {
1551                parent_node.set_measured_size(Size { width, height });
1552                parent_node.clear_needs_measure();
1553                parent_node.clear_needs_layout();
1554            });
1555        }
1556
1557        for placement in &placements {
1558            let child = if let Some(measured) = measured_children_by_id.remove(&placement.node_id) {
1559                measured
1560            } else {
1561                // Policies may place subcomposed children without calling `measure()` first
1562                // (for example, when they only need a slot's rendered content). Keep the
1563                // existing fallback for that case, but preserve the policy-time measurement
1564                // whenever it exists so we don't silently remeasure lazy items with the
1565                // container's tighter constraints.
1566                Self::measure_node(Rc::clone(&state_rc), placement.node_id, inner_constraints)?
1567            };
1568            let position = Point {
1569                x: padding.left + placement.x,
1570                y: padding.top + placement.y,
1571            };
1572
1573            // Critical: Update the child's retained placement state.
1574            // Standard layouts do this via Placeable::place(), but SubcomposeLayout
1575            // logic bypasses Placeables and returns raw Placements. A subcomposed
1576            // child can itself be a SubcomposeLayout (e.g. a `BoxWithConstraints`
1577            // inside a `LazyColumn` item), so both node kinds must be positioned
1578            // and marked placed; otherwise the applier-traversal render, layout,
1579            // and semantics builds cull the child's whole subtree (issue #305).
1580            if let Ok(mut applier) = applier_host.try_borrow_typed() {
1581                if applier
1582                    .with_node::<LayoutNode, _>(placement.node_id, |node| {
1583                        node.set_position(position);
1584                    })
1585                    .is_err()
1586                {
1587                    let _ =
1588                        applier.with_node::<SubcomposeLayoutNode, _>(placement.node_id, |node| {
1589                            node.set_position(position);
1590                        });
1591                }
1592            }
1593
1594            children.push(MeasuredChild {
1595                node: child,
1596                offset: position,
1597            });
1598        }
1599
1600        // Update the SubcomposeLayoutNode's active children for rendering
1601        node_handle.set_active_children(children.iter().map(|c| c.node.node_id));
1602        node_handle.recycle_placement_scratch(placements);
1603
1604        Ok(Some(Rc::new(MeasuredNode::new(
1605            node_id,
1606            Size { width, height },
1607            offset,
1608            Point::default(), // Subcompose nodes: content_offset handled by child layout
1609            children,
1610        ))))
1611    }
1612    /// Measures through the layout modifier coordinator chain using reconciled modifier nodes.
1613    /// Iterates through LayoutModifierNode instances from the ModifierNodeChain and calls
1614    /// their measure() methods through the retained coordinator chain.
1615    ///
1616    /// Always succeeds, measuring either directly or through retained layout modifier nodes.
1617    ///
1618    fn measure_through_modifier_chain(
1619        state_rc: &Rc<RefCell<Self>>,
1620        node_id: NodeId,
1621        runtime_state: &mut LayoutRuntimeState,
1622        measure_policy: &Rc<dyn MeasurePolicy>,
1623        constraints: Constraints,
1624        layout_node_data: &mut Vec<LayoutModifierNodeData>,
1625        placements: &mut Vec<Placement>,
1626    ) -> ModifierChainMeasurement {
1627        use cranpose_foundation::NodeCapabilities;
1628
1629        // Collect layout node information from the modifier chain
1630        layout_node_data.clear();
1631        let mut offset = Point::default();
1632
1633        {
1634            let state = state_rc.borrow();
1635            let mut applier = state.applier.borrow_typed();
1636
1637            let _ = applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1638                let chain_handle = layout_node.modifier_chain();
1639
1640                if !chain_handle.has_layout_nodes() {
1641                    return;
1642                }
1643
1644                // Collect indices and node Rc clones for layout modifier nodes
1645                chain_handle.chain().for_each_forward_matching(
1646                    NodeCapabilities::LAYOUT,
1647                    |node_ref| {
1648                        if let Some(index) = node_ref.entry_index() {
1649                            // Get the Rc clone for this node
1650                            if let Some(node_rc) = chain_handle.chain().get_node_rc(index) {
1651                                layout_node_data.push((index, Rc::clone(&node_rc)));
1652                            }
1653
1654                            // Extract offset from OffsetNode for the node's own position
1655                            // The coordinator chain handles placement_offset (for children),
1656                            // but the node's offset affects where IT is positioned in the parent
1657                            node_ref.with_node(|node| {
1658                                if let Some(offset_node) =
1659                                    node.as_any()
1660                                        .downcast_ref::<crate::modifier_nodes::OffsetNode>()
1661                                {
1662                                    let delta = offset_node.offset();
1663                                    offset.x += delta.x;
1664                                    offset.y += delta.y;
1665                                }
1666                            });
1667                        }
1668                    },
1669                );
1670            });
1671        }
1672
1673        // Fast path: if there are no layout modifiers, measure directly without the
1674        // retained coordinator chain frame.
1675        if layout_node_data.is_empty() {
1676            let final_size = measure_policy.measure_into(
1677                runtime_state.child_measurables(),
1678                constraints,
1679                placements,
1680            );
1681
1682            return ModifierChainMeasurement {
1683                size: final_size,
1684                content_offset: Point::default(),
1685                offset,
1686            };
1687        }
1688
1689        runtime_state.reconcile_coordinator_chain(layout_node_data.as_slice());
1690        let frame = CoordinatorFrame::new(
1691            measure_policy,
1692            runtime_state.child_measurables(),
1693            placements,
1694        );
1695
1696        // Measure through the complete coordinator chain
1697        let placeable = runtime_state
1698            .coordinator_chain()
1699            .measure_from(0, &frame, constraints);
1700        let final_size = Size {
1701            width: placeable.width(),
1702            height: placeable.height(),
1703        };
1704
1705        // Get accumulated content offset from the placeable (computed during measure)
1706        let content_offset = placeable.content_offset();
1707        let all_placement_offset = Point {
1708            x: content_offset.0,
1709            y: content_offset.1,
1710        };
1711
1712        // The content_offset for scroll/inner transforms is the accumulated placement offset
1713        // MINUS the node's own offset (which affects its position in the parent, not content position).
1714        // This properly separates: node position (offset) vs inner content position (content_offset).
1715        let content_offset = Point {
1716            x: all_placement_offset.x - offset.x,
1717            y: all_placement_offset.y - offset.y,
1718        };
1719
1720        // offset was already extracted from OffsetNode above
1721
1722        // Process any invalidations requested during measurement
1723        let invalidations = frame.take_invalidations();
1724        if !invalidations.is_empty() {
1725            // Mark the LayoutNode as needing the appropriate passes
1726            Self::with_applier_result(state_rc, |applier| {
1727                applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1728                    for kind in invalidations {
1729                        match kind {
1730                            InvalidationKind::Layout => layout_node.mark_needs_measure(),
1731                            InvalidationKind::Draw => layout_node.mark_needs_redraw(),
1732                            InvalidationKind::Semantics => layout_node.mark_needs_semantics(),
1733                            InvalidationKind::PointerInput => layout_node.mark_needs_pointer_pass(),
1734                            InvalidationKind::Focus => layout_node.mark_needs_focus_sync(),
1735                        }
1736                    }
1737                })
1738            })
1739            .ok();
1740        }
1741
1742        ModifierChainMeasurement {
1743            size: final_size,
1744            content_offset,
1745            offset,
1746        }
1747    }
1748
1749    fn layout_child_measure_data(
1750        applier: &mut MemoryApplier,
1751        child_id: NodeId,
1752    ) -> Result<Option<LayoutChildMeasureData>, NodeError> {
1753        match applier.with_node::<LayoutNode, _>(child_id, |n| LayoutChildMeasureData {
1754            cache: n.cache_handles(),
1755            layout_state: Some(n.layout_state_handle()),
1756            needs_layout: n.needs_layout(),
1757            needs_measure: n.needs_measure(),
1758        }) {
1759            Ok(data) => Ok(Some(data)),
1760            Err(NodeError::TypeMismatch { .. }) => {
1761                match applier.with_node::<SubcomposeLayoutNode, _>(child_id, |n| {
1762                    LayoutChildMeasureData {
1763                        cache: n.cache_handles(),
1764                        layout_state: None,
1765                        needs_layout: n.needs_layout(),
1766                        needs_measure: n.needs_measure(),
1767                    }
1768                }) {
1769                    Ok(data) => Ok(Some(data)),
1770                    Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
1771                        Ok(None)
1772                    }
1773                    Err(err) => Err(err),
1774                }
1775            }
1776            Err(NodeError::Missing { .. }) => Ok(None),
1777            Err(err) => Err(err),
1778        }
1779    }
1780
1781    fn measure_layout_node(
1782        state_rc: Rc<RefCell<Self>>,
1783        node_id: NodeId,
1784        snapshot: LayoutNodeSnapshot,
1785        constraints: Constraints,
1786    ) -> Result<Rc<MeasuredNode>, NodeError> {
1787        let cache_epoch = {
1788            let state = state_rc.borrow();
1789            state.cache_epoch
1790        };
1791        let LayoutNodeSnapshot {
1792            measure_policy,
1793            cache,
1794            layout_runtime_state,
1795            needs_layout,
1796            needs_measure,
1797        } = snapshot;
1798        cache.activate(cache_epoch);
1799
1800        if needs_measure {
1801            // Node has needs_measure=true
1802        }
1803
1804        // Only check cache when the node is fully clean.
1805        // needs_layout=true means either the node itself or one of its descendants
1806        // must be revisited even if the node's own measured size can stay cached.
1807        if !needs_measure && !needs_layout {
1808            // Check cache for current constraints
1809            if let Some(cached) = cache.get_measurement(constraints) {
1810                // Clear dirty flag after successful cache hit
1811                Self::with_applier_result(&state_rc, |applier| {
1812                    applier.with_node::<LayoutNode, _>(node_id, |node| {
1813                        node.clear_needs_measure();
1814                        node.clear_needs_layout();
1815                    })
1816                })
1817                .ok();
1818                return Ok(cached);
1819            }
1820        }
1821
1822        let (runtime_handle, applier_host) = {
1823            let state = state_rc.borrow();
1824            (state.runtime_handle.clone(), Rc::clone(&state.applier))
1825        };
1826
1827        let measure_handle = LayoutMeasureHandle::new(Rc::clone(&state_rc));
1828        let error = Rc::new(RefCell::new(None));
1829        let mut pools = VecPools::acquire(Rc::clone(&state_rc));
1830        let (records, child_ids, layout_node_data, placements) = pools.parts();
1831
1832        applier_host
1833            .borrow_typed()
1834            .with_node::<LayoutNode, _>(node_id, |node| {
1835                child_ids.extend_from_slice(&node.children);
1836            })?;
1837
1838        let mut valid_child_count = 0;
1839        for index in 0..child_ids.len() {
1840            let child_id = child_ids[index];
1841            let child_exists = {
1842                let mut applier = applier_host.borrow_typed();
1843                Self::layout_child_measure_data(&mut applier, child_id)?.is_some()
1844            };
1845            if child_exists {
1846                child_ids[valid_child_count] = child_id;
1847                valid_child_count += 1;
1848            }
1849        }
1850        child_ids.truncate(valid_child_count);
1851
1852        let _frame_binding_cleanup =
1853            LayoutRuntimeFrameBindingCleanup::new(Rc::clone(&layout_runtime_state));
1854
1855        {
1856            let mut runtime_state = layout_runtime_state.borrow_mut();
1857            runtime_state.reconcile_child_measurables(child_ids.as_slice());
1858
1859            for (index, &child_id) in child_ids.iter().enumerate() {
1860                let data = {
1861                    let mut applier = applier_host.borrow_typed();
1862                    Self::layout_child_measure_data(&mut applier, child_id)?
1863                };
1864                let Some(data) = data else {
1865                    continue;
1866                };
1867
1868                let child_is_dirty = data.needs_layout || data.needs_measure;
1869                let child_cache_epoch = if child_is_dirty {
1870                    cache_epoch
1871                } else {
1872                    data.cache.epoch()
1873                };
1874                let child_state = runtime_state.child_state(index);
1875                child_state.configure(LayoutChildMeasureConfig {
1876                    applier: Rc::clone(&applier_host),
1877                    node_id: child_id,
1878                    error: Rc::clone(&error),
1879                    runtime_handle: runtime_handle.clone(),
1880                    cache: data.cache,
1881                    cache_epoch: child_cache_epoch,
1882                    force_remeasure: child_is_dirty,
1883                    measure_handle: Some(measure_handle.clone()),
1884                    layout_state: data.layout_state,
1885                });
1886                records.push((child_id, ChildRecord { state: child_state }));
1887            }
1888        }
1889
1890        let chain_constraints = constraints;
1891
1892        let modifier_chain_result = {
1893            let mut runtime_state = layout_runtime_state.borrow_mut();
1894            Self::measure_through_modifier_chain(
1895                &state_rc,
1896                node_id,
1897                &mut runtime_state,
1898                &measure_policy,
1899                chain_constraints,
1900                layout_node_data,
1901                placements,
1902            )
1903        };
1904
1905        // Modifier chain always succeeds - use the node-driven measurement.
1906        let (width, height, content_offset, offset) = {
1907            let result = modifier_chain_result;
1908            // The size is already correct from the modifier chain (modifiers like SizeNode
1909            // have already enforced their constraints), so we use it directly.
1910            if let Some(err) = error.borrow_mut().take() {
1911                return Err(err);
1912            }
1913
1914            (
1915                result.size.width,
1916                result.size.height,
1917                result.content_offset,
1918                result.offset,
1919            )
1920        };
1921
1922        let mut measured_children = Vec::with_capacity(records.len());
1923        for (child_id, record) in records.iter() {
1924            if let Some(measured) = record.state.take_measured() {
1925                let base_position = placements
1926                    .iter()
1927                    .find(|placement| placement.node_id == *child_id)
1928                    .map(|placement| Point {
1929                        x: placement.x,
1930                        y: placement.y,
1931                    })
1932                    .or_else(|| record.state.last_position())
1933                    .unwrap_or(Point { x: 0.0, y: 0.0 });
1934                // Apply content_offset (from scroll/transforms) to child positioning
1935                let position = Point {
1936                    x: content_offset.x + base_position.x,
1937                    y: content_offset.y + base_position.y,
1938                };
1939                measured_children.push(MeasuredChild {
1940                    node: measured,
1941                    offset: position,
1942                });
1943            }
1944        }
1945
1946        let measured = Rc::new(MeasuredNode::new(
1947            node_id,
1948            Size { width, height },
1949            offset,
1950            content_offset,
1951            measured_children,
1952        ));
1953
1954        cache.store_measurement(constraints, Rc::clone(&measured));
1955
1956        // Clear dirty flags and update derived state
1957        Self::with_applier_result(&state_rc, |applier| {
1958            applier.with_node::<LayoutNode, _>(node_id, |node| {
1959                node.clear_needs_measure();
1960                node.clear_needs_layout();
1961                node.set_measured_size(Size { width, height });
1962                node.set_content_offset(content_offset);
1963            })
1964        })
1965        .ok();
1966
1967        Ok(measured)
1968    }
1969}
1970
1971struct LayoutChildMeasureData {
1972    cache: LayoutNodeCacheHandles,
1973    layout_state: Option<Rc<RefCell<LayoutState>>>,
1974    needs_layout: bool,
1975    needs_measure: bool,
1976}
1977
1978/// Snapshot of a LayoutNode's data for measuring.
1979/// This is a temporary copy used during the measure phase, not a live node.
1980///
1981/// Note: We capture `needs_measure` here because it's checked during measure to enable
1982/// selective measure optimization at the individual node level. Even if the tree is partially
1983/// dirty (some nodes changed), clean nodes can skip measure and use cached results.
1984struct LayoutNodeSnapshot {
1985    measure_policy: Rc<dyn MeasurePolicy>,
1986    cache: LayoutNodeCacheHandles,
1987    layout_runtime_state: Rc<RefCell<LayoutRuntimeState>>,
1988    needs_layout: bool,
1989    /// Whether this specific node needs to be measured (vs using cached measurement)
1990    needs_measure: bool,
1991}
1992
1993impl LayoutNodeSnapshot {
1994    fn from_layout_node(node: &LayoutNode) -> Self {
1995        Self {
1996            measure_policy: Rc::clone(&node.measure_policy),
1997            cache: node.cache_handles(),
1998            layout_runtime_state: node.layout_runtime_state_handle(),
1999            needs_layout: node.needs_layout(),
2000            needs_measure: node.needs_measure(),
2001        }
2002    }
2003}
2004
2005// Helper types for accessing subsets of LayoutBuilderState
2006struct VecPools {
2007    state: Rc<RefCell<LayoutBuilderState>>,
2008    records: Vec<(NodeId, ChildRecord)>,
2009    child_ids: Vec<NodeId>,
2010    layout_node_data: Vec<LayoutModifierNodeData>,
2011    placements: Vec<Placement>,
2012}
2013
2014impl VecPools {
2015    fn acquire(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
2016        let (records, child_ids, layout_node_data, placements) = {
2017            let mut state_mut = state.borrow_mut();
2018            (
2019                state_mut.frame_arena.tmp_records.acquire(),
2020                state_mut.frame_arena.tmp_child_ids.acquire(),
2021                state_mut.frame_arena.tmp_layout_node_data.acquire(),
2022                state_mut.frame_arena.tmp_placements.acquire(),
2023            )
2024        };
2025        Self {
2026            state,
2027            records,
2028            child_ids,
2029            layout_node_data,
2030            placements,
2031        }
2032    }
2033
2034    #[allow(clippy::type_complexity)] // Returns internal Vec references for layout operations
2035    fn parts(
2036        &mut self,
2037    ) -> (
2038        &mut Vec<(NodeId, ChildRecord)>,
2039        &mut Vec<NodeId>,
2040        &mut Vec<LayoutModifierNodeData>,
2041        &mut Vec<Placement>,
2042    ) {
2043        (
2044            &mut self.records,
2045            &mut self.child_ids,
2046            &mut self.layout_node_data,
2047            &mut self.placements,
2048        )
2049    }
2050}
2051
2052impl Drop for VecPools {
2053    fn drop(&mut self) {
2054        let mut state = self.state.borrow_mut();
2055        state
2056            .frame_arena
2057            .tmp_records
2058            .release(std::mem::take(&mut self.records));
2059        state
2060            .frame_arena
2061            .tmp_child_ids
2062            .release(std::mem::take(&mut self.child_ids));
2063        state
2064            .frame_arena
2065            .tmp_layout_node_data
2066            .release(std::mem::take(&mut self.layout_node_data));
2067        state
2068            .frame_arena
2069            .tmp_placements
2070            .release(std::mem::take(&mut self.placements));
2071    }
2072}
2073
2074struct SlotsGuard {
2075    state: Rc<RefCell<LayoutBuilderState>>,
2076    slots: Option<SlotTable>,
2077}
2078
2079impl SlotsGuard {
2080    fn take(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
2081        let slots = {
2082            let state_ref = state.borrow();
2083            let mut slots_ref = state_ref.slots.borrow_mut();
2084            std::mem::take(&mut *slots_ref)
2085        };
2086        Self {
2087            state,
2088            slots: Some(slots),
2089        }
2090    }
2091
2092    fn host(&mut self) -> Rc<SlotsHost> {
2093        let slots = self.slots.take().unwrap_or_default();
2094        Rc::new(SlotsHost::new(slots))
2095    }
2096
2097    fn restore(&mut self, slots: SlotTable) {
2098        debug_assert!(self.slots.is_none());
2099        self.slots = Some(slots);
2100    }
2101}
2102
2103impl Drop for SlotsGuard {
2104    fn drop(&mut self) {
2105        if let Some(slots) = self.slots.take() {
2106            let state_ref = self.state.borrow();
2107            *state_ref.slots.borrow_mut() = slots;
2108        }
2109    }
2110}
2111
2112#[derive(Clone)]
2113struct LayoutMeasureHandle {
2114    state: Rc<RefCell<LayoutBuilderState>>,
2115}
2116
2117impl LayoutMeasureHandle {
2118    fn new(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
2119        Self { state }
2120    }
2121
2122    fn measure(
2123        &self,
2124        node_id: NodeId,
2125        constraints: Constraints,
2126    ) -> Result<Rc<MeasuredNode>, NodeError> {
2127        LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
2128    }
2129}
2130
2131#[derive(Debug, Clone)]
2132pub(crate) struct MeasuredNode {
2133    node_id: NodeId,
2134    size: Size,
2135    /// Node's position offset relative to parent (from OffsetNode etc.)
2136    offset: Point,
2137    /// Content offset for scroll/inner transforms (NOT node position)
2138    content_offset: Point,
2139    children: Vec<MeasuredChild>,
2140}
2141
2142impl MeasuredNode {
2143    fn new(
2144        node_id: NodeId,
2145        size: Size,
2146        offset: Point,
2147        content_offset: Point,
2148        children: Vec<MeasuredChild>,
2149    ) -> Self {
2150        Self {
2151            node_id,
2152            size,
2153            offset,
2154            content_offset,
2155            children,
2156        }
2157    }
2158
2159    #[cfg(test)]
2160    pub(crate) fn leaf(node_id: NodeId, size: Size) -> Self {
2161        Self::new(
2162            node_id,
2163            size,
2164            Point::default(),
2165            Point::default(),
2166            Vec::new(),
2167        )
2168    }
2169
2170    pub(crate) fn node_id(&self) -> NodeId {
2171        self.node_id
2172    }
2173
2174    pub(crate) fn size(&self) -> Size {
2175        self.size
2176    }
2177}
2178
2179#[derive(Debug, Clone)]
2180struct MeasuredChild {
2181    node: Rc<MeasuredNode>,
2182    offset: Point,
2183}
2184
2185struct ChildRecord {
2186    state: Rc<LayoutChildMeasureState>,
2187}
2188
2189struct CoordinatorFrame<'a> {
2190    measure_policy: &'a Rc<dyn MeasurePolicy>,
2191    measurables: &'a [Box<dyn Measurable>],
2192    placements: RefCell<&'a mut Vec<Placement>>,
2193    context: RefCell<LayoutNodeContext>,
2194}
2195
2196impl<'a> CoordinatorFrame<'a> {
2197    fn new(
2198        measure_policy: &'a Rc<dyn MeasurePolicy>,
2199        measurables: &'a [Box<dyn Measurable>],
2200        placements: &'a mut Vec<Placement>,
2201    ) -> Self {
2202        Self {
2203            measure_policy,
2204            measurables,
2205            placements: RefCell::new(placements),
2206            context: RefCell::new(LayoutNodeContext::new()),
2207        }
2208    }
2209
2210    fn take_invalidations(&self) -> Vec<InvalidationKind> {
2211        self.context.borrow_mut().take_invalidations()
2212    }
2213}
2214
2215struct CoordinatorLink<'chain, 'frame_ref, 'frame_data> {
2216    chain: &'chain CoordinatorChain,
2217    frame: &'frame_ref CoordinatorFrame<'frame_data>,
2218    index: usize,
2219}
2220
2221impl Measurable for CoordinatorLink<'_, '_, '_> {
2222    fn measure(&self, constraints: Constraints) -> Placeable {
2223        self.chain.measure_from(self.index, self.frame, constraints)
2224    }
2225
2226    fn min_intrinsic_width(&self, height: f32) -> f32 {
2227        self.chain
2228            .min_intrinsic_width_from(self.index, self.frame, height)
2229    }
2230
2231    fn max_intrinsic_width(&self, height: f32) -> f32 {
2232        self.chain
2233            .max_intrinsic_width_from(self.index, self.frame, height)
2234    }
2235
2236    fn min_intrinsic_height(&self, width: f32) -> f32 {
2237        self.chain
2238            .min_intrinsic_height_from(self.index, self.frame, width)
2239    }
2240
2241    fn max_intrinsic_height(&self, width: f32) -> f32 {
2242        self.chain
2243            .max_intrinsic_height_from(self.index, self.frame, width)
2244    }
2245}
2246
2247struct CoordinatorNode {
2248    modifier_index: usize,
2249    node: Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
2250    measured_size: Cell<Size>,
2251    accumulated_offset: Cell<Point>,
2252}
2253
2254impl CoordinatorNode {
2255    fn new(
2256        modifier_index: usize,
2257        node: Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
2258    ) -> Self {
2259        Self {
2260            modifier_index,
2261            node,
2262            measured_size: Cell::new(Size::default()),
2263            accumulated_offset: Cell::new(Point::default()),
2264        }
2265    }
2266
2267    fn matches(
2268        &self,
2269        modifier_index: usize,
2270        node: &Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
2271    ) -> bool {
2272        self.modifier_index == modifier_index && Rc::ptr_eq(&self.node, node)
2273    }
2274
2275    #[cfg(test)]
2276    fn ptr(&self) -> usize {
2277        Rc::as_ptr(&self.node) as *const () as usize
2278    }
2279}
2280
2281#[derive(Default)]
2282struct CoordinatorChain {
2283    nodes: Vec<CoordinatorNode>,
2284}
2285
2286impl CoordinatorChain {
2287    fn reconcile(&mut self, layout_node_data: &[LayoutModifierNodeData]) {
2288        if self.matches(layout_node_data) {
2289            return;
2290        }
2291
2292        let mut previous_nodes = std::mem::take(&mut self.nodes);
2293        self.nodes.reserve(layout_node_data.len());
2294
2295        for (modifier_index, node) in layout_node_data.iter() {
2296            if let Some(position) = previous_nodes
2297                .iter()
2298                .position(|candidate| candidate.matches(*modifier_index, node))
2299            {
2300                self.nodes.push(previous_nodes.swap_remove(position));
2301            } else {
2302                self.nodes
2303                    .push(CoordinatorNode::new(*modifier_index, Rc::clone(node)));
2304            }
2305        }
2306    }
2307
2308    fn matches(&self, layout_node_data: &[LayoutModifierNodeData]) -> bool {
2309        self.nodes.len() == layout_node_data.len()
2310            && self
2311                .nodes
2312                .iter()
2313                .zip(layout_node_data.iter())
2314                .all(|(node, (modifier_index, node_rc))| node.matches(*modifier_index, node_rc))
2315    }
2316
2317    fn measure_from(
2318        &self,
2319        index: usize,
2320        frame: &CoordinatorFrame<'_>,
2321        constraints: Constraints,
2322    ) -> Placeable {
2323        let Some(node) = self.nodes.get(index) else {
2324            let mut placements = frame.placements.borrow_mut();
2325            let size =
2326                frame
2327                    .measure_policy
2328                    .measure_into(frame.measurables, constraints, &mut placements);
2329            return Placeable::value(size.width, size.height, NodeId::default());
2330        };
2331
2332        let wrapped = CoordinatorLink {
2333            chain: self,
2334            frame,
2335            index: index + 1,
2336        };
2337        let node_borrow = node.node.borrow();
2338
2339        let Some(layout_node) = node_borrow.as_layout_node() else {
2340            let placeable = wrapped.measure(constraints);
2341            let child_accumulated = self.total_content_offset_from(index + 1);
2342            node.accumulated_offset.set(child_accumulated);
2343            return Placeable::value_with_offset(
2344                placeable.width(),
2345                placeable.height(),
2346                NodeId::default(),
2347                (child_accumulated.x, child_accumulated.y),
2348            );
2349        };
2350
2351        let result = match frame.context.try_borrow_mut() {
2352            Ok(mut context) => layout_node.measure(&mut *context, &wrapped, constraints),
2353            Err(_) => {
2354                let mut temp = LayoutNodeContext::new();
2355                let result = layout_node.measure(&mut temp, &wrapped, constraints);
2356                if let Ok(mut context) = frame.context.try_borrow_mut() {
2357                    for kind in temp.take_invalidations() {
2358                        context.invalidate(kind);
2359                    }
2360                }
2361                result
2362            }
2363        };
2364
2365        node.measured_size.set(result.size);
2366        let local_offset = Point {
2367            x: result.placement_offset_x,
2368            y: result.placement_offset_y,
2369        };
2370        let child_accumulated = self.total_content_offset_from(index + 1);
2371        let accumulated = Point {
2372            x: local_offset.x + child_accumulated.x,
2373            y: local_offset.y + child_accumulated.y,
2374        };
2375        node.accumulated_offset.set(accumulated);
2376
2377        Placeable::value_with_offset(
2378            result.size.width,
2379            result.size.height,
2380            NodeId::default(),
2381            (accumulated.x, accumulated.y),
2382        )
2383    }
2384
2385    fn min_intrinsic_width_from(
2386        &self,
2387        index: usize,
2388        frame: &CoordinatorFrame<'_>,
2389        height: f32,
2390    ) -> f32 {
2391        let Some(node) = self.nodes.get(index) else {
2392            return frame
2393                .measure_policy
2394                .min_intrinsic_width(frame.measurables, height);
2395        };
2396        let wrapped = CoordinatorLink {
2397            chain: self,
2398            frame,
2399            index: index + 1,
2400        };
2401        let node_borrow = node.node.borrow();
2402        node_borrow
2403            .as_layout_node()
2404            .map(|layout_node| layout_node.min_intrinsic_width(&wrapped, height))
2405            .unwrap_or_else(|| wrapped.min_intrinsic_width(height))
2406    }
2407
2408    fn max_intrinsic_width_from(
2409        &self,
2410        index: usize,
2411        frame: &CoordinatorFrame<'_>,
2412        height: f32,
2413    ) -> f32 {
2414        let Some(node) = self.nodes.get(index) else {
2415            return frame
2416                .measure_policy
2417                .max_intrinsic_width(frame.measurables, height);
2418        };
2419        let wrapped = CoordinatorLink {
2420            chain: self,
2421            frame,
2422            index: index + 1,
2423        };
2424        let node_borrow = node.node.borrow();
2425        node_borrow
2426            .as_layout_node()
2427            .map(|layout_node| layout_node.max_intrinsic_width(&wrapped, height))
2428            .unwrap_or_else(|| wrapped.max_intrinsic_width(height))
2429    }
2430
2431    fn min_intrinsic_height_from(
2432        &self,
2433        index: usize,
2434        frame: &CoordinatorFrame<'_>,
2435        width: f32,
2436    ) -> f32 {
2437        let Some(node) = self.nodes.get(index) else {
2438            return frame
2439                .measure_policy
2440                .min_intrinsic_height(frame.measurables, width);
2441        };
2442        let wrapped = CoordinatorLink {
2443            chain: self,
2444            frame,
2445            index: index + 1,
2446        };
2447        let node_borrow = node.node.borrow();
2448        node_borrow
2449            .as_layout_node()
2450            .map(|layout_node| layout_node.min_intrinsic_height(&wrapped, width))
2451            .unwrap_or_else(|| wrapped.min_intrinsic_height(width))
2452    }
2453
2454    fn max_intrinsic_height_from(
2455        &self,
2456        index: usize,
2457        frame: &CoordinatorFrame<'_>,
2458        width: f32,
2459    ) -> f32 {
2460        let Some(node) = self.nodes.get(index) else {
2461            return frame
2462                .measure_policy
2463                .max_intrinsic_height(frame.measurables, width);
2464        };
2465        let wrapped = CoordinatorLink {
2466            chain: self,
2467            frame,
2468            index: index + 1,
2469        };
2470        let node_borrow = node.node.borrow();
2471        node_borrow
2472            .as_layout_node()
2473            .map(|layout_node| layout_node.max_intrinsic_height(&wrapped, width))
2474            .unwrap_or_else(|| wrapped.max_intrinsic_height(width))
2475    }
2476
2477    fn total_content_offset_from(&self, index: usize) -> Point {
2478        self.nodes
2479            .get(index)
2480            .map(|node| node.accumulated_offset.get())
2481            .unwrap_or_default()
2482    }
2483
2484    #[cfg(test)]
2485    fn debug_ptrs(&self) -> Vec<usize> {
2486        self.nodes.iter().map(CoordinatorNode::ptr).collect()
2487    }
2488}
2489
2490#[derive(Default)]
2491pub(crate) struct LayoutRuntimeState {
2492    child_ids: Vec<NodeId>,
2493    child_states: Vec<Rc<LayoutChildMeasureState>>,
2494    child_measurables: Vec<Box<dyn Measurable>>,
2495    coordinator_chain: CoordinatorChain,
2496}
2497
2498impl LayoutRuntimeState {
2499    fn reconcile_child_measurables(&mut self, child_ids: &[NodeId]) {
2500        if self.child_ids == child_ids {
2501            return;
2502        }
2503
2504        let mut previous_ids = std::mem::take(&mut self.child_ids);
2505        let mut previous_states = std::mem::take(&mut self.child_states);
2506        let mut previous_measurables = std::mem::take(&mut self.child_measurables);
2507
2508        self.child_ids.reserve(child_ids.len());
2509        self.child_states.reserve(child_ids.len());
2510        self.child_measurables.reserve(child_ids.len());
2511
2512        for &child_id in child_ids {
2513            if let Some(position) = previous_ids.iter().position(|&id| id == child_id) {
2514                self.child_ids.push(previous_ids.swap_remove(position));
2515                self.child_states
2516                    .push(previous_states.swap_remove(position));
2517                self.child_measurables
2518                    .push(previous_measurables.swap_remove(position));
2519            } else {
2520                let state = LayoutChildMeasureState::new(child_id);
2521                self.child_ids.push(child_id);
2522                self.child_states.push(Rc::clone(&state));
2523                self.child_measurables
2524                    .push(Box::new(LayoutChildMeasurable::new(state)));
2525            }
2526        }
2527    }
2528
2529    fn child_state(&self, index: usize) -> Rc<LayoutChildMeasureState> {
2530        Rc::clone(&self.child_states[index])
2531    }
2532
2533    fn child_measurables(&self) -> &[Box<dyn Measurable>] {
2534        self.child_measurables.as_slice()
2535    }
2536
2537    fn reconcile_coordinator_chain(&mut self, layout_node_data: &[LayoutModifierNodeData]) {
2538        self.coordinator_chain.reconcile(layout_node_data);
2539    }
2540
2541    fn coordinator_chain(&self) -> &CoordinatorChain {
2542        &self.coordinator_chain
2543    }
2544
2545    fn clear_frame_bindings(&self) {
2546        for child_state in &self.child_states {
2547            child_state.clear_frame_bindings();
2548        }
2549    }
2550
2551    #[cfg(test)]
2552    pub(crate) fn debug_stats(&self) -> LayoutRuntimeDebugStats {
2553        LayoutRuntimeDebugStats {
2554            child_ids: self.child_ids.clone(),
2555            child_state_ptrs: self
2556                .child_states
2557                .iter()
2558                .map(|state| Rc::as_ptr(state) as *const () as usize)
2559                .collect(),
2560            child_measurable_ptrs: self
2561                .child_measurables
2562                .iter()
2563                .map(|measurable| {
2564                    measurable.as_ref() as *const dyn Measurable as *const () as usize
2565                })
2566                .collect(),
2567            child_measurable_count: self.child_measurables.len(),
2568            coordinator_node_ptrs: self.coordinator_chain.debug_ptrs(),
2569            coordinator_node_count: self.coordinator_chain.nodes.len(),
2570        }
2571    }
2572}
2573
2574#[cfg(test)]
2575#[derive(Debug, Clone, PartialEq, Eq)]
2576pub(crate) struct LayoutRuntimeDebugStats {
2577    pub(crate) child_ids: Vec<NodeId>,
2578    pub(crate) child_state_ptrs: Vec<usize>,
2579    pub(crate) child_measurable_ptrs: Vec<usize>,
2580    pub(crate) child_measurable_count: usize,
2581    pub(crate) coordinator_node_ptrs: Vec<usize>,
2582    pub(crate) coordinator_node_count: usize,
2583}
2584
2585struct LayoutChildMeasureConfig {
2586    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
2587    node_id: NodeId,
2588    error: Rc<RefCell<Option<NodeError>>>,
2589    runtime_handle: Option<RuntimeHandle>,
2590    cache: LayoutNodeCacheHandles,
2591    cache_epoch: u64,
2592    force_remeasure: bool,
2593    measure_handle: Option<LayoutMeasureHandle>,
2594    layout_state: Option<Rc<RefCell<LayoutState>>>,
2595}
2596
2597struct LayoutChildMeasureState {
2598    applier: RefCell<Option<Rc<ConcreteApplierHost<MemoryApplier>>>>,
2599    node_id: Cell<NodeId>,
2600    measured: RefCell<Option<Rc<MeasuredNode>>>,
2601    last_position: Cell<Option<Point>>,
2602    error: RefCell<Option<Rc<RefCell<Option<NodeError>>>>>,
2603    runtime_handle: RefCell<Option<RuntimeHandle>>,
2604    cache: RefCell<LayoutNodeCacheHandles>,
2605    cache_epoch: Cell<u64>,
2606    force_remeasure: Cell<bool>,
2607    measure_handle: RefCell<Option<LayoutMeasureHandle>>,
2608    layout_state: RefCell<Option<Rc<RefCell<LayoutState>>>>,
2609}
2610
2611impl LayoutChildMeasureState {
2612    fn new(node_id: NodeId) -> Rc<Self> {
2613        Rc::new(Self {
2614            applier: RefCell::new(None),
2615            node_id: Cell::new(node_id),
2616            measured: RefCell::new(None),
2617            last_position: Cell::new(None),
2618            error: RefCell::new(None),
2619            runtime_handle: RefCell::new(None),
2620            cache: RefCell::new(LayoutNodeCacheHandles::default()),
2621            cache_epoch: Cell::new(0),
2622            force_remeasure: Cell::new(true),
2623            measure_handle: RefCell::new(None),
2624            layout_state: RefCell::new(None),
2625        })
2626    }
2627
2628    fn configure(&self, config: LayoutChildMeasureConfig) {
2629        config.cache.activate(config.cache_epoch);
2630        *self.applier.borrow_mut() = Some(config.applier);
2631        self.node_id.set(config.node_id);
2632        self.measured.borrow_mut().take();
2633        self.last_position.set(None);
2634        *self.error.borrow_mut() = Some(config.error);
2635        *self.runtime_handle.borrow_mut() = config.runtime_handle;
2636        *self.cache.borrow_mut() = config.cache;
2637        self.cache_epoch.set(config.cache_epoch);
2638        self.force_remeasure.set(config.force_remeasure);
2639        *self.measure_handle.borrow_mut() = config.measure_handle;
2640        *self.layout_state.borrow_mut() = config.layout_state;
2641    }
2642
2643    fn clear_frame_bindings(&self) {
2644        self.measured.borrow_mut().take();
2645        *self.applier.borrow_mut() = None;
2646        *self.error.borrow_mut() = None;
2647        *self.runtime_handle.borrow_mut() = None;
2648        *self.measure_handle.borrow_mut() = None;
2649        *self.layout_state.borrow_mut() = None;
2650    }
2651
2652    fn node_id(&self) -> NodeId {
2653        self.node_id.get()
2654    }
2655
2656    fn cache(&self) -> LayoutNodeCacheHandles {
2657        self.cache.borrow().clone()
2658    }
2659
2660    fn applier(&self) -> Option<Rc<ConcreteApplierHost<MemoryApplier>>> {
2661        self.applier.borrow().clone()
2662    }
2663
2664    fn layout_state(&self) -> Option<Rc<RefCell<LayoutState>>> {
2665        self.layout_state.borrow().clone()
2666    }
2667
2668    fn take_measured(&self) -> Option<Rc<MeasuredNode>> {
2669        self.measured.borrow_mut().take()
2670    }
2671
2672    fn last_position(&self) -> Option<Point> {
2673        self.last_position.get()
2674    }
2675
2676    fn set_last_position(&self, position: Point) {
2677        self.last_position.set(Some(position));
2678    }
2679
2680    fn set_measured(&self, measured: Option<Rc<MeasuredNode>>) {
2681        *self.measured.borrow_mut() = measured;
2682    }
2683
2684    fn record_error(&self, err: NodeError) {
2685        let Some(error) = self.error.borrow().clone() else {
2686            return;
2687        };
2688        let mut slot = error.borrow_mut();
2689        if slot.is_none() {
2690            *slot = Some(err);
2691        }
2692    }
2693
2694    fn perform_measure(&self, constraints: Constraints) -> Result<Rc<MeasuredNode>, NodeError> {
2695        let node_id = self.node_id();
2696        if let Some(handle) = self.measure_handle.borrow().clone() {
2697            return handle.measure(node_id, constraints);
2698        }
2699        let applier = self.applier().ok_or(NodeError::MissingContext {
2700            id: node_id,
2701            reason: "layout child applier not configured",
2702        })?;
2703        measure_node_with_host(
2704            applier,
2705            self.runtime_handle.borrow().clone(),
2706            node_id,
2707            constraints,
2708            self.cache_epoch.get(),
2709        )
2710    }
2711
2712    fn intrinsic_measure(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
2713        let cache = self.cache();
2714        cache.activate(self.cache_epoch.get());
2715        if !self.force_remeasure.get() {
2716            if let Some(cached) = cache.get_measurement(constraints) {
2717                return Some(cached);
2718            }
2719        }
2720
2721        match self.perform_measure(constraints) {
2722            Ok(measured) => {
2723                self.force_remeasure.set(false);
2724                cache.store_measurement(constraints, Rc::clone(&measured));
2725                Some(measured)
2726            }
2727            Err(err) => {
2728                self.record_error(err);
2729                None
2730            }
2731        }
2732    }
2733}
2734
2735struct LayoutChildMeasurable {
2736    state: Rc<LayoutChildMeasureState>,
2737}
2738
2739impl LayoutChildMeasurable {
2740    fn new(state: Rc<LayoutChildMeasureState>) -> Self {
2741        Self { state }
2742    }
2743}
2744
2745impl Measurable for LayoutChildMeasurable {
2746    fn measure(&self, constraints: Constraints) -> Placeable {
2747        let state = &self.state;
2748        let cache = state.cache();
2749        cache.activate(state.cache_epoch.get());
2750        let measured_size;
2751        if !state.force_remeasure.get() {
2752            if let Some(cached) = cache.get_measurement(constraints) {
2753                measured_size = cached.size;
2754                state.set_measured(Some(Rc::clone(&cached)));
2755            } else {
2756                match state.perform_measure(constraints) {
2757                    Ok(measured) => {
2758                        state.force_remeasure.set(false);
2759                        measured_size = measured.size;
2760                        cache.store_measurement(constraints, Rc::clone(&measured));
2761                        state.set_measured(Some(measured));
2762                    }
2763                    Err(err) => {
2764                        state.record_error(err);
2765                        state.set_measured(None);
2766                        measured_size = Size {
2767                            width: 0.0,
2768                            height: 0.0,
2769                        };
2770                    }
2771                }
2772            }
2773        } else {
2774            match state.perform_measure(constraints) {
2775                Ok(measured) => {
2776                    state.force_remeasure.set(false);
2777                    measured_size = measured.size;
2778                    cache.store_measurement(constraints, Rc::clone(&measured));
2779                    state.set_measured(Some(measured));
2780                }
2781                Err(err) => {
2782                    state.record_error(err);
2783                    state.set_measured(None);
2784                    measured_size = Size {
2785                        width: 0.0,
2786                        height: 0.0,
2787                    };
2788                }
2789            }
2790        }
2791
2792        if let Some(layout_state) = state.layout_state() {
2793            let mut layout_state = layout_state.borrow_mut();
2794            layout_state.size = measured_size;
2795            layout_state.measurement_constraints = constraints;
2796        } else if let Some(applier) = state.applier() {
2797            let Ok(mut applier) = applier.try_borrow_typed() else {
2798                return Placeable::value(
2799                    measured_size.width,
2800                    measured_size.height,
2801                    state.node_id(),
2802                );
2803            };
2804            let _ = applier.with_node::<LayoutNode, _>(state.node_id(), |node| {
2805                node.set_measured_size(measured_size);
2806                node.set_measurement_constraints(constraints);
2807            });
2808        }
2809
2810        let state = Rc::clone(&self.state);
2811        let applier = state.applier();
2812        let node_id = state.node_id();
2813        let layout_state = state.layout_state();
2814
2815        let place_fn = Rc::new(move |x: f32, y: f32| {
2816            let internal_offset = state
2817                .measured
2818                .borrow()
2819                .as_ref()
2820                .map(|m| m.offset)
2821                .unwrap_or_default();
2822
2823            let position = Point {
2824                x: x + internal_offset.x,
2825                y: y + internal_offset.y,
2826            };
2827            state.set_last_position(position);
2828
2829            if let Some(layout_state) = &layout_state {
2830                let mut layout_state = layout_state.borrow_mut();
2831                layout_state.position = position;
2832                layout_state.is_placed = true;
2833            } else if let Some(applier) = &applier {
2834                let Ok(mut applier) = applier.try_borrow_typed() else {
2835                    return;
2836                };
2837                if applier
2838                    .with_node::<LayoutNode, _>(node_id, |node| {
2839                        node.set_position(position);
2840                    })
2841                    .is_err()
2842                {
2843                    let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
2844                        node.set_position(position);
2845                    });
2846                }
2847            }
2848        });
2849
2850        Placeable::with_place_fn(measured_size.width, measured_size.height, node_id, place_fn)
2851    }
2852
2853    fn min_intrinsic_width(&self, height: f32) -> f32 {
2854        let kind = IntrinsicKind::MinWidth(height);
2855        let cache = self.state.cache();
2856        cache.activate(self.state.cache_epoch.get());
2857        if !self.state.force_remeasure.get() {
2858            if let Some(value) = cache.get_intrinsic(&kind) {
2859                return value;
2860            }
2861        }
2862        let constraints = Constraints {
2863            min_width: 0.0,
2864            max_width: f32::INFINITY,
2865            min_height: height,
2866            max_height: height,
2867        };
2868        if let Some(node) = self.state.intrinsic_measure(constraints) {
2869            let value = node.size.width;
2870            cache.store_intrinsic(kind, value);
2871            value
2872        } else {
2873            0.0
2874        }
2875    }
2876
2877    fn max_intrinsic_width(&self, height: f32) -> f32 {
2878        let kind = IntrinsicKind::MaxWidth(height);
2879        let cache = self.state.cache();
2880        cache.activate(self.state.cache_epoch.get());
2881        if !self.state.force_remeasure.get() {
2882            if let Some(value) = cache.get_intrinsic(&kind) {
2883                return value;
2884            }
2885        }
2886        let constraints = Constraints {
2887            min_width: 0.0,
2888            max_width: f32::INFINITY,
2889            min_height: 0.0,
2890            max_height: height,
2891        };
2892        if let Some(node) = self.state.intrinsic_measure(constraints) {
2893            let value = node.size.width;
2894            cache.store_intrinsic(kind, value);
2895            value
2896        } else {
2897            0.0
2898        }
2899    }
2900
2901    fn min_intrinsic_height(&self, width: f32) -> f32 {
2902        let kind = IntrinsicKind::MinHeight(width);
2903        let cache = self.state.cache();
2904        cache.activate(self.state.cache_epoch.get());
2905        if !self.state.force_remeasure.get() {
2906            if let Some(value) = cache.get_intrinsic(&kind) {
2907                return value;
2908            }
2909        }
2910        let constraints = Constraints {
2911            min_width: width,
2912            max_width: width,
2913            min_height: 0.0,
2914            max_height: f32::INFINITY,
2915        };
2916        if let Some(node) = self.state.intrinsic_measure(constraints) {
2917            let value = node.size.height;
2918            cache.store_intrinsic(kind, value);
2919            value
2920        } else {
2921            0.0
2922        }
2923    }
2924
2925    fn max_intrinsic_height(&self, width: f32) -> f32 {
2926        let kind = IntrinsicKind::MaxHeight(width);
2927        let cache = self.state.cache();
2928        cache.activate(self.state.cache_epoch.get());
2929        if !self.state.force_remeasure.get() {
2930            if let Some(value) = cache.get_intrinsic(&kind) {
2931                return value;
2932            }
2933        }
2934        let constraints = Constraints {
2935            min_width: 0.0,
2936            max_width: width,
2937            min_height: 0.0,
2938            max_height: f32::INFINITY,
2939        };
2940        if let Some(node) = self.state.intrinsic_measure(constraints) {
2941            let value = node.size.height;
2942            cache.store_intrinsic(kind, value);
2943            value
2944        } else {
2945            0.0
2946        }
2947    }
2948
2949    fn flex_parent_data(&self) -> Option<cranpose_ui_layout::FlexParentData> {
2950        let applier = self.state.applier()?;
2951        let node_id = self.state.node_id();
2952        let Ok(mut applier) = applier.try_borrow_typed() else {
2953            return None;
2954        };
2955
2956        applier
2957            .with_node::<LayoutNode, _>(node_id, |layout_node| {
2958                let props = layout_node.resolved_modifiers().layout_properties();
2959                props.weight().map(|weight_data| {
2960                    cranpose_ui_layout::FlexParentData::new(weight_data.weight, weight_data.fill)
2961                })
2962            })
2963            .ok()
2964            .flatten()
2965    }
2966}
2967
2968fn measure_node_with_host(
2969    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
2970    runtime_handle: Option<RuntimeHandle>,
2971    node_id: NodeId,
2972    constraints: Constraints,
2973    epoch: u64,
2974) -> Result<Rc<MeasuredNode>, NodeError> {
2975    let runtime_handle = match runtime_handle {
2976        Some(handle) => Some(handle),
2977        None => applier.borrow_typed().runtime_handle(),
2978    };
2979    let mut builder = LayoutBuilder::new_with_epoch(
2980        applier,
2981        epoch,
2982        Rc::new(RefCell::new(SlotTable::default())),
2983        FrameLayoutArena::default(),
2984    );
2985    builder.set_runtime_handle(runtime_handle);
2986    builder.measure_node(node_id, constraints)
2987}
2988
2989#[derive(Clone)]
2990struct RuntimeNodeMetadata {
2991    modifier: Modifier,
2992    resolved_modifiers: ResolvedModifiers,
2993    modifier_slices: Rc<ModifierNodeSlices>,
2994    role: SemanticsRole,
2995    button_handler: Option<Rc<RefCell<dyn FnMut()>>>,
2996}
2997
2998impl Default for RuntimeNodeMetadata {
2999    fn default() -> Self {
3000        Self {
3001            modifier: Modifier::empty(),
3002            resolved_modifiers: ResolvedModifiers::default(),
3003            modifier_slices: Rc::default(),
3004            role: SemanticsRole::Unknown,
3005            button_handler: None,
3006        }
3007    }
3008}
3009
3010fn role_from_modifier_slices(modifier_slices: &ModifierNodeSlices) -> SemanticsRole {
3011    modifier_slices
3012        .text_content()
3013        .map(|text| SemanticsRole::Text {
3014            value: text.to_string(),
3015        })
3016        .unwrap_or(SemanticsRole::Layout)
3017}
3018
3019fn runtime_metadata_for(
3020    applier: &mut MemoryApplier,
3021    node_id: NodeId,
3022) -> Result<RuntimeNodeMetadata, NodeError> {
3023    // Try LayoutNode (the primary modern path)
3024    // IMPORTANT: We use with_node (reference) instead of try_clone because cloning
3025    // LayoutNode creates a NEW ModifierChainHandle with NEW nodes and NEW handlers,
3026    // which would lose gesture state like press_position.
3027    if let Ok(meta) = applier.with_node::<LayoutNode, _>(node_id, |layout| {
3028        let modifier = layout.modifier.clone();
3029        let resolved_modifiers = layout.resolved_modifiers();
3030        let modifier_slices = layout.modifier_slices_snapshot();
3031        let role = role_from_modifier_slices(&modifier_slices);
3032
3033        RuntimeNodeMetadata {
3034            modifier,
3035            resolved_modifiers,
3036            modifier_slices,
3037            role,
3038            button_handler: None,
3039        }
3040    }) {
3041        return Ok(meta);
3042    }
3043
3044    // Try SubcomposeLayoutNode
3045    if let Ok((modifier, resolved_modifiers, modifier_slices)) = applier
3046        .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
3047            (
3048                node.modifier(),
3049                node.resolved_modifiers(),
3050                node.modifier_slices_snapshot(),
3051            )
3052        })
3053    {
3054        return Ok(RuntimeNodeMetadata {
3055            modifier,
3056            resolved_modifiers,
3057            modifier_slices,
3058            role: SemanticsRole::Subcompose,
3059            button_handler: None,
3060        });
3061    }
3062    Ok(RuntimeNodeMetadata::default())
3063}
3064
3065fn clear_semantics_dirty_flags(
3066    applier: &mut MemoryApplier,
3067    node: &MeasuredNode,
3068) -> Result<(), NodeError> {
3069    match applier.with_node::<LayoutNode, _>(node.node_id, |layout| {
3070        layout.clear_needs_semantics();
3071    }) {
3072        Ok(()) => {}
3073        Err(NodeError::Missing { .. }) => {}
3074        Err(NodeError::TypeMismatch { .. }) => {
3075            match applier.with_node::<SubcomposeLayoutNode, _>(node.node_id, |subcompose| {
3076                subcompose.clear_needs_semantics();
3077            }) {
3078                Ok(()) | Err(NodeError::Missing { .. }) | Err(NodeError::TypeMismatch { .. }) => {}
3079                Err(err) => return Err(err),
3080            }
3081        }
3082        Err(err) => return Err(err),
3083    }
3084
3085    for child in &node.children {
3086        clear_semantics_dirty_flags(applier, &child.node)?;
3087    }
3088
3089    Ok(())
3090}
3091
3092fn build_semantics_tree_from_live_nodes(
3093    applier: &mut MemoryApplier,
3094    node: &MeasuredNode,
3095) -> Result<SemanticsTree, NodeError> {
3096    Ok(SemanticsTree::new(build_semantics_node_from_live_nodes(
3097        applier, node,
3098    )?))
3099}
3100
3101fn semantics_node_from_parts(
3102    node_id: NodeId,
3103    mut role: SemanticsRole,
3104    config: Option<SemanticsConfiguration>,
3105    children: Vec<SemanticsNode>,
3106) -> SemanticsNode {
3107    let mut actions = Vec::new();
3108    let mut description = None;
3109    let mut editable_text = false;
3110    let mut text_selection = None;
3111
3112    if let Some(config) = config {
3113        if config.is_button {
3114            role = SemanticsRole::Button;
3115        }
3116        if config.is_clickable {
3117            actions.push(SemanticsAction::Click {
3118                handler: SemanticsCallback::new(node_id),
3119            });
3120        }
3121        description = config.content_description;
3122        editable_text = config.is_editable_text;
3123        text_selection = config.text_selection;
3124    }
3125
3126    SemanticsNode::new(
3127        node_id,
3128        role,
3129        actions,
3130        children,
3131        description,
3132        editable_text,
3133        text_selection,
3134    )
3135}
3136
3137fn build_semantics_node_from_live_nodes(
3138    applier: &mut MemoryApplier,
3139    node: &MeasuredNode,
3140) -> Result<SemanticsNode, NodeError> {
3141    let (role, config) = match applier.with_node::<LayoutNode, _>(node.node_id, |layout| {
3142        let role = role_from_modifier_slices(&layout.modifier_slices_snapshot());
3143        let config = layout.semantics_configuration();
3144        layout.clear_needs_semantics();
3145        (role, config)
3146    }) {
3147        Ok(data) => data,
3148        Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
3149            match applier.with_node::<SubcomposeLayoutNode, _>(node.node_id, |subcompose| {
3150                subcompose.clear_needs_semantics();
3151                (
3152                    SemanticsRole::Subcompose,
3153                    collect_semantics_from_modifier(&subcompose.modifier()),
3154                )
3155            }) {
3156                Ok(data) => data,
3157                Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
3158                    (SemanticsRole::Unknown, None)
3159                }
3160                Err(err) => return Err(err),
3161            }
3162        }
3163        Err(err) => return Err(err),
3164    };
3165
3166    let mut children = Vec::with_capacity(node.children.len());
3167    for child in &node.children {
3168        children.push(build_semantics_node_from_live_nodes(applier, &child.node)?);
3169    }
3170
3171    Ok(semantics_node_from_parts(
3172        node.node_id,
3173        role,
3174        config,
3175        children,
3176    ))
3177}
3178
3179fn record_semantics_allocation_stats(node: &SemanticsNode, stats: &mut LayoutAllocationDebugStats) {
3180    stats.semantics_node_count += 1;
3181    stats.semantics_action_count += node.actions.len();
3182    stats.semantics_action_capacity += node.actions.capacity();
3183    stats.semantics_child_count += node.children.len();
3184    stats.semantics_child_capacity += node.children.capacity();
3185    stats.semantics_heap_bytes += node.actions.capacity() * size_of::<SemanticsAction>();
3186    stats.semantics_heap_bytes += node.children.capacity() * size_of::<SemanticsNode>();
3187
3188    if let Some(description) = &node.description {
3189        stats.semantics_description_count += 1;
3190        stats.semantics_description_bytes += description.capacity();
3191        stats.semantics_heap_bytes += description.capacity();
3192    }
3193    if let SemanticsRole::Text { value } = &node.role {
3194        stats.semantics_text_role_bytes += value.capacity();
3195        stats.semantics_heap_bytes += value.capacity();
3196    }
3197
3198    for child in &node.children {
3199        record_semantics_allocation_stats(child, stats);
3200    }
3201}
3202
3203fn record_layout_box_allocation_stats(
3204    layout_box: &LayoutBox,
3205    stats: &mut LayoutAllocationDebugStats,
3206) {
3207    stats.layout_box_count += 1;
3208    stats.layout_box_child_count += layout_box.children.len();
3209    stats.layout_box_child_capacity += layout_box.children.capacity();
3210    stats.layout_box_heap_bytes += layout_box.children.capacity() * size_of::<LayoutBox>();
3211    stats.add_modifier_slice(layout_box.node_data.modifier_slices().debug_stats());
3212
3213    for child in &layout_box.children {
3214        record_layout_box_allocation_stats(child, stats);
3215    }
3216}
3217
3218fn build_layout_tree(
3219    applier: &mut MemoryApplier,
3220    node: &MeasuredNode,
3221) -> Result<LayoutTree, NodeError> {
3222    fn place(
3223        applier: &mut MemoryApplier,
3224        node: &MeasuredNode,
3225        origin: Point,
3226    ) -> Result<LayoutBox, NodeError> {
3227        // Include the node's own offset (from OffsetNode) in its position
3228        let top_left = Point {
3229            x: origin.x + node.offset.x,
3230            y: origin.y + node.offset.y,
3231        };
3232        let rect = GeometryRect {
3233            x: top_left.x,
3234            y: top_left.y,
3235            width: node.size.width,
3236            height: node.size.height,
3237        };
3238        let info = runtime_metadata_for(applier, node.node_id)?;
3239        let kind = layout_kind_from_metadata(node.node_id, &info);
3240        let RuntimeNodeMetadata {
3241            modifier,
3242            resolved_modifiers,
3243            modifier_slices,
3244            ..
3245        } = info;
3246        let data = LayoutNodeData::new(modifier, resolved_modifiers, modifier_slices, kind);
3247        let mut children = Vec::with_capacity(node.children.len());
3248        for child in &node.children {
3249            let child_origin = Point {
3250                x: top_left.x + child.offset.x,
3251                y: top_left.y + child.offset.y,
3252            };
3253            children.push(place(applier, &child.node, child_origin)?);
3254        }
3255        Ok(LayoutBox::new(
3256            node.node_id,
3257            rect,
3258            node.content_offset,
3259            data,
3260            children,
3261        ))
3262    }
3263
3264    Ok(LayoutTree::new(place(
3265        applier,
3266        node,
3267        Point { x: 0.0, y: 0.0 },
3268    )?))
3269}
3270
3271fn semantics_role_from_layout_box(layout_box: &LayoutBox) -> SemanticsRole {
3272    match &layout_box.node_data.kind {
3273        LayoutNodeKind::Subcompose => SemanticsRole::Subcompose,
3274        LayoutNodeKind::Spacer => SemanticsRole::Spacer,
3275        LayoutNodeKind::Unknown => SemanticsRole::Unknown,
3276        LayoutNodeKind::Button { .. } => SemanticsRole::Button,
3277        LayoutNodeKind::Layout => layout_box
3278            .node_data
3279            .modifier_slices()
3280            .text_content()
3281            .map(|text| SemanticsRole::Text {
3282                value: text.to_string(),
3283            })
3284            .unwrap_or(SemanticsRole::Layout),
3285    }
3286}
3287
3288fn build_semantics_node_from_layout_box(layout_box: &LayoutBox) -> SemanticsNode {
3289    let children = layout_box
3290        .children
3291        .iter()
3292        .map(build_semantics_node_from_layout_box)
3293        .collect();
3294
3295    semantics_node_from_parts(
3296        layout_box.node_id,
3297        semantics_role_from_layout_box(layout_box),
3298        collect_semantics_from_modifier(&layout_box.node_data.modifier),
3299        children,
3300    )
3301}
3302
3303fn layout_kind_from_metadata(_node_id: NodeId, info: &RuntimeNodeMetadata) -> LayoutNodeKind {
3304    match &info.role {
3305        SemanticsRole::Layout => LayoutNodeKind::Layout,
3306        SemanticsRole::Subcompose => LayoutNodeKind::Subcompose,
3307        SemanticsRole::Text { .. } => {
3308            // Text content is now handled via TextModifierNode in the modifier chain
3309            // and collected in modifier_slices.text_content(). LayoutNodeKind should
3310            // reflect the layout policy (EmptyMeasurePolicy), not the content type.
3311            LayoutNodeKind::Layout
3312        }
3313        SemanticsRole::Spacer => LayoutNodeKind::Spacer,
3314        SemanticsRole::Button => {
3315            let handler = info
3316                .button_handler
3317                .as_ref()
3318                .cloned()
3319                .unwrap_or_else(|| Rc::new(RefCell::new(|| {})));
3320            LayoutNodeKind::Button { on_click: handler }
3321        }
3322        SemanticsRole::Unknown => LayoutNodeKind::Unknown,
3323    }
3324}
3325
3326fn subtract_padding(constraints: Constraints, padding: EdgeInsets) -> Constraints {
3327    let horizontal = padding.horizontal_sum();
3328    let vertical = padding.vertical_sum();
3329    let min_width = (constraints.min_width - horizontal).max(0.0);
3330    let mut max_width = constraints.max_width;
3331    if max_width.is_finite() {
3332        max_width = (max_width - horizontal).max(0.0);
3333    }
3334    let min_height = (constraints.min_height - vertical).max(0.0);
3335    let mut max_height = constraints.max_height;
3336    if max_height.is_finite() {
3337        max_height = (max_height - vertical).max(0.0);
3338    }
3339    normalize_constraints(Constraints {
3340        min_width,
3341        max_width,
3342        min_height,
3343        max_height,
3344    })
3345}
3346
3347#[cfg(test)]
3348pub(crate) fn align_horizontal(alignment: HorizontalAlignment, available: f32, child: f32) -> f32 {
3349    match alignment {
3350        HorizontalAlignment::Start => 0.0,
3351        HorizontalAlignment::CenterHorizontally => ((available - child) / 2.0).max(0.0),
3352        HorizontalAlignment::End => (available - child).max(0.0),
3353    }
3354}
3355
3356#[cfg(test)]
3357pub(crate) fn align_vertical(alignment: VerticalAlignment, available: f32, child: f32) -> f32 {
3358    match alignment {
3359        VerticalAlignment::Top => 0.0,
3360        VerticalAlignment::CenterVertically => ((available - child) / 2.0).max(0.0),
3361        VerticalAlignment::Bottom => (available - child).max(0.0),
3362    }
3363}
3364
3365fn resolve_dimension(
3366    base: f32,
3367    explicit: DimensionConstraint,
3368    min_override: Option<f32>,
3369    max_override: Option<f32>,
3370    min_limit: f32,
3371    max_limit: f32,
3372) -> f32 {
3373    let mut min_bound = min_limit;
3374    if let Some(min_value) = min_override {
3375        min_bound = min_bound.max(min_value);
3376    }
3377
3378    let mut max_bound = if max_limit.is_finite() {
3379        max_limit
3380    } else {
3381        max_override.unwrap_or(max_limit)
3382    };
3383    if let Some(max_value) = max_override {
3384        if max_bound.is_finite() {
3385            max_bound = max_bound.min(max_value);
3386        } else {
3387            max_bound = max_value;
3388        }
3389    }
3390    if max_bound < min_bound {
3391        max_bound = min_bound;
3392    }
3393
3394    let mut size = match explicit {
3395        DimensionConstraint::Points(points) => points,
3396        DimensionConstraint::Fraction(fraction) => {
3397            if max_limit.is_finite() {
3398                max_limit * fraction.clamp(0.0, 1.0)
3399            } else {
3400                base
3401            }
3402        }
3403        DimensionConstraint::Unspecified => base,
3404        // Intrinsic sizing is resolved at a higher level where we have access to children.
3405        // At this point we just use the base size as a fallback.
3406        DimensionConstraint::Intrinsic(_) => base,
3407    };
3408
3409    size = clamp_dimension(size, min_bound, max_bound);
3410    size = clamp_dimension(size, min_limit, max_limit);
3411    size.max(0.0)
3412}
3413
3414fn clamp_dimension(value: f32, min: f32, max: f32) -> f32 {
3415    let mut result = value.max(min);
3416    if max.is_finite() {
3417        result = result.min(max);
3418    }
3419    result
3420}
3421
3422fn normalize_constraints(mut constraints: Constraints) -> Constraints {
3423    if constraints.max_width < constraints.min_width {
3424        constraints.max_width = constraints.min_width;
3425    }
3426    if constraints.max_height < constraints.min_height {
3427        constraints.max_height = constraints.min_height;
3428    }
3429    constraints
3430}
3431
3432#[cfg(test)]
3433#[path = "tests/layout_tests.rs"]
3434mod tests;