1use std::{
2 cell::{Cell, Ref, RefCell, RefMut},
3 collections::HashMap,
4 rc::Rc,
5};
6
7use cranpose_core::{
8 Composer, NodeError, NodeId, Phase, SlotId, SlotTable, SlotsHost, SubcomposeState,
9};
10use cranpose_foundation::{InvalidationKind, ModifierInvalidation, NodeCapabilities};
11pub use cranpose_ui_layout::{Constraints, MeasureResult, Placement};
12use smallvec::SmallVec;
13use web_time::Instant;
14
15use crate::{
16 layout::MeasuredNode,
17 modifier::{
18 Modifier, ModifierChainHandle, ModifierNodeSlices, Point, ResolvedModifiers, Size,
19 collect_modifier_slices_into,
20 },
21 widgets::nodes::{
22 LayoutNode, LayoutNodeCacheHandles, LayoutState, allocate_virtual_node_id, is_virtual_node,
23 register_layout_node,
24 },
25};
26
27fn subcompose_telemetry_enabled() -> bool {
28 cranpose_core::env_flag!("CRANPOSE_SUBCOMPOSE_TELEMETRY")
29}
30
31#[derive(Clone, Copy, Debug)]
32pub struct SubcomposeChild {
33 node_id: NodeId,
34 measured_size: Option<Size>,
35}
36
37impl SubcomposeChild {
38 pub fn new(node_id: NodeId) -> Self {
39 Self {
40 node_id,
41 measured_size: None,
42 }
43 }
44
45 pub fn with_size(node_id: NodeId, size: Size) -> Self {
46 Self {
47 node_id,
48 measured_size: Some(size),
49 }
50 }
51
52 pub fn node_id(&self) -> NodeId {
53 self.node_id
54 }
55
56 pub fn size(&self) -> Size {
57 self.measured_size.unwrap_or(Size {
58 width: 0.0,
59 height: 0.0,
60 })
61 }
62
63 pub fn width(&self) -> f32 {
64 self.size().width
65 }
66
67 pub fn height(&self) -> f32 {
68 self.size().height
69 }
70
71 pub fn set_size(&mut self, size: Size) {
72 self.measured_size = Some(size);
73 }
74}
75
76impl PartialEq for SubcomposeChild {
77 fn eq(&self, other: &Self) -> bool {
78 self.node_id == other.node_id
79 }
80}
81
82pub type SubcomposePlaceable = cranpose_ui_layout::Placeable;
83
84type CachedMeasureBatchRegistrar<'a> =
85 Box<dyn FnMut(&[NodeId], Constraints, &mut Vec<Option<Size>>) + 'a>;
86type RetainedMeasureLookup<'a> = Box<dyn FnMut(NodeId) -> Option<Rc<MeasuredNode>> + 'a>;
87type RetainedMeasureRegistrar<'a> = Box<dyn FnMut(&[Rc<MeasuredNode>]) + 'a>;
88
89pub(crate) struct CachedBatchMeasureInputs<'a> {
90 pub(crate) measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
91 pub(crate) cached_measure_batch_registrar: CachedMeasureBatchRegistrar<'a>,
92 pub(crate) retained_measure_lookup: RetainedMeasureLookup<'a>,
93 pub(crate) retained_measure_registrar: RetainedMeasureRegistrar<'a>,
94 pub(crate) error: &'a RefCell<Option<NodeError>>,
95}
96
97pub trait SubcomposeLayoutScope: cranpose_ui_layout::MeasureScope {
99 fn constraints(&self) -> Constraints;
100
101 fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
102 where
103 I: IntoIterator<Item = Placement>,
104 {
105 MeasureResult::new(Size { width, height }, placements.into_iter().collect())
106 }
107}
108
109pub trait SubcomposeMeasureScope: SubcomposeLayoutScope {
111 fn subcompose<K, Content>(
126 &mut self,
127 slot_id: SlotId,
128 key: K,
129 content: Content,
130 ) -> Vec<SubcomposeChild>
131 where
132 K: PartialEq + 'static,
133 Content: FnMut() + 'static;
134
135 fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable;
137
138 fn node_has_no_parent(&self, node_id: NodeId) -> bool;
141}
142
143pub struct SubcomposeMeasureScopeImpl<'a> {
145 composer: Composer,
146 density_scope: crate::density::DensityMeasureScope,
147 state: &'a mut SubcomposeState,
148 constraints: Constraints,
149 measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
150 cached_measure_batch_registrar: CachedMeasureBatchRegistrar<'a>,
151 retained_measure_lookup: RetainedMeasureLookup<'a>,
152 retained_measure_registrar: RetainedMeasureRegistrar<'a>,
153 error: &'a RefCell<Option<NodeError>>,
154 parent_handle: SubcomposeLayoutNodeHandle,
155 root_id: NodeId,
156 placement_scratch: Vec<Placement>,
157 cached_measure_node_scratch: Vec<NodeId>,
158 cached_measure_size_scratch: Vec<Option<Size>>,
159 cached_measure_missing_scratch: Vec<NodeId>,
160 registered_measurement_node_ids: Vec<NodeId>,
161 pending_commands_applied: bool,
162 #[cfg(debug_assertions)]
163 shadow_stash: Option<(Vec<NodeId>, Vec<NodeId>)>,
164}
165
166thread_local! {
167 static CLEAN_SLOT_SKIPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
168}
169
170fn record_clean_slot_skip() {
171 CLEAN_SLOT_SKIPS.with(|count| count.set(count.get() + 1));
172}
173
174pub fn clean_slot_skip_count() -> u64 {
178 CLEAN_SLOT_SKIPS.with(std::cell::Cell::get)
179}
180
181struct SubcomposeMeasureScopeInit<'a> {
182 composer: Composer,
183 density: crate::density::Density,
184 state: &'a mut SubcomposeState,
185 constraints: Constraints,
186 measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
187 cached_measure_batch_registrar: CachedMeasureBatchRegistrar<'a>,
188 retained_measure_lookup: RetainedMeasureLookup<'a>,
189 retained_measure_registrar: RetainedMeasureRegistrar<'a>,
190 error: &'a RefCell<Option<NodeError>>,
191 parent_handle: SubcomposeLayoutNodeHandle,
192 root_id: NodeId,
193 placement_scratch: Vec<Placement>,
194}
195
196impl<'a> SubcomposeMeasureScopeImpl<'a> {
197 fn new(init: SubcomposeMeasureScopeInit<'a>) -> Self {
198 Self {
199 composer: init.composer,
200 density_scope: crate::density::DensityMeasureScope::new(init.density),
201 state: init.state,
202 constraints: init.constraints,
203 measurer: init.measurer,
204 cached_measure_batch_registrar: init.cached_measure_batch_registrar,
205 retained_measure_lookup: init.retained_measure_lookup,
206 retained_measure_registrar: init.retained_measure_registrar,
207 error: init.error,
208 parent_handle: init.parent_handle,
209 root_id: init.root_id,
210 placement_scratch: init.placement_scratch,
211 cached_measure_node_scratch: Vec::new(),
212 cached_measure_size_scratch: Vec::new(),
213 cached_measure_missing_scratch: Vec::new(),
214 registered_measurement_node_ids: Vec::new(),
215 pending_commands_applied: false,
216 #[cfg(debug_assertions)]
217 shadow_stash: None,
218 }
219 }
220
221 fn register_measurement_node_id(&mut self, node_id: NodeId) {
222 if !self.registered_measurement_node_ids.contains(&node_id) {
223 self.registered_measurement_node_ids.push(node_id);
224 }
225 }
226
227 fn into_placement_scratch(self) -> Vec<Placement> {
228 self.placement_scratch
229 }
230
231 pub(crate) fn layout_with_placement_builder(
232 &mut self,
233 width: f32,
234 height: f32,
235 build: impl FnOnce(&mut Vec<Placement>),
236 ) -> MeasureResult {
237 self.placement_scratch.clear();
238 build(&mut self.placement_scratch);
239 MeasureResult::new(
240 Size { width, height },
241 std::mem::take(&mut self.placement_scratch),
242 )
243 }
244
245 fn record_error(&self, err: NodeError) {
246 let mut slot = self.error.borrow_mut();
247 if slot.is_none() {
248 eprintln!("[SubcomposeLayout] Error suppressed: {:?}", err);
249 *slot = Some(err);
250 }
251 }
252
253 fn owner_chain_deactivation_epoch(&self) -> u64 {
254 self.parent_handle
255 .inner
256 .borrow()
257 .captured_context
258 .as_ref()
259 .map(cranpose_core::CapturedCompositionContext::owner_chain_deactivation_epoch)
260 .unwrap_or(0)
261 }
262
263 fn ensure_pending_commands_applied(&mut self) -> bool {
264 if self.pending_commands_applied {
265 return true;
266 }
267
268 let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
269 if let Err(err) = self.composer.apply_pending_commands() {
270 self.record_error(err);
271 return false;
272 }
273 if let Some(start) = telemetry_start {
274 log::warn!(
275 "[subcompose-telemetry] apply_pending_commands_ms={:.2}",
276 start.elapsed().as_secs_f64() * 1000.0
277 );
278 }
279
280 self.pending_commands_applied = true;
281 true
282 }
283
284 fn perform_subcompose<Content>(&mut self, slot_id: SlotId, content: Content) -> Vec<NodeId>
285 where
286 Content: FnMut() + 'static,
287 {
288 let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
289 let mut inner = self.parent_handle.inner.borrow_mut();
290
291 let (virtual_node_id, is_rebound) =
292 if let Some((node_id, rebound)) = self.state.take_node_from_reusables(slot_id) {
293 (node_id, rebound)
294 } else {
295 let id = allocate_virtual_node_id();
296 let node = LayoutNode::new_virtual();
297 if let Err(e) = self
298 .composer
299 .register_virtual_node(id, Box::new(node.clone()))
300 {
301 eprintln!(
302 "[Subcompose] Failed to register virtual node {}: {:?}",
303 id, e
304 );
305 }
306 register_layout_node(id, &node);
307
308 inner.virtual_nodes.insert(id, Rc::new(node));
309 inner.children.push(id);
310 (id, false)
311 };
312
313 self.composer.record_subcompose_child(virtual_node_id);
314
315 if let Some(v_node) = inner.virtual_nodes.get(&virtual_node_id) {
316 v_node.set_parent(self.root_id);
317 }
318
319 drop(inner);
320
321 let children = self.compose_into_slot(slot_id, virtual_node_id, content);
322 if is_rebound {
323 self.composer.record_rebound_slot_children(&children);
324 }
325 if let Some(start) = telemetry_start {
326 log::warn!(
327 "[subcompose-telemetry] slot={} reused={} children={} subcompose_ms={:.2}",
328 slot_id.raw(),
329 is_rebound,
330 children.len(),
331 start.elapsed().as_secs_f64() * 1000.0
332 );
333 }
334 children
335 }
336
337 fn compose_into_slot<Content>(
338 &mut self,
339 slot_id: SlotId,
340 virtual_node_id: NodeId,
341 content: Content,
342 ) -> Vec<NodeId>
343 where
344 Content: FnMut() + 'static,
345 {
346 let content_holder = self.state.callback_holder(slot_id);
347 content_holder.update(content);
348
349 let _ = self
350 .composer
351 .with_node_mut::<LayoutNode, _>(virtual_node_id, |node| {
352 node.set_parent(self.root_id);
353 });
354
355 let slot_host = self.state.get_or_create_slots(slot_id);
356 self.parent_handle.note_slot_host(&slot_host);
357 let holder_for_slot = content_holder.clone();
358 let scopes = self
359 .composer
360 .subcompose_slot(&slot_host, Some(virtual_node_id), move |_| {
361 compose_subcompose_slot_content(holder_for_slot.clone());
362 })
363 .map(|(_, scopes)| scopes)
364 .unwrap_or_default();
365 self.pending_commands_applied = false;
366
367 let owner_epoch = self.owner_chain_deactivation_epoch();
368 self.state
369 .register_active(slot_id, &[virtual_node_id], &scopes);
370 self.state.mark_slot_composed_current(slot_id, owner_epoch);
371
372 self.composer.get_node_children(virtual_node_id).to_vec()
373 }
374
375 fn activate_clean_retained_slot(&mut self, slot_id: SlotId) -> Option<Vec<NodeId>> {
376 if self.state.has_pending_precompositions(slot_id) {
377 return None;
378 }
379 if !self
380 .state
381 .slot_content_generation_current(slot_id, self.owner_chain_deactivation_epoch())
382 {
383 return None;
384 }
385 if !self.ensure_pending_commands_applied() {
386 return None;
387 }
388 let virtual_node_ids = self.state.activate_current_active_slot(slot_id)?;
389
390 {
391 let inner = self.parent_handle.inner.borrow();
392 for virtual_node_id in &virtual_node_ids {
393 self.composer.record_subcompose_child(*virtual_node_id);
394 if let Some(v_node) = inner.virtual_nodes.get(virtual_node_id) {
395 v_node.set_parent(self.root_id);
396 }
397 }
398 }
399 for virtual_node_id in &virtual_node_ids {
400 let _ = self
401 .composer
402 .with_node_mut::<LayoutNode, _>(*virtual_node_id, |node| {
403 node.set_parent(self.root_id);
404 });
405 }
406
407 let mut children = Vec::new();
408 for virtual_node_id in &virtual_node_ids {
409 children.extend(self.composer.get_node_children(*virtual_node_id));
410 }
411 record_clean_slot_skip();
412
413 #[cfg(debug_assertions)]
414 {
415 self.shadow_stash = Some((virtual_node_ids, children.clone()));
416 }
417
418 Some(children)
419 }
420
421 #[cfg(debug_assertions)]
422 fn shadow_verify_clean_slot<Content>(&mut self, slot_id: SlotId, content: Content)
423 where
424 Content: FnMut() + 'static,
425 {
426 let Some((virtual_node_ids, skipped_children)) = self.shadow_stash.take() else {
427 return;
428 };
429 if virtual_node_ids.len() != 1 {
430 return;
431 }
432 let composed = self.compose_into_slot(slot_id, virtual_node_ids[0], content);
433 assert!(
434 composed == skipped_children,
435 "clean-slot skip diverged for slot {:?}: recomposing produced root \
436 children {:?} but the retained slot held {:?}. The slot content \
437 read a value that changed between measure passes without any \
438 invalidation path — make that value reactive state, or part of \
439 the subcompose capture key",
440 slot_id,
441 composed,
442 skipped_children,
443 );
444 }
445
446 pub(crate) fn activate_exact_retained_slot_with_known_children(
447 &mut self,
448 slot_id: SlotId,
449 known_children: &[u64],
450 ) -> Option<(Vec<SubcomposeChild>, bool)> {
451 for &node_id in known_children {
452 NodeId::try_from(node_id).ok()?;
453 }
454
455 let virtual_node_ids = match self.activate_current_active_slot_roots(slot_id) {
456 Some(virtual_node_ids) => {
457 for virtual_node_id in &virtual_node_ids {
458 self.composer.record_subcompose_child(*virtual_node_id);
459 }
460 virtual_node_ids
461 }
462 None => self.activate_recycled_exact_retained_slot_roots(slot_id)?,
463 };
464
465 if !self.ensure_pending_commands_applied() {
466 return None;
467 }
468
469 let mut activated_children = Vec::with_capacity(known_children.len());
470 for virtual_node_id in virtual_node_ids {
471 activated_children.extend(
472 self.composer
473 .get_node_children(virtual_node_id)
474 .iter()
475 .copied()
476 .map(SubcomposeChild::new),
477 );
478 }
479 let children_match = activated_children
480 .iter()
481 .map(|child| child.node_id() as u64)
482 .eq(known_children.iter().copied());
483 Some((activated_children, children_match))
484 }
485
486 fn activate_current_active_slot_roots(&mut self, slot_id: SlotId) -> Option<Vec<NodeId>> {
487 self.state.activate_current_active_slot(slot_id)
488 }
489
490 fn activate_recycled_exact_retained_slot_roots(
491 &mut self,
492 slot_id: SlotId,
493 ) -> Option<Vec<NodeId>> {
494 let activation = self.state.take_exact_slot_activation(slot_id)?;
495 let virtual_node_ids = activation.nodes;
496 let scopes = activation.scopes;
497 let reactivate_scopes = activation.reactivate_scopes;
498
499 if reactivate_scopes {
500 let inner = self.parent_handle.inner.borrow();
501 for virtual_node_id in &virtual_node_ids {
502 self.composer.record_subcompose_child(*virtual_node_id);
503 if let Some(v_node) = inner.virtual_nodes.get(virtual_node_id) {
504 v_node.set_parent(self.root_id);
505 }
506 }
507 for virtual_node_id in &virtual_node_ids {
508 let _ = self
509 .composer
510 .with_node_mut::<LayoutNode, _>(*virtual_node_id, |node| {
511 node.set_parent(self.root_id);
512 });
513 }
514 } else {
515 for virtual_node_id in &virtual_node_ids {
516 self.composer.record_subcompose_child(*virtual_node_id);
517 }
518 }
519
520 self.state.register_active_with_scope_reactivation(
521 slot_id,
522 &virtual_node_ids,
523 &scopes,
524 reactivate_scopes,
525 );
526 Some(virtual_node_ids)
527 }
528}
529
530impl<'a> SubcomposeLayoutScope for SubcomposeMeasureScopeImpl<'a> {
531 fn constraints(&self) -> Constraints {
532 self.constraints
533 }
534
535 fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
536 where
537 I: IntoIterator<Item = Placement>,
538 {
539 self.layout_with_placement_builder(width, height, |scratch| {
540 scratch.extend(placements);
541 })
542 }
543}
544
545impl cranpose_ui_layout::MeasureScope for SubcomposeMeasureScopeImpl<'_> {
546 fn density(&self) -> f32 {
547 self.density_scope.density()
548 }
549
550 fn font_scale(&self) -> f32 {
551 self.density_scope.font_scale()
552 }
553}
554
555impl<'a> SubcomposeMeasureScope for SubcomposeMeasureScopeImpl<'a> {
556 fn subcompose<K, Content>(
557 &mut self,
558 slot_id: SlotId,
559 key: K,
560 content: Content,
561 ) -> Vec<SubcomposeChild>
562 where
563 K: PartialEq + 'static,
564 Content: FnMut() + 'static,
565 {
566 if self.state.retained_capture_key_matches(slot_id, &key)
567 && let Some(children) = self.activate_clean_retained_slot(slot_id)
568 {
569 #[cfg(debug_assertions)]
570 self.shadow_verify_clean_slot(slot_id, content);
571 return children.into_iter().map(SubcomposeChild::new).collect();
572 }
573 self.state.store_retained_capture_key(slot_id, key);
574 let nodes = self.perform_subcompose(slot_id, content);
575 nodes.into_iter().map(SubcomposeChild::new).collect()
576 }
577
578 fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable {
579 if self.error.borrow().is_some() {
580 return SubcomposePlaceable::value(0.0, 0.0, child.node_id);
581 }
582
583 let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
584 if !self.ensure_pending_commands_applied() {
585 return SubcomposePlaceable::value(0.0, 0.0, child.node_id);
586 }
587
588 let size = (self.measurer)(child.node_id, constraints);
589 self.register_measurement_node_id(child.node_id);
590 if let Some(start) = telemetry_start {
591 log::warn!(
592 "[subcompose-telemetry] child={} measure_ms={:.2} size=({:.2},{:.2})",
593 child.node_id,
594 start.elapsed().as_secs_f64() * 1000.0,
595 size.width,
596 size.height
597 );
598 }
599 SubcomposePlaceable::value(size.width, size.height, child.node_id)
600 }
601
602 fn node_has_no_parent(&self, node_id: NodeId) -> bool {
603 self.composer.node_has_no_parent(node_id)
604 }
605}
606
607impl<'a> SubcomposeMeasureScopeImpl<'a> {
608 pub fn active_slots_count(&self) -> usize {
612 self.state.active_slots_count()
613 }
614
615 pub fn reusable_slots_count(&self) -> usize {
619 self.state.reusable_slots_count()
620 }
621
622 pub fn register_content_type(&mut self, slot_id: SlotId, content_type: u64) {
628 self.state.register_content_type(slot_id, content_type);
629 }
630
631 pub fn update_content_type(&mut self, slot_id: SlotId, content_type: Option<u64>) {
637 self.state.update_content_type(slot_id, content_type);
638 }
639
640 pub(crate) fn set_reusable_pool_limits(&mut self, per_type: usize, untyped: usize) {
641 self.state.set_reusable_pool_limits(per_type, untyped);
642 }
643
644 pub(crate) fn recycle_active_slots_where(&mut self, predicate: impl FnMut(SlotId) -> bool) {
645 let disposed = self.state.recycle_active_slots_where(predicate);
646 debug_assert!(
647 disposed.is_empty(),
648 "lazy subcompose reusable pool limits must retain recycled active slots"
649 );
650 }
651
652 pub fn was_last_slot_reused(&self) -> Option<bool> {
660 self.state.was_last_slot_reused()
661 }
662
663 pub(crate) fn measure_retained(
664 &mut self,
665 child: SubcomposeChild,
666 constraints: Constraints,
667 ) -> (SubcomposePlaceable, Option<Rc<MeasuredNode>>) {
668 let placeable = self.measure(child, constraints);
669 let retained = (self.retained_measure_lookup)(child.node_id);
670 (placeable, retained)
671 }
672
673 pub(crate) fn register_retained_measurements(&mut self, measurements: &[Rc<MeasuredNode>]) {
674 if measurements.is_empty() {
675 return;
676 }
677
678 for measured in measurements {
679 self.register_measurement_node_id(measured.node_id());
680 }
681 (self.retained_measure_registrar)(measurements);
682 }
683
684 pub(crate) fn children_need_relayout(&mut self, children: &[SubcomposeChild]) -> bool {
685 if !self.ensure_pending_commands_applied() {
686 return true;
687 }
688
689 let mut root_ids = smallvec::SmallVec::<[NodeId; 8]>::new();
690 root_ids.extend(children.iter().map(SubcomposeChild::node_id));
691 self.composer.nodes_need_measure(&root_ids) || self.composer.nodes_need_layout(&root_ids)
692 }
693
694 pub(crate) fn ensure_cached_measurement_node_ids<I>(
695 &mut self,
696 node_ids: I,
697 constraints: Constraints,
698 ) -> usize
699 where
700 I: IntoIterator<Item = NodeId>,
701 {
702 if self.error.borrow().is_some() || !self.ensure_pending_commands_applied() {
703 return 0;
704 }
705
706 self.cached_measure_node_scratch.clear();
707 self.cached_measure_node_scratch.extend(
708 node_ids
709 .into_iter()
710 .filter(|node_id| !self.registered_measurement_node_ids.contains(node_id)),
711 );
712 if self.cached_measure_node_scratch.is_empty() {
713 return 0;
714 }
715
716 self.cached_measure_size_scratch.clear();
717 (self.cached_measure_batch_registrar)(
718 &self.cached_measure_node_scratch,
719 constraints,
720 &mut self.cached_measure_size_scratch,
721 );
722 self.cached_measure_size_scratch
723 .resize(self.cached_measure_node_scratch.len(), None);
724
725 let mut cached_count = 0;
726 self.cached_measure_missing_scratch.clear();
727 for index in 0..self.cached_measure_node_scratch.len() {
728 let node_id = self.cached_measure_node_scratch[index];
729 if self.cached_measure_size_scratch[index].is_some() {
730 cached_count += 1;
731 self.register_measurement_node_id(node_id);
732 } else {
733 self.cached_measure_missing_scratch.push(node_id);
734 }
735 }
736
737 let mut missing = std::mem::take(&mut self.cached_measure_missing_scratch);
738 for node_id in missing.drain(..) {
739 let _ = self.measure(SubcomposeChild::new(node_id), constraints);
740 }
741 self.cached_measure_missing_scratch = missing;
742
743 cached_count
744 }
745}
746
747fn compose_subcompose_slot_content(holder: cranpose_core::CallbackHolder) {
748 cranpose_core::with_current_composer(|composer| {
749 let holder_for_recompose = holder.clone();
750 composer.set_recompose_callback(move |_composer| {
751 compose_subcompose_slot_content(holder_for_recompose.clone());
752 });
753 });
754
755 let invoke = holder.clone_rc();
756 invoke();
757}
758
759pub type MeasurePolicy =
760 dyn for<'scope> Fn(&mut SubcomposeMeasureScopeImpl<'scope>, Constraints) -> MeasureResult;
761
762pub struct SubcomposeLayoutNode {
764 inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
765 parent: Cell<Option<NodeId>>,
766 id: Cell<Option<NodeId>>,
767 needs_measure: Cell<bool>,
768 needs_layout: Cell<bool>,
769 needs_semantics: Cell<bool>,
770 needs_redraw: Cell<bool>,
771 needs_pointer_pass: Cell<bool>,
772 needs_focus_sync: Cell<bool>,
773 virtual_children_count: Cell<usize>,
774 layout_state: RefCell<LayoutState>,
775 cache_handles: LayoutNodeCacheHandles,
776 modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
777 modifier_slices_dirty: Cell<bool>,
778}
779
780impl SubcomposeLayoutNode {
781 pub fn new(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
782 let inner = Rc::new(RefCell::new(SubcomposeLayoutNodeInner::new(measure_policy)));
783 let node = Self {
784 inner,
785 parent: Cell::new(None),
786 id: Cell::new(None),
787 needs_measure: Cell::new(true),
788 needs_layout: Cell::new(true),
789 needs_semantics: Cell::new(true),
790 needs_redraw: Cell::new(true),
791 needs_pointer_pass: Cell::new(false),
792 needs_focus_sync: Cell::new(false),
793 virtual_children_count: Cell::new(0),
794 layout_state: RefCell::new(LayoutState::default()),
795 cache_handles: LayoutNodeCacheHandles::default(),
796 modifier_slices_snapshot: RefCell::new(Rc::default()),
797 modifier_slices_dirty: Cell::new(true),
798 };
799 let (invalidations, _) = node.inner.borrow_mut().set_modifier_collect(modifier);
800 node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
801 node.update_modifier_slices_cache();
802 node.note_host_to_the_composition_that_made_it();
803 node
804 }
805
806 fn note_host_to_the_composition_that_made_it(&self) {
807 let host = Rc::clone(&self.inner.borrow().slots);
808 cranpose_core::note_nested_slots_host(&host);
809 }
810
811 pub fn with_content_type_policy(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
817 let mut inner_data = SubcomposeLayoutNodeInner::new(measure_policy);
818 inner_data
819 .state
820 .set_policy(Box::new(cranpose_core::ContentTypeReusePolicy::new()));
821 let inner = Rc::new(RefCell::new(inner_data));
822 let node = Self {
823 inner,
824 parent: Cell::new(None),
825 id: Cell::new(None),
826 needs_measure: Cell::new(true),
827 needs_layout: Cell::new(true),
828 needs_semantics: Cell::new(true),
829 needs_redraw: Cell::new(true),
830 needs_pointer_pass: Cell::new(false),
831 needs_focus_sync: Cell::new(false),
832 virtual_children_count: Cell::new(0),
833 layout_state: RefCell::new(LayoutState::default()),
834 cache_handles: LayoutNodeCacheHandles::default(),
835 modifier_slices_snapshot: RefCell::new(Rc::default()),
836 modifier_slices_dirty: Cell::new(true),
837 };
838 let (invalidations, _) = node.inner.borrow_mut().set_modifier_collect(modifier);
839 node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
840 node.update_modifier_slices_cache();
841 node.note_host_to_the_composition_that_made_it();
842 node
843 }
844
845 pub fn handle(&self) -> SubcomposeLayoutNodeHandle {
846 SubcomposeLayoutNodeHandle {
847 inner: Rc::clone(&self.inner),
848 }
849 }
850
851 #[doc(hidden)]
852 pub fn debug_scope_ids_by_slot(&self) -> Vec<(u64, Vec<usize>)> {
853 self.inner.borrow().state.debug_scope_ids_by_slot()
854 }
855
856 #[doc(hidden)]
857 pub fn debug_slot_table_for_slot(
858 &self,
859 slot_id: cranpose_core::SlotId,
860 ) -> Option<Vec<cranpose_core::SlotDebugEntry>> {
861 self.inner.borrow().state.debug_slot_table_for_slot(slot_id)
862 }
863
864 #[doc(hidden)]
865 pub fn debug_slot_table_groups_for_slot(
866 &self,
867 slot_id: cranpose_core::SlotId,
868 ) -> Option<Vec<cranpose_core::subcompose::DebugSlotGroup>> {
869 self.inner
870 .borrow()
871 .state
872 .debug_slot_table_groups_for_slot(slot_id)
873 }
874
875 pub fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
876 let mut inner = self.inner.borrow_mut();
877 if Rc::ptr_eq(&inner.measure_policy, &policy) {
878 return;
879 }
880 inner.set_measure_policy(policy);
881 drop(inner);
882 self.invalidate_subcomposition();
883 }
884
885 pub fn set_captured_context(&mut self, context: cranpose_core::CapturedCompositionContext) {
887 self.inner.borrow_mut().captured_context = Some(context);
888 }
889
890 pub fn set_density(&mut self, density: crate::density::Density) {
896 let mut inner = self.inner.borrow_mut();
897 if inner.density != density {
898 inner.density = density;
899 drop(inner);
900 self.mark_needs_measure();
901 }
902 }
903
904 pub fn set_modifier(&mut self, modifier: Modifier) {
905 let prev_caps = self.modifier_capabilities();
906 let (invalidations, modifier_changed) = {
907 let mut inner = self.inner.borrow_mut();
908 inner.set_modifier_collect(modifier)
909 };
910 self.dispatch_modifier_invalidations(&invalidations, prev_caps);
911 self.update_modifier_slices_cache();
912 if modifier_changed {
913 self.request_semantics_update();
914 }
915 }
916
917 fn update_modifier_slices_cache(&self) {
918 let inner = self.inner.borrow();
919 let mut snapshot = self.modifier_slices_snapshot.borrow_mut();
920 collect_modifier_slices_into(inner.modifier_chain.chain(), Rc::make_mut(&mut snapshot));
921 self.modifier_slices_dirty.set(false);
922 }
923
924 pub(crate) fn mark_modifier_slices_dirty(&self) {
925 self.modifier_slices_dirty.set(true);
926 }
927
928 pub fn set_debug_modifiers(&mut self, enabled: bool) {
929 self.inner.borrow_mut().set_debug_modifiers(enabled);
930 }
931
932 pub fn modifier(&self) -> Modifier {
933 self.handle().modifier()
934 }
935
936 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
937 self.inner.borrow().resolved_modifiers
938 }
939
940 pub fn layout_state(&self) -> LayoutState {
942 self.layout_state.borrow().clone()
943 }
944
945 pub(crate) fn cache_handles(&self) -> LayoutNodeCacheHandles {
946 self.cache_handles.clone()
947 }
948
949 pub fn set_position(&self, position: Point) {
952 self.layout_state.borrow_mut().place(position);
953 }
954
955 pub fn set_measured_size(&self, size: Size) {
959 self.layout_state.borrow_mut().set_size(size);
960 }
961
962 pub fn clear_placed(&self) {
964 self.layout_state.borrow_mut().clear_placed();
965 }
966
967 pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
969 if self.modifier_slices_dirty.get() {
970 self.update_modifier_slices_cache();
971 }
972 self.modifier_slices_snapshot.borrow().clone()
973 }
974
975 pub fn state(&self) -> Ref<'_, SubcomposeState> {
976 Ref::map(self.inner.borrow(), |inner| &inner.state)
977 }
978
979 pub fn state_mut(&self) -> RefMut<'_, SubcomposeState> {
980 RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.state)
981 }
982
983 pub fn invalidate_subcomposition(&self) {
984 self.inner.borrow().state.invalidate_scopes();
985 self.mark_needs_measure();
986 if let Some(id) = self.id.get() {
987 cranpose_core::bubble_measure_dirty_in_composer(id);
988 }
989 }
990
991 pub fn request_measure_recompose(&self) {
992 self.mark_needs_measure();
993 if let Some(id) = self.id.get() {
994 cranpose_core::bubble_measure_dirty_in_composer(id);
995 }
996 }
997
998 pub fn active_children(&self) -> Vec<NodeId> {
999 current_subcompose_children(&self.inner.borrow())
1000 }
1001
1002 pub fn mark_needs_measure(&self) {
1004 self.needs_measure.set(true);
1005 self.needs_layout.set(true);
1006 }
1007
1008 pub fn mark_needs_layout_flag(&self) {
1010 self.needs_layout.set(true);
1011 }
1012
1013 pub fn mark_needs_redraw(&self) {
1015 self.needs_redraw.set(true);
1016 if let Some(id) = self.id.get() {
1017 crate::schedule_draw_repass(id);
1018 }
1019 crate::request_render_invalidation();
1020 }
1021
1022 pub fn needs_measure(&self) -> bool {
1024 self.needs_measure.get()
1025 }
1026
1027 pub(crate) fn clear_needs_measure(&self) {
1028 self.needs_measure.set(false);
1029 }
1030
1031 pub(crate) fn clear_needs_layout(&self) {
1032 self.needs_layout.set(false);
1033 }
1034
1035 pub fn mark_needs_semantics(&self) {
1037 self.needs_semantics.set(true);
1038 }
1039
1040 pub(crate) fn clear_needs_semantics(&self) {
1041 self.needs_semantics.set(false);
1042 }
1043
1044 #[cfg(test)]
1045 pub(crate) fn clear_needs_semantics_for_tests(&self) {
1046 self.clear_needs_semantics();
1047 }
1048
1049 pub fn needs_redraw(&self) -> bool {
1051 self.needs_redraw.get()
1052 }
1053
1054 pub fn clear_needs_redraw(&self) {
1055 self.needs_redraw.set(false);
1056 }
1057
1058 pub fn mark_needs_pointer_pass(&self) {
1060 self.needs_pointer_pass.set(true);
1061 }
1062
1063 pub fn needs_pointer_pass(&self) -> bool {
1065 self.needs_pointer_pass.get()
1066 }
1067
1068 pub fn clear_needs_pointer_pass(&self) {
1070 self.needs_pointer_pass.set(false);
1071 }
1072
1073 pub fn mark_needs_focus_sync(&self) {
1075 self.needs_focus_sync.set(true);
1076 }
1077
1078 pub fn needs_focus_sync(&self) -> bool {
1080 self.needs_focus_sync.get()
1081 }
1082
1083 pub fn clear_needs_focus_sync(&self) {
1085 self.needs_focus_sync.set(false);
1086 }
1087
1088 fn request_semantics_update(&self) {
1089 let already_dirty = self.needs_semantics.replace(true);
1090 if already_dirty {
1091 return;
1092 }
1093
1094 if let Some(id) = self.id.get() {
1095 cranpose_core::queue_semantics_invalidation(id);
1096 }
1097 }
1098
1099 pub fn modifier_capabilities(&self) -> NodeCapabilities {
1101 self.inner.borrow().modifier_capabilities
1102 }
1103
1104 pub fn has_layout_modifier_nodes(&self) -> bool {
1105 self.modifier_capabilities()
1106 .contains(NodeCapabilities::LAYOUT)
1107 }
1108
1109 pub fn has_draw_modifier_nodes(&self) -> bool {
1110 self.modifier_capabilities()
1111 .contains(NodeCapabilities::DRAW)
1112 }
1113
1114 pub fn has_pointer_input_modifier_nodes(&self) -> bool {
1115 self.modifier_capabilities()
1116 .contains(NodeCapabilities::POINTER_INPUT)
1117 }
1118
1119 pub fn has_semantics_modifier_nodes(&self) -> bool {
1120 self.modifier_capabilities()
1121 .contains(NodeCapabilities::SEMANTICS)
1122 }
1123
1124 pub fn has_focus_modifier_nodes(&self) -> bool {
1125 self.modifier_capabilities()
1126 .contains(NodeCapabilities::FOCUS)
1127 }
1128
1129 fn dispatch_modifier_invalidations(
1130 &self,
1131 invalidations: &[ModifierInvalidation],
1132 prev_caps: NodeCapabilities,
1133 ) {
1134 let curr_caps = self.modifier_capabilities();
1135 for invalidation in invalidations {
1136 self.modifier_slices_dirty.set(true);
1137 let invalidation_caps = invalidation.capabilities();
1138 let has_capability = |capability| {
1139 curr_caps.contains(capability)
1140 || prev_caps.contains(capability)
1141 || invalidation_caps.contains(capability)
1142 };
1143 match invalidation.kind() {
1144 InvalidationKind::Layout => {
1145 if has_capability(NodeCapabilities::LAYOUT) {
1146 self.mark_needs_measure();
1147 }
1148 }
1149 InvalidationKind::Draw => {
1150 if has_capability(NodeCapabilities::DRAW) {
1151 self.mark_needs_redraw();
1152 }
1153 }
1154 InvalidationKind::PointerInput => {
1155 if has_capability(NodeCapabilities::POINTER_INPUT) {
1156 self.mark_needs_pointer_pass();
1157 crate::request_pointer_invalidation();
1158 if let Some(id) = self.id.get() {
1159 crate::schedule_pointer_repass(id);
1160 }
1161 }
1162 }
1163 InvalidationKind::Semantics => {
1164 self.request_semantics_update();
1165 }
1166 InvalidationKind::Focus => {
1167 if has_capability(NodeCapabilities::FOCUS) {
1168 self.mark_needs_focus_sync();
1169 crate::request_focus_invalidation();
1170 if let Some(id) = self.id.get() {
1171 crate::schedule_focus_invalidation(id);
1172 }
1173 }
1174 }
1175 }
1176 }
1177 }
1178}
1179
1180impl cranpose_core::Node for SubcomposeLayoutNode {
1181 fn mount(&mut self) {
1182 let mut inner = self.inner.borrow_mut();
1183 let (chain, mut context) = inner.modifier_chain.chain_and_context_mut();
1184 chain.repair_chain();
1185 chain.attach_nodes(&mut *context);
1186 }
1187
1188 fn unmount(&mut self) {
1189 self.inner
1190 .borrow_mut()
1191 .modifier_chain
1192 .chain_mut()
1193 .detach_nodes();
1194 }
1195
1196 fn insert_child(&mut self, child: NodeId) -> bool {
1197 let mut inner = self.inner.borrow_mut();
1198 if inner.children.contains(&child) {
1199 return false;
1200 }
1201 if is_virtual_node(child) {
1202 let count = self.virtual_children_count.get();
1203 self.virtual_children_count.set(count + 1);
1204 }
1205 inner.children.push(child);
1206 true
1207 }
1208
1209 fn remove_child(&mut self, child: NodeId) -> bool {
1210 let mut inner = self.inner.borrow_mut();
1211 let before = inner.children.len();
1212 inner.children.retain(|&id| id != child);
1213 let removed = inner.children.len() < before;
1214 if removed && is_virtual_node(child) {
1215 let count = self.virtual_children_count.get();
1216 if count > 0 {
1217 self.virtual_children_count.set(count - 1);
1218 }
1219 }
1220 removed
1221 }
1222
1223 fn move_child(&mut self, from: usize, to: usize) {
1224 let mut inner = self.inner.borrow_mut();
1225 if from == to || from >= inner.children.len() {
1226 return;
1227 }
1228 let child = inner.children.remove(from);
1229 let target = to.min(inner.children.len());
1230 inner.children.insert(target, child);
1231 }
1232
1233 fn update_children(&mut self, children: &[NodeId]) {
1234 let mut inner = self.inner.borrow_mut();
1235 inner.children.clear();
1236 inner.children.extend_from_slice(children);
1237 }
1238
1239 fn children(&self) -> Vec<NodeId> {
1240 current_subcompose_children(&self.inner.borrow())
1241 }
1242
1243 fn collect_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1244 out.clear();
1245 out.extend(self.inner.borrow().last_placements.iter().copied());
1246 }
1247
1248 fn collect_owned_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1249 out.clear();
1250 out.extend(self.inner.borrow().children.iter().copied());
1251 }
1252
1253 fn set_node_id(&mut self, id: NodeId) {
1254 self.id.set(Some(id));
1255 self.layout_state.borrow_mut().set_node_id(id);
1256 {
1257 let mut inner = self.inner.borrow_mut();
1258 inner.node_id = Some(id);
1259 inner.modifier_chain.set_node_id(Some(id));
1260 }
1261 self.update_modifier_slices_cache();
1262 }
1263
1264 fn on_attached_to_parent(&mut self, parent: NodeId) {
1265 self.parent.set(Some(parent));
1266 }
1267
1268 fn on_removed_from_parent(&mut self) {
1269 self.parent.set(None);
1270 self.inner.borrow().state.bump_content_generation();
1271 }
1272
1273 fn parent(&self) -> Option<NodeId> {
1274 self.parent.get()
1275 }
1276
1277 fn mark_needs_layout(&self) {
1278 self.needs_layout.set(true);
1279 }
1280
1281 fn needs_layout(&self) -> bool {
1282 self.needs_layout.get()
1283 }
1284
1285 fn mark_needs_measure(&self) {
1286 self.needs_measure.set(true);
1287 self.needs_layout.set(true);
1288 }
1289
1290 fn needs_measure(&self) -> bool {
1291 self.needs_measure.get()
1292 }
1293
1294 fn mark_needs_semantics(&self) {
1295 self.needs_semantics.set(true);
1296 }
1297
1298 fn needs_semantics(&self) -> bool {
1299 self.needs_semantics.get()
1300 }
1301
1302 fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1303 self.parent.set(Some(parent));
1304 }
1305}
1306
1307#[derive(Clone)]
1308pub struct SubcomposeLayoutNodeHandle {
1309 inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
1310}
1311
1312impl SubcomposeLayoutNodeHandle {
1313 pub(crate) fn note_slot_host(&self, slot_host: &Rc<cranpose_core::SlotsHost>) {
1314 let Ok(inner) = self.inner.try_borrow() else {
1315 return;
1316 };
1317 if Rc::ptr_eq(&inner.slots, slot_host) {
1318 return;
1319 }
1320 inner.slots.note_nested_host(slot_host);
1321 }
1322
1323 pub(crate) fn measured_children_scratch(
1324 &self,
1325 ) -> Rc<RefCell<HashMap<NodeId, Rc<MeasuredNode>>>> {
1326 let scratch = {
1327 let inner = self.inner.borrow();
1328 Rc::clone(&inner.measured_children_scratch)
1329 };
1330 scratch.borrow_mut().clear();
1331 scratch
1332 }
1333
1334 pub fn modifier(&self) -> Modifier {
1335 self.inner.borrow().modifier.clone()
1336 }
1337
1338 pub fn layout_properties(&self) -> crate::modifier::LayoutProperties {
1339 self.resolved_modifiers().layout_properties()
1340 }
1341
1342 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
1343 self.inner.borrow().resolved_modifiers
1344 }
1345
1346 pub fn total_offset(&self) -> Point {
1347 self.resolved_modifiers().offset()
1348 }
1349
1350 pub fn modifier_capabilities(&self) -> NodeCapabilities {
1351 self.inner.borrow().modifier_capabilities
1352 }
1353
1354 pub fn has_layout_modifier_nodes(&self) -> bool {
1355 self.modifier_capabilities()
1356 .contains(NodeCapabilities::LAYOUT)
1357 }
1358
1359 pub fn has_draw_modifier_nodes(&self) -> bool {
1360 self.modifier_capabilities()
1361 .contains(NodeCapabilities::DRAW)
1362 }
1363
1364 pub fn has_pointer_input_modifier_nodes(&self) -> bool {
1365 self.modifier_capabilities()
1366 .contains(NodeCapabilities::POINTER_INPUT)
1367 }
1368
1369 pub fn has_semantics_modifier_nodes(&self) -> bool {
1370 self.modifier_capabilities()
1371 .contains(NodeCapabilities::SEMANTICS)
1372 }
1373
1374 pub fn has_focus_modifier_nodes(&self) -> bool {
1375 self.modifier_capabilities()
1376 .contains(NodeCapabilities::FOCUS)
1377 }
1378
1379 pub fn set_debug_modifiers(&self, enabled: bool) {
1380 self.inner.borrow_mut().set_debug_modifiers(enabled);
1381 }
1382
1383 pub fn measure<'a>(
1384 &self,
1385 composer: &Composer,
1386 node_id: NodeId,
1387 constraints: Constraints,
1388 measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
1389 mut cached_measure_registrar: Box<dyn FnMut(NodeId, Constraints) -> Option<Size> + 'a>,
1390 error: &'a RefCell<Option<NodeError>>,
1391 ) -> Result<MeasureResult, NodeError> {
1392 self.measure_with_cached_batch(
1393 composer,
1394 node_id,
1395 constraints,
1396 CachedBatchMeasureInputs {
1397 measurer,
1398 cached_measure_batch_registrar: Box::new(
1399 move |node_ids, child_constraints, out| {
1400 out.clear();
1401 out.reserve(node_ids.len());
1402 for &child_id in node_ids {
1403 out.push(cached_measure_registrar(child_id, child_constraints));
1404 }
1405 },
1406 ),
1407 retained_measure_lookup: Box::new(|_| None),
1408 retained_measure_registrar: Box::new(|_| {}),
1409 error,
1410 },
1411 )
1412 }
1413
1414 pub(crate) fn measure_with_cached_batch<'a>(
1415 &self,
1416 composer: &Composer,
1417 node_id: NodeId,
1418 constraints: Constraints,
1419 callbacks: CachedBatchMeasureInputs<'a>,
1420 ) -> Result<MeasureResult, NodeError> {
1421 let CachedBatchMeasureInputs {
1422 measurer,
1423 cached_measure_batch_registrar,
1424 retained_measure_lookup,
1425 retained_measure_registrar,
1426 error,
1427 } = callbacks;
1428 let (policy, mut state, slots_host, placement_scratch, captured_context, density) = {
1429 let mut inner = self.inner.borrow_mut();
1430 let policy = Rc::clone(&inner.measure_policy);
1431 let state = std::mem::take(&mut inner.state);
1432 let slots_host = Rc::clone(&inner.slots);
1433 let placement_scratch = std::mem::take(&mut inner.placement_scratch);
1434 let captured_context = inner.captured_context.clone();
1435 let density = inner.density;
1436 (
1437 policy,
1438 state,
1439 slots_host,
1440 placement_scratch,
1441 captured_context,
1442 density,
1443 )
1444 };
1445 state.begin_pass();
1446
1447 let previous = composer.phase();
1448 if !matches!(previous, Phase::Measure | Phase::Layout) {
1449 composer.enter_phase(Phase::Measure);
1450 }
1451
1452 let constraints_copy = constraints;
1453 let fallback_context;
1454 let context = if let Some(context) = captured_context.as_ref() {
1455 context
1456 } else {
1457 fallback_context = composer.capture_composition_context();
1458 &fallback_context
1459 };
1460 let ((result, placement_scratch), _) = composer.subcompose_slot_with_context(
1461 &slots_host,
1462 Some(node_id),
1463 context,
1464 |inner_composer| {
1465 let mut scope = SubcomposeMeasureScopeImpl::new(SubcomposeMeasureScopeInit {
1466 composer: inner_composer.clone(),
1467 density,
1468 state: &mut state,
1469 constraints: constraints_copy,
1470 measurer,
1471 cached_measure_batch_registrar,
1472 retained_measure_lookup,
1473 retained_measure_registrar,
1474 error,
1475 parent_handle: self.clone(),
1476 root_id: node_id,
1477 placement_scratch,
1478 });
1479 let result = (policy)(&mut scope, constraints_copy);
1480 (result, scope.into_placement_scratch())
1481 },
1482 )?;
1483
1484 state.finish_pass();
1485
1486 if previous != composer.phase() {
1487 composer.enter_phase(previous);
1488 }
1489
1490 {
1491 let mut inner = self.inner.borrow_mut();
1492 inner.state = state;
1493 inner.placement_scratch = placement_scratch;
1494
1495 inner.replace_placed_children(
1496 result.placements.iter().map(|placement| placement.node_id),
1497 );
1498 }
1499
1500 Ok(result)
1501 }
1502
1503 pub(crate) fn recycle_placement_scratch(&self, mut placements: Vec<Placement>) {
1504 placements.clear();
1505 let mut inner = self.inner.borrow_mut();
1506 if placements.capacity() > inner.placement_scratch.capacity() {
1507 inner.placement_scratch = placements;
1508 }
1509 }
1510
1511 pub fn set_active_children<I>(&self, children: I)
1512 where
1513 I: IntoIterator<Item = NodeId>,
1514 {
1515 self.inner.borrow_mut().replace_placed_children(children);
1516 }
1517}
1518
1519fn current_subcompose_children(inner: &SubcomposeLayoutNodeInner) -> Vec<NodeId> {
1520 inner.last_placements.clone()
1521}
1522
1523struct SubcomposeLayoutNodeInner {
1524 modifier: Modifier,
1525 modifier_chain: ModifierChainHandle,
1526 resolved_modifiers: ResolvedModifiers,
1527 modifier_capabilities: NodeCapabilities,
1528 state: SubcomposeState,
1529 measure_policy: Rc<MeasurePolicy>,
1530 children: Vec<NodeId>,
1531 slots: Rc<SlotsHost>,
1532 debug_modifiers: bool,
1533 virtual_nodes: HashMap<NodeId, Rc<LayoutNode>>,
1534 node_id: Option<NodeId>,
1535 last_placements: Vec<NodeId>,
1536 placement_scratch: Vec<Placement>,
1537 measured_children_scratch: Rc<RefCell<HashMap<NodeId, Rc<MeasuredNode>>>>,
1538 captured_context: Option<cranpose_core::CapturedCompositionContext>,
1539 density: crate::density::Density,
1540}
1541
1542impl SubcomposeLayoutNodeInner {
1543 fn replace_placed_children<I>(&mut self, children: I)
1554 where
1555 I: IntoIterator<Item = NodeId>,
1556 {
1557 let mut changed = false;
1558 let mut count = 0usize;
1559 for child in children {
1560 match self.last_placements.get(count) {
1561 Some(&placed) if placed == child => {}
1562 Some(_) => {
1563 self.last_placements[count] = child;
1564 changed = true;
1565 }
1566 None => {
1567 self.last_placements.push(child);
1568 changed = true;
1569 }
1570 }
1571 count += 1;
1572 }
1573 if self.last_placements.len() > count {
1574 self.last_placements.truncate(count);
1575 changed = true;
1576 }
1577 if changed && let Some(id) = self.node_id {
1578 crate::render_state::record_geometry_scene_node(id);
1579 }
1580 }
1581
1582 fn new(measure_policy: Rc<MeasurePolicy>) -> Self {
1583 Self {
1584 modifier: Modifier::empty(),
1585 modifier_chain: ModifierChainHandle::new(),
1586 resolved_modifiers: ResolvedModifiers::default(),
1587 modifier_capabilities: NodeCapabilities::default(),
1588 state: SubcomposeState::default(),
1589 measure_policy,
1590 children: Vec::new(),
1591 slots: Rc::new(SlotsHost::new(SlotTable::default())),
1592 debug_modifiers: false,
1593 virtual_nodes: HashMap::new(),
1594 node_id: None,
1595 last_placements: Vec::new(),
1596 placement_scratch: Vec::new(),
1597 measured_children_scratch: Rc::new(RefCell::new(HashMap::default())),
1598 captured_context: None,
1599 density: crate::density::Density::default(),
1600 }
1601 }
1602
1603 fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
1604 self.measure_policy = policy;
1605 if let Err(err) = self.slots.reset() {
1606 log::error!(
1607 "failed to reset root measurement slots after measure policy update: {err}"
1608 );
1609 }
1610 }
1611
1612 fn set_modifier_collect(&mut self, modifier: Modifier) -> (Vec<ModifierInvalidation>, bool) {
1613 let modifier_changed = !self.modifier.structural_eq(&modifier);
1614 self.modifier = modifier;
1615 self.modifier_chain.set_debug_logging(self.debug_modifiers);
1616 let modifier_local_invalidations = self.modifier_chain.update(&self.modifier);
1617 self.resolved_modifiers = self.modifier_chain.resolved_modifiers();
1618 self.modifier_capabilities = self.modifier_chain.capabilities();
1619
1620 let mut invalidations = self.modifier_chain.take_invalidations();
1621 invalidations.extend(modifier_local_invalidations);
1622
1623 (invalidations, modifier_changed)
1624 }
1625
1626 fn set_debug_modifiers(&mut self, enabled: bool) {
1627 self.debug_modifiers = enabled;
1628 self.modifier_chain.set_debug_logging(enabled);
1629 }
1630}
1631
1632#[cfg(test)]
1633#[path = "tests/subcompose_layout_tests.rs"]
1634mod tests;