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#[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#[derive(Clone, Debug, PartialEq, Eq)]
324pub enum SemanticsAction {
325 Click { handler: SemanticsCallback },
326}
327
328#[derive(Clone, Debug, PartialEq, Eq)]
331pub enum SemanticsRole {
332 Layout,
334 Subcompose,
336 Text { value: String },
338 Spacer,
340 Button,
342 Unknown,
344}
345
346#[derive(Clone, Debug, PartialEq)]
353pub struct SemanticsNode {
354 pub node_id: NodeId,
355 pub node_generation: u32,
357 pub role: SemanticsRole,
359 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 pub on_click: Option<SemanticsCustomAction>,
370 pub on_long_click: Option<SemanticsLongClick>,
372 pub on_long_click_label: Option<String>,
374 pub on_magic_tap: Option<SemanticsMagicTap>,
376 pub on_magic_tap_label: Option<String>,
378 pub input_labels: Vec<String>,
380 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 pub canvas_children: Vec<CanvasSemanticsNode>,
389 pub editable_text: bool,
390 pub multiline: bool,
392 pub hidden: bool,
394 pub is_modal: bool,
396 pub merge_descendants: bool,
399 pub selectable_group: bool,
401 pub pane_title: Option<String>,
403 pub error: Option<String>,
405 pub password: bool,
407 pub traversal_index: f32,
409 pub text: Option<String>,
411 pub text_selection: Option<TextRange>,
412 pub focusable: bool,
415 pub focused: bool,
417 pub live_region: Option<LiveRegionMode>,
420 pub progress: Option<ProgressBarRangeInfo>,
423 pub set_progress: Option<SemanticsSetProgress>,
425 pub set_text: Option<SemanticsSetText>,
427 pub set_selection: Option<SemanticsSetSelection>,
430 pub expand: Option<SemanticsExpand>,
432 pub collapse: Option<SemanticsExpand>,
434 pub dismiss: Option<SemanticsDismiss>,
436 pub vertical_scroll: Option<ScrollAxisRange>,
438 pub horizontal_scroll: Option<ScrollAxisRange>,
440 pub scroll_by: Option<SemanticsScrollBy>,
442 pub scroll_to_index: Option<SemanticsScrollToIndex>,
444 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#[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 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#[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#[derive(Debug, Clone)]
618pub struct LayoutBox {
619 pub node_id: NodeId,
620 pub node_generation: u32,
622 pub rect: GeometryRect,
623 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#[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#[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
708pub 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#[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 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 pub fn into_layout_tree(self) -> Option<LayoutTree> {
769 self.layout_tree
770 }
771
772 pub fn layout_tree(&self) -> Option<LayoutTree> {
774 self.layout_tree.clone()
775 }
776}
777
778pub 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
786pub 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 { .. }) | Err(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 { .. }) | Err(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
896pub 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 { .. }) | Err(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 { .. }) | Err(NodeError::Missing { .. }) => {
970 Ok(None)
971 }
972 Err(err) => Err(err),
973 }
974 }
975
976 node(applier, root).map(|root| root.map(SemanticsTree::new))
977}
978
979#[derive(Clone, Copy, Debug, PartialEq, Eq)]
980pub struct MeasureLayoutOptions {
981 pub collect_semantics: bool,
982 pub build_layout_tree: bool,
983}
984
985impl Default for MeasureLayoutOptions {
986 fn default() -> Self {
987 Self {
988 collect_semantics: true,
989 build_layout_tree: true,
990 }
991 }
992}
993
994pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
1002 Ok(applier.get_mut(root)?.needs_layout())
1003}
1004
1005fn publish_window_geometry(
1006 modifier_slices: &crate::modifier::ModifierNodeSlices,
1007 top_left: Point,
1008 layer_translation: Point,
1009 size: Size,
1010) {
1011 let origin = Point {
1012 x: top_left.x + layer_translation.x,
1013 y: top_left.y + layer_translation.y,
1014 };
1015 if let Some(sink) = modifier_slices.text_field_window_origin() {
1016 sink.set(origin);
1017 }
1018 if let Some(sink) = modifier_slices.viewport_window_rect() {
1019 sink.set(GeometryRect {
1020 x: origin.x,
1021 y: origin.y,
1022 width: size.width,
1023 height: size.height,
1024 });
1025 }
1026 modifier_slices.publish_pointer_input_size(size);
1027}
1028
1029fn children_in_this_window(applier: &mut MemoryApplier, children: Vec<NodeId>) -> Vec<NodeId> {
1030 children
1031 .into_iter()
1032 .filter(|child| !crate::modifier::is_window_root(applier, *child))
1033 .collect()
1034}
1035
1036pub fn tree_needs_semantics(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
1042 Ok(applier.get_mut(root)?.needs_semantics())
1043}
1044
1045#[cfg(test)]
1046pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
1047 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
1048}
1049
1050pub fn measure_layout(
1052 applier: &mut MemoryApplier,
1053 root: NodeId,
1054 max_size: Size,
1055) -> Result<LayoutMeasurements, NodeError> {
1056 measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
1057}
1058
1059pub fn measure_layout_with_options(
1060 applier: &mut MemoryApplier,
1061 root: NodeId,
1062 max_size: Size,
1063 options: MeasureLayoutOptions,
1064) -> Result<LayoutMeasurements, NodeError> {
1065 let telemetry_start = Instant::now();
1066 process_pending_layout_repasses(applier, root)?;
1067 let after_repasses = Instant::now();
1068
1069 let constraints = Constraints {
1070 min_width: 0.0,
1071 max_width: max_size.width,
1072 min_height: 0.0,
1073 max_height: max_size.height,
1074 };
1075
1076 let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
1077 .with_node::<LayoutNode, _>(root, |node| {
1078 (
1079 node.needs_measure(),
1080 node.needs_semantics(),
1081 node.cache_handles().epoch(),
1082 )
1083 }) {
1084 Ok(tuple) => tuple,
1085 Err(NodeError::TypeMismatch { .. }) => {
1086 let node = applier.get_mut(root)?;
1087 let measure_dirty = node.needs_measure();
1088 let semantics_dirty = node.needs_semantics();
1089 (measure_dirty, semantics_dirty, 0)
1090 }
1091 Err(err) => return Err(err),
1092 };
1093
1094 let epoch = if needs_remeasure {
1095 crate::render_state::next_layout_cache_epoch()
1096 } else if cached_epoch != 0 {
1097 cached_epoch
1098 } else {
1099 crate::render_state::current_layout_cache_epoch()
1100 };
1101
1102 let guard = ApplierSlotGuard::new(applier);
1103 let applier_host = guard.host();
1104 let slots_handle = guard.slots_handle();
1105 let after_guard = Instant::now();
1106
1107 let frame_arena = crate::render_state::take_layout_frame_arena();
1108 let mut builder = LayoutBuilder::new_with_epoch(
1109 Rc::clone(&applier_host),
1110 epoch,
1111 Rc::clone(&slots_handle),
1112 frame_arena,
1113 );
1114 let after_builder = Instant::now();
1115
1116 let measured = builder.measure_node(root, normalize_constraints(constraints))?;
1117 let after_measure = Instant::now();
1118
1119 if let Ok(mut applier) = applier_host.try_borrow_typed()
1120 && applier
1121 .with_node::<LayoutNode, _>(root, |node| {
1122 node.set_position(Point::default());
1123 })
1124 .is_err()
1125 {
1126 let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
1127 node.set_position(Point::default());
1128 });
1129 }
1130 let after_root_place = Instant::now();
1131
1132 let (layout_tree, semantics) = {
1133 let mut applier_ref = applier_host.borrow_typed();
1134 let layout_tree = if options.build_layout_tree {
1135 Some(build_layout_tree(&mut applier_ref, &measured)?)
1136 } else {
1137 None
1138 };
1139 let semantics = if options.collect_semantics {
1140 let semantics_tree = if let Some(layout_tree) = layout_tree.as_ref() {
1141 clear_semantics_dirty_flags(&mut applier_ref, &measured)?;
1142 build_semantics_tree_from_layout_tree(layout_tree)
1143 } else {
1144 build_semantics_tree_from_live_nodes(&mut applier_ref, &measured)?
1145 };
1146 Some(semantics_tree)
1147 } else {
1148 None
1149 };
1150 (layout_tree, semantics)
1151 };
1152 let after_aux = Instant::now();
1153
1154 drop(builder);
1155 let after_builder_drop = Instant::now();
1156
1157 drop(guard);
1158 let after_guard_drop = Instant::now();
1159
1160 log_layout_measure_telemetry(LayoutMeasureTelemetry {
1161 root,
1162 start: telemetry_start,
1163 after_repasses,
1164 after_guard,
1165 after_builder,
1166 after_measure,
1167 after_root_place,
1168 after_aux,
1169 after_builder_drop,
1170 after_guard_drop,
1171 });
1172
1173 Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
1174}
1175
1176fn process_pending_layout_repasses(
1177 applier: &mut MemoryApplier,
1178 root: NodeId,
1179) -> Result<(), NodeError> {
1180 for node_id in crate::render_state::take_modifier_slice_repass_nodes() {
1181 if let Ok(node) = applier.get_mut(node_id) {
1182 let any = node.as_any_mut();
1183 if let Some(layout) = any.downcast_mut::<crate::widgets::nodes::LayoutNode>() {
1184 layout.mark_modifier_slices_dirty();
1185 } else if let Some(subcompose) =
1186 any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
1187 {
1188 subcompose.mark_modifier_slices_dirty();
1189 }
1190 }
1191 }
1192 let measure_repass_nodes = crate::take_measure_repass_nodes();
1193 let repass_nodes = crate::take_layout_repass_nodes();
1194 if measure_repass_nodes.is_empty() && repass_nodes.is_empty() {
1195 return Ok(());
1196 }
1197 for node_id in measure_repass_nodes {
1198 cranpose_core::bubble_measure_dirty(applier as &mut dyn Applier, node_id);
1199 }
1200 for node_id in repass_nodes {
1201 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
1202 }
1203 applier.get_mut(root)?.mark_needs_layout();
1204 Ok(())
1205}
1206
1207struct LayoutBuilder {
1208 state: Rc<RefCell<LayoutBuilderState>>,
1209}
1210
1211impl LayoutBuilder {
1212 fn new_with_epoch(
1213 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1214 epoch: u64,
1215 slots: Rc<RefCell<SlotTable>>,
1216 frame_arena: FrameLayoutArena,
1217 ) -> Self {
1218 Self {
1219 state: Rc::new(RefCell::new(LayoutBuilderState::new_with_epoch(
1220 applier,
1221 epoch,
1222 slots,
1223 frame_arena,
1224 ))),
1225 }
1226 }
1227
1228 fn measure_node(
1229 &mut self,
1230 node_id: NodeId,
1231 constraints: Constraints,
1232 ) -> Result<Rc<MeasuredNode>, NodeError> {
1233 LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
1234 }
1235
1236 fn set_runtime_handle(&mut self, handle: Option<RuntimeHandle>) {
1237 self.state.borrow_mut().runtime_handle = handle;
1238 }
1239}
1240
1241impl Drop for LayoutBuilder {
1242 fn drop(&mut self) {
1243 if Rc::strong_count(&self.state) != 1 {
1244 return;
1245 }
1246 let Ok(mut state) = self.state.try_borrow_mut() else {
1247 return;
1248 };
1249 crate::render_state::replace_layout_frame_arena(std::mem::take(&mut state.frame_arena));
1250 }
1251}
1252
1253struct LayoutBuilderState {
1254 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1255 runtime_handle: Option<RuntimeHandle>,
1256 slots: Rc<RefCell<SlotTable>>,
1257 cache_epoch: u64,
1258 frame_arena: FrameLayoutArena,
1259}
1260
1261struct LayoutRuntimeFrameBindingCleanup {
1262 state: Rc<RefCell<LayoutRuntimeState>>,
1263}
1264
1265impl LayoutRuntimeFrameBindingCleanup {
1266 fn new(state: Rc<RefCell<LayoutRuntimeState>>) -> Self {
1267 Self { state }
1268 }
1269}
1270
1271impl Drop for LayoutRuntimeFrameBindingCleanup {
1272 fn drop(&mut self) {
1273 self.state.borrow().clear_frame_bindings();
1274 }
1275}
1276
1277impl LayoutBuilderState {
1278 fn new_with_epoch(
1279 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1280 epoch: u64,
1281 slots: Rc<RefCell<SlotTable>>,
1282 frame_arena: FrameLayoutArena,
1283 ) -> Self {
1284 let runtime_handle = applier.borrow_typed().runtime_handle();
1285
1286 Self {
1287 applier,
1288 runtime_handle,
1289 slots,
1290 cache_epoch: epoch,
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 { .. }) | Err(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.clone(),
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 { .. }) | Err(NodeError::Missing { .. }) => {
1841 Ok(None)
1842 }
1843 Err(err) => Err(err),
1844 }
1845 }
1846 Err(NodeError::Missing { .. }) => Ok(None),
1847 Err(err) => Err(err),
1848 }
1849 }
1850
1851 fn measure_layout_node(
1852 state_rc: Rc<RefCell<Self>>,
1853 node_id: NodeId,
1854 snapshot: LayoutNodeSnapshot,
1855 constraints: Constraints,
1856 ) -> Result<Rc<MeasuredNode>, NodeError> {
1857 let cache_epoch = {
1858 let state = state_rc.borrow();
1859 state.cache_epoch
1860 };
1861 let LayoutNodeSnapshot {
1862 measure_policy,
1863 cache,
1864 layout_runtime_state,
1865 needs_layout,
1866 needs_measure,
1867 } = snapshot;
1868 cache.activate(cache_epoch);
1869
1870 if !needs_measure
1871 && !needs_layout
1872 && let Some(cached) = cache.get_measurement(constraints)
1873 {
1874 Self::with_applier_result(&state_rc, |applier| {
1875 applier.with_node::<LayoutNode, _>(node_id, |node| {
1876 node.clear_needs_measure();
1877 node.clear_needs_layout();
1878 })
1879 })
1880 .ok();
1881 return Ok(cached);
1882 }
1883
1884 let (runtime_handle, applier_host) = {
1885 let state = state_rc.borrow();
1886 (state.runtime_handle.clone(), Rc::clone(&state.applier))
1887 };
1888
1889 let measure_handle = LayoutMeasureHandle::new(Rc::clone(&state_rc));
1890 let error = Rc::new(RefCell::new(None));
1891 let mut pools = VecPools::acquire(Rc::clone(&state_rc));
1892 let (records, child_ids, layout_node_data, placements) = pools.parts();
1893
1894 applier_host
1895 .borrow_typed()
1896 .with_node::<LayoutNode, _>(node_id, |node| {
1897 child_ids.extend_from_slice(&node.children);
1898 })?;
1899
1900 let mut valid_child_count = 0;
1901 for index in 0..child_ids.len() {
1902 let child_id = child_ids[index];
1903 let child_exists = {
1904 let mut applier = applier_host.borrow_typed();
1905 Self::layout_child_measure_data(&mut applier, child_id)?.is_some()
1906 };
1907 if child_exists {
1908 child_ids[valid_child_count] = child_id;
1909 valid_child_count += 1;
1910 }
1911 }
1912 child_ids.truncate(valid_child_count);
1913
1914 let _frame_binding_cleanup =
1915 LayoutRuntimeFrameBindingCleanup::new(Rc::clone(&layout_runtime_state));
1916
1917 {
1918 let mut runtime_state = layout_runtime_state.borrow_mut();
1919 runtime_state.reconcile_child_measurables(child_ids.as_slice());
1920
1921 for (index, &child_id) in child_ids.iter().enumerate() {
1922 let data = {
1923 let mut applier = applier_host.borrow_typed();
1924 Self::layout_child_measure_data(&mut applier, child_id)?
1925 };
1926 let Some(data) = data else {
1927 continue;
1928 };
1929
1930 let child_is_dirty = data.needs_layout || data.needs_measure;
1931 let child_cache_epoch = if child_is_dirty {
1932 cache_epoch
1933 } else {
1934 data.cache.epoch()
1935 };
1936 let child_state = runtime_state.child_state(index);
1937 child_state.configure(LayoutChildMeasureConfig {
1938 applier: Rc::clone(&applier_host),
1939 node_id: child_id,
1940 error: Rc::clone(&error),
1941 runtime_handle: runtime_handle.clone(),
1942 cache: data.cache,
1943 cache_epoch: child_cache_epoch,
1944 force_remeasure: child_is_dirty,
1945 measure_handle: Some(measure_handle.clone()),
1946 layout_state: data.layout_state,
1947 });
1948 records.push((child_id, ChildRecord { state: child_state }));
1949 }
1950 }
1951
1952 let chain_constraints = constraints;
1953
1954 let modifier_chain_result = {
1955 let mut runtime_state = layout_runtime_state.borrow_mut();
1956 Self::measure_through_modifier_chain(
1957 &state_rc,
1958 node_id,
1959 &mut runtime_state,
1960 &measure_policy,
1961 chain_constraints,
1962 layout_node_data,
1963 placements,
1964 )
1965 };
1966
1967 let (width, height, content_offset, offset, window_root) = {
1968 let result = modifier_chain_result;
1969 if let Some(err) = error.borrow_mut().take() {
1970 return Err(err);
1971 }
1972
1973 (
1974 result.size.width,
1975 result.size.height,
1976 result.content_offset,
1977 result.offset,
1978 result.window_root,
1979 )
1980 };
1981
1982 let mut measured_children = Vec::with_capacity(records.len());
1983 for (child_id, record) in records.iter() {
1984 if let Some(measured) = record.state.take_measured() {
1985 let placed = placements
1986 .iter()
1987 .find(|placement| placement.node_id == *child_id)
1988 .map(|placement| Point {
1989 x: placement.x,
1990 y: placement.y,
1991 });
1992 if let Some(raw) = placed {
1993 record.state.place_retained(Point {
1994 x: raw.x + measured.offset.x,
1995 y: raw.y + measured.offset.y,
1996 });
1997 }
1998 let base_position = placed
1999 .or_else(|| record.state.last_position())
2000 .unwrap_or(Point { x: 0.0, y: 0.0 });
2001 let position = Point {
2002 x: content_offset.x + base_position.x,
2003 y: content_offset.y + base_position.y,
2004 };
2005 measured_children.push(MeasuredChild {
2006 node: measured,
2007 offset: position,
2008 });
2009 }
2010 }
2011
2012 let measured = Rc::new(
2013 MeasuredNode::new(
2014 node_id,
2015 Size { width, height },
2016 offset,
2017 content_offset,
2018 measured_children,
2019 )
2020 .with_window_root(window_root),
2021 );
2022
2023 cache.store_measurement(constraints, Rc::clone(&measured));
2024
2025 Self::with_applier_result(&state_rc, |applier| {
2026 applier.with_node::<LayoutNode, _>(node_id, |node| {
2027 node.clear_needs_measure();
2028 node.clear_needs_layout();
2029 node.set_measured_size(Size { width, height });
2030 node.set_content_offset(content_offset);
2031 })
2032 })
2033 .ok();
2034
2035 Ok(measured)
2036 }
2037}
2038
2039struct LayoutChildMeasureData {
2040 cache: LayoutNodeCacheHandles,
2041 layout_state: Option<Rc<RefCell<LayoutState>>>,
2042 needs_layout: bool,
2043 needs_measure: bool,
2044}
2045
2046struct LayoutNodeSnapshot {
2047 measure_policy: Rc<dyn MeasurePolicy>,
2048 cache: LayoutNodeCacheHandles,
2049 layout_runtime_state: Rc<RefCell<LayoutRuntimeState>>,
2050 needs_layout: bool,
2051 needs_measure: bool,
2052}
2053
2054impl LayoutNodeSnapshot {
2055 fn from_layout_node(node: &LayoutNode) -> Self {
2056 Self {
2057 measure_policy: Rc::clone(&node.measure_policy),
2058 cache: node.cache_handles(),
2059 layout_runtime_state: node.layout_runtime_state_handle(),
2060 needs_layout: node.needs_layout(),
2061 needs_measure: node.needs_measure(),
2062 }
2063 }
2064}
2065
2066struct VecPools {
2067 state: Rc<RefCell<LayoutBuilderState>>,
2068 records: Vec<(NodeId, ChildRecord)>,
2069 child_ids: Vec<NodeId>,
2070 layout_node_data: Vec<LayoutModifierNodeData>,
2071 placements: Vec<Placement>,
2072}
2073
2074impl VecPools {
2075 fn acquire(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
2076 let (records, child_ids, layout_node_data, placements) = {
2077 let mut state_mut = state.borrow_mut();
2078 (
2079 state_mut.frame_arena.tmp_records.acquire(),
2080 state_mut.frame_arena.tmp_child_ids.acquire(),
2081 state_mut.frame_arena.tmp_layout_node_data.acquire(),
2082 state_mut.frame_arena.tmp_placements.acquire(),
2083 )
2084 };
2085 Self {
2086 state,
2087 records,
2088 child_ids,
2089 layout_node_data,
2090 placements,
2091 }
2092 }
2093
2094 #[allow(clippy::type_complexity)]
2095 fn parts(
2096 &mut self,
2097 ) -> (
2098 &mut Vec<(NodeId, ChildRecord)>,
2099 &mut Vec<NodeId>,
2100 &mut Vec<LayoutModifierNodeData>,
2101 &mut Vec<Placement>,
2102 ) {
2103 (
2104 &mut self.records,
2105 &mut self.child_ids,
2106 &mut self.layout_node_data,
2107 &mut self.placements,
2108 )
2109 }
2110}
2111
2112impl Drop for VecPools {
2113 fn drop(&mut self) {
2114 let mut state = self.state.borrow_mut();
2115 state
2116 .frame_arena
2117 .tmp_records
2118 .release(std::mem::take(&mut self.records));
2119 state
2120 .frame_arena
2121 .tmp_child_ids
2122 .release(std::mem::take(&mut self.child_ids));
2123 state
2124 .frame_arena
2125 .tmp_layout_node_data
2126 .release(std::mem::take(&mut self.layout_node_data));
2127 state
2128 .frame_arena
2129 .tmp_placements
2130 .release(std::mem::take(&mut self.placements));
2131 }
2132}
2133
2134struct SlotsGuard {
2135 state: Rc<RefCell<LayoutBuilderState>>,
2136 slots: Option<SlotTable>,
2137}
2138
2139impl SlotsGuard {
2140 fn take(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
2141 let slots = {
2142 let state_ref = state.borrow();
2143 let mut slots_ref = state_ref.slots.borrow_mut();
2144 std::mem::take(&mut *slots_ref)
2145 };
2146 Self {
2147 state,
2148 slots: Some(slots),
2149 }
2150 }
2151
2152 fn host(&mut self) -> Rc<SlotsHost> {
2153 let slots = self.slots.take().unwrap_or_default();
2154 Rc::new(SlotsHost::new(slots))
2155 }
2156
2157 fn restore(&mut self, slots: SlotTable) {
2158 debug_assert!(self.slots.is_none());
2159 self.slots = Some(slots);
2160 }
2161}
2162
2163impl Drop for SlotsGuard {
2164 fn drop(&mut self) {
2165 if let Some(slots) = self.slots.take() {
2166 let state_ref = self.state.borrow();
2167 *state_ref.slots.borrow_mut() = slots;
2168 }
2169 }
2170}
2171
2172#[derive(Clone)]
2173struct LayoutMeasureHandle {
2174 state: Rc<RefCell<LayoutBuilderState>>,
2175}
2176
2177impl LayoutMeasureHandle {
2178 fn new(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
2179 Self { state }
2180 }
2181
2182 fn measure(
2183 &self,
2184 node_id: NodeId,
2185 constraints: Constraints,
2186 ) -> Result<Rc<MeasuredNode>, NodeError> {
2187 LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
2188 }
2189}
2190
2191#[derive(Debug, Clone)]
2192pub(crate) struct MeasuredNode {
2193 node_id: NodeId,
2194 size: Size,
2195 offset: Point,
2196 content_offset: Point,
2197 children: Vec<MeasuredChild>,
2198 window_root: bool,
2199}
2200
2201impl MeasuredNode {
2202 fn new(
2203 node_id: NodeId,
2204 size: Size,
2205 offset: Point,
2206 content_offset: Point,
2207 children: Vec<MeasuredChild>,
2208 ) -> Self {
2209 Self {
2210 node_id,
2211 size,
2212 offset,
2213 content_offset,
2214 children,
2215 window_root: false,
2216 }
2217 }
2218
2219 fn with_window_root(mut self, window_root: bool) -> Self {
2220 self.window_root = window_root;
2221 self
2222 }
2223
2224 pub(crate) fn size_for_parent(&self) -> Size {
2225 if self.window_root {
2226 Size::new(0.0, 0.0)
2227 } else {
2228 self.size
2229 }
2230 }
2231
2232 #[cfg(test)]
2233 pub(crate) fn leaf(node_id: NodeId, size: Size) -> Self {
2234 Self::new(
2235 node_id,
2236 size,
2237 Point::default(),
2238 Point::default(),
2239 Vec::new(),
2240 )
2241 }
2242
2243 pub(crate) fn node_id(&self) -> NodeId {
2244 self.node_id
2245 }
2246
2247 pub(crate) fn size(&self) -> Size {
2248 self.size
2249 }
2250}
2251
2252#[derive(Debug, Clone)]
2253struct MeasuredChild {
2254 node: Rc<MeasuredNode>,
2255 offset: Point,
2256}
2257
2258struct ChildRecord {
2259 state: Rc<LayoutChildMeasureState>,
2260}
2261
2262struct CoordinatorFrame<'a> {
2263 measure_policy: &'a Rc<dyn MeasurePolicy>,
2264 scope: &'a dyn cranpose_ui_layout::MeasureScope,
2265 measurables: &'a [Box<dyn Measurable>],
2266 placements: RefCell<&'a mut Vec<Placement>>,
2267 context: RefCell<LayoutNodeContext>,
2268}
2269
2270impl<'a> CoordinatorFrame<'a> {
2271 fn new(
2272 measure_policy: &'a Rc<dyn MeasurePolicy>,
2273 scope: &'a dyn cranpose_ui_layout::MeasureScope,
2274 measurables: &'a [Box<dyn Measurable>],
2275 placements: &'a mut Vec<Placement>,
2276 ) -> Self {
2277 Self {
2278 measure_policy,
2279 scope,
2280 measurables,
2281 placements: RefCell::new(placements),
2282 context: RefCell::new(LayoutNodeContext::new()),
2283 }
2284 }
2285
2286 fn take_invalidations(&self) -> Vec<InvalidationKind> {
2287 self.context.borrow_mut().take_invalidations()
2288 }
2289}
2290
2291struct CoordinatorLink<'chain, 'frame_ref, 'frame_data> {
2292 chain: &'chain CoordinatorChain,
2293 frame: &'frame_ref CoordinatorFrame<'frame_data>,
2294 index: usize,
2295}
2296
2297impl Measurable for CoordinatorLink<'_, '_, '_> {
2298 fn measure(&self, constraints: Constraints) -> Placeable {
2299 self.chain.measure_from(self.index, self.frame, constraints)
2300 }
2301
2302 fn min_intrinsic_width(&self, height: f32) -> f32 {
2303 self.chain
2304 .min_intrinsic_width_from(self.index, self.frame, height)
2305 }
2306
2307 fn max_intrinsic_width(&self, height: f32) -> f32 {
2308 self.chain
2309 .max_intrinsic_width_from(self.index, self.frame, height)
2310 }
2311
2312 fn min_intrinsic_height(&self, width: f32) -> f32 {
2313 self.chain
2314 .min_intrinsic_height_from(self.index, self.frame, width)
2315 }
2316
2317 fn max_intrinsic_height(&self, width: f32) -> f32 {
2318 self.chain
2319 .max_intrinsic_height_from(self.index, self.frame, width)
2320 }
2321}
2322
2323struct CoordinatorNode {
2324 modifier_index: usize,
2325 node: Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
2326 measured_size: Cell<Size>,
2327 accumulated_offset: Cell<Point>,
2328}
2329
2330impl CoordinatorNode {
2331 fn new(
2332 modifier_index: usize,
2333 node: Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
2334 ) -> Self {
2335 Self {
2336 modifier_index,
2337 node,
2338 measured_size: Cell::new(Size::default()),
2339 accumulated_offset: Cell::new(Point::default()),
2340 }
2341 }
2342
2343 fn matches(
2344 &self,
2345 modifier_index: usize,
2346 node: &Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
2347 ) -> bool {
2348 self.modifier_index == modifier_index && Rc::ptr_eq(&self.node, node)
2349 }
2350
2351 #[cfg(test)]
2352 fn ptr(&self) -> usize {
2353 Rc::as_ptr(&self.node) as *const () as usize
2354 }
2355}
2356
2357#[derive(Default)]
2358struct CoordinatorChain {
2359 nodes: Vec<CoordinatorNode>,
2360}
2361
2362impl CoordinatorChain {
2363 fn reconcile(&mut self, layout_node_data: &[LayoutModifierNodeData]) {
2364 if self.matches(layout_node_data) {
2365 return;
2366 }
2367
2368 let mut previous_nodes = std::mem::take(&mut self.nodes);
2369 self.nodes.reserve(layout_node_data.len());
2370
2371 for (modifier_index, node) in layout_node_data.iter() {
2372 if let Some(position) = previous_nodes
2373 .iter()
2374 .position(|candidate| candidate.matches(*modifier_index, node))
2375 {
2376 self.nodes.push(previous_nodes.swap_remove(position));
2377 } else {
2378 self.nodes
2379 .push(CoordinatorNode::new(*modifier_index, Rc::clone(node)));
2380 }
2381 }
2382 }
2383
2384 fn matches(&self, layout_node_data: &[LayoutModifierNodeData]) -> bool {
2385 self.nodes.len() == layout_node_data.len()
2386 && self
2387 .nodes
2388 .iter()
2389 .zip(layout_node_data.iter())
2390 .all(|(node, (modifier_index, node_rc))| node.matches(*modifier_index, node_rc))
2391 }
2392
2393 fn measure_from(
2394 &self,
2395 index: usize,
2396 frame: &CoordinatorFrame<'_>,
2397 constraints: Constraints,
2398 ) -> Placeable {
2399 let Some(node) = self.nodes.get(index) else {
2400 let mut placements = frame.placements.borrow_mut();
2401 let size = frame.measure_policy.measure_into(
2402 frame.scope,
2403 frame.measurables,
2404 constraints,
2405 &mut placements,
2406 );
2407 return Placeable::value(size.width, size.height, NodeId::default());
2408 };
2409
2410 let wrapped = CoordinatorLink {
2411 chain: self,
2412 frame,
2413 index: index + 1,
2414 };
2415 let node_borrow = node.node.borrow();
2416
2417 let Some(layout_node) = node_borrow.as_layout_node() else {
2418 let placeable = wrapped.measure(constraints);
2419 let child_accumulated = self.total_content_offset_from(index + 1);
2420 node.accumulated_offset.set(child_accumulated);
2421 return Placeable::value_with_offset(
2422 placeable.width(),
2423 placeable.height(),
2424 NodeId::default(),
2425 (child_accumulated.x, child_accumulated.y),
2426 );
2427 };
2428
2429 let result = match frame.context.try_borrow_mut() {
2430 Ok(mut context) => layout_node.measure(&mut *context, &wrapped, constraints),
2431 Err(_) => {
2432 let mut temp = LayoutNodeContext::new();
2433 let result = layout_node.measure(&mut temp, &wrapped, constraints);
2434 if let Ok(mut context) = frame.context.try_borrow_mut() {
2435 for kind in temp.take_invalidations() {
2436 context.invalidate(kind);
2437 }
2438 }
2439 result
2440 }
2441 };
2442
2443 node.measured_size.set(result.size);
2444 let local_offset = Point {
2445 x: result.placement_offset_x,
2446 y: result.placement_offset_y,
2447 };
2448 let child_accumulated = self.total_content_offset_from(index + 1);
2449 let accumulated = Point {
2450 x: local_offset.x + child_accumulated.x,
2451 y: local_offset.y + child_accumulated.y,
2452 };
2453 node.accumulated_offset.set(accumulated);
2454
2455 Placeable::value_with_offset(
2456 result.size.width,
2457 result.size.height,
2458 NodeId::default(),
2459 (accumulated.x, accumulated.y),
2460 )
2461 }
2462
2463 fn min_intrinsic_width_from(
2464 &self,
2465 index: usize,
2466 frame: &CoordinatorFrame<'_>,
2467 height: f32,
2468 ) -> f32 {
2469 let Some(node) = self.nodes.get(index) else {
2470 return frame
2471 .measure_policy
2472 .min_intrinsic_width(frame.measurables, height);
2473 };
2474 let wrapped = CoordinatorLink {
2475 chain: self,
2476 frame,
2477 index: index + 1,
2478 };
2479 let node_borrow = node.node.borrow();
2480 node_borrow
2481 .as_layout_node()
2482 .map(|layout_node| layout_node.min_intrinsic_width(&wrapped, height))
2483 .unwrap_or_else(|| wrapped.min_intrinsic_width(height))
2484 }
2485
2486 fn max_intrinsic_width_from(
2487 &self,
2488 index: usize,
2489 frame: &CoordinatorFrame<'_>,
2490 height: f32,
2491 ) -> f32 {
2492 let Some(node) = self.nodes.get(index) else {
2493 return frame
2494 .measure_policy
2495 .max_intrinsic_width(frame.measurables, height);
2496 };
2497 let wrapped = CoordinatorLink {
2498 chain: self,
2499 frame,
2500 index: index + 1,
2501 };
2502 let node_borrow = node.node.borrow();
2503 node_borrow
2504 .as_layout_node()
2505 .map(|layout_node| layout_node.max_intrinsic_width(&wrapped, height))
2506 .unwrap_or_else(|| wrapped.max_intrinsic_width(height))
2507 }
2508
2509 fn min_intrinsic_height_from(
2510 &self,
2511 index: usize,
2512 frame: &CoordinatorFrame<'_>,
2513 width: f32,
2514 ) -> f32 {
2515 let Some(node) = self.nodes.get(index) else {
2516 return frame
2517 .measure_policy
2518 .min_intrinsic_height(frame.measurables, width);
2519 };
2520 let wrapped = CoordinatorLink {
2521 chain: self,
2522 frame,
2523 index: index + 1,
2524 };
2525 let node_borrow = node.node.borrow();
2526 node_borrow
2527 .as_layout_node()
2528 .map(|layout_node| layout_node.min_intrinsic_height(&wrapped, width))
2529 .unwrap_or_else(|| wrapped.min_intrinsic_height(width))
2530 }
2531
2532 fn max_intrinsic_height_from(
2533 &self,
2534 index: usize,
2535 frame: &CoordinatorFrame<'_>,
2536 width: f32,
2537 ) -> f32 {
2538 let Some(node) = self.nodes.get(index) else {
2539 return frame
2540 .measure_policy
2541 .max_intrinsic_height(frame.measurables, width);
2542 };
2543 let wrapped = CoordinatorLink {
2544 chain: self,
2545 frame,
2546 index: index + 1,
2547 };
2548 let node_borrow = node.node.borrow();
2549 node_borrow
2550 .as_layout_node()
2551 .map(|layout_node| layout_node.max_intrinsic_height(&wrapped, width))
2552 .unwrap_or_else(|| wrapped.max_intrinsic_height(width))
2553 }
2554
2555 fn total_content_offset_from(&self, index: usize) -> Point {
2556 self.nodes
2557 .get(index)
2558 .map(|node| node.accumulated_offset.get())
2559 .unwrap_or_default()
2560 }
2561
2562 #[cfg(test)]
2563 fn debug_ptrs(&self) -> Vec<usize> {
2564 self.nodes.iter().map(CoordinatorNode::ptr).collect()
2565 }
2566}
2567
2568#[derive(Default)]
2569pub(crate) struct LayoutRuntimeState {
2570 child_ids: Vec<NodeId>,
2571 child_states: Vec<Rc<LayoutChildMeasureState>>,
2572 child_measurables: Vec<Box<dyn Measurable>>,
2573 coordinator_chain: CoordinatorChain,
2574}
2575
2576impl LayoutRuntimeState {
2577 fn reconcile_child_measurables(&mut self, child_ids: &[NodeId]) {
2578 if self.child_ids == child_ids {
2579 return;
2580 }
2581
2582 let mut previous_ids = std::mem::take(&mut self.child_ids);
2583 let mut previous_states = std::mem::take(&mut self.child_states);
2584 let mut previous_measurables = std::mem::take(&mut self.child_measurables);
2585
2586 self.child_ids.reserve(child_ids.len());
2587 self.child_states.reserve(child_ids.len());
2588 self.child_measurables.reserve(child_ids.len());
2589
2590 for &child_id in child_ids {
2591 if let Some(position) = previous_ids.iter().position(|&id| id == child_id) {
2592 self.child_ids.push(previous_ids.swap_remove(position));
2593 self.child_states
2594 .push(previous_states.swap_remove(position));
2595 self.child_measurables
2596 .push(previous_measurables.swap_remove(position));
2597 } else {
2598 let state = LayoutChildMeasureState::new(child_id);
2599 self.child_ids.push(child_id);
2600 self.child_states.push(Rc::clone(&state));
2601 self.child_measurables
2602 .push(Box::new(LayoutChildMeasurable::new(state)));
2603 }
2604 }
2605 }
2606
2607 fn child_state(&self, index: usize) -> Rc<LayoutChildMeasureState> {
2608 Rc::clone(&self.child_states[index])
2609 }
2610
2611 fn child_measurables(&self) -> &[Box<dyn Measurable>] {
2612 self.child_measurables.as_slice()
2613 }
2614
2615 fn reconcile_coordinator_chain(&mut self, layout_node_data: &[LayoutModifierNodeData]) {
2616 self.coordinator_chain.reconcile(layout_node_data);
2617 }
2618
2619 fn coordinator_chain(&self) -> &CoordinatorChain {
2620 &self.coordinator_chain
2621 }
2622
2623 fn clear_frame_bindings(&self) {
2624 for child_state in &self.child_states {
2625 child_state.clear_frame_bindings();
2626 }
2627 }
2628
2629 #[cfg(test)]
2630 pub(crate) fn debug_stats(&self) -> LayoutRuntimeDebugStats {
2631 LayoutRuntimeDebugStats {
2632 child_ids: self.child_ids.clone(),
2633 child_state_ptrs: self
2634 .child_states
2635 .iter()
2636 .map(|state| Rc::as_ptr(state) as *const () as usize)
2637 .collect(),
2638 child_measurable_ptrs: self
2639 .child_measurables
2640 .iter()
2641 .map(|measurable| {
2642 measurable.as_ref() as *const dyn Measurable as *const () as usize
2643 })
2644 .collect(),
2645 child_measurable_count: self.child_measurables.len(),
2646 coordinator_node_ptrs: self.coordinator_chain.debug_ptrs(),
2647 coordinator_node_count: self.coordinator_chain.nodes.len(),
2648 }
2649 }
2650}
2651
2652#[cfg(test)]
2653#[derive(Debug, Clone, PartialEq, Eq)]
2654pub(crate) struct LayoutRuntimeDebugStats {
2655 pub(crate) child_ids: Vec<NodeId>,
2656 pub(crate) child_state_ptrs: Vec<usize>,
2657 pub(crate) child_measurable_ptrs: Vec<usize>,
2658 pub(crate) child_measurable_count: usize,
2659 pub(crate) coordinator_node_ptrs: Vec<usize>,
2660 pub(crate) coordinator_node_count: usize,
2661}
2662
2663struct LayoutChildMeasureConfig {
2664 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
2665 node_id: NodeId,
2666 error: Rc<RefCell<Option<NodeError>>>,
2667 runtime_handle: Option<RuntimeHandle>,
2668 cache: LayoutNodeCacheHandles,
2669 cache_epoch: u64,
2670 force_remeasure: bool,
2671 measure_handle: Option<LayoutMeasureHandle>,
2672 layout_state: Option<Rc<RefCell<LayoutState>>>,
2673}
2674
2675struct LayoutChildMeasureState {
2676 applier: RefCell<Option<Rc<ConcreteApplierHost<MemoryApplier>>>>,
2677 node_id: Cell<NodeId>,
2678 measured: RefCell<Option<Rc<MeasuredNode>>>,
2679 last_position: Cell<Option<Point>>,
2680 error: RefCell<Option<Rc<RefCell<Option<NodeError>>>>>,
2681 runtime_handle: RefCell<Option<RuntimeHandle>>,
2682 cache: RefCell<LayoutNodeCacheHandles>,
2683 cache_epoch: Cell<u64>,
2684 force_remeasure: Cell<bool>,
2685 measure_handle: RefCell<Option<LayoutMeasureHandle>>,
2686 layout_state: RefCell<Option<Rc<RefCell<LayoutState>>>>,
2687}
2688
2689impl LayoutChildMeasureState {
2690 fn new(node_id: NodeId) -> Rc<Self> {
2691 Rc::new(Self {
2692 applier: RefCell::new(None),
2693 node_id: Cell::new(node_id),
2694 measured: RefCell::new(None),
2695 last_position: Cell::new(None),
2696 error: RefCell::new(None),
2697 runtime_handle: RefCell::new(None),
2698 cache: RefCell::new(LayoutNodeCacheHandles::default()),
2699 cache_epoch: Cell::new(0),
2700 force_remeasure: Cell::new(true),
2701 measure_handle: RefCell::new(None),
2702 layout_state: RefCell::new(None),
2703 })
2704 }
2705
2706 fn configure(&self, config: LayoutChildMeasureConfig) {
2707 config.cache.activate(config.cache_epoch);
2708 *self.applier.borrow_mut() = Some(config.applier);
2709 self.node_id.set(config.node_id);
2710 self.measured.borrow_mut().take();
2711 self.last_position.set(None);
2712 *self.error.borrow_mut() = Some(config.error);
2713 *self.runtime_handle.borrow_mut() = config.runtime_handle;
2714 *self.cache.borrow_mut() = config.cache;
2715 self.cache_epoch.set(config.cache_epoch);
2716 self.force_remeasure.set(config.force_remeasure);
2717 *self.measure_handle.borrow_mut() = config.measure_handle;
2718 *self.layout_state.borrow_mut() = config.layout_state;
2719 }
2720
2721 fn clear_frame_bindings(&self) {
2722 self.measured.borrow_mut().take();
2723 *self.applier.borrow_mut() = None;
2724 *self.error.borrow_mut() = None;
2725 *self.runtime_handle.borrow_mut() = None;
2726 *self.measure_handle.borrow_mut() = None;
2727 *self.layout_state.borrow_mut() = None;
2728 }
2729
2730 fn node_id(&self) -> NodeId {
2731 self.node_id.get()
2732 }
2733
2734 fn cache(&self) -> LayoutNodeCacheHandles {
2735 self.cache.borrow().clone()
2736 }
2737
2738 fn applier(&self) -> Option<Rc<ConcreteApplierHost<MemoryApplier>>> {
2739 self.applier.borrow().clone()
2740 }
2741
2742 fn layout_state(&self) -> Option<Rc<RefCell<LayoutState>>> {
2743 self.layout_state.borrow().clone()
2744 }
2745
2746 fn take_measured(&self) -> Option<Rc<MeasuredNode>> {
2747 self.measured.borrow_mut().take()
2748 }
2749
2750 fn last_position(&self) -> Option<Point> {
2751 self.last_position.get()
2752 }
2753
2754 fn set_last_position(&self, position: Point) {
2755 self.last_position.set(Some(position));
2756 }
2757
2758 fn place_retained(&self, position: Point) {
2759 self.set_last_position(position);
2760 if let Some(layout_state) = self.layout_state() {
2761 layout_state.borrow_mut().place(position);
2762 return;
2763 }
2764 let Some(applier) = self.applier() else {
2765 return;
2766 };
2767 let Ok(mut applier) = applier.try_borrow_typed() else {
2768 return;
2769 };
2770 let node_id = self.node_id();
2771 if applier
2772 .with_node::<LayoutNode, _>(node_id, |node| {
2773 node.set_position(position);
2774 })
2775 .is_err()
2776 {
2777 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
2778 node.set_position(position);
2779 });
2780 }
2781 }
2782
2783 fn set_measured(&self, measured: Option<Rc<MeasuredNode>>) {
2784 *self.measured.borrow_mut() = measured;
2785 }
2786
2787 fn record_error(&self, err: NodeError) {
2788 let Some(error) = self.error.borrow().clone() else {
2789 return;
2790 };
2791 let mut slot = error.borrow_mut();
2792 if slot.is_none() {
2793 *slot = Some(err);
2794 }
2795 }
2796
2797 fn perform_measure(&self, constraints: Constraints) -> Result<Rc<MeasuredNode>, NodeError> {
2798 let node_id = self.node_id();
2799 if let Some(handle) = self.measure_handle.borrow().clone() {
2800 return handle.measure(node_id, constraints);
2801 }
2802 let applier = self.applier().ok_or(NodeError::MissingContext {
2803 id: node_id,
2804 reason: "layout child applier not configured",
2805 })?;
2806 measure_node_with_host(
2807 applier,
2808 self.runtime_handle.borrow().clone(),
2809 node_id,
2810 constraints,
2811 self.cache_epoch.get(),
2812 )
2813 }
2814
2815 fn intrinsic_measure(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
2816 let cache = self.cache();
2817 cache.activate(self.cache_epoch.get());
2818 if !self.force_remeasure.get()
2819 && let Some(cached) = cache.get_measurement(constraints)
2820 {
2821 return Some(cached);
2822 }
2823
2824 match self.perform_measure(constraints) {
2825 Ok(measured) => {
2826 self.force_remeasure.set(false);
2827 cache.store_measurement(constraints, Rc::clone(&measured));
2828 Some(measured)
2829 }
2830 Err(err) => {
2831 self.record_error(err);
2832 None
2833 }
2834 }
2835 }
2836}
2837
2838struct LayoutChildMeasurable {
2839 state: Rc<LayoutChildMeasureState>,
2840}
2841
2842impl LayoutChildMeasurable {
2843 fn new(state: Rc<LayoutChildMeasureState>) -> Self {
2844 Self { state }
2845 }
2846
2847 fn resolved_parent_data(&self) -> Option<cranpose_ui_layout::ParentData> {
2848 let applier = self.state.applier()?;
2849 let node_id = self.state.node_id();
2850 let Ok(mut applier) = applier.try_borrow_typed() else {
2851 return None;
2852 };
2853
2854 applier
2855 .with_node::<LayoutNode, _>(node_id, |layout_node| {
2856 let props = layout_node.resolved_modifiers().layout_properties();
2857 let weight = props.weight().unwrap_or_default();
2858 cranpose_ui_layout::ParentData {
2859 weight: weight.weight,
2860 fill: weight.fill,
2861 box_alignment: props.box_alignment(),
2862 row_alignment: props.row_alignment(),
2863 column_alignment: props.column_alignment(),
2864 }
2865 })
2866 .ok()
2867 }
2868}
2869
2870impl Measurable for LayoutChildMeasurable {
2871 fn measure(&self, constraints: Constraints) -> Placeable {
2872 let state = &self.state;
2873 let cache = state.cache();
2874 cache.activate(state.cache_epoch.get());
2875 let measured_size;
2876 if !state.force_remeasure.get() {
2877 if let Some(cached) = cache.get_measurement(constraints) {
2878 measured_size = cached.size;
2879 state.set_measured(Some(Rc::clone(&cached)));
2880 } else {
2881 match state.perform_measure(constraints) {
2882 Ok(measured) => {
2883 state.force_remeasure.set(false);
2884 measured_size = measured.size;
2885 cache.store_measurement(constraints, Rc::clone(&measured));
2886 state.set_measured(Some(measured));
2887 }
2888 Err(err) => {
2889 state.record_error(err);
2890 state.set_measured(None);
2891 measured_size = Size {
2892 width: 0.0,
2893 height: 0.0,
2894 };
2895 }
2896 }
2897 }
2898 } else {
2899 match state.perform_measure(constraints) {
2900 Ok(measured) => {
2901 state.force_remeasure.set(false);
2902 measured_size = measured.size;
2903 cache.store_measurement(constraints, Rc::clone(&measured));
2904 state.set_measured(Some(measured));
2905 }
2906 Err(err) => {
2907 state.record_error(err);
2908 state.set_measured(None);
2909 measured_size = Size {
2910 width: 0.0,
2911 height: 0.0,
2912 };
2913 }
2914 }
2915 }
2916
2917 if let Some(layout_state) = state.layout_state() {
2918 let mut layout_state = layout_state.borrow_mut();
2919 layout_state.set_size(measured_size);
2920 layout_state.measurement_constraints = constraints;
2921 } else if let Some(applier) = state.applier() {
2922 let Ok(mut applier) = applier.try_borrow_typed() else {
2923 return Placeable::value(
2924 measured_size.width,
2925 measured_size.height,
2926 state.node_id(),
2927 );
2928 };
2929 let _ = applier.with_node::<LayoutNode, _>(state.node_id(), |node| {
2930 node.set_measured_size(measured_size);
2931 node.set_measurement_constraints(constraints);
2932 });
2933 }
2934
2935 let state = Rc::clone(&self.state);
2936 let node_id = state.node_id();
2937 let size_for_parent = state
2938 .measured
2939 .borrow()
2940 .as_ref()
2941 .map_or(measured_size, |measured| measured.size_for_parent());
2942
2943 let place_fn = Rc::new(move |x: f32, y: f32| {
2944 let internal_offset = state
2945 .measured
2946 .borrow()
2947 .as_ref()
2948 .map(|m| m.offset)
2949 .unwrap_or_default();
2950
2951 state.place_retained(Point {
2952 x: x + internal_offset.x,
2953 y: y + internal_offset.y,
2954 });
2955 });
2956
2957 Placeable::with_place_fn(
2958 size_for_parent.width,
2959 size_for_parent.height,
2960 node_id,
2961 place_fn,
2962 )
2963 }
2964
2965 fn min_intrinsic_width(&self, height: f32) -> f32 {
2966 let kind = IntrinsicKind::MinWidth(height);
2967 let cache = self.state.cache();
2968 cache.activate(self.state.cache_epoch.get());
2969 if !self.state.force_remeasure.get()
2970 && let Some(value) = cache.get_intrinsic(&kind)
2971 {
2972 return value;
2973 }
2974 let constraints = Constraints {
2975 min_width: 0.0,
2976 max_width: f32::INFINITY,
2977 min_height: height,
2978 max_height: height,
2979 };
2980 if let Some(node) = self.state.intrinsic_measure(constraints) {
2981 let value = node.size_for_parent().width;
2982 cache.store_intrinsic(kind, value);
2983 value
2984 } else {
2985 0.0
2986 }
2987 }
2988
2989 fn max_intrinsic_width(&self, height: f32) -> f32 {
2990 let kind = IntrinsicKind::MaxWidth(height);
2991 let cache = self.state.cache();
2992 cache.activate(self.state.cache_epoch.get());
2993 if !self.state.force_remeasure.get()
2994 && let Some(value) = cache.get_intrinsic(&kind)
2995 {
2996 return value;
2997 }
2998 let constraints = Constraints {
2999 min_width: 0.0,
3000 max_width: f32::INFINITY,
3001 min_height: 0.0,
3002 max_height: height,
3003 };
3004 if let Some(node) = self.state.intrinsic_measure(constraints) {
3005 let value = node.size_for_parent().width;
3006 cache.store_intrinsic(kind, value);
3007 value
3008 } else {
3009 0.0
3010 }
3011 }
3012
3013 fn min_intrinsic_height(&self, width: f32) -> f32 {
3014 let kind = IntrinsicKind::MinHeight(width);
3015 let cache = self.state.cache();
3016 cache.activate(self.state.cache_epoch.get());
3017 if !self.state.force_remeasure.get()
3018 && let Some(value) = cache.get_intrinsic(&kind)
3019 {
3020 return value;
3021 }
3022 let constraints = Constraints {
3023 min_width: width,
3024 max_width: width,
3025 min_height: 0.0,
3026 max_height: f32::INFINITY,
3027 };
3028 if let Some(node) = self.state.intrinsic_measure(constraints) {
3029 let value = node.size_for_parent().height;
3030 cache.store_intrinsic(kind, value);
3031 value
3032 } else {
3033 0.0
3034 }
3035 }
3036
3037 fn max_intrinsic_height(&self, width: f32) -> f32 {
3038 let kind = IntrinsicKind::MaxHeight(width);
3039 let cache = self.state.cache();
3040 cache.activate(self.state.cache_epoch.get());
3041 if !self.state.force_remeasure.get()
3042 && let Some(value) = cache.get_intrinsic(&kind)
3043 {
3044 return value;
3045 }
3046 let constraints = Constraints {
3047 min_width: 0.0,
3048 max_width: width,
3049 min_height: 0.0,
3050 max_height: f32::INFINITY,
3051 };
3052 if let Some(node) = self.state.intrinsic_measure(constraints) {
3053 let value = node.size_for_parent().height;
3054 cache.store_intrinsic(kind, value);
3055 value
3056 } else {
3057 0.0
3058 }
3059 }
3060
3061 fn flex_parent_data(&self) -> Option<cranpose_ui_layout::FlexParentData> {
3062 let parent_data = self.resolved_parent_data()?;
3063 if !parent_data.has_weight() {
3064 return None;
3065 }
3066 Some(cranpose_ui_layout::FlexParentData::new(
3067 parent_data.weight,
3068 parent_data.fill,
3069 ))
3070 }
3071
3072 fn parent_data(&self) -> cranpose_ui_layout::ParentData {
3073 self.resolved_parent_data().unwrap_or_default()
3074 }
3075}
3076
3077fn measure_node_with_host(
3078 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
3079 runtime_handle: Option<RuntimeHandle>,
3080 node_id: NodeId,
3081 constraints: Constraints,
3082 epoch: u64,
3083) -> Result<Rc<MeasuredNode>, NodeError> {
3084 let runtime_handle = match runtime_handle {
3085 Some(handle) => Some(handle),
3086 None => applier.borrow_typed().runtime_handle(),
3087 };
3088 let mut builder = LayoutBuilder::new_with_epoch(
3089 applier,
3090 epoch,
3091 Rc::new(RefCell::new(SlotTable::default())),
3092 FrameLayoutArena::default(),
3093 );
3094 builder.set_runtime_handle(runtime_handle);
3095 builder.measure_node(node_id, constraints)
3096}
3097
3098#[derive(Clone)]
3099struct RuntimeNodeMetadata {
3100 modifier: Modifier,
3101 resolved_modifiers: ResolvedModifiers,
3102 modifier_slices: Rc<ModifierNodeSlices>,
3103 role: SemanticsRole,
3104 button_handler: Option<Rc<RefCell<dyn FnMut()>>>,
3105}
3106
3107impl Default for RuntimeNodeMetadata {
3108 fn default() -> Self {
3109 Self {
3110 modifier: Modifier::empty(),
3111 resolved_modifiers: ResolvedModifiers::default(),
3112 modifier_slices: Rc::default(),
3113 role: SemanticsRole::Unknown,
3114 button_handler: None,
3115 }
3116 }
3117}
3118
3119fn role_from_modifier_slices(modifier_slices: &ModifierNodeSlices) -> SemanticsRole {
3120 modifier_slices
3121 .text_content()
3122 .map(|text| SemanticsRole::Text {
3123 value: text.to_string(),
3124 })
3125 .unwrap_or(SemanticsRole::Layout)
3126}
3127
3128fn runtime_metadata_for(
3129 applier: &mut MemoryApplier,
3130 node_id: NodeId,
3131) -> Result<RuntimeNodeMetadata, NodeError> {
3132 if let Ok(meta) = applier.with_node::<LayoutNode, _>(node_id, |layout| {
3133 let modifier = layout.modifier.clone();
3134 let resolved_modifiers = layout.resolved_modifiers();
3135 let modifier_slices = layout.modifier_slices_snapshot();
3136 let role = role_from_modifier_slices(&modifier_slices);
3137
3138 RuntimeNodeMetadata {
3139 modifier,
3140 resolved_modifiers,
3141 modifier_slices,
3142 role,
3143 button_handler: None,
3144 }
3145 }) {
3146 return Ok(meta);
3147 }
3148
3149 if let Ok((modifier, resolved_modifiers, modifier_slices)) = applier
3150 .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
3151 (
3152 node.modifier(),
3153 node.resolved_modifiers(),
3154 node.modifier_slices_snapshot(),
3155 )
3156 })
3157 {
3158 return Ok(RuntimeNodeMetadata {
3159 modifier,
3160 resolved_modifiers,
3161 modifier_slices,
3162 role: SemanticsRole::Subcompose,
3163 button_handler: None,
3164 });
3165 }
3166 Ok(RuntimeNodeMetadata::default())
3167}
3168
3169fn clear_semantics_dirty_flags(
3170 applier: &mut MemoryApplier,
3171 node: &MeasuredNode,
3172) -> Result<(), NodeError> {
3173 match applier.with_node::<LayoutNode, _>(node.node_id, |layout| {
3174 layout.clear_needs_semantics();
3175 }) {
3176 Ok(()) => {}
3177 Err(NodeError::Missing { .. }) => {}
3178 Err(NodeError::TypeMismatch { .. }) => {
3179 match applier.with_node::<SubcomposeLayoutNode, _>(node.node_id, |subcompose| {
3180 subcompose.clear_needs_semantics();
3181 }) {
3182 Ok(()) | Err(NodeError::Missing { .. }) | Err(NodeError::TypeMismatch { .. }) => {}
3183 Err(err) => return Err(err),
3184 }
3185 }
3186 Err(err) => return Err(err),
3187 }
3188
3189 for child in &node.children {
3190 clear_semantics_dirty_flags(applier, &child.node)?;
3191 }
3192
3193 Ok(())
3194}
3195
3196fn build_semantics_tree_from_live_nodes(
3197 applier: &mut MemoryApplier,
3198 node: &MeasuredNode,
3199) -> Result<SemanticsTree, NodeError> {
3200 Ok(SemanticsTree::new(build_semantics_node_from_live_nodes(
3201 applier, node,
3202 )?))
3203}
3204
3205fn semantics_node_from_parts(
3206 node_id: NodeId,
3207 node_generation: u32,
3208 mut role: SemanticsRole,
3209 config: Option<SemanticsConfiguration>,
3210 children: Vec<SemanticsNode>,
3211 size: Size,
3212) -> SemanticsNode {
3213 let mut node = SemanticsNode {
3214 node_id,
3215 node_generation,
3216 children,
3217 ..SemanticsNode::default()
3218 };
3219
3220 if let Some(config) = config {
3221 if config.role == Some(SemanticsWidgetRole::Button) {
3222 role = SemanticsRole::Button;
3223 }
3224 if config.is_activatable() {
3225 node.actions.push(SemanticsAction::Click {
3226 handler: SemanticsCallback::new(node_id),
3227 });
3228 }
3229 node.widget_role = config.role;
3230 node.description = config.content_description;
3231 node.state_description = config.state_description;
3232 node.on_click_label = config.on_click_label.or_else(|| {
3233 config
3234 .on_click
3235 .as_ref()
3236 .and_then(|action| (!action.label.is_empty()).then(|| action.label.clone()))
3237 });
3238 node.on_click = config.on_click;
3239 node.on_long_click = config.on_long_click;
3240 node.on_long_click_label = config.on_long_click_label;
3241 node.on_magic_tap = config.on_magic_tap;
3242 node.on_magic_tap_label = config.on_magic_tap_label;
3243 node.input_labels = config.input_labels;
3244 node.language = config.language;
3245 node.selected = config.selected;
3246 node.toggled = config.toggled;
3247 node.enabled = config.enabled;
3248 node.custom_actions = config.custom_actions;
3249 node.canvas_children = config.canvas_children;
3250 node.editable_text = config.is_editable_text;
3251 node.multiline = config.multiline;
3252 node.hidden = config.hidden;
3253 node.is_modal = config.is_modal
3254 && size.width > 0.0
3255 && size.height > 0.0
3256 && size.width.is_finite()
3257 && size.height.is_finite();
3258 node.merge_descendants = config.merge_descendants;
3259 node.selectable_group = config.selectable_group;
3260 node.pane_title = config.pane_title;
3261 node.error = config.error;
3262 node.password = config.password;
3263 node.traversal_index = config.traversal_index;
3264 node.text = config.text;
3265 node.text_selection = config.text_selection;
3266 node.live_region = config.live_region;
3267 node.progress = config.progress;
3268 node.set_progress = config.set_progress;
3269 node.set_text = config.set_text;
3270 node.set_selection = config.set_selection;
3271 node.expand = config.expand;
3272 node.collapse = config.collapse;
3273 node.dismiss = config.dismiss;
3274 node.vertical_scroll = config.vertical_scroll;
3275 node.horizontal_scroll = config.horizontal_scroll;
3276 node.scroll_by = config.scroll_by;
3277 node.scroll_to_index = config.scroll_to_index;
3278 node.collection = config.collection;
3279 }
3280
3281 node.focusable = crate::focus_dispatch::has_focus_target(node_id);
3282 node.focused = node.focusable && crate::focus_dispatch::active_focus_target() == Some(node_id);
3283
3284 node.role = role;
3285 node
3286}
3287
3288fn build_semantics_node_from_live_nodes(
3289 applier: &mut MemoryApplier,
3290 node: &MeasuredNode,
3291) -> Result<SemanticsNode, NodeError> {
3292 let (role, config) = match applier.with_node::<LayoutNode, _>(node.node_id, |layout| {
3293 let role = role_from_modifier_slices(&layout.modifier_slices_snapshot());
3294 let config = layout.semantics_configuration();
3295 layout.clear_needs_semantics();
3296 (role, config)
3297 }) {
3298 Ok(data) => data,
3299 Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
3300 match applier.with_node::<SubcomposeLayoutNode, _>(node.node_id, |subcompose| {
3301 subcompose.clear_needs_semantics();
3302 (
3303 SemanticsRole::Subcompose,
3304 collect_semantics_from_modifier(&subcompose.modifier()),
3305 )
3306 }) {
3307 Ok(data) => data,
3308 Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {
3309 (SemanticsRole::Unknown, None)
3310 }
3311 Err(err) => return Err(err),
3312 }
3313 }
3314 Err(err) => return Err(err),
3315 };
3316
3317 let mut children = Vec::with_capacity(node.children.len());
3318 for child in &node.children {
3319 children.push(build_semantics_node_from_live_nodes(applier, &child.node)?);
3320 }
3321
3322 Ok(semantics_node_from_parts(
3323 node.node_id,
3324 applier.node_generation(node.node_id),
3325 role,
3326 config,
3327 children,
3328 node.size,
3329 ))
3330}
3331
3332fn record_semantics_allocation_stats(node: &SemanticsNode, stats: &mut LayoutAllocationDebugStats) {
3333 stats.semantics_node_count += 1;
3334 stats.semantics_action_count += node.actions.len();
3335 stats.semantics_action_capacity += node.actions.capacity();
3336 stats.semantics_child_count += node.children.len();
3337 stats.semantics_child_capacity += node.children.capacity();
3338 stats.semantics_heap_bytes += node.actions.capacity() * size_of::<SemanticsAction>();
3339 stats.semantics_heap_bytes += node.children.capacity() * size_of::<SemanticsNode>();
3340
3341 if let Some(description) = &node.description {
3342 stats.semantics_description_count += 1;
3343 stats.semantics_description_bytes += description.capacity();
3344 stats.semantics_heap_bytes += description.capacity();
3345 }
3346 if let SemanticsRole::Text { value } = &node.role {
3347 stats.semantics_text_role_bytes += value.capacity();
3348 stats.semantics_heap_bytes += value.capacity();
3349 }
3350
3351 for child in &node.children {
3352 record_semantics_allocation_stats(child, stats);
3353 }
3354}
3355
3356fn record_layout_box_allocation_stats(
3357 layout_box: &LayoutBox,
3358 stats: &mut LayoutAllocationDebugStats,
3359) {
3360 stats.layout_box_count += 1;
3361 stats.layout_box_child_count += layout_box.children.len();
3362 stats.layout_box_child_capacity += layout_box.children.capacity();
3363 stats.layout_box_heap_bytes += layout_box.children.capacity() * size_of::<LayoutBox>();
3364 stats.add_modifier_slice(layout_box.node_data.modifier_slices().debug_stats());
3365
3366 for child in &layout_box.children {
3367 record_layout_box_allocation_stats(child, stats);
3368 }
3369}
3370
3371fn build_layout_tree(
3372 applier: &mut MemoryApplier,
3373 node: &MeasuredNode,
3374) -> Result<LayoutTree, NodeError> {
3375 fn place(
3376 applier: &mut MemoryApplier,
3377 node: &MeasuredNode,
3378 origin: Point,
3379 parent_layer_translation: Point,
3380 ) -> Result<LayoutBox, NodeError> {
3381 let top_left = Point {
3382 x: origin.x + node.offset.x,
3383 y: origin.y + node.offset.y,
3384 };
3385 let rect = GeometryRect {
3386 x: top_left.x,
3387 y: top_left.y,
3388 width: node.size.width,
3389 height: node.size.height,
3390 };
3391 let info = runtime_metadata_for(applier, node.node_id)?;
3392 let kind = layout_kind_from_metadata(node.node_id, &info);
3393 let RuntimeNodeMetadata {
3394 modifier,
3395 resolved_modifiers,
3396 modifier_slices,
3397 ..
3398 } = info;
3399
3400 let layer_translation = match modifier_slices.graphics_layer() {
3401 Some(layer) => Point {
3402 x: parent_layer_translation.x + layer.translation_x,
3403 y: parent_layer_translation.y + layer.translation_y,
3404 },
3405 None => parent_layer_translation,
3406 };
3407
3408 publish_window_geometry(&modifier_slices, top_left, layer_translation, node.size);
3409
3410 let data = LayoutNodeData::new(modifier, resolved_modifiers, modifier_slices, kind);
3411 let mut children = Vec::with_capacity(node.children.len());
3412 for child in &node.children {
3413 if crate::modifier::is_window_root(applier, child.node.node_id) {
3414 continue;
3415 }
3416 let child_origin = Point {
3417 x: top_left.x + child.offset.x,
3418 y: top_left.y + child.offset.y,
3419 };
3420 children.push(place(
3421 applier,
3422 &child.node,
3423 child_origin,
3424 layer_translation,
3425 )?);
3426 }
3427 Ok(LayoutBox {
3428 node_generation: applier.node_generation(node.node_id),
3429 ..LayoutBox::new(node.node_id, rect, node.content_offset, data, children)
3430 })
3431 }
3432
3433 Ok(LayoutTree::new(place(
3434 applier,
3435 node,
3436 Point { x: 0.0, y: 0.0 },
3437 Point { x: 0.0, y: 0.0 },
3438 )?))
3439}
3440
3441fn semantics_role_from_layout_box(layout_box: &LayoutBox) -> SemanticsRole {
3442 match &layout_box.node_data.kind {
3443 LayoutNodeKind::Subcompose => SemanticsRole::Subcompose,
3444 LayoutNodeKind::Spacer => SemanticsRole::Spacer,
3445 LayoutNodeKind::Unknown => SemanticsRole::Unknown,
3446 LayoutNodeKind::Button { .. } => SemanticsRole::Button,
3447 LayoutNodeKind::Layout => layout_box
3448 .node_data
3449 .modifier_slices()
3450 .text_content()
3451 .map(|text| SemanticsRole::Text {
3452 value: text.to_string(),
3453 })
3454 .unwrap_or(SemanticsRole::Layout),
3455 }
3456}
3457
3458fn build_semantics_node_from_layout_box(layout_box: &LayoutBox) -> SemanticsNode {
3459 let children = layout_box
3460 .children
3461 .iter()
3462 .map(build_semantics_node_from_layout_box)
3463 .collect();
3464
3465 semantics_node_from_parts(
3466 layout_box.node_id,
3467 layout_box.node_generation,
3468 semantics_role_from_layout_box(layout_box),
3469 collect_semantics_from_modifier(&layout_box.node_data.modifier),
3470 children,
3471 Size::new(layout_box.rect.width, layout_box.rect.height),
3472 )
3473}
3474
3475fn layout_kind_from_metadata(_node_id: NodeId, info: &RuntimeNodeMetadata) -> LayoutNodeKind {
3476 match &info.role {
3477 SemanticsRole::Layout => LayoutNodeKind::Layout,
3478 SemanticsRole::Subcompose => LayoutNodeKind::Subcompose,
3479 SemanticsRole::Text { .. } => LayoutNodeKind::Layout,
3480 SemanticsRole::Spacer => LayoutNodeKind::Spacer,
3481 SemanticsRole::Button => {
3482 let handler = info
3483 .button_handler
3484 .as_ref()
3485 .cloned()
3486 .unwrap_or_else(|| Rc::new(RefCell::new(|| {})));
3487 LayoutNodeKind::Button { on_click: handler }
3488 }
3489 SemanticsRole::Unknown => LayoutNodeKind::Unknown,
3490 }
3491}
3492
3493fn subtract_padding(constraints: Constraints, padding: EdgeInsets) -> Constraints {
3494 let horizontal = padding.horizontal_sum();
3495 let vertical = padding.vertical_sum();
3496 let min_width = (constraints.min_width - horizontal).max(0.0);
3497 let mut max_width = constraints.max_width;
3498 if max_width.is_finite() {
3499 max_width = (max_width - horizontal).max(0.0);
3500 }
3501 let min_height = (constraints.min_height - vertical).max(0.0);
3502 let mut max_height = constraints.max_height;
3503 if max_height.is_finite() {
3504 max_height = (max_height - vertical).max(0.0);
3505 }
3506 normalize_constraints(Constraints {
3507 min_width,
3508 max_width,
3509 min_height,
3510 max_height,
3511 })
3512}
3513
3514#[cfg(test)]
3515pub(crate) fn align_horizontal(alignment: HorizontalAlignment, available: f32, child: f32) -> f32 {
3516 match alignment {
3517 HorizontalAlignment::Start => 0.0,
3518 HorizontalAlignment::CenterHorizontally => ((available - child) / 2.0).max(0.0),
3519 HorizontalAlignment::End => (available - child).max(0.0),
3520 }
3521}
3522
3523#[cfg(test)]
3524pub(crate) fn align_vertical(alignment: VerticalAlignment, available: f32, child: f32) -> f32 {
3525 match alignment {
3526 VerticalAlignment::Top => 0.0,
3527 VerticalAlignment::CenterVertically => ((available - child) / 2.0).max(0.0),
3528 VerticalAlignment::Bottom => (available - child).max(0.0),
3529 }
3530}
3531
3532fn resolve_dimension(
3533 base: f32,
3534 explicit: DimensionConstraint,
3535 min_override: Option<f32>,
3536 max_override: Option<f32>,
3537 min_limit: f32,
3538 max_limit: f32,
3539) -> f32 {
3540 let mut min_bound = min_limit;
3541 if let Some(min_value) = min_override {
3542 min_bound = min_bound.max(min_value);
3543 }
3544
3545 let mut max_bound = if max_limit.is_finite() {
3546 max_limit
3547 } else {
3548 max_override.unwrap_or(max_limit)
3549 };
3550 if let Some(max_value) = max_override {
3551 if max_bound.is_finite() {
3552 max_bound = max_bound.min(max_value);
3553 } else {
3554 max_bound = max_value;
3555 }
3556 }
3557 if max_bound < min_bound {
3558 max_bound = min_bound;
3559 }
3560
3561 let mut size = match explicit {
3562 DimensionConstraint::Points(points) => points,
3563 DimensionConstraint::Fraction(fraction) => {
3564 if max_limit.is_finite() {
3565 max_limit * fraction.clamp(0.0, 1.0)
3566 } else {
3567 base
3568 }
3569 }
3570 DimensionConstraint::Unspecified => base,
3571 DimensionConstraint::Intrinsic(_) => base,
3572 };
3573
3574 size = clamp_dimension(size, min_bound, max_bound);
3575 size = clamp_dimension(size, min_limit, max_limit);
3576 size.max(0.0)
3577}
3578
3579fn clamp_dimension(value: f32, min: f32, max: f32) -> f32 {
3580 let mut result = value.max(min);
3581 if max.is_finite() {
3582 result = result.min(max);
3583 }
3584 result
3585}
3586
3587fn normalize_constraints(mut constraints: Constraints) -> Constraints {
3588 if constraints.max_width < constraints.min_width {
3589 constraints.max_width = constraints.min_width;
3590 }
3591 if constraints.max_height < constraints.min_height {
3592 constraints.max_height = constraints.min_height;
3593 }
3594 constraints
3595}
3596
3597#[cfg(test)]
3598#[path = "tests/layout_tests.rs"]
3599mod tests;