1mod bottom_up;
2mod coordinator_chain;
3pub mod core;
5pub(crate) mod flex_box;
6mod frame_layout_arena;
7pub(crate) mod grid;
8mod layout_child_measurable;
9mod layout_child_measure_state;
10mod layout_node_data;
11mod layout_runtime_state;
12mod live_layout_node;
13mod measure_telemetry;
14mod modifier_chain_measure;
15mod placed_children;
16mod placed_root_measurements;
17pub mod policies;
19mod reveal;
20mod semantics_details;
21mod semantics_labels;
22mod semantics_tree;
23mod semantics_update;
24mod subcompose_measure;
25mod unplaced_nodes;
26
27use std::{cell::RefCell, mem::size_of, rc::Rc};
28
29use cranpose_core::{
30 Applier, ConcreteApplierHost, MemoryApplier, Node, NodeError, NodeId, RuntimeHandle,
31};
32use cranpose_foundation::{
33 InvalidationKind, ModifierNodeContext, SemanticsConfiguration, SemanticsWidgetRole,
34};
35use cranpose_ui_graphics::ProjectiveTransform;
36use cranpose_ui_layout::{AlignmentLines, Constraints, Measurables, MeasurePolicy};
37pub(crate) use frame_layout_arena::FrameLayoutArena;
38use frame_layout_arena::VecPools;
39pub(crate) use layout_child_measure_state::LayoutChildMeasureState;
40use layout_child_measure_state::{ChildPass, inherited_alignment_lines, read_cell};
41use layout_node_data::{role_from_modifier_slices, snapshot_node_data};
42pub(crate) use layout_runtime_state::LayoutRuntimeState;
43use live_layout_node::{LiveLayoutNode, read_live_layout_node};
44use placed_children::PlacedChildren;
45use placed_root_measurements::PlacedRootMeasurements;
46pub use semantics_tree::{
47 SemanticsAction, SemanticsCallback, SemanticsNode, SemanticsPlacement, SemanticsRole,
48 SemanticsText, SemanticsTree,
49};
50use semantics_tree::{modal_takes_space, top_modal_path};
51use unplaced_nodes::record_unplaced_nodes;
52use web_time::Instant;
53
54#[cfg(test)]
55use self::core::{HorizontalAlignment, VerticalAlignment};
56use self::{
57 coordinator_chain::CoordinatorFrame,
58 measure_telemetry::{
59 LayoutStages, layout_measure_telemetry_threshold_ms, log_layout_measure_telemetry,
60 log_node_measure_telemetry,
61 },
62 semantics_update::semantics_placement,
63};
64pub use self::{
65 layout_node_data::{LayoutNodeData, LayoutNodeKind},
66 reveal::can_skip_scroll_reveal_from_applier,
67 semantics_details::SemanticsDetails,
68 semantics_update::{build_semantics_tree_from_applier, update_semantics_tree_from_applier},
69};
70use crate::{
71 modifier::{
72 DimensionConstraint, EdgeInsets, ModifierNodeSlicesDebugStats, Point, Rect as GeometryRect,
73 Size,
74 },
75 render_state::AppContext,
76 subcompose_layout::SubcomposeLayoutNode,
77 widgets::nodes::{ChildPlacement, IntrinsicKind, LayoutNode, LayoutParts, LayoutState},
78};
79
80#[derive(Default)]
81pub(crate) struct LayoutNodeContext {
82 invalidations: Vec<InvalidationKind>,
83 update_requested: bool,
84 density: f32,
85}
86
87impl LayoutNodeContext {
88 pub(crate) fn new(density: f32) -> Self {
89 Self {
90 density,
91 ..Self::default()
92 }
93 }
94
95 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationKind> {
96 std::mem::take(&mut self.invalidations)
97 }
98}
99
100impl ModifierNodeContext for LayoutNodeContext {
101 fn invalidate(&mut self, kind: InvalidationKind) {
102 if !self.invalidations.contains(&kind) {
103 self.invalidations.push(kind);
104 }
105 }
106
107 fn request_update(&mut self) {
108 self.update_requested = true;
109 }
110
111 fn density(&self) -> f32 {
112 self.density
113 }
114}
115
116#[doc(hidden)]
117pub fn invalidate_all_layout_caches() {
118 crate::render_state::invalidate_layout_cache_epoch();
119}
120
121pub(crate) struct LayoutHost {
124 host: Rc<ConcreteApplierHost<MemoryApplier>>,
125}
126
127impl Default for LayoutHost {
128 fn default() -> Self {
129 Self {
130 host: Rc::new(ConcreteApplierHost::new(MemoryApplier::new())),
131 }
132 }
133}
134
135struct ApplierSlotGuard<'a> {
138 target: &'a mut MemoryApplier,
139 lent: LayoutHost,
140 context: &'a AppContext,
141}
142
143impl<'a> ApplierSlotGuard<'a> {
144 fn new(target: &'a mut MemoryApplier, context: &'a AppContext) -> Self {
145 let lent = context.take_layout_host();
146 std::mem::swap(target, &mut *lent.host.borrow_typed());
147 Self {
148 target,
149 lent,
150 context,
151 }
152 }
153
154 fn host(&self) -> &Rc<ConcreteApplierHost<MemoryApplier>> {
155 &self.lent.host
156 }
157}
158
159impl Drop for ApplierSlotGuard<'_> {
160 fn drop(&mut self) {
161 let host = &self.lent.host;
162 std::mem::swap(self.target, &mut *host.borrow_typed());
163 if Rc::strong_count(host) == 1 {
165 self.context.replace_layout_host(LayoutHost {
166 host: Rc::clone(host),
167 });
168 }
169 }
170}
171
172#[derive(Clone, Copy, PartialEq)]
173struct ModifierChainInputs {
174 density: crate::density::Density,
175 window_root: bool,
176 offset: Point,
177 uses_chain: bool,
178}
179
180struct ModifierChainMeasurement {
181 size: Size,
182 alignment_lines: AlignmentLines,
183 content_offset: Point,
184 offset: Point,
185 window_root: bool,
186 hold: Option<cranpose_ui_layout::ConstraintsHold>,
188 ignores_child_sizes: bool,
191}
192
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
196pub struct LayoutAllocationDebugStats {
197 pub layout_box_count: usize,
199 pub layout_box_child_count: usize,
201 pub layout_box_child_capacity: usize,
203 pub layout_box_heap_bytes: usize,
205 pub modifier_slice_count: usize,
207 pub modifier_slice_heap_bytes: usize,
209 pub modifier_draw_command_count: usize,
211 pub modifier_draw_command_capacity: usize,
213 pub modifier_pointer_input_count: usize,
215 pub modifier_pointer_input_capacity: usize,
217 pub modifier_text_content_count: usize,
219 pub modifier_text_style_count: usize,
221 pub modifier_text_layout_options_count: usize,
223 pub modifier_prepared_text_layout_count: usize,
225 pub modifier_graphics_layer_count: usize,
227 pub modifier_graphics_layer_resolver_count: usize,
229 pub semantics_node_count: usize,
231 pub semantics_action_count: usize,
233 pub semantics_action_capacity: usize,
235 pub semantics_child_count: usize,
237 pub semantics_child_capacity: usize,
239 pub semantics_description_count: usize,
241 pub semantics_description_bytes: usize,
243 pub semantics_heap_bytes: usize,
245}
246
247impl LayoutAllocationDebugStats {
248 fn add_modifier_slice(&mut self, stats: ModifierNodeSlicesDebugStats) {
249 self.modifier_slice_count += 1;
250 self.modifier_slice_heap_bytes += stats.heap_bytes;
251 self.modifier_draw_command_count += stats.draw_command_count;
252 self.modifier_draw_command_capacity += stats.draw_command_capacity;
253 self.modifier_pointer_input_count += stats.pointer_input_count;
254 self.modifier_pointer_input_capacity += stats.pointer_input_capacity;
255 self.modifier_text_content_count += usize::from(stats.has_text_content);
256 self.modifier_text_style_count += usize::from(stats.has_text_style);
257 self.modifier_text_layout_options_count += usize::from(stats.has_text_layout_options);
258 self.modifier_prepared_text_layout_count += usize::from(stats.has_prepared_text_layout);
259 self.modifier_graphics_layer_count += usize::from(stats.has_graphics_layer);
260 self.modifier_graphics_layer_resolver_count +=
261 usize::from(stats.has_graphics_layer_resolver);
262 }
263}
264
265#[derive(Debug, Clone)]
267pub struct LayoutTree {
268 root: LayoutBox,
269}
270
271impl LayoutTree {
272 pub fn new(root: LayoutBox) -> Self {
274 Self { root }
275 }
276
277 pub fn root(&self) -> &LayoutBox {
279 &self.root
280 }
281
282 pub fn root_mut(&mut self) -> &mut LayoutBox {
284 &mut self.root
285 }
286
287 pub fn into_root(self) -> LayoutBox {
289 self.root
290 }
291
292 pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
294 let mut stats = LayoutAllocationDebugStats::default();
295 record_layout_box_allocation_stats(&self.root, &mut stats);
296 stats
297 }
298}
299
300#[derive(Debug, Clone)]
302pub struct LayoutBox {
303 pub node_id: NodeId,
305 pub node_generation: u32,
307 pub rect: GeometryRect,
310 pub content_offset: Point,
312 pub node_data: LayoutNodeData,
314 pub children: Vec<Self>,
316}
317
318impl LayoutBox {
319 pub fn new(
321 node_id: NodeId,
322 rect: GeometryRect,
323 content_offset: Point,
324 node_data: LayoutNodeData,
325 children: Vec<Self>,
326 ) -> Self {
327 Self {
328 node_id,
329 node_generation: 0,
330 rect,
331 content_offset,
332 node_data,
333 children,
334 }
335 }
336}
337
338pub trait LayoutEngine {
340 fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError>;
342}
343
344impl LayoutEngine for MemoryApplier {
345 fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError> {
346 let measurements = measure_layout(self, root, max_size)?;
347 measurements
348 .into_layout_tree()
349 .ok_or(NodeError::MissingContext {
350 id: root,
351 reason: "layout tree was not requested",
352 })
353 }
354}
355
356#[derive(Debug, Clone)]
358pub struct LayoutMeasurements {
359 root: MeasuredNode,
360 semantics: Option<Box<SemanticsTree>>,
363 layout_tree: Option<Box<LayoutTree>>,
364}
365
366impl LayoutMeasurements {
367 fn new(
368 root: MeasuredNode,
369 semantics: Option<SemanticsTree>,
370 layout_tree: Option<LayoutTree>,
371 ) -> Self {
372 Self {
373 root,
374 semantics: semantics.map(Box::new),
375 layout_tree: layout_tree.map(Box::new),
376 }
377 }
378
379 pub fn root_size(&self) -> Size {
381 self.root.size
382 }
383
384 pub fn semantics_tree(&self) -> Option<&SemanticsTree> {
386 self.semantics.as_deref()
387 }
388
389 pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
391 let mut stats = self
392 .layout_tree
393 .as_deref()
394 .map_or_default(LayoutTree::debug_allocation_stats);
395 if let Some(semantics) = &self.semantics {
396 record_semantics_allocation_stats(semantics.root(), &mut stats);
397 }
398 stats
399 }
400
401 pub fn into_layout_tree(self) -> Option<LayoutTree> {
403 self.layout_tree.map(|tree| *tree)
404 }
405
406 pub fn layout_tree(&self) -> Option<LayoutTree> {
408 self.layout_tree.as_deref().cloned()
409 }
410}
411
412pub fn build_semantics_tree_from_layout_tree(layout_tree: &LayoutTree) -> SemanticsTree {
417 SemanticsTree::new(build_semantics_node_from_layout_box(
418 layout_tree.root(),
419 Point::default(),
420 ))
421}
422
423pub fn build_layout_tree_from_applier(
429 applier: &mut MemoryApplier,
430 root: NodeId,
431) -> Result<Option<LayoutTree>, NodeError> {
432 let origin = layout_tree_origin(read_layout_node(applier, root, |state, _| state)?);
433 let mut child_stack = Vec::new();
434 place_layout_box(
435 applier,
436 root,
437 origin,
438 Some(ProjectiveTransform::identity()),
439 &mut child_stack,
440 )
441 .map(|root| root.map(LayoutTree::new))
442}
443
444pub fn has_placed_content(applier: &mut MemoryApplier, root: NodeId) -> Result<bool, NodeError> {
448 walk_placed_boxes(applier, root, |_| std::ops::ControlFlow::Break(()))
449}
450
451pub fn placed_content_extent(
456 applier: &mut MemoryApplier,
457 root: NodeId,
458) -> Result<Option<Size>, NodeError> {
459 let mut extent: Option<Size> = None;
460 walk_placed_boxes(applier, root, |rect| {
461 let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
462 extent = Some(extent.map_or_else(
463 || Size::new(right, bottom),
464 |extent| Size::new(extent.width.max(right), extent.height.max(bottom)),
465 ));
466 std::ops::ControlFlow::Continue(())
467 })?;
468 Ok(extent)
469}
470
471fn walk_placed_boxes(
476 applier: &mut MemoryApplier,
477 root: NodeId,
478 mut visit: impl FnMut(GeometryRect) -> std::ops::ControlFlow<()>,
479) -> Result<bool, NodeError> {
480 let mut pending: Vec<(NodeId, Point)> = Vec::new();
481 let placed = read_layout_node(applier, root, |state, children| {
482 if state.is_placed() {
483 pending.extend(
484 children
485 .iter()
486 .map(|&child| (child, state.content_offset())),
487 );
488 }
489 })?;
490 if placed.is_none() {
491 return Ok(false);
492 }
493 while let Some((node_id, origin)) = pending.pop() {
494 if crate::modifier::is_window_root(applier, node_id) {
495 continue;
496 }
497 let rect = read_layout_node(applier, node_id, |state, children| {
498 if !state.is_placed() {
499 return None;
500 }
501 let (rect, content) = semantics_placement(&state, Some(origin));
502 pending.extend(children.iter().map(|&child| (child, content)));
503 Some(rect)
504 })?
505 .flatten();
506 if let Some(rect) = rect
507 && rect.width > 0.0
508 && rect.height > 0.0
509 && visit(rect).is_break()
510 {
511 return Ok(true);
512 }
513 }
514 Ok(false)
515}
516
517fn layout_tree_origin(root: Option<LayoutState>) -> Point {
518 let Some(state) = root else {
519 return Point::default();
520 };
521 let position = state.position();
522 Point {
523 x: -position.x,
524 y: -position.y,
525 }
526}
527
528fn finish_placement(applier: &mut MemoryApplier, root: NodeId, context: &AppContext) {
531 if applier
532 .with_node::<LayoutNode, _>(root, |node| {
533 node.place(ChildPlacement::default(), None, context);
534 })
535 .is_err()
536 {
537 let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
538 node.place(ChildPlacement::default(), None, context);
539 });
540 }
541 if let Some(pass) = context.placement_pass().with_unplaced_nodes() {
542 record_unplaced_nodes(applier, pass, context);
543 }
544}
545
546fn read_layout_node<R>(
547 applier: &mut MemoryApplier,
548 node_id: NodeId,
549 mut read: impl FnMut(LayoutState, &[NodeId]) -> R,
550) -> Result<Option<R>, NodeError> {
551 read_live_layout_node(applier, node_id, |node| {
552 node.with_children(|children| read(node.state(), children))
553 })
554}
555
556fn place_layout_box(
561 applier: &mut MemoryApplier,
562 node_id: NodeId,
563 parent_content_origin: Point,
564 parent_transform: Option<ProjectiveTransform>,
565 child_stack: &mut Vec<NodeId>,
566) -> Result<Option<LayoutBox>, NodeError> {
567 let first_child = child_stack.len();
568 let Some(state) = read_layout_node(applier, node_id, |state, children| {
569 if state.is_placed() {
570 child_stack.extend_from_slice(children);
571 }
572 state
573 })?
574 else {
575 return Ok(None);
576 };
577 if !state.is_placed() {
578 return Ok(None);
579 }
580
581 let top_left = Point {
582 x: parent_content_origin.x + state.position().x,
583 y: parent_content_origin.y + state.position().y,
584 };
585 let rect = GeometryRect {
586 x: top_left.x,
587 y: top_left.y,
588 width: state.size().width,
589 height: state.size().height,
590 };
591 let (data, window_transform) =
592 snapshot_node_data(applier, node_id, top_left, state.size(), parent_transform)?;
593 let child_origin = Point {
594 x: top_left.x + state.content_offset().x,
595 y: top_left.y + state.content_offset().y,
596 };
597 let end = child_stack.len();
598 let mut children = Vec::with_capacity(end - first_child);
599 for index in first_child..end {
600 let child_id = child_stack[index];
601 if crate::modifier::is_window_root(applier, child_id) {
602 continue;
603 }
604 if let Some(child) = place_layout_box(
605 applier,
606 child_id,
607 child_origin,
608 window_transform,
609 child_stack,
610 )? {
611 children.push(child);
612 }
613 }
614 child_stack.truncate(first_child);
615
616 Ok(Some(LayoutBox {
617 node_generation: applier.node_generation(node_id),
618 ..LayoutBox::new(node_id, rect, state.content_offset(), data, children)
619 }))
620}
621
622pub fn top_modal_from_applier(
627 applier: &mut MemoryApplier,
628 root: NodeId,
629) -> Result<Option<NodeId>, NodeError> {
630 enum Step {
635 Enter { node: NodeId, child: bool },
636 Modal(NodeId),
637 }
638
639 fn push_placed(
640 steps: &mut Vec<Step>,
641 node: NodeId,
642 reach: cranpose_foundation::SemanticsReach,
643 size: Size,
644 children: impl IntoIterator<Item = NodeId>,
645 ) {
646 if reach.hidden {
647 return;
648 }
649 if reach.is_modal && modal_takes_space(size) {
650 steps.push(Step::Modal(node));
651 }
652 steps.extend(
653 children
654 .into_iter()
655 .map(|node| Step::Enter { node, child: true }),
656 );
657 }
658
659 let mut steps = vec![Step::Enter {
660 node: root,
661 child: false,
662 }];
663 while let Some(step) = steps.pop() {
664 let (node_id, child) = match step {
665 Step::Modal(node) => return Ok(Some(node)),
666 Step::Enter { node, child } => (node, child),
667 };
668 let node = match applier.get_mut(node_id) {
669 Ok(node) => node.as_any_mut(),
670 Err(NodeError::Missing { .. }) => continue,
671 Err(error) => return Err(error),
672 };
673 if let Some(layout) = node.downcast_mut::<LayoutNode>() {
674 let state = layout.layout_state();
675 if state.is_placed() && !(child && layout.is_window_root()) {
676 let children = layout.children.iter().copied();
677 push_placed(
678 &mut steps,
679 node_id,
680 layout.semantics_reach(),
681 state.size(),
682 children,
683 );
684 }
685 } else if let Some(subcompose) = node.downcast_mut::<SubcomposeLayoutNode>() {
686 let state = subcompose.layout_state();
687 if state.is_placed() {
688 let reach = subcompose.semantics_reach();
689 subcompose.with_active_children(|children| {
690 push_placed(
691 &mut steps,
692 node_id,
693 reach,
694 state.size(),
695 children.iter().copied(),
696 );
697 });
698 }
699 }
700 }
701 Ok(None)
702}
703
704#[derive(Clone, Copy, Debug, PartialEq, Eq)]
706pub struct MeasureLayoutOptions {
707 pub collect_semantics: bool,
709 pub build_layout_tree: bool,
711}
712
713impl Default for MeasureLayoutOptions {
714 fn default() -> Self {
715 Self {
716 collect_semantics: true,
717 build_layout_tree: true,
718 }
719 }
720}
721
722pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
730 Ok(applier.get_mut(root)?.layout_dirty())
731}
732
733pub fn tree_needs_semantics(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
739 Ok(applier.get_mut(root)?.needs_semantics())
740}
741
742#[cfg(test)]
743pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
744 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
745}
746
747pub fn measure_layout(
749 applier: &mut MemoryApplier,
750 root: NodeId,
751 max_size: Size,
752) -> Result<LayoutMeasurements, NodeError> {
753 measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
754}
755
756pub fn measure_layout_with_options(
759 applier: &mut MemoryApplier,
760 root: NodeId,
761 max_size: Size,
762 options: MeasureLayoutOptions,
763) -> Result<LayoutMeasurements, NodeError> {
764 let mut stages = LayoutStages::start(layout_measure_telemetry_threshold_ms().is_some());
765 let context = crate::render_state::require_current_app_context("a layout pass");
766 context.begin_text_layout_pass();
767 context.placement_pass().begin();
768 process_pending_layout_repasses(&context, applier, root)?;
769 stages.reached();
770
771 let constraints = Constraints {
772 min_width: 0.0,
773 max_width: max_size.width,
774 min_height: 0.0,
775 max_height: max_size.height,
776 };
777
778 let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
779 .with_node::<LayoutNode, _>(root, |node| {
780 (
781 node.needs_measure() || Node::descendant_needs_measure(node),
782 node.needs_semantics(),
783 node.cache().epoch(),
784 )
785 }) {
786 Ok(tuple) => tuple,
787 Err(NodeError::TypeMismatch { .. }) => {
788 let node = applier.get_mut(root)?;
789 let measure_dirty = node.needs_measure() || node.descendant_needs_measure();
790 let semantics_dirty = node.needs_semantics();
791 (measure_dirty, semantics_dirty, 0)
792 }
793 Err(err) => return Err(err),
794 };
795
796 let epoch = if needs_remeasure {
797 context.next_layout_cache_epoch()
798 } else if cached_epoch != 0 {
799 cached_epoch
800 } else {
801 context.current_layout_cache_epoch()
802 };
803
804 let guard = ApplierSlotGuard::new(applier, &context);
805 let applier_host = guard.host();
806 stages.reached();
807
808 let builder = LayoutBuilder::new_with_epoch(Rc::clone(applier_host), epoch, &context);
809 stages.reached();
810
811 let measured = builder
812 .state
813 .measure_root(root, normalize_constraints(constraints))?;
814 stages.reached();
815
816 if let Ok(mut applier) = applier_host.try_borrow_typed() {
817 finish_placement(&mut applier, root, &context);
818 }
819 stages.reached();
820
821 let (layout_tree, semantics) = {
822 let mut applier_ref = applier_host.borrow_typed();
823 let layout_tree = if options.build_layout_tree {
824 Some(build_layout_tree(&mut applier_ref, root, &measured)?)
825 } else {
826 None
827 };
828 let semantics = if options.collect_semantics {
829 let semantics_tree = if let Some(layout_tree) = layout_tree.as_ref() {
830 clear_semantics_dirty_flags(&mut applier_ref, root)?;
831 build_semantics_tree_from_layout_tree(layout_tree)
832 } else {
833 build_semantics_tree_from_live_nodes(&mut applier_ref, root, &measured)?
834 };
835 Some(semantics_tree)
836 } else {
837 None
838 };
839 (layout_tree, semantics)
840 };
841 stages.reached();
842
843 drop(builder);
844 stages.reached();
845
846 drop(guard);
847 stages.reached();
848
849 log_layout_measure_telemetry(root, &stages);
850
851 Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
852}
853
854fn process_pending_layout_repasses(
855 context: &AppContext,
856 applier: &mut MemoryApplier,
857 root: NodeId,
858) -> Result<(), NodeError> {
859 for node_id in context.take_modifier_slice_repass_nodes() {
860 if let Ok(node) = applier.get_mut(node_id) {
861 let any = node.as_any_mut();
862 if let Some(layout) = any.downcast_mut::<LayoutNode>() {
863 layout.mark_modifier_slices_dirty();
864 } else if let Some(subcompose) = any.downcast_mut::<SubcomposeLayoutNode>() {
865 subcompose.mark_modifier_slices_dirty();
866 }
867 }
868 }
869 let measure_repass_nodes = context.take_measure_repass_nodes();
870 let repass_nodes = context.take_layout_repass_nodes();
871 if measure_repass_nodes.is_empty() && repass_nodes.is_empty() {
872 return Ok(());
873 }
874 for node_id in measure_repass_nodes {
875 cranpose_core::bubble_measure_dirty(applier as &mut dyn Applier, node_id);
876 }
877 for node_id in repass_nodes {
878 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
879 }
880 applier.get_mut(root)?.mark_descendant_needs_layout(false);
881 Ok(())
882}
883
884struct LayoutBuilder<'a> {
887 state: Rc<LayoutBuilderState>,
888 context: &'a AppContext,
889}
890
891impl<'a> LayoutBuilder<'a> {
892 fn new_with_epoch(
893 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
894 epoch: u64,
895 context: &'a Rc<AppContext>,
896 ) -> Self {
897 Self {
898 state: Rc::new(LayoutBuilderState::new_with_epoch(
899 applier,
900 epoch,
901 Rc::clone(context),
902 )),
903 context,
904 }
905 }
906}
907
908impl Drop for LayoutBuilder<'_> {
909 fn drop(&mut self) {
910 if Rc::strong_count(&self.state) != 1 {
911 return;
912 }
913 let Ok(mut frame_arena) = self.state.frame_arena.try_borrow_mut() else {
914 return;
915 };
916 self.context
917 .replace_layout_frame_arena(std::mem::take(&mut *frame_arena));
918 }
919}
920
921struct LayoutBuilderState {
922 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
923 runtime_handle: RefCell<Option<RuntimeHandle>>,
924 cache_epoch: u64,
925 cache_floor: u64,
926 frame_arena: RefCell<FrameLayoutArena>,
927 context: Rc<AppContext>,
930 measure_telemetry_ms: Option<f64>,
933}
934
935struct LayoutRuntimeFrameBindingCleanup<'a> {
936 state: &'a RefCell<LayoutRuntimeState>,
937}
938
939impl Drop for LayoutRuntimeFrameBindingCleanup<'_> {
940 fn drop(&mut self) {
941 self.state.borrow().unbind_children();
942 }
943}
944
945enum LayoutNodeVisit<'a> {
946 Cached(MeasuredNode),
947 Keep(KeptNode),
950 Measure(LayoutNodeMeasure<'a>),
951}
952
953struct KeptNode {
956 measured: MeasuredNode,
957 parts: Rc<LayoutParts>,
958 ignores_child_sizes: bool,
961}
962
963struct KeptChildren {
966 measured: MeasuredNode,
967 resized: bool,
968}
969
970#[derive(Clone, Copy)]
972struct ChangedChild {
973 constraints: Constraints,
974 placed: bool,
975}
976
977enum ChildChange {
979 Unchanged,
980 Changed(ChangedChild),
981 Refuse,
983}
984
985struct ChildView {
988 self_dirty: bool,
989 parent_data: Option<crate::modifier::SharedParentData>,
992 cached_constraints: Option<Constraints>,
994 read_intrinsics: bool,
995 placed: bool,
996}
997
998impl ChildView {
999 fn of(node: &LiveLayoutNode<'_>) -> Option<Self> {
1001 let cache = node.cache();
1002 let dirt = cache.dirt();
1003 let self_dirty = dirt.measure || dirt.layout;
1004 if !self_dirty && !dirt.descendant.layout {
1005 return None;
1006 }
1007 Some(Self {
1008 self_dirty,
1009 parent_data: self_dirty.then(|| node.parent_data()),
1010 cached_constraints: cache.measured_constraints(),
1011 read_intrinsics: cache.has_intrinsics(),
1012 placed: node.is_placed(),
1013 })
1014 }
1015}
1016
1017struct LayoutNodeMeasure<'a> {
1018 parts: Rc<LayoutParts>,
1019 chain: ModifierChainInputs,
1020 pools: VecPools<'a>,
1021}
1022
1023#[expect(
1024 clippy::multiple_inherent_impl,
1025 reason = "the bottom-up pass, the chain measure and the subcompose measure in their files"
1026)]
1027impl LayoutBuilderState {
1028 fn new_with_epoch(
1029 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1030 epoch: u64,
1031 context: Rc<AppContext>,
1032 ) -> Self {
1033 let runtime_handle = applier.borrow_typed().runtime_handle();
1034
1035 Self {
1036 applier,
1037 runtime_handle: RefCell::new(runtime_handle),
1038 cache_epoch: epoch,
1039 cache_floor: context.layout_cache_floor(),
1040 frame_arena: RefCell::new(context.take_layout_frame_arena()),
1041 context,
1042 measure_telemetry_ms: layout_measure_telemetry_threshold_ms(),
1043 }
1044 }
1045
1046 fn with_applier_result<R>(
1047 &self,
1048 f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
1049 ) -> Result<R, NodeError> {
1050 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1051 return Err(NodeError::MissingContext {
1052 id: NodeId::default(),
1053 reason: "applier already borrowed",
1054 });
1055 };
1056 f(&mut applier)
1057 }
1058
1059 fn measure_subcompose_node(
1060 self: &Rc<Self>,
1061 node_id: NodeId,
1062 constraints: Constraints,
1063 ) -> Result<(&'static str, MeasuredNode), NodeError> {
1064 self.clear_subcompose_placed(node_id);
1065 if let Some(cached) = self.subcompose_measurement_to_keep(node_id, constraints)
1066 && let Some(kept) = self.keep_subcompose_measurement(node_id, constraints, &cached)?
1067 {
1068 return Ok(("subcompose kept", kept));
1069 }
1070 Ok(match self.try_measure_subcompose(node_id, constraints)? {
1071 Some(measured) => {
1072 self.store_subcompose_measurement(node_id, constraints, &measured);
1073 ("subcompose", measured)
1074 }
1075 None => ("fallback", MeasuredNode::default()),
1076 })
1077 }
1078
1079 fn subcompose_measurement_to_keep(
1083 &self,
1084 node_id: NodeId,
1085 constraints: Constraints,
1086 ) -> Option<MeasuredNode> {
1087 let mut applier = self.applier.try_borrow_typed().ok()?;
1088 applier
1089 .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1090 if node.needs_measure() || Node::needs_layout(node) {
1091 return None;
1092 }
1093 let cache = node.cache();
1094 if cache.epoch() < self.cache_floor {
1095 return None;
1096 }
1097 cache.get_measurement(constraints)
1098 })
1099 .ok()
1100 .flatten()
1101 }
1102
1103 fn keep_subcompose_measurement(
1109 self: &Rc<Self>,
1110 node_id: NodeId,
1111 constraints: Constraints,
1112 cached: &MeasuredNode,
1113 ) -> Result<Option<MeasuredNode>, NodeError> {
1114 let kept = self.remeasure_changed_children(
1115 node_id,
1116 &PlacedChildren::Subcompose(node_id),
1117 cached,
1118 false,
1119 |child_id| self.subcompose_child_change(child_id),
1120 |child_id| self.mark_measured_without_policy(child_id),
1121 )?;
1122 let Some(KeptChildren { measured: kept, .. }) = kept else {
1123 return Ok(None);
1124 };
1125 self.with_applier_result(|applier| {
1126 applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1127 node.cache().store_kept_measurement(constraints);
1128 node.clear_needs_layout();
1129 })
1130 })?;
1131 Ok(Some(kept))
1132 }
1133
1134 fn subcompose_child_change(&self, child_id: NodeId) -> Result<ChildChange, NodeError> {
1138 self.child_change(child_id, |view| {
1139 match view.cached_constraints.filter(|_| !view.self_dirty) {
1140 Some(constraints) if !view.read_intrinsics => ChildChange::Changed(ChangedChild {
1141 constraints,
1142 placed: view.placed,
1143 }),
1144 _ => ChildChange::Refuse,
1145 }
1146 })
1147 }
1148
1149 fn child_change(
1152 &self,
1153 child_id: NodeId,
1154 decide: impl FnOnce(ChildView) -> ChildChange,
1155 ) -> Result<ChildChange, NodeError> {
1156 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1157 return Ok(ChildChange::Refuse);
1158 };
1159 Ok(
1160 match read_live_layout_node(&mut applier, child_id, |node| ChildView::of(&node))? {
1161 None => ChildChange::Refuse,
1162 Some(None) => ChildChange::Unchanged,
1163 Some(Some(view)) => decide(view),
1164 },
1165 )
1166 }
1167
1168 fn mark_measured_without_policy(&self, child_id: NodeId) {
1172 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1173 return;
1174 };
1175 if let Ok(node) = applier.get_mut(child_id) {
1176 node.mark_descendant_needs_layout(true);
1177 }
1178 }
1179
1180 fn clear_subcompose_placed(&self, node_id: NodeId) {
1181 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1182 return;
1183 };
1184 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1185 node.clear_placed(&self.context);
1186 });
1187 }
1188
1189 fn measure_node(
1190 self: &Rc<Self>,
1191 node_id: NodeId,
1192 constraints: Constraints,
1193 ) -> Result<MeasuredNode, NodeError> {
1194 let Some(threshold_ms) = self.measure_telemetry_ms else {
1195 return self
1196 .measure_node_untimed(node_id, constraints)
1197 .map(|(_, measured)| measured);
1198 };
1199 self.measure_node_timed(node_id, constraints, threshold_ms)
1200 }
1201
1202 #[inline(never)]
1205 fn measure_node_timed(
1206 self: &Rc<Self>,
1207 node_id: NodeId,
1208 constraints: Constraints,
1209 threshold_ms: f64,
1210 ) -> Result<MeasuredNode, NodeError> {
1211 let start = Instant::now();
1212 let (kind, measured) = self.measure_node_untimed(node_id, constraints)?;
1213 let children = || {
1214 self.with_applier_result(
1215 |applier| Ok(PlacedChildren::of(applier, node_id).len(applier)),
1216 )
1217 .unwrap_or_default()
1218 };
1219 log_node_measure_telemetry(
1220 kind,
1221 node_id,
1222 constraints,
1223 (&measured, children),
1224 (threshold_ms, start),
1225 );
1226 Ok(measured)
1227 }
1228
1229 fn measure_node_untimed(
1231 self: &Rc<Self>,
1232 node_id: NodeId,
1233 constraints: Constraints,
1234 ) -> Result<(&'static str, MeasuredNode), NodeError> {
1235 if let Some(measured) = self.measure_layout_node(node_id, constraints)? {
1236 return Ok(("layout", measured));
1237 }
1238 self.measure_subcompose_node(node_id, constraints)
1239 }
1240
1241 fn try_measure_subcompose(
1242 self: &Rc<Self>,
1243 node_id: NodeId,
1244 constraints: Constraints,
1245 ) -> Result<Option<MeasuredNode>, NodeError> {
1246 let (node_handle, resolved_modifiers) = {
1247 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1248 return Ok(None);
1249 };
1250 let node = match applier.get_mut(node_id) {
1251 Ok(node) => node,
1252 Err(NodeError::Missing { .. }) => return Ok(None),
1253 Err(err) => return Err(err),
1254 };
1255 let any = node.as_any_mut();
1256 if let Some(subcompose) = any.downcast_mut::<SubcomposeLayoutNode>() {
1257 let handle = subcompose.handle();
1258 let resolved_modifiers = handle
1259 .resolved_modifiers()
1260 .on_device_grid(subcompose.density().density());
1261 subcompose.cache().clear_measurement();
1262 (handle, resolved_modifiers)
1263 } else {
1264 return Ok(None);
1265 }
1266 };
1267
1268 let props = resolved_modifiers.layout_properties();
1269 let padding = resolved_modifiers.padding();
1270 let offset = resolved_modifiers.offset();
1271 let mut inner_constraints = normalize_constraints(subtract_padding(constraints, padding));
1272
1273 if let DimensionConstraint::Points(width) = props.width() {
1274 let constrained_width = width - padding.horizontal_sum();
1275 inner_constraints.max_width = inner_constraints.max_width.min(constrained_width);
1276 inner_constraints.min_width = inner_constraints.min_width.min(constrained_width);
1277 }
1278 if let DimensionConstraint::Points(height) = props.height() {
1279 let constrained_height = height - padding.vertical_sum();
1280 inner_constraints.max_height = inner_constraints.max_height.min(constrained_height);
1281 inner_constraints.min_height = inner_constraints.min_height.min(constrained_height);
1282 }
1283
1284 let measure_error = RefCell::new(None);
1285 let measured_children = node_handle.measured_children_scratch();
1286 let measure_result = self.subcompose_policy_result(
1287 &node_handle,
1288 node_id,
1289 inner_constraints,
1290 &measured_children,
1291 &measure_error,
1292 )?;
1293
1294 if let Some(err) = measure_error.borrow_mut().take() {
1295 return Err(err);
1296 }
1297
1298 let cranpose_ui_layout::MeasureResult {
1299 size: measured_size,
1300 alignment_lines: explicit_lines,
1301 placements,
1302 } = measure_result;
1303
1304 let mut width = measured_size.width + padding.horizontal_sum();
1305 let mut height = measured_size.height + padding.vertical_sum();
1306
1307 width = resolve_dimension(
1308 width,
1309 props.width(),
1310 props.min_width(),
1311 props.max_width(),
1312 constraints.min_width,
1313 constraints.max_width,
1314 );
1315 height = resolve_dimension(
1316 height,
1317 props.height(),
1318 props.min_height(),
1319 props.max_height(),
1320 constraints.min_height,
1321 constraints.max_height,
1322 );
1323
1324 let mut alignment_lines = AlignmentLines::default();
1325 let mut measured_children_by_id = measured_children.borrow_mut();
1326
1327 let mut applier = self.applier.try_borrow_typed().ok();
1330 if let Some(applier) = applier.as_mut() {
1331 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |parent_node| {
1332 parent_node.set_measured_size(Size { width, height }, &self.context);
1333 parent_node
1334 .layout_parts()
1335 .note_child_placements(&placements);
1336 parent_node.clear_needs_measure();
1337 parent_node.clear_needs_layout();
1338 });
1339 }
1340
1341 let placed_roots = node_handle.take_placed_roots();
1344 let mut carried = PlacedRootMeasurements::new(&placed_roots);
1345 for placement in &placements {
1346 let looked_up;
1347 let child: &MeasuredNode = if let Some(measured) = carried.next_measurement() {
1348 measured
1349 } else {
1350 looked_up =
1351 if let Some(measured) = measured_children_by_id.remove(&placement.node_id) {
1352 measured
1353 } else {
1354 drop(applier.take());
1355 let measured = self.measure_node(placement.node_id, inner_constraints)?;
1356 applier = self.applier.try_borrow_typed().ok();
1357 measured
1358 };
1359 &looked_up
1360 };
1361 let policy_position = Point {
1362 x: padding.left + placement.x,
1363 y: padding.top + placement.y,
1364 };
1365 let retained_position = Point {
1366 x: policy_position.x + child.offset.x,
1367 y: policy_position.y + child.offset.y,
1368 };
1369 let retained = ChildPlacement::new(retained_position, placement.z_index);
1370 alignment_lines.merge(
1371 child
1372 .alignment_lines_for_parent()
1373 .translated(policy_position.y),
1374 );
1375
1376 if let Some(applier) = applier.as_mut() {
1377 let _ = read_live_layout_node(applier, placement.node_id, |node| {
1378 node.place(retained, node_id, &self.context);
1379 node.keep_in_parent(MeasuredChild::new(child, policy_position));
1380 });
1381 }
1382 }
1383 drop(applier);
1384
1385 node_handle.recycle_placed_roots(placed_roots);
1386 node_handle.recycle_placement_scratch(placements);
1387
1388 Ok(Some(
1389 MeasuredNode::new(Size { width, height }, offset, Point::default())
1390 .with_alignment_lines(
1391 alignment_lines
1392 .with_overrides(explicit_lines.translated(padding.top))
1393 .translated(offset.y),
1394 ),
1395 ))
1396 }
1397
1398 fn measure_layout_node(
1399 self: &Rc<Self>,
1400 node_id: NodeId,
1401 constraints: Constraints,
1402 ) -> Result<Option<MeasuredNode>, NodeError> {
1403 let mut keep = true;
1404 let (mut applier, measure) = loop {
1405 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1406 return Ok(None);
1407 };
1408 match applier.with_node::<LayoutNode, _>(node_id, |node| {
1409 self.visit_layout_node(node, constraints, keep)
1410 }) {
1411 Ok(LayoutNodeVisit::Measure(measure)) => break (applier, measure),
1412 Ok(LayoutNodeVisit::Cached(measured)) => return Ok(Some(measured)),
1413 Ok(LayoutNodeVisit::Keep(node)) => {
1414 drop(applier);
1415 if let Some(kept) = self.keep_measurement(node_id, constraints, node)? {
1416 return Ok(Some(kept));
1417 }
1418 keep = false;
1419 }
1420 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => return Ok(None),
1421 Err(err) => return Err(err),
1422 }
1423 };
1424 let LayoutNodeMeasure {
1425 parts,
1426 chain,
1427 mut pools,
1428 } = measure;
1429
1430 let _frame_binding_cleanup = LayoutRuntimeFrameBindingCleanup {
1431 state: parts.runtime_state(),
1432 };
1433 self.bind_layout_children(
1434 &mut applier,
1435 (node_id, &parts),
1436 &pools.child_ids,
1437 ChildPass::Measure,
1438 )?;
1439 drop(applier);
1440
1441 let runtime_state = parts.runtime_state().borrow();
1442 let measurement = self.measure_through_modifier_chain(
1443 node_id,
1444 &runtime_state,
1445 chain,
1446 constraints,
1447 &mut pools.placements,
1448 &mut pools.placement_indices,
1449 );
1450
1451 if let Some(err) = runtime_state.take_child_error() {
1452 for child in runtime_state.child_states() {
1453 child.record().measured.take();
1454 }
1455 if runtime_state.take_moved_coordinators() {
1456 let layout_state = parts.layout_state();
1457 layout_state.note_geometry_change(node_id, &self.context);
1458 }
1459 return Err(err);
1460 }
1461
1462 runtime_state.place_measured_children(
1463 &pools.placements,
1464 &pools.placement_indices,
1465 measurement.content_offset,
1466 );
1467 let measured = MeasuredNode::new(
1468 measurement.size,
1469 measurement.offset,
1470 measurement.content_offset,
1471 )
1472 .with_alignment_lines(measurement.alignment_lines)
1473 .with_window_root(measurement.window_root);
1474
1475 let cache = parts.cache();
1477 cache.store_held_measurement(
1478 constraints,
1479 measured,
1480 measurement.hold,
1481 measurement.ignores_child_sizes,
1482 );
1483 let layout_state = parts.layout_state();
1484 if runtime_state.take_moved_coordinators() {
1485 layout_state.note_geometry_change(node_id, &self.context);
1486 }
1487 cache.clear_needs_measure();
1488 cache.clear_layout_dirt();
1489 layout_state.set_size(Some(node_id), measurement.size, &self.context);
1490 layout_state.set_content_offset(Some(node_id), measurement.content_offset);
1491
1492 Ok(Some(measured))
1493 }
1494
1495 fn layout_node_intrinsic(
1500 self: &Rc<Self>,
1501 node_id: NodeId,
1502 kind: IntrinsicKind,
1503 ) -> Result<Option<f32>, NodeError> {
1504 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1505 return Ok(None);
1506 };
1507 let mut pools = VecPools::acquire(&self.frame_arena);
1508 let bound = applier.with_node::<LayoutNode, _>(node_id, |node| {
1509 let parts = Rc::clone(node.layout_parts());
1510 let chain = parts.runtime_state().borrow_mut().bind_node(node);
1511 pools.child_ids.extend_from_slice(&node.children);
1512 (parts, chain)
1513 });
1514 let (parts, chain) = match bound {
1515 Ok(bound) => bound,
1516 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => return Ok(None),
1517 Err(err) => return Err(err),
1518 };
1519 let _frame_binding_cleanup = LayoutRuntimeFrameBindingCleanup {
1520 state: parts.runtime_state(),
1521 };
1522 self.bind_layout_children(
1523 &mut applier,
1524 (node_id, &parts),
1525 &pools.child_ids,
1526 ChildPass::Intrinsics,
1527 )?;
1528 drop(applier);
1529
1530 let runtime_state = parts.runtime_state().borrow();
1531 let value = if chain.uses_chain {
1532 let scope = crate::density::DensityMeasureScope::new(chain.density);
1533 let frame = CoordinatorFrame::new(
1534 &runtime_state.measure_policy,
1535 &scope,
1536 runtime_state.child_measurables(),
1537 runtime_state.child_states(),
1538 &mut pools.placements,
1539 &mut pools.placement_indices,
1540 );
1541 runtime_state
1542 .coordinator_chain
1543 .intrinsic_from(0, &frame, kind)
1544 } else {
1545 policy_intrinsic(
1546 runtime_state.measure_policy.as_ref(),
1547 runtime_state.child_measurables(),
1548 kind,
1549 )
1550 };
1551 match runtime_state.take_child_error() {
1552 Some(err) => Err(err),
1553 None => Ok(Some(value)),
1554 }
1555 }
1556
1557 fn measurement_to_keep(
1560 &self,
1561 node: &LayoutNode,
1562 constraints: Constraints,
1563 ) -> Option<MeasuredNode> {
1564 if node.needs_measure() || node.needs_layout() || node.is_virtual() {
1565 return None;
1566 }
1567 let cache = node.cache();
1568 if cache.epoch() < self.cache_floor {
1569 return None;
1570 }
1571 cache.get_measurement(constraints)
1572 }
1573
1574 #[inline(never)]
1579 fn keep_measurement(
1580 self: &Rc<Self>,
1581 node_id: NodeId,
1582 constraints: Constraints,
1583 node: KeptNode,
1584 ) -> Result<Option<MeasuredNode>, NodeError> {
1585 let KeptNode {
1586 measured,
1587 parts,
1588 ignores_child_sizes,
1589 } = node;
1590 let mut next_state = 0;
1591 let kept = self.remeasure_changed_children(
1592 node_id,
1593 &PlacedChildren::Layout(Rc::clone(&parts)),
1594 &measured,
1595 ignores_child_sizes,
1596 |child_id| self.layout_child_change(parts.runtime_state(), &mut next_state, child_id),
1597 |_| {},
1598 )?;
1599 let Some(KeptChildren {
1600 measured: kept,
1601 resized,
1602 }) = kept
1603 else {
1604 return Ok(None);
1605 };
1606 let cache = parts.cache();
1607 if resized {
1608 cache.store_resized_measurement(constraints, kept);
1609 } else {
1610 cache.store_kept_measurement(constraints);
1611 }
1612 cache.clear_layout_dirt();
1613 Ok(Some(kept))
1614 }
1615
1616 fn remeasure_changed_children(
1621 self: &Rc<Self>,
1622 node_id: NodeId,
1623 placed: &PlacedChildren,
1624 cached: &MeasuredNode,
1625 ignores_child_sizes: bool,
1626 mut change: impl FnMut(NodeId) -> Result<ChildChange, NodeError>,
1627 mut remeasured: impl FnMut(NodeId),
1628 ) -> Result<Option<KeptChildren>, NodeError> {
1629 let mut resized = false;
1630 let mut index = 0;
1631 while let Some((child_id, previous)) = match placed.listed_child(index) {
1632 Some(listed) => listed,
1633 None => self.with_applier_result(|applier| placed.get(applier, index))?,
1634 } {
1635 index += 1;
1636 let Some(previous) = previous else {
1637 continue;
1638 };
1639 let child = match change(child_id)? {
1640 ChildChange::Unchanged => continue,
1641 ChildChange::Refuse => return Ok(None),
1642 ChildChange::Changed(child) => child,
1643 };
1644 let measured = self.measure_node(child_id, child.constraints)?;
1645 remeasured(child_id);
1646 let now = ForParent::of(&measured);
1647 if !previous.for_parent.same_as(&now) {
1648 if !(ignores_child_sizes && previous.for_parent.same_but_size(&now)) {
1649 return Ok(None);
1650 }
1651 resized = true;
1652 }
1653 if child.placed {
1654 self.place_where_it_was(node_id, child_id);
1655 }
1656 }
1657 Ok(Some(KeptChildren {
1658 measured: *cached,
1659 resized,
1660 }))
1661 }
1662
1663 fn layout_child_change(
1668 &self,
1669 runtime_state: &RefCell<LayoutRuntimeState>,
1670 next_state: &mut usize,
1671 child_id: NodeId,
1672 ) -> Result<ChildChange, NodeError> {
1673 let runtime_state = runtime_state.borrow();
1674 let Some((offset, state)) = runtime_state
1675 .child_states()
1676 .get(*next_state..)
1677 .unwrap_or_default()
1678 .iter()
1679 .enumerate()
1680 .find(|(_, state)| state.record().child_id() == child_id)
1681 else {
1682 return Ok(ChildChange::Refuse);
1683 };
1684 *next_state += offset + 1;
1685 if !state.cache().dirt().any() {
1687 return Ok(ChildChange::Unchanged);
1688 }
1689 let state = state.record();
1690 self.child_change(child_id, |view| {
1691 let parent_data_changed = view.parent_data.as_ref().is_some_and(|data| {
1692 state.reads_parent_data_change(&*runtime_state.measure_policy, data)
1693 });
1694 match state.measured_constraints.get() {
1695 Some(constraints) if !state.read_intrinsics.get() && !parent_data_changed => {
1696 ChildChange::Changed(ChangedChild {
1697 constraints,
1698 placed: view.placed,
1699 })
1700 }
1701 _ => ChildChange::Refuse,
1702 }
1703 })
1704 }
1705
1706 fn store_subcompose_measurement(
1709 &self,
1710 node_id: NodeId,
1711 constraints: Constraints,
1712 measured: &MeasuredNode,
1713 ) {
1714 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1715 return;
1716 };
1717 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1718 node.cache().store_measurement(constraints, *measured);
1719 });
1720 }
1721
1722 fn place_where_it_was(&self, parent: NodeId, child_id: NodeId) {
1725 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1726 return;
1727 };
1728 let _ = read_live_layout_node(&mut applier, child_id, |child| {
1729 child.stay_placed(parent, &self.context);
1730 });
1731 }
1732
1733 fn visit_layout_node(
1734 &self,
1735 node: &mut LayoutNode,
1736 constraints: Constraints,
1737 keep: bool,
1738 ) -> LayoutNodeVisit<'_> {
1739 node.clear_placed(&self.context);
1740 if keep && let Some(measured) = self.measurement_to_keep(node, constraints) {
1741 return LayoutNodeVisit::Keep(KeptNode {
1742 ignores_child_sizes: node.cache().ignores_child_sizes(),
1743 measured,
1744 parts: Rc::clone(node.layout_parts()),
1745 });
1746 }
1747 let cache = node.cache();
1748 cache.activate(self.cache_epoch);
1749 if !Node::layout_dirty(node)
1750 && let Some(cached) = cache.get_measurement(constraints)
1751 {
1752 node.clear_needs_measure();
1753 node.clear_needs_layout();
1754 return LayoutNodeVisit::Cached(cached);
1755 }
1756
1757 cache.clear_measurement();
1758 let parts = Rc::clone(node.layout_parts());
1759 let chain = parts.runtime_state().borrow_mut().bind_node(node);
1760 let mut pools = VecPools::acquire(&self.frame_arena);
1761 pools.child_ids.extend_from_slice(&node.children);
1762 LayoutNodeVisit::Measure(LayoutNodeMeasure {
1763 parts,
1764 chain,
1765 pools,
1766 })
1767 }
1768}
1769
1770#[derive(Debug, Clone, Copy, Default, PartialEq)]
1771pub(crate) struct MeasuredNode {
1772 size: Size,
1773 offset: Point,
1774 content_offset: Point,
1775 alignment_lines: AlignmentLines,
1776 window_root: bool,
1777}
1778
1779impl MeasuredNode {
1780 fn new(size: Size, offset: Point, content_offset: Point) -> Self {
1781 Self {
1782 size,
1783 offset,
1784 content_offset,
1785 alignment_lines: AlignmentLines::default(),
1786 window_root: false,
1787 }
1788 }
1789
1790 fn with_window_root(mut self, window_root: bool) -> Self {
1791 self.window_root = window_root;
1792 self
1793 }
1794
1795 fn with_alignment_lines(mut self, alignment_lines: AlignmentLines) -> Self {
1796 self.alignment_lines = alignment_lines;
1797 self
1798 }
1799
1800 pub(crate) fn alignment_lines_for_parent(&self) -> AlignmentLines {
1801 if self.window_root {
1802 AlignmentLines::default()
1803 } else {
1804 self.alignment_lines
1805 }
1806 }
1807
1808 pub(crate) fn size_for_parent(&self) -> Size {
1809 if self.window_root {
1810 Size::new(0.0, 0.0)
1811 } else {
1812 self.size
1813 }
1814 }
1815
1816 pub(crate) fn size(&self) -> Size {
1817 self.size
1818 }
1819}
1820
1821#[derive(Debug, Clone, Copy, Default)]
1826struct MeasuredChild {
1827 offset: Point,
1828 for_parent: ForParent,
1829}
1830
1831impl MeasuredChild {
1832 fn new(measured: &MeasuredNode, offset: Point) -> Self {
1833 Self {
1834 offset,
1835 for_parent: ForParent::of(measured),
1836 }
1837 }
1838}
1839
1840#[derive(Debug, Clone, Copy, Default)]
1843struct ForParent {
1844 size: Size,
1845 offset: Point,
1846 alignment_lines: AlignmentLines,
1847}
1848
1849impl ForParent {
1850 fn of(measured: &MeasuredNode) -> Self {
1851 Self {
1852 size: measured.size_for_parent(),
1853 offset: measured.offset,
1854 alignment_lines: measured.alignment_lines_for_parent(),
1855 }
1856 }
1857
1858 fn same_as(&self, other: &Self) -> bool {
1861 self.size == other.size && self.same_but_size(other)
1862 }
1863
1864 fn same_but_size(&self, other: &Self) -> bool {
1866 self.offset == other.offset
1867 && self.alignment_lines.first_baseline() == other.alignment_lines.first_baseline()
1868 && self.alignment_lines.last_baseline() == other.alignment_lines.last_baseline()
1869 }
1870}
1871
1872fn policy_intrinsic(
1874 policy: &dyn MeasurePolicy,
1875 measurables: Measurables<'_>,
1876 kind: IntrinsicKind,
1877) -> f32 {
1878 match kind {
1879 IntrinsicKind::MinWidth(height) => policy.min_intrinsic_width(measurables, height),
1880 IntrinsicKind::MaxWidth(height) => policy.max_intrinsic_width(measurables, height),
1881 IntrinsicKind::MinHeight(width) => policy.min_intrinsic_height(measurables, width),
1882 IntrinsicKind::MaxHeight(width) => policy.max_intrinsic_height(measurables, width),
1883 }
1884}
1885
1886fn clear_semantics_dirty_flags(
1887 applier: &mut MemoryApplier,
1888 node_id: NodeId,
1889) -> Result<(), NodeError> {
1890 match applier.with_node::<LayoutNode, _>(node_id, |layout| {
1891 layout.clear_needs_semantics();
1892 }) {
1893 Ok(()) => {}
1894 Err(NodeError::Missing { .. }) => {}
1895 Err(NodeError::TypeMismatch { .. }) => {
1896 match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |subcompose| {
1897 subcompose.clear_needs_semantics();
1898 }) {
1899 Ok(()) | Err(NodeError::Missing { .. } | NodeError::TypeMismatch { .. }) => {}
1900 Err(err) => return Err(err),
1901 }
1902 }
1903 Err(err) => return Err(err),
1904 }
1905
1906 PlacedChildren::of(applier, node_id).visit(applier, |applier, child, _, _| {
1907 clear_semantics_dirty_flags(applier, child)
1908 })
1909}
1910
1911fn build_semantics_tree_from_live_nodes(
1912 applier: &mut MemoryApplier,
1913 node_id: NodeId,
1914 node: &MeasuredNode,
1915) -> Result<SemanticsTree, NodeError> {
1916 Ok(SemanticsTree::new(build_semantics_node_from_live_nodes(
1917 applier, node_id, node, None,
1918 )?))
1919}
1920
1921fn semantics_node_from_parts(
1922 node_id: NodeId,
1923 node_generation: u32,
1924 mut role: SemanticsRole,
1925 config: Option<SemanticsConfiguration>,
1926 children: Vec<SemanticsNode>,
1927 held_details: Option<Box<SemanticsDetails>>,
1928 bounds: GeometryRect,
1929) -> SemanticsNode {
1930 let focusable = crate::focus_dispatch::has_focus_target(node_id);
1931 let mut node = SemanticsNode {
1932 node_id,
1933 bounds,
1934 node_generation,
1935 children,
1936 focusable,
1937 focused: focusable && crate::focus_dispatch::active_focus_target() == Some(node_id),
1938 details: held_details,
1939 ..SemanticsNode::default()
1940 };
1941 let details = match config {
1942 Some(mut config) => {
1943 if config.role == Some(SemanticsWidgetRole::Button) {
1944 role = SemanticsRole::Button;
1945 }
1946 if config.is_activatable() {
1947 node.actions.push(SemanticsAction::Click {
1948 handler: SemanticsCallback::new(node_id),
1949 });
1950 }
1951 let on_click_label = config.on_click_label.take().or_else(|| {
1952 config
1953 .on_click
1954 .as_ref()
1955 .and_then(|action| (!action.label.is_empty()).then(|| action.label.clone()))
1956 });
1957 node.widget_role = config.role;
1958 node.description = config.content_description.take();
1959 node.on_click = config.on_click.take();
1960 node.selected = config.selected;
1961 node.toggled = config.toggled;
1962 node.enabled = config.enabled;
1963 node.hidden = config.hidden;
1964 node.merge_descendants = config.merge_descendants;
1965 node.traversal_index = config.traversal_index;
1966 node.text = config.text.take();
1967 let is_modal = config.is_modal
1968 && modal_takes_space(Size {
1969 width: bounds.width,
1970 height: bounds.height,
1971 });
1972 SemanticsDetails::from_configuration(config, on_click_label, is_modal)
1973 }
1974 None => SemanticsDetails::NONE,
1975 };
1976 node.set_details(details);
1977 node.role = role;
1978 node
1979}
1980
1981#[inline(never)]
1982fn build_semantics_node_from_live_nodes(
1983 applier: &mut MemoryApplier,
1984 node_id: NodeId,
1985 node: &MeasuredNode,
1986 origin: Option<Point>,
1987) -> Result<SemanticsNode, NodeError> {
1988 let (role, config, (bounds, content), placement) =
1989 match applier.with_node::<LayoutNode, _>(node_id, |layout| {
1990 let role = role_from_modifier_slices(&layout.modifier_slices_snapshot());
1991 let config = layout.semantics_configuration();
1992 layout.clear_needs_semantics();
1993 let state = layout.layout_state();
1994 (
1995 role,
1996 config,
1997 semantics_placement(&state, origin),
1998 SemanticsPlacement::of(&state),
1999 )
2000 }) {
2001 Ok(data) => data,
2002 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => {
2003 match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |subcompose| {
2004 subcompose.clear_needs_semantics();
2005 let state = subcompose.layout_state();
2006 (
2007 SemanticsRole::Subcompose,
2008 subcompose.semantics_configuration(),
2009 semantics_placement(&state, origin),
2010 SemanticsPlacement::of(&state),
2011 )
2012 }) {
2013 Ok(data) => data,
2014 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => {
2015 let top_left = origin.unwrap_or_default();
2016 (
2017 SemanticsRole::Unknown,
2018 None,
2019 (
2020 GeometryRect::from_origin_size(top_left, node.size),
2021 top_left,
2022 ),
2023 SemanticsPlacement::default(),
2024 )
2025 }
2026 Err(err) => return Err(err),
2027 }
2028 }
2029 Err(err) => return Err(err),
2030 };
2031
2032 let placed = PlacedChildren::of(applier, node_id);
2033 let mut children = Vec::with_capacity(placed.len(applier));
2034 placed.visit(applier, |applier, child_id, _, child| {
2035 children.push(build_semantics_node_from_live_nodes(
2036 applier,
2037 child_id,
2038 child,
2039 Some(content),
2040 )?);
2041 Ok(())
2042 })?;
2043
2044 Ok(SemanticsNode {
2045 placement,
2046 ..semantics_node_from_parts(
2047 node_id,
2048 applier.node_generation(node_id),
2049 role,
2050 config,
2051 children,
2052 None,
2053 bounds,
2054 )
2055 })
2056}
2057
2058fn record_semantics_allocation_stats(node: &SemanticsNode, stats: &mut LayoutAllocationDebugStats) {
2059 stats.semantics_node_count += 1;
2060 stats.semantics_action_count += node.actions.len();
2061 stats.semantics_action_capacity += node.actions.capacity();
2062 stats.semantics_child_count += node.children.len();
2063 stats.semantics_child_capacity += node.children.capacity();
2064 stats.semantics_heap_bytes += node.actions.capacity() * size_of::<SemanticsAction>();
2065 stats.semantics_heap_bytes += node.children.capacity() * size_of::<SemanticsNode>();
2066 if node.details.is_some() {
2067 stats.semantics_heap_bytes += size_of::<SemanticsDetails>();
2068 }
2069
2070 if let Some(description) = &node.description {
2071 stats.semantics_description_count += 1;
2072 stats.semantics_description_bytes += description.capacity();
2073 stats.semantics_heap_bytes += description.capacity();
2074 }
2075
2076 for child in &node.children {
2077 record_semantics_allocation_stats(child, stats);
2078 }
2079}
2080
2081fn record_layout_box_allocation_stats(
2082 layout_box: &LayoutBox,
2083 stats: &mut LayoutAllocationDebugStats,
2084) {
2085 stats.layout_box_count += 1;
2086 stats.layout_box_child_count += layout_box.children.len();
2087 stats.layout_box_child_capacity += layout_box.children.capacity();
2088 stats.layout_box_heap_bytes += layout_box.children.capacity() * size_of::<LayoutBox>();
2089 stats.add_modifier_slice(layout_box.node_data.modifier_slices().debug_stats());
2090
2091 for child in &layout_box.children {
2092 record_layout_box_allocation_stats(child, stats);
2093 }
2094}
2095
2096fn build_layout_tree(
2097 applier: &mut MemoryApplier,
2098 node_id: NodeId,
2099 node: &MeasuredNode,
2100) -> Result<LayoutTree, NodeError> {
2101 fn place(
2102 applier: &mut MemoryApplier,
2103 node_id: NodeId,
2104 node: &MeasuredNode,
2105 origin: Point,
2106 parent_transform: Option<ProjectiveTransform>,
2107 ) -> Result<LayoutBox, NodeError> {
2108 let top_left = Point {
2109 x: origin.x + node.offset.x,
2110 y: origin.y + node.offset.y,
2111 };
2112 let rect = GeometryRect {
2113 x: top_left.x,
2114 y: top_left.y,
2115 width: node.size.width,
2116 height: node.size.height,
2117 };
2118 let (data, window_transform) =
2119 snapshot_node_data(applier, node_id, top_left, node.size, parent_transform)?;
2120 let placed = PlacedChildren::of(applier, node_id);
2121 let mut children = Vec::with_capacity(placed.len(applier));
2122 placed.visit(applier, |applier, child_id, offset, child| {
2123 if crate::modifier::is_window_root(applier, child_id) {
2124 return Ok(());
2125 }
2126 let child_origin = Point {
2127 x: top_left.x + offset.x,
2128 y: top_left.y + offset.y,
2129 };
2130 children.push(place(
2131 applier,
2132 child_id,
2133 child,
2134 child_origin,
2135 window_transform,
2136 )?);
2137 Ok(())
2138 })?;
2139 Ok(LayoutBox {
2140 node_generation: applier.node_generation(node_id),
2141 ..LayoutBox::new(node_id, rect, node.content_offset, data, children)
2142 })
2143 }
2144
2145 Ok(LayoutTree::new(place(
2146 applier,
2147 node_id,
2148 node,
2149 Point { x: 0.0, y: 0.0 },
2150 Some(ProjectiveTransform::identity()),
2151 )?))
2152}
2153
2154fn semantics_role_from_layout_box(layout_box: &LayoutBox) -> SemanticsRole {
2155 match &layout_box.node_data.kind {
2156 LayoutNodeKind::Subcompose => SemanticsRole::Subcompose,
2157 LayoutNodeKind::Spacer => SemanticsRole::Spacer,
2158 LayoutNodeKind::Unknown => SemanticsRole::Unknown,
2159 LayoutNodeKind::Button { .. } => SemanticsRole::Button,
2160 LayoutNodeKind::Layout => role_from_modifier_slices(layout_box.node_data.modifier_slices()),
2161 }
2162}
2163
2164#[inline(never)]
2165fn build_semantics_node_from_layout_box(layout_box: &LayoutBox, origin: Point) -> SemanticsNode {
2166 let rect = layout_box.rect;
2167 let content = Point {
2168 x: rect.x + layout_box.content_offset.x,
2169 y: rect.y + layout_box.content_offset.y,
2170 };
2171 let children = layout_box
2172 .children
2173 .iter()
2174 .map(|child| build_semantics_node_from_layout_box(child, content))
2175 .collect();
2176
2177 SemanticsNode {
2178 placement: SemanticsPlacement {
2179 position: Point {
2180 x: rect.x - origin.x,
2181 y: rect.y - origin.y,
2182 },
2183 content_offset: layout_box.content_offset,
2184 },
2185 ..semantics_node_from_parts(
2186 layout_box.node_id,
2187 layout_box.node_generation,
2188 semantics_role_from_layout_box(layout_box),
2189 layout_box.node_data.semantics().cloned(),
2190 children,
2191 None,
2192 rect,
2193 )
2194 }
2195}
2196
2197fn subtract_padding(constraints: Constraints, padding: EdgeInsets) -> Constraints {
2198 let horizontal = padding.horizontal_sum();
2199 let vertical = padding.vertical_sum();
2200 let min_width = (constraints.min_width - horizontal).max(0.0);
2201 let mut max_width = constraints.max_width;
2202 if max_width.is_finite() {
2203 max_width = (max_width - horizontal).max(0.0);
2204 }
2205 let min_height = (constraints.min_height - vertical).max(0.0);
2206 let mut max_height = constraints.max_height;
2207 if max_height.is_finite() {
2208 max_height = (max_height - vertical).max(0.0);
2209 }
2210 normalize_constraints(Constraints {
2211 min_width,
2212 max_width,
2213 min_height,
2214 max_height,
2215 })
2216}
2217
2218fn resolve_dimension(
2219 base: f32,
2220 explicit: DimensionConstraint,
2221 min_override: Option<f32>,
2222 max_override: Option<f32>,
2223 min_limit: f32,
2224 max_limit: f32,
2225) -> f32 {
2226 let mut min_bound = min_limit;
2227 if let Some(min_value) = min_override {
2228 min_bound = min_bound.max(min_value);
2229 }
2230
2231 let mut max_bound = if max_limit.is_finite() {
2232 max_limit
2233 } else {
2234 max_override.unwrap_or(max_limit)
2235 };
2236 if let Some(max_value) = max_override {
2237 if max_bound.is_finite() {
2238 max_bound = max_bound.min(max_value);
2239 } else {
2240 max_bound = max_value;
2241 }
2242 }
2243 if max_bound < min_bound {
2244 max_bound = min_bound;
2245 }
2246
2247 let mut size = match explicit {
2248 DimensionConstraint::Points(points) => points,
2249 DimensionConstraint::Fraction(fraction) => {
2250 if max_limit.is_finite() {
2251 max_limit * fraction.clamp(0.0, 1.0)
2252 } else {
2253 base
2254 }
2255 }
2256 DimensionConstraint::Unspecified => base,
2257 DimensionConstraint::Intrinsic(_) => base,
2258 };
2259
2260 size = clamp_dimension(size, min_bound, max_bound);
2261 size = clamp_dimension(size, min_limit, max_limit);
2262 size.max(0.0)
2263}
2264
2265fn clamp_dimension(value: f32, min: f32, max: f32) -> f32 {
2266 let mut result = value.max(min);
2267 if max.is_finite() {
2268 result = result.min(max);
2269 }
2270 result
2271}
2272
2273fn normalize_constraints(mut constraints: Constraints) -> Constraints {
2274 if constraints.max_width < constraints.min_width {
2275 constraints.max_width = constraints.min_width;
2276 }
2277 if constraints.max_height < constraints.min_height {
2278 constraints.max_height = constraints.min_height;
2279 }
2280 constraints
2281}
2282
2283#[cfg(test)]
2284#[path = "tests/layout_tests.rs"]
2285mod tests;
2286
2287#[cfg(test)]
2288#[path = "tests/semantics_update_tests.rs"]
2289mod semantics_update_tests;
2290
2291#[cfg(test)]
2292#[path = "tests/coordinator_geometry_tests.rs"]
2293mod coordinator_geometry_tests;