1use std::{
2 cell::{Cell, Ref, RefCell, RefMut},
3 rc::Rc,
4};
5
6use cranpose_core::{
7 ApplierHost, CapturedCompositionContext, Composer, NodeError, NodeId, RuntimeHandle, SlotId,
8 SlotTable, SlotsHost, SubcomposeState, collections::map::HashMap,
9};
10use cranpose_foundation::{
11 InvalidationKind, ModifierInvalidation, ModifierInvalidations, NodeCapabilities,
12 SemanticsConfiguration,
13 lazy::{LazyItemRoots, SmallNodeVec},
14};
15pub use cranpose_ui_layout::{Constraints, MeasureResult, Placement};
16use smallvec::SmallVec;
17use web_time::Instant;
18
19use crate::{
20 layout::MeasuredNode,
21 modifier::{
22 ElementMatch, Modifier, ModifierChainHandle, ModifierNodeSlices, ResolvedModifiers, Size,
23 },
24 render_state::AppContext,
25 widgets::nodes::{ChildPlacement, LayoutNode, LayoutParts, LayoutState, NodeCache},
26};
27
28mod measure_scratch;
29mod retained_measure_scope;
30mod retained_slot_children;
31mod subcompose_child;
32
33pub(crate) use measure_scratch::MeasureScratch;
34pub(crate) use retained_measure_scope::RetainedMeasureScope;
35pub(crate) use retained_slot_children::RetainedSlotChildren;
36pub(crate) use subcompose_child::SubcomposeChild;
37
38fn subcompose_telemetry_enabled() -> bool {
39 cranpose_core::DIAGNOSTICS.subcompose_telemetry.is_set()
40}
41
42pub(crate) type SubcomposePlaceable = cranpose_ui_layout::Placeable;
43
44type RetainedMeasureLookup<'a> = Box<dyn FnMut(NodeId) -> Option<MeasuredNode> + 'a>;
45
46pub(crate) type MeasuredChildren = RefCell<HashMap<NodeId, MeasuredNode>>;
48
49pub(crate) trait PlacedRootsScope: cranpose_ui_layout::MeasureScope {
53 fn reusable_slots_count(&self) -> usize;
55
56 fn scratch(&mut self) -> &mut MeasureScratch;
58
59 fn layout_with_placed_roots(
64 &mut self,
65 width: f32,
66 height: f32,
67 build: impl FnOnce(&mut Vec<Placement>, &mut Vec<Rc<LazyItemRoots>>),
68 ) -> MeasureResult {
69 self.scratch()
70 .layout_with_placed_roots(width, height, build)
71 }
72}
73
74pub(crate) struct MeasureCallbacks<'a> {
75 pub(crate) measurer: Box<dyn FnMut(NodeId, Constraints) -> SubcomposePlaceable + 'a>,
76 pub(crate) retained_measure_lookup: RetainedMeasureLookup<'a>,
77 pub(crate) error: &'a RefCell<Option<NodeError>>,
78}
79
80pub trait SubcomposeLayoutScope: cranpose_ui_layout::MeasureScope {
82 fn constraints(&self) -> Constraints;
84
85 fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
88 where
89 I: IntoIterator<Item = Placement>,
90 {
91 MeasureResult::new(Size { width, height }, placements.into_iter().collect())
92 }
93}
94
95pub trait SubcomposeMeasureScope: SubcomposeLayoutScope {
97 fn subcompose<K, Content>(
112 &mut self,
113 slot_id: SlotId,
114 key: K,
115 content: Content,
116 ) -> Vec<SubcomposeChild>
117 where
118 K: PartialEq + 'static,
119 Content: FnMut() + 'static;
120
121 fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable;
123
124 fn node_has_no_parent(&self, node_id: NodeId) -> bool;
127}
128
129pub struct SubcomposeMeasureScopeImpl<'a> {
131 composer: Composer,
132 density_scope: crate::density::DensityMeasureScope,
133 state: &'a mut SubcomposeState,
134 constraints: Constraints,
135 measurer: Box<dyn FnMut(NodeId, Constraints) -> SubcomposePlaceable + 'a>,
136 retained_measure_lookup: RetainedMeasureLookup<'a>,
137 error: &'a RefCell<Option<NodeError>>,
138 parent_handle: SubcomposeLayoutNodeHandle,
139 root_id: NodeId,
140 scratch: MeasureScratch,
141 pending_commands_applied: bool,
142 #[cfg(debug_assertions)]
143 shadow_stash: Option<(Vec<NodeId>, SmallNodeVec)>,
144}
145
146fn record_clean_slot_skip() {
147 crate::thread_state::cells(|cells| {
148 cells.clean_slot_skips.set(cells.clean_slot_skips.get() + 1);
149 });
150}
151
152pub fn clean_slot_skip_count() -> u64 {
156 crate::thread_state::cells(|cells| cells.clean_slot_skips.get())
157}
158
159pub fn retained_measure_count() -> u64 {
164 crate::thread_state::cells(|cells| cells.retained_measures.get())
165}
166
167struct SubcomposeMeasureScopeInit<'a> {
168 composer: Composer,
169 density: crate::density::Density,
170 state: &'a mut SubcomposeState,
171 constraints: Constraints,
172 measurer: Box<dyn FnMut(NodeId, Constraints) -> SubcomposePlaceable + 'a>,
173 retained_measure_lookup: RetainedMeasureLookup<'a>,
174 error: &'a RefCell<Option<NodeError>>,
175 parent_handle: SubcomposeLayoutNodeHandle,
176 root_id: NodeId,
177 scratch: MeasureScratch,
178}
179
180impl<'a> SubcomposeMeasureScopeImpl<'a> {
181 pub(crate) fn root_id(&self) -> NodeId {
182 self.root_id
183 }
184
185 fn new(init: SubcomposeMeasureScopeInit<'a>) -> Self {
186 Self {
187 composer: init.composer,
188 density_scope: crate::density::DensityMeasureScope::new(init.density),
189 state: init.state,
190 constraints: init.constraints,
191 measurer: init.measurer,
192 retained_measure_lookup: init.retained_measure_lookup,
193 error: init.error,
194 parent_handle: init.parent_handle,
195 root_id: init.root_id,
196 scratch: init.scratch,
197 pending_commands_applied: false,
198 #[cfg(debug_assertions)]
199 shadow_stash: None,
200 }
201 }
202
203 fn into_scratch(self) -> MeasureScratch {
204 self.scratch
205 }
206
207 pub(crate) fn layout_with_placement_builder(
208 &mut self,
209 width: f32,
210 height: f32,
211 build: impl FnOnce(&mut Vec<Placement>),
212 ) -> MeasureResult {
213 self.scratch.placements.clear();
214 self.scratch.placed_roots.clear();
215 build(&mut self.scratch.placements);
216 MeasureResult::new(
217 Size { width, height },
218 std::mem::take(&mut self.scratch.placements),
219 )
220 }
221
222 fn record_error(&self, err: NodeError) {
223 let mut slot = self.error.borrow_mut();
224 if slot.is_none() {
225 log::warn!("[SubcomposeLayout] Error suppressed: {err:?}");
226 *slot = Some(err);
227 }
228 }
229
230 fn owner_chain_deactivation_epoch(&self) -> u64 {
231 self.parent_handle
232 .inner
233 .borrow()
234 .captured_context
235 .as_ref()
236 .map_or(
237 0,
238 CapturedCompositionContext::owner_chain_deactivation_epoch,
239 )
240 }
241
242 fn ensure_pending_commands_applied(&mut self) -> bool {
243 if self.pending_commands_applied {
244 return true;
245 }
246
247 let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
248 if let Err(err) = self.composer.apply_pending_commands() {
249 self.record_error(err);
250 return false;
251 }
252 if let Some(start) = telemetry_start {
253 log::warn!(
254 "[subcompose-telemetry] apply_pending_commands_ms={:.2}",
255 start.elapsed().as_secs_f64() * 1000.0
256 );
257 }
258
259 self.pending_commands_applied = true;
260 true
261 }
262
263 fn perform_subcompose<Content>(&mut self, slot_id: SlotId, content: Content) -> SmallNodeVec
264 where
265 Content: FnMut() + 'static,
266 {
267 let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
268 let context = crate::render_state::current_app_context();
271 let _paused = context
272 .as_ref()
273 .map(|context| context.measure_reads.paused());
274 let (virtual_node_id, is_rebound) =
275 if let Some((node_id, rebound)) = self.state.take_node_from_reusables(slot_id) {
276 (node_id, rebound)
277 } else {
278 let id = self
279 .composer
280 .create_virtual_node(Box::new(LayoutNode::new_virtual()));
281 self.parent_handle.inner.borrow_mut().children.push(id);
282 (id, false)
283 };
284
285 let children = self.compose_into_slot(slot_id, virtual_node_id, content);
286 if is_rebound {
287 self.composer.record_rebound_slot_children(&children);
288 }
289 if let Some(start) = telemetry_start {
290 log::warn!(
291 "[subcompose-telemetry] slot={} reused={} children={} subcompose_ms={:.2}",
292 slot_id.raw(),
293 is_rebound,
294 children.len(),
295 start.elapsed().as_secs_f64() * 1000.0
296 );
297 }
298 children
299 }
300
301 fn compose_into_slot<Content>(
302 &mut self,
303 slot_id: SlotId,
304 virtual_node_id: NodeId,
305 content: Content,
306 ) -> SmallNodeVec
307 where
308 Content: FnMut() + 'static,
309 {
310 let content_holder = self.state.callback_holder(slot_id);
311 content_holder.update(content);
312
313 let _ = self
314 .composer
315 .with_node_mut::<LayoutNode, _>(virtual_node_id, |node| {
316 node.set_parent(self.root_id);
317 });
318
319 let slot_host = self.state.get_or_create_slots(slot_id);
320 self.parent_handle.note_slot_host(&slot_host);
321 let locals_stale = self.state.slot_locals_stale(slot_id);
322 let scopes = self
323 .composer
324 .with_locals_changed(locals_stale, |composer| {
325 composer.subcompose_slot(&slot_host, Some(virtual_node_id), move |_| {
326 compose_subcompose_slot_content(content_holder);
327 })
328 })
329 .map_or_default(|((), scopes)| scopes);
330 self.pending_commands_applied = false;
331
332 let owner_epoch = self.owner_chain_deactivation_epoch();
333 self.state
334 .register_active(slot_id, &[virtual_node_id], &scopes);
335 self.state.mark_slot_composed_current(slot_id, owner_epoch);
336
337 self.composer
338 .get_node_children(virtual_node_id)
339 .into_iter()
340 .collect()
341 }
342}
343
344impl SubcomposeLayoutScope for SubcomposeMeasureScopeImpl<'_> {
345 fn constraints(&self) -> Constraints {
346 self.constraints
347 }
348
349 fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
350 where
351 I: IntoIterator<Item = Placement>,
352 {
353 self.layout_with_placement_builder(width, height, |scratch| {
354 scratch.extend(placements);
355 })
356 }
357}
358
359impl cranpose_ui_layout::MeasureScope for SubcomposeMeasureScopeImpl<'_> {
360 fn density(&self) -> f32 {
361 self.density_scope.density()
362 }
363
364 fn font_scale(&self) -> f32 {
365 self.density_scope.font_scale()
366 }
367}
368
369impl PlacedRootsScope for SubcomposeMeasureScopeImpl<'_> {
370 fn reusable_slots_count(&self) -> usize {
371 self.state.reusable_slots_count()
372 }
373
374 fn scratch(&mut self) -> &mut MeasureScratch {
375 &mut self.scratch
376 }
377}
378
379impl SubcomposeMeasureScope for SubcomposeMeasureScopeImpl<'_> {
380 fn subcompose<K, Content>(
381 &mut self,
382 slot_id: SlotId,
383 key: K,
384 content: Content,
385 ) -> Vec<SubcomposeChild>
386 where
387 K: PartialEq + 'static,
388 Content: FnMut() + 'static,
389 {
390 self.subcompose_roots(slot_id, key, content)
391 .into_iter()
392 .map(SubcomposeChild::new)
393 .collect()
394 }
395
396 fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable {
397 if self.error.borrow().is_some() {
398 return SubcomposePlaceable::value(0.0, 0.0, child.node_id());
399 }
400
401 let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
402 if !self.ensure_pending_commands_applied() {
403 return SubcomposePlaceable::value(0.0, 0.0, child.node_id());
404 }
405
406 let placeable = (self.measurer)(child.node_id(), constraints);
407 if let Some(start) = telemetry_start {
408 log::warn!(
409 "[subcompose-telemetry] child={} measure_ms={:.2} size=({:.2},{:.2})",
410 child.node_id(),
411 start.elapsed().as_secs_f64() * 1000.0,
412 placeable.width(),
413 placeable.height()
414 );
415 }
416 placeable
417 }
418
419 fn node_has_no_parent(&self, node_id: NodeId) -> bool {
420 self.composer.node_has_no_parent(node_id)
421 }
422}
423
424impl SubcomposeMeasureScopeImpl<'_> {
425 pub fn active_slots_count(&self) -> usize {
429 self.state.active_slots_count()
430 }
431
432 pub fn reusable_slots_count(&self) -> usize {
436 self.state.reusable_slots_count()
437 }
438
439 pub(crate) fn slot_is_retained(&self, slot_id: SlotId) -> bool {
441 self.state.slot_is_retained(slot_id)
442 }
443
444 pub(crate) fn slot_is_active(&self, slot_id: SlotId) -> bool {
445 self.state.slot_is_active(slot_id)
446 }
447
448 pub fn register_content_type(&mut self, slot_id: SlotId, content_type: u64) {
454 self.state.register_content_type(slot_id, content_type);
455 }
456
457 pub fn update_content_type(&mut self, slot_id: SlotId, content_type: Option<u64>) {
463 self.state.update_content_type(slot_id, content_type);
464 }
465
466 pub(crate) fn set_reusable_pool_limits(&mut self, per_type: usize, untyped: usize) {
467 self.state.set_reusable_pool_limits(per_type, untyped);
468 }
469
470 pub(crate) fn focused_slot(&self) -> Option<SlotId> {
471 let mut node_id = crate::active_focus_target()?;
472 while node_id != self.root_id {
473 if let Some(slot) = self.state.active_slot_for_node(node_id) {
474 return Some(slot);
475 }
476 node_id = self.composer.node_parent(node_id).ok()??;
477 }
478 None
479 }
480
481 pub(crate) fn recycle_active_slots_where(&mut self, predicate: impl FnMut(SlotId) -> bool) {
482 let disposed = self.state.recycle_active_slots_where(predicate);
483 if let Err(error) = self.composer.dispose_subcomposed_nodes(disposed) {
484 self.record_error(error);
485 }
486 }
487
488 pub fn was_last_slot_reused(&self) -> Option<bool> {
496 self.state.was_last_slot_reused()
497 }
498
499 pub(crate) fn measure_retained(
500 &mut self,
501 node_id: NodeId,
502 constraints: Constraints,
503 ) -> (SubcomposePlaceable, Option<MeasuredNode>) {
504 let placeable = self.measure(SubcomposeChild::new(node_id), constraints);
505 let retained = (self.retained_measure_lookup)(node_id);
506 (placeable, retained)
507 }
508
509 pub(crate) fn children_need_relayout(&mut self, children: &[NodeId]) -> bool {
510 if !self.ensure_pending_commands_applied() {
511 return true;
512 }
513
514 self.composer.nodes_need_relayout(children.iter().copied())
515 }
516}
517
518fn compose_subcompose_slot_content(holder: cranpose_core::CallbackHolder) {
519 cranpose_core::with_current_composer(|composer| {
520 let holder_for_recompose = holder.clone();
521 composer.set_recompose_callback(move |_composer| {
522 compose_subcompose_slot_content(holder_for_recompose.clone());
523 });
524 });
525
526 let invoke = holder.clone_rc();
527 invoke();
528}
529
530pub(crate) type MeasurePolicy =
531 dyn for<'scope> Fn(&mut SubcomposeMeasureScopeImpl<'scope>, Constraints) -> MeasureResult;
532
533pub(crate) type RetainedMeasurePolicy =
537 dyn for<'scope> Fn(&mut RetainedMeasureScope<'scope>, Constraints) -> Option<MeasureResult>;
538
539pub struct SubcomposeLayoutNode {
541 inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
542 modifier_chain: ModifierChainHandle,
543 modifier_capabilities: NodeCapabilities,
544 debug_modifiers: bool,
545 parent: Cell<Option<NodeId>>,
546 id: Cell<Option<NodeId>>,
547 needs_semantics: Cell<bool>,
548 needs_redraw: Cell<bool>,
549 needs_pointer_pass: Cell<bool>,
550 needs_focus_sync: Cell<bool>,
551 parts: Rc<LayoutParts>,
552 modifier_slices_snapshot: crate::modifier::SlicesSnapshot,
553 modifier_slices_dirty: Cell<bool>,
554}
555
556impl SubcomposeLayoutNode {
557 pub fn new(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
559 let inner = Rc::new(RefCell::new(SubcomposeLayoutNodeInner::new(measure_policy)));
560 let mut node = Self {
561 inner,
562 modifier_chain: ModifierChainHandle::detached(crate::LayoutDirection::Ltr),
563 modifier_capabilities: NodeCapabilities::default(),
564 debug_modifiers: false,
565 parent: Cell::new(None),
566 id: Cell::new(None),
567 needs_semantics: Cell::new(true),
568 needs_redraw: Cell::new(true),
569 needs_pointer_pass: Cell::new(false),
570 needs_focus_sync: Cell::new(false),
571 parts: Rc::new(LayoutParts::empty()),
572 modifier_slices_snapshot: crate::modifier::SlicesSnapshot::default(),
573 modifier_slices_dirty: Cell::new(true),
574 };
575 let (invalidations, _) = node.set_modifier_collect(modifier);
576 node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
577 node.note_host_to_the_composition_that_made_it();
578 node
579 }
580
581 fn note_host_to_the_composition_that_made_it(&self) {
582 let host = Rc::clone(&self.inner.borrow().slots);
583 cranpose_core::note_nested_slots_host(&host);
584 }
585
586 pub fn with_content_type_policy(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
592 let mut inner_data = SubcomposeLayoutNodeInner::new(measure_policy);
593 inner_data
594 .state
595 .set_policy(Box::new(cranpose_core::ContentTypeReusePolicy));
596 let inner = Rc::new(RefCell::new(inner_data));
597 let mut node = Self {
598 inner,
599 modifier_chain: ModifierChainHandle::detached(crate::LayoutDirection::Ltr),
600 modifier_capabilities: NodeCapabilities::default(),
601 debug_modifiers: false,
602 parent: Cell::new(None),
603 id: Cell::new(None),
604 needs_semantics: Cell::new(true),
605 needs_redraw: Cell::new(true),
606 needs_pointer_pass: Cell::new(false),
607 needs_focus_sync: Cell::new(false),
608 parts: Rc::new(LayoutParts::empty()),
609 modifier_slices_snapshot: crate::modifier::SlicesSnapshot::default(),
610 modifier_slices_dirty: Cell::new(true),
611 };
612 let (invalidations, _) = node.set_modifier_collect(modifier);
613 node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
614 node.note_host_to_the_composition_that_made_it();
615 node
616 }
617
618 pub fn handle(&self) -> SubcomposeLayoutNodeHandle {
620 SubcomposeLayoutNodeHandle {
621 inner: Rc::clone(&self.inner),
622 }
623 }
624
625 #[doc(hidden)]
626 pub fn debug_scope_ids_by_slot(&self) -> Vec<(u64, Vec<usize>)> {
627 self.inner.borrow().state.debug_scope_ids_by_slot()
628 }
629
630 #[doc(hidden)]
631 pub fn debug_slot_table_for_slot(
632 &self,
633 slot_id: SlotId,
634 ) -> Option<Vec<cranpose_core::SlotDebugEntry>> {
635 self.inner.borrow().state.debug_slot_table_for_slot(slot_id)
636 }
637
638 #[doc(hidden)]
639 pub fn debug_slot_table_groups_for_slot(
640 &self,
641 slot_id: SlotId,
642 ) -> Option<Vec<cranpose_core::subcompose::DebugSlotGroup>> {
643 self.inner
644 .borrow()
645 .state
646 .debug_slot_table_groups_for_slot(slot_id)
647 }
648
649 pub fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
652 let mut inner = self.inner.borrow_mut();
653 if Rc::ptr_eq(&inner.measure_policy, &policy) {
654 return;
655 }
656 inner.set_measure_policy(policy);
657 drop(inner);
658 self.invalidate_subcomposition();
659 }
660
661 pub(crate) fn set_retained_measure_policy(&mut self, policy: Rc<RetainedMeasurePolicy>) {
665 self.inner.borrow_mut().retained_measure_policy = Some(policy);
666 }
667
668 pub fn set_captured_context(&mut self, context: CapturedCompositionContext) {
673 let locals_changed = context.locals_changed();
674 self.inner.borrow_mut().captured_context = Some(context);
675 if locals_changed {
676 self.inner.borrow().state.invalidate_locals();
677 self.request_measure_recompose();
678 }
679 }
680
681 pub fn set_density(&mut self, density: crate::density::Density) {
687 let mut inner = self.inner.borrow_mut();
688 if inner.density != density {
689 inner.density = density;
690 drop(inner);
691 self.modifier_slices_dirty.set(true);
692 self.mark_needs_measure();
693 }
694 }
695
696 pub fn set_layout_direction(&mut self, direction: crate::LayoutDirection) {
698 if self.modifier_chain.set_layout_direction(direction) {
699 self.modifier_slices_dirty.set(true);
700 self.mark_needs_measure();
701 }
702 }
703
704 pub fn set_modifier(&mut self, modifier: Modifier) {
707 let prev_caps = self.modifier_capabilities;
708 let (invalidations, modifier_changed) = self.set_modifier_collect(modifier);
709 self.dispatch_modifier_invalidations(&invalidations, prev_caps);
710 self.modifier_slices_dirty.set(true);
711 crate::modal_nodes::reach_changed(self.id.get());
712 if modifier_changed {
713 self.request_semantics_update();
714 }
715 }
716
717 fn set_modifier_collect(&mut self, modifier: Modifier) -> (ModifierInvalidations, bool) {
718 let modifier_changed = !self
719 .modifier_chain
720 .holds(&modifier, ElementMatch::Structural);
721 self.modifier_chain.set_debug_logging(self.debug_modifiers);
722 let invalidations = self.modifier_chain.update_on_node(self.id.get(), &modifier);
723 self.modifier_capabilities = self.modifier_chain.capabilities();
724
725 (invalidations, modifier_changed)
726 }
727
728 fn update_modifier_slices_cache(&self) {
729 let density = self.inner.borrow().density.density();
730 self.modifier_slices_snapshot.collect(
731 self.modifier_chain.chain(),
732 Some(&self.parts),
733 density,
734 );
735 self.modifier_slices_dirty.set(false);
736 }
737
738 pub(crate) fn begin_measure(
739 &self,
740 constraints: Constraints,
741 ) -> crate::layout::SubcomposeMeasureStart {
742 let (density, measured_children) = {
743 let inner = self.inner.borrow();
744 (inner.density, Rc::clone(&inner.measured_children_scratch))
745 };
746 let plan = self.parts.runtime_state().borrow_mut().bind_subcompose(
747 density,
748 &self.modifier_chain,
749 constraints,
750 );
751 measured_children.borrow_mut().clear();
752 self.cache().clear_measurement();
753 crate::layout::SubcomposeMeasureStart::new(
754 self.handle(),
755 Rc::clone(&self.parts),
756 plan,
757 measured_children,
758 )
759 }
760
761 pub(crate) fn mark_modifier_slices_dirty(&self) {
762 self.modifier_slices_dirty.set(true);
763 }
764
765 pub fn set_debug_modifiers(&mut self, enabled: bool) {
767 self.debug_modifiers = enabled;
768 self.modifier_chain.set_debug_logging(enabled);
769 }
770
771 pub fn modifier(&self) -> Modifier {
773 self.modifier_chain.modifier()
774 }
775
776 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
778 self.modifier_chain.resolved_modifiers()
779 }
780
781 pub(crate) fn parent_data(&self) -> crate::modifier::SharedParentData {
783 self.modifier_chain.parent_data()
784 }
785
786 pub fn layout_state(&self) -> LayoutState {
788 self.parts.layout_state().snapshot()
789 }
790
791 pub(crate) fn cache(&self) -> &NodeCache {
792 self.parts.cache()
793 }
794
795 pub(crate) fn layout_parts(&self) -> &Rc<LayoutParts> {
796 &self.parts
797 }
798
799 pub(crate) fn place(&self, at: ChildPlacement, placer: Option<NodeId>, context: &AppContext) {
803 self.parts.place(self.id.get(), at, placer, context);
804 }
805
806 pub fn set_measured_size(&self, size: Size, context: &AppContext) {
809 self.parts.set_size(self.id.get(), size, context);
810 }
811
812 pub fn clear_placed(&self, context: &AppContext) {
814 self.parts.clear_placed(self.id.get(), context);
815 }
816
817 pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
819 crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
820 }
821
822 pub fn semantics_reach(&self) -> cranpose_foundation::SemanticsReach {
824 crate::modifier::semantics_reach_of_chain(self.modifier_chain.chain())
825 }
826
827 pub(crate) fn with_modifier_chain<R>(&self, read: impl FnOnce(&ModifierChainHandle) -> R) -> R {
829 read(&self.modifier_chain)
830 }
831
832 pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
834 if self.modifier_slices_dirty.get() {
835 self.update_modifier_slices_cache();
836 }
837 self.modifier_slices_snapshot.get()
838 }
839
840 pub fn state(&self) -> Ref<'_, SubcomposeState> {
842 Ref::map(self.inner.borrow(), |inner| &inner.state)
843 }
844
845 pub fn state_mut(&self) -> RefMut<'_, SubcomposeState> {
847 RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.state)
848 }
849
850 pub fn invalidate_subcomposition(&self) {
853 self.inner.borrow().state.invalidate_scopes();
854 self.mark_needs_measure();
855 if let Some(id) = self.id.get() {
856 cranpose_core::bubble_measure_dirty_in_composer(id);
857 }
858 }
859
860 pub fn request_measure_recompose(&self) {
863 self.mark_needs_measure();
864 if let Some(id) = self.id.get() {
865 cranpose_core::bubble_measure_dirty_in_composer(id);
866 }
867 }
868
869 pub fn with_active_children<R>(&self, f: impl FnOnce(&[NodeId]) -> R) -> R {
874 let children = Rc::clone(&self.inner.borrow().last_placements);
875 f(&children)
876 }
877
878 pub fn mark_needs_measure(&self) {
880 self.parts.cache().mark_needs_measure();
881 }
882
883 pub fn mark_needs_layout_flag(&self) {
885 self.parts.cache().mark_needs_layout();
886 }
887
888 pub fn mark_needs_redraw(&self) {
890 self.needs_redraw.set(true);
891 if let Some(id) = self.id.get() {
892 crate::schedule_draw_repass(id);
893 }
894 crate::request_render_invalidation();
895 }
896
897 pub fn needs_measure(&self) -> bool {
899 self.parts.cache().dirt().measure
900 }
901
902 pub(crate) fn clear_needs_layout(&self) {
905 self.parts.cache().clear_layout_dirt();
906 }
907
908 pub fn mark_needs_semantics(&self) {
910 self.needs_semantics.set(true);
911 crate::modal_nodes::reach_changed(self.id.get());
912 }
913
914 pub(crate) fn id(&self) -> Option<NodeId> {
916 self.id.get()
917 }
918
919 pub(crate) fn clear_needs_semantics(&self) {
920 self.needs_semantics.set(false);
921 }
922
923 #[cfg(test)]
924 pub(crate) fn clear_needs_semantics_for_tests(&self) {
925 self.clear_needs_semantics();
926 }
927
928 pub fn needs_redraw(&self) -> bool {
930 self.needs_redraw.get()
931 }
932
933 pub fn clear_needs_redraw(&self) {
935 self.needs_redraw.set(false);
936 }
937
938 pub fn mark_needs_pointer_pass(&self) {
940 self.needs_pointer_pass.set(true);
941 }
942
943 pub fn needs_pointer_pass(&self) -> bool {
945 self.needs_pointer_pass.get()
946 }
947
948 pub fn clear_needs_pointer_pass(&self) {
950 self.needs_pointer_pass.set(false);
951 }
952
953 pub fn mark_needs_focus_sync(&self) {
955 self.needs_focus_sync.set(true);
956 }
957
958 pub fn needs_focus_sync(&self) -> bool {
960 self.needs_focus_sync.get()
961 }
962
963 pub fn clear_needs_focus_sync(&self) {
965 self.needs_focus_sync.set(false);
966 }
967
968 fn request_semantics_update(&self) {
969 let already_dirty = self.needs_semantics.replace(true);
970 if already_dirty {
971 return;
972 }
973
974 if let Some(id) = self.id.get() {
975 cranpose_core::queue_semantics_invalidation(id);
976 }
977 }
978
979 pub fn modifier_capabilities(&self) -> NodeCapabilities {
981 self.modifier_capabilities
982 }
983
984 pub fn has_layout_modifier_nodes(&self) -> bool {
986 self.modifier_capabilities()
987 .contains(NodeCapabilities::LAYOUT)
988 }
989
990 pub fn has_draw_modifier_nodes(&self) -> bool {
992 self.modifier_capabilities()
993 .contains(NodeCapabilities::DRAW)
994 }
995
996 pub fn has_pointer_input_modifier_nodes(&self) -> bool {
998 self.modifier_capabilities()
999 .contains(NodeCapabilities::POINTER_INPUT)
1000 }
1001
1002 pub fn has_semantics_modifier_nodes(&self) -> bool {
1004 self.modifier_capabilities()
1005 .contains(NodeCapabilities::SEMANTICS)
1006 }
1007
1008 pub fn has_focus_modifier_nodes(&self) -> bool {
1010 self.modifier_capabilities()
1011 .contains(NodeCapabilities::FOCUS)
1012 }
1013
1014 fn dispatch_modifier_invalidations(
1015 &self,
1016 invalidations: &[ModifierInvalidation],
1017 prev_caps: NodeCapabilities,
1018 ) {
1019 let curr_caps = self.modifier_capabilities();
1020 for invalidation in invalidations {
1021 self.modifier_slices_dirty.set(true);
1022 let invalidation_caps = invalidation.capabilities();
1023 let has_capability = |capability| {
1024 curr_caps.contains(capability)
1025 || prev_caps.contains(capability)
1026 || invalidation_caps.contains(capability)
1027 };
1028 match invalidation.kind() {
1029 InvalidationKind::Layout => {
1030 if has_capability(NodeCapabilities::LAYOUT) {
1031 self.mark_needs_measure();
1032 }
1033 }
1034 InvalidationKind::Draw => {
1035 if has_capability(NodeCapabilities::DRAW) {
1036 self.mark_needs_redraw();
1037 }
1038 }
1039 InvalidationKind::PointerInput => {
1040 if has_capability(NodeCapabilities::POINTER_INPUT) {
1041 self.mark_needs_pointer_pass();
1042 crate::request_pointer_invalidation();
1043 if let Some(id) = self.id.get() {
1044 crate::schedule_pointer_repass(id);
1045 }
1046 }
1047 }
1048 InvalidationKind::Semantics => {
1049 self.request_semantics_update();
1050 }
1051 InvalidationKind::Focus => {
1052 if has_capability(NodeCapabilities::FOCUS) {
1053 self.mark_needs_focus_sync();
1054 crate::request_focus_invalidation();
1055 if let Some(id) = self.id.get() {
1056 crate::schedule_focus_invalidation(id);
1057 }
1058 }
1059 }
1060 }
1061 }
1062 }
1063}
1064
1065impl cranpose_core::Node for SubcomposeLayoutNode {
1066 fn mount(&mut self) {
1067 self.modifier_chain.remount(self.id.get());
1068 crate::modal_nodes::reach_changed(self.id.get());
1069 }
1070
1071 fn unmount(&mut self) {
1072 self.modifier_chain.chain_mut().detach_nodes();
1073 if let Some(node_id) = self.id.get()
1074 && let Some(context) = crate::render_state::current_app_context()
1075 {
1076 context.measure_reads.forget(node_id);
1077 }
1078 }
1079
1080 fn insert_child(&mut self, child: NodeId) -> bool {
1081 let mut inner = self.inner.borrow_mut();
1082 if inner.children.contains(&child) {
1083 return false;
1084 }
1085 inner.children.push(child);
1086 true
1087 }
1088
1089 fn remove_child(&mut self, child: NodeId) -> bool {
1090 let mut inner = self.inner.borrow_mut();
1091 let at = inner.children.iter().rposition(|&id| id == child);
1092 at.map(|at| inner.children.remove(at)).is_some()
1093 }
1094
1095 fn move_child(&mut self, from: usize, to: usize) {
1096 let mut inner = self.inner.borrow_mut();
1097 if from == to || from >= inner.children.len() {
1098 return;
1099 }
1100 let child = inner.children.remove(from);
1101 let target = to.min(inner.children.len());
1102 inner.children.insert(target, child);
1103 }
1104
1105 fn update_children(&mut self, children: &[NodeId]) {
1106 let mut inner = self.inner.borrow_mut();
1107 inner.children.clear();
1108 inner.children.extend_from_slice(children);
1109 }
1110
1111 fn keeps_own_children(&self) -> bool {
1115 true
1116 }
1117
1118 fn collect_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1119 out.clear();
1120 self.with_active_children(|children| out.extend_from_slice(children));
1121 }
1122
1123 fn collect_owned_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1124 out.clear();
1125 out.extend_from_slice(&self.inner.borrow().children);
1126 }
1127
1128 fn owned_child_index(&self, child: NodeId) -> Option<usize> {
1129 self.inner
1130 .borrow()
1131 .children
1132 .iter()
1133 .position(|&id| id == child)
1134 }
1135
1136 fn set_node_id(&mut self, id: NodeId) {
1137 let previous = self.id.replace(Some(id));
1138 self.inner.borrow_mut().node_id = Some(id);
1139 self.modifier_chain.move_to_node_later(previous, Some(id));
1140 self.modifier_slices_dirty.set(true);
1142 }
1143
1144 fn on_attached_to_parent(&mut self, parent: NodeId) {
1145 self.parent.set(Some(parent));
1146 }
1147
1148 fn on_removed_from_parent(&mut self) {
1149 self.parent.set(None);
1150 self.inner.borrow().state.bump_content_generation();
1151 }
1152
1153 fn parent(&self) -> Option<NodeId> {
1154 self.parent.get()
1155 }
1156
1157 fn mark_needs_layout(&self) {
1158 self.parts.cache().mark_needs_layout();
1159 }
1160
1161 fn needs_layout(&self) -> bool {
1162 self.parts.cache().dirt().layout
1163 }
1164
1165 fn mark_needs_measure(&self) {
1166 Self::mark_needs_measure(self);
1167 }
1168
1169 fn needs_measure(&self) -> bool {
1170 Self::needs_measure(self)
1171 }
1172
1173 fn mark_descendant_needs_layout(&self, measure: bool) {
1174 self.parts.cache().mark_descendant_needs_layout(measure);
1175 }
1176
1177 fn descendant_needs_layout(&self) -> bool {
1178 self.parts.cache().dirt().descendant.layout
1179 }
1180
1181 fn descendant_needs_measure(&self) -> bool {
1182 self.parts.cache().dirt().descendant.measure
1183 }
1184
1185 fn mark_needs_semantics(&self) {
1186 self.needs_semantics.set(true);
1187 crate::modal_nodes::reach_changed(self.id.get());
1188 }
1189
1190 fn mark_descendant_needs_semantics(&self) {
1193 self.needs_semantics.set(true);
1194 }
1195
1196 fn needs_semantics(&self) -> bool {
1197 self.needs_semantics.get()
1198 }
1199
1200 fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1201 if self.parent.get().is_none() {
1202 self.parent.set(Some(parent));
1203 }
1204 }
1205}
1206
1207#[derive(Clone)]
1208pub struct SubcomposeLayoutNodeHandle {
1209 inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
1210}
1211
1212impl SubcomposeLayoutNodeHandle {
1213 pub(crate) fn note_slot_host(&self, slot_host: &Rc<SlotsHost>) {
1214 let Ok(inner) = self.inner.try_borrow() else {
1215 return;
1216 };
1217 if Rc::ptr_eq(&inner.slots, slot_host) {
1218 return;
1219 }
1220 inner.slots.note_nested_host(slot_host);
1221 }
1222
1223 pub(crate) fn measure_retained(
1227 &self,
1228 applier: &dyn ApplierHost,
1229 node_id: NodeId,
1230 constraints: Constraints,
1231 ) -> Option<MeasureResult> {
1232 let (policy, state, mut scratch, density, owner_epoch) = {
1233 let mut inner = self.inner.borrow_mut();
1234 let policy = Rc::clone(inner.retained_measure_policy.as_ref()?);
1235 let owner_epoch = inner.captured_context.as_ref().map_or(
1236 0,
1237 CapturedCompositionContext::owner_chain_deactivation_epoch,
1238 );
1239 (
1240 policy,
1241 std::mem::take(&mut inner.state),
1242 std::mem::take(&mut inner.measure_scratch),
1243 inner.density,
1244 owner_epoch,
1245 )
1246 };
1247 let result = policy(
1248 &mut RetainedMeasureScope::new(
1249 &state,
1250 applier,
1251 node_id,
1252 (density, owner_epoch),
1253 &mut scratch,
1254 ),
1255 constraints,
1256 );
1257 let mut inner = self.inner.borrow_mut();
1258 inner.state = state;
1259 inner.measure_scratch = scratch;
1260 if let Some(result) = &result {
1261 inner.replace_placed_children(
1262 result.placements.iter().map(|placement| placement.node_id),
1263 );
1264 crate::thread_state::cells(|cells| {
1265 cells
1266 .retained_measures
1267 .set(cells.retained_measures.get() + 1);
1268 });
1269 }
1270 result
1271 }
1272
1273 pub(crate) fn measure_with_callbacks(
1274 &self,
1275 applier: &Rc<dyn ApplierHost>,
1276 runtime: &RuntimeHandle,
1277 node_id: NodeId,
1278 constraints: Constraints,
1279 callbacks: MeasureCallbacks<'_>,
1280 ) -> Result<MeasureResult, NodeError> {
1281 let MeasureCallbacks {
1282 measurer,
1283 retained_measure_lookup,
1284 error,
1285 } = callbacks;
1286 let (policy, mut state, slots_host, scratch, captured_context, density) = {
1287 let mut inner = self.inner.borrow_mut();
1288 let policy = Rc::clone(&inner.measure_policy);
1289 let state = std::mem::take(&mut inner.state);
1290 let slots_host = Rc::clone(&inner.slots);
1291 let scratch = std::mem::take(&mut inner.measure_scratch);
1292 let captured_context = inner.captured_context.clone();
1293 let density = inner.density;
1294 (
1295 policy,
1296 state,
1297 slots_host,
1298 scratch,
1299 captured_context,
1300 density,
1301 )
1302 };
1303 state.begin_pass();
1304
1305 let constraints_copy = constraints;
1306 let fallback_context;
1307 let context = if let Some(context) = captured_context.as_ref() {
1308 context
1309 } else {
1310 fallback_context = CapturedCompositionContext::default();
1311 &fallback_context
1312 };
1313 let ((result, scratch), _) = Composer::subcompose_measure_slot(
1314 applier,
1315 runtime,
1316 &slots_host,
1317 node_id,
1318 context,
1319 |inner_composer| {
1320 let mut scope = SubcomposeMeasureScopeImpl::new(SubcomposeMeasureScopeInit {
1321 composer: inner_composer.clone(),
1322 density,
1323 state: &mut state,
1324 constraints: constraints_copy,
1325 measurer,
1326 retained_measure_lookup,
1327 error,
1328 parent_handle: self.clone(),
1329 root_id: node_id,
1330 scratch,
1331 });
1332 let result = (policy)(&mut scope, constraints_copy);
1333 (result, scope.into_scratch())
1334 },
1335 )?;
1336
1337 let disposed = state.finish_pass();
1338 let disposal = Composer::dispose_measure_subcomposed_nodes(applier, disposed);
1339
1340 {
1341 let mut inner = self.inner.borrow_mut();
1342 inner.state = state;
1343 inner.measure_scratch = scratch;
1344
1345 inner.replace_placed_children(
1346 result.placements.iter().map(|placement| placement.node_id),
1347 );
1348 }
1349
1350 disposal?;
1351 Ok(result)
1352 }
1353
1354 pub(crate) fn recycle_placement_scratch(&self, mut placements: Vec<Placement>) {
1355 placements.clear();
1356 let mut inner = self.inner.borrow_mut();
1357 if placements.capacity() > inner.measure_scratch.placements.capacity() {
1358 inner.measure_scratch.placements = placements;
1359 }
1360 }
1361
1362 pub(crate) fn take_placed_roots(&self) -> Vec<Rc<LazyItemRoots>> {
1367 std::mem::take(&mut self.inner.borrow_mut().measure_scratch.placed_roots)
1368 }
1369
1370 pub(crate) fn recycle_placed_roots(&self, mut placed_roots: Vec<Rc<LazyItemRoots>>) {
1371 placed_roots.clear();
1372 let mut inner = self.inner.borrow_mut();
1373 if placed_roots.capacity() > inner.measure_scratch.placed_roots.capacity() {
1374 inner.measure_scratch.placed_roots = placed_roots;
1375 }
1376 }
1377
1378 pub fn set_active_children<I>(&self, children: I)
1379 where
1380 I: IntoIterator<Item = NodeId>,
1381 {
1382 self.inner.borrow_mut().replace_placed_children(children);
1383 }
1384}
1385
1386struct SubcomposeLayoutNodeInner {
1387 state: SubcomposeState,
1388 measure_policy: Rc<MeasurePolicy>,
1389 retained_measure_policy: Option<Rc<RetainedMeasurePolicy>>,
1390 children: Vec<NodeId>,
1391 slots: Rc<SlotsHost>,
1392 node_id: Option<NodeId>,
1393 last_placements: Rc<Vec<NodeId>>,
1394 measure_scratch: MeasureScratch,
1395 measured_children_scratch: Rc<RefCell<HashMap<NodeId, MeasuredNode>>>,
1396 captured_context: Option<CapturedCompositionContext>,
1397 density: crate::density::Density,
1398}
1399
1400impl SubcomposeLayoutNodeInner {
1401 fn replace_placed_children<I>(&mut self, children: I)
1412 where
1413 I: IntoIterator<Item = NodeId>,
1414 {
1415 let mut children = children.into_iter();
1416 let mut kept = 0usize;
1417 let mut first_change = None;
1418 for child in children.by_ref() {
1419 if self.last_placements.get(kept) != Some(&child) {
1420 first_change = Some(child);
1421 break;
1422 }
1423 kept += 1;
1424 }
1425 let changed = if let Some(child) = first_change {
1426 let placements = Rc::make_mut(&mut self.last_placements);
1428 placements.truncate(kept);
1429 placements.push(child);
1430 placements.extend(children);
1431 true
1432 } else if self.last_placements.len() > kept {
1433 Rc::make_mut(&mut self.last_placements).truncate(kept);
1434 true
1435 } else {
1436 false
1437 };
1438 if changed && let Some(id) = self.node_id {
1439 crate::render_state::record_geometry_scene_node(id);
1440 }
1441 }
1442
1443 fn new(measure_policy: Rc<MeasurePolicy>) -> Self {
1444 Self {
1445 state: SubcomposeState::default(),
1446 measure_policy,
1447 retained_measure_policy: None,
1448 children: Vec::new(),
1449 slots: Rc::new(SlotsHost::new(SlotTable::default())),
1450 node_id: None,
1451 last_placements: Rc::new(Vec::new()),
1452 measure_scratch: MeasureScratch::default(),
1453 measured_children_scratch: Rc::new(RefCell::new(HashMap::default())),
1454 captured_context: None,
1455 density: crate::density::Density::default(),
1456 }
1457 }
1458
1459 fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
1460 self.measure_policy = policy;
1461 self.retained_measure_policy = None;
1462 if let Err(err) = self.slots.reset() {
1463 log::error!(
1464 "failed to reset root measurement slots after measure policy update: {err}"
1465 );
1466 }
1467 }
1468}
1469
1470#[cfg(test)]
1471#[path = "tests/subcompose_layout_tests.rs"]
1472pub(crate) mod tests;