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};
16use cranpose_foundation::{
17    text::TextRange, CanvasSemanticsNode, InvalidationKind, ModifierNodeContext, NodeCapabilities,
18    SemanticsConfiguration, SemanticsCustomAction, SemanticsWidgetRole,
19};
20use cranpose_ui_layout::{Constraints, MeasurePolicy, Placement};
21use web_time::Instant;
22
23#[cfg(test)]
24use self::core::{HorizontalAlignment, VerticalAlignment};
25use self::core::{Measurable, Placeable};
26use crate::{
27    modifier::{
28        collect_semantics_from_modifier, DimensionConstraint, EdgeInsets, Modifier,
29        ModifierNodeSlices, ModifierNodeSlicesDebugStats, Point, Rect as GeometryRect,
30        ResolvedModifiers, Size,
31    },
32    subcompose_layout::{CachedBatchMeasureInputs, SubcomposeLayoutNode},
33    widgets::nodes::{IntrinsicKind, LayoutNode, LayoutNodeCacheHandles, LayoutState},
34};
35
36/// Runtime context for modifier nodes during measurement.
37///
38/// Unlike `BasicModifierNodeContext`, this context accumulates invalidations
39/// that can be processed after measurement to set dirty flags on the LayoutNode.
40#[derive(Default)]
41pub(crate) struct LayoutNodeContext {
42    invalidations: Vec<InvalidationKind>,
43    update_requested: bool,
44    active_capabilities: Vec<NodeCapabilities>,
45}
46
47impl LayoutNodeContext {
48    pub(crate) fn new() -> Self {
49        Self::default()
50    }
51
52    pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationKind> {
53        std::mem::take(&mut self.invalidations)
54    }
55}
56
57impl ModifierNodeContext for LayoutNodeContext {
58    fn invalidate(&mut self, kind: InvalidationKind) {
59        if !self.invalidations.contains(&kind) {
60            self.invalidations.push(kind);
61        }
62    }
63
64    fn request_update(&mut self) {
65        self.update_requested = true;
66    }
67
68    fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
69        self.active_capabilities.push(capabilities);
70    }
71
72    fn pop_active_capabilities(&mut self) {
73        self.active_capabilities.pop();
74    }
75}
76
77/// Forces all layout caches to be invalidated on the next measure by incrementing the epoch.
78///
79/// # ⚠️ Internal Use Only - NOT Public API
80///
81/// **This function is hidden from public documentation and MUST NOT be called by external code.**
82///
83/// Only `cranpose-app-shell` may call this for rare global events:
84/// - Window/viewport resize
85/// - Global font scale or density changes
86/// - Debug toggles that affect all layout
87///
88/// **This is O(entire app size) - extremely expensive!**
89///
90/// # For Local Changes
91///
92/// **Do NOT use this for scroll, single-node mutations, or any local layout change.**
93/// Instead, use the scoped repass mechanism:
94/// ```text
95/// cranpose_ui::schedule_layout_repass(node_id);
96/// ```
97///
98/// The scoped path bubbles dirty flags without invalidating all caches, giving you O(subtree) instead of O(app).
99#[doc(hidden)]
100pub fn invalidate_all_layout_caches() {
101    crate::render_state::invalidate_layout_cache_epoch();
102}
103
104fn layout_measure_telemetry_threshold_ms() -> Option<f64> {
105    static THRESHOLD_MS: OnceLock<Option<f64>> = OnceLock::new();
106    *THRESHOLD_MS.get_or_init(|| {
107        std::env::var("CRANPOSE_LAYOUT_MEASURE_TELEMETRY_MS")
108            .ok()
109            .and_then(|value| value.parse::<f64>().ok())
110            .filter(|value| value.is_finite() && *value >= 0.0)
111            .or_else(|| {
112                std::env::var_os("CRANPOSE_LAYOUT_MEASURE_TELEMETRY")
113                    .is_some()
114                    .then_some(4.0)
115            })
116    })
117}
118
119struct LayoutMeasureTelemetry {
120    root: NodeId,
121    start: Instant,
122    after_repasses: Instant,
123    after_guard: Instant,
124    after_builder: Instant,
125    after_measure: Instant,
126    after_root_place: Instant,
127    after_aux: Instant,
128    after_builder_drop: Instant,
129    after_guard_drop: Instant,
130}
131
132fn log_layout_measure_telemetry(times: LayoutMeasureTelemetry) {
133    let Some(threshold_ms) = layout_measure_telemetry_threshold_ms() else {
134        return;
135    };
136
137    let total_ms = times
138        .after_guard_drop
139        .duration_since(times.start)
140        .as_secs_f64()
141        * 1000.0;
142    if total_ms < threshold_ms {
143        return;
144    }
145
146    let repass_ms = times
147        .after_repasses
148        .duration_since(times.start)
149        .as_secs_f64()
150        * 1000.0;
151    let guard_ms = times
152        .after_guard
153        .duration_since(times.after_repasses)
154        .as_secs_f64()
155        * 1000.0;
156    let builder_ms = times
157        .after_builder
158        .duration_since(times.after_guard)
159        .as_secs_f64()
160        * 1000.0;
161    let measure_ms = times
162        .after_measure
163        .duration_since(times.after_builder)
164        .as_secs_f64()
165        * 1000.0;
166    let root_place_ms = times
167        .after_root_place
168        .duration_since(times.after_measure)
169        .as_secs_f64()
170        * 1000.0;
171    let aux_ms = times
172        .after_aux
173        .duration_since(times.after_root_place)
174        .as_secs_f64()
175        * 1000.0;
176    let builder_drop_ms = times
177        .after_builder_drop
178        .duration_since(times.after_aux)
179        .as_secs_f64()
180        * 1000.0;
181    let guard_drop_ms = times
182        .after_guard_drop
183        .duration_since(times.after_builder_drop)
184        .as_secs_f64()
185        * 1000.0;
186    log::warn!(
187        "[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}",
188        times.root
189    );
190}
191
192fn log_node_measure_telemetry(
193    kind: &'static str,
194    node_id: NodeId,
195    constraints: Constraints,
196    size: Size,
197    children: usize,
198    start: Instant,
199) {
200    let Some(threshold_ms) = layout_measure_telemetry_threshold_ms() else {
201        return;
202    };
203
204    let total_ms = start.elapsed().as_secs_f64() * 1000.0;
205    if total_ms < threshold_ms {
206        return;
207    }
208
209    log::warn!(
210        "[layout-node-telemetry] kind={kind} node={} total_ms={total_ms:.2} constraints=({:.1},{:.1},{:.1},{:.1}) size=({:.1},{:.1}) children={children}",
211        node_id,
212        constraints.min_width,
213        constraints.max_width,
214        constraints.min_height,
215        constraints.max_height,
216        size.width,
217        size.height,
218    );
219}
220
221/// RAII guard that:
222/// - moves the current MemoryApplier into a ConcreteApplierHost
223/// - holds a shared handle to the `SlotTable` used by `LayoutBuilder`
224/// - on Drop, always:
225///   * restores slots into the host from the shared handle
226///   * moves the original MemoryApplier back into the Composition
227///
228/// This makes `measure_layout` panic/Err-safe wrt both the applier and slots.
229/// The key invariant: guard and builder share the same `Rc<RefCell<SlotTable>>`,
230/// so the guard never loses access to the authoritative slots even on panic.
231struct ApplierSlotGuard<'a> {
232    /// The `MemoryApplier` inside the Composition::applier that we must restore into.
233    target: &'a mut MemoryApplier,
234    /// Host that owns the original MemoryApplier while layout is running.
235    host: Rc<ConcreteApplierHost<MemoryApplier>>,
236    /// Shared handle to the slot table. Both the guard and the builder hold a clone.
237    /// On Drop, we write whatever is in this handle back into the applier.
238    slots: Rc<RefCell<SlotTable>>,
239}
240
241impl<'a> ApplierSlotGuard<'a> {
242    /// Creates a new guard:
243    /// - moves the current MemoryApplier out of `target` into a host
244    /// - takes the current slots out of the host and wraps them in a shared handle
245    fn new(target: &'a mut MemoryApplier) -> Self {
246        // Move the original applier into a host; leave `target` with a fresh one
247        let original_applier = std::mem::replace(target, MemoryApplier::new());
248        let host = Rc::new(ConcreteApplierHost::new(original_applier));
249
250        // Take slots from the host into a shared handle
251        let slots = {
252            let mut applier_ref = host.borrow_typed();
253            std::mem::take(applier_ref.slots())
254        };
255        let slots = Rc::new(RefCell::new(slots));
256
257        Self {
258            target,
259            host,
260            slots,
261        }
262    }
263
264    /// Rc to pass into LayoutBuilder::new_with_epoch
265    fn host(&self) -> Rc<ConcreteApplierHost<MemoryApplier>> {
266        Rc::clone(&self.host)
267    }
268
269    /// Returns the shared handle to slots for the builder to use.
270    /// The builder clones this Rc, so both guard and builder share the same slots.
271    fn slots_handle(&self) -> Rc<RefCell<SlotTable>> {
272        Rc::clone(&self.slots)
273    }
274}
275
276impl Drop for ApplierSlotGuard<'_> {
277    fn drop(&mut self) {
278        // 1) Restore slots into the host's MemoryApplier from the shared handle.
279        // This works correctly whether we're on the success path or panic/error path,
280        // because we always have the shared handle.
281        {
282            let mut applier_ref = self.host.borrow_typed();
283            *applier_ref.slots() = std::mem::take(&mut *self.slots.borrow_mut());
284        }
285
286        // 2) Move the original MemoryApplier (with restored/updated slots) back into `target`
287        {
288            let mut applier_ref = self.host.borrow_typed();
289            let original_applier = std::mem::take(&mut *applier_ref);
290            let _ = std::mem::replace(self.target, original_applier);
291        }
292        // No Rc::try_unwrap in Drop → no "panic during panic" risk.
293    }
294}
295
296/// Result of measuring through the modifier node chain.
297struct ModifierChainMeasurement {
298    size: Size,
299    /// Content offset for scroll/inner transforms - NOT padding semantics
300    content_offset: Point,
301    /// Node's own offset (from OffsetNode, affects position in parent)
302    offset: Point,
303}
304
305type LayoutModifierNodeData = (
306    usize,
307    Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
308);
309
310struct ScratchVecPool<T> {
311    available: Vec<Vec<T>>,
312}
313
314impl<T> ScratchVecPool<T> {
315    fn acquire(&mut self) -> Vec<T> {
316        self.available.pop().unwrap_or_default()
317    }
318
319    fn release(&mut self, mut values: Vec<T>) {
320        values.clear();
321        self.available.push(values);
322    }
323
324    #[cfg(test)]
325    fn available_count(&self) -> usize {
326        self.available.len()
327    }
328}
329
330impl<T> Default for ScratchVecPool<T> {
331    fn default() -> Self {
332        Self {
333            available: Vec::new(),
334        }
335    }
336}
337
338#[derive(Default)]
339pub(crate) struct FrameLayoutArena {
340    tmp_records: ScratchVecPool<(NodeId, ChildRecord)>,
341    tmp_child_ids: ScratchVecPool<NodeId>,
342    tmp_layout_node_data: ScratchVecPool<LayoutModifierNodeData>,
343    tmp_placements: ScratchVecPool<Placement>,
344}
345
346#[cfg(test)]
347impl FrameLayoutArena {
348    pub(crate) fn available_placement_scratch_count(&self) -> usize {
349        self.tmp_placements.available_count()
350    }
351
352    pub(crate) fn seed_placement_scratch_for_test(&mut self) {
353        self.tmp_placements.release(Vec::with_capacity(1));
354    }
355}
356
357/// Discrete event callback reference produced during semantics extraction.
358#[derive(Clone, Debug, PartialEq, Eq)]
359pub struct SemanticsCallback {
360    node_id: NodeId,
361}
362
363impl SemanticsCallback {
364    pub fn new(node_id: NodeId) -> Self {
365        Self { node_id }
366    }
367
368    pub fn node_id(&self) -> NodeId {
369        self.node_id
370    }
371}
372
373/// Semantics action exposed to the input system.
374#[derive(Clone, Debug, PartialEq, Eq)]
375pub enum SemanticsAction {
376    Click { handler: SemanticsCallback },
377}
378
379/// Semantic role describing how a node should participate in accessibility and hit testing.
380/// Roles are now derived from SemanticsConfiguration rather than widget types.
381#[derive(Clone, Debug, PartialEq, Eq)]
382pub enum SemanticsRole {
383    /// Generic container or layout node
384    Layout,
385    /// Subcomposition boundary
386    Subcompose,
387    /// Text content derived from the text node semantics payload.
388    Text { value: String },
389    /// Spacer (non-interactive)
390    Spacer,
391    /// Button (derived from the semantics `role`)
392    Button,
393    /// Unknown or unspecified role
394    Unknown,
395}
396
397/// A single node within the semantics tree.
398///
399/// Not `Eq`: a node now carries drawn-control bounds, which are floats. The
400/// tree is compared for "did anything a screen reader can see change", and
401/// that comparison is `PartialEq` everywhere else on the accessibility path
402/// (`AccessibilityRect`, `AccessibilityElement`) for the same reason.
403#[derive(Clone, Debug, PartialEq)]
404pub struct SemanticsNode {
405    pub node_id: NodeId,
406    /// Where this node sits in the tree (layout, text, subcomposition …).
407    pub role: SemanticsRole,
408    /// What kind of control this node is, as a screen reader announces it —
409    /// Compose's `Role`. Separate from [`SemanticsNode::role`] because a
410    /// clickable `Row` is structurally a layout node and semantically a button.
411    pub widget_role: Option<SemanticsWidgetRole>,
412    pub actions: Vec<SemanticsAction>,
413    pub children: Vec<SemanticsNode>,
414    pub description: Option<String>,
415    pub state_description: Option<String>,
416    pub on_click_label: Option<String>,
417    pub selected: Option<bool>,
418    pub toggled: Option<bool>,
419    pub enabled: bool,
420    pub custom_actions: Vec<SemanticsCustomAction>,
421    /// Controls this node drew rather than laid out; their bounds are relative
422    /// to this node's own top-left. See [`CanvasSemanticsNode`].
423    pub canvas_children: Vec<CanvasSemanticsNode>,
424    pub editable_text: bool,
425    pub text_selection: Option<TextRange>,
426}
427
428impl Default for SemanticsNode {
429    fn default() -> Self {
430        Self {
431            node_id: 0,
432            role: SemanticsRole::Unknown,
433            widget_role: None,
434            actions: Vec::new(),
435            children: Vec::new(),
436            description: None,
437            state_description: None,
438            on_click_label: None,
439            selected: None,
440            toggled: None,
441            enabled: true,
442            custom_actions: Vec::new(),
443            canvas_children: Vec::new(),
444            editable_text: false,
445            text_selection: None,
446        }
447    }
448}
449
450/// Rooted semantics tree extracted after layout.
451#[derive(Clone, Debug, PartialEq)]
452pub struct SemanticsTree {
453    root: SemanticsNode,
454}
455
456impl SemanticsTree {
457    fn new(root: SemanticsNode) -> Self {
458        Self { root }
459    }
460
461    pub fn root(&self) -> &SemanticsNode {
462        &self.root
463    }
464}
465
466#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
467pub struct LayoutAllocationDebugStats {
468    pub layout_box_count: usize,
469    pub layout_box_child_count: usize,
470    pub layout_box_child_capacity: usize,
471    pub layout_box_heap_bytes: usize,
472    pub modifier_slice_count: usize,
473    pub modifier_slice_heap_bytes: usize,
474    pub modifier_draw_command_count: usize,
475    pub modifier_draw_command_capacity: usize,
476    pub modifier_pointer_input_count: usize,
477    pub modifier_pointer_input_capacity: usize,
478    pub modifier_click_handler_count: usize,
479    pub modifier_click_handler_capacity: usize,
480    pub modifier_text_content_count: usize,
481    pub modifier_text_style_count: usize,
482    pub modifier_text_layout_options_count: usize,
483    pub modifier_prepared_text_layout_count: usize,
484    pub modifier_graphics_layer_count: usize,
485    pub modifier_graphics_layer_resolver_count: usize,
486    pub semantics_node_count: usize,
487    pub semantics_action_count: usize,
488    pub semantics_action_capacity: usize,
489    pub semantics_child_count: usize,
490    pub semantics_child_capacity: usize,
491    pub semantics_description_count: usize,
492    pub semantics_description_bytes: usize,
493    pub semantics_text_role_bytes: usize,
494    pub semantics_heap_bytes: usize,
495}
496
497impl LayoutAllocationDebugStats {
498    fn add_modifier_slice(&mut self, stats: ModifierNodeSlicesDebugStats) {
499        self.modifier_slice_count += 1;
500        self.modifier_slice_heap_bytes += stats.heap_bytes;
501        self.modifier_draw_command_count += stats.draw_command_count;
502        self.modifier_draw_command_capacity += stats.draw_command_capacity;
503        self.modifier_pointer_input_count += stats.pointer_input_count;
504        self.modifier_pointer_input_capacity += stats.pointer_input_capacity;
505        self.modifier_click_handler_count += stats.click_handler_count;
506        self.modifier_click_handler_capacity += stats.click_handler_capacity;
507        self.modifier_text_content_count += usize::from(stats.has_text_content);
508        self.modifier_text_style_count += usize::from(stats.has_text_style);
509        self.modifier_text_layout_options_count += usize::from(stats.has_text_layout_options);
510        self.modifier_prepared_text_layout_count += usize::from(stats.has_prepared_text_layout);
511        self.modifier_graphics_layer_count += usize::from(stats.has_graphics_layer);
512        self.modifier_graphics_layer_resolver_count +=
513            usize::from(stats.has_graphics_layer_resolver);
514    }
515}
516
517/// Result of running layout for a Compose tree.
518#[derive(Debug, Clone)]
519pub struct LayoutTree {
520    root: LayoutBox,
521}
522
523impl LayoutTree {
524    pub fn new(root: LayoutBox) -> Self {
525        Self { root }
526    }
527
528    pub fn root(&self) -> &LayoutBox {
529        &self.root
530    }
531
532    pub fn root_mut(&mut self) -> &mut LayoutBox {
533        &mut self.root
534    }
535
536    pub fn into_root(self) -> LayoutBox {
537        self.root
538    }
539
540    pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
541        let mut stats = LayoutAllocationDebugStats::default();
542        record_layout_box_allocation_stats(&self.root, &mut stats);
543        stats
544    }
545}
546
547/// Layout information for a single node.
548#[derive(Debug, Clone)]
549pub struct LayoutBox {
550    pub node_id: NodeId,
551    pub rect: GeometryRect,
552    /// Content offset for scroll/inner transforms (applies to children, NOT this node's position)
553    pub content_offset: Point,
554    pub node_data: LayoutNodeData,
555    pub children: Vec<LayoutBox>,
556}
557
558impl LayoutBox {
559    pub fn new(
560        node_id: NodeId,
561        rect: GeometryRect,
562        content_offset: Point,
563        node_data: LayoutNodeData,
564        children: Vec<LayoutBox>,
565    ) -> Self {
566        Self {
567            node_id,
568            rect,
569            content_offset,
570            node_data,
571            children,
572        }
573    }
574}
575
576/// Snapshot of the data required to render a layout node.
577#[derive(Debug, Clone)]
578pub struct LayoutNodeData {
579    pub modifier: Modifier,
580    pub resolved_modifiers: ResolvedModifiers,
581    pub modifier_slices: Rc<ModifierNodeSlices>,
582    pub kind: LayoutNodeKind,
583}
584
585impl LayoutNodeData {
586    pub fn new(
587        modifier: Modifier,
588        resolved_modifiers: ResolvedModifiers,
589        modifier_slices: Rc<ModifierNodeSlices>,
590        kind: LayoutNodeKind,
591    ) -> Self {
592        Self {
593            modifier,
594            resolved_modifiers,
595            modifier_slices,
596            kind,
597        }
598    }
599
600    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
601        self.resolved_modifiers
602    }
603
604    pub fn modifier_slices(&self) -> &ModifierNodeSlices {
605        &self.modifier_slices
606    }
607}
608
609/// Classification of the node captured inside a [`LayoutBox`].
610///
611/// Note: Text content is no longer represented as a distinct LayoutNodeKind.
612/// Text nodes now use `LayoutNodeKind::Layout` with their content stored in
613/// `modifier_slices.text_content()` via TextModifierNode, following Jetpack
614/// Compose's pattern where text is a modifier node capability.
615#[derive(Clone)]
616pub enum LayoutNodeKind {
617    Layout,
618    Subcompose,
619    Spacer,
620    Button { on_click: Rc<RefCell<dyn FnMut()>> },
621    Unknown,
622}
623
624impl fmt::Debug for LayoutNodeKind {
625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626        match self {
627            LayoutNodeKind::Layout => f.write_str("Layout"),
628            LayoutNodeKind::Subcompose => f.write_str("Subcompose"),
629            LayoutNodeKind::Spacer => f.write_str("Spacer"),
630            LayoutNodeKind::Button { .. } => f.write_str("Button"),
631            LayoutNodeKind::Unknown => f.write_str("Unknown"),
632        }
633    }
634}
635
636/// Extension trait that equips `MemoryApplier` with layout computation.
637pub trait LayoutEngine {
638    fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError>;
639}
640
641impl LayoutEngine for MemoryApplier {
642    fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError> {
643        let measurements = measure_layout(self, root, max_size)?;
644        measurements
645            .into_layout_tree()
646            .ok_or(NodeError::MissingContext {
647                id: root,
648                reason: "layout tree was not requested",
649            })
650    }
651}
652
653/// Result of running the measure pass for a Compose layout tree.
654#[derive(Debug, Clone)]
655pub struct LayoutMeasurements {
656    root: Rc<MeasuredNode>,
657    semantics: Option<SemanticsTree>,
658    layout_tree: Option<LayoutTree>,
659}
660
661impl LayoutMeasurements {
662    fn new(
663        root: Rc<MeasuredNode>,
664        semantics: Option<SemanticsTree>,
665        layout_tree: Option<LayoutTree>,
666    ) -> Self {
667        Self {
668            root,
669            semantics,
670            layout_tree,
671        }
672    }
673
674    /// Returns the measured size of the root node.
675    pub fn root_size(&self) -> Size {
676        self.root.size
677    }
678
679    pub fn semantics_tree(&self) -> Option<&SemanticsTree> {
680        self.semantics.as_ref()
681    }
682
683    pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
684        let mut stats = self
685            .layout_tree
686            .as_ref()
687            .map(LayoutTree::debug_allocation_stats)
688            .unwrap_or_default();
689        if let Some(semantics) = &self.semantics {
690            record_semantics_allocation_stats(semantics.root(), &mut stats);
691        }
692        stats
693    }
694
695    /// Consumes the measurements and returns the built [`LayoutTree`], if requested.
696    pub fn into_layout_tree(self) -> Option<LayoutTree> {
697        self.layout_tree
698    }
699
700    /// Returns a cloned [`LayoutTree`] for rendering/debug consumers, if requested.
701    pub fn layout_tree(&self) -> Option<LayoutTree> {
702        self.layout_tree.clone()
703    }
704}
705
706/// Builds a semantics tree from an existing [`LayoutTree`].
707///
708/// This is useful for consumers that need semantics on demand without forcing
709/// every layout pass to eagerly allocate a full [`SemanticsTree`].
710pub fn build_semantics_tree_from_layout_tree(layout_tree: &LayoutTree) -> SemanticsTree {
711    SemanticsTree::new(build_semantics_node_from_layout_box(layout_tree.root()))
712}
713
714/// Builds a layout snapshot from retained layout state in the live applier tree.
715///
716/// Renderers use retained node state directly. This function exists for debug,
717/// robot, and tests that need an owned [`LayoutTree`] without forcing every
718/// layout pass to allocate one.
719pub fn build_layout_tree_from_applier(
720    applier: &mut MemoryApplier,
721    root: NodeId,
722) -> Result<Option<LayoutTree>, NodeError> {
723    fn snapshot(
724        applier: &mut MemoryApplier,
725        node_id: NodeId,
726    ) -> Result<Option<(crate::widgets::nodes::layout_node::LayoutState, Vec<NodeId>)>, NodeError>
727    {
728        match applier.with_node::<LayoutNode, _>(node_id, |node| {
729            (node.layout_state(), node.children.clone())
730        }) {
731            Ok(snapshot) => return Ok(Some(snapshot)),
732            Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {}
733            Err(err) => return Err(err),
734        }
735
736        match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
737            (node.layout_state(), node.active_children())
738        }) {
739            Ok(snapshot) => Ok(Some(snapshot)),
740            Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => Ok(None),
741            Err(err) => Err(err),
742        }
743    }
744
745    fn place(
746        applier: &mut MemoryApplier,
747        node_id: NodeId,
748        parent_content_origin: Point,
749        // Accumulated ancestor graphics-layer translation (window px). A node's
750        // drawn content is offset by every ancestor layer's translation on top
751        // of its layout position, so a text field's true on-screen origin must
752        // add this. Scroll offsets are already baked into `parent_content_origin`
753        // via placement; this carries the extra translation-transform component.
754        parent_layer_translation: Point,
755    ) -> Result<Option<LayoutBox>, NodeError> {
756        let Some((state, child_ids)) = snapshot(applier, node_id)? else {
757            return Ok(None);
758        };
759        if !state.is_placed {
760            return Ok(None);
761        }
762
763        let top_left = Point {
764            x: parent_content_origin.x + state.position.x,
765            y: parent_content_origin.y + state.position.y,
766        };
767        let rect = GeometryRect {
768            x: top_left.x,
769            y: top_left.y,
770            width: state.size.width,
771            height: state.size.height,
772        };
773        let info = runtime_metadata_for(applier, node_id)?;
774        let kind = layout_kind_from_metadata(node_id, &info);
775        let RuntimeNodeMetadata {
776            modifier,
777            resolved_modifiers,
778            modifier_slices,
779            ..
780        } = info;
781
782        // Add this node's own graphics-layer translation to the accumulated
783        // ancestor translation: it shifts where this node (and its subtree) is
784        // drawn relative to its layout box. (Scale/rotation are not folded in —
785        // handle positioning under a zoom/rotation layer is a documented gap.)
786        let layer_translation = match modifier_slices.graphics_layer() {
787            Some(layer) => Point {
788                x: parent_layer_translation.x + layer.translation_x,
789                y: parent_layer_translation.y + layer.translation_y,
790            },
791            None => parent_layer_translation,
792        };
793
794        // Publish the field's TRUE composited window origin for its selection
795        // handles: layout position (scroll already baked in) + accumulated layer
796        // translation. Re-read every layout pass so handles track live scrolling.
797        if let Some(sink) = modifier_slices.text_field_window_origin() {
798            sink.set(Point {
799                x: top_left.x + layer_translation.x,
800                y: top_left.y + layer_translation.y,
801            });
802        }
803
804        // Publish a scroll container's composited viewport rect (window
805        // coordinates) for its `BringIntoViewResponder`, so a focused
806        // descendant field can be scrolled above the soft keyboard.
807        if let Some(sink) = modifier_slices.viewport_window_rect() {
808            sink.set(GeometryRect {
809                x: top_left.x + layer_translation.x,
810                y: top_left.y + layer_translation.y,
811                width: state.size.width,
812                height: state.size.height,
813            });
814        }
815
816        // Publish this node's resolved size to its `pointer_input` handlers so
817        // `PointerInputScope::size()` reports the node's real dimensions (the
818        // box the dispatched event positions are local to), not `0x0`.
819        modifier_slices.publish_pointer_input_size(state.size);
820
821        let data = LayoutNodeData::new(modifier, resolved_modifiers, modifier_slices, kind);
822        let child_origin = Point {
823            x: top_left.x + state.content_offset.x,
824            y: top_left.y + state.content_offset.y,
825        };
826        let mut children = Vec::with_capacity(child_ids.len());
827        for child_id in child_ids {
828            if let Some(child) = place(applier, child_id, child_origin, layer_translation)? {
829                children.push(child);
830            }
831        }
832
833        Ok(Some(LayoutBox::new(
834            node_id,
835            rect,
836            state.content_offset,
837            data,
838            children,
839        )))
840    }
841
842    place(applier, root, Point::default(), Point::default()).map(|root| root.map(LayoutTree::new))
843}
844
845/// Builds a semantics snapshot from retained layout state in the live applier tree.
846///
847/// This is the on-demand counterpart to [`build_layout_tree_from_applier`].
848/// It follows the currently placed child set, including subcompose active
849/// children, and clears semantics dirty flags for nodes it visits.
850pub fn build_semantics_tree_from_applier(
851    applier: &mut MemoryApplier,
852    root: NodeId,
853) -> Result<Option<SemanticsTree>, NodeError> {
854    fn node(
855        applier: &mut MemoryApplier,
856        node_id: NodeId,
857    ) -> Result<Option<SemanticsNode>, NodeError> {
858        match applier.with_node::<LayoutNode, _>(node_id, |layout| {
859            let state = layout.layout_state();
860            if !state.is_placed {
861                return None;
862            }
863            let role = role_from_modifier_slices(&layout.modifier_slices_snapshot());
864            let config = layout.semantics_configuration();
865            let children = layout.children.clone();
866            layout.clear_needs_semantics();
867            Some((role, config, children))
868        }) {
869            Ok(Some((role, config, child_ids))) => {
870                let mut children = Vec::with_capacity(child_ids.len());
871                for child_id in child_ids {
872                    if let Some(child) = node(applier, child_id)? {
873                        children.push(child);
874                    }
875                }
876                return Ok(Some(semantics_node_from_parts(
877                    node_id, role, config, children,
878                )));
879            }
880            Ok(None) => return Ok(None),
881            Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {}
882            Err(err) => return Err(err),
883        }
884
885        match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |subcompose| {
886            let state = subcompose.layout_state();
887            if !state.is_placed {
888                return None;
889            }
890            let config = collect_semantics_from_modifier(&subcompose.modifier());
891            let children = subcompose.active_children();
892            subcompose.clear_needs_semantics();
893            Some((config, children))
894        }) {
895            Ok(Some((config, child_ids))) => {
896                let mut children = Vec::with_capacity(child_ids.len());
897                for child_id in child_ids {
898                    if let Some(child) = node(applier, child_id)? {
899                        children.push(child);
900                    }
901                }
902                Ok(Some(semantics_node_from_parts(
903                    node_id,
904                    SemanticsRole::Subcompose,
905                    config,
906                    children,
907                )))
908            }
909            Ok(None) | Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
910                Ok(None)
911            }
912            Err(err) => Err(err),
913        }
914    }
915
916    node(applier, root).map(|root| root.map(SemanticsTree::new))
917}
918
919#[derive(Clone, Copy, Debug, PartialEq, Eq)]
920pub struct MeasureLayoutOptions {
921    pub collect_semantics: bool,
922    pub build_layout_tree: bool,
923}
924
925impl Default for MeasureLayoutOptions {
926    fn default() -> Self {
927        Self {
928            collect_semantics: true,
929            build_layout_tree: true,
930        }
931    }
932}
933
934/// Check if a node or any of its descendants needs measure (selective measure optimization).
935/// This can be used by the app shell to skip layout when the tree is clean.
936///
937/// O(1) check - just looks at root's dirty flag.
938/// Works because all mutation paths bubble dirty flags to root via composer commands.
939///
940/// Returns Result to force caller to handle errors explicitly. No more unwrap_or(true) safety net.
941pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
942    Ok(applier.get_mut(root)?.needs_layout())
943}
944
945/// Check if the root semantics snapshot is dirty.
946///
947/// Semantics invalidations bubble to the root the same way layout invalidations do,
948/// so a root check is sufficient to determine whether the next layout pass needs to
949/// rebuild semantic data even when geometry is otherwise unchanged.
950pub fn tree_needs_semantics(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
951    Ok(applier.get_mut(root)?.needs_semantics())
952}
953
954/// Test helper: bubbles layout dirty flag to root.
955#[cfg(test)]
956pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
957    cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
958}
959
960/// Runs the measure phase for the subtree rooted at `root`.
961pub fn measure_layout(
962    applier: &mut MemoryApplier,
963    root: NodeId,
964    max_size: Size,
965) -> Result<LayoutMeasurements, NodeError> {
966    measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
967}
968
969pub fn measure_layout_with_options(
970    applier: &mut MemoryApplier,
971    root: NodeId,
972    max_size: Size,
973    options: MeasureLayoutOptions,
974) -> Result<LayoutMeasurements, NodeError> {
975    let telemetry_start = Instant::now();
976    process_pending_layout_repasses(applier, root)?;
977    let after_repasses = Instant::now();
978
979    let constraints = Constraints {
980        min_width: 0.0,
981        max_width: max_size.width,
982        min_height: 0.0,
983        max_height: max_size.height,
984    };
985
986    // Selective measure: only increment epoch if something needs MEASURING (not just layout)
987    // O(1) check - just look at root's dirty flag (bubbling ensures correctness)
988    //
989    // CRITICAL: We check needs_MEASURE, not needs_LAYOUT!
990    // - needs_measure: size may change, caches must be invalidated
991    // - needs_layout: position may change but size is cached (e.g., scroll)
992    //
993    // Scroll operations bubble needs_layout to ancestors, but NOT needs_measure.
994    // Using needs_layout here would wipe ALL caches on every scroll frame, causing
995    // O(N) full remeasurement instead of O(changed nodes).
996    let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
997        .with_node::<LayoutNode, _>(root, |node| {
998            (
999                node.needs_measure(), // CORRECT: check needs_measure, not needs_layout
1000                node.needs_semantics(),
1001                node.cache_handles().epoch(),
1002            )
1003        }) {
1004        Ok(tuple) => tuple,
1005        Err(NodeError::TypeMismatch { .. }) => {
1006            let node = applier.get_mut(root)?;
1007            // Non-LayoutNode roots still expose Node dirty flags.
1008            // Use needs_measure here so layout-only subtree repasses can reuse
1009            // the existing cache epoch instead of invalidating the whole tree.
1010            let measure_dirty = node.needs_measure();
1011            let semantics_dirty = node.needs_semantics();
1012            (measure_dirty, semantics_dirty, 0)
1013        }
1014        Err(err) => return Err(err),
1015    };
1016
1017    let epoch = if needs_remeasure {
1018        crate::render_state::next_layout_cache_epoch()
1019    } else if cached_epoch != 0 {
1020        cached_epoch
1021    } else {
1022        // Fallback when caller root isn't a LayoutNode (e.g. tests using Spacer directly).
1023        crate::render_state::current_layout_cache_epoch()
1024    };
1025
1026    // Move the current applier into a host and set up a guard that will
1027    // ALWAYS restore:
1028    // - the MemoryApplier back into `applier`
1029    // - the SlotTable back into that MemoryApplier
1030    //
1031    // IMPORTANT: Declare the guard *before* the builder so the builder
1032    // is dropped first (both on Ok and on unwind).
1033    let guard = ApplierSlotGuard::new(applier);
1034    let applier_host = guard.host();
1035    let slots_handle = guard.slots_handle();
1036    let after_guard = Instant::now();
1037
1038    // Give the builder the shared slots handle - both guard and builder
1039    // now share access to the same SlotTable via Rc<RefCell<_>>.
1040    let frame_arena = crate::render_state::take_layout_frame_arena();
1041    let mut builder = LayoutBuilder::new_with_epoch(
1042        Rc::clone(&applier_host),
1043        epoch,
1044        Rc::clone(&slots_handle),
1045        frame_arena,
1046    );
1047    let after_builder = Instant::now();
1048
1049    // ---- Measurement -------------------------------------------------------
1050    // If measurement fails, the guard will restore slots from the shared handle
1051    // on drop - this is safe because the handle always contains valid slots.
1052
1053    let measured = builder.measure_node(root, normalize_constraints(constraints))?;
1054    let after_measure = Instant::now();
1055
1056    // Root node has no parent to place it, so we must explicitly place it at (0,0).
1057    // This ensures is_placed=true, allowing the renderer to traverse the tree.
1058    // Handle both LayoutNode and SubcomposeLayoutNode as potential roots.
1059    if let Ok(mut applier) = applier_host.try_borrow_typed() {
1060        if applier
1061            .with_node::<LayoutNode, _>(root, |node| {
1062                node.set_position(Point::default());
1063            })
1064            .is_err()
1065        {
1066            let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
1067                node.set_position(Point::default());
1068            });
1069        }
1070    }
1071    let after_root_place = Instant::now();
1072
1073    let (layout_tree, semantics) = {
1074        let mut applier_ref = applier_host.borrow_typed();
1075        let layout_tree = if options.build_layout_tree {
1076            Some(build_layout_tree(&mut applier_ref, &measured)?)
1077        } else {
1078            None
1079        };
1080        let semantics = if options.collect_semantics {
1081            let semantics_tree = if let Some(layout_tree) = layout_tree.as_ref() {
1082                clear_semantics_dirty_flags(&mut applier_ref, &measured)?;
1083                build_semantics_tree_from_layout_tree(layout_tree)
1084            } else {
1085                build_semantics_tree_from_live_nodes(&mut applier_ref, &measured)?
1086            };
1087            Some(semantics_tree)
1088        } else {
1089            None
1090        };
1091        (layout_tree, semantics)
1092    };
1093    let after_aux = Instant::now();
1094
1095    // Drop builder before guard - slots are already in the shared handle.
1096    // Guard's Drop will write them back to the applier.
1097    drop(builder);
1098    let after_builder_drop = Instant::now();
1099
1100    // DO NOT manually unwrap `applier_host` or replace `applier` here.
1101    // `ApplierSlotGuard::drop` will restore everything when this function returns.
1102    drop(guard);
1103    let after_guard_drop = Instant::now();
1104
1105    log_layout_measure_telemetry(LayoutMeasureTelemetry {
1106        root,
1107        start: telemetry_start,
1108        after_repasses,
1109        after_guard,
1110        after_builder,
1111        after_measure,
1112        after_root_place,
1113        after_aux,
1114        after_builder_drop,
1115        after_guard_drop,
1116    });
1117
1118    Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
1119}
1120
1121fn process_pending_layout_repasses(
1122    applier: &mut MemoryApplier,
1123    root: NodeId,
1124) -> Result<(), NodeError> {
1125    for node_id in crate::render_state::take_modifier_slice_repass_nodes() {
1126        if let Ok(node) = applier.get_mut(node_id) {
1127            let any = node.as_any_mut();
1128            if let Some(layout) = any.downcast_mut::<crate::widgets::nodes::LayoutNode>() {
1129                layout.mark_modifier_slices_dirty();
1130            } else if let Some(subcompose) =
1131                any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
1132            {
1133                subcompose.mark_modifier_slices_dirty();
1134            }
1135        }
1136    }
1137    // Measure repasses re-*size* a subtree (and its ancestors), so an enclosing
1138    // LazyColumn re-measures the node instead of reusing its cached item slot.
1139    let measure_repass_nodes = crate::take_measure_repass_nodes();
1140    let repass_nodes = crate::take_layout_repass_nodes();
1141    if measure_repass_nodes.is_empty() && repass_nodes.is_empty() {
1142        return Ok(());
1143    }
1144    for node_id in measure_repass_nodes {
1145        cranpose_core::bubble_measure_dirty(applier as &mut dyn Applier, node_id);
1146    }
1147    for node_id in repass_nodes {
1148        cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
1149    }
1150    applier.get_mut(root)?.mark_needs_layout();
1151    Ok(())
1152}
1153
1154struct LayoutBuilder {
1155    state: Rc<RefCell<LayoutBuilderState>>,
1156}
1157
1158impl LayoutBuilder {
1159    fn new_with_epoch(
1160        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1161        epoch: u64,
1162        slots: Rc<RefCell<SlotTable>>,
1163        frame_arena: FrameLayoutArena,
1164    ) -> Self {
1165        Self {
1166            state: Rc::new(RefCell::new(LayoutBuilderState::new_with_epoch(
1167                applier,
1168                epoch,
1169                slots,
1170                frame_arena,
1171            ))),
1172        }
1173    }
1174
1175    fn measure_node(
1176        &mut self,
1177        node_id: NodeId,
1178        constraints: Constraints,
1179    ) -> Result<Rc<MeasuredNode>, NodeError> {
1180        LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
1181    }
1182
1183    fn set_runtime_handle(&mut self, handle: Option<RuntimeHandle>) {
1184        self.state.borrow_mut().runtime_handle = handle;
1185    }
1186}
1187
1188impl Drop for LayoutBuilder {
1189    fn drop(&mut self) {
1190        if Rc::strong_count(&self.state) != 1 {
1191            return;
1192        }
1193        let Ok(mut state) = self.state.try_borrow_mut() else {
1194            return;
1195        };
1196        crate::render_state::replace_layout_frame_arena(std::mem::take(&mut state.frame_arena));
1197    }
1198}
1199
1200struct LayoutBuilderState {
1201    applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1202    runtime_handle: Option<RuntimeHandle>,
1203    /// Shared handle to the slot table. This is shared with ApplierSlotGuard
1204    /// to ensure panic-safety: even if we panic, the guard can restore slots.
1205    slots: Rc<RefCell<SlotTable>>,
1206    cache_epoch: u64,
1207    frame_arena: FrameLayoutArena,
1208}
1209
1210struct LayoutRuntimeFrameBindingCleanup {
1211    state: Rc<RefCell<LayoutRuntimeState>>,
1212}
1213
1214impl LayoutRuntimeFrameBindingCleanup {
1215    fn new(state: Rc<RefCell<LayoutRuntimeState>>) -> Self {
1216        Self { state }
1217    }
1218}
1219
1220impl Drop for LayoutRuntimeFrameBindingCleanup {
1221    fn drop(&mut self) {
1222        self.state.borrow().clear_frame_bindings();
1223    }
1224}
1225
1226impl LayoutBuilderState {
1227    fn new_with_epoch(
1228        applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1229        epoch: u64,
1230        slots: Rc<RefCell<SlotTable>>,
1231        frame_arena: FrameLayoutArena,
1232    ) -> Self {
1233        let runtime_handle = applier.borrow_typed().runtime_handle();
1234
1235        Self {
1236            applier,
1237            runtime_handle,
1238            slots,
1239            cache_epoch: epoch,
1240            frame_arena,
1241        }
1242    }
1243
1244    fn try_with_applier_result<R>(
1245        state_rc: &Rc<RefCell<Self>>,
1246        f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
1247    ) -> Option<Result<R, NodeError>> {
1248        let host = {
1249            let state = state_rc.borrow();
1250            Rc::clone(&state.applier)
1251        };
1252
1253        // Try to borrow - if already borrowed (nested call), return None
1254        let Ok(mut applier) = host.try_borrow_typed() else {
1255            return None;
1256        };
1257
1258        Some(f(&mut applier))
1259    }
1260
1261    fn with_applier_result<R>(
1262        state_rc: &Rc<RefCell<Self>>,
1263        f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
1264    ) -> Result<R, NodeError> {
1265        Self::try_with_applier_result(state_rc, f).unwrap_or_else(|| {
1266            Err(NodeError::MissingContext {
1267                id: NodeId::default(),
1268                reason: "applier already borrowed",
1269            })
1270        })
1271    }
1272
1273    /// Clears the is_placed flag for a node at the start of measurement.
1274    /// This ensures nodes that drop out of placement won't render with stale geometry.
1275    fn clear_node_placed(state_rc: &Rc<RefCell<Self>>, node_id: NodeId) {
1276        let host = {
1277            let state = state_rc.borrow();
1278            Rc::clone(&state.applier)
1279        };
1280        let Ok(mut applier) = host.try_borrow_typed() else {
1281            return;
1282        };
1283        // Try LayoutNode first, then SubcomposeLayoutNode
1284        if applier
1285            .with_node::<LayoutNode, _>(node_id, |node| {
1286                node.clear_placed();
1287            })
1288            .is_err()
1289        {
1290            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1291                node.clear_placed();
1292            });
1293        }
1294    }
1295
1296    fn measure_node(
1297        state_rc: Rc<RefCell<Self>>,
1298        node_id: NodeId,
1299        constraints: Constraints,
1300    ) -> Result<Rc<MeasuredNode>, NodeError> {
1301        let telemetry_start = Instant::now();
1302        // Clear is_placed at the start of measurement.
1303        // Nodes that are placed will have is_placed set to true via Placeable::place().
1304        // Nodes that drop out of placement (not placed this pass) will remain is_placed=false.
1305        Self::clear_node_placed(&state_rc, node_id);
1306
1307        // Try SubcomposeLayoutNode first
1308        if let Some(subcompose) =
1309            Self::try_measure_subcompose(Rc::clone(&state_rc), node_id, constraints)?
1310        {
1311            log_node_measure_telemetry(
1312                "subcompose",
1313                node_id,
1314                constraints,
1315                subcompose.size,
1316                subcompose.children.len(),
1317                telemetry_start,
1318            );
1319            return Ok(subcompose);
1320        }
1321
1322        // Try LayoutNode (the primary modern path)
1323        if let Some(result) = Self::try_with_applier_result(&state_rc, |applier| {
1324            match applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1325                LayoutNodeSnapshot::from_layout_node(layout_node)
1326            }) {
1327                Ok(snapshot) => Ok(Some(snapshot)),
1328                Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => Ok(None),
1329                Err(err) => Err(err),
1330            }
1331        }) {
1332            // Applier was available, process the result
1333            if let Some(snapshot) = result? {
1334                let measured = Self::measure_layout_node(
1335                    Rc::clone(&state_rc),
1336                    node_id,
1337                    snapshot,
1338                    constraints,
1339                )?;
1340                log_node_measure_telemetry(
1341                    "layout",
1342                    node_id,
1343                    constraints,
1344                    measured.size,
1345                    measured.children.len(),
1346                    telemetry_start,
1347                );
1348                return Ok(measured);
1349            }
1350        }
1351        // If applier was busy (None) or snapshot was None, fall through to fallback
1352
1353        // No alternate fallbacks - all widgets use LayoutNode or SubcomposeLayoutNode
1354        // If we reach here, it's an unknown node type (shouldn't happen in normal use)
1355        let measured = Rc::new(MeasuredNode::new(
1356            node_id,
1357            Size::default(),
1358            Point { x: 0.0, y: 0.0 },
1359            Point::default(), // No content offset for fallback nodes
1360            Vec::new(),
1361        ));
1362        log_node_measure_telemetry(
1363            "fallback",
1364            node_id,
1365            constraints,
1366            measured.size,
1367            measured.children.len(),
1368            telemetry_start,
1369        );
1370        Ok(measured)
1371    }
1372
1373    fn cached_measure_node_with_applier(
1374        applier: &mut MemoryApplier,
1375        node_id: NodeId,
1376        constraints: Constraints,
1377    ) -> Result<Option<Rc<MeasuredNode>>, NodeError> {
1378        let Some(data) = Self::layout_child_measure_data(applier, node_id)? else {
1379            return Ok(None);
1380        };
1381        if data.needs_measure || data.cache.epoch() == 0 {
1382            return Ok(None);
1383        }
1384
1385        let Some(measured) = data.cache.get_measurement(constraints) else {
1386            return Ok(None);
1387        };
1388
1389        if let Some(layout_state) = data.layout_state {
1390            let mut layout_state = layout_state.borrow_mut();
1391            layout_state.size = measured.size;
1392            layout_state.measurement_constraints = constraints;
1393            drop(layout_state);
1394            let _ = applier.with_node::<LayoutNode, _>(node_id, |node| {
1395                if data.needs_layout {
1396                    node.clear_needs_layout();
1397                }
1398            });
1399        } else {
1400            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1401                node.set_measured_size(measured.size);
1402                if data.needs_layout {
1403                    node.clear_needs_layout();
1404                }
1405            });
1406        }
1407
1408        Ok(Some(measured))
1409    }
1410
1411    fn try_measure_subcompose(
1412        state_rc: Rc<RefCell<Self>>,
1413        node_id: NodeId,
1414        constraints: Constraints,
1415    ) -> Result<Option<Rc<MeasuredNode>>, NodeError> {
1416        let applier_host = {
1417            let state = state_rc.borrow();
1418            Rc::clone(&state.applier)
1419        };
1420
1421        let (node_handle, resolved_modifiers) = {
1422            // Try to borrow - if already borrowed (nested measurement), return None
1423            let Ok(mut applier) = applier_host.try_borrow_typed() else {
1424                return Ok(None);
1425            };
1426            let node = match applier.get_mut(node_id) {
1427                Ok(node) => node,
1428                Err(NodeError::Missing { .. }) => return Ok(None),
1429                Err(err) => return Err(err),
1430            };
1431            let any = node.as_any_mut();
1432            if let Some(subcompose) =
1433                any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
1434            {
1435                let handle = subcompose.handle();
1436                let resolved_modifiers = handle.resolved_modifiers();
1437                (handle, resolved_modifiers)
1438            } else {
1439                return Ok(None);
1440            }
1441        };
1442
1443        let runtime_handle = {
1444            let mut state = state_rc.borrow_mut();
1445            if state.runtime_handle.is_none() {
1446                // Try to borrow - if already borrowed, we can't get runtime handle
1447                if let Ok(applier) = applier_host.try_borrow_typed() {
1448                    state.runtime_handle = applier.runtime_handle();
1449                }
1450            }
1451            state
1452                .runtime_handle
1453                .clone()
1454                .ok_or(NodeError::MissingContext {
1455                    id: node_id,
1456                    reason: "runtime handle required for subcomposition",
1457                })?
1458        };
1459
1460        let props = resolved_modifiers.layout_properties();
1461        let padding = resolved_modifiers.padding();
1462        let offset = resolved_modifiers.offset();
1463        let mut inner_constraints = normalize_constraints(subtract_padding(constraints, padding));
1464
1465        if let DimensionConstraint::Points(width) = props.width() {
1466            let constrained_width = width - padding.horizontal_sum();
1467            inner_constraints.max_width = inner_constraints.max_width.min(constrained_width);
1468            inner_constraints.min_width = inner_constraints.min_width.min(constrained_width);
1469        }
1470        if let DimensionConstraint::Points(height) = props.height() {
1471            let constrained_height = height - padding.vertical_sum();
1472            inner_constraints.max_height = inner_constraints.max_height.min(constrained_height);
1473            inner_constraints.min_height = inner_constraints.min_height.min(constrained_height);
1474        }
1475
1476        let mut slots_guard = SlotsGuard::take(Rc::clone(&state_rc));
1477        let slots_host = slots_guard.host();
1478        let applier_host_dyn: Rc<dyn ApplierHost> = applier_host.clone();
1479        let observer = SnapshotStateObserver::new(|callback| callback());
1480        let composer = Composer::new(
1481            Rc::clone(&slots_host),
1482            applier_host_dyn,
1483            runtime_handle.clone(),
1484            observer,
1485            Some(node_id),
1486        );
1487        composer.enter_phase(Phase::Measure);
1488
1489        let state_rc_clone = Rc::clone(&state_rc);
1490        let measure_error = RefCell::new(None);
1491        let state_rc_for_subcompose = Rc::clone(&state_rc_clone);
1492        let error_for_subcompose = &measure_error;
1493        let measured_children = node_handle.measured_children_scratch();
1494        let measured_children_for_subcompose = Rc::clone(&measured_children);
1495        let state_rc_for_cached = Rc::clone(&state_rc_clone);
1496        let error_for_cached = &measure_error;
1497        let measured_children_for_cached = Rc::clone(&measured_children);
1498        let measured_children_for_lookup = Rc::clone(&measured_children);
1499        let measured_children_for_retained = Rc::clone(&measured_children);
1500
1501        let measure_result = node_handle.measure_with_cached_batch(
1502            &composer,
1503            node_id,
1504            inner_constraints,
1505            CachedBatchMeasureInputs {
1506                measurer: Box::new(
1507                    move |child_id: NodeId, child_constraints: Constraints| -> Size {
1508                        match Self::measure_node(
1509                            Rc::clone(&state_rc_for_subcompose),
1510                            child_id,
1511                            child_constraints,
1512                        ) {
1513                            Ok(measured) => {
1514                                measured_children_for_subcompose
1515                                    .borrow_mut()
1516                                    .insert(child_id, Rc::clone(&measured));
1517                                measured.size
1518                            }
1519                            Err(err) => {
1520                                let mut slot = error_for_subcompose.borrow_mut();
1521                                if slot.is_none() {
1522                                    *slot = Some(err);
1523                                }
1524                                Size::default()
1525                            }
1526                        }
1527                    },
1528                ),
1529                cached_measure_batch_registrar: Box::new(
1530                    move |child_ids: &[NodeId],
1531                          child_constraints: Constraints,
1532                          out: &mut Vec<Option<Size>>| {
1533                        out.clear();
1534                        out.resize(child_ids.len(), None);
1535
1536                        let applier_host = {
1537                            let state = state_rc_for_cached.borrow();
1538                            Rc::clone(&state.applier)
1539                        };
1540                        let Ok(mut applier) = applier_host.try_borrow_typed() else {
1541                            return;
1542                        };
1543
1544                        let mut measured_children = measured_children_for_cached.borrow_mut();
1545                        for (index, &child_id) in child_ids.iter().enumerate() {
1546                            match Self::cached_measure_node_with_applier(
1547                                &mut applier,
1548                                child_id,
1549                                child_constraints,
1550                            ) {
1551                                Ok(Some(measured)) => {
1552                                    out[index] = Some(measured.size);
1553                                    measured_children.insert(child_id, Rc::clone(&measured));
1554                                }
1555                                Ok(None) => {}
1556                                Err(err) => {
1557                                    let mut slot = error_for_cached.borrow_mut();
1558                                    if slot.is_none() {
1559                                        *slot = Some(err);
1560                                    }
1561                                    break;
1562                                }
1563                            }
1564                        }
1565                    },
1566                ),
1567                retained_measure_lookup: Box::new(move |child_id| {
1568                    measured_children_for_lookup
1569                        .borrow()
1570                        .get(&child_id)
1571                        .cloned()
1572                }),
1573                retained_measure_registrar: Box::new(move |measurements| {
1574                    let mut measured_children = measured_children_for_retained.borrow_mut();
1575                    for measured in measurements {
1576                        measured_children.insert(measured.node_id(), Rc::clone(measured));
1577                    }
1578                }),
1579                error: &measure_error,
1580            },
1581        )?;
1582        drop(composer);
1583        slots_guard.restore(slots_host.into_table()?);
1584
1585        if let Some(err) = measure_error.borrow_mut().take() {
1586            return Err(err);
1587        }
1588
1589        // NOTE: Children are now managed by the composer via insert_child commands
1590        // (from parent_stack initialization with root). set_active_children is no longer used.
1591
1592        let cranpose_ui_layout::MeasureResult {
1593            size: measured_size,
1594            placements,
1595        } = measure_result;
1596
1597        let mut width = measured_size.width + padding.horizontal_sum();
1598        let mut height = measured_size.height + padding.vertical_sum();
1599
1600        width = resolve_dimension(
1601            width,
1602            props.width(),
1603            props.min_width(),
1604            props.max_width(),
1605            constraints.min_width,
1606            constraints.max_width,
1607        );
1608        height = resolve_dimension(
1609            height,
1610            props.height(),
1611            props.min_height(),
1612            props.max_height(),
1613            constraints.min_height,
1614            constraints.max_height,
1615        );
1616
1617        let mut children = Vec::with_capacity(placements.len());
1618        let mut measured_children_by_id = measured_children.borrow_mut();
1619
1620        // Update the SubcomposeLayoutNode's size (position will be set by parent's placement)
1621        if let Ok(mut applier) = applier_host.try_borrow_typed() {
1622            let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |parent_node| {
1623                parent_node.set_measured_size(Size { width, height });
1624                parent_node.clear_needs_measure();
1625                parent_node.clear_needs_layout();
1626            });
1627        }
1628
1629        for placement in &placements {
1630            let child = if let Some(measured) = measured_children_by_id.remove(&placement.node_id) {
1631                measured
1632            } else {
1633                // Policies may place subcomposed children without calling `measure()` first
1634                // (for example, when they only need a slot's rendered content). Keep the
1635                // existing fallback for that case, but preserve the policy-time measurement
1636                // whenever it exists so we don't silently remeasure lazy items with the
1637                // container's tighter constraints.
1638                Self::measure_node(Rc::clone(&state_rc), placement.node_id, inner_constraints)?
1639            };
1640            let policy_position = Point {
1641                x: padding.left + placement.x,
1642                y: padding.top + placement.y,
1643            };
1644            // Subcompose policies return raw placements and bypass the
1645            // child's `Placeable::place`, which normally adds the modifier
1646            // chain's node offset. Retained rendering reads the live node
1647            // position, so it must receive that same final coordinate. The
1648            // measured-tree edge keeps the raw policy position because
1649            // `build_layout_tree` applies `child.offset` itself.
1650            let retained_position = Point {
1651                x: policy_position.x + child.offset.x,
1652                y: policy_position.y + child.offset.y,
1653            };
1654
1655            // Critical: Update the child's retained placement state.
1656            // Standard layouts do this via Placeable::place(), but SubcomposeLayout
1657            // logic bypasses Placeables and returns raw Placements. A subcomposed
1658            // child can itself be a SubcomposeLayout (e.g. a `BoxWithConstraints`
1659            // inside a `LazyColumn` item), so both node kinds must be positioned
1660            // and marked placed; otherwise the applier-traversal render, layout,
1661            // and semantics builds cull the child's whole subtree (issue #305).
1662            if let Ok(mut applier) = applier_host.try_borrow_typed() {
1663                if applier
1664                    .with_node::<LayoutNode, _>(placement.node_id, |node| {
1665                        node.set_position(retained_position);
1666                    })
1667                    .is_err()
1668                {
1669                    let _ =
1670                        applier.with_node::<SubcomposeLayoutNode, _>(placement.node_id, |node| {
1671                            node.set_position(retained_position);
1672                        });
1673                }
1674            }
1675
1676            children.push(MeasuredChild {
1677                node: child,
1678                offset: policy_position,
1679            });
1680        }
1681
1682        // Update the SubcomposeLayoutNode's active children for rendering
1683        node_handle.set_active_children(children.iter().map(|c| c.node.node_id));
1684        node_handle.recycle_placement_scratch(placements);
1685
1686        Ok(Some(Rc::new(MeasuredNode::new(
1687            node_id,
1688            Size { width, height },
1689            offset,
1690            Point::default(), // Subcompose nodes: content_offset handled by child layout
1691            children,
1692        ))))
1693    }
1694    /// Measures through the layout modifier coordinator chain using reconciled modifier nodes.
1695    /// Iterates through LayoutModifierNode instances from the ModifierNodeChain and calls
1696    /// their measure() methods through the retained coordinator chain.
1697    ///
1698    /// Always succeeds, measuring either directly or through retained layout modifier nodes.
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;