Skip to main content

cranpose_ui/layout/
mod.rs

1// WIP: Layout system infrastructure - many helper types not yet fully wired up
2
3pub mod coordinator;
4pub mod core;
5pub mod policies;
6
7use cranpose_core::collections::map::Entry;
8use cranpose_core::collections::map::HashMap;
9use std::{
10    cell::RefCell,
11    fmt,
12    rc::Rc,
13    sync::atomic::{AtomicU64, Ordering},
14};
15
16use cranpose_core::{
17    Applier, ApplierHost, Composer, ConcreteApplierHost, MemoryApplier, NodeError, NodeId, Phase,
18    RuntimeHandle, SlotBackend, SlotsHost, SnapshotStateObserver,
19};
20
21use self::coordinator::NodeCoordinator;
22use self::core::Measurable;
23use self::core::Placeable;
24#[cfg(test)]
25use self::core::{HorizontalAlignment, VerticalAlignment};
26use crate::modifier::{
27    collect_semantics_from_modifier, DimensionConstraint, EdgeInsets, Modifier, ModifierNodeSlices,
28    Point, Rect as GeometryRect, ResolvedModifiers, Size,
29};
30
31use crate::subcompose_layout::SubcomposeLayoutNode;
32use crate::widgets::nodes::{IntrinsicKind, LayoutNode, LayoutNodeCacheHandles};
33use cranpose_foundation::InvalidationKind;
34use cranpose_foundation::ModifierNodeContext;
35use cranpose_foundation::{NodeCapabilities, SemanticsConfiguration};
36use cranpose_ui_layout::{Constraints, MeasurePolicy, MeasureResult};
37
38/// Runtime context for modifier nodes during measurement.
39///
40/// Unlike `BasicModifierNodeContext`, this context accumulates invalidations
41/// that can be processed after measurement to set dirty flags on the LayoutNode.
42#[derive(Default)]
43pub(crate) struct LayoutNodeContext {
44    invalidations: Vec<InvalidationKind>,
45    update_requested: bool,
46    active_capabilities: Vec<NodeCapabilities>,
47}
48
49impl LayoutNodeContext {
50    pub(crate) fn new() -> Self {
51        Self::default()
52    }
53
54    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationKind> {
55        std::mem::take(&mut self.invalidations)
56    }
57}
58
59impl ModifierNodeContext for LayoutNodeContext {
60    fn invalidate(&mut self, kind: InvalidationKind) {
61        if !self.invalidations.contains(&kind) {
62            self.invalidations.push(kind);
63        }
64    }
65
66    fn request_update(&mut self) {
67        self.update_requested = true;
68    }
69
70    fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
71        self.active_capabilities.push(capabilities);
72    }
73
74    fn pop_active_capabilities(&mut self) {
75        self.active_capabilities.pop();
76    }
77}
78
79static NEXT_CACHE_EPOCH: AtomicU64 = AtomicU64::new(1);
80
81/// Forces all layout caches to be invalidated on the next measure by incrementing the epoch.
82///
83/// # ⚠️ Internal Use Only - NOT Public API
84///
85/// **This function is hidden from public documentation and MUST NOT be called by external code.**
86///
87/// Only `cranpose-app-shell` may call this for rare global events:
88/// - Window/viewport resize
89/// - Global font scale or density changes
90/// - Debug toggles that affect all layout
91///
92/// **This is O(entire app size) - extremely expensive!**
93///
94/// # For Local Changes
95///
96/// **Do NOT use this for scroll, single-node mutations, or any local layout change.**
97/// Instead, use the scoped repass mechanism:
98/// ```text
99/// cranpose_ui::schedule_layout_repass(node_id);
100/// ```
101///
102/// The scoped path bubbles dirty flags without invalidating all caches, giving you O(subtree) instead of O(app).
103#[doc(hidden)]
104pub fn invalidate_all_layout_caches() {
105    NEXT_CACHE_EPOCH.fetch_add(1, Ordering::Relaxed);
106}
107
108/// RAII guard that:
109/// - moves the current MemoryApplier into a ConcreteApplierHost
110/// - holds a shared handle to the SlotBackend used by LayoutBuilder
111/// - on Drop, always:
112///   * restores slots into the host from the shared handle
113///   * moves the original MemoryApplier back into the Composition
114///
115/// This makes `measure_layout` panic/Err-safe wrt both the applier and slots.
116/// The key invariant: guard and builder share the same `Rc<RefCell<SlotBackend>>`,
117/// so the guard never loses access to the authoritative slots even on panic.
118struct ApplierSlotGuard<'a> {
119    /// The `MemoryApplier` inside the Composition::applier that we must restore into.
120    target: &'a mut MemoryApplier,
121    /// Host that owns the original MemoryApplier while layout is running.
122    host: Rc<ConcreteApplierHost<MemoryApplier>>,
123    /// Shared handle to the slot table. Both the guard and the builder hold a clone.
124    /// On Drop, we write whatever is in this handle back into the applier.
125    slots: Rc<RefCell<SlotBackend>>,
126}
127
128impl<'a> ApplierSlotGuard<'a> {
129    /// Creates a new guard:
130    /// - moves the current MemoryApplier out of `target` into a host
131    /// - takes the current slots out of the host and wraps them in a shared handle
132    fn new(target: &'a mut MemoryApplier) -> Self {
133        // Move the original applier into a host; leave `target` with a fresh one
134        let original_applier = std::mem::replace(target, MemoryApplier::new());
135        let host = Rc::new(ConcreteApplierHost::new(original_applier));
136
137        // Take slots from the host into a shared handle
138        let slots = {
139            let mut applier_ref = host.borrow_typed();
140            std::mem::take(applier_ref.slots())
141        };
142        let slots = Rc::new(RefCell::new(slots));
143
144        Self {
145            target,
146            host,
147            slots,
148        }
149    }
150
151    /// Rc to pass into LayoutBuilder::new_with_epoch
152    fn host(&self) -> Rc<ConcreteApplierHost<MemoryApplier>> {
153        Rc::clone(&self.host)
154    }
155
156    /// Returns the shared handle to slots for the builder to use.
157    /// The builder clones this Rc, so both guard and builder share the same slots.
158    fn slots_handle(&self) -> Rc<RefCell<SlotBackend>> {
159        Rc::clone(&self.slots)
160    }
161}
162
163impl Drop for ApplierSlotGuard<'_> {
164    fn drop(&mut self) {
165        // 1) Restore slots into the host's MemoryApplier from the shared handle.
166        // This works correctly whether we're on the success path or panic/error path,
167        // because we always have the shared handle.
168        {
169            let mut applier_ref = self.host.borrow_typed();
170            *applier_ref.slots() = std::mem::take(&mut *self.slots.borrow_mut());
171        }
172
173        // 2) Move the original MemoryApplier (with restored/updated slots) back into `target`
174        {
175            let mut applier_ref = self.host.borrow_typed();
176            let original_applier = std::mem::take(&mut *applier_ref);
177            let _ = std::mem::replace(self.target, original_applier);
178        }
179        // No Rc::try_unwrap in Drop → no "panic during panic" risk.
180    }
181}
182
183/// Result of measuring through the modifier node chain.
184struct ModifierChainMeasurement {
185    result: MeasureResult,
186    /// Content offset for scroll/inner transforms - NOT padding semantics
187    content_offset: Point,
188    /// Node's own offset (from OffsetNode, affects position in parent)
189    offset: Point,
190}
191
192type LayoutModifierNodeData = (
193    usize,
194    Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
195);
196
197struct ScratchVecPool<T> {
198    available: Vec<Vec<T>>,
199}
200
201impl<T> ScratchVecPool<T> {
202    fn acquire(&mut self) -> Vec<T> {
203        self.available.pop().unwrap_or_default()
204    }
205
206    fn release(&mut self, mut values: Vec<T>) {
207        values.clear();
208        self.available.push(values);
209    }
210
211    #[cfg(test)]
212    fn available_count(&self) -> usize {
213        self.available.len()
214    }
215}
216
217impl<T> Default for ScratchVecPool<T> {
218    fn default() -> Self {
219        Self {
220            available: Vec::new(),
221        }
222    }
223}
224
225/// Discrete event callback reference produced during semantics extraction.
226#[derive(Clone, Debug, PartialEq, Eq)]
227pub struct SemanticsCallback {
228    node_id: NodeId,
229}
230
231impl SemanticsCallback {
232    pub fn new(node_id: NodeId) -> Self {
233        Self { node_id }
234    }
235
236    pub fn node_id(&self) -> NodeId {
237        self.node_id
238    }
239}
240
241/// Semantics action exposed to the input system.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub enum SemanticsAction {
244    Click { handler: SemanticsCallback },
245}
246
247/// Semantic role describing how a node should participate in accessibility and hit testing.
248/// Roles are now derived from SemanticsConfiguration rather than widget types.
249#[derive(Clone, Debug, PartialEq, Eq)]
250pub enum SemanticsRole {
251    /// Generic container or layout node
252    Layout,
253    /// Subcomposition boundary
254    Subcompose,
255    /// Text content (derived from TextNode for backward compatibility)
256    Text { value: String },
257    /// Spacer (non-interactive)
258    Spacer,
259    /// Button (derived from is_button semantics flag)
260    Button,
261    /// Unknown or unspecified role
262    Unknown,
263}
264
265/// A single node within the semantics tree.
266#[derive(Clone, Debug)]
267pub struct SemanticsNode {
268    pub node_id: NodeId,
269    pub role: SemanticsRole,
270    pub actions: Vec<SemanticsAction>,
271    pub children: Vec<SemanticsNode>,
272    pub description: Option<String>,
273}
274
275impl SemanticsNode {
276    fn new(
277        node_id: NodeId,
278        role: SemanticsRole,
279        actions: Vec<SemanticsAction>,
280        children: Vec<SemanticsNode>,
281        description: Option<String>,
282    ) -> Self {
283        Self {
284            node_id,
285            role,
286            actions,
287            children,
288            description,
289        }
290    }
291}
292
293/// Rooted semantics tree extracted after layout.
294#[derive(Clone, Debug)]
295pub struct SemanticsTree {
296    root: SemanticsNode,
297}
298
299impl SemanticsTree {
300    fn new(root: SemanticsNode) -> Self {
301        Self { root }
302    }
303
304    pub fn root(&self) -> &SemanticsNode {
305        &self.root
306    }
307}
308
309/// Caches semantics configurations for layout nodes, similar to Jetpack Compose's SemanticsOwner.
310/// This enables lazy semantics tree construction and efficient invalidation.
311#[derive(Default)]
312pub struct SemanticsOwner {
313    configurations: RefCell<HashMap<NodeId, Option<SemanticsConfiguration>>>,
314}
315
316impl SemanticsOwner {
317    pub fn new() -> Self {
318        Self {
319            configurations: RefCell::new(HashMap::default()),
320        }
321    }
322
323    /// Returns the cached configuration for the given node, computing it if necessary.
324    pub fn get_or_compute(
325        &self,
326        node_id: NodeId,
327        applier: &mut MemoryApplier,
328    ) -> Option<SemanticsConfiguration> {
329        // Check cache first
330        if let Some(cached) = self.configurations.borrow().get(&node_id) {
331            return cached.clone();
332        }
333
334        // Compute and cache
335        let config = compute_semantics_for_node(applier, node_id);
336        self.configurations
337            .borrow_mut()
338            .insert(node_id, config.clone());
339        config
340    }
341}
342
343/// Result of running layout for a Compose tree.
344#[derive(Debug, Clone)]
345pub struct LayoutTree {
346    root: LayoutBox,
347}
348
349impl LayoutTree {
350    pub fn new(root: LayoutBox) -> Self {
351        Self { root }
352    }
353
354    pub fn root(&self) -> &LayoutBox {
355        &self.root
356    }
357
358    pub fn root_mut(&mut self) -> &mut LayoutBox {
359        &mut self.root
360    }
361
362    pub fn into_root(self) -> LayoutBox {
363        self.root
364    }
365}
366
367/// Layout information for a single node.
368#[derive(Debug, Clone)]
369pub struct LayoutBox {
370    pub node_id: NodeId,
371    pub rect: GeometryRect,
372    /// Content offset for scroll/inner transforms (applies to children, NOT this node's position)
373    pub content_offset: Point,
374    pub node_data: LayoutNodeData,
375    pub children: Vec<LayoutBox>,
376}
377
378impl LayoutBox {
379    pub fn new(
380        node_id: NodeId,
381        rect: GeometryRect,
382        content_offset: Point,
383        node_data: LayoutNodeData,
384        children: Vec<LayoutBox>,
385    ) -> Self {
386        Self {
387            node_id,
388            rect,
389            content_offset,
390            node_data,
391            children,
392        }
393    }
394}
395
396/// Snapshot of the data required to render a layout node.
397#[derive(Debug, Clone)]
398pub struct LayoutNodeData {
399    pub modifier: Modifier,
400    pub resolved_modifiers: ResolvedModifiers,
401    pub modifier_slices: Rc<ModifierNodeSlices>,
402    pub kind: LayoutNodeKind,
403}
404
405impl LayoutNodeData {
406    pub fn new(
407        modifier: Modifier,
408        resolved_modifiers: ResolvedModifiers,
409        modifier_slices: Rc<ModifierNodeSlices>,
410        kind: LayoutNodeKind,
411    ) -> Self {
412        Self {
413            modifier,
414            resolved_modifiers,
415            modifier_slices,
416            kind,
417        }
418    }
419
420    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
421        self.resolved_modifiers
422    }
423
424    pub fn modifier_slices(&self) -> &ModifierNodeSlices {
425        &self.modifier_slices
426    }
427}
428
429/// Classification of the node captured inside a [`LayoutBox`].
430///
431/// Note: Text content is no longer represented as a distinct LayoutNodeKind.
432/// Text nodes now use `LayoutNodeKind::Layout` with their content stored in
433/// `modifier_slices.text_content()` via TextModifierNode, following Jetpack
434/// Compose's pattern where text is a modifier node capability.
435#[derive(Clone)]
436pub enum LayoutNodeKind {
437    Layout,
438    Subcompose,
439    Spacer,
440    Button { on_click: Rc<RefCell<dyn FnMut()>> },
441    Unknown,
442}
443
444impl fmt::Debug for LayoutNodeKind {
445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446        match self {
447            LayoutNodeKind::Layout => f.write_str("Layout"),
448            LayoutNodeKind::Subcompose => f.write_str("Subcompose"),
449            LayoutNodeKind::Spacer => f.write_str("Spacer"),
450            LayoutNodeKind::Button { .. } => f.write_str("Button"),
451            LayoutNodeKind::Unknown => f.write_str("Unknown"),
452        }
453    }
454}
455
456/// Extension trait that equips `MemoryApplier` with layout computation.
457pub trait LayoutEngine {
458    fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError>;
459}
460
461impl LayoutEngine for MemoryApplier {
462    fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError> {
463        let measurements = measure_layout(self, root, max_size)?;
464        Ok(measurements.into_layout_tree())
465    }
466}
467
468/// Result of running the measure pass for a Compose layout tree.
469#[derive(Debug, Clone)]
470pub struct LayoutMeasurements {
471    root: Rc<MeasuredNode>,
472    semantics: Option<SemanticsTree>,
473    layout_tree: LayoutTree,
474}
475
476impl LayoutMeasurements {
477    fn new(
478        root: Rc<MeasuredNode>,
479        semantics: Option<SemanticsTree>,
480        layout_tree: LayoutTree,
481    ) -> Self {
482        Self {
483            root,
484            semantics,
485            layout_tree,
486        }
487    }
488
489    /// Returns the measured size of the root node.
490    pub fn root_size(&self) -> Size {
491        self.root.size
492    }
493
494    pub fn semantics_tree(&self) -> Option<&SemanticsTree> {
495        self.semantics.as_ref()
496    }
497
498    /// Consumes the measurements and produces a [`LayoutTree`].
499    pub fn into_layout_tree(self) -> LayoutTree {
500        self.layout_tree
501    }
502
503    /// Returns a borrowed [`LayoutTree`] for rendering.
504    pub fn layout_tree(&self) -> LayoutTree {
505        self.layout_tree.clone()
506    }
507}
508
509#[derive(Clone, Copy, Debug, PartialEq, Eq)]
510pub struct MeasureLayoutOptions {
511    pub collect_semantics: bool,
512}
513
514impl Default for MeasureLayoutOptions {
515    fn default() -> Self {
516        Self {
517            collect_semantics: true,
518        }
519    }
520}
521
522/// Check if a node or any of its descendants needs measure (selective measure optimization).
523/// This can be used by the app shell to skip layout when the tree is clean.
524///
525/// O(1) check - just looks at root's dirty flag.
526/// Works because all mutation paths bubble dirty flags to root via composer commands.
527///
528/// Returns Result to force caller to handle errors explicitly. No more unwrap_or(true) safety net.
529pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
530    // Just check root - bubbling ensures it's dirty if any descendant is dirty
531    let node = applier.get_mut(root)?;
532    let layout_node =
533        node.as_any_mut()
534            .downcast_mut::<LayoutNode>()
535            .ok_or(NodeError::TypeMismatch {
536                id: root,
537                expected: std::any::type_name::<LayoutNode>(),
538            })?;
539    Ok(layout_node.needs_layout())
540}
541
542/// Test helper: bubbles layout dirty flag to root.
543#[cfg(test)]
544pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
545    cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
546}
547
548/// Runs the measure phase for the subtree rooted at `root`.
549pub fn measure_layout(
550    applier: &mut MemoryApplier,
551    root: NodeId,
552    max_size: Size,
553) -> Result<LayoutMeasurements, NodeError> {
554    measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
555}
556
557pub fn measure_layout_with_options(
558    applier: &mut MemoryApplier,
559    root: NodeId,
560    max_size: Size,
561    options: MeasureLayoutOptions,
562) -> Result<LayoutMeasurements, NodeError> {
563    let constraints = Constraints {
564        min_width: 0.0,
565        max_width: max_size.width,
566        min_height: 0.0,
567        max_height: max_size.height,
568    };
569
570    // Selective measure: only increment epoch if something needs MEASURING (not just layout)
571    // O(1) check - just look at root's dirty flag (bubbling ensures correctness)
572    //
573    // CRITICAL: We check needs_MEASURE, not needs_LAYOUT!
574    // - needs_measure: size may change, caches must be invalidated
575    // - needs_layout: position may change but size is cached (e.g., scroll)
576    //
577    // Scroll operations bubble needs_layout to ancestors, but NOT needs_measure.
578    // Using needs_layout here would wipe ALL caches on every scroll frame, causing
579    // O(N) full remeasurement instead of O(changed nodes).
580    let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
581        .with_node::<LayoutNode, _>(root, |node| {
582            (
583                node.needs_measure(), // CORRECT: check needs_measure, not needs_layout
584                node.needs_semantics(),
585                node.cache_handles().epoch(),
586            )
587        }) {
588        Ok(tuple) => tuple,
589        Err(NodeError::TypeMismatch { .. }) => {
590            let node = applier.get_mut(root)?;
591            // For non-LayoutNode roots, check needs_layout as fallback
592            let measure_dirty = node.needs_layout();
593            let semantics_dirty = node.needs_semantics();
594            (measure_dirty, semantics_dirty, 0)
595        }
596        Err(err) => return Err(err),
597    };
598
599    let epoch = if needs_remeasure {
600        NEXT_CACHE_EPOCH.fetch_add(1, Ordering::Relaxed)
601    } else if cached_epoch != 0 {
602        cached_epoch
603    } else {
604        // Fallback when caller root isn't a LayoutNode (e.g. tests using Spacer directly).
605        NEXT_CACHE_EPOCH.load(Ordering::Relaxed)
606    };
607
608    // Move the current applier into a host and set up a guard that will
609    // ALWAYS restore:
610    // - the MemoryApplier back into `applier`
611    // - the SlotBackend back into that MemoryApplier
612    //
613    // IMPORTANT: Declare the guard *before* the builder so the builder
614    // is dropped first (both on Ok and on unwind).
615    let guard = ApplierSlotGuard::new(applier);
616    let applier_host = guard.host();
617    let slots_handle = guard.slots_handle();
618
619    // Give the builder the shared slots handle - both guard and builder
620    // now share access to the same SlotBackend via Rc<RefCell<_>>.
621    let mut builder =
622        LayoutBuilder::new_with_epoch(Rc::clone(&applier_host), epoch, Rc::clone(&slots_handle));
623
624    // ---- Measurement -------------------------------------------------------
625    // If measurement fails, the guard will restore slots from the shared handle
626    // on drop - this is safe because the handle always contains valid slots.
627
628    let measured = builder.measure_node(root, normalize_constraints(constraints))?;
629
630    // Root node has no parent to place it, so we must explicitly place it at (0,0).
631    // This ensures is_placed=true, allowing the renderer to traverse the tree.
632    // Handle both LayoutNode and SubcomposeLayoutNode as potential roots.
633    if let Ok(mut applier) = applier_host.try_borrow_typed() {
634        if applier
635            .with_node::<LayoutNode, _>(root, |node| {
636                node.set_position(Point::default());
637            })
638            .is_err()
639        {
640            let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
641                node.set_position(Point::default());
642            });
643        }
644    }
645
646    // ---- Metadata ----------------------------------------------------------
647    let metadata = {
648        let mut applier_ref = applier_host.borrow_typed();
649        collect_runtime_metadata(&mut applier_ref, &measured)?
650    };
651
652    let semantics = if options.collect_semantics {
653        let semantics_snapshot = {
654            let mut applier_ref = applier_host.borrow_typed();
655            collect_semantics_snapshot(&mut applier_ref, &measured)?
656        };
657
658        Some(SemanticsTree::new(build_semantics_node(
659            &measured,
660            &metadata,
661            &semantics_snapshot,
662        )))
663    } else {
664        None
665    };
666
667    // Drop builder before guard - slots are already in the shared handle.
668    // Guard's Drop will write them back to the applier.
669    drop(builder);
670
671    // DO NOT manually unwrap `applier_host` or replace `applier` here.
672    // `ApplierSlotGuard::drop` will restore everything when this function returns.
673
674    let layout_tree = build_layout_tree_from_metadata(&measured, &metadata);
675
676    Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
677}
678
679struct LayoutBuilder {
680    state: Rc<RefCell<LayoutBuilderState>>,
681}
682
683impl LayoutBuilder {
684    fn new_with_epoch(
685        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
686        epoch: u64,
687        slots: Rc<RefCell<SlotBackend>>,
688    ) -> Self {
689        Self {
690            state: Rc::new(RefCell::new(LayoutBuilderState::new_with_epoch(
691                applier, epoch, slots,
692            ))),
693        }
694    }
695
696    fn measure_node(
697        &mut self,
698        node_id: NodeId,
699        constraints: Constraints,
700    ) -> Result<Rc<MeasuredNode>, NodeError> {
701        LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
702    }
703
704    fn set_runtime_handle(&mut self, handle: Option<RuntimeHandle>) {
705        self.state.borrow_mut().runtime_handle = handle;
706    }
707}
708
709struct LayoutBuilderState {
710    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
711    runtime_handle: Option<RuntimeHandle>,
712    /// Shared handle to the slot table. This is shared with ApplierSlotGuard
713    /// to ensure panic-safety: even if we panic, the guard can restore slots.
714    slots: Rc<RefCell<SlotBackend>>,
715    cache_epoch: u64,
716    tmp_measurables: ScratchVecPool<Box<dyn Measurable>>,
717    tmp_records: ScratchVecPool<(NodeId, ChildRecord)>,
718    tmp_child_ids: ScratchVecPool<NodeId>,
719    tmp_layout_node_data: ScratchVecPool<LayoutModifierNodeData>,
720}
721
722impl LayoutBuilderState {
723    fn new_with_epoch(
724        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
725        epoch: u64,
726        slots: Rc<RefCell<SlotBackend>>,
727    ) -> Self {
728        let runtime_handle = applier.borrow_typed().runtime_handle();
729
730        Self {
731            applier,
732            runtime_handle,
733            slots,
734            cache_epoch: epoch,
735            tmp_measurables: ScratchVecPool::default(),
736            tmp_records: ScratchVecPool::default(),
737            tmp_child_ids: ScratchVecPool::default(),
738            tmp_layout_node_data: ScratchVecPool::default(),
739        }
740    }
741
742    fn try_with_applier_result<R>(
743        state_rc: &Rc<RefCell<Self>>,
744        f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
745    ) -> Option<Result<R, NodeError>> {
746        let host = {
747            let state = state_rc.borrow();
748            Rc::clone(&state.applier)
749        };
750
751        // Try to borrow - if already borrowed (nested call), return None
752        let Ok(mut applier) = host.try_borrow_typed() else {
753            return None;
754        };
755
756        Some(f(&mut applier))
757    }
758
759    fn with_applier_result<R>(
760        state_rc: &Rc<RefCell<Self>>,
761        f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
762    ) -> Result<R, NodeError> {
763        Self::try_with_applier_result(state_rc, f).unwrap_or_else(|| {
764            Err(NodeError::MissingContext {
765                id: NodeId::default(),
766                reason: "applier already borrowed",
767            })
768        })
769    }
770
771    /// Clears the is_placed flag for a node at the start of measurement.
772    /// This ensures nodes that drop out of placement won't render with stale geometry.
773    fn clear_node_placed(state_rc: &Rc<RefCell<Self>>, node_id: NodeId) {
774        let host = {
775            let state = state_rc.borrow();
776            Rc::clone(&state.applier)
777        };
778        let Ok(mut applier) = host.try_borrow_typed() else {
779            return;
780        };
781        // Try LayoutNode first, then SubcomposeLayoutNode
782        if applier
783            .with_node::<LayoutNode, _>(node_id, |node| {
784                node.clear_placed();
785            })
786            .is_err()
787        {
788            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
789                node.clear_placed();
790            });
791        }
792    }
793
794    fn measure_node(
795        state_rc: Rc<RefCell<Self>>,
796        node_id: NodeId,
797        constraints: Constraints,
798    ) -> Result<Rc<MeasuredNode>, NodeError> {
799        // Clear is_placed at the start of measurement.
800        // Nodes that are placed will have is_placed set to true via Placeable::place().
801        // Nodes that drop out of placement (not placed this pass) will remain is_placed=false.
802        Self::clear_node_placed(&state_rc, node_id);
803
804        // Try SubcomposeLayoutNode first
805        if let Some(subcompose) =
806            Self::try_measure_subcompose(Rc::clone(&state_rc), node_id, constraints)?
807        {
808            return Ok(subcompose);
809        }
810
811        // Try LayoutNode (the primary modern path)
812        if let Some(result) = Self::try_with_applier_result(&state_rc, |applier| {
813            match applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
814                LayoutNodeSnapshot::from_layout_node(layout_node)
815            }) {
816                Ok(snapshot) => Ok(Some(snapshot)),
817                Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => Ok(None),
818                Err(err) => Err(err),
819            }
820        }) {
821            // Applier was available, process the result
822            if let Some(snapshot) = result? {
823                return Self::measure_layout_node(
824                    Rc::clone(&state_rc),
825                    node_id,
826                    snapshot,
827                    constraints,
828                );
829            }
830        }
831        // If applier was busy (None) or snapshot was None, fall through to fallback
832
833        // No alternate fallbacks - all widgets use LayoutNode or SubcomposeLayoutNode
834        // If we reach here, it's an unknown node type (shouldn't happen in normal use)
835        Ok(Rc::new(MeasuredNode::new(
836            node_id,
837            Size::default(),
838            Point { x: 0.0, y: 0.0 },
839            Point::default(), // No content offset for fallback nodes
840            Vec::new(),
841        )))
842    }
843
844    fn try_measure_subcompose(
845        state_rc: Rc<RefCell<Self>>,
846        node_id: NodeId,
847        constraints: Constraints,
848    ) -> Result<Option<Rc<MeasuredNode>>, NodeError> {
849        let applier_host = {
850            let state = state_rc.borrow();
851            Rc::clone(&state.applier)
852        };
853
854        let (node_handle, resolved_modifiers) = {
855            // Try to borrow - if already borrowed (nested measurement), return None
856            let Ok(mut applier) = applier_host.try_borrow_typed() else {
857                return Ok(None);
858            };
859            let node = match applier.get_mut(node_id) {
860                Ok(node) => node,
861                Err(NodeError::Missing { .. }) => return Ok(None),
862                Err(err) => return Err(err),
863            };
864            let any = node.as_any_mut();
865            if let Some(subcompose) =
866                any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
867            {
868                let handle = subcompose.handle();
869                let resolved_modifiers = handle.resolved_modifiers();
870                (handle, resolved_modifiers)
871            } else {
872                return Ok(None);
873            }
874        };
875
876        let runtime_handle = {
877            let mut state = state_rc.borrow_mut();
878            if state.runtime_handle.is_none() {
879                // Try to borrow - if already borrowed, we can't get runtime handle
880                if let Ok(applier) = applier_host.try_borrow_typed() {
881                    state.runtime_handle = applier.runtime_handle();
882                }
883            }
884            state
885                .runtime_handle
886                .clone()
887                .ok_or(NodeError::MissingContext {
888                    id: node_id,
889                    reason: "runtime handle required for subcomposition",
890                })?
891        };
892
893        let props = resolved_modifiers.layout_properties();
894        let padding = resolved_modifiers.padding();
895        let offset = resolved_modifiers.offset();
896        let mut inner_constraints = normalize_constraints(subtract_padding(constraints, padding));
897
898        if let DimensionConstraint::Points(width) = props.width() {
899            let constrained_width = width - padding.horizontal_sum();
900            inner_constraints.max_width = inner_constraints.max_width.min(constrained_width);
901            inner_constraints.min_width = inner_constraints.min_width.min(constrained_width);
902        }
903        if let DimensionConstraint::Points(height) = props.height() {
904            let constrained_height = height - padding.vertical_sum();
905            inner_constraints.max_height = inner_constraints.max_height.min(constrained_height);
906            inner_constraints.min_height = inner_constraints.min_height.min(constrained_height);
907        }
908
909        let mut slots_guard = SlotsGuard::take(Rc::clone(&state_rc));
910        let slots_host = slots_guard.host();
911        let applier_host_dyn: Rc<dyn ApplierHost> = applier_host.clone();
912        let observer = SnapshotStateObserver::new(|callback| callback());
913        let composer = Composer::new(
914            Rc::clone(&slots_host),
915            applier_host_dyn,
916            runtime_handle.clone(),
917            observer,
918            Some(node_id),
919        );
920        composer.enter_phase(Phase::Measure);
921
922        let state_rc_clone = Rc::clone(&state_rc);
923        let measure_error: Rc<RefCell<Option<NodeError>>> = Rc::new(RefCell::new(None));
924        let error_for_measurer = Rc::clone(&measure_error);
925        let state_rc_for_subcompose = Rc::clone(&state_rc_clone);
926        let error_for_subcompose = Rc::clone(&error_for_measurer);
927        let measured_children = Rc::new(RefCell::new(HashMap::default()));
928        let measured_children_for_subcompose = Rc::clone(&measured_children);
929
930        let measure_result = node_handle.measure(
931            &composer,
932            node_id,
933            inner_constraints,
934            Box::new(
935                move |child_id: NodeId, child_constraints: Constraints| -> Size {
936                    match Self::measure_node(
937                        Rc::clone(&state_rc_for_subcompose),
938                        child_id,
939                        child_constraints,
940                    ) {
941                        Ok(measured) => {
942                            measured_children_for_subcompose
943                                .borrow_mut()
944                                .insert(child_id, Rc::clone(&measured));
945                            measured.size
946                        }
947                        Err(err) => {
948                            let mut slot = error_for_subcompose.borrow_mut();
949                            if slot.is_none() {
950                                *slot = Some(err);
951                            }
952                            Size::default()
953                        }
954                    }
955                },
956            ),
957            Rc::clone(&measure_error),
958        )?;
959
960        slots_guard.restore(slots_host.take());
961
962        if let Some(err) = measure_error.borrow_mut().take() {
963            return Err(err);
964        }
965
966        // NOTE: Children are now managed by the composer via insert_child commands
967        // (from parent_stack initialization with root). set_active_children is no longer used.
968
969        let mut width = measure_result.size.width + padding.horizontal_sum();
970        let mut height = measure_result.size.height + padding.vertical_sum();
971
972        width = resolve_dimension(
973            width,
974            props.width(),
975            props.min_width(),
976            props.max_width(),
977            constraints.min_width,
978            constraints.max_width,
979        );
980        height = resolve_dimension(
981            height,
982            props.height(),
983            props.min_height(),
984            props.max_height(),
985            constraints.min_height,
986            constraints.max_height,
987        );
988
989        let mut children = Vec::with_capacity(measure_result.placements.len());
990        let mut measured_children_by_id = measured_children.borrow_mut();
991
992        // Update the SubcomposeLayoutNode's size (position will be set by parent's placement)
993        if let Ok(mut applier) = applier_host.try_borrow_typed() {
994            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |parent_node| {
995                parent_node.set_measured_size(Size { width, height });
996            });
997        }
998
999        for placement in measure_result.placements {
1000            let child = if let Some(measured) = measured_children_by_id.remove(&placement.node_id) {
1001                measured
1002            } else {
1003                // Policies may place subcomposed children without calling `measure()` first
1004                // (for example, when they only need a slot's rendered content). Keep the
1005                // existing fallback for that case, but preserve the policy-time measurement
1006                // whenever it exists so we don't silently remeasure lazy items with the
1007                // container's tighter constraints.
1008                Self::measure_node(Rc::clone(&state_rc), placement.node_id, inner_constraints)?
1009            };
1010            let position = Point {
1011                x: padding.left + placement.x,
1012                y: padding.top + placement.y,
1013            };
1014
1015            // Critical: Update the child LayoutNode's retained state.
1016            // Standard layouts do this via Placeable::place(), but SubcomposeLayout logic
1017            // bypasses Placeables and returns raw Placements.
1018            if let Ok(mut applier) = applier_host.try_borrow_typed() {
1019                let _ = applier.with_node::<LayoutNode, _>(placement.node_id, |node| {
1020                    node.set_position(position);
1021                });
1022            }
1023
1024            children.push(MeasuredChild {
1025                node: child,
1026                offset: position,
1027            });
1028        }
1029
1030        // Update the SubcomposeLayoutNode's active children for rendering
1031        node_handle.set_active_children(children.iter().map(|c| c.node.node_id));
1032
1033        Ok(Some(Rc::new(MeasuredNode::new(
1034            node_id,
1035            Size { width, height },
1036            offset,
1037            Point::default(), // Subcompose nodes: content_offset handled by child layout
1038            children,
1039        ))))
1040    }
1041    /// Measures through the layout modifier coordinator chain using reconciled modifier nodes.
1042    /// Iterates through LayoutModifierNode instances from the ModifierNodeChain and calls
1043    /// their measure() methods, mirroring Jetpack Compose's LayoutModifierNodeCoordinator pattern.
1044    ///
1045    /// Always succeeds, building a coordinator chain (possibly just InnerCoordinator) to measure.
1046    ///
1047    fn measure_through_modifier_chain(
1048        state_rc: &Rc<RefCell<Self>>,
1049        node_id: NodeId,
1050        measurables: &[Box<dyn Measurable>],
1051        measure_policy: &Rc<dyn MeasurePolicy>,
1052        constraints: Constraints,
1053        layout_node_data: &mut Vec<LayoutModifierNodeData>,
1054    ) -> ModifierChainMeasurement {
1055        use cranpose_foundation::NodeCapabilities;
1056
1057        // Collect layout node information from the modifier chain
1058        layout_node_data.clear();
1059        let mut offset = Point::default();
1060
1061        {
1062            let state = state_rc.borrow();
1063            let mut applier = state.applier.borrow_typed();
1064
1065            let _ = applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1066                let chain_handle = layout_node.modifier_chain();
1067
1068                if !chain_handle.has_layout_nodes() {
1069                    return;
1070                }
1071
1072                // Collect indices and node Rc clones for layout modifier nodes
1073                chain_handle.chain().for_each_forward_matching(
1074                    NodeCapabilities::LAYOUT,
1075                    |node_ref| {
1076                        if let Some(index) = node_ref.entry_index() {
1077                            // Get the Rc clone for this node
1078                            if let Some(node_rc) = chain_handle.chain().get_node_rc(index) {
1079                                layout_node_data.push((index, Rc::clone(&node_rc)));
1080                            }
1081
1082                            // Extract offset from OffsetNode for the node's own position
1083                            // The coordinator chain handles placement_offset (for children),
1084                            // but the node's offset affects where IT is positioned in the parent
1085                            node_ref.with_node(|node| {
1086                                if let Some(offset_node) =
1087                                    node.as_any()
1088                                        .downcast_ref::<crate::modifier_nodes::OffsetNode>()
1089                                {
1090                                    let delta = offset_node.offset();
1091                                    offset.x += delta.x;
1092                                    offset.y += delta.y;
1093                                }
1094                            });
1095                        }
1096                    },
1097                );
1098            });
1099        }
1100
1101        // Fast path: if there are no layout modifiers, measure directly without coordinator chain.
1102        // This saves 3 allocations (shared_context, policy_result, InnerCoordinator box).
1103        if layout_node_data.is_empty() {
1104            let result = measure_policy.measure(measurables, constraints);
1105            let final_size = result.size;
1106            let placements = result.placements;
1107
1108            return ModifierChainMeasurement {
1109                result: MeasureResult {
1110                    size: final_size,
1111                    placements,
1112                },
1113                content_offset: Point::default(),
1114                offset,
1115            };
1116        }
1117
1118        // Slow path: build coordinator chain for layout modifiers.
1119        // Popping from the end preserves the "rightmost modifier measures first" order
1120        // without allocating or cloning the collected node list.
1121        // Create a shared context for this measurement pass to track invalidations
1122        let shared_context = Rc::new(RefCell::new(LayoutNodeContext::new()));
1123
1124        // Create the inner coordinator that wraps the measure policy
1125        let policy_result = Rc::new(RefCell::new(None));
1126        let inner_coordinator: Box<dyn NodeCoordinator + '_> =
1127            Box::new(coordinator::InnerCoordinator::new(
1128                Rc::clone(measure_policy),
1129                measurables,
1130                Rc::clone(&policy_result),
1131            ));
1132
1133        // Wrap each layout modifier node in a coordinator, building the chain
1134        let mut current_coordinator = inner_coordinator;
1135        while let Some((_, node_rc)) = layout_node_data.pop() {
1136            current_coordinator = Box::new(coordinator::LayoutModifierCoordinator::new(
1137                node_rc,
1138                current_coordinator,
1139                Rc::clone(&shared_context),
1140            ));
1141        }
1142
1143        // Measure through the complete coordinator chain
1144        let placeable = current_coordinator.measure(constraints);
1145        let final_size = Size {
1146            width: placeable.width(),
1147            height: placeable.height(),
1148        };
1149
1150        // Get accumulated content offset from the placeable (computed during measure)
1151        let content_offset = placeable.content_offset();
1152        let all_placement_offset = Point {
1153            x: content_offset.0,
1154            y: content_offset.1,
1155        };
1156
1157        // The content_offset for scroll/inner transforms is the accumulated placement offset
1158        // MINUS the node's own offset (which affects its position in the parent, not content position).
1159        // This properly separates: node position (offset) vs inner content position (content_offset).
1160        let content_offset = Point {
1161            x: all_placement_offset.x - offset.x,
1162            y: all_placement_offset.y - offset.y,
1163        };
1164
1165        // offset was already extracted from OffsetNode above
1166
1167        let placements = policy_result
1168            .borrow_mut()
1169            .take()
1170            .map(|result| result.placements)
1171            .unwrap_or_default();
1172
1173        // Process any invalidations requested during measurement
1174        let invalidations = shared_context.borrow_mut().take_invalidations();
1175        if !invalidations.is_empty() {
1176            // Mark the LayoutNode as needing the appropriate passes
1177            Self::with_applier_result(state_rc, |applier| {
1178                applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1179                    for kind in invalidations {
1180                        match kind {
1181                            InvalidationKind::Layout => layout_node.mark_needs_measure(),
1182                            InvalidationKind::Draw => layout_node.mark_needs_redraw(),
1183                            InvalidationKind::Semantics => layout_node.mark_needs_semantics(),
1184                            InvalidationKind::PointerInput => layout_node.mark_needs_pointer_pass(),
1185                            InvalidationKind::Focus => layout_node.mark_needs_focus_sync(),
1186                        }
1187                    }
1188                })
1189            })
1190            .ok();
1191        }
1192
1193        ModifierChainMeasurement {
1194            result: MeasureResult {
1195                size: final_size,
1196                placements,
1197            },
1198            content_offset,
1199            offset,
1200        }
1201    }
1202
1203    fn measure_layout_node(
1204        state_rc: Rc<RefCell<Self>>,
1205        node_id: NodeId,
1206        snapshot: LayoutNodeSnapshot,
1207        constraints: Constraints,
1208    ) -> Result<Rc<MeasuredNode>, NodeError> {
1209        let cache_epoch = {
1210            let state = state_rc.borrow();
1211            state.cache_epoch
1212        };
1213        let LayoutNodeSnapshot {
1214            measure_policy,
1215            cache,
1216            needs_measure,
1217        } = snapshot;
1218        cache.activate(cache_epoch);
1219
1220        if needs_measure {
1221            // Node has needs_measure=true
1222        }
1223
1224        // Only check cache if not marked as needing measure.
1225        // When needs_measure=true, we MUST re-run measure() even if constraints match,
1226        // because something else changed (e.g., scroll offset, modifier state).
1227        if !needs_measure {
1228            // Check cache for current constraints
1229            if let Some(cached) = cache.get_measurement(constraints) {
1230                // Clear dirty flag after successful cache hit
1231                Self::with_applier_result(&state_rc, |applier| {
1232                    applier.with_node::<LayoutNode, _>(node_id, |node| {
1233                        node.clear_needs_measure();
1234                        node.clear_needs_layout();
1235                    })
1236                })
1237                .ok();
1238                return Ok(cached);
1239            }
1240        }
1241
1242        let (runtime_handle, applier_host) = {
1243            let state = state_rc.borrow();
1244            (state.runtime_handle.clone(), Rc::clone(&state.applier))
1245        };
1246
1247        let measure_handle = LayoutMeasureHandle::new(Rc::clone(&state_rc));
1248        let error = Rc::new(RefCell::new(None));
1249        let mut pools = VecPools::acquire(Rc::clone(&state_rc));
1250        let (measurables, records, child_ids, layout_node_data) = pools.parts();
1251
1252        applier_host
1253            .borrow_typed()
1254            .with_node::<LayoutNode, _>(node_id, |node| {
1255                child_ids.extend_from_slice(&node.children);
1256            })?;
1257
1258        for &child_id in child_ids.iter() {
1259            let measured = Rc::new(RefCell::new(None));
1260            let position = Rc::new(RefCell::new(None));
1261
1262            let data = {
1263                let mut applier = applier_host.borrow_typed();
1264                match applier.with_node::<LayoutNode, _>(child_id, |n| {
1265                    (n.cache_handles(), n.layout_state_handle())
1266                }) {
1267                    Ok((cache, state)) => Some((cache, Some(state))),
1268                    Err(NodeError::TypeMismatch { .. }) => {
1269                        Some((LayoutNodeCacheHandles::default(), None))
1270                    }
1271                    Err(NodeError::Missing { .. }) => None,
1272                    Err(err) => return Err(err),
1273                }
1274            };
1275
1276            let Some((cache_handles, layout_state)) = data else {
1277                continue;
1278            };
1279
1280            cache_handles.activate(cache_epoch);
1281
1282            records.push((
1283                child_id,
1284                ChildRecord {
1285                    measured: Rc::clone(&measured),
1286                    last_position: Rc::clone(&position),
1287                },
1288            ));
1289            measurables.push(Box::new(LayoutChildMeasurable::new(
1290                Rc::clone(&applier_host),
1291                child_id,
1292                measured,
1293                position,
1294                Rc::clone(&error),
1295                runtime_handle.clone(),
1296                cache_handles,
1297                cache_epoch,
1298                Some(measure_handle.clone()),
1299                layout_state,
1300            )));
1301        }
1302
1303        let chain_constraints = constraints;
1304
1305        let modifier_chain_result = Self::measure_through_modifier_chain(
1306            &state_rc,
1307            node_id,
1308            measurables.as_slice(),
1309            &measure_policy,
1310            chain_constraints,
1311            layout_node_data,
1312        );
1313
1314        // Modifier chain always succeeds - use the node-driven measurement.
1315        let (width, height, policy_result, content_offset, offset) = {
1316            let result = modifier_chain_result;
1317            // The size is already correct from the modifier chain (modifiers like SizeNode
1318            // have already enforced their constraints), so we use it directly.
1319            if let Some(err) = error.borrow_mut().take() {
1320                return Err(err);
1321            }
1322
1323            (
1324                result.result.size.width,
1325                result.result.size.height,
1326                result.result,
1327                result.content_offset,
1328                result.offset,
1329            )
1330        };
1331
1332        let mut measured_children = Vec::with_capacity(records.len());
1333        for (child_id, record) in records.iter() {
1334            if let Some(measured) = record.measured.borrow_mut().take() {
1335                let base_position = policy_result
1336                    .placements
1337                    .iter()
1338                    .find(|placement| placement.node_id == *child_id)
1339                    .map(|placement| Point {
1340                        x: placement.x,
1341                        y: placement.y,
1342                    })
1343                    .or_else(|| record.last_position.borrow().as_ref().copied())
1344                    .unwrap_or(Point { x: 0.0, y: 0.0 });
1345                // Apply content_offset (from scroll/transforms) to child positioning
1346                let position = Point {
1347                    x: content_offset.x + base_position.x,
1348                    y: content_offset.y + base_position.y,
1349                };
1350                measured_children.push(MeasuredChild {
1351                    node: measured,
1352                    offset: position,
1353                });
1354            }
1355        }
1356
1357        let measured = Rc::new(MeasuredNode::new(
1358            node_id,
1359            Size { width, height },
1360            offset,
1361            content_offset,
1362            measured_children,
1363        ));
1364
1365        cache.store_measurement(constraints, Rc::clone(&measured));
1366
1367        // Clear dirty flags and update derived state
1368        Self::with_applier_result(&state_rc, |applier| {
1369            applier.with_node::<LayoutNode, _>(node_id, |node| {
1370                node.clear_needs_measure();
1371                node.clear_needs_layout();
1372                node.set_measured_size(Size { width, height });
1373                node.set_content_offset(content_offset);
1374            })
1375        })
1376        .ok();
1377
1378        Ok(measured)
1379    }
1380}
1381
1382/// Snapshot of a LayoutNode's data for measuring.
1383/// This is a temporary copy used during the measure phase, not a live node.
1384///
1385/// Note: We capture `needs_measure` here because it's checked during measure to enable
1386/// selective measure optimization at the individual node level. Even if the tree is partially
1387/// dirty (some nodes changed), clean nodes can skip measure and use cached results.
1388struct LayoutNodeSnapshot {
1389    measure_policy: Rc<dyn MeasurePolicy>,
1390    cache: LayoutNodeCacheHandles,
1391    /// Whether this specific node needs to be measured (vs using cached measurement)
1392    needs_measure: bool,
1393}
1394
1395impl LayoutNodeSnapshot {
1396    fn from_layout_node(node: &LayoutNode) -> Self {
1397        Self {
1398            measure_policy: Rc::clone(&node.measure_policy),
1399            cache: node.cache_handles(),
1400            needs_measure: node.needs_measure(),
1401        }
1402    }
1403}
1404
1405// Helper types for accessing subsets of LayoutBuilderState
1406struct VecPools {
1407    state: Rc<RefCell<LayoutBuilderState>>,
1408    measurables: Option<Vec<Box<dyn Measurable>>>,
1409    records: Option<Vec<(NodeId, ChildRecord)>>,
1410    child_ids: Option<Vec<NodeId>>,
1411    layout_node_data: Option<Vec<LayoutModifierNodeData>>,
1412}
1413
1414impl VecPools {
1415    fn acquire(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
1416        let (measurables, records, child_ids, layout_node_data) = {
1417            let mut state_mut = state.borrow_mut();
1418            (
1419                state_mut.tmp_measurables.acquire(),
1420                state_mut.tmp_records.acquire(),
1421                state_mut.tmp_child_ids.acquire(),
1422                state_mut.tmp_layout_node_data.acquire(),
1423            )
1424        };
1425        Self {
1426            state,
1427            measurables: Some(measurables),
1428            records: Some(records),
1429            child_ids: Some(child_ids),
1430            layout_node_data: Some(layout_node_data),
1431        }
1432    }
1433
1434    #[allow(clippy::type_complexity)] // Returns internal Vec references for layout operations
1435    fn parts(
1436        &mut self,
1437    ) -> (
1438        &mut Vec<Box<dyn Measurable>>,
1439        &mut Vec<(NodeId, ChildRecord)>,
1440        &mut Vec<NodeId>,
1441        &mut Vec<LayoutModifierNodeData>,
1442    ) {
1443        let measurables = self
1444            .measurables
1445            .as_mut()
1446            .expect("measurables already returned");
1447        let records = self.records.as_mut().expect("records already returned");
1448        let child_ids = self.child_ids.as_mut().expect("child_ids already returned");
1449        let layout_node_data = self
1450            .layout_node_data
1451            .as_mut()
1452            .expect("layout_node_data already returned");
1453        (measurables, records, child_ids, layout_node_data)
1454    }
1455}
1456
1457impl Drop for VecPools {
1458    fn drop(&mut self) {
1459        let mut state = self.state.borrow_mut();
1460        if let Some(measurables) = self.measurables.take() {
1461            state.tmp_measurables.release(measurables);
1462        }
1463        if let Some(records) = self.records.take() {
1464            state.tmp_records.release(records);
1465        }
1466        if let Some(child_ids) = self.child_ids.take() {
1467            state.tmp_child_ids.release(child_ids);
1468        }
1469        if let Some(layout_node_data) = self.layout_node_data.take() {
1470            state.tmp_layout_node_data.release(layout_node_data);
1471        }
1472    }
1473}
1474
1475struct SlotsGuard {
1476    state: Rc<RefCell<LayoutBuilderState>>,
1477    slots: Option<SlotBackend>,
1478}
1479
1480impl SlotsGuard {
1481    fn take(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
1482        let slots = {
1483            let state_ref = state.borrow();
1484            let mut slots_ref = state_ref.slots.borrow_mut();
1485            std::mem::take(&mut *slots_ref)
1486        };
1487        Self {
1488            state,
1489            slots: Some(slots),
1490        }
1491    }
1492
1493    fn host(&mut self) -> Rc<SlotsHost> {
1494        let slots = self.slots.take().unwrap_or_default();
1495        Rc::new(SlotsHost::new(slots))
1496    }
1497
1498    fn restore(&mut self, slots: SlotBackend) {
1499        debug_assert!(self.slots.is_none());
1500        self.slots = Some(slots);
1501    }
1502}
1503
1504impl Drop for SlotsGuard {
1505    fn drop(&mut self) {
1506        if let Some(slots) = self.slots.take() {
1507            let state_ref = self.state.borrow();
1508            *state_ref.slots.borrow_mut() = slots;
1509        }
1510    }
1511}
1512
1513#[derive(Clone)]
1514struct LayoutMeasureHandle {
1515    state: Rc<RefCell<LayoutBuilderState>>,
1516}
1517
1518impl LayoutMeasureHandle {
1519    fn new(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
1520        Self { state }
1521    }
1522
1523    fn measure(
1524        &self,
1525        node_id: NodeId,
1526        constraints: Constraints,
1527    ) -> Result<Rc<MeasuredNode>, NodeError> {
1528        LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
1529    }
1530}
1531
1532#[derive(Debug, Clone)]
1533pub(crate) struct MeasuredNode {
1534    node_id: NodeId,
1535    size: Size,
1536    /// Node's position offset relative to parent (from OffsetNode etc.)
1537    offset: Point,
1538    /// Content offset for scroll/inner transforms (NOT node position)
1539    content_offset: Point,
1540    children: Vec<MeasuredChild>,
1541}
1542
1543impl MeasuredNode {
1544    fn new(
1545        node_id: NodeId,
1546        size: Size,
1547        offset: Point,
1548        content_offset: Point,
1549        children: Vec<MeasuredChild>,
1550    ) -> Self {
1551        Self {
1552            node_id,
1553            size,
1554            offset,
1555            content_offset,
1556            children,
1557        }
1558    }
1559}
1560
1561#[derive(Debug, Clone)]
1562struct MeasuredChild {
1563    node: Rc<MeasuredNode>,
1564    offset: Point,
1565}
1566
1567struct ChildRecord {
1568    measured: Rc<RefCell<Option<Rc<MeasuredNode>>>>,
1569    last_position: Rc<RefCell<Option<Point>>>,
1570}
1571
1572struct LayoutChildMeasurable {
1573    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1574    node_id: NodeId,
1575    measured: Rc<RefCell<Option<Rc<MeasuredNode>>>>,
1576    last_position: Rc<RefCell<Option<Point>>>,
1577    error: Rc<RefCell<Option<NodeError>>>,
1578    runtime_handle: Option<RuntimeHandle>,
1579    cache: LayoutNodeCacheHandles,
1580    cache_epoch: u64,
1581    measure_handle: Option<LayoutMeasureHandle>,
1582    layout_state: Option<Rc<RefCell<crate::widgets::nodes::layout_node::LayoutState>>>,
1583}
1584
1585impl LayoutChildMeasurable {
1586    #[allow(clippy::too_many_arguments)] // Constructor needs all layout state for child measurement
1587    fn new(
1588        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1589        node_id: NodeId,
1590        measured: Rc<RefCell<Option<Rc<MeasuredNode>>>>,
1591        last_position: Rc<RefCell<Option<Point>>>,
1592        error: Rc<RefCell<Option<NodeError>>>,
1593        runtime_handle: Option<RuntimeHandle>,
1594        cache: LayoutNodeCacheHandles,
1595        cache_epoch: u64,
1596        measure_handle: Option<LayoutMeasureHandle>,
1597        layout_state: Option<Rc<RefCell<crate::widgets::nodes::layout_node::LayoutState>>>,
1598    ) -> Self {
1599        cache.activate(cache_epoch);
1600        Self {
1601            applier,
1602            node_id,
1603            measured,
1604            last_position,
1605            error,
1606            runtime_handle,
1607            cache,
1608            cache_epoch,
1609            measure_handle,
1610            layout_state,
1611        }
1612    }
1613
1614    fn record_error(&self, err: NodeError) {
1615        let mut slot = self.error.borrow_mut();
1616        if slot.is_none() {
1617            *slot = Some(err);
1618        }
1619    }
1620
1621    fn perform_measure(&self, constraints: Constraints) -> Result<Rc<MeasuredNode>, NodeError> {
1622        if let Some(handle) = &self.measure_handle {
1623            handle.measure(self.node_id, constraints)
1624        } else {
1625            measure_node_with_host(
1626                Rc::clone(&self.applier),
1627                self.runtime_handle.clone(),
1628                self.node_id,
1629                constraints,
1630                self.cache_epoch,
1631            )
1632        }
1633    }
1634
1635    fn intrinsic_measure(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
1636        self.cache.activate(self.cache_epoch);
1637        if let Some(cached) = self.cache.get_measurement(constraints) {
1638            return Some(cached);
1639        }
1640
1641        match self.perform_measure(constraints) {
1642            Ok(measured) => {
1643                self.cache
1644                    .store_measurement(constraints, Rc::clone(&measured));
1645                Some(measured)
1646            }
1647            Err(err) => {
1648                self.record_error(err);
1649                None
1650            }
1651        }
1652    }
1653}
1654
1655impl Measurable for LayoutChildMeasurable {
1656    fn measure(&self, constraints: Constraints) -> Placeable {
1657        self.cache.activate(self.cache_epoch);
1658        let measured_size;
1659        if let Some(cached) = self.cache.get_measurement(constraints) {
1660            measured_size = cached.size;
1661            *self.measured.borrow_mut() = Some(Rc::clone(&cached));
1662        } else {
1663            match self.perform_measure(constraints) {
1664                Ok(measured) => {
1665                    measured_size = measured.size;
1666                    self.cache
1667                        .store_measurement(constraints, Rc::clone(&measured));
1668                    *self.measured.borrow_mut() = Some(measured);
1669                }
1670                Err(err) => {
1671                    self.record_error(err);
1672                    self.measured.borrow_mut().take();
1673                    measured_size = Size {
1674                        width: 0.0,
1675                        height: 0.0,
1676                    };
1677                }
1678            }
1679        }
1680
1681        // Update retained LayoutNode state with measured size (new architecture).
1682        // PRIORITIZE direct handle to avoid Applier borrow conflicts during layout!
1683        if let Some(state) = &self.layout_state {
1684            let mut state = state.borrow_mut();
1685            state.size = measured_size;
1686            state.measurement_constraints = constraints;
1687        } else if let Ok(mut applier) = self.applier.try_borrow_typed() {
1688            let _ = applier.with_node::<LayoutNode, _>(self.node_id, |node| {
1689                node.set_measured_size(measured_size);
1690                node.set_measurement_constraints(constraints);
1691            });
1692        }
1693
1694        // Build the place closure that captures all state needed for placement
1695        let applier = Rc::clone(&self.applier);
1696        let node_id = self.node_id;
1697        let measured = Rc::clone(&self.measured);
1698        let last_position = Rc::clone(&self.last_position);
1699        let layout_state = self.layout_state.clone();
1700
1701        let place_fn = Rc::new(move |x: f32, y: f32| {
1702            // Retrieve the node's own offset (from modifiers like offset(), padding(), etc.)
1703            let internal_offset = measured
1704                .borrow()
1705                .as_ref()
1706                .map(|m| m.offset)
1707                .unwrap_or_default();
1708
1709            let position = Point {
1710                x: x + internal_offset.x,
1711                y: y + internal_offset.y,
1712            };
1713            *last_position.borrow_mut() = Some(position);
1714
1715            // Update retained LayoutNode state
1716            if let Some(state) = &layout_state {
1717                let mut state = state.borrow_mut();
1718                state.position = position;
1719                state.is_placed = true;
1720            } else if let Ok(mut applier) = applier.try_borrow_typed() {
1721                if applier
1722                    .with_node::<LayoutNode, _>(node_id, |node| {
1723                        node.set_position(position);
1724                    })
1725                    .is_err()
1726                {
1727                    let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1728                        node.set_position(position);
1729                    });
1730                }
1731            }
1732        });
1733
1734        Placeable::with_place_fn(
1735            measured_size.width,
1736            measured_size.height,
1737            self.node_id,
1738            place_fn,
1739        )
1740    }
1741
1742    fn min_intrinsic_width(&self, height: f32) -> f32 {
1743        let kind = IntrinsicKind::MinWidth(height);
1744        self.cache.activate(self.cache_epoch);
1745        if let Some(value) = self.cache.get_intrinsic(&kind) {
1746            return value;
1747        }
1748        let constraints = Constraints {
1749            min_width: 0.0,
1750            max_width: f32::INFINITY,
1751            min_height: height,
1752            max_height: height,
1753        };
1754        if let Some(node) = self.intrinsic_measure(constraints) {
1755            let value = node.size.width;
1756            self.cache.store_intrinsic(kind, value);
1757            value
1758        } else {
1759            0.0
1760        }
1761    }
1762
1763    fn max_intrinsic_width(&self, height: f32) -> f32 {
1764        let kind = IntrinsicKind::MaxWidth(height);
1765        self.cache.activate(self.cache_epoch);
1766        if let Some(value) = self.cache.get_intrinsic(&kind) {
1767            return value;
1768        }
1769        let constraints = Constraints {
1770            min_width: 0.0,
1771            max_width: f32::INFINITY,
1772            min_height: 0.0,
1773            max_height: height,
1774        };
1775        if let Some(node) = self.intrinsic_measure(constraints) {
1776            let value = node.size.width;
1777            self.cache.store_intrinsic(kind, value);
1778            value
1779        } else {
1780            0.0
1781        }
1782    }
1783
1784    fn min_intrinsic_height(&self, width: f32) -> f32 {
1785        let kind = IntrinsicKind::MinHeight(width);
1786        self.cache.activate(self.cache_epoch);
1787        if let Some(value) = self.cache.get_intrinsic(&kind) {
1788            return value;
1789        }
1790        let constraints = Constraints {
1791            min_width: width,
1792            max_width: width,
1793            min_height: 0.0,
1794            max_height: f32::INFINITY,
1795        };
1796        if let Some(node) = self.intrinsic_measure(constraints) {
1797            let value = node.size.height;
1798            self.cache.store_intrinsic(kind, value);
1799            value
1800        } else {
1801            0.0
1802        }
1803    }
1804
1805    fn max_intrinsic_height(&self, width: f32) -> f32 {
1806        let kind = IntrinsicKind::MaxHeight(width);
1807        self.cache.activate(self.cache_epoch);
1808        if let Some(value) = self.cache.get_intrinsic(&kind) {
1809            return value;
1810        }
1811        let constraints = Constraints {
1812            min_width: 0.0,
1813            max_width: width,
1814            min_height: 0.0,
1815            max_height: f32::INFINITY,
1816        };
1817        if let Some(node) = self.intrinsic_measure(constraints) {
1818            let value = node.size.height;
1819            self.cache.store_intrinsic(kind, value);
1820            value
1821        } else {
1822            0.0
1823        }
1824    }
1825
1826    fn flex_parent_data(&self) -> Option<cranpose_ui_layout::FlexParentData> {
1827        // Try to borrow the applier - if it's already borrowed (nested measurement), return None.
1828        // This is safe because parent data doesn't change during measurement.
1829        let Ok(mut applier) = self.applier.try_borrow_typed() else {
1830            return None;
1831        };
1832
1833        applier
1834            .with_node::<LayoutNode, _>(self.node_id, |layout_node| {
1835                let props = layout_node.resolved_modifiers().layout_properties();
1836                props.weight().map(|weight_data| {
1837                    cranpose_ui_layout::FlexParentData::new(weight_data.weight, weight_data.fill)
1838                })
1839            })
1840            .ok()
1841            .flatten()
1842    }
1843}
1844
1845fn measure_node_with_host(
1846    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1847    runtime_handle: Option<RuntimeHandle>,
1848    node_id: NodeId,
1849    constraints: Constraints,
1850    epoch: u64,
1851) -> Result<Rc<MeasuredNode>, NodeError> {
1852    let runtime_handle = match runtime_handle {
1853        Some(handle) => Some(handle),
1854        None => applier.borrow_typed().runtime_handle(),
1855    };
1856    let mut builder = LayoutBuilder::new_with_epoch(
1857        applier,
1858        epoch,
1859        Rc::new(RefCell::new(SlotBackend::default())),
1860    );
1861    builder.set_runtime_handle(runtime_handle);
1862    builder.measure_node(node_id, constraints)
1863}
1864
1865#[derive(Clone)]
1866struct RuntimeNodeMetadata {
1867    modifier: Modifier,
1868    resolved_modifiers: ResolvedModifiers,
1869    modifier_slices: Rc<ModifierNodeSlices>,
1870    role: SemanticsRole,
1871    button_handler: Option<Rc<RefCell<dyn FnMut()>>>,
1872}
1873
1874impl Default for RuntimeNodeMetadata {
1875    fn default() -> Self {
1876        Self {
1877            modifier: Modifier::empty(),
1878            resolved_modifiers: ResolvedModifiers::default(),
1879            modifier_slices: Rc::default(),
1880            role: SemanticsRole::Unknown,
1881            button_handler: None,
1882        }
1883    }
1884}
1885
1886fn collect_runtime_metadata(
1887    applier: &mut MemoryApplier,
1888    node: &MeasuredNode,
1889) -> Result<HashMap<NodeId, RuntimeNodeMetadata>, NodeError> {
1890    let mut map = HashMap::default();
1891    collect_runtime_metadata_inner(applier, node, &mut map)?;
1892    Ok(map)
1893}
1894
1895/// Collects semantics configurations for all nodes in the measured tree using the SemanticsOwner cache.
1896fn collect_semantics_with_owner(
1897    applier: &mut MemoryApplier,
1898    node: &MeasuredNode,
1899    owner: &SemanticsOwner,
1900) -> Result<(), NodeError> {
1901    // Compute and cache configuration for this node
1902    owner.get_or_compute(node.node_id, applier);
1903
1904    // Recurse to children
1905    for child in &node.children {
1906        collect_semantics_with_owner(applier, &child.node, owner)?;
1907    }
1908    Ok(())
1909}
1910
1911fn collect_semantics_snapshot(
1912    applier: &mut MemoryApplier,
1913    node: &MeasuredNode,
1914) -> Result<HashMap<NodeId, Option<SemanticsConfiguration>>, NodeError> {
1915    let owner = SemanticsOwner::new();
1916    collect_semantics_with_owner(applier, node, &owner)?;
1917
1918    // Extract all cached configurations into a map
1919    let mut map = HashMap::default();
1920    extract_configurations_recursive(node, &owner, &mut map);
1921    Ok(map)
1922}
1923
1924fn extract_configurations_recursive(
1925    node: &MeasuredNode,
1926    owner: &SemanticsOwner,
1927    map: &mut HashMap<NodeId, Option<SemanticsConfiguration>>,
1928) {
1929    if let Some(config) = owner.configurations.borrow().get(&node.node_id) {
1930        map.insert(node.node_id, config.clone());
1931    }
1932    for child in &node.children {
1933        extract_configurations_recursive(&child.node, owner, map);
1934    }
1935}
1936
1937fn collect_runtime_metadata_inner(
1938    applier: &mut MemoryApplier,
1939    node: &MeasuredNode,
1940    map: &mut HashMap<NodeId, RuntimeNodeMetadata>,
1941) -> Result<(), NodeError> {
1942    if let Entry::Vacant(entry) = map.entry(node.node_id) {
1943        let meta = runtime_metadata_for(applier, node.node_id)?;
1944        entry.insert(meta);
1945    }
1946    for child in &node.children {
1947        collect_runtime_metadata_inner(applier, &child.node, map)?;
1948    }
1949    Ok(())
1950}
1951
1952fn role_from_modifier_slices(modifier_slices: &ModifierNodeSlices) -> SemanticsRole {
1953    modifier_slices
1954        .text_content()
1955        .map(|text| SemanticsRole::Text {
1956            value: text.to_string(),
1957        })
1958        .unwrap_or(SemanticsRole::Layout)
1959}
1960
1961fn runtime_metadata_for(
1962    applier: &mut MemoryApplier,
1963    node_id: NodeId,
1964) -> Result<RuntimeNodeMetadata, NodeError> {
1965    // Try LayoutNode (the primary modern path)
1966    // IMPORTANT: We use with_node (reference) instead of try_clone because cloning
1967    // LayoutNode creates a NEW ModifierChainHandle with NEW nodes and NEW handlers,
1968    // which would lose gesture state like press_position.
1969    if let Ok(meta) = applier.with_node::<LayoutNode, _>(node_id, |layout| {
1970        let modifier = layout.modifier.clone();
1971        let resolved_modifiers = layout.resolved_modifiers();
1972        let modifier_slices = layout.modifier_slices_snapshot();
1973        let role = role_from_modifier_slices(&modifier_slices);
1974
1975        RuntimeNodeMetadata {
1976            modifier,
1977            resolved_modifiers,
1978            modifier_slices,
1979            role,
1980            button_handler: None,
1981        }
1982    }) {
1983        return Ok(meta);
1984    }
1985
1986    // Try SubcomposeLayoutNode
1987    if let Ok((modifier, resolved_modifiers, modifier_slices)) = applier
1988        .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1989            (
1990                node.modifier(),
1991                node.resolved_modifiers(),
1992                node.modifier_slices_snapshot(),
1993            )
1994        })
1995    {
1996        return Ok(RuntimeNodeMetadata {
1997            modifier,
1998            resolved_modifiers,
1999            modifier_slices,
2000            role: SemanticsRole::Subcompose,
2001            button_handler: None,
2002        });
2003    }
2004    Ok(RuntimeNodeMetadata::default())
2005}
2006
2007/// Computes semantics configuration for a node by reading from its modifier chain.
2008/// This is the primary entry point for extracting semantics from nodes, replacing
2009/// the widget-specific fallbacks with pure modifier-node traversal.
2010fn compute_semantics_for_node(
2011    applier: &mut MemoryApplier,
2012    node_id: NodeId,
2013) -> Option<SemanticsConfiguration> {
2014    // Try LayoutNode (the primary modern path)
2015    match applier.with_node::<LayoutNode, _>(node_id, |layout| {
2016        let config = layout.semantics_configuration();
2017        layout.clear_needs_semantics();
2018        config
2019    }) {
2020        Ok(config) => return config,
2021        Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {}
2022        Err(_) => return None,
2023    }
2024
2025    // Try SubcomposeLayoutNode
2026    if let Ok(modifier) =
2027        applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| node.modifier())
2028    {
2029        return collect_semantics_from_modifier(&modifier);
2030    }
2031
2032    None
2033}
2034
2035/// Builds a semantics node from measured tree data and semantics configurations.
2036/// Roles and actions are now derived entirely from SemanticsConfiguration, with
2037/// metadata consulted only for prior widget type information.
2038fn build_semantics_node(
2039    node: &MeasuredNode,
2040    metadata: &HashMap<NodeId, RuntimeNodeMetadata>,
2041    semantics: &HashMap<NodeId, Option<SemanticsConfiguration>>,
2042) -> SemanticsNode {
2043    let info = metadata.get(&node.node_id).cloned().unwrap_or_default();
2044
2045    // Start with the widget-derived role as a fallback
2046    let mut role = info.role.clone();
2047    let mut actions = Vec::new();
2048    let mut description = None;
2049
2050    // Override with semantics configuration if present
2051    if let Some(config) = semantics.get(&node.node_id).cloned().flatten() {
2052        // Role synthesis: prefer semantics flags over widget type
2053        if config.is_button {
2054            role = SemanticsRole::Button;
2055        }
2056
2057        // Action synthesis: create click action if node is clickable
2058        if config.is_clickable {
2059            actions.push(SemanticsAction::Click {
2060                handler: SemanticsCallback::new(node.node_id),
2061            });
2062        }
2063
2064        // Description from configuration
2065        if let Some(desc) = config.content_description {
2066            description = Some(desc);
2067        }
2068    }
2069
2070    let children = node
2071        .children
2072        .iter()
2073        .map(|child| build_semantics_node(&child.node, metadata, semantics))
2074        .collect();
2075
2076    SemanticsNode::new(node.node_id, role, actions, children, description)
2077}
2078
2079fn build_layout_tree_from_metadata(
2080    node: &MeasuredNode,
2081    metadata: &HashMap<NodeId, RuntimeNodeMetadata>,
2082) -> LayoutTree {
2083    fn place(
2084        node: &MeasuredNode,
2085        origin: Point,
2086        metadata: &HashMap<NodeId, RuntimeNodeMetadata>,
2087    ) -> LayoutBox {
2088        // Include the node's own offset (from OffsetNode) in its position
2089        let top_left = Point {
2090            x: origin.x + node.offset.x,
2091            y: origin.y + node.offset.y,
2092        };
2093        let rect = GeometryRect {
2094            x: top_left.x,
2095            y: top_left.y,
2096            width: node.size.width,
2097            height: node.size.height,
2098        };
2099        let info = metadata.get(&node.node_id).cloned().unwrap_or_default();
2100        let kind = layout_kind_from_metadata(node.node_id, &info);
2101        let data = LayoutNodeData::new(
2102            info.modifier.clone(),
2103            info.resolved_modifiers,
2104            info.modifier_slices.clone(),
2105            kind,
2106        );
2107        let children = node
2108            .children
2109            .iter()
2110            .map(|child| {
2111                let child_origin = Point {
2112                    x: top_left.x + child.offset.x,
2113                    y: top_left.y + child.offset.y,
2114                };
2115                place(&child.node, child_origin, metadata)
2116            })
2117            .collect();
2118        LayoutBox::new(node.node_id, rect, node.content_offset, data, children)
2119    }
2120
2121    LayoutTree::new(place(node, Point { x: 0.0, y: 0.0 }, metadata))
2122}
2123
2124fn layout_kind_from_metadata(_node_id: NodeId, info: &RuntimeNodeMetadata) -> LayoutNodeKind {
2125    match &info.role {
2126        SemanticsRole::Layout => LayoutNodeKind::Layout,
2127        SemanticsRole::Subcompose => LayoutNodeKind::Subcompose,
2128        SemanticsRole::Text { .. } => {
2129            // Text content is now handled via TextModifierNode in the modifier chain
2130            // and collected in modifier_slices.text_content(). LayoutNodeKind should
2131            // reflect the layout policy (EmptyMeasurePolicy), not the content type.
2132            LayoutNodeKind::Layout
2133        }
2134        SemanticsRole::Spacer => LayoutNodeKind::Spacer,
2135        SemanticsRole::Button => {
2136            let handler = info
2137                .button_handler
2138                .as_ref()
2139                .cloned()
2140                .unwrap_or_else(|| Rc::new(RefCell::new(|| {})));
2141            LayoutNodeKind::Button { on_click: handler }
2142        }
2143        SemanticsRole::Unknown => LayoutNodeKind::Unknown,
2144    }
2145}
2146
2147fn subtract_padding(constraints: Constraints, padding: EdgeInsets) -> Constraints {
2148    let horizontal = padding.horizontal_sum();
2149    let vertical = padding.vertical_sum();
2150    let min_width = (constraints.min_width - horizontal).max(0.0);
2151    let mut max_width = constraints.max_width;
2152    if max_width.is_finite() {
2153        max_width = (max_width - horizontal).max(0.0);
2154    }
2155    let min_height = (constraints.min_height - vertical).max(0.0);
2156    let mut max_height = constraints.max_height;
2157    if max_height.is_finite() {
2158        max_height = (max_height - vertical).max(0.0);
2159    }
2160    normalize_constraints(Constraints {
2161        min_width,
2162        max_width,
2163        min_height,
2164        max_height,
2165    })
2166}
2167
2168#[cfg(test)]
2169pub(crate) fn align_horizontal(alignment: HorizontalAlignment, available: f32, child: f32) -> f32 {
2170    match alignment {
2171        HorizontalAlignment::Start => 0.0,
2172        HorizontalAlignment::CenterHorizontally => ((available - child) / 2.0).max(0.0),
2173        HorizontalAlignment::End => (available - child).max(0.0),
2174    }
2175}
2176
2177#[cfg(test)]
2178pub(crate) fn align_vertical(alignment: VerticalAlignment, available: f32, child: f32) -> f32 {
2179    match alignment {
2180        VerticalAlignment::Top => 0.0,
2181        VerticalAlignment::CenterVertically => ((available - child) / 2.0).max(0.0),
2182        VerticalAlignment::Bottom => (available - child).max(0.0),
2183    }
2184}
2185
2186fn resolve_dimension(
2187    base: f32,
2188    explicit: DimensionConstraint,
2189    min_override: Option<f32>,
2190    max_override: Option<f32>,
2191    min_limit: f32,
2192    max_limit: f32,
2193) -> f32 {
2194    let mut min_bound = min_limit;
2195    if let Some(min_value) = min_override {
2196        min_bound = min_bound.max(min_value);
2197    }
2198
2199    let mut max_bound = if max_limit.is_finite() {
2200        max_limit
2201    } else {
2202        max_override.unwrap_or(max_limit)
2203    };
2204    if let Some(max_value) = max_override {
2205        if max_bound.is_finite() {
2206            max_bound = max_bound.min(max_value);
2207        } else {
2208            max_bound = max_value;
2209        }
2210    }
2211    if max_bound < min_bound {
2212        max_bound = min_bound;
2213    }
2214
2215    let mut size = match explicit {
2216        DimensionConstraint::Points(points) => points,
2217        DimensionConstraint::Fraction(fraction) => {
2218            if max_limit.is_finite() {
2219                max_limit * fraction.clamp(0.0, 1.0)
2220            } else {
2221                base
2222            }
2223        }
2224        DimensionConstraint::Unspecified => base,
2225        // Intrinsic sizing is resolved at a higher level where we have access to children.
2226        // At this point we just use the base size as a fallback.
2227        DimensionConstraint::Intrinsic(_) => base,
2228    };
2229
2230    size = clamp_dimension(size, min_bound, max_bound);
2231    size = clamp_dimension(size, min_limit, max_limit);
2232    size.max(0.0)
2233}
2234
2235fn clamp_dimension(value: f32, min: f32, max: f32) -> f32 {
2236    let mut result = value.max(min);
2237    if max.is_finite() {
2238        result = result.min(max);
2239    }
2240    result
2241}
2242
2243fn normalize_constraints(mut constraints: Constraints) -> Constraints {
2244    if constraints.max_width < constraints.min_width {
2245        constraints.max_width = constraints.min_width;
2246    }
2247    if constraints.max_height < constraints.min_height {
2248        constraints.max_height = constraints.min_height;
2249    }
2250    constraints
2251}
2252
2253#[cfg(test)]
2254#[path = "tests/layout_tests.rs"]
2255mod tests;