1pub mod coordinator;
4pub mod core;
5pub mod policies;
6
7use cranpose_core::collections::map::Entry;
8use cranpose_core::collections::map::HashMap;
9use std::{
10 cell::RefCell,
11 fmt,
12 rc::Rc,
13 sync::atomic::{AtomicU64, Ordering},
14};
15
16use cranpose_core::{
17 Applier, ApplierHost, Composer, ConcreteApplierHost, MemoryApplier, NodeError, NodeId, Phase,
18 RuntimeHandle, SlotBackend, SlotsHost, SnapshotStateObserver,
19};
20
21use self::coordinator::NodeCoordinator;
22use self::core::Measurable;
23use self::core::Placeable;
24#[cfg(test)]
25use self::core::{HorizontalAlignment, VerticalAlignment};
26use crate::modifier::{
27 collect_semantics_from_modifier, DimensionConstraint, EdgeInsets, Modifier, ModifierNodeSlices,
28 Point, Rect as GeometryRect, ResolvedModifiers, Size,
29};
30
31use crate::subcompose_layout::SubcomposeLayoutNode;
32use crate::widgets::nodes::{IntrinsicKind, LayoutNode, LayoutNodeCacheHandles};
33use cranpose_foundation::InvalidationKind;
34use cranpose_foundation::ModifierNodeContext;
35use cranpose_foundation::{NodeCapabilities, SemanticsConfiguration};
36use cranpose_ui_layout::{Constraints, MeasurePolicy, MeasureResult};
37
38#[derive(Default)]
43pub(crate) struct LayoutNodeContext {
44 invalidations: Vec<InvalidationKind>,
45 update_requested: bool,
46 active_capabilities: Vec<NodeCapabilities>,
47}
48
49impl LayoutNodeContext {
50 pub(crate) fn new() -> Self {
51 Self::default()
52 }
53
54 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationKind> {
55 std::mem::take(&mut self.invalidations)
56 }
57}
58
59impl ModifierNodeContext for LayoutNodeContext {
60 fn invalidate(&mut self, kind: InvalidationKind) {
61 if !self.invalidations.contains(&kind) {
62 self.invalidations.push(kind);
63 }
64 }
65
66 fn request_update(&mut self) {
67 self.update_requested = true;
68 }
69
70 fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
71 self.active_capabilities.push(capabilities);
72 }
73
74 fn pop_active_capabilities(&mut self) {
75 self.active_capabilities.pop();
76 }
77}
78
79static NEXT_CACHE_EPOCH: AtomicU64 = AtomicU64::new(1);
80
81#[doc(hidden)]
104pub fn invalidate_all_layout_caches() {
105 NEXT_CACHE_EPOCH.fetch_add(1, Ordering::Relaxed);
106}
107
108struct ApplierSlotGuard<'a> {
119 target: &'a mut MemoryApplier,
121 host: Rc<ConcreteApplierHost<MemoryApplier>>,
123 slots: Rc<RefCell<SlotBackend>>,
126}
127
128impl<'a> ApplierSlotGuard<'a> {
129 fn new(target: &'a mut MemoryApplier) -> Self {
133 let original_applier = std::mem::replace(target, MemoryApplier::new());
135 let host = Rc::new(ConcreteApplierHost::new(original_applier));
136
137 let slots = {
139 let mut applier_ref = host.borrow_typed();
140 std::mem::take(applier_ref.slots())
141 };
142 let slots = Rc::new(RefCell::new(slots));
143
144 Self {
145 target,
146 host,
147 slots,
148 }
149 }
150
151 fn host(&self) -> Rc<ConcreteApplierHost<MemoryApplier>> {
153 Rc::clone(&self.host)
154 }
155
156 fn slots_handle(&self) -> Rc<RefCell<SlotBackend>> {
159 Rc::clone(&self.slots)
160 }
161}
162
163impl Drop for ApplierSlotGuard<'_> {
164 fn drop(&mut self) {
165 {
169 let mut applier_ref = self.host.borrow_typed();
170 *applier_ref.slots() = std::mem::take(&mut *self.slots.borrow_mut());
171 }
172
173 {
175 let mut applier_ref = self.host.borrow_typed();
176 let original_applier = std::mem::take(&mut *applier_ref);
177 let _ = std::mem::replace(self.target, original_applier);
178 }
179 }
181}
182
183struct ModifierChainMeasurement {
185 result: MeasureResult,
186 content_offset: Point,
188 offset: Point,
190}
191
192type LayoutModifierNodeData = (
193 usize,
194 Rc<RefCell<Box<dyn cranpose_foundation::ModifierNode>>>,
195);
196
197struct ScratchVecPool<T> {
198 available: Vec<Vec<T>>,
199}
200
201impl<T> ScratchVecPool<T> {
202 fn acquire(&mut self) -> Vec<T> {
203 self.available.pop().unwrap_or_default()
204 }
205
206 fn release(&mut self, mut values: Vec<T>) {
207 values.clear();
208 self.available.push(values);
209 }
210
211 #[cfg(test)]
212 fn available_count(&self) -> usize {
213 self.available.len()
214 }
215}
216
217impl<T> Default for ScratchVecPool<T> {
218 fn default() -> Self {
219 Self {
220 available: Vec::new(),
221 }
222 }
223}
224
225#[derive(Clone, Debug, PartialEq, Eq)]
227pub struct SemanticsCallback {
228 node_id: NodeId,
229}
230
231impl SemanticsCallback {
232 pub fn new(node_id: NodeId) -> Self {
233 Self { node_id }
234 }
235
236 pub fn node_id(&self) -> NodeId {
237 self.node_id
238 }
239}
240
241#[derive(Clone, Debug, PartialEq, Eq)]
243pub enum SemanticsAction {
244 Click { handler: SemanticsCallback },
245}
246
247#[derive(Clone, Debug, PartialEq, Eq)]
250pub enum SemanticsRole {
251 Layout,
253 Subcompose,
255 Text { value: String },
257 Spacer,
259 Button,
261 Unknown,
263}
264
265#[derive(Clone, Debug)]
267pub struct SemanticsNode {
268 pub node_id: NodeId,
269 pub role: SemanticsRole,
270 pub actions: Vec<SemanticsAction>,
271 pub children: Vec<SemanticsNode>,
272 pub description: Option<String>,
273}
274
275impl SemanticsNode {
276 fn new(
277 node_id: NodeId,
278 role: SemanticsRole,
279 actions: Vec<SemanticsAction>,
280 children: Vec<SemanticsNode>,
281 description: Option<String>,
282 ) -> Self {
283 Self {
284 node_id,
285 role,
286 actions,
287 children,
288 description,
289 }
290 }
291}
292
293#[derive(Clone, Debug)]
295pub struct SemanticsTree {
296 root: SemanticsNode,
297}
298
299impl SemanticsTree {
300 fn new(root: SemanticsNode) -> Self {
301 Self { root }
302 }
303
304 pub fn root(&self) -> &SemanticsNode {
305 &self.root
306 }
307}
308
309#[derive(Default)]
312pub struct SemanticsOwner {
313 configurations: RefCell<HashMap<NodeId, Option<SemanticsConfiguration>>>,
314}
315
316impl SemanticsOwner {
317 pub fn new() -> Self {
318 Self {
319 configurations: RefCell::new(HashMap::default()),
320 }
321 }
322
323 pub fn get_or_compute(
325 &self,
326 node_id: NodeId,
327 applier: &mut MemoryApplier,
328 ) -> Option<SemanticsConfiguration> {
329 if let Some(cached) = self.configurations.borrow().get(&node_id) {
331 return cached.clone();
332 }
333
334 let config = compute_semantics_for_node(applier, node_id);
336 self.configurations
337 .borrow_mut()
338 .insert(node_id, config.clone());
339 config
340 }
341}
342
343#[derive(Debug, Clone)]
345pub struct LayoutTree {
346 root: LayoutBox,
347}
348
349impl LayoutTree {
350 pub fn new(root: LayoutBox) -> Self {
351 Self { root }
352 }
353
354 pub fn root(&self) -> &LayoutBox {
355 &self.root
356 }
357
358 pub fn root_mut(&mut self) -> &mut LayoutBox {
359 &mut self.root
360 }
361
362 pub fn into_root(self) -> LayoutBox {
363 self.root
364 }
365}
366
367#[derive(Debug, Clone)]
369pub struct LayoutBox {
370 pub node_id: NodeId,
371 pub rect: GeometryRect,
372 pub content_offset: Point,
374 pub node_data: LayoutNodeData,
375 pub children: Vec<LayoutBox>,
376}
377
378impl LayoutBox {
379 pub fn new(
380 node_id: NodeId,
381 rect: GeometryRect,
382 content_offset: Point,
383 node_data: LayoutNodeData,
384 children: Vec<LayoutBox>,
385 ) -> Self {
386 Self {
387 node_id,
388 rect,
389 content_offset,
390 node_data,
391 children,
392 }
393 }
394}
395
396#[derive(Debug, Clone)]
398pub struct LayoutNodeData {
399 pub modifier: Modifier,
400 pub resolved_modifiers: ResolvedModifiers,
401 pub modifier_slices: Rc<ModifierNodeSlices>,
402 pub kind: LayoutNodeKind,
403}
404
405impl LayoutNodeData {
406 pub fn new(
407 modifier: Modifier,
408 resolved_modifiers: ResolvedModifiers,
409 modifier_slices: Rc<ModifierNodeSlices>,
410 kind: LayoutNodeKind,
411 ) -> Self {
412 Self {
413 modifier,
414 resolved_modifiers,
415 modifier_slices,
416 kind,
417 }
418 }
419
420 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
421 self.resolved_modifiers
422 }
423
424 pub fn modifier_slices(&self) -> &ModifierNodeSlices {
425 &self.modifier_slices
426 }
427}
428
429#[derive(Clone)]
436pub enum LayoutNodeKind {
437 Layout,
438 Subcompose,
439 Spacer,
440 Button { on_click: Rc<RefCell<dyn FnMut()>> },
441 Unknown,
442}
443
444impl fmt::Debug for LayoutNodeKind {
445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446 match self {
447 LayoutNodeKind::Layout => f.write_str("Layout"),
448 LayoutNodeKind::Subcompose => f.write_str("Subcompose"),
449 LayoutNodeKind::Spacer => f.write_str("Spacer"),
450 LayoutNodeKind::Button { .. } => f.write_str("Button"),
451 LayoutNodeKind::Unknown => f.write_str("Unknown"),
452 }
453 }
454}
455
456pub trait LayoutEngine {
458 fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError>;
459}
460
461impl LayoutEngine for MemoryApplier {
462 fn compute_layout(&mut self, root: NodeId, max_size: Size) -> Result<LayoutTree, NodeError> {
463 let measurements = measure_layout(self, root, max_size)?;
464 Ok(measurements.into_layout_tree())
465 }
466}
467
468#[derive(Debug, Clone)]
470pub struct LayoutMeasurements {
471 root: Rc<MeasuredNode>,
472 semantics: Option<SemanticsTree>,
473 layout_tree: LayoutTree,
474}
475
476impl LayoutMeasurements {
477 fn new(
478 root: Rc<MeasuredNode>,
479 semantics: Option<SemanticsTree>,
480 layout_tree: LayoutTree,
481 ) -> Self {
482 Self {
483 root,
484 semantics,
485 layout_tree,
486 }
487 }
488
489 pub fn root_size(&self) -> Size {
491 self.root.size
492 }
493
494 pub fn semantics_tree(&self) -> Option<&SemanticsTree> {
495 self.semantics.as_ref()
496 }
497
498 pub fn into_layout_tree(self) -> LayoutTree {
500 self.layout_tree
501 }
502
503 pub fn layout_tree(&self) -> LayoutTree {
505 self.layout_tree.clone()
506 }
507}
508
509#[derive(Clone, Copy, Debug, PartialEq, Eq)]
510pub struct MeasureLayoutOptions {
511 pub collect_semantics: bool,
512}
513
514impl Default for MeasureLayoutOptions {
515 fn default() -> Self {
516 Self {
517 collect_semantics: true,
518 }
519 }
520}
521
522pub fn tree_needs_layout(applier: &mut dyn Applier, root: NodeId) -> Result<bool, NodeError> {
530 let node = applier.get_mut(root)?;
532 let layout_node =
533 node.as_any_mut()
534 .downcast_mut::<LayoutNode>()
535 .ok_or(NodeError::TypeMismatch {
536 id: root,
537 expected: std::any::type_name::<LayoutNode>(),
538 })?;
539 Ok(layout_node.needs_layout())
540}
541
542#[cfg(test)]
544pub(crate) fn bubble_layout_dirty(applier: &mut MemoryApplier, node_id: NodeId) {
545 cranpose_core::bubble_layout_dirty(applier as &mut dyn Applier, node_id);
546}
547
548pub fn measure_layout(
550 applier: &mut MemoryApplier,
551 root: NodeId,
552 max_size: Size,
553) -> Result<LayoutMeasurements, NodeError> {
554 measure_layout_with_options(applier, root, max_size, MeasureLayoutOptions::default())
555}
556
557pub fn measure_layout_with_options(
558 applier: &mut MemoryApplier,
559 root: NodeId,
560 max_size: Size,
561 options: MeasureLayoutOptions,
562) -> Result<LayoutMeasurements, NodeError> {
563 let constraints = Constraints {
564 min_width: 0.0,
565 max_width: max_size.width,
566 min_height: 0.0,
567 max_height: max_size.height,
568 };
569
570 let (needs_remeasure, _needs_semantics, cached_epoch) = match applier
581 .with_node::<LayoutNode, _>(root, |node| {
582 (
583 node.needs_measure(), node.needs_semantics(),
585 node.cache_handles().epoch(),
586 )
587 }) {
588 Ok(tuple) => tuple,
589 Err(NodeError::TypeMismatch { .. }) => {
590 let node = applier.get_mut(root)?;
591 let measure_dirty = node.needs_layout();
593 let semantics_dirty = node.needs_semantics();
594 (measure_dirty, semantics_dirty, 0)
595 }
596 Err(err) => return Err(err),
597 };
598
599 let epoch = if needs_remeasure {
600 NEXT_CACHE_EPOCH.fetch_add(1, Ordering::Relaxed)
601 } else if cached_epoch != 0 {
602 cached_epoch
603 } else {
604 NEXT_CACHE_EPOCH.load(Ordering::Relaxed)
606 };
607
608 let guard = ApplierSlotGuard::new(applier);
616 let applier_host = guard.host();
617 let slots_handle = guard.slots_handle();
618
619 let mut builder =
622 LayoutBuilder::new_with_epoch(Rc::clone(&applier_host), epoch, Rc::clone(&slots_handle));
623
624 let measured = builder.measure_node(root, normalize_constraints(constraints))?;
629
630 if let Ok(mut applier) = applier_host.try_borrow_typed() {
634 if applier
635 .with_node::<LayoutNode, _>(root, |node| {
636 node.set_position(Point::default());
637 })
638 .is_err()
639 {
640 let _ = applier.with_node::<SubcomposeLayoutNode, _>(root, |node| {
641 node.set_position(Point::default());
642 });
643 }
644 }
645
646 let metadata = {
648 let mut applier_ref = applier_host.borrow_typed();
649 collect_runtime_metadata(&mut applier_ref, &measured)?
650 };
651
652 let semantics = if options.collect_semantics {
653 let semantics_snapshot = {
654 let mut applier_ref = applier_host.borrow_typed();
655 collect_semantics_snapshot(&mut applier_ref, &measured)?
656 };
657
658 Some(SemanticsTree::new(build_semantics_node(
659 &measured,
660 &metadata,
661 &semantics_snapshot,
662 )))
663 } else {
664 None
665 };
666
667 drop(builder);
670
671 let layout_tree = build_layout_tree_from_metadata(&measured, &metadata);
675
676 Ok(LayoutMeasurements::new(measured, semantics, layout_tree))
677}
678
679struct LayoutBuilder {
680 state: Rc<RefCell<LayoutBuilderState>>,
681}
682
683impl LayoutBuilder {
684 fn new_with_epoch(
685 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
686 epoch: u64,
687 slots: Rc<RefCell<SlotBackend>>,
688 ) -> Self {
689 Self {
690 state: Rc::new(RefCell::new(LayoutBuilderState::new_with_epoch(
691 applier, epoch, slots,
692 ))),
693 }
694 }
695
696 fn measure_node(
697 &mut self,
698 node_id: NodeId,
699 constraints: Constraints,
700 ) -> Result<Rc<MeasuredNode>, NodeError> {
701 LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
702 }
703
704 fn set_runtime_handle(&mut self, handle: Option<RuntimeHandle>) {
705 self.state.borrow_mut().runtime_handle = handle;
706 }
707}
708
709struct LayoutBuilderState {
710 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
711 runtime_handle: Option<RuntimeHandle>,
712 slots: Rc<RefCell<SlotBackend>>,
715 cache_epoch: u64,
716 tmp_measurables: ScratchVecPool<Box<dyn Measurable>>,
717 tmp_records: ScratchVecPool<(NodeId, ChildRecord)>,
718 tmp_child_ids: ScratchVecPool<NodeId>,
719 tmp_layout_node_data: ScratchVecPool<LayoutModifierNodeData>,
720}
721
722impl LayoutBuilderState {
723 fn new_with_epoch(
724 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
725 epoch: u64,
726 slots: Rc<RefCell<SlotBackend>>,
727 ) -> Self {
728 let runtime_handle = applier.borrow_typed().runtime_handle();
729
730 Self {
731 applier,
732 runtime_handle,
733 slots,
734 cache_epoch: epoch,
735 tmp_measurables: ScratchVecPool::default(),
736 tmp_records: ScratchVecPool::default(),
737 tmp_child_ids: ScratchVecPool::default(),
738 tmp_layout_node_data: ScratchVecPool::default(),
739 }
740 }
741
742 fn try_with_applier_result<R>(
743 state_rc: &Rc<RefCell<Self>>,
744 f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
745 ) -> Option<Result<R, NodeError>> {
746 let host = {
747 let state = state_rc.borrow();
748 Rc::clone(&state.applier)
749 };
750
751 let Ok(mut applier) = host.try_borrow_typed() else {
753 return None;
754 };
755
756 Some(f(&mut applier))
757 }
758
759 fn with_applier_result<R>(
760 state_rc: &Rc<RefCell<Self>>,
761 f: impl FnOnce(&mut MemoryApplier) -> Result<R, NodeError>,
762 ) -> Result<R, NodeError> {
763 Self::try_with_applier_result(state_rc, f).unwrap_or_else(|| {
764 Err(NodeError::MissingContext {
765 id: NodeId::default(),
766 reason: "applier already borrowed",
767 })
768 })
769 }
770
771 fn clear_node_placed(state_rc: &Rc<RefCell<Self>>, node_id: NodeId) {
774 let host = {
775 let state = state_rc.borrow();
776 Rc::clone(&state.applier)
777 };
778 let Ok(mut applier) = host.try_borrow_typed() else {
779 return;
780 };
781 if applier
783 .with_node::<LayoutNode, _>(node_id, |node| {
784 node.clear_placed();
785 })
786 .is_err()
787 {
788 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
789 node.clear_placed();
790 });
791 }
792 }
793
794 fn measure_node(
795 state_rc: Rc<RefCell<Self>>,
796 node_id: NodeId,
797 constraints: Constraints,
798 ) -> Result<Rc<MeasuredNode>, NodeError> {
799 Self::clear_node_placed(&state_rc, node_id);
803
804 if let Some(subcompose) =
806 Self::try_measure_subcompose(Rc::clone(&state_rc), node_id, constraints)?
807 {
808 return Ok(subcompose);
809 }
810
811 if let Some(result) = Self::try_with_applier_result(&state_rc, |applier| {
813 match applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
814 LayoutNodeSnapshot::from_layout_node(layout_node)
815 }) {
816 Ok(snapshot) => Ok(Some(snapshot)),
817 Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => Ok(None),
818 Err(err) => Err(err),
819 }
820 }) {
821 if let Some(snapshot) = result? {
823 return Self::measure_layout_node(
824 Rc::clone(&state_rc),
825 node_id,
826 snapshot,
827 constraints,
828 );
829 }
830 }
831 Ok(Rc::new(MeasuredNode::new(
836 node_id,
837 Size::default(),
838 Point { x: 0.0, y: 0.0 },
839 Point::default(), Vec::new(),
841 )))
842 }
843
844 fn try_measure_subcompose(
845 state_rc: Rc<RefCell<Self>>,
846 node_id: NodeId,
847 constraints: Constraints,
848 ) -> Result<Option<Rc<MeasuredNode>>, NodeError> {
849 let applier_host = {
850 let state = state_rc.borrow();
851 Rc::clone(&state.applier)
852 };
853
854 let (node_handle, resolved_modifiers) = {
855 let Ok(mut applier) = applier_host.try_borrow_typed() else {
857 return Ok(None);
858 };
859 let node = match applier.get_mut(node_id) {
860 Ok(node) => node,
861 Err(NodeError::Missing { .. }) => return Ok(None),
862 Err(err) => return Err(err),
863 };
864 let any = node.as_any_mut();
865 if let Some(subcompose) =
866 any.downcast_mut::<crate::subcompose_layout::SubcomposeLayoutNode>()
867 {
868 let handle = subcompose.handle();
869 let resolved_modifiers = handle.resolved_modifiers();
870 (handle, resolved_modifiers)
871 } else {
872 return Ok(None);
873 }
874 };
875
876 let runtime_handle = {
877 let mut state = state_rc.borrow_mut();
878 if state.runtime_handle.is_none() {
879 if let Ok(applier) = applier_host.try_borrow_typed() {
881 state.runtime_handle = applier.runtime_handle();
882 }
883 }
884 state
885 .runtime_handle
886 .clone()
887 .ok_or(NodeError::MissingContext {
888 id: node_id,
889 reason: "runtime handle required for subcomposition",
890 })?
891 };
892
893 let props = resolved_modifiers.layout_properties();
894 let padding = resolved_modifiers.padding();
895 let offset = resolved_modifiers.offset();
896 let mut inner_constraints = normalize_constraints(subtract_padding(constraints, padding));
897
898 if let DimensionConstraint::Points(width) = props.width() {
899 let constrained_width = width - padding.horizontal_sum();
900 inner_constraints.max_width = inner_constraints.max_width.min(constrained_width);
901 inner_constraints.min_width = inner_constraints.min_width.min(constrained_width);
902 }
903 if let DimensionConstraint::Points(height) = props.height() {
904 let constrained_height = height - padding.vertical_sum();
905 inner_constraints.max_height = inner_constraints.max_height.min(constrained_height);
906 inner_constraints.min_height = inner_constraints.min_height.min(constrained_height);
907 }
908
909 let mut slots_guard = SlotsGuard::take(Rc::clone(&state_rc));
910 let slots_host = slots_guard.host();
911 let applier_host_dyn: Rc<dyn ApplierHost> = applier_host.clone();
912 let observer = SnapshotStateObserver::new(|callback| callback());
913 let composer = Composer::new(
914 Rc::clone(&slots_host),
915 applier_host_dyn,
916 runtime_handle.clone(),
917 observer,
918 Some(node_id),
919 );
920 composer.enter_phase(Phase::Measure);
921
922 let state_rc_clone = Rc::clone(&state_rc);
923 let measure_error: Rc<RefCell<Option<NodeError>>> = Rc::new(RefCell::new(None));
924 let error_for_measurer = Rc::clone(&measure_error);
925 let state_rc_for_subcompose = Rc::clone(&state_rc_clone);
926 let error_for_subcompose = Rc::clone(&error_for_measurer);
927
928 let measure_result = node_handle.measure(
929 &composer,
930 node_id,
931 inner_constraints,
932 Box::new(
933 move |child_id: NodeId, child_constraints: Constraints| -> Size {
934 match Self::measure_node(
935 Rc::clone(&state_rc_for_subcompose),
936 child_id,
937 child_constraints,
938 ) {
939 Ok(measured) => measured.size,
940 Err(err) => {
941 let mut slot = error_for_subcompose.borrow_mut();
942 if slot.is_none() {
943 *slot = Some(err);
944 }
945 Size::default()
946 }
947 }
948 },
949 ),
950 Rc::clone(&measure_error),
951 )?;
952
953 slots_guard.restore(slots_host.take());
954
955 if let Some(err) = measure_error.borrow_mut().take() {
956 return Err(err);
957 }
958
959 let mut width = measure_result.size.width + padding.horizontal_sum();
963 let mut height = measure_result.size.height + padding.vertical_sum();
964
965 width = resolve_dimension(
966 width,
967 props.width(),
968 props.min_width(),
969 props.max_width(),
970 constraints.min_width,
971 constraints.max_width,
972 );
973 height = resolve_dimension(
974 height,
975 props.height(),
976 props.min_height(),
977 props.max_height(),
978 constraints.min_height,
979 constraints.max_height,
980 );
981
982 let mut children = Vec::with_capacity(measure_result.placements.len());
983
984 if let Ok(mut applier) = applier_host.try_borrow_typed() {
986 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |parent_node| {
987 parent_node.set_measured_size(Size { width, height });
988 });
989 }
990
991 for placement in measure_result.placements {
992 let child =
993 Self::measure_node(Rc::clone(&state_rc), placement.node_id, inner_constraints)?;
994 let position = Point {
995 x: padding.left + placement.x,
996 y: padding.top + placement.y,
997 };
998
999 if let Ok(mut applier) = applier_host.try_borrow_typed() {
1003 let _ = applier.with_node::<LayoutNode, _>(placement.node_id, |node| {
1004 node.set_position(position);
1005 });
1006 }
1007
1008 children.push(MeasuredChild {
1009 node: child,
1010 offset: position,
1011 });
1012 }
1013
1014 node_handle.set_active_children(children.iter().map(|c| c.node.node_id));
1016
1017 Ok(Some(Rc::new(MeasuredNode::new(
1018 node_id,
1019 Size { width, height },
1020 offset,
1021 Point::default(), children,
1023 ))))
1024 }
1025 fn measure_through_modifier_chain(
1032 state_rc: &Rc<RefCell<Self>>,
1033 node_id: NodeId,
1034 measurables: &[Box<dyn Measurable>],
1035 measure_policy: &Rc<dyn MeasurePolicy>,
1036 constraints: Constraints,
1037 layout_node_data: &mut Vec<LayoutModifierNodeData>,
1038 ) -> ModifierChainMeasurement {
1039 use cranpose_foundation::NodeCapabilities;
1040
1041 layout_node_data.clear();
1043 let mut offset = Point::default();
1044
1045 {
1046 let state = state_rc.borrow();
1047 let mut applier = state.applier.borrow_typed();
1048
1049 let _ = applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1050 let chain_handle = layout_node.modifier_chain();
1051
1052 if !chain_handle.has_layout_nodes() {
1053 return;
1054 }
1055
1056 chain_handle.chain().for_each_forward_matching(
1058 NodeCapabilities::LAYOUT,
1059 |node_ref| {
1060 if let Some(index) = node_ref.entry_index() {
1061 if let Some(node_rc) = chain_handle.chain().get_node_rc(index) {
1063 layout_node_data.push((index, Rc::clone(&node_rc)));
1064 }
1065
1066 node_ref.with_node(|node| {
1070 if let Some(offset_node) =
1071 node.as_any()
1072 .downcast_ref::<crate::modifier_nodes::OffsetNode>()
1073 {
1074 let delta = offset_node.offset();
1075 offset.x += delta.x;
1076 offset.y += delta.y;
1077 }
1078 });
1079 }
1080 },
1081 );
1082 });
1083 }
1084
1085 if layout_node_data.is_empty() {
1088 let result = measure_policy.measure(measurables, constraints);
1089 let final_size = result.size;
1090 let placements = result.placements;
1091
1092 return ModifierChainMeasurement {
1093 result: MeasureResult {
1094 size: final_size,
1095 placements,
1096 },
1097 content_offset: Point::default(),
1098 offset,
1099 };
1100 }
1101
1102 let shared_context = Rc::new(RefCell::new(LayoutNodeContext::new()));
1107
1108 let policy_result = Rc::new(RefCell::new(None));
1110 let inner_coordinator: Box<dyn NodeCoordinator + '_> =
1111 Box::new(coordinator::InnerCoordinator::new(
1112 Rc::clone(measure_policy),
1113 measurables,
1114 Rc::clone(&policy_result),
1115 ));
1116
1117 let mut current_coordinator = inner_coordinator;
1119 while let Some((_, node_rc)) = layout_node_data.pop() {
1120 current_coordinator = Box::new(coordinator::LayoutModifierCoordinator::new(
1121 node_rc,
1122 current_coordinator,
1123 Rc::clone(&shared_context),
1124 ));
1125 }
1126
1127 let placeable = current_coordinator.measure(constraints);
1129 let final_size = Size {
1130 width: placeable.width(),
1131 height: placeable.height(),
1132 };
1133
1134 let content_offset = placeable.content_offset();
1136 let all_placement_offset = Point {
1137 x: content_offset.0,
1138 y: content_offset.1,
1139 };
1140
1141 let content_offset = Point {
1145 x: all_placement_offset.x - offset.x,
1146 y: all_placement_offset.y - offset.y,
1147 };
1148
1149 let placements = policy_result
1152 .borrow_mut()
1153 .take()
1154 .map(|result| result.placements)
1155 .unwrap_or_default();
1156
1157 let invalidations = shared_context.borrow_mut().take_invalidations();
1159 if !invalidations.is_empty() {
1160 Self::with_applier_result(state_rc, |applier| {
1162 applier.with_node::<LayoutNode, _>(node_id, |layout_node| {
1163 for kind in invalidations {
1164 match kind {
1165 InvalidationKind::Layout => layout_node.mark_needs_measure(),
1166 InvalidationKind::Draw => layout_node.mark_needs_redraw(),
1167 InvalidationKind::Semantics => layout_node.mark_needs_semantics(),
1168 InvalidationKind::PointerInput => layout_node.mark_needs_pointer_pass(),
1169 InvalidationKind::Focus => layout_node.mark_needs_focus_sync(),
1170 }
1171 }
1172 })
1173 })
1174 .ok();
1175 }
1176
1177 ModifierChainMeasurement {
1178 result: MeasureResult {
1179 size: final_size,
1180 placements,
1181 },
1182 content_offset,
1183 offset,
1184 }
1185 }
1186
1187 fn measure_layout_node(
1188 state_rc: Rc<RefCell<Self>>,
1189 node_id: NodeId,
1190 snapshot: LayoutNodeSnapshot,
1191 constraints: Constraints,
1192 ) -> Result<Rc<MeasuredNode>, NodeError> {
1193 let cache_epoch = {
1194 let state = state_rc.borrow();
1195 state.cache_epoch
1196 };
1197 let LayoutNodeSnapshot {
1198 measure_policy,
1199 cache,
1200 needs_measure,
1201 } = snapshot;
1202 cache.activate(cache_epoch);
1203
1204 if needs_measure {
1205 }
1207
1208 if !needs_measure {
1212 if let Some(cached) = cache.get_measurement(constraints) {
1214 Self::with_applier_result(&state_rc, |applier| {
1216 applier.with_node::<LayoutNode, _>(node_id, |node| {
1217 node.clear_needs_measure();
1218 node.clear_needs_layout();
1219 })
1220 })
1221 .ok();
1222 return Ok(cached);
1223 }
1224 }
1225
1226 let (runtime_handle, applier_host) = {
1227 let state = state_rc.borrow();
1228 (state.runtime_handle.clone(), Rc::clone(&state.applier))
1229 };
1230
1231 let measure_handle = LayoutMeasureHandle::new(Rc::clone(&state_rc));
1232 let error = Rc::new(RefCell::new(None));
1233 let mut pools = VecPools::acquire(Rc::clone(&state_rc));
1234 let (measurables, records, child_ids, layout_node_data) = pools.parts();
1235
1236 applier_host
1237 .borrow_typed()
1238 .with_node::<LayoutNode, _>(node_id, |node| {
1239 child_ids.extend_from_slice(&node.children);
1240 })?;
1241
1242 for &child_id in child_ids.iter() {
1243 let measured = Rc::new(RefCell::new(None));
1244 let position = Rc::new(RefCell::new(None));
1245
1246 let data = {
1247 let mut applier = applier_host.borrow_typed();
1248 match applier.with_node::<LayoutNode, _>(child_id, |n| {
1249 (n.cache_handles(), n.layout_state_handle())
1250 }) {
1251 Ok((cache, state)) => Some((cache, Some(state))),
1252 Err(NodeError::TypeMismatch { .. }) => {
1253 Some((LayoutNodeCacheHandles::default(), None))
1254 }
1255 Err(NodeError::Missing { .. }) => None,
1256 Err(err) => return Err(err),
1257 }
1258 };
1259
1260 let Some((cache_handles, layout_state)) = data else {
1261 continue;
1262 };
1263
1264 cache_handles.activate(cache_epoch);
1265
1266 records.push((
1267 child_id,
1268 ChildRecord {
1269 measured: Rc::clone(&measured),
1270 last_position: Rc::clone(&position),
1271 },
1272 ));
1273 measurables.push(Box::new(LayoutChildMeasurable::new(
1274 Rc::clone(&applier_host),
1275 child_id,
1276 measured,
1277 position,
1278 Rc::clone(&error),
1279 runtime_handle.clone(),
1280 cache_handles,
1281 cache_epoch,
1282 Some(measure_handle.clone()),
1283 layout_state,
1284 )));
1285 }
1286
1287 let chain_constraints = constraints;
1288
1289 let modifier_chain_result = Self::measure_through_modifier_chain(
1290 &state_rc,
1291 node_id,
1292 measurables.as_slice(),
1293 &measure_policy,
1294 chain_constraints,
1295 layout_node_data,
1296 );
1297
1298 let (width, height, policy_result, content_offset, offset) = {
1300 let result = modifier_chain_result;
1301 if let Some(err) = error.borrow_mut().take() {
1304 return Err(err);
1305 }
1306
1307 (
1308 result.result.size.width,
1309 result.result.size.height,
1310 result.result,
1311 result.content_offset,
1312 result.offset,
1313 )
1314 };
1315
1316 let mut measured_children = Vec::with_capacity(records.len());
1317 for (child_id, record) in records.iter() {
1318 if let Some(measured) = record.measured.borrow_mut().take() {
1319 let base_position = policy_result
1320 .placements
1321 .iter()
1322 .find(|placement| placement.node_id == *child_id)
1323 .map(|placement| Point {
1324 x: placement.x,
1325 y: placement.y,
1326 })
1327 .or_else(|| record.last_position.borrow().as_ref().copied())
1328 .unwrap_or(Point { x: 0.0, y: 0.0 });
1329 let position = Point {
1331 x: content_offset.x + base_position.x,
1332 y: content_offset.y + base_position.y,
1333 };
1334 measured_children.push(MeasuredChild {
1335 node: measured,
1336 offset: position,
1337 });
1338 }
1339 }
1340
1341 let measured = Rc::new(MeasuredNode::new(
1342 node_id,
1343 Size { width, height },
1344 offset,
1345 content_offset,
1346 measured_children,
1347 ));
1348
1349 cache.store_measurement(constraints, Rc::clone(&measured));
1350
1351 Self::with_applier_result(&state_rc, |applier| {
1353 applier.with_node::<LayoutNode, _>(node_id, |node| {
1354 node.clear_needs_measure();
1355 node.clear_needs_layout();
1356 node.set_measured_size(Size { width, height });
1357 node.set_content_offset(content_offset);
1358 })
1359 })
1360 .ok();
1361
1362 Ok(measured)
1363 }
1364}
1365
1366struct LayoutNodeSnapshot {
1373 measure_policy: Rc<dyn MeasurePolicy>,
1374 cache: LayoutNodeCacheHandles,
1375 needs_measure: bool,
1377}
1378
1379impl LayoutNodeSnapshot {
1380 fn from_layout_node(node: &LayoutNode) -> Self {
1381 Self {
1382 measure_policy: Rc::clone(&node.measure_policy),
1383 cache: node.cache_handles(),
1384 needs_measure: node.needs_measure(),
1385 }
1386 }
1387}
1388
1389struct VecPools {
1391 state: Rc<RefCell<LayoutBuilderState>>,
1392 measurables: Option<Vec<Box<dyn Measurable>>>,
1393 records: Option<Vec<(NodeId, ChildRecord)>>,
1394 child_ids: Option<Vec<NodeId>>,
1395 layout_node_data: Option<Vec<LayoutModifierNodeData>>,
1396}
1397
1398impl VecPools {
1399 fn acquire(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
1400 let (measurables, records, child_ids, layout_node_data) = {
1401 let mut state_mut = state.borrow_mut();
1402 (
1403 state_mut.tmp_measurables.acquire(),
1404 state_mut.tmp_records.acquire(),
1405 state_mut.tmp_child_ids.acquire(),
1406 state_mut.tmp_layout_node_data.acquire(),
1407 )
1408 };
1409 Self {
1410 state,
1411 measurables: Some(measurables),
1412 records: Some(records),
1413 child_ids: Some(child_ids),
1414 layout_node_data: Some(layout_node_data),
1415 }
1416 }
1417
1418 #[allow(clippy::type_complexity)] fn parts(
1420 &mut self,
1421 ) -> (
1422 &mut Vec<Box<dyn Measurable>>,
1423 &mut Vec<(NodeId, ChildRecord)>,
1424 &mut Vec<NodeId>,
1425 &mut Vec<LayoutModifierNodeData>,
1426 ) {
1427 let measurables = self
1428 .measurables
1429 .as_mut()
1430 .expect("measurables already returned");
1431 let records = self.records.as_mut().expect("records already returned");
1432 let child_ids = self.child_ids.as_mut().expect("child_ids already returned");
1433 let layout_node_data = self
1434 .layout_node_data
1435 .as_mut()
1436 .expect("layout_node_data already returned");
1437 (measurables, records, child_ids, layout_node_data)
1438 }
1439}
1440
1441impl Drop for VecPools {
1442 fn drop(&mut self) {
1443 let mut state = self.state.borrow_mut();
1444 if let Some(measurables) = self.measurables.take() {
1445 state.tmp_measurables.release(measurables);
1446 }
1447 if let Some(records) = self.records.take() {
1448 state.tmp_records.release(records);
1449 }
1450 if let Some(child_ids) = self.child_ids.take() {
1451 state.tmp_child_ids.release(child_ids);
1452 }
1453 if let Some(layout_node_data) = self.layout_node_data.take() {
1454 state.tmp_layout_node_data.release(layout_node_data);
1455 }
1456 }
1457}
1458
1459struct SlotsGuard {
1460 state: Rc<RefCell<LayoutBuilderState>>,
1461 slots: Option<SlotBackend>,
1462}
1463
1464impl SlotsGuard {
1465 fn take(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
1466 let slots = {
1467 let state_ref = state.borrow();
1468 let mut slots_ref = state_ref.slots.borrow_mut();
1469 std::mem::take(&mut *slots_ref)
1470 };
1471 Self {
1472 state,
1473 slots: Some(slots),
1474 }
1475 }
1476
1477 fn host(&mut self) -> Rc<SlotsHost> {
1478 let slots = self.slots.take().unwrap_or_default();
1479 Rc::new(SlotsHost::new(slots))
1480 }
1481
1482 fn restore(&mut self, slots: SlotBackend) {
1483 debug_assert!(self.slots.is_none());
1484 self.slots = Some(slots);
1485 }
1486}
1487
1488impl Drop for SlotsGuard {
1489 fn drop(&mut self) {
1490 if let Some(slots) = self.slots.take() {
1491 let state_ref = self.state.borrow();
1492 *state_ref.slots.borrow_mut() = slots;
1493 }
1494 }
1495}
1496
1497#[derive(Clone)]
1498struct LayoutMeasureHandle {
1499 state: Rc<RefCell<LayoutBuilderState>>,
1500}
1501
1502impl LayoutMeasureHandle {
1503 fn new(state: Rc<RefCell<LayoutBuilderState>>) -> Self {
1504 Self { state }
1505 }
1506
1507 fn measure(
1508 &self,
1509 node_id: NodeId,
1510 constraints: Constraints,
1511 ) -> Result<Rc<MeasuredNode>, NodeError> {
1512 LayoutBuilderState::measure_node(Rc::clone(&self.state), node_id, constraints)
1513 }
1514}
1515
1516#[derive(Debug, Clone)]
1517pub(crate) struct MeasuredNode {
1518 node_id: NodeId,
1519 size: Size,
1520 offset: Point,
1522 content_offset: Point,
1524 children: Vec<MeasuredChild>,
1525}
1526
1527impl MeasuredNode {
1528 fn new(
1529 node_id: NodeId,
1530 size: Size,
1531 offset: Point,
1532 content_offset: Point,
1533 children: Vec<MeasuredChild>,
1534 ) -> Self {
1535 Self {
1536 node_id,
1537 size,
1538 offset,
1539 content_offset,
1540 children,
1541 }
1542 }
1543}
1544
1545#[derive(Debug, Clone)]
1546struct MeasuredChild {
1547 node: Rc<MeasuredNode>,
1548 offset: Point,
1549}
1550
1551struct ChildRecord {
1552 measured: Rc<RefCell<Option<Rc<MeasuredNode>>>>,
1553 last_position: Rc<RefCell<Option<Point>>>,
1554}
1555
1556struct LayoutChildMeasurable {
1557 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1558 node_id: NodeId,
1559 measured: Rc<RefCell<Option<Rc<MeasuredNode>>>>,
1560 last_position: Rc<RefCell<Option<Point>>>,
1561 error: Rc<RefCell<Option<NodeError>>>,
1562 runtime_handle: Option<RuntimeHandle>,
1563 cache: LayoutNodeCacheHandles,
1564 cache_epoch: u64,
1565 measure_handle: Option<LayoutMeasureHandle>,
1566 layout_state: Option<Rc<RefCell<crate::widgets::nodes::layout_node::LayoutState>>>,
1567}
1568
1569impl LayoutChildMeasurable {
1570 #[allow(clippy::too_many_arguments)] fn new(
1572 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1573 node_id: NodeId,
1574 measured: Rc<RefCell<Option<Rc<MeasuredNode>>>>,
1575 last_position: Rc<RefCell<Option<Point>>>,
1576 error: Rc<RefCell<Option<NodeError>>>,
1577 runtime_handle: Option<RuntimeHandle>,
1578 cache: LayoutNodeCacheHandles,
1579 cache_epoch: u64,
1580 measure_handle: Option<LayoutMeasureHandle>,
1581 layout_state: Option<Rc<RefCell<crate::widgets::nodes::layout_node::LayoutState>>>,
1582 ) -> Self {
1583 cache.activate(cache_epoch);
1584 Self {
1585 applier,
1586 node_id,
1587 measured,
1588 last_position,
1589 error,
1590 runtime_handle,
1591 cache,
1592 cache_epoch,
1593 measure_handle,
1594 layout_state,
1595 }
1596 }
1597
1598 fn record_error(&self, err: NodeError) {
1599 let mut slot = self.error.borrow_mut();
1600 if slot.is_none() {
1601 *slot = Some(err);
1602 }
1603 }
1604
1605 fn perform_measure(&self, constraints: Constraints) -> Result<Rc<MeasuredNode>, NodeError> {
1606 if let Some(handle) = &self.measure_handle {
1607 handle.measure(self.node_id, constraints)
1608 } else {
1609 measure_node_with_host(
1610 Rc::clone(&self.applier),
1611 self.runtime_handle.clone(),
1612 self.node_id,
1613 constraints,
1614 self.cache_epoch,
1615 )
1616 }
1617 }
1618
1619 fn intrinsic_measure(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
1620 self.cache.activate(self.cache_epoch);
1621 if let Some(cached) = self.cache.get_measurement(constraints) {
1622 return Some(cached);
1623 }
1624
1625 match self.perform_measure(constraints) {
1626 Ok(measured) => {
1627 self.cache
1628 .store_measurement(constraints, Rc::clone(&measured));
1629 Some(measured)
1630 }
1631 Err(err) => {
1632 self.record_error(err);
1633 None
1634 }
1635 }
1636 }
1637}
1638
1639impl Measurable for LayoutChildMeasurable {
1640 fn measure(&self, constraints: Constraints) -> Placeable {
1641 self.cache.activate(self.cache_epoch);
1642 let measured_size;
1643 if let Some(cached) = self.cache.get_measurement(constraints) {
1644 measured_size = cached.size;
1645 *self.measured.borrow_mut() = Some(Rc::clone(&cached));
1646 } else {
1647 match self.perform_measure(constraints) {
1648 Ok(measured) => {
1649 measured_size = measured.size;
1650 self.cache
1651 .store_measurement(constraints, Rc::clone(&measured));
1652 *self.measured.borrow_mut() = Some(measured);
1653 }
1654 Err(err) => {
1655 self.record_error(err);
1656 self.measured.borrow_mut().take();
1657 measured_size = Size {
1658 width: 0.0,
1659 height: 0.0,
1660 };
1661 }
1662 }
1663 }
1664
1665 if let Some(state) = &self.layout_state {
1668 let mut state = state.borrow_mut();
1669 state.size = measured_size;
1670 state.measurement_constraints = constraints;
1671 } else if let Ok(mut applier) = self.applier.try_borrow_typed() {
1672 let _ = applier.with_node::<LayoutNode, _>(self.node_id, |node| {
1673 node.set_measured_size(measured_size);
1674 node.set_measurement_constraints(constraints);
1675 });
1676 }
1677
1678 let applier = Rc::clone(&self.applier);
1680 let node_id = self.node_id;
1681 let measured = Rc::clone(&self.measured);
1682 let last_position = Rc::clone(&self.last_position);
1683 let layout_state = self.layout_state.clone();
1684
1685 let place_fn = Rc::new(move |x: f32, y: f32| {
1686 let internal_offset = measured
1688 .borrow()
1689 .as_ref()
1690 .map(|m| m.offset)
1691 .unwrap_or_default();
1692
1693 let position = Point {
1694 x: x + internal_offset.x,
1695 y: y + internal_offset.y,
1696 };
1697 *last_position.borrow_mut() = Some(position);
1698
1699 if let Some(state) = &layout_state {
1701 let mut state = state.borrow_mut();
1702 state.position = position;
1703 state.is_placed = true;
1704 } else if let Ok(mut applier) = applier.try_borrow_typed() {
1705 if applier
1706 .with_node::<LayoutNode, _>(node_id, |node| {
1707 node.set_position(position);
1708 })
1709 .is_err()
1710 {
1711 let _ = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1712 node.set_position(position);
1713 });
1714 }
1715 }
1716 });
1717
1718 Placeable::with_place_fn(
1719 measured_size.width,
1720 measured_size.height,
1721 self.node_id,
1722 place_fn,
1723 )
1724 }
1725
1726 fn min_intrinsic_width(&self, height: f32) -> f32 {
1727 let kind = IntrinsicKind::MinWidth(height);
1728 self.cache.activate(self.cache_epoch);
1729 if let Some(value) = self.cache.get_intrinsic(&kind) {
1730 return value;
1731 }
1732 let constraints = Constraints {
1733 min_width: 0.0,
1734 max_width: f32::INFINITY,
1735 min_height: height,
1736 max_height: height,
1737 };
1738 if let Some(node) = self.intrinsic_measure(constraints) {
1739 let value = node.size.width;
1740 self.cache.store_intrinsic(kind, value);
1741 value
1742 } else {
1743 0.0
1744 }
1745 }
1746
1747 fn max_intrinsic_width(&self, height: f32) -> f32 {
1748 let kind = IntrinsicKind::MaxWidth(height);
1749 self.cache.activate(self.cache_epoch);
1750 if let Some(value) = self.cache.get_intrinsic(&kind) {
1751 return value;
1752 }
1753 let constraints = Constraints {
1754 min_width: 0.0,
1755 max_width: f32::INFINITY,
1756 min_height: 0.0,
1757 max_height: height,
1758 };
1759 if let Some(node) = self.intrinsic_measure(constraints) {
1760 let value = node.size.width;
1761 self.cache.store_intrinsic(kind, value);
1762 value
1763 } else {
1764 0.0
1765 }
1766 }
1767
1768 fn min_intrinsic_height(&self, width: f32) -> f32 {
1769 let kind = IntrinsicKind::MinHeight(width);
1770 self.cache.activate(self.cache_epoch);
1771 if let Some(value) = self.cache.get_intrinsic(&kind) {
1772 return value;
1773 }
1774 let constraints = Constraints {
1775 min_width: width,
1776 max_width: width,
1777 min_height: 0.0,
1778 max_height: f32::INFINITY,
1779 };
1780 if let Some(node) = self.intrinsic_measure(constraints) {
1781 let value = node.size.height;
1782 self.cache.store_intrinsic(kind, value);
1783 value
1784 } else {
1785 0.0
1786 }
1787 }
1788
1789 fn max_intrinsic_height(&self, width: f32) -> f32 {
1790 let kind = IntrinsicKind::MaxHeight(width);
1791 self.cache.activate(self.cache_epoch);
1792 if let Some(value) = self.cache.get_intrinsic(&kind) {
1793 return value;
1794 }
1795 let constraints = Constraints {
1796 min_width: 0.0,
1797 max_width: width,
1798 min_height: 0.0,
1799 max_height: f32::INFINITY,
1800 };
1801 if let Some(node) = self.intrinsic_measure(constraints) {
1802 let value = node.size.height;
1803 self.cache.store_intrinsic(kind, value);
1804 value
1805 } else {
1806 0.0
1807 }
1808 }
1809
1810 fn flex_parent_data(&self) -> Option<cranpose_ui_layout::FlexParentData> {
1811 let Ok(mut applier) = self.applier.try_borrow_typed() else {
1814 return None;
1815 };
1816
1817 applier
1818 .with_node::<LayoutNode, _>(self.node_id, |layout_node| {
1819 let props = layout_node.resolved_modifiers().layout_properties();
1820 props.weight().map(|weight_data| {
1821 cranpose_ui_layout::FlexParentData::new(weight_data.weight, weight_data.fill)
1822 })
1823 })
1824 .ok()
1825 .flatten()
1826 }
1827}
1828
1829fn measure_node_with_host(
1830 applier: Rc<ConcreteApplierHost<MemoryApplier>>,
1831 runtime_handle: Option<RuntimeHandle>,
1832 node_id: NodeId,
1833 constraints: Constraints,
1834 epoch: u64,
1835) -> Result<Rc<MeasuredNode>, NodeError> {
1836 let runtime_handle = match runtime_handle {
1837 Some(handle) => Some(handle),
1838 None => applier.borrow_typed().runtime_handle(),
1839 };
1840 let mut builder = LayoutBuilder::new_with_epoch(
1841 applier,
1842 epoch,
1843 Rc::new(RefCell::new(SlotBackend::default())),
1844 );
1845 builder.set_runtime_handle(runtime_handle);
1846 builder.measure_node(node_id, constraints)
1847}
1848
1849#[derive(Clone)]
1850struct RuntimeNodeMetadata {
1851 modifier: Modifier,
1852 resolved_modifiers: ResolvedModifiers,
1853 modifier_slices: Rc<ModifierNodeSlices>,
1854 role: SemanticsRole,
1855 button_handler: Option<Rc<RefCell<dyn FnMut()>>>,
1856}
1857
1858impl Default for RuntimeNodeMetadata {
1859 fn default() -> Self {
1860 Self {
1861 modifier: Modifier::empty(),
1862 resolved_modifiers: ResolvedModifiers::default(),
1863 modifier_slices: Rc::default(),
1864 role: SemanticsRole::Unknown,
1865 button_handler: None,
1866 }
1867 }
1868}
1869
1870fn collect_runtime_metadata(
1871 applier: &mut MemoryApplier,
1872 node: &MeasuredNode,
1873) -> Result<HashMap<NodeId, RuntimeNodeMetadata>, NodeError> {
1874 let mut map = HashMap::default();
1875 collect_runtime_metadata_inner(applier, node, &mut map)?;
1876 Ok(map)
1877}
1878
1879fn collect_semantics_with_owner(
1881 applier: &mut MemoryApplier,
1882 node: &MeasuredNode,
1883 owner: &SemanticsOwner,
1884) -> Result<(), NodeError> {
1885 owner.get_or_compute(node.node_id, applier);
1887
1888 for child in &node.children {
1890 collect_semantics_with_owner(applier, &child.node, owner)?;
1891 }
1892 Ok(())
1893}
1894
1895fn collect_semantics_snapshot(
1896 applier: &mut MemoryApplier,
1897 node: &MeasuredNode,
1898) -> Result<HashMap<NodeId, Option<SemanticsConfiguration>>, NodeError> {
1899 let owner = SemanticsOwner::new();
1900 collect_semantics_with_owner(applier, node, &owner)?;
1901
1902 let mut map = HashMap::default();
1904 extract_configurations_recursive(node, &owner, &mut map);
1905 Ok(map)
1906}
1907
1908fn extract_configurations_recursive(
1909 node: &MeasuredNode,
1910 owner: &SemanticsOwner,
1911 map: &mut HashMap<NodeId, Option<SemanticsConfiguration>>,
1912) {
1913 if let Some(config) = owner.configurations.borrow().get(&node.node_id) {
1914 map.insert(node.node_id, config.clone());
1915 }
1916 for child in &node.children {
1917 extract_configurations_recursive(&child.node, owner, map);
1918 }
1919}
1920
1921fn collect_runtime_metadata_inner(
1922 applier: &mut MemoryApplier,
1923 node: &MeasuredNode,
1924 map: &mut HashMap<NodeId, RuntimeNodeMetadata>,
1925) -> Result<(), NodeError> {
1926 if let Entry::Vacant(entry) = map.entry(node.node_id) {
1927 let meta = runtime_metadata_for(applier, node.node_id)?;
1928 entry.insert(meta);
1929 }
1930 for child in &node.children {
1931 collect_runtime_metadata_inner(applier, &child.node, map)?;
1932 }
1933 Ok(())
1934}
1935
1936fn role_from_modifier_slices(modifier_slices: &ModifierNodeSlices) -> SemanticsRole {
1937 modifier_slices
1938 .text_content()
1939 .map(|text| SemanticsRole::Text {
1940 value: text.to_string(),
1941 })
1942 .unwrap_or(SemanticsRole::Layout)
1943}
1944
1945fn runtime_metadata_for(
1946 applier: &mut MemoryApplier,
1947 node_id: NodeId,
1948) -> Result<RuntimeNodeMetadata, NodeError> {
1949 if let Ok(meta) = applier.with_node::<LayoutNode, _>(node_id, |layout| {
1954 let modifier = layout.modifier.clone();
1955 let resolved_modifiers = layout.resolved_modifiers();
1956 let modifier_slices = layout.modifier_slices_snapshot();
1957 let role = role_from_modifier_slices(&modifier_slices);
1958
1959 RuntimeNodeMetadata {
1960 modifier,
1961 resolved_modifiers,
1962 modifier_slices,
1963 role,
1964 button_handler: None,
1965 }
1966 }) {
1967 return Ok(meta);
1968 }
1969
1970 if let Ok((modifier, resolved_modifiers, modifier_slices)) = applier
1972 .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
1973 (
1974 node.modifier(),
1975 node.resolved_modifiers(),
1976 node.modifier_slices_snapshot(),
1977 )
1978 })
1979 {
1980 return Ok(RuntimeNodeMetadata {
1981 modifier,
1982 resolved_modifiers,
1983 modifier_slices,
1984 role: SemanticsRole::Subcompose,
1985 button_handler: None,
1986 });
1987 }
1988 Ok(RuntimeNodeMetadata::default())
1989}
1990
1991fn compute_semantics_for_node(
1995 applier: &mut MemoryApplier,
1996 node_id: NodeId,
1997) -> Option<SemanticsConfiguration> {
1998 match applier.with_node::<LayoutNode, _>(node_id, |layout| {
2000 let config = layout.semantics_configuration();
2001 layout.clear_needs_semantics();
2002 config
2003 }) {
2004 Ok(config) => return config,
2005 Err(NodeError::TypeMismatch { .. }) | Err(NodeError::Missing { .. }) => {}
2006 Err(_) => return None,
2007 }
2008
2009 if let Ok(modifier) =
2011 applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| node.modifier())
2012 {
2013 return collect_semantics_from_modifier(&modifier);
2014 }
2015
2016 None
2017}
2018
2019fn build_semantics_node(
2023 node: &MeasuredNode,
2024 metadata: &HashMap<NodeId, RuntimeNodeMetadata>,
2025 semantics: &HashMap<NodeId, Option<SemanticsConfiguration>>,
2026) -> SemanticsNode {
2027 let info = metadata.get(&node.node_id).cloned().unwrap_or_default();
2028
2029 let mut role = info.role.clone();
2031 let mut actions = Vec::new();
2032 let mut description = None;
2033
2034 if let Some(config) = semantics.get(&node.node_id).cloned().flatten() {
2036 if config.is_button {
2038 role = SemanticsRole::Button;
2039 }
2040
2041 if config.is_clickable {
2043 actions.push(SemanticsAction::Click {
2044 handler: SemanticsCallback::new(node.node_id),
2045 });
2046 }
2047
2048 if let Some(desc) = config.content_description {
2050 description = Some(desc);
2051 }
2052 }
2053
2054 let children = node
2055 .children
2056 .iter()
2057 .map(|child| build_semantics_node(&child.node, metadata, semantics))
2058 .collect();
2059
2060 SemanticsNode::new(node.node_id, role, actions, children, description)
2061}
2062
2063fn build_layout_tree_from_metadata(
2064 node: &MeasuredNode,
2065 metadata: &HashMap<NodeId, RuntimeNodeMetadata>,
2066) -> LayoutTree {
2067 fn place(
2068 node: &MeasuredNode,
2069 origin: Point,
2070 metadata: &HashMap<NodeId, RuntimeNodeMetadata>,
2071 ) -> LayoutBox {
2072 let top_left = Point {
2074 x: origin.x + node.offset.x,
2075 y: origin.y + node.offset.y,
2076 };
2077 let rect = GeometryRect {
2078 x: top_left.x,
2079 y: top_left.y,
2080 width: node.size.width,
2081 height: node.size.height,
2082 };
2083 let info = metadata.get(&node.node_id).cloned().unwrap_or_default();
2084 let kind = layout_kind_from_metadata(node.node_id, &info);
2085 let data = LayoutNodeData::new(
2086 info.modifier.clone(),
2087 info.resolved_modifiers,
2088 info.modifier_slices.clone(),
2089 kind,
2090 );
2091 let children = node
2092 .children
2093 .iter()
2094 .map(|child| {
2095 let child_origin = Point {
2096 x: top_left.x + child.offset.x,
2097 y: top_left.y + child.offset.y,
2098 };
2099 place(&child.node, child_origin, metadata)
2100 })
2101 .collect();
2102 LayoutBox::new(node.node_id, rect, node.content_offset, data, children)
2103 }
2104
2105 LayoutTree::new(place(node, Point { x: 0.0, y: 0.0 }, metadata))
2106}
2107
2108fn layout_kind_from_metadata(_node_id: NodeId, info: &RuntimeNodeMetadata) -> LayoutNodeKind {
2109 match &info.role {
2110 SemanticsRole::Layout => LayoutNodeKind::Layout,
2111 SemanticsRole::Subcompose => LayoutNodeKind::Subcompose,
2112 SemanticsRole::Text { .. } => {
2113 LayoutNodeKind::Layout
2117 }
2118 SemanticsRole::Spacer => LayoutNodeKind::Spacer,
2119 SemanticsRole::Button => {
2120 let handler = info
2121 .button_handler
2122 .as_ref()
2123 .cloned()
2124 .unwrap_or_else(|| Rc::new(RefCell::new(|| {})));
2125 LayoutNodeKind::Button { on_click: handler }
2126 }
2127 SemanticsRole::Unknown => LayoutNodeKind::Unknown,
2128 }
2129}
2130
2131fn subtract_padding(constraints: Constraints, padding: EdgeInsets) -> Constraints {
2132 let horizontal = padding.horizontal_sum();
2133 let vertical = padding.vertical_sum();
2134 let min_width = (constraints.min_width - horizontal).max(0.0);
2135 let mut max_width = constraints.max_width;
2136 if max_width.is_finite() {
2137 max_width = (max_width - horizontal).max(0.0);
2138 }
2139 let min_height = (constraints.min_height - vertical).max(0.0);
2140 let mut max_height = constraints.max_height;
2141 if max_height.is_finite() {
2142 max_height = (max_height - vertical).max(0.0);
2143 }
2144 normalize_constraints(Constraints {
2145 min_width,
2146 max_width,
2147 min_height,
2148 max_height,
2149 })
2150}
2151
2152#[cfg(test)]
2153pub(crate) fn align_horizontal(alignment: HorizontalAlignment, available: f32, child: f32) -> f32 {
2154 match alignment {
2155 HorizontalAlignment::Start => 0.0,
2156 HorizontalAlignment::CenterHorizontally => ((available - child) / 2.0).max(0.0),
2157 HorizontalAlignment::End => (available - child).max(0.0),
2158 }
2159}
2160
2161#[cfg(test)]
2162pub(crate) fn align_vertical(alignment: VerticalAlignment, available: f32, child: f32) -> f32 {
2163 match alignment {
2164 VerticalAlignment::Top => 0.0,
2165 VerticalAlignment::CenterVertically => ((available - child) / 2.0).max(0.0),
2166 VerticalAlignment::Bottom => (available - child).max(0.0),
2167 }
2168}
2169
2170fn resolve_dimension(
2171 base: f32,
2172 explicit: DimensionConstraint,
2173 min_override: Option<f32>,
2174 max_override: Option<f32>,
2175 min_limit: f32,
2176 max_limit: f32,
2177) -> f32 {
2178 let mut min_bound = min_limit;
2179 if let Some(min_value) = min_override {
2180 min_bound = min_bound.max(min_value);
2181 }
2182
2183 let mut max_bound = if max_limit.is_finite() {
2184 max_limit
2185 } else {
2186 max_override.unwrap_or(max_limit)
2187 };
2188 if let Some(max_value) = max_override {
2189 if max_bound.is_finite() {
2190 max_bound = max_bound.min(max_value);
2191 } else {
2192 max_bound = max_value;
2193 }
2194 }
2195 if max_bound < min_bound {
2196 max_bound = min_bound;
2197 }
2198
2199 let mut size = match explicit {
2200 DimensionConstraint::Points(points) => points,
2201 DimensionConstraint::Fraction(fraction) => {
2202 if max_limit.is_finite() {
2203 max_limit * fraction.clamp(0.0, 1.0)
2204 } else {
2205 base
2206 }
2207 }
2208 DimensionConstraint::Unspecified => base,
2209 DimensionConstraint::Intrinsic(_) => base,
2212 };
2213
2214 size = clamp_dimension(size, min_bound, max_bound);
2215 size = clamp_dimension(size, min_limit, max_limit);
2216 size.max(0.0)
2217}
2218
2219fn clamp_dimension(value: f32, min: f32, max: f32) -> f32 {
2220 let mut result = value.max(min);
2221 if max.is_finite() {
2222 result = result.min(max);
2223 }
2224 result
2225}
2226
2227fn normalize_constraints(mut constraints: Constraints) -> Constraints {
2228 if constraints.max_width < constraints.min_width {
2229 constraints.max_width = constraints.min_width;
2230 }
2231 if constraints.max_height < constraints.min_height {
2232 constraints.max_height = constraints.min_height;
2233 }
2234 constraints
2235}
2236
2237#[cfg(test)]
2238#[path = "tests/layout_tests.rs"]
2239mod tests;