1use crate::{
2 layout::MeasuredNode,
3 modifier::{
4 Modifier, ModifierChainHandle, ModifierLocalSource, ModifierLocalToken,
5 ModifierLocalsHandle, ModifierNodeSlices, Point, ResolvedModifierLocal, ResolvedModifiers,
6 Size,
7 },
8};
9use cranpose_core::{Node, NodeId};
10use cranpose_foundation::{
11 InvalidationKind, ModifierInvalidation, NodeCapabilities, SemanticsConfiguration,
12};
13use cranpose_ui_layout::{Constraints, MeasurePolicy};
14use std::any::TypeId;
15use std::cell::{Cell, RefCell};
16use std::collections::HashMap;
17use std::hash::{Hash, Hasher};
18use std::rc::Rc;
19
20#[derive(Clone, Debug)]
25pub struct LayoutState {
26 pub size: Size,
28 pub position: Point,
30 pub is_placed: bool,
32 pub measurement_constraints: Constraints,
34 pub content_offset: Point,
36}
37
38impl Default for LayoutState {
39 fn default() -> Self {
40 Self {
41 size: Size::default(),
42 position: Point::default(),
43 is_placed: false,
44 measurement_constraints: Constraints {
45 min_width: 0.0,
46 max_width: f32::INFINITY,
47 min_height: 0.0,
48 max_height: f32::INFINITY,
49 },
50 content_offset: Point::default(),
51 }
52 }
53}
54
55#[derive(Clone)]
56struct MeasurementCacheEntry {
57 constraints: Constraints,
58 measured: Rc<MeasuredNode>,
59}
60
61#[derive(Clone, Copy, Debug)]
62pub enum IntrinsicKind {
63 MinWidth(f32),
64 MaxWidth(f32),
65 MinHeight(f32),
66 MaxHeight(f32),
67}
68
69impl IntrinsicKind {
70 fn discriminant(&self) -> u8 {
71 match self {
72 IntrinsicKind::MinWidth(_) => 0,
73 IntrinsicKind::MaxWidth(_) => 1,
74 IntrinsicKind::MinHeight(_) => 2,
75 IntrinsicKind::MaxHeight(_) => 3,
76 }
77 }
78
79 fn value_bits(&self) -> u32 {
80 match self {
81 IntrinsicKind::MinWidth(value)
82 | IntrinsicKind::MaxWidth(value)
83 | IntrinsicKind::MinHeight(value)
84 | IntrinsicKind::MaxHeight(value) => value.to_bits(),
85 }
86 }
87}
88
89impl PartialEq for IntrinsicKind {
90 fn eq(&self, other: &Self) -> bool {
91 self.discriminant() == other.discriminant() && self.value_bits() == other.value_bits()
92 }
93}
94
95impl Eq for IntrinsicKind {}
96
97impl Hash for IntrinsicKind {
98 fn hash<H: Hasher>(&self, state: &mut H) {
99 self.discriminant().hash(state);
100 self.value_bits().hash(state);
101 }
102}
103
104#[derive(Default)]
105struct NodeCacheState {
106 epoch: u64,
107 measurements: Vec<MeasurementCacheEntry>,
108 intrinsics: Vec<(IntrinsicKind, f32)>,
109}
110
111#[derive(Clone, Default)]
112pub(crate) struct LayoutNodeCacheHandles {
113 state: Rc<RefCell<NodeCacheState>>,
114}
115
116impl LayoutNodeCacheHandles {
117 pub(crate) fn clear(&self) {
118 let mut state = self.state.borrow_mut();
119 state.measurements.clear();
120 state.intrinsics.clear();
121 state.epoch = 0;
122 }
123
124 pub(crate) fn activate(&self, epoch: u64) {
125 let mut state = self.state.borrow_mut();
126 if state.epoch != epoch {
127 state.measurements.clear();
128 state.intrinsics.clear();
129 state.epoch = epoch;
130 }
131 }
132
133 pub(crate) fn epoch(&self) -> u64 {
134 self.state.borrow().epoch
135 }
136
137 pub(crate) fn get_measurement(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
138 let state = self.state.borrow();
139 state
140 .measurements
141 .iter()
142 .find(|entry| entry.constraints == constraints)
143 .map(|entry| Rc::clone(&entry.measured))
144 }
145
146 pub(crate) fn store_measurement(&self, constraints: Constraints, measured: Rc<MeasuredNode>) {
147 let mut state = self.state.borrow_mut();
148 if let Some(entry) = state
149 .measurements
150 .iter_mut()
151 .find(|entry| entry.constraints == constraints)
152 {
153 entry.measured = measured;
154 } else {
155 state.measurements.push(MeasurementCacheEntry {
156 constraints,
157 measured,
158 });
159 }
160 }
161
162 pub(crate) fn get_intrinsic(&self, kind: &IntrinsicKind) -> Option<f32> {
163 let state = self.state.borrow();
164 state
165 .intrinsics
166 .iter()
167 .find(|(stored_kind, _)| stored_kind == kind)
168 .map(|(_, value)| *value)
169 }
170
171 pub(crate) fn store_intrinsic(&self, kind: IntrinsicKind, value: f32) {
172 let mut state = self.state.borrow_mut();
173 if let Some((_, existing)) = state
174 .intrinsics
175 .iter_mut()
176 .find(|(stored_kind, _)| stored_kind == &kind)
177 {
178 *existing = value;
179 } else {
180 state.intrinsics.push((kind, value));
181 }
182 }
183}
184
185pub struct LayoutNode {
186 pub modifier: Modifier,
187 modifier_chain: ModifierChainHandle,
188 resolved_modifiers: ResolvedModifiers,
189 modifier_capabilities: NodeCapabilities,
190 modifier_child_capabilities: NodeCapabilities,
191 pub measure_policy: Rc<dyn MeasurePolicy>,
192 pub children: Vec<NodeId>,
194 cache: LayoutNodeCacheHandles,
195 needs_measure: Cell<bool>,
197 needs_layout: Cell<bool>,
198 needs_semantics: Cell<bool>,
199 needs_redraw: Cell<bool>,
200 needs_pointer_pass: Cell<bool>,
201 needs_focus_sync: Cell<bool>,
202 parent: Cell<Option<NodeId>>,
204 folded_parent: Cell<Option<NodeId>>,
206 id: Cell<Option<NodeId>>,
208 debug_modifiers: Cell<bool>,
209 is_virtual: bool,
212 virtual_children_count: Cell<usize>,
214
215 modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
216 modifier_slices_dirty: Cell<bool>,
217
218 layout_state: Rc<RefCell<LayoutState>>,
222}
223
224pub(crate) const RECYCLED_LAYOUT_NODE_POOL_LIMIT: usize = 128;
225
226thread_local! {
227 static EMPTY_MEASURE_POLICY: Rc<dyn MeasurePolicy> =
228 Rc::new(crate::layout::policies::EmptyMeasurePolicy);
229}
230
231fn empty_measure_policy() -> Rc<dyn MeasurePolicy> {
232 EMPTY_MEASURE_POLICY.with(Rc::clone)
233}
234
235impl LayoutNode {
236 pub fn new(modifier: Modifier, measure_policy: Rc<dyn MeasurePolicy>) -> Self {
237 Self::new_with_virtual(modifier, measure_policy, false)
238 }
239
240 pub fn new_virtual() -> Self {
243 Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), true)
244 }
245
246 fn new_recycled_shell(is_virtual: bool) -> Self {
247 let mut shell =
248 Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), is_virtual);
249 shell.needs_measure.set(false);
250 shell.needs_layout.set(false);
251 shell.needs_semantics.set(false);
252 shell.needs_redraw.set(false);
253 shell.needs_pointer_pass.set(false);
254 shell.needs_focus_sync.set(false);
255 shell.parent.set(None);
256 shell.folded_parent.set(None);
257 shell.id.set(None);
258 shell.debug_modifiers.set(false);
259 shell.virtual_children_count.set(0);
260 shell.cache = LayoutNodeCacheHandles::default();
261 shell.modifier_slices_snapshot = RefCell::new(Rc::default());
262 shell.modifier_slices_dirty = Cell::new(true);
263 shell.layout_state = Rc::new(RefCell::new(LayoutState::default()));
264 shell
265 }
266
267 fn new_with_virtual(
268 modifier: Modifier,
269 measure_policy: Rc<dyn MeasurePolicy>,
270 is_virtual: bool,
271 ) -> Self {
272 let mut node = Self {
273 modifier,
274 modifier_chain: ModifierChainHandle::new(),
275 resolved_modifiers: ResolvedModifiers::default(),
276 modifier_capabilities: NodeCapabilities::default(),
277 modifier_child_capabilities: NodeCapabilities::default(),
278 measure_policy,
279 children: Vec::new(),
280 cache: LayoutNodeCacheHandles::default(),
281 needs_measure: Cell::new(true), needs_layout: Cell::new(true), needs_semantics: Cell::new(true), needs_redraw: Cell::new(true), needs_pointer_pass: Cell::new(false),
286 needs_focus_sync: Cell::new(false),
287 parent: Cell::new(None), folded_parent: Cell::new(None), id: Cell::new(None), debug_modifiers: Cell::new(false),
291 is_virtual,
292 virtual_children_count: Cell::new(0),
293 modifier_slices_snapshot: RefCell::new(Rc::default()),
294 modifier_slices_dirty: Cell::new(true),
295 layout_state: Rc::new(RefCell::new(LayoutState::default())),
296 };
297 node.sync_modifier_chain();
298 node
299 }
300
301 pub fn set_modifier(&mut self, modifier: Modifier) {
302 let modifier_changed = !self.modifier.structural_eq(&modifier);
308 self.modifier = modifier;
309 self.sync_modifier_chain();
310 if modifier_changed {
311 self.cache.clear();
312 self.request_semantics_update();
313 }
314 }
315
316 fn sync_modifier_chain(&mut self) {
317 let prev_caps = self.modifier_capabilities;
318 let start_parent = self.parent();
319 let mut resolver = move |token: ModifierLocalToken| {
320 resolve_modifier_local_from_parent_chain(start_parent, token)
321 };
322 self.modifier_chain
323 .set_debug_logging(self.debug_modifiers.get());
324 self.modifier_chain.set_node_id(self.id.get());
325 let modifier_local_invalidations = self
326 .modifier_chain
327 .update_with_resolver(&self.modifier, &mut resolver);
328 self.resolved_modifiers = self.modifier_chain.resolved_modifiers();
329 self.modifier_capabilities = self.modifier_chain.capabilities();
330 self.modifier_child_capabilities = self.modifier_chain.aggregate_child_capabilities();
331
332 self.update_modifier_slices_cache();
333
334 let mut invalidations = self.modifier_chain.take_invalidations();
335 invalidations.extend(modifier_local_invalidations);
336 self.dispatch_modifier_invalidations_with_prev(&invalidations, prev_caps);
337 self.refresh_registry_state();
338 }
339
340 fn update_modifier_slices_cache(&self) {
341 use crate::modifier::collect_modifier_slices_into;
342
343 let mut snapshot = self.modifier_slices_snapshot.borrow_mut();
344 collect_modifier_slices_into(self.modifier_chain.chain(), Rc::make_mut(&mut snapshot));
345 self.modifier_slices_dirty.set(false);
346 }
347
348 #[cfg(test)]
349 fn dispatch_modifier_invalidations(&self, invalidations: &[ModifierInvalidation]) {
350 self.dispatch_modifier_invalidations_with_prev(invalidations, NodeCapabilities::empty());
351 }
352
353 fn dispatch_modifier_invalidations_with_prev(
354 &self,
355 invalidations: &[ModifierInvalidation],
356 prev_caps: NodeCapabilities,
357 ) {
358 let curr_caps = self.modifier_capabilities;
359 for invalidation in invalidations {
360 self.modifier_slices_dirty.set(true);
361 match invalidation.kind() {
362 InvalidationKind::Layout => {
363 if curr_caps.contains(NodeCapabilities::LAYOUT)
364 || prev_caps.contains(NodeCapabilities::LAYOUT)
365 {
366 self.mark_needs_measure();
367 if let Some(id) = self.id.get() {
368 let inside_composition =
369 cranpose_core::composer_context::try_with_composer(|_| ())
370 .is_some();
371 if !inside_composition {
372 crate::schedule_layout_repass(id);
373 }
374 }
375 }
376 }
377 InvalidationKind::Draw => {
378 if curr_caps.contains(NodeCapabilities::DRAW)
379 || prev_caps.contains(NodeCapabilities::DRAW)
380 {
381 self.mark_needs_redraw();
382 }
383 }
384 InvalidationKind::PointerInput => {
385 if curr_caps.contains(NodeCapabilities::POINTER_INPUT)
386 || prev_caps.contains(NodeCapabilities::POINTER_INPUT)
387 {
388 self.mark_needs_pointer_pass();
389 crate::request_pointer_invalidation();
390 if let Some(id) = self.id.get() {
392 crate::schedule_pointer_repass(id);
393 }
394 }
395 }
396 InvalidationKind::Semantics => {
397 self.request_semantics_update();
398 }
399 InvalidationKind::Focus => {
400 if curr_caps.contains(NodeCapabilities::FOCUS)
401 || prev_caps.contains(NodeCapabilities::FOCUS)
402 {
403 self.mark_needs_focus_sync();
404 crate::request_focus_invalidation();
405 if let Some(id) = self.id.get() {
407 crate::schedule_focus_invalidation(id);
408 }
409 }
410 }
411 }
412 }
413 }
414
415 pub fn set_measure_policy(&mut self, policy: Rc<dyn MeasurePolicy>) {
416 if !Rc::ptr_eq(&self.measure_policy, &policy) {
418 self.measure_policy = policy;
419 self.cache.clear();
420 self.mark_needs_measure();
421 if let Some(id) = self.id.get() {
422 cranpose_core::bubble_measure_dirty_in_composer(id);
423 }
424 }
425 }
426
427 pub fn mark_needs_measure(&self) {
429 self.needs_measure.set(true);
430 self.needs_layout.set(true);
431 }
432
433 pub fn mark_needs_layout(&self) {
435 self.needs_layout.set(true);
436 }
437
438 pub fn mark_needs_redraw(&self) {
440 self.needs_redraw.set(true);
441 if let Some(id) = self.id.get() {
442 crate::schedule_draw_repass(id);
443 }
444 crate::request_render_invalidation();
445 }
446
447 pub fn needs_measure(&self) -> bool {
449 self.needs_measure.get()
450 }
451
452 pub fn needs_layout(&self) -> bool {
454 self.needs_layout.get()
455 }
456
457 pub fn mark_needs_semantics(&self) {
459 self.needs_semantics.set(true);
460 }
461
462 pub(crate) fn clear_needs_semantics(&self) {
464 self.needs_semantics.set(false);
465 }
466
467 pub fn needs_semantics(&self) -> bool {
469 self.needs_semantics.get()
470 }
471
472 pub fn needs_redraw(&self) -> bool {
474 self.needs_redraw.get()
475 }
476
477 pub fn clear_needs_redraw(&self) {
478 self.needs_redraw.set(false);
479 }
480
481 fn request_semantics_update(&self) {
482 let already_dirty = self.needs_semantics.replace(true);
483 if already_dirty {
484 return;
485 }
486
487 if let Some(id) = self.id.get() {
488 cranpose_core::queue_semantics_invalidation(id);
489 }
490 }
491
492 pub(crate) fn clear_needs_measure(&self) {
494 self.needs_measure.set(false);
495 }
496
497 pub(crate) fn clear_needs_layout(&self) {
499 self.needs_layout.set(false);
500 }
501
502 pub fn mark_needs_pointer_pass(&self) {
504 self.needs_pointer_pass.set(true);
505 }
506
507 pub fn needs_pointer_pass(&self) -> bool {
509 self.needs_pointer_pass.get()
510 }
511
512 pub fn clear_needs_pointer_pass(&self) {
514 self.needs_pointer_pass.set(false);
515 }
516
517 pub fn mark_needs_focus_sync(&self) {
519 self.needs_focus_sync.set(true);
520 }
521
522 pub fn needs_focus_sync(&self) -> bool {
524 self.needs_focus_sync.get()
525 }
526
527 pub fn clear_needs_focus_sync(&self) {
529 self.needs_focus_sync.set(false);
530 }
531
532 pub fn set_node_id(&mut self, id: NodeId) {
534 if let Some(existing) = self.id.replace(Some(id)) {
535 unregister_layout_node(existing);
536 }
537 register_layout_node(id, self);
538 self.refresh_registry_state();
539
540 self.modifier_chain.set_node_id(Some(id));
543 }
544
545 pub fn node_id(&self) -> Option<NodeId> {
547 self.id.get()
548 }
549
550 pub fn set_parent(&self, parent: NodeId) {
553 self.folded_parent.set(Some(parent));
554 self.parent.set(Some(parent));
557 self.refresh_registry_state();
558 }
559
560 pub fn clear_parent(&self) {
562 self.folded_parent.set(None);
563 self.parent.set(None);
564 self.refresh_registry_state();
565 }
566
567 pub fn parent(&self) -> Option<NodeId> {
569 self.parent.get()
570 }
571
572 pub fn folded_parent(&self) -> Option<NodeId> {
574 self.folded_parent.get()
575 }
576
577 pub fn is_virtual(&self) -> bool {
579 self.is_virtual
580 }
581
582 pub(crate) fn cache_handles(&self) -> LayoutNodeCacheHandles {
583 self.cache.clone()
584 }
585
586 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
587 self.resolved_modifiers
588 }
589
590 pub fn modifier_capabilities(&self) -> NodeCapabilities {
591 self.modifier_capabilities
592 }
593
594 pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
595 self.modifier_child_capabilities
596 }
597
598 pub fn set_debug_modifiers(&mut self, enabled: bool) {
599 self.debug_modifiers.set(enabled);
600 self.modifier_chain.set_debug_logging(enabled);
601 }
602
603 pub fn debug_modifiers_enabled(&self) -> bool {
604 self.debug_modifiers.get()
605 }
606
607 pub fn modifier_locals_handle(&self) -> ModifierLocalsHandle {
608 self.modifier_chain.modifier_locals_handle()
609 }
610
611 pub fn has_layout_modifier_nodes(&self) -> bool {
612 self.modifier_capabilities
613 .contains(NodeCapabilities::LAYOUT)
614 }
615
616 pub fn has_draw_modifier_nodes(&self) -> bool {
617 self.modifier_capabilities.contains(NodeCapabilities::DRAW)
618 }
619
620 pub fn has_pointer_input_modifier_nodes(&self) -> bool {
621 self.modifier_capabilities
622 .contains(NodeCapabilities::POINTER_INPUT)
623 }
624
625 pub fn has_semantics_modifier_nodes(&self) -> bool {
626 self.modifier_capabilities
627 .contains(NodeCapabilities::SEMANTICS)
628 }
629
630 pub fn has_focus_modifier_nodes(&self) -> bool {
631 self.modifier_capabilities.contains(NodeCapabilities::FOCUS)
632 }
633
634 fn refresh_registry_state(&self) {
635 if let Some(id) = self.id.get() {
636 let parent = self.parent();
637 let capabilities = self.modifier_child_capabilities();
638 let modifier_locals = self.modifier_locals_handle();
639 LAYOUT_NODE_REGISTRY.with(|registry| {
640 if let Some(entry) = registry.borrow_mut().get_mut(&id) {
641 entry.parent = parent;
642 entry.modifier_child_capabilities = capabilities;
643 entry.modifier_locals = modifier_locals;
644 }
645 });
646 }
647 }
648
649 pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
650 if self.modifier_slices_dirty.get() {
651 self.update_modifier_slices_cache();
652 }
653 self.modifier_slices_snapshot.borrow().clone()
654 }
655
656 pub fn layout_state(&self) -> LayoutState {
662 self.layout_state.borrow().clone()
663 }
664
665 pub fn measured_size(&self) -> Size {
667 self.layout_state.borrow().size
668 }
669
670 pub fn position(&self) -> Point {
672 self.layout_state.borrow().position
673 }
674
675 pub fn is_placed(&self) -> bool {
677 self.layout_state.borrow().is_placed
678 }
679
680 pub fn set_measured_size(&self, size: Size) {
682 let mut state = self.layout_state.borrow_mut();
683 state.size = size;
684 }
685
686 pub fn set_position(&self, position: Point) {
688 let mut state = self.layout_state.borrow_mut();
689 state.position = position;
690 state.is_placed = true;
691 }
692
693 pub fn set_measurement_constraints(&self, constraints: Constraints) {
695 self.layout_state.borrow_mut().measurement_constraints = constraints;
696 }
697
698 pub fn set_content_offset(&self, offset: Point) {
700 self.layout_state.borrow_mut().content_offset = offset;
701 }
702
703 pub fn clear_placed(&self) {
705 self.layout_state.borrow_mut().is_placed = false;
706 }
707
708 pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
709 crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
710 }
711
712 pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
714 &self.modifier_chain
715 }
716
717 pub fn with_text_field_modifier_mut<R>(
722 &mut self,
723 f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
724 ) -> Option<R> {
725 self.modifier_chain.with_text_field_modifier_mut(f)
726 }
727
728 pub fn layout_state_handle(&self) -> Rc<RefCell<LayoutState>> {
731 self.layout_state.clone()
732 }
733}
734impl Clone for LayoutNode {
735 fn clone(&self) -> Self {
736 let mut node = Self {
737 modifier: self.modifier.clone(),
738 modifier_chain: ModifierChainHandle::new(),
739 resolved_modifiers: ResolvedModifiers::default(),
740 modifier_capabilities: self.modifier_capabilities,
741 modifier_child_capabilities: self.modifier_child_capabilities,
742 measure_policy: self.measure_policy.clone(),
743 children: self.children.clone(),
744 cache: self.cache.clone(),
745 needs_measure: Cell::new(self.needs_measure.get()),
746 needs_layout: Cell::new(self.needs_layout.get()),
747 needs_semantics: Cell::new(self.needs_semantics.get()),
748 needs_redraw: Cell::new(self.needs_redraw.get()),
749 needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
750 needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
751 parent: Cell::new(self.parent.get()),
752 folded_parent: Cell::new(self.folded_parent.get()),
753 id: Cell::new(None),
754 debug_modifiers: Cell::new(self.debug_modifiers.get()),
755 is_virtual: self.is_virtual,
756 virtual_children_count: Cell::new(self.virtual_children_count.get()),
757 modifier_slices_snapshot: RefCell::new(Rc::default()),
758 modifier_slices_dirty: Cell::new(true),
759 layout_state: self.layout_state.clone(),
761 };
762 node.sync_modifier_chain();
763 node
764 }
765}
766
767impl Node for LayoutNode {
768 fn mount(&mut self) {
769 let (chain, mut context) = self.modifier_chain.chain_and_context_mut();
770 chain.repair_chain();
771 chain.attach_nodes(&mut *context);
772 }
773
774 fn unmount(&mut self) {
775 self.modifier_chain.chain_mut().detach_nodes();
776 }
777
778 fn set_node_id(&mut self, id: NodeId) {
779 LayoutNode::set_node_id(self, id);
781 }
782
783 fn insert_child(&mut self, child: NodeId) {
784 if self.children.contains(&child) {
785 return;
786 }
787 if is_virtual_node(child) {
788 let count = self.virtual_children_count.get();
789 self.virtual_children_count.set(count + 1);
790 }
791 self.children.push(child);
792 self.cache.clear();
793 self.mark_needs_measure();
794 }
795
796 fn remove_child(&mut self, child: NodeId) {
797 let before = self.children.len();
798 self.children.retain(|&id| id != child);
799 if self.children.len() < before {
800 if is_virtual_node(child) {
801 let count = self.virtual_children_count.get();
802 if count > 0 {
803 self.virtual_children_count.set(count - 1);
804 }
805 }
806 self.cache.clear();
807 self.mark_needs_measure();
808 }
809 }
810
811 fn move_child(&mut self, from: usize, to: usize) {
812 if from == to || from >= self.children.len() {
813 return;
814 }
815 let child = self.children.remove(from);
816 let target = to.min(self.children.len());
817 self.children.insert(target, child);
818 self.cache.clear();
819 self.mark_needs_measure();
820 }
821
822 fn update_children(&mut self, children: &[NodeId]) {
823 self.children.clear();
824 self.children.extend_from_slice(children);
825 self.cache.clear();
826 self.mark_needs_measure();
827 }
828
829 fn children(&self) -> Vec<NodeId> {
830 self.children.clone()
831 }
832
833 fn collect_children_into(&self, out: &mut smallvec::SmallVec<[NodeId; 8]>) {
834 out.clear();
835 out.extend(self.children.iter().copied());
836 }
837
838 fn on_attached_to_parent(&mut self, parent: NodeId) {
839 self.set_parent(parent);
840 }
841
842 fn on_removed_from_parent(&mut self) {
843 self.clear_parent();
844 }
845
846 fn parent(&self) -> Option<NodeId> {
847 self.parent.get()
848 }
849
850 fn mark_needs_layout(&self) {
851 self.needs_layout.set(true);
852 }
853
854 fn needs_layout(&self) -> bool {
855 self.needs_layout.get()
856 }
857
858 fn mark_needs_measure(&self) {
859 self.needs_measure.set(true);
860 self.needs_layout.set(true);
861 }
862
863 fn needs_measure(&self) -> bool {
864 self.needs_measure.get()
865 }
866
867 fn mark_needs_semantics(&self) {
868 self.needs_semantics.set(true);
869 }
870
871 fn needs_semantics(&self) -> bool {
872 self.needs_semantics.get()
873 }
874
875 fn set_parent_for_bubbling(&mut self, parent: NodeId) {
880 self.parent.set(Some(parent));
881 }
882
883 fn recycle_key(&self) -> Option<TypeId> {
884 Some(TypeId::of::<Self>())
885 }
886
887 fn recycle_pool_limit(&self) -> Option<usize> {
888 Some(RECYCLED_LAYOUT_NODE_POOL_LIMIT)
889 }
890
891 fn prepare_for_recycle(&mut self) {
892 *self = Self::new_recycled_shell(self.is_virtual);
893 }
894
895 fn rehouse_for_recycle(&self) -> Option<Box<dyn cranpose_core::Node>> {
896 Some(Box::new(Self::new_recycled_shell(self.is_virtual)))
897 }
898
899 fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn cranpose_core::Node>> {
900 let mut previous = std::mem::replace(self, Self::new_recycled_shell(self.is_virtual));
901 let node_id = previous.id.replace(None);
902 let parent = previous.parent.get();
903 let folded_parent = previous.folded_parent.get();
904 let debug_modifiers = previous.debug_modifiers.get();
905 let needs_measure = previous.needs_measure.get();
906 let needs_layout = previous.needs_layout.get();
907 let needs_semantics = previous.needs_semantics.get();
908 let needs_redraw = previous.needs_redraw.get();
909 let needs_pointer_pass = previous.needs_pointer_pass.get();
910 let needs_focus_sync = previous.needs_focus_sync.get();
911 let virtual_children_count = previous.virtual_children_count.get();
912 let children = previous.children.to_vec();
913 let modifier = previous.modifier.rehouse_for_live_compaction();
914 let measure_policy = previous.measure_policy.clone();
915 let layout_state = previous.layout_state.clone();
916
917 previous.modifier_chain.chain_mut().detach_nodes();
918
919 let mut compact = Self::new_with_virtual(modifier, measure_policy, previous.is_virtual);
920 compact.children = children;
921 compact.parent.set(parent);
922 compact.folded_parent.set(folded_parent);
923 compact.id.set(node_id);
924 compact.debug_modifiers.set(debug_modifiers);
925 compact.needs_measure.set(needs_measure);
926 compact.needs_layout.set(needs_layout);
927 compact.needs_semantics.set(needs_semantics);
928 compact.needs_redraw.set(needs_redraw);
929 compact.needs_pointer_pass.set(needs_pointer_pass);
930 compact.needs_focus_sync.set(needs_focus_sync);
931 compact.virtual_children_count.set(virtual_children_count);
932 compact.layout_state = layout_state;
933 compact.sync_modifier_chain();
934 if let Some(id) = node_id {
935 register_layout_node(id, &compact);
936 }
937
938 Some(Box::new(compact))
939 }
940}
941
942impl Drop for LayoutNode {
943 fn drop(&mut self) {
944 if let Some(id) = self.id.get() {
945 unregister_layout_node(id);
946 }
947 }
948}
949
950thread_local! {
951 static LAYOUT_NODE_REGISTRY: RefCell<HashMap<NodeId, LayoutNodeRegistryEntry>> =
952 RefCell::new(HashMap::new());
953 static VIRTUAL_NODE_ID_COUNTER: std::sync::atomic::AtomicUsize = const { std::sync::atomic::AtomicUsize::new(0xC0000000) };
957}
958
959const MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY: usize = 128;
960
961#[cfg(test)]
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
963struct LayoutNodeRegistryDebugStats {
964 len: usize,
965 capacity: usize,
966}
967
968struct LayoutNodeRegistryEntry {
969 parent: Option<NodeId>,
970 modifier_child_capabilities: NodeCapabilities,
971 modifier_locals: ModifierLocalsHandle,
972 is_virtual: bool,
973}
974
975pub(crate) fn register_layout_node(id: NodeId, node: &LayoutNode) {
976 LAYOUT_NODE_REGISTRY.with(|registry| {
977 registry.borrow_mut().insert(
978 id,
979 LayoutNodeRegistryEntry {
980 parent: node.parent(),
981 modifier_child_capabilities: node.modifier_child_capabilities(),
982 modifier_locals: node.modifier_locals_handle(),
983 is_virtual: node.is_virtual(),
984 },
985 );
986 });
987}
988
989pub(crate) fn unregister_layout_node(id: NodeId) {
990 LAYOUT_NODE_REGISTRY.with(|registry| {
991 let mut registry = registry.borrow_mut();
992 registry.remove(&id);
993 let should_shrink = (registry.len() <= MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
994 && registry.capacity() > MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
995 || registry.capacity()
996 > registry
997 .len()
998 .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
999 .saturating_mul(4);
1000 if should_shrink {
1001 let retained = registry
1002 .len()
1003 .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY);
1004 let mut rebuilt = HashMap::new();
1005 rebuilt.reserve(retained);
1006 rebuilt.extend(registry.drain());
1007 *registry = rebuilt;
1008 }
1009 });
1010}
1011
1012#[cfg(test)]
1013fn layout_node_registry_stats() -> LayoutNodeRegistryDebugStats {
1014 LAYOUT_NODE_REGISTRY.with(|registry| {
1015 let registry = registry.borrow();
1016 LayoutNodeRegistryDebugStats {
1017 len: registry.len(),
1018 capacity: registry.capacity(),
1019 }
1020 })
1021}
1022
1023pub(crate) fn is_virtual_node(id: NodeId) -> bool {
1024 LAYOUT_NODE_REGISTRY.with(|registry| {
1025 registry
1026 .borrow()
1027 .get(&id)
1028 .map(|entry| entry.is_virtual)
1029 .unwrap_or(false)
1030 })
1031}
1032
1033pub(crate) fn allocate_virtual_node_id() -> NodeId {
1034 use std::sync::atomic::Ordering;
1035 VIRTUAL_NODE_ID_COUNTER.with(|counter| counter.fetch_add(1, Ordering::Relaxed))
1038}
1039
1040fn resolve_modifier_local_from_parent_chain(
1041 start: Option<NodeId>,
1042 token: ModifierLocalToken,
1043) -> Option<ResolvedModifierLocal> {
1044 let mut current = start;
1045 while let Some(parent_id) = current {
1046 let (next_parent, resolved) = LAYOUT_NODE_REGISTRY.with(|registry| {
1047 let registry = registry.borrow();
1048 if let Some(entry) = registry.get(&parent_id) {
1049 let resolved = if entry
1050 .modifier_child_capabilities
1051 .contains(NodeCapabilities::MODIFIER_LOCALS)
1052 {
1053 entry
1054 .modifier_locals
1055 .borrow()
1056 .resolve(token)
1057 .map(|value| value.with_source(ModifierLocalSource::Ancestor))
1058 } else {
1059 None
1060 };
1061 (entry.parent, resolved)
1062 } else {
1063 (None, None)
1064 }
1065 });
1066 if let Some(value) = resolved {
1067 return Some(value);
1068 }
1069 current = next_parent;
1070 }
1071 None
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076 use super::*;
1077 use cranpose_ui_graphics::Size as GeometrySize;
1078 use cranpose_ui_layout::{Measurable, MeasureResult};
1079 use std::rc::Rc;
1080
1081 #[derive(Default)]
1082 struct TestMeasurePolicy;
1083
1084 impl MeasurePolicy for TestMeasurePolicy {
1085 fn measure(
1086 &self,
1087 _measurables: &[Box<dyn Measurable>],
1088 _constraints: Constraints,
1089 ) -> MeasureResult {
1090 MeasureResult::new(
1091 GeometrySize {
1092 width: 0.0,
1093 height: 0.0,
1094 },
1095 Vec::new(),
1096 )
1097 }
1098
1099 fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
1100 0.0
1101 }
1102
1103 fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
1104 0.0
1105 }
1106
1107 fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
1108 0.0
1109 }
1110
1111 fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
1112 0.0
1113 }
1114 }
1115
1116 fn fresh_node() -> LayoutNode {
1117 LayoutNode::new(Modifier::empty(), Rc::new(TestMeasurePolicy))
1118 }
1119
1120 #[test]
1121 fn modifier_slices_cache_reuses_unique_snapshot_allocation() {
1122 let mut node = fresh_node();
1123 let snapshot = node.modifier_slices_snapshot();
1124 let snapshot_ptr = Rc::as_ptr(&snapshot);
1125 drop(snapshot);
1126
1127 node.set_modifier(Modifier::empty().padding(4.0));
1128
1129 let updated = node.modifier_slices_snapshot();
1130 assert_eq!(Rc::as_ptr(&updated), snapshot_ptr);
1131 }
1132
1133 #[test]
1134 fn modifier_slices_cache_preserves_live_snapshot_isolation() {
1135 let mut node = fresh_node();
1136 let old_snapshot = node.modifier_slices_snapshot();
1137 let old_snapshot_ptr = Rc::as_ptr(&old_snapshot);
1138
1139 node.set_modifier(Modifier::empty().padding(4.0));
1140
1141 let updated = node.modifier_slices_snapshot();
1142 assert_ne!(Rc::as_ptr(&updated), old_snapshot_ptr);
1143 assert_eq!(old_snapshot.draw_commands().len(), 0);
1144 }
1145
1146 #[test]
1147 fn layout_node_registry_retains_warm_capacity_after_large_cleanup() {
1148 let nodes: Vec<_> = (0..2048)
1149 .map(|_| {
1150 let id = allocate_virtual_node_id();
1151 let node = fresh_node();
1152 register_layout_node(id, &node);
1153 (id, node)
1154 })
1155 .collect();
1156
1157 for (id, _) in &nodes {
1158 unregister_layout_node(*id);
1159 }
1160
1161 let stats = layout_node_registry_stats();
1162 assert_eq!(stats.len, 0);
1163 assert!(
1164 (MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
1165 ..=MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY.saturating_mul(2))
1166 .contains(&stats.capacity),
1167 "registry warm capacity {} fell outside expected retained range {}..={}",
1168 stats.capacity,
1169 MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY,
1170 MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY.saturating_mul(2),
1171 );
1172 }
1173
1174 fn invalidation(kind: InvalidationKind) -> ModifierInvalidation {
1175 ModifierInvalidation::new(kind, NodeCapabilities::for_invalidation(kind))
1176 }
1177
1178 #[test]
1179 fn layout_invalidation_requires_layout_capability() {
1180 let mut node = fresh_node();
1181 node.clear_needs_measure();
1182 node.clear_needs_layout();
1183 node.modifier_capabilities = NodeCapabilities::DRAW;
1184 node.modifier_child_capabilities = node.modifier_capabilities;
1185
1186 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1187
1188 assert!(!node.needs_measure());
1189 assert!(!node.needs_layout());
1190 }
1191
1192 #[test]
1193 fn semantics_configuration_reflects_modifier_state() {
1194 let mut node = fresh_node();
1195 node.set_modifier(Modifier::empty().semantics(|config| {
1196 config.content_description = Some("greeting".into());
1197 config.is_clickable = true;
1198 }));
1199
1200 let config = node
1201 .semantics_configuration()
1202 .expect("expected semantics configuration");
1203 assert_eq!(config.content_description.as_deref(), Some("greeting"));
1204 assert!(config.is_clickable);
1205 }
1206
1207 #[test]
1208 fn layout_invalidation_marks_flags_when_capability_present() {
1209 let _guard = crate::render_state::render_state_test_guard();
1210 crate::reset_render_state_for_tests();
1211 let mut node = fresh_node();
1212 node.id.set(Some(11));
1213 node.clear_needs_measure();
1214 node.clear_needs_layout();
1215 node.modifier_capabilities = NodeCapabilities::LAYOUT;
1216 node.modifier_child_capabilities = node.modifier_capabilities;
1217
1218 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1219
1220 assert!(node.needs_measure());
1221 assert!(node.needs_layout());
1222 assert_eq!(crate::take_layout_repass_nodes(), vec![11]);
1223 assert!(crate::take_layout_invalidation());
1224 }
1225
1226 #[test]
1227 fn layout_invalidation_skips_repass_while_composing() {
1228 let _guard = crate::render_state::render_state_test_guard();
1229 crate::reset_render_state_for_tests();
1230
1231 let node = Rc::new(RefCell::new(fresh_node()));
1232 {
1233 let mut node = node.borrow_mut();
1234 node.id.set(Some(17));
1235 node.clear_needs_measure();
1236 node.clear_needs_layout();
1237 node.modifier_capabilities = NodeCapabilities::LAYOUT;
1238 node.modifier_child_capabilities = node.modifier_capabilities;
1239 }
1240
1241 let node_for_composition = Rc::clone(&node);
1242 let _composition = crate::run_test_composition(move || {
1243 node_for_composition
1244 .borrow()
1245 .dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1246 });
1247
1248 let node = node.borrow();
1249 assert!(node.needs_measure());
1250 assert!(node.needs_layout());
1251 assert!(crate::take_layout_repass_nodes().is_empty());
1252 assert!(!crate::take_layout_invalidation());
1253 }
1254
1255 #[test]
1256 fn draw_invalidation_marks_redraw_flag_when_capable() {
1257 let mut node = fresh_node();
1258 node.clear_needs_measure();
1259 node.clear_needs_layout();
1260 node.modifier_capabilities = NodeCapabilities::DRAW;
1261 node.modifier_child_capabilities = node.modifier_capabilities;
1262
1263 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Draw)]);
1264
1265 assert!(node.needs_redraw());
1266 assert!(!node.needs_layout());
1267 }
1268
1269 #[test]
1270 fn semantics_invalidation_sets_semantics_flag_only() {
1271 let mut node = fresh_node();
1272 node.clear_needs_measure();
1273 node.clear_needs_layout();
1274 node.clear_needs_semantics();
1275 node.modifier_capabilities = NodeCapabilities::SEMANTICS;
1276 node.modifier_child_capabilities = node.modifier_capabilities;
1277
1278 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Semantics)]);
1279
1280 assert!(node.needs_semantics());
1281 assert!(!node.needs_measure());
1282 assert!(!node.needs_layout());
1283 }
1284
1285 #[test]
1286 fn pointer_invalidation_requires_pointer_capability() {
1287 let mut node = fresh_node();
1288 node.clear_needs_pointer_pass();
1289 node.modifier_capabilities = NodeCapabilities::DRAW;
1290 node.modifier_child_capabilities = node.modifier_capabilities;
1291 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1296
1297 assert!(!node.needs_pointer_pass());
1298 }
1299
1300 #[test]
1301 fn pointer_invalidation_marks_flag_and_requests_queue() {
1302 let mut node = fresh_node();
1303 node.clear_needs_pointer_pass();
1304 node.modifier_capabilities = NodeCapabilities::POINTER_INPUT;
1305 node.modifier_child_capabilities = node.modifier_capabilities;
1306 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1311
1312 assert!(node.needs_pointer_pass());
1313 }
1314
1315 #[test]
1316 fn focus_invalidation_requires_focus_capability() {
1317 let mut node = fresh_node();
1318 node.clear_needs_focus_sync();
1319 node.modifier_capabilities = NodeCapabilities::DRAW;
1320 node.modifier_child_capabilities = node.modifier_capabilities;
1321 crate::take_focus_invalidation();
1322
1323 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1324
1325 assert!(!node.needs_focus_sync());
1326 assert!(!crate::take_focus_invalidation());
1327 }
1328
1329 #[test]
1330 fn focus_invalidation_marks_flag_and_requests_queue() {
1331 let mut node = fresh_node();
1332 node.clear_needs_focus_sync();
1333 node.modifier_capabilities = NodeCapabilities::FOCUS;
1334 node.modifier_child_capabilities = node.modifier_capabilities;
1335 crate::take_focus_invalidation();
1336
1337 node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1338
1339 assert!(node.needs_focus_sync());
1340 assert!(crate::take_focus_invalidation());
1341 }
1342
1343 #[test]
1344 fn set_modifier_marks_semantics_dirty() {
1345 let mut node = fresh_node();
1346 node.clear_needs_semantics();
1347 node.set_modifier(Modifier::empty().semantics(|config| {
1348 config.is_clickable = true;
1349 }));
1350
1351 assert!(node.needs_semantics());
1352 }
1353
1354 #[test]
1355 fn modifier_child_capabilities_reflect_chain_head() {
1356 let mut node = fresh_node();
1357 node.set_modifier(Modifier::empty().padding(4.0));
1358 assert!(
1359 node.modifier_child_capabilities()
1360 .contains(NodeCapabilities::LAYOUT),
1361 "padding should introduce layout capability"
1362 );
1363 }
1364}