Skip to main content

cranpose_ui/layout/
mod.rs

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