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::{ModifierNodeSlicesDebugStats, Point, Rect as GeometryRect, Size},
72 render_state::AppContext,
73 subcompose_layout::SubcomposeLayoutNode,
74 widgets::nodes::{ChildPlacement, IntrinsicKind, LayoutNode, LayoutParts, LayoutState},
75};
76
77#[derive(Clone, Copy, Default)]
78pub(crate) struct LayoutNodeContext {
79 invalidations: u8,
80 update_requested: bool,
81 density: f32,
82}
83
84impl LayoutNodeContext {
85 pub(crate) const LAYOUT_BIT: u8 = 1 << 0;
86 pub(crate) const DRAW_BIT: u8 = 1 << 1;
87 pub(crate) const SEMANTICS_BIT: u8 = 1 << 2;
88 pub(crate) const POINTER_INPUT_BIT: u8 = 1 << 3;
89 pub(crate) const FOCUS_BIT: u8 = 1 << 4;
90
91 #[inline]
92 pub(crate) fn new(density: f32) -> Self {
93 Self {
94 density,
95 ..Self::default()
96 }
97 }
98
99 #[inline]
100 pub(crate) fn invalidations(self) -> u8 {
101 self.invalidations
102 }
103}
104
105impl ModifierNodeContext for LayoutNodeContext {
106 #[inline]
107 fn invalidate(&mut self, kind: InvalidationKind) {
108 self.invalidations |= match kind {
109 InvalidationKind::Layout => Self::LAYOUT_BIT,
110 InvalidationKind::Draw => Self::DRAW_BIT,
111 InvalidationKind::Semantics => Self::SEMANTICS_BIT,
112 InvalidationKind::PointerInput => Self::POINTER_INPUT_BIT,
113 InvalidationKind::Focus => Self::FOCUS_BIT,
114 };
115 }
116
117 fn request_update(&mut self) {
118 self.update_requested = true;
119 }
120
121 fn density(&self) -> f32 {
122 self.density
123 }
124}
125
126#[doc(hidden)]
127pub fn invalidate_all_layout_caches() {
128 crate::render_state::invalidate_layout_cache_epoch();
129}
130
131pub(crate) struct LayoutHost {
134 host: Rc<ConcreteApplierHost<MemoryApplier>>,
135}
136
137impl Default for LayoutHost {
138 fn default() -> Self {
139 Self {
140 host: Rc::new(ConcreteApplierHost::new(MemoryApplier::new())),
141 }
142 }
143}
144
145struct ApplierSlotGuard<'a> {
148 target: &'a mut MemoryApplier,
149 lent: LayoutHost,
150 context: &'a AppContext,
151}
152
153impl<'a> ApplierSlotGuard<'a> {
154 fn new(target: &'a mut MemoryApplier, context: &'a AppContext) -> Self {
155 let lent = context.take_layout_host();
156 std::mem::swap(target, &mut *lent.host.borrow_typed());
157 Self {
158 target,
159 lent,
160 context,
161 }
162 }
163
164 fn host(&self) -> &Rc<ConcreteApplierHost<MemoryApplier>> {
165 &self.lent.host
166 }
167}
168
169impl Drop for ApplierSlotGuard<'_> {
170 fn drop(&mut self) {
171 let host = &self.lent.host;
172 std::mem::swap(self.target, &mut *host.borrow_typed());
173 if Rc::strong_count(host) == 1 {
175 self.context.replace_layout_host(LayoutHost {
176 host: Rc::clone(host),
177 });
178 }
179 }
180}
181
182pub(crate) use self::subcompose_measure::{SubcomposeChainPlan, SubcomposeMeasureStart};
183
184#[derive(Clone, Copy, PartialEq)]
185struct ModifierChainInputs {
186 density: crate::density::Density,
187 window_root: bool,
188 offset: Point,
189 uses_chain: bool,
190}
191
192#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
195pub struct LayoutAllocationDebugStats {
196 pub layout_box_count: usize,
198 pub layout_box_child_count: usize,
200 pub layout_box_child_capacity: usize,
202 pub layout_box_heap_bytes: usize,
204 pub modifier_slice_count: usize,
206 pub modifier_slice_heap_bytes: usize,
208 pub modifier_draw_command_count: usize,
210 pub modifier_draw_command_capacity: usize,
212 pub modifier_pointer_input_count: usize,
214 pub modifier_pointer_input_capacity: usize,
216 pub modifier_text_content_count: usize,
218 pub modifier_text_style_count: usize,
220 pub modifier_text_layout_options_count: usize,
222 pub modifier_prepared_text_layout_count: usize,
224 pub modifier_graphics_layer_count: usize,
226 pub modifier_graphics_layer_resolver_count: usize,
228 pub semantics_node_count: usize,
230 pub semantics_action_count: usize,
232 pub semantics_action_capacity: usize,
234 pub semantics_child_count: usize,
236 pub semantics_child_capacity: usize,
238 pub semantics_description_count: usize,
240 pub semantics_description_bytes: usize,
242 pub semantics_heap_bytes: usize,
244}
245
246impl LayoutAllocationDebugStats {
247 fn add_modifier_slice(&mut self, stats: ModifierNodeSlicesDebugStats) {
248 self.modifier_slice_count += 1;
249 self.modifier_slice_heap_bytes += stats.heap_bytes;
250 self.modifier_draw_command_count += stats.draw_command_count;
251 self.modifier_draw_command_capacity += stats.draw_command_capacity;
252 self.modifier_pointer_input_count += stats.pointer_input_count;
253 self.modifier_pointer_input_capacity += stats.pointer_input_capacity;
254 self.modifier_text_content_count += usize::from(stats.has_text_content);
255 self.modifier_text_style_count += usize::from(stats.has_text_style);
256 self.modifier_text_layout_options_count += usize::from(stats.has_text_layout_options);
257 self.modifier_prepared_text_layout_count += usize::from(stats.has_prepared_text_layout);
258 self.modifier_graphics_layer_count += usize::from(stats.has_graphics_layer);
259 self.modifier_graphics_layer_resolver_count +=
260 usize::from(stats.has_graphics_layer_resolver);
261 }
262}
263
264#[derive(Debug, Clone)]
266pub struct LayoutTree {
267 root: LayoutBox,
268}
269
270impl LayoutTree {
271 pub fn new(root: LayoutBox) -> Self {
273 Self { root }
274 }
275
276 pub fn root(&self) -> &LayoutBox {
278 &self.root
279 }
280
281 pub fn root_mut(&mut self) -> &mut LayoutBox {
283 &mut self.root
284 }
285
286 pub fn into_root(self) -> LayoutBox {
288 self.root
289 }
290
291 pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
293 let mut stats = LayoutAllocationDebugStats::default();
294 record_layout_box_allocation_stats(&self.root, &mut stats);
295 stats
296 }
297}
298
299#[derive(Debug, Clone)]
301pub struct LayoutBox {
302 pub node_id: NodeId,
304 pub node_generation: u32,
306 pub rect: GeometryRect,
309 pub content_offset: Point,
311 pub node_data: LayoutNodeData,
313 pub children: Vec<Self>,
315}
316
317impl LayoutBox {
318 pub fn new(
320 node_id: NodeId,
321 rect: GeometryRect,
322 content_offset: Point,
323 node_data: LayoutNodeData,
324 children: Vec<Self>,
325 ) -> Self {
326 Self {
327 node_id,
328 node_generation: 0,
329 rect,
330 content_offset,
331 node_data,
332 children,
333 }
334 }
335}
336
337pub trait LayoutEngine {
339 fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError>;
341}
342
343impl LayoutEngine for MemoryApplier {
344 fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError> {
345 let measurements = measure_layout(self, root, max_size)?;
346 measurements
347 .into_layout_tree()
348 .ok_or(NodeError::MissingContext {
349 id: root,
350 reason: "layout tree was not requested",
351 })
352 }
353}
354
355#[derive(Debug, Clone)]
357pub struct LayoutMeasurements {
358 root: MeasuredNode,
359 semantics: Option<Box<SemanticsTree>>,
362 layout_tree: Option<Box<LayoutTree>>,
363}
364
365impl LayoutMeasurements {
366 fn new(
367 root: MeasuredNode,
368 semantics: Option<SemanticsTree>,
369 layout_tree: Option<LayoutTree>,
370 ) -> Self {
371 Self {
372 root,
373 semantics: semantics.map(Box::new),
374 layout_tree: layout_tree.map(Box::new),
375 }
376 }
377
378 pub fn root_size(&self) -> Size {
380 self.root.size
381 }
382
383 pub fn semantics_tree(&self) -> Option<&SemanticsTree> {
385 self.semantics.as_deref()
386 }
387
388 pub fn debug_allocation_stats(&self) -> LayoutAllocationDebugStats {
390 let mut stats = self
391 .layout_tree
392 .as_deref()
393 .map_or_default(LayoutTree::debug_allocation_stats);
394 if let Some(semantics) = &self.semantics {
395 record_semantics_allocation_stats(semantics.root(), &mut stats);
396 }
397 stats
398 }
399
400 pub fn into_layout_tree(self) -> Option<LayoutTree> {
402 self.layout_tree.map(|tree| *tree)
403 }
404
405 pub fn layout_tree(&self) -> Option<LayoutTree> {
407 self.layout_tree.as_deref().cloned()
408 }
409}
410
411pub fn build_semantics_tree_from_layout_tree(layout_tree: &LayoutTree) -> SemanticsTree {
416 SemanticsTree::new(build_semantics_node_from_layout_box(
417 layout_tree.root(),
418 Point::default(),
419 ))
420}
421
422pub fn build_layout_tree_from_applier(
428 applier: &mut MemoryApplier,
429 root: NodeId,
430) -> Result<Option<LayoutTree>, NodeError> {
431 let origin = layout_tree_origin(read_layout_node(applier, root, |state, _| state)?);
432 let mut child_stack = Vec::new();
433 place_layout_box(
434 applier,
435 root,
436 origin,
437 Some(ProjectiveTransform::identity()),
438 &mut child_stack,
439 )
440 .map(|root| root.map(LayoutTree::new))
441}
442
443pub fn has_placed_content(applier: &mut MemoryApplier, root: NodeId) -> Result<bool, NodeError> {
447 walk_placed_boxes(applier, root, |_| std::ops::ControlFlow::Break(()))
448}
449
450pub fn placed_content_extent(
455 applier: &mut MemoryApplier,
456 root: NodeId,
457) -> Result<Option<Size>, NodeError> {
458 let mut extent: Option<Size> = None;
459 walk_placed_boxes(applier, root, |rect| {
460 let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
461 extent = Some(extent.map_or_else(
462 || Size::new(right, bottom),
463 |extent| Size::new(extent.width.max(right), extent.height.max(bottom)),
464 ));
465 std::ops::ControlFlow::Continue(())
466 })?;
467 Ok(extent)
468}
469
470fn walk_placed_boxes(
475 applier: &mut MemoryApplier,
476 root: NodeId,
477 mut visit: impl FnMut(GeometryRect) -> std::ops::ControlFlow<()>,
478) -> Result<bool, NodeError> {
479 let mut pending: Vec<(NodeId, Point)> = Vec::new();
480 let placed = read_layout_node(applier, root, |state, children| {
481 if state.is_placed() {
482 pending.extend(
483 children
484 .iter()
485 .map(|&child| (child, state.content_offset())),
486 );
487 }
488 })?;
489 if placed.is_none() {
490 return Ok(false);
491 }
492 while let Some((node_id, origin)) = pending.pop() {
493 if crate::modifier::is_window_root(applier, node_id) {
494 continue;
495 }
496 let rect = read_layout_node(applier, node_id, |state, children| {
497 if !state.is_placed() {
498 return None;
499 }
500 let (rect, content) = semantics_placement(&state, Some(origin));
501 pending.extend(children.iter().map(|&child| (child, content)));
502 Some(rect)
503 })?
504 .flatten();
505 if let Some(rect) = rect
506 && rect.width > 0.0
507 && rect.height > 0.0
508 && visit(rect).is_break()
509 {
510 return Ok(true);
511 }
512 }
513 Ok(false)
514}
515
516fn layout_tree_origin(root: Option<LayoutState>) -> Point {
517 let Some(state) = root else {
518 return Point::default();
519 };
520 let position = state.position();
521 Point {
522 x: -position.x,
523 y: -position.y,
524 }
525}
526
527fn finish_placement(applier: &mut MemoryApplier, root: NodeId, context: &AppContext) {
530 if applier
531 .with_node::<LayoutNode, _>(root, |node| {
532 node.place(ChildPlacement::default(), None, context);
533 })
534 .is_err()
535 {
536 let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
537 node.place(ChildPlacement::default(), None, context);
538 });
539 }
540 if let Some(pass) = context.placement_pass().with_unplaced_nodes() {
541 record_unplaced_nodes(applier, pass, context);
542 }
543}
544
545fn read_layout_node<R>(
546 applier: &mut MemoryApplier,
547 node_id: NodeId,
548 mut read: impl FnMut(LayoutState, &[NodeId]) -> R,
549) -> Result<Option<R>, NodeError> {
550 read_live_layout_node(applier, node_id, |node| {
551 node.with_children(|children| read(node.state(), children))
552 })
553}
554
555fn place_layout_box(
560 applier: &mut MemoryApplier,
561 node_id: NodeId,
562 parent_content_origin: Point,
563 parent_transform: Option<ProjectiveTransform>,
564 child_stack: &mut Vec<NodeId>,
565) -> Result<Option<LayoutBox>, NodeError> {
566 let first_child = child_stack.len();
567 let Some(state) = read_layout_node(applier, node_id, |state, children| {
568 if state.is_placed() {
569 child_stack.extend_from_slice(children);
570 }
571 state
572 })?
573 else {
574 return Ok(None);
575 };
576 if !state.is_placed() {
577 return Ok(None);
578 }
579
580 let top_left = Point {
581 x: parent_content_origin.x + state.position().x,
582 y: parent_content_origin.y + state.position().y,
583 };
584 let rect = GeometryRect {
585 x: top_left.x,
586 y: top_left.y,
587 width: state.size().width,
588 height: state.size().height,
589 };
590 let (data, window_transform) =
591 snapshot_node_data(applier, node_id, top_left, state.size(), parent_transform)?;
592 let child_origin = Point {
593 x: top_left.x + state.content_offset().x,
594 y: top_left.y + state.content_offset().y,
595 };
596 let end = child_stack.len();
597 let mut children = Vec::with_capacity(end - first_child);
598 for index in first_child..end {
599 let child_id = child_stack[index];
600 if crate::modifier::is_window_root(applier, child_id) {
601 continue;
602 }
603 if let Some(child) = place_layout_box(
604 applier,
605 child_id,
606 child_origin,
607 window_transform,
608 child_stack,
609 )? {
610 children.push(child);
611 }
612 }
613 child_stack.truncate(first_child);
614
615 Ok(Some(LayoutBox {
616 node_generation: applier.node_generation(node_id),
617 ..LayoutBox::new(node_id, rect, state.content_offset(), data, children)
618 }))
619}
620
621pub fn top_modal_from_applier(
626 applier: &mut MemoryApplier,
627 root: NodeId,
628) -> Result<Option<NodeId>, NodeError> {
629 enum Step {
634 Enter { node: NodeId, child: bool },
635 Modal(NodeId),
636 }
637
638 fn push_placed(
639 steps: &mut Vec<Step>,
640 node: NodeId,
641 reach: cranpose_foundation::SemanticsReach,
642 size: Size,
643 children: impl IntoIterator<Item = NodeId>,
644 ) {
645 if reach.hidden {
646 return;
647 }
648 if reach.is_modal && modal_takes_space(size) {
649 steps.push(Step::Modal(node));
650 }
651 steps.extend(
652 children
653 .into_iter()
654 .map(|node| Step::Enter { node, child: true }),
655 );
656 }
657
658 let mut steps = vec![Step::Enter {
659 node: root,
660 child: false,
661 }];
662 while let Some(step) = steps.pop() {
663 let (node_id, child) = match step {
664 Step::Modal(node) => return Ok(Some(node)),
665 Step::Enter { node, child } => (node, child),
666 };
667 let node = match applier.get_mut(node_id) {
668 Ok(node) => node.as_any_mut(),
669 Err(NodeError::Missing { .. }) => continue,
670 Err(error) => return Err(error),
671 };
672 if let Some(layout) = node.downcast_mut::<LayoutNode>() {
673 let state = layout.layout_state();
674 if state.is_placed() && !(child && layout.is_window_root()) {
675 let children = layout.children.iter().copied();
676 push_placed(
677 &mut steps,
678 node_id,
679 layout.semantics_reach(),
680 state.size(),
681 children,
682 );
683 }
684 } else if let Some(subcompose) = node.downcast_mut::<SubcomposeLayoutNode>() {
685 let state = subcompose.layout_state();
686 if state.is_placed() {
687 let reach = subcompose.semantics_reach();
688 subcompose.with_active_children(|children| {
689 push_placed(
690 &mut steps,
691 node_id,
692 reach,
693 state.size(),
694 children.iter().copied(),
695 );
696 });
697 }
698 }
699 }
700 Ok(None)
701}
702
703#[derive(Clone, Copy, Debug, PartialEq, Eq)]
705pub struct MeasureLayoutOptions {
706 pub collect_semantics: bool,
708 pub build_layout_tree: bool,
710}
711
712impl Default for MeasureLayoutOptions {
713 fn default() -> Self {
714 Self {
715 collect_semantics: true,
716 build_layout_tree: true,
717 }
718 }
719}
720
721pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
729 Ok(applier.get_mut(root)?.layout_dirty())
730}
731
732pub fn tree_needs_semantics(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
738 Ok(applier.get_mut(root)?.needs_semantics())
739}
740
741#[cfg(test)]
742pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
743 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
744}
745
746pub fn measure_layout(
748 applier: &mut MemoryApplier,
749 root: NodeId,
750 max_size: Size,
751) -> Result<LayoutMeasurements, NodeError> {
752 measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
753}
754
755pub fn measure_layout_with_options(
758 applier: &mut MemoryApplier,
759 root: NodeId,
760 max_size: Size,
761 options: MeasureLayoutOptions,
762) -> Result<LayoutMeasurements, NodeError> {
763 let mut stages = LayoutStages::start(layout_measure_telemetry_threshold_ms().is_some());
764 let context = crate::render_state::require_current_app_context("a layout pass");
765 context.begin_text_layout_pass();
766 context.placement_pass().begin();
767 process_pending_layout_repasses(&context, applier, root)?;
768 stages.reached();
769
770 let constraints = Constraints {
771 min_width: 0.0,
772 max_width: max_size.width,
773 min_height: 0.0,
774 max_height: max_size.height,
775 };
776
777 let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
778 .with_node::<LayoutNode, _>(root, |node| {
779 (
780 node.needs_measure() || Node::descendant_needs_measure(node),
781 node.needs_semantics(),
782 node.cache().epoch(),
783 )
784 }) {
785 Ok(tuple) => tuple,
786 Err(NodeError::TypeMismatch { .. }) => {
787 let node = applier.get_mut(root)?;
788 let measure_dirty = node.needs_measure() || node.descendant_needs_measure();
789 let semantics_dirty = node.needs_semantics();
790 (measure_dirty, semantics_dirty, 0)
791 }
792 Err(err) => return Err(err),
793 };
794
795 let epoch = if needs_remeasure {
796 context.next_layout_cache_epoch()
797 } else if cached_epoch != 0 {
798 cached_epoch
799 } else {
800 context.current_layout_cache_epoch()
801 };
802
803 let guard = ApplierSlotGuard::new(applier, &context);
804 let applier_host = guard.host();
805 stages.reached();
806
807 let builder = LayoutBuilder::new_with_epoch(Rc::clone(applier_host), epoch, &context);
808 stages.reached();
809
810 let measured = builder
811 .state
812 .measure_root(root, normalize_constraints(constraints))?;
813 stages.reached();
814
815 if let Ok(mut applier) = applier_host.try_borrow_typed() {
816 finish_placement(&mut applier, root, &context);
817 }
818 stages.reached();
819
820 let (layout_tree, semantics) = {
821 let mut applier_ref = applier_host.borrow_typed();
822 let layout_tree = if options.build_layout_tree {
823 Some(build_layout_tree(&mut applier_ref, root, &measured)?)
824 } else {
825 None
826 };
827 let semantics = if options.collect_semantics {
828 let semantics_tree = if let Some(layout_tree) = layout_tree.as_ref() {
829 clear_semantics_dirty_flags(&mut applier_ref, root)?;
830 build_semantics_tree_from_layout_tree(layout_tree)
831 } else {
832 build_semantics_tree_from_live_nodes(&mut applier_ref, root, &measured)?
833 };
834 Some(semantics_tree)
835 } else {
836 None
837 };
838 (layout_tree, semantics)
839 };
840 stages.reached();
841
842 drop(builder);
843 stages.reached();
844
845 drop(guard);
846 stages.reached();
847
848 log_layout_measure_telemetry(root, &stages);
849
850 Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
851}
852
853fn process_pending_layout_repasses(
854 context: &AppContext,
855 applier: &mut MemoryApplier,
856 root: NodeId,
857) -> Result<(), NodeError> {
858 for node_id in context.take_modifier_slice_repass_nodes() {
859 if let Ok(node) = applier.get_mut(node_id) {
860 let any = node.as_any_mut();
861 if let Some(layout) = any.downcast_mut::<LayoutNode>() {
862 layout.mark_modifier_slices_dirty();
863 } else if let Some(subcompose) = any.downcast_mut::<SubcomposeLayoutNode>() {
864 subcompose.mark_modifier_slices_dirty();
865 }
866 }
867 }
868 let measure_repass_nodes = context.take_measure_repass_nodes();
869 let repass_nodes = context.take_layout_repass_nodes();
870 if measure_repass_nodes.is_empty() && repass_nodes.is_empty() {
871 return Ok(());
872 }
873 for node_id in measure_repass_nodes {
874 cranpose_core::bubble_measure_dirty(applier as &mut dyn Applier, node_id);
875 }
876 for node_id in repass_nodes {
877 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
878 }
879 applier.get_mut(root)?.mark_descendant_needs_layout(false);
880 Ok(())
881}
882
883struct LayoutBuilder<'a> {
886 state: Rc<LayoutBuilderState>,
887 context: &'a AppContext,
888}
889
890impl<'a> LayoutBuilder<'a> {
891 fn new_with_epoch(
892 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
893 epoch: u64,
894 context: &'a Rc<AppContext>,
895 ) -> Self {
896 Self {
897 state: Rc::new(LayoutBuilderState::new_with_epoch(
898 applier,
899 epoch,
900 Rc::clone(context),
901 )),
902 context,
903 }
904 }
905}
906
907impl Drop for LayoutBuilder<'_> {
908 fn drop(&mut self) {
909 if Rc::strong_count(&self.state) != 1 {
910 return;
911 }
912 let Ok(mut frame_arena) = self.state.frame_arena.try_borrow_mut() else {
913 return;
914 };
915 self.context
916 .replace_layout_frame_arena(std::mem::take(&mut *frame_arena));
917 }
918}
919
920struct LayoutBuilderState {
921 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
922 runtime_handle: RefCell<Option<RuntimeHandle>>,
923 cache_epoch: u64,
924 cache_floor: u64,
925 frame_arena: RefCell<FrameLayoutArena>,
926 context: Rc<AppContext>,
929 measure_telemetry_ms: Option<f64>,
932}
933
934struct LayoutRuntimeFrameBindingCleanup<'a> {
935 state: &'a RefCell<LayoutRuntimeState>,
936}
937
938impl Drop for LayoutRuntimeFrameBindingCleanup<'_> {
939 fn drop(&mut self) {
940 self.state.borrow().unbind_children();
941 }
942}
943
944enum LayoutNodeVisit<'a> {
945 Cached(MeasuredNode),
946 Keep(KeptNode),
949 Measure(LayoutNodeMeasure<'a>),
950}
951
952struct KeptNode {
955 measured: MeasuredNode,
956 parts: Rc<LayoutParts>,
957 ignores_child_sizes: bool,
960}
961
962struct KeptChildren {
965 measured: MeasuredNode,
966 resized: bool,
967}
968
969#[derive(Clone, Copy)]
971struct ChangedChild {
972 constraints: Constraints,
973 placed: bool,
974}
975
976enum ChildChange {
978 Unchanged,
979 Changed(ChangedChild),
980 Refuse,
982}
983
984struct ChildView {
987 self_dirty: bool,
988 parent_data: Option<crate::modifier::SharedParentData>,
991 cached_constraints: Option<Constraints>,
993 read_intrinsics: bool,
994 placed: bool,
995}
996
997impl ChildView {
998 fn of(node: &LiveLayoutNode<'_>) -> Option<Self> {
1000 let cache = node.cache();
1001 let dirt = cache.dirt();
1002 let self_dirty = dirt.measure || dirt.layout;
1003 if !self_dirty && !dirt.descendant.layout {
1004 return None;
1005 }
1006 Some(Self {
1007 self_dirty,
1008 parent_data: self_dirty.then(|| node.parent_data()),
1009 cached_constraints: cache.measured_constraints(),
1010 read_intrinsics: cache.has_intrinsics(),
1011 placed: node.is_placed(),
1012 })
1013 }
1014}
1015
1016struct LayoutNodeMeasure<'a> {
1017 parts: Rc<LayoutParts>,
1018 chain: ModifierChainInputs,
1019 pools: VecPools<'a>,
1020}
1021
1022#[expect(
1023 clippy::multiple_inherent_impl,
1024 reason = "the bottom-up pass, the chain measure and the subcompose measure in their files"
1025)]
1026impl LayoutBuilderState {
1027 fn new_with_epoch(
1028 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1029 epoch: u64,
1030 context: Rc<AppContext>,
1031 ) -> Self {
1032 let runtime_handle = applier.borrow_typed().runtime_handle();
1033
1034 Self {
1035 applier,
1036 runtime_handle: RefCell::new(runtime_handle),
1037 cache_epoch: epoch,
1038 cache_floor: context.layout_cache_floor(),
1039 frame_arena: RefCell::new(context.take_layout_frame_arena()),
1040 context,
1041 measure_telemetry_ms: layout_measure_telemetry_threshold_ms(),
1042 }
1043 }
1044
1045 fn with_applier_result<R>(
1046 &self,
1047 f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
1048 ) -> Result<R, NodeError> {
1049 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1050 return Err(NodeError::MissingContext {
1051 id: NodeId::default(),
1052 reason: "applier already borrowed",
1053 });
1054 };
1055 f(&mut applier)
1056 }
1057
1058 fn measure_subcompose_node(
1059 self: &Rc<Self>,
1060 node_id: NodeId,
1061 constraints: Constraints,
1062 ) -> Result<(&'static str, MeasuredNode), NodeError> {
1063 enum Visit {
1064 Keep(MeasuredNode),
1065 Measure(SubcomposeMeasureStart),
1066 }
1067
1068 let mut keep = true;
1069 let started = loop {
1070 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1071 return Ok(("fallback", MeasuredNode::default()));
1072 };
1073 let visit = match applier.get_mut(node_id) {
1074 Ok(node) => match node.as_any_mut().downcast_mut::<SubcomposeLayoutNode>() {
1075 Some(subcompose) => {
1076 if keep {
1077 subcompose.clear_placed(&self.context);
1078 }
1079 if keep
1080 && !subcompose.needs_measure()
1081 && !Node::needs_layout(subcompose)
1082 && subcompose.cache().epoch() >= self.cache_floor
1083 && let Some(cached) = subcompose.cache().get_measurement(constraints)
1084 {
1085 Visit::Keep(cached)
1086 } else {
1087 Visit::Measure(subcompose.begin_measure(constraints))
1088 }
1089 }
1090 None => return Ok(("fallback", MeasuredNode::default())),
1091 },
1092 Err(NodeError::Missing { .. }) => return Ok(("fallback", MeasuredNode::default())),
1093 Err(err) => return Err(err),
1094 };
1095 drop(applier);
1096 match visit {
1097 Visit::Keep(cached) => {
1098 if let Some(kept) =
1099 self.keep_subcompose_measurement(node_id, constraints, &cached)?
1100 {
1101 return Ok(("subcompose kept", kept));
1102 }
1103 keep = false;
1104 }
1105 Visit::Measure(started) => break started,
1106 }
1107 };
1108 let measured = self.finish_subcompose_measure(node_id, constraints, started)?;
1109 Ok(("subcompose", measured))
1110 }
1111
1112 fn keep_subcompose_measurement(
1118 self: &Rc<Self>,
1119 node_id: NodeId,
1120 constraints: Constraints,
1121 cached: &MeasuredNode,
1122 ) -> Result<Option<MeasuredNode>, NodeError> {
1123 let kept = self.remeasure_changed_children(
1124 node_id,
1125 &PlacedChildren::Subcompose(node_id),
1126 cached,
1127 false,
1128 |child_id| self.subcompose_child_change(child_id),
1129 |child_id| self.mark_measured_without_policy(child_id),
1130 )?;
1131 let Some(KeptChildren { measured: kept, .. }) = kept else {
1132 return Ok(None);
1133 };
1134 self.with_applier_result(|applier| {
1135 applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1136 node.cache().store_kept_measurement(constraints);
1137 node.clear_needs_layout();
1138 })
1139 })?;
1140 Ok(Some(kept))
1141 }
1142
1143 fn subcompose_child_change(&self, child_id: NodeId) -> Result<ChildChange, NodeError> {
1147 self.child_change(child_id, |view| {
1148 match view.cached_constraints.filter(|_| !view.self_dirty) {
1149 Some(constraints) if !view.read_intrinsics => ChildChange::Changed(ChangedChild {
1150 constraints,
1151 placed: view.placed,
1152 }),
1153 _ => ChildChange::Refuse,
1154 }
1155 })
1156 }
1157
1158 fn child_change(
1161 &self,
1162 child_id: NodeId,
1163 decide: impl FnOnce(ChildView) -> ChildChange,
1164 ) -> Result<ChildChange, NodeError> {
1165 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1166 return Ok(ChildChange::Refuse);
1167 };
1168 Ok(
1169 match read_live_layout_node(&mut applier, child_id, |node| ChildView::of(&node))? {
1170 None => ChildChange::Refuse,
1171 Some(None) => ChildChange::Unchanged,
1172 Some(Some(view)) => decide(view),
1173 },
1174 )
1175 }
1176
1177 fn mark_measured_without_policy(&self, child_id: NodeId) {
1181 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1182 return;
1183 };
1184 if let Ok(node) = applier.get_mut(child_id) {
1185 node.mark_descendant_needs_layout(true);
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 #[inline(never)]
1242 fn finish_subcompose_measure(
1243 self: &Rc<Self>,
1244 node_id: NodeId,
1245 constraints: Constraints,
1246 SubcomposeMeasureStart {
1247 handle: node_handle,
1248 parts,
1249 plan,
1250 measured_children,
1251 }: SubcomposeMeasureStart,
1252 ) -> Result<MeasuredNode, NodeError> {
1253 let subcompose_measure::SubcomposeChainMeasurement {
1254 size,
1255 offset,
1256 content_offset,
1257 explicit_lines,
1258 inner_constraints,
1259 placements,
1260 moved_coordinators,
1261 invalidations,
1262 } = self.measure_subcompose_through_modifier_chain(
1263 &node_handle,
1264 &parts,
1265 node_id,
1266 plan,
1267 constraints,
1268 &measured_children,
1269 )?;
1270
1271 let mut alignment_lines = AlignmentLines::default();
1272 let cache = parts.cache();
1273 let layout_state = parts.layout_state();
1274 if moved_coordinators && layout_state.size() == size {
1275 layout_state.note_geometry_change(node_id, &self.context);
1276 }
1277 layout_state.set_size(Some(node_id), size, &self.context);
1278 layout_state.set_content_offset(Some(node_id), content_offset);
1279 parts.note_child_placements(&placements);
1280 cache.clear_needs_measure();
1281 cache.clear_layout_dirt();
1282 self.mark_invalidations(node_id, invalidations);
1283
1284 let mut applier = (!placements.is_empty())
1287 .then(|| self.applier.try_borrow_typed().ok())
1288 .flatten();
1289
1290 let placed_roots = node_handle.take_placed_roots();
1293 let mut carried = PlacedRootMeasurements::new(&placed_roots);
1294 for placement in &placements {
1295 let looked_up;
1296 let child: &MeasuredNode = if let Some(measured) = carried.next_measurement() {
1297 measured
1298 } else {
1299 let recorded = measured_children.borrow_mut().remove(&placement.node_id);
1300 looked_up = if let Some(measured) = recorded {
1301 measured
1302 } else {
1303 drop(applier.take());
1304 let measured = self.measure_node(placement.node_id, inner_constraints)?;
1305 applier = self.applier.try_borrow_typed().ok();
1306 measured
1307 };
1308 &looked_up
1309 };
1310 let policy_position = Point {
1311 x: content_offset.x + placement.x,
1312 y: content_offset.y + placement.y,
1313 };
1314 let retained_position = Point {
1315 x: placement.x + child.offset.x,
1316 y: placement.y + child.offset.y,
1317 };
1318 let retained = ChildPlacement::new(retained_position, placement.z_index);
1319 alignment_lines.merge(
1320 child
1321 .alignment_lines_for_parent()
1322 .translated(policy_position.y),
1323 );
1324
1325 if let Some(applier) = applier.as_mut() {
1326 let _ = read_live_layout_node(applier, placement.node_id, |node| {
1327 node.place(retained, node_id, &self.context);
1328 node.keep_in_parent(MeasuredChild::new(child, policy_position));
1329 });
1330 }
1331 }
1332 drop(applier);
1333
1334 node_handle.recycle_placed_roots(placed_roots);
1335 node_handle.recycle_placement_scratch(placements);
1336
1337 let measured = MeasuredNode::new(size, offset, content_offset).with_alignment_lines(
1338 alignment_lines
1339 .translated(offset.y)
1340 .with_overrides(explicit_lines),
1341 );
1342 cache.store_measurement(constraints, measured);
1343 Ok(measured)
1344 }
1345
1346 fn measure_layout_node(
1347 self: &Rc<Self>,
1348 node_id: NodeId,
1349 constraints: Constraints,
1350 ) -> Result<Option<MeasuredNode>, NodeError> {
1351 let mut keep = true;
1352 let (mut applier, measure) = loop {
1353 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1354 return Ok(None);
1355 };
1356 match applier.with_node::<LayoutNode, _>(node_id, |node| {
1357 self.visit_layout_node(node, constraints, keep)
1358 }) {
1359 Ok(LayoutNodeVisit::Measure(measure)) => break (applier, measure),
1360 Ok(LayoutNodeVisit::Cached(measured)) => return Ok(Some(measured)),
1361 Ok(LayoutNodeVisit::Keep(node)) => {
1362 drop(applier);
1363 if let Some(kept) = self.keep_measurement(node_id, constraints, node)? {
1364 return Ok(Some(kept));
1365 }
1366 keep = false;
1367 }
1368 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => return Ok(None),
1369 Err(err) => return Err(err),
1370 }
1371 };
1372 let LayoutNodeMeasure {
1373 parts,
1374 chain,
1375 mut pools,
1376 } = measure;
1377
1378 let _frame_binding_cleanup = LayoutRuntimeFrameBindingCleanup {
1379 state: parts.runtime_state(),
1380 };
1381 self.bind_layout_children(
1382 &mut applier,
1383 (node_id, &parts),
1384 &pools.child_ids,
1385 ChildPass::Measure,
1386 )?;
1387 drop(applier);
1388
1389 let runtime_state = parts.runtime_state().borrow();
1390 let measurement = self.measure_through_modifier_chain(
1391 node_id,
1392 &runtime_state,
1393 chain,
1394 constraints,
1395 &mut pools.placements,
1396 &mut pools.placement_indices,
1397 );
1398
1399 if let Some(err) = runtime_state.take_child_error() {
1400 for child in runtime_state.child_states() {
1401 child.record().measured.take();
1402 }
1403 if runtime_state.take_moved_coordinators() {
1404 let layout_state = parts.layout_state();
1405 layout_state.note_geometry_change(node_id, &self.context);
1406 }
1407 return Err(err);
1408 }
1409
1410 runtime_state.place_measured_children(
1411 &pools.placements,
1412 &pools.placement_indices,
1413 measurement.content_offset,
1414 );
1415 let measured = MeasuredNode::new(
1416 measurement.size,
1417 measurement.offset,
1418 measurement.content_offset,
1419 )
1420 .with_alignment_lines(measurement.alignment_lines)
1421 .with_window_root(measurement.window_root);
1422
1423 let cache = parts.cache();
1425 cache.store_held_measurement(
1426 constraints,
1427 measured,
1428 measurement.hold,
1429 measurement.ignores_child_sizes,
1430 );
1431 let layout_state = parts.layout_state();
1432 if runtime_state.take_moved_coordinators() && layout_state.size() == measurement.size {
1433 layout_state.note_geometry_change(node_id, &self.context);
1434 }
1435 cache.clear_needs_measure();
1436 cache.clear_layout_dirt();
1437 self.mark_invalidations(node_id, measurement.invalidations);
1438 layout_state.set_size(Some(node_id), measurement.size, &self.context);
1439 layout_state.set_content_offset(Some(node_id), measurement.content_offset);
1440
1441 Ok(Some(measured))
1442 }
1443
1444 fn layout_node_intrinsic(
1449 self: &Rc<Self>,
1450 node_id: NodeId,
1451 kind: IntrinsicKind,
1452 ) -> Result<Option<f32>, NodeError> {
1453 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1454 return Ok(None);
1455 };
1456 let mut pools = VecPools::acquire(&self.frame_arena);
1457 let bound = applier.with_node::<LayoutNode, _>(node_id, |node| {
1458 let parts = Rc::clone(node.layout_parts());
1459 let chain = parts.runtime_state().borrow_mut().bind_node(node);
1460 pools.child_ids.extend_from_slice(&node.children);
1461 (parts, chain)
1462 });
1463 let (parts, chain) = match bound {
1464 Ok(bound) => bound,
1465 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => return Ok(None),
1466 Err(err) => return Err(err),
1467 };
1468 let _frame_binding_cleanup = LayoutRuntimeFrameBindingCleanup {
1469 state: parts.runtime_state(),
1470 };
1471 self.bind_layout_children(
1472 &mut applier,
1473 (node_id, &parts),
1474 &pools.child_ids,
1475 ChildPass::Intrinsics,
1476 )?;
1477 drop(applier);
1478
1479 let runtime_state = parts.runtime_state().borrow();
1480 let value = if chain.uses_chain {
1481 let scope = crate::density::DensityMeasureScope::new(chain.density);
1482 let frame = CoordinatorFrame::new(
1483 &runtime_state.measure_policy,
1484 &scope,
1485 runtime_state.child_measurables(),
1486 runtime_state.child_states(),
1487 &mut pools.placements,
1488 &mut pools.placement_indices,
1489 );
1490 runtime_state
1491 .coordinator_chain
1492 .intrinsic_from(0, &frame, kind)
1493 } else {
1494 policy_intrinsic(
1495 runtime_state.measure_policy.as_ref(),
1496 runtime_state.child_measurables(),
1497 kind,
1498 )
1499 };
1500 match runtime_state.take_child_error() {
1501 Some(err) => Err(err),
1502 None => Ok(Some(value)),
1503 }
1504 }
1505
1506 fn measurement_to_keep(
1509 &self,
1510 node: &LayoutNode,
1511 constraints: Constraints,
1512 ) -> Option<MeasuredNode> {
1513 if node.needs_measure() || node.needs_layout() || node.is_virtual() {
1514 return None;
1515 }
1516 let cache = node.cache();
1517 if cache.epoch() < self.cache_floor {
1518 return None;
1519 }
1520 cache.get_measurement(constraints)
1521 }
1522
1523 #[inline(never)]
1528 fn keep_measurement(
1529 self: &Rc<Self>,
1530 node_id: NodeId,
1531 constraints: Constraints,
1532 node: KeptNode,
1533 ) -> Result<Option<MeasuredNode>, NodeError> {
1534 let KeptNode {
1535 measured,
1536 parts,
1537 ignores_child_sizes,
1538 } = node;
1539 let mut next_state = 0;
1540 let kept = self.remeasure_changed_children(
1541 node_id,
1542 &PlacedChildren::Layout(Rc::clone(&parts)),
1543 &measured,
1544 ignores_child_sizes,
1545 |child_id| self.layout_child_change(parts.runtime_state(), &mut next_state, child_id),
1546 |_| {},
1547 )?;
1548 let Some(KeptChildren {
1549 measured: kept,
1550 resized,
1551 }) = kept
1552 else {
1553 return Ok(None);
1554 };
1555 let cache = parts.cache();
1556 if resized {
1557 cache.store_resized_measurement(constraints, kept);
1558 } else {
1559 cache.store_kept_measurement(constraints);
1560 }
1561 cache.clear_layout_dirt();
1562 Ok(Some(kept))
1563 }
1564
1565 fn remeasure_changed_children(
1570 self: &Rc<Self>,
1571 node_id: NodeId,
1572 placed: &PlacedChildren,
1573 cached: &MeasuredNode,
1574 ignores_child_sizes: bool,
1575 mut change: impl FnMut(NodeId) -> Result<ChildChange, NodeError>,
1576 mut remeasured: impl FnMut(NodeId),
1577 ) -> Result<Option<KeptChildren>, NodeError> {
1578 let mut resized = false;
1579 let mut index = 0;
1580 while let Some((child_id, previous)) = match placed.listed_child(index) {
1581 Some(listed) => listed,
1582 None => self.with_applier_result(|applier| placed.get(applier, index))?,
1583 } {
1584 index += 1;
1585 let Some(previous) = previous else {
1586 continue;
1587 };
1588 let child = match change(child_id)? {
1589 ChildChange::Unchanged => continue,
1590 ChildChange::Refuse => return Ok(None),
1591 ChildChange::Changed(child) => child,
1592 };
1593 let measured = self.measure_node(child_id, child.constraints)?;
1594 remeasured(child_id);
1595 let now = ForParent::of(&measured);
1596 if !previous.for_parent.same_as(&now) {
1597 if !(ignores_child_sizes && previous.for_parent.same_but_size(&now)) {
1598 return Ok(None);
1599 }
1600 resized = true;
1601 }
1602 if child.placed {
1603 self.place_where_it_was(node_id, child_id);
1604 }
1605 }
1606 Ok(Some(KeptChildren {
1607 measured: *cached,
1608 resized,
1609 }))
1610 }
1611
1612 fn layout_child_change(
1617 &self,
1618 runtime_state: &RefCell<LayoutRuntimeState>,
1619 next_state: &mut usize,
1620 child_id: NodeId,
1621 ) -> Result<ChildChange, NodeError> {
1622 let runtime_state = runtime_state.borrow();
1623 let Some((offset, state)) = runtime_state
1624 .child_states()
1625 .get(*next_state..)
1626 .unwrap_or_default()
1627 .iter()
1628 .enumerate()
1629 .find(|(_, state)| state.record().child_id() == child_id)
1630 else {
1631 return Ok(ChildChange::Refuse);
1632 };
1633 *next_state += offset + 1;
1634 if !state.cache().dirt().any() {
1636 return Ok(ChildChange::Unchanged);
1637 }
1638 let state = state.record();
1639 self.child_change(child_id, |view| {
1640 let parent_data_changed = view.parent_data.as_ref().is_some_and(|data| {
1641 state.reads_parent_data_change(&*runtime_state.measure_policy, data)
1642 });
1643 match state.measured_constraints.get() {
1644 Some(constraints) if !state.read_intrinsics.get() && !parent_data_changed => {
1645 ChildChange::Changed(ChangedChild {
1646 constraints,
1647 placed: view.placed,
1648 })
1649 }
1650 _ => ChildChange::Refuse,
1651 }
1652 })
1653 }
1654
1655 fn place_where_it_was(&self, parent: NodeId, child_id: NodeId) {
1658 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1659 return;
1660 };
1661 let _ = read_live_layout_node(&mut applier, child_id, |child| {
1662 child.stay_placed(parent, &self.context);
1663 });
1664 }
1665
1666 fn visit_layout_node(
1667 &self,
1668 node: &mut LayoutNode,
1669 constraints: Constraints,
1670 keep: bool,
1671 ) -> LayoutNodeVisit<'_> {
1672 node.clear_placed(&self.context);
1673 if keep && let Some(measured) = self.measurement_to_keep(node, constraints) {
1674 return LayoutNodeVisit::Keep(KeptNode {
1675 ignores_child_sizes: node.cache().ignores_child_sizes(),
1676 measured,
1677 parts: Rc::clone(node.layout_parts()),
1678 });
1679 }
1680 let cache = node.cache();
1681 cache.activate(self.cache_epoch);
1682 if !Node::layout_dirty(node)
1683 && let Some(cached) = cache.get_measurement(constraints)
1684 {
1685 node.clear_needs_measure();
1686 node.clear_needs_layout();
1687 return LayoutNodeVisit::Cached(cached);
1688 }
1689
1690 cache.clear_measurement();
1691 let parts = Rc::clone(node.layout_parts());
1692 let chain = parts.runtime_state().borrow_mut().bind_node(node);
1693 let mut pools = VecPools::acquire(&self.frame_arena);
1694 pools.child_ids.extend_from_slice(&node.children);
1695 LayoutNodeVisit::Measure(LayoutNodeMeasure {
1696 parts,
1697 chain,
1698 pools,
1699 })
1700 }
1701}
1702
1703#[derive(Debug, Clone, Copy, Default, PartialEq)]
1704pub(crate) struct MeasuredNode {
1705 size: Size,
1706 offset: Point,
1707 content_offset: Point,
1708 alignment_lines: AlignmentLines,
1709 window_root: bool,
1710}
1711
1712impl MeasuredNode {
1713 fn new(size: Size, offset: Point, content_offset: Point) -> Self {
1714 Self {
1715 size,
1716 offset,
1717 content_offset,
1718 alignment_lines: AlignmentLines::default(),
1719 window_root: false,
1720 }
1721 }
1722
1723 fn with_window_root(mut self, window_root: bool) -> Self {
1724 self.window_root = window_root;
1725 self
1726 }
1727
1728 fn with_alignment_lines(mut self, alignment_lines: AlignmentLines) -> Self {
1729 self.alignment_lines = alignment_lines;
1730 self
1731 }
1732
1733 pub(crate) fn alignment_lines_for_parent(&self) -> AlignmentLines {
1734 if self.window_root {
1735 AlignmentLines::default()
1736 } else {
1737 self.alignment_lines
1738 }
1739 }
1740
1741 pub(crate) fn size_for_parent(&self) -> Size {
1742 if self.window_root {
1743 Size::new(0.0, 0.0)
1744 } else {
1745 self.size
1746 }
1747 }
1748
1749 pub(crate) fn size(&self) -> Size {
1750 self.size
1751 }
1752}
1753
1754#[derive(Debug, Clone, Copy, Default)]
1759struct MeasuredChild {
1760 offset: Point,
1761 for_parent: ForParent,
1762}
1763
1764impl MeasuredChild {
1765 fn new(measured: &MeasuredNode, offset: Point) -> Self {
1766 Self {
1767 offset,
1768 for_parent: ForParent::of(measured),
1769 }
1770 }
1771}
1772
1773#[derive(Debug, Clone, Copy, Default)]
1776struct ForParent {
1777 size: Size,
1778 offset: Point,
1779 alignment_lines: AlignmentLines,
1780}
1781
1782impl ForParent {
1783 fn of(measured: &MeasuredNode) -> Self {
1784 Self {
1785 size: measured.size_for_parent(),
1786 offset: measured.offset,
1787 alignment_lines: measured.alignment_lines_for_parent(),
1788 }
1789 }
1790
1791 fn same_as(&self, other: &Self) -> bool {
1794 self.size == other.size && self.same_but_size(other)
1795 }
1796
1797 fn same_but_size(&self, other: &Self) -> bool {
1799 self.offset == other.offset
1800 && self.alignment_lines.first_baseline() == other.alignment_lines.first_baseline()
1801 && self.alignment_lines.last_baseline() == other.alignment_lines.last_baseline()
1802 }
1803}
1804
1805fn policy_intrinsic(
1807 policy: &dyn MeasurePolicy,
1808 measurables: Measurables<'_>,
1809 kind: IntrinsicKind,
1810) -> f32 {
1811 match kind {
1812 IntrinsicKind::MinWidth(height) => policy.min_intrinsic_width(measurables, height),
1813 IntrinsicKind::MaxWidth(height) => policy.max_intrinsic_width(measurables, height),
1814 IntrinsicKind::MinHeight(width) => policy.min_intrinsic_height(measurables, width),
1815 IntrinsicKind::MaxHeight(width) => policy.max_intrinsic_height(measurables, width),
1816 }
1817}
1818
1819fn clear_semantics_dirty_flags(
1820 applier: &mut MemoryApplier,
1821 node_id: NodeId,
1822) -> Result<(), NodeError> {
1823 match applier.with_node::<LayoutNode, _>(node_id, |layout| {
1824 layout.clear_needs_semantics();
1825 }) {
1826 Ok(()) => {}
1827 Err(NodeError::Missing { .. }) => {}
1828 Err(NodeError::TypeMismatch { .. }) => {
1829 match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |subcompose| {
1830 subcompose.clear_needs_semantics();
1831 }) {
1832 Ok(()) | Err(NodeError::Missing { .. } | NodeError::TypeMismatch { .. }) => {}
1833 Err(err) => return Err(err),
1834 }
1835 }
1836 Err(err) => return Err(err),
1837 }
1838
1839 PlacedChildren::of(applier, node_id).visit(applier, |applier, child, _, _| {
1840 clear_semantics_dirty_flags(applier, child)
1841 })
1842}
1843
1844fn build_semantics_tree_from_live_nodes(
1845 applier: &mut MemoryApplier,
1846 node_id: NodeId,
1847 node: &MeasuredNode,
1848) -> Result<SemanticsTree, NodeError> {
1849 Ok(SemanticsTree::new(build_semantics_node_from_live_nodes(
1850 applier, node_id, node, None,
1851 )?))
1852}
1853
1854fn semantics_node_from_parts(
1855 node_id: NodeId,
1856 node_generation: u32,
1857 mut role: SemanticsRole,
1858 config: Option<SemanticsConfiguration>,
1859 children: Vec<SemanticsNode>,
1860 held_details: Option<Box<SemanticsDetails>>,
1861 bounds: GeometryRect,
1862) -> SemanticsNode {
1863 let focusable = crate::focus_dispatch::has_focus_target(node_id);
1864 let mut node = SemanticsNode {
1865 node_id,
1866 bounds,
1867 node_generation,
1868 children,
1869 focusable,
1870 focused: focusable && crate::focus_dispatch::active_focus_target() == Some(node_id),
1871 details: held_details,
1872 ..SemanticsNode::default()
1873 };
1874 let details = match config {
1875 Some(mut config) => {
1876 if config.role == Some(SemanticsWidgetRole::Button) {
1877 role = SemanticsRole::Button;
1878 }
1879 if config.is_activatable() {
1880 node.actions.push(SemanticsAction::Click {
1881 handler: SemanticsCallback::new(node_id),
1882 });
1883 }
1884 let on_click_label = config.on_click_label.take().or_else(|| {
1885 config
1886 .on_click
1887 .as_ref()
1888 .and_then(|action| (!action.label.is_empty()).then(|| action.label.clone()))
1889 });
1890 node.widget_role = config.role;
1891 node.description = config.content_description.take();
1892 node.on_click = config.on_click.take();
1893 node.selected = config.selected;
1894 node.toggled = config.toggled;
1895 node.enabled = config.enabled;
1896 node.hidden = config.hidden;
1897 node.merge_descendants = config.merge_descendants;
1898 node.traversal_index = config.traversal_index;
1899 node.text = config.text.take();
1900 let is_modal = config.is_modal
1901 && modal_takes_space(Size {
1902 width: bounds.width,
1903 height: bounds.height,
1904 });
1905 SemanticsDetails::from_configuration(config, on_click_label, is_modal)
1906 }
1907 None => SemanticsDetails::NONE,
1908 };
1909 node.set_details(details);
1910 node.role = role;
1911 node
1912}
1913
1914#[inline(never)]
1915fn build_semantics_node_from_live_nodes(
1916 applier: &mut MemoryApplier,
1917 node_id: NodeId,
1918 node: &MeasuredNode,
1919 origin: Option<Point>,
1920) -> Result<SemanticsNode, NodeError> {
1921 let (role, config, (bounds, content), placement) =
1922 match applier.with_node::<LayoutNode, _>(node_id, |layout| {
1923 let role = role_from_modifier_slices(&layout.modifier_slices_snapshot());
1924 let config = layout.semantics_configuration();
1925 layout.clear_needs_semantics();
1926 let state = layout.layout_state();
1927 (
1928 role,
1929 config,
1930 semantics_placement(&state, origin),
1931 SemanticsPlacement::of(&state),
1932 )
1933 }) {
1934 Ok(data) => data,
1935 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => {
1936 match applier.with_node::<SubcomposeLayoutNode, _>(node_id, |subcompose| {
1937 subcompose.clear_needs_semantics();
1938 let state = subcompose.layout_state();
1939 (
1940 SemanticsRole::Subcompose,
1941 subcompose.semantics_configuration(),
1942 semantics_placement(&state, origin),
1943 SemanticsPlacement::of(&state),
1944 )
1945 }) {
1946 Ok(data) => data,
1947 Err(NodeError::TypeMismatch { .. } | NodeError::Missing { .. }) => {
1948 let top_left = origin.unwrap_or_default();
1949 (
1950 SemanticsRole::Unknown,
1951 None,
1952 (
1953 GeometryRect::from_origin_size(top_left, node.size),
1954 top_left,
1955 ),
1956 SemanticsPlacement::default(),
1957 )
1958 }
1959 Err(err) => return Err(err),
1960 }
1961 }
1962 Err(err) => return Err(err),
1963 };
1964
1965 let placed = PlacedChildren::of(applier, node_id);
1966 let mut children = Vec::with_capacity(placed.len(applier));
1967 placed.visit(applier, |applier, child_id, _, child| {
1968 children.push(build_semantics_node_from_live_nodes(
1969 applier,
1970 child_id,
1971 child,
1972 Some(content),
1973 )?);
1974 Ok(())
1975 })?;
1976
1977 Ok(SemanticsNode {
1978 placement,
1979 ..semantics_node_from_parts(
1980 node_id,
1981 applier.node_generation(node_id),
1982 role,
1983 config,
1984 children,
1985 None,
1986 bounds,
1987 )
1988 })
1989}
1990
1991fn record_semantics_allocation_stats(node: &SemanticsNode, stats: &mut LayoutAllocationDebugStats) {
1992 stats.semantics_node_count += 1;
1993 stats.semantics_action_count += node.actions.len();
1994 stats.semantics_action_capacity += node.actions.capacity();
1995 stats.semantics_child_count += node.children.len();
1996 stats.semantics_child_capacity += node.children.capacity();
1997 stats.semantics_heap_bytes += node.actions.capacity() * size_of::<SemanticsAction>();
1998 stats.semantics_heap_bytes += node.children.capacity() * size_of::<SemanticsNode>();
1999 if node.details.is_some() {
2000 stats.semantics_heap_bytes += size_of::<SemanticsDetails>();
2001 }
2002
2003 if let Some(description) = &node.description {
2004 stats.semantics_description_count += 1;
2005 stats.semantics_description_bytes += description.capacity();
2006 stats.semantics_heap_bytes += description.capacity();
2007 }
2008
2009 for child in &node.children {
2010 record_semantics_allocation_stats(child, stats);
2011 }
2012}
2013
2014fn record_layout_box_allocation_stats(
2015 layout_box: &LayoutBox,
2016 stats: &mut LayoutAllocationDebugStats,
2017) {
2018 stats.layout_box_count += 1;
2019 stats.layout_box_child_count += layout_box.children.len();
2020 stats.layout_box_child_capacity += layout_box.children.capacity();
2021 stats.layout_box_heap_bytes += layout_box.children.capacity() * size_of::<LayoutBox>();
2022 stats.add_modifier_slice(layout_box.node_data.modifier_slices().debug_stats());
2023
2024 for child in &layout_box.children {
2025 record_layout_box_allocation_stats(child, stats);
2026 }
2027}
2028
2029fn build_layout_tree(
2030 applier: &mut MemoryApplier,
2031 node_id: NodeId,
2032 node: &MeasuredNode,
2033) -> Result<LayoutTree, NodeError> {
2034 fn place(
2035 applier: &mut MemoryApplier,
2036 node_id: NodeId,
2037 node: &MeasuredNode,
2038 origin: Point,
2039 parent_transform: Option<ProjectiveTransform>,
2040 ) -> Result<LayoutBox, NodeError> {
2041 let top_left = Point {
2042 x: origin.x + node.offset.x,
2043 y: origin.y + node.offset.y,
2044 };
2045 let rect = GeometryRect {
2046 x: top_left.x,
2047 y: top_left.y,
2048 width: node.size.width,
2049 height: node.size.height,
2050 };
2051 let (data, window_transform) =
2052 snapshot_node_data(applier, node_id, top_left, node.size, parent_transform)?;
2053 let placed = PlacedChildren::of(applier, node_id);
2054 let mut children = Vec::with_capacity(placed.len(applier));
2055 placed.visit(applier, |applier, child_id, offset, child| {
2056 if crate::modifier::is_window_root(applier, child_id) {
2057 return Ok(());
2058 }
2059 let child_origin = Point {
2060 x: top_left.x + offset.x,
2061 y: top_left.y + offset.y,
2062 };
2063 children.push(place(
2064 applier,
2065 child_id,
2066 child,
2067 child_origin,
2068 window_transform,
2069 )?);
2070 Ok(())
2071 })?;
2072 Ok(LayoutBox {
2073 node_generation: applier.node_generation(node_id),
2074 ..LayoutBox::new(node_id, rect, node.content_offset, data, children)
2075 })
2076 }
2077
2078 Ok(LayoutTree::new(place(
2079 applier,
2080 node_id,
2081 node,
2082 Point { x: 0.0, y: 0.0 },
2083 Some(ProjectiveTransform::identity()),
2084 )?))
2085}
2086
2087fn semantics_role_from_layout_box(layout_box: &LayoutBox) -> SemanticsRole {
2088 match &layout_box.node_data.kind {
2089 LayoutNodeKind::Subcompose => SemanticsRole::Subcompose,
2090 LayoutNodeKind::Spacer => SemanticsRole::Spacer,
2091 LayoutNodeKind::Unknown => SemanticsRole::Unknown,
2092 LayoutNodeKind::Button { .. } => SemanticsRole::Button,
2093 LayoutNodeKind::Layout => role_from_modifier_slices(layout_box.node_data.modifier_slices()),
2094 }
2095}
2096
2097#[inline(never)]
2098fn build_semantics_node_from_layout_box(layout_box: &LayoutBox, origin: Point) -> SemanticsNode {
2099 let rect = layout_box.rect;
2100 let content = Point {
2101 x: rect.x + layout_box.content_offset.x,
2102 y: rect.y + layout_box.content_offset.y,
2103 };
2104 let children = layout_box
2105 .children
2106 .iter()
2107 .map(|child| build_semantics_node_from_layout_box(child, content))
2108 .collect();
2109
2110 SemanticsNode {
2111 placement: SemanticsPlacement {
2112 position: Point {
2113 x: rect.x - origin.x,
2114 y: rect.y - origin.y,
2115 },
2116 content_offset: layout_box.content_offset,
2117 },
2118 ..semantics_node_from_parts(
2119 layout_box.node_id,
2120 layout_box.node_generation,
2121 semantics_role_from_layout_box(layout_box),
2122 layout_box.node_data.semantics().cloned(),
2123 children,
2124 None,
2125 rect,
2126 )
2127 }
2128}
2129
2130fn normalize_constraints(mut constraints: Constraints) -> Constraints {
2131 if constraints.max_width < constraints.min_width {
2132 constraints.max_width = constraints.min_width;
2133 }
2134 if constraints.max_height < constraints.min_height {
2135 constraints.max_height = constraints.min_height;
2136 }
2137 constraints
2138}
2139
2140#[cfg(test)]
2141#[path = "tests/layout_tests.rs"]
2142mod tests;
2143
2144#[cfg(test)]
2145#[path = "tests/semantics_update_tests.rs"]
2146mod semantics_update_tests;
2147
2148#[cfg(test)]
2149#[path = "tests/coordinator_geometry_tests.rs"]
2150mod coordinator_geometry_tests;