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