Skip to main content

cranpose_ui/modifier/
slices.rs

1use std::{fmt, mem::size_of, rc::Rc};
2
3use cranpose_foundation::{ModifierNodeChain, NodeCapabilities, PointerEvent, PointerEventKind};
4use cranpose_ui_graphics::{
5    ColorFilter, EdgeInsets, GraphicsLayer, LayerShape, PointerIcon, Rect, RenderEffect,
6    RoundedCornerShape, Size,
7};
8use smallvec::SmallVec;
9
10use super::{
11    ModifierChainHandle, Point,
12    coordinator_geometry::{CoordinatorGeometry, CoordinatorRect},
13};
14use crate::{
15    draw::DrawCommand,
16    modifier::{
17        Modifier,
18        scroll::{MotionContextAnimatedNode, TranslatedContentContextNode},
19    },
20    modifier_nodes::{
21        BackgroundNode, ClipToBoundsNode, CornerShapeNode, DrawCommandNode, GraphicsLayerNode,
22        PaddingNode, PointerIconNode, SelectableTextNode, WindowRectReporterNode,
23    },
24    text::{TextLayoutOptions, TextStyle},
25    text_field_modifier_node::{TextFieldLayoutHandle, TextFieldModifierNode, TextPanResolver},
26    text_modifier_node::{TextModifierNode, TextPreparedLayoutHandle},
27};
28
29/// Snapshot of modifier node slices that impact draw and pointer subsystems.
30#[derive(Default)]
31pub struct ModifierNodeSlices {
32    draw_commands: Vec<DrawCommand>,
33    layer_draw_boundary: Option<usize>,
34    pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
35    pointer_input_sizes: Vec<Rc<std::cell::Cell<cranpose_ui_graphics::Size>>>,
36    pointer_icon: Option<PointerIcon>,
37    clip_to_bounds: bool,
38    /// Where the outermost clip or graphics layer of the chain sits: its
39    /// coordinator, which a later offset moves the content inside of.
40    layer_coordinator: Option<CoordinatorRect>,
41    motion_context_animated: bool,
42    translated_content_context: bool,
43    translated_content_context_identity: Option<usize>,
44    translated_content_offset_reader: Option<Rc<dyn Fn() -> Point>>,
45    text: Option<SliceText>,
46    text_coordinator: Option<CoordinatorRect>,
47    text_window_transform: Option<Rc<std::cell::Cell<cranpose_ui_graphics::ProjectiveTransform>>>,
48    viewport_window_rect: Option<Rc<dyn crate::modifier_nodes::WindowRectSink>>,
49    /// Boxed: few nodes carry a layer, and inline it took 240 bytes of
50    /// every node's slices.
51    graphics_layer: Option<Box<GraphicsLayer>>,
52    graphics_layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
53    corner_shape: Option<RoundedCornerShape>,
54    chain_guard: Option<Rc<ChainGuard>>,
55}
56
57struct ChainGuard {
58    _handle: ModifierChainHandle,
59}
60
61/// The text a node shows. A `Text`'s string, style and options are its
62/// prepared layout's, read from there rather than copied into every
63/// rebuild of the slices; a text field's are held here.
64#[derive(Clone)]
65enum SliceText {
66    Text(TextPreparedLayoutHandle),
67    Field(Rc<FieldText>),
68}
69
70struct FieldText {
71    content: Rc<crate::text::AnnotatedString>,
72    style: TextStyle,
73    layout: TextFieldLayoutHandle,
74    pan: Option<TextPanResolver>,
75}
76
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78pub struct ModifierNodeSlicesDebugStats {
79    pub draw_command_count: usize,
80    pub draw_command_capacity: usize,
81    pub pointer_input_count: usize,
82    pub pointer_input_capacity: usize,
83    pub has_text_content: bool,
84    pub has_text_style: bool,
85    pub has_text_layout_options: bool,
86    pub has_prepared_text_layout: bool,
87    pub has_graphics_layer: bool,
88    pub has_graphics_layer_resolver: bool,
89    pub heap_bytes: usize,
90}
91
92impl Clone for ModifierNodeSlices {
93    fn clone(&self) -> Self {
94        Self {
95            draw_commands: self.draw_commands.clone(),
96            layer_draw_boundary: self.layer_draw_boundary,
97            pointer_inputs: self.pointer_inputs.clone(),
98            pointer_input_sizes: self.pointer_input_sizes.clone(),
99            pointer_icon: self.pointer_icon.clone(),
100            clip_to_bounds: self.clip_to_bounds,
101            layer_coordinator: self.layer_coordinator.clone(),
102            motion_context_animated: self.motion_context_animated,
103            translated_content_context: self.translated_content_context,
104            translated_content_context_identity: self.translated_content_context_identity,
105            translated_content_offset_reader: self.translated_content_offset_reader.clone(),
106            text: self.text.clone(),
107            text_coordinator: self.text_coordinator.clone(),
108            text_window_transform: self.text_window_transform.clone(),
109            viewport_window_rect: self.viewport_window_rect.clone(),
110            graphics_layer: self.graphics_layer.clone(),
111            graphics_layer_resolver: self.graphics_layer_resolver.clone(),
112            corner_shape: self.corner_shape,
113            chain_guard: self.chain_guard.clone(),
114        }
115    }
116}
117
118fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
119    GraphicsLayer {
120        alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
121        scale: base.scale * overlay.scale,
122        scale_x: base.scale_x * overlay.scale_x,
123        scale_y: base.scale_y * overlay.scale_y,
124        rotation_x: base.rotation_x + overlay.rotation_x,
125        rotation_y: base.rotation_y + overlay.rotation_y,
126        rotation_z: base.rotation_z + overlay.rotation_z,
127        camera_distance: transform_frame(&base, &overlay).camera_distance,
128        transform_origin: transform_frame(&base, &overlay).transform_origin,
129        translation_x: base.translation_x + overlay.translation_x,
130        translation_y: base.translation_y + overlay.translation_y,
131        shadow_elevation: overlay.shadow_elevation,
132        ambient_shadow_color: overlay.ambient_shadow_color,
133        spot_shadow_color: overlay.spot_shadow_color,
134        shape: merged_layer_shape(&base, &overlay),
135        clip: base.clip || overlay.clip,
136        compositing_strategy: overlay.compositing_strategy,
137        blend_mode: overlay.blend_mode,
138        color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
139        render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
140        backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
141    }
142}
143
144/// Which of two stacked layers merged into one frames the merged transform:
145/// the later layer when it rotates or scales itself, else the earlier one. A
146/// layer that neither rotates nor scales, such as a glass surface under a
147/// tilt, leaves its camera and pivot at their defaults, and those would
148/// replace the tilt's own.
149fn transform_frame<'a>(base: &'a GraphicsLayer, overlay: &'a GraphicsLayer) -> &'a GraphicsLayer {
150    let transforms = |layer: &GraphicsLayer| {
151        layer.rotation_x != 0.0
152            || layer.rotation_y != 0.0
153            || layer.rotation_z != 0.0
154            || layer.scale != 1.0
155            || layer.scale_x != 1.0
156            || layer.scale_y != 1.0
157    };
158    if transforms(overlay) || !transforms(base) {
159        overlay
160    } else {
161        base
162    }
163}
164
165/// The shape of two stacked layers merged into one: the layer that clips
166/// owns it, else the layer that carries the backdrop (its effect covers that
167/// shape), else the later layer, whose default resets it like every other
168/// parent-local field.
169fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
170    if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
171        overlay.shape
172    } else if base.clip || base.backdrop_effect.is_some() {
173        base.shape
174    } else {
175        overlay.shape
176    }
177}
178
179fn compose_render_effects(
180    outer: Option<RenderEffect>,
181    inner: Option<RenderEffect>,
182) -> Option<RenderEffect> {
183    match (outer, inner) {
184        (None, None) => None,
185        (Some(effect), None) | (None, Some(effect)) => Some(effect),
186        (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
187    }
188}
189
190fn compose_color_filters(
191    base: Option<ColorFilter>,
192    overlay: Option<ColorFilter>,
193) -> Option<ColorFilter> {
194    match (base, overlay) {
195        (None, None) => None,
196        (Some(filter), None) | (None, Some(filter)) => Some(filter),
197        (Some(filter), Some(next)) => Some(filter.compose(next)),
198    }
199}
200
201impl ModifierNodeSlices {
202    pub fn draw_commands(&self) -> &[DrawCommand] {
203        &self.draw_commands
204    }
205
206    /// How many leading [`draw_commands`](Self::draw_commands) come from
207    /// modifiers chained before the node's graphics layer or clip. Those draw
208    /// around the layer in the parent's space, outside its clip, alpha and
209    /// transform, exactly as an outer `drawBehind` wraps a `graphicsLayer`.
210    pub fn outer_draw_command_count(&self) -> usize {
211        self.layer_draw_boundary.unwrap_or(0)
212    }
213
214    fn insert_background_draw(
215        &mut self,
216        insert_index: usize,
217        precedes_layer: bool,
218        command: DrawCommand,
219    ) {
220        let insert_index = insert_index.min(self.draw_commands.len());
221        self.draw_commands.insert(insert_index, command);
222        if let Some(boundary) = self.layer_draw_boundary.as_mut()
223            && precedes_layer
224        {
225            *boundary += 1;
226        }
227    }
228
229    fn mark_layer_draw_boundary(&mut self) {
230        if self.layer_draw_boundary.is_none() {
231            self.layer_draw_boundary = Some(self.draw_commands.len());
232        }
233    }
234
235    pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
236        &self.pointer_inputs
237    }
238
239    /// Dispatches an event whose position is already local to this layout node.
240    /// Consumed events stop propagation except for release and cancellation,
241    /// which reach every handler so each can finish its active interaction.
242    pub fn dispatch_pointer_event(&self, event: PointerEvent) {
243        let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
244        for handler in &self.pointer_inputs {
245            if event.is_consumed() && !terminal {
246                break;
247            }
248            handler(event.clone());
249        }
250    }
251
252    /// The write targets for this node's resolved size, one per pointer-input
253    /// node that exposes a size to its handler. See
254    /// [`ModifierNodeSlices::publish_pointer_input_size`].
255    pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<cranpose_ui_graphics::Size>>] {
256        &self.pointer_input_sizes
257    }
258
259    /// Publishes this layout node's resolved size to every pointer-input
260    /// handler attached to it, so `PointerInputScope::size()` reports the
261    /// node's real dimensions.
262    ///
263    /// Called by every pass that resolves a node's geometry (the layout `place`
264    /// passes and the per-frame scene build), so the size is current before any
265    /// pointer event for that frame is dispatched and tracks resizes.
266    ///
267    /// `size` is the node's layout box — the same box the dispatched
268    /// [`PointerEvent`] positions are made local to — so handlers can compare
269    /// event coordinates against it directly.
270    pub fn publish_pointer_input_size(&self, size: cranpose_ui_graphics::Size) {
271        for sink in &self.pointer_input_sizes {
272            sink.set(size);
273        }
274    }
275
276    /// The pointer's appearance over this node, when a `pointer_icon`
277    /// modifier names one. The innermost declaration in the chain wins.
278    pub fn pointer_icon(&self) -> Option<&PointerIcon> {
279        self.pointer_icon.as_ref()
280    }
281
282    pub fn clip_to_bounds(&self) -> bool {
283        self.clip_to_bounds
284    }
285
286    /// The bounds of the node's layer in a node of `node_size`, where its
287    /// clip cuts and its transforms pivot: as in Compose, the rect of the
288    /// coordinator its outermost clip or graphics layer wraps, so an offset
289    /// declared after it moves the content inside the layer rather than the
290    /// layer. The node's own rect when it has neither.
291    pub fn layer_bounds(&self, node_size: Size) -> Rect {
292        self.layer_coordinator
293            .as_ref()
294            .map_or_else(|| Rect::from_size(node_size), |layer| layer.rect(node_size))
295    }
296
297    /// Publishes geometry in window coordinates through the same transform as
298    /// rendering. Pointer-input sizes stay in the node's local coordinates.
299    #[doc(hidden)]
300    pub fn publish_window_geometry(
301        &self,
302        origin: Point,
303        transform: cranpose_ui_graphics::ProjectiveTransform,
304        size: Size,
305    ) {
306        if self.text_window_transform.is_some() || self.viewport_window_rect.is_some() {
307            let local_to_window =
308                cranpose_ui_graphics::ProjectiveTransform::translation(origin.x, origin.y)
309                    .then(transform);
310            if let Some(sink) = self.text_window_transform() {
311                sink.set(local_to_window);
312            }
313            if let Some(sink) = self.viewport_window_rect() {
314                sink.set(cranpose_ui_graphics::WindowCoordinates {
315                    size,
316                    local_to_window,
317                });
318            }
319        }
320        self.publish_pointer_input_size(size);
321    }
322
323    pub fn motion_context_animated(&self) -> bool {
324        self.motion_context_animated
325    }
326
327    pub fn translated_content_context(&self) -> bool {
328        self.translated_content_context
329    }
330
331    pub fn translated_content_context_identity(&self) -> Option<usize> {
332        self.translated_content_context_identity
333    }
334
335    pub fn translated_content_offset(&self) -> Option<Point> {
336        self.translated_content_offset_reader
337            .as_ref()
338            .map(|reader| reader())
339    }
340
341    /// Points the text slice at a text node's new layout, after an update
342    /// that changed only the text node's element.
343    pub(crate) fn replace_text_layout(&mut self, layout: TextPreparedLayoutHandle) {
344        self.text = Some(SliceText::Text(layout));
345    }
346
347    pub fn text_content(&self) -> Option<&str> {
348        self.annotated_text().map(|text| text.text.as_str())
349    }
350
351    pub fn annotated_text(&self) -> Option<&Rc<crate::text::AnnotatedString>> {
352        match self.text.as_ref()? {
353            SliceText::Text(layout) => Some(layout.annotated_text()),
354            SliceText::Field(field) => Some(&field.content),
355        }
356    }
357
358    /// Where the text draws in a node of `node_size`: the rect its layout put
359    /// the text in, after every layout modifier before it.
360    pub fn text_content_rect(&self, node_size: Size) -> Rect {
361        self.text_coordinator.as_ref().map_or(
362            Rect {
363                x: 0.0,
364                y: 0.0,
365                width: node_size.width,
366                height: node_size.height,
367            },
368            |coordinator| coordinator.rect(node_size),
369        )
370    }
371
372    pub fn text_style(&self) -> Option<&TextStyle> {
373        match self.text.as_ref()? {
374            SliceText::Text(layout) => Some(layout.style()),
375            SliceText::Field(field) => Some(&field.style),
376        }
377    }
378
379    pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
380        match self.text.as_ref()? {
381            SliceText::Text(layout) => Some(layout.options()),
382            SliceText::Field(_) => Some(TextLayoutOptions::default()),
383        }
384    }
385
386    /// Returns the horizontal pan resolver for single-line text fields.
387    ///
388    /// The resolver takes the content viewport width (px) and returns the
389    /// horizontal scroll offset that keeps the cursor visible. Renderers
390    /// subtract this offset from the text origin so the glyphs pan together
391    /// with the cursor and selection.
392    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
393        match self.text.as_ref()? {
394            SliceText::Field(field) => field.pan.clone(),
395            SliceText::Text(_) => None,
396        }
397    }
398
399    /// The write target for a text node's local-to-window transform, used by
400    /// editable and selectable text for caret, selection and pointer geometry.
401    pub fn text_window_transform(
402        &self,
403    ) -> Option<&Rc<std::cell::Cell<cranpose_ui_graphics::ProjectiveTransform>>> {
404        self.text_window_transform.as_ref()
405    }
406
407    /// The write target for a scroll container's composited window rect, if this
408    /// node carries a `report_window_rect` modifier. The layout pass writes the
409    /// node's true on-screen viewport rect here so a `BringIntoViewResponder`
410    /// can scroll a focused field's caret above the soft keyboard.
411    pub fn viewport_window_rect(&self) -> Option<&Rc<dyn crate::modifier_nodes::WindowRectSink>> {
412        self.viewport_window_rect.as_ref()
413    }
414
415    /// Returns the text layout this node's `Text` or text field produced when
416    /// layout last measured it, laid out at the same width.
417    ///
418    /// A text field's layout is its current text wrapped at the width its
419    /// caret and selection are placed on. `None` when the node carries no text,
420    /// or carries a `Text` that has not been measured yet.
421    pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
422        match self.text.as_ref()? {
423            SliceText::Text(layout) => layout.measured_layout(),
424            SliceText::Field(field) => Some(field.layout.measured_layout(&field.style)),
425        }
426    }
427
428    pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
429        if let Some(resolve) = &self.graphics_layer_resolver {
430            Some(resolve())
431        } else {
432            self.graphics_layer.as_deref().cloned()
433        }
434    }
435
436    pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
437        self.corner_shape
438    }
439
440    /// Records the layer's coordinator when this is the chain's outermost
441    /// clip or graphics layer.
442    fn enter_layer(&mut self, site: &DrawSite) {
443        if self.layer_coordinator.is_none() {
444            self.layer_coordinator = Some(site.coordinator.clone());
445        }
446    }
447
448    fn push_graphics_layer(
449        &mut self,
450        layer: GraphicsLayer,
451        resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
452    ) {
453        let existing_snapshot = self.graphics_layer.as_deref().cloned();
454        let next_snapshot = existing_snapshot.as_ref().map_or_else(
455            || layer.clone(),
456            |current| merge_graphics_layers(current.clone(), layer.clone()),
457        );
458        let existing_resolver = self.graphics_layer_resolver.clone();
459
460        match &mut self.graphics_layer {
461            Some(held) => **held = next_snapshot,
462            None => self.graphics_layer = Some(Box::new(next_snapshot)),
463        }
464        self.graphics_layer_resolver = match (existing_resolver, resolver) {
465            (None, None) => None,
466            (Some(current_resolver), None) => Some(Rc::new(move || {
467                merge_graphics_layers(current_resolver(), layer.clone())
468            })),
469            (None, Some(next_resolver)) => {
470                let base = existing_snapshot.unwrap_or_default();
471                Some(Rc::new(move || {
472                    merge_graphics_layers(base.clone(), next_resolver())
473                }))
474            }
475            (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
476                merge_graphics_layers(current_resolver(), next_resolver())
477            })),
478        };
479    }
480
481    pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
482        self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
483        self
484    }
485
486    pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
487        let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
488        let pointer_input_bytes =
489            self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
490        ModifierNodeSlicesDebugStats {
491            draw_command_count: self.draw_commands.len(),
492            draw_command_capacity: self.draw_commands.capacity(),
493            pointer_input_count: self.pointer_inputs.len(),
494            pointer_input_capacity: self.pointer_inputs.capacity(),
495            has_text_content: self.text.is_some(),
496            has_text_style: self.text.is_some(),
497            has_text_layout_options: self.text.is_some(),
498            has_prepared_text_layout: self.text.is_some(),
499            has_graphics_layer: self.graphics_layer.is_some(),
500            has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
501            heap_bytes: draw_command_bytes + pointer_input_bytes,
502        }
503    }
504
505    /// Resets the slice collection for reuse, retaining vector capacity.
506    pub fn clear(&mut self) {
507        self.draw_commands.clear();
508        self.layer_draw_boundary = None;
509        self.pointer_inputs.clear();
510        self.pointer_input_sizes.clear();
511        self.pointer_icon = None;
512        self.clip_to_bounds = false;
513        self.layer_coordinator = None;
514        self.motion_context_animated = false;
515        self.translated_content_context = false;
516        self.translated_content_context_identity = None;
517        self.translated_content_offset_reader = None;
518        self.text = None;
519        self.text_coordinator = None;
520        self.text_window_transform = None;
521        self.viewport_window_rect = None;
522        self.graphics_layer = None;
523        self.graphics_layer_resolver = None;
524        self.corner_shape = None;
525        self.chain_guard = None;
526    }
527}
528
529impl fmt::Debug for ModifierNodeSlices {
530    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531        f.debug_struct("ModifierNodeSlices")
532            .field("draw_commands", &self.draw_commands.len())
533            .field("pointer_inputs", &self.pointer_inputs.len())
534            .field("pointer_icon", &self.pointer_icon)
535            .field("clip_to_bounds", &self.clip_to_bounds)
536            .field("motion_context_animated", &self.motion_context_animated)
537            .field(
538                "translated_content_context",
539                &self.translated_content_context,
540            )
541            .field(
542                "translated_content_context_identity",
543                &self.translated_content_context_identity,
544            )
545            .field(
546                "translated_content_offset",
547                &self.translated_content_offset(),
548            )
549            .field("text_content", &self.annotated_text())
550            .field("text_style", &self.text_style())
551            .field("text_layout_options", &self.text_layout_options())
552            .field("graphics_layer", &self.graphics_layer)
553            .field(
554                "graphics_layer_resolver",
555                &self.graphics_layer_resolver.is_some(),
556            )
557            .field("corner_shape", &self.corner_shape)
558            .finish()
559    }
560}
561
562/// Records `node`'s pointer icon when it declares one, leaving the icon already
563/// collected in place when it does not.
564///
565/// The chain is walked head to tail, so the innermost declaration is the last
566/// one written and the one that survives.
567fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
568    if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
569        slices.pointer_icon = Some(icon_node.icon().clone());
570    }
571}
572
573/// Collects modifier node slices directly from a reconciled [`ModifierNodeChain`]
574/// that no layout places: its draws sit inside the padding before them.
575pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
576    let mut slices = ModifierNodeSlices::default();
577    collect_modifier_slices_into(chain, &mut slices, &Rc::default(), 1.0);
578    slices
579}
580
581/// Collects modifier node slices into an existing buffer to reuse allocations.
582///
583/// Single-pass: iterates the chain once instead of 4 separate capability-filtered
584/// traversals, reducing per-node `RefCell::borrow()` overhead.
585/// Collects `chain`'s slices into the node's shared snapshot. The snapshot's
586/// storage is reused when nothing else holds it; one the render graph still
587/// shares is left to the graph and replaced, not cloned only to be cleared.
588/// Its draws and text read their place from `geometry`, which the node's
589/// layout writes, and until then sit inside the padding before them on the
590/// device pixel grid of `density`.
591pub(crate) fn collect_modifier_slices_into_shared(
592    chain: &ModifierNodeChain,
593    slices: &mut Rc<ModifierNodeSlices>,
594    geometry: &Rc<CoordinatorGeometry>,
595    density: f32,
596) {
597    if Rc::get_mut(slices).is_none() {
598        *slices = Rc::default();
599    }
600    if let Some(slices) = Rc::get_mut(slices) {
601        collect_modifier_slices_into(chain, slices, geometry, density);
602    }
603}
604
605fn collect_modifier_slices_into(
606    chain: &ModifierNodeChain,
607    slices: &mut ModifierNodeSlices,
608    geometry: &Rc<CoordinatorGeometry>,
609    density: f32,
610) {
611    slices.clear();
612
613    let caps = chain.capabilities();
614    let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
615    let has_draw = caps.intersects(NodeCapabilities::DRAW);
616    let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
617
618    if !has_pointer && !has_draw && !has_layout {
619        return;
620    }
621
622    let mut backgrounds = Backgrounds::default();
623    let mut padding = EdgeInsets::default();
624    // The layout nodes walked so far: the index of the coordinator the next
625    // draw belongs to, which is the next layout node's (or a layout node's
626    // own) or, past the last one, the node's content.
627    let mut layout_ordinal = 0_usize;
628
629    for (modifier_index, node_ref) in chain.head_to_tail().enumerate() {
630        let node_caps = node_ref.kind_set();
631
632        node_ref.with_node(|node| {
633            let any = node.as_any();
634
635            if has_pointer
636                && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
637                && let Some(pointer_node) = node.as_pointer_input_node()
638            {
639                if let Some(handler) = pointer_node.pointer_input_handler() {
640                    slices.pointer_inputs.push(handler);
641                }
642                if let Some(sink) = pointer_node.layout_size_sink() {
643                    slices.pointer_input_sizes.push(sink);
644                }
645                collect_pointer_icon(any, slices);
646            }
647
648            if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
649                let draw = DrawSite {
650                    coordinator: CoordinatorRect::new(geometry, layout_ordinal, padding),
651                    displaceable: has_layout,
652                    modifier_index,
653                };
654                collect_draw_node(node, &draw, slices, &mut backgrounds);
655            }
656
657            if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
658                if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
659                    padding +=
660                        crate::modifier_nodes::device_padding(padding_node.padding(), density);
661                }
662
663                if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
664                    slices.motion_context_animated = motion_context_node.is_active();
665                }
666
667                collect_window_geometry_sink(
668                    any,
669                    // The text a selectable wraps is the layout node after it.
670                    CoordinatorRect::new(geometry, layout_ordinal + 1, padding),
671                    slices,
672                );
673
674                if let Some(translated_content_node) =
675                    any.downcast_ref::<TranslatedContentContextNode>()
676                {
677                    slices.translated_content_context = translated_content_node.is_active();
678                    slices.translated_content_context_identity =
679                        Some(translated_content_node.identity());
680                    slices.translated_content_offset_reader =
681                        translated_content_node.content_offset_reader();
682                }
683
684                if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
685                    slices.text_coordinator =
686                        Some(CoordinatorRect::new(geometry, layout_ordinal, padding));
687                    slices.text = Some(SliceText::Text(text_node.prepared_layout_handle()));
688                }
689
690                if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
691                    slices.text = Some(SliceText::Field(Rc::new(FieldText {
692                        content: Rc::new(crate::text::AnnotatedString::from(
693                            text_field_node.text(),
694                        )),
695                        style: text_field_node.style().clone(),
696                        layout: text_field_node.layout_handle(),
697                        pan: text_field_node.text_pan_resolver(),
698                    })));
699                    slices.text_window_transform = Some(text_field_node.window_transform_sink());
700
701                    let coordinator = CoordinatorRect::new(geometry, layout_ordinal, padding);
702                    text_field_node.set_content_origin(coordinator.clone());
703                    slices.text_coordinator = Some(coordinator);
704                }
705                layout_ordinal += 1;
706            }
707        });
708    }
709
710    backgrounds.insert_into(slices);
711}
712
713/// Where a draw modifier draws: in its coordinator's rect, which only moves
714/// off the node's own rect when the chain has layout modifiers.
715struct DrawSite {
716    coordinator: CoordinatorRect,
717    displaceable: bool,
718    modifier_index: usize,
719}
720
721/// The chain's backgrounds as the walk finds them. Each draws at its place in
722/// the draw order, in its coordinator's rect, as Compose draws every
723/// background of a chain; a corner shape shapes the nearest background
724/// before it, or the next one when none comes before.
725#[derive(Default)]
726struct Backgrounds {
727    slots: SmallVec<[BackgroundSlot; 2]>,
728    pending_shape: Option<RoundedCornerShape>,
729    last_shape: Option<RoundedCornerShape>,
730}
731
732struct BackgroundSlot {
733    color: crate::modifier::Color,
734    coordinator: CoordinatorRect,
735    insert_index: usize,
736    precedes_layer: bool,
737    corner_shape: Option<RoundedCornerShape>,
738}
739
740impl Backgrounds {
741    fn push(
742        &mut self,
743        color: crate::modifier::Color,
744        shape: Option<RoundedCornerShape>,
745        site: &DrawSite,
746        slices: &ModifierNodeSlices,
747    ) {
748        let corner_shape = shape.or_else(|| self.pending_shape.take());
749        if shape.is_some() {
750            self.last_shape = shape;
751        }
752        self.slots.push(BackgroundSlot {
753            color,
754            coordinator: site.coordinator.clone(),
755            insert_index: slices.draw_commands.len(),
756            precedes_layer: slices.layer_draw_boundary.is_none(),
757            corner_shape,
758        });
759    }
760
761    fn shape(&mut self, shape: RoundedCornerShape) {
762        self.last_shape = Some(shape);
763        match self.slots.last_mut() {
764            Some(slot) => slot.corner_shape = Some(shape),
765            None => self.pending_shape = Some(shape),
766        }
767    }
768
769    /// Inserts every background at its place, the last first so the places
770    /// of those before it still hold.
771    fn insert_into(self, slices: &mut ModifierNodeSlices) {
772        slices.corner_shape = self.last_shape;
773        for slot in self.slots.into_iter().rev() {
774            let BackgroundSlot {
775                color,
776                coordinator,
777                insert_index,
778                precedes_layer,
779                corner_shape,
780            } = slot;
781            let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
782                use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
783
784                use crate::modifier::Brush;
785
786                let rect = coordinator.rect(scope.size());
787                let brush = Brush::solid(color);
788                if let Some(shape) = corner_shape {
789                    let radii: CornerRadii = shape.resolve(rect.width, rect.height);
790                    scope.draw_round_rect_at(rect, brush, radii);
791                } else {
792                    scope.draw_rect_at(rect, brush);
793                }
794            });
795            slices.insert_background_draw(
796                insert_index,
797                precedes_layer,
798                DrawCommand::Behind(draw_cmd),
799            );
800        }
801    }
802}
803
804/// Where layout reports a node's window geometry: a scroll viewport's rect,
805/// or the origin of a selectable text, whose content is `text`'s rect.
806fn collect_window_geometry_sink(
807    any: &dyn std::any::Any,
808    text: CoordinatorRect,
809    slices: &mut ModifierNodeSlices,
810) {
811    if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
812        slices.viewport_window_rect = Some(reporter.window_rect_sink());
813    }
814    if let Some(selectable) = any.downcast_ref::<SelectableTextNode>() {
815        slices.text_window_transform = Some(selectable.geometry().window_transform_sink());
816        selectable.geometry().set_content_origin(text);
817    }
818}
819
820/// Collects what a draw-capable node contributes, drawn at `site`.
821fn collect_draw_node(
822    node: &dyn cranpose_foundation::ModifierNode,
823    site: &DrawSite,
824    slices: &mut ModifierNodeSlices,
825    backgrounds: &mut Backgrounds,
826) {
827    let any = node.as_any();
828    if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
829        backgrounds.push(bg_node.color(), bg_node.shape(), site, slices);
830    }
831
832    if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
833        backgrounds.shape(shape_node.shape());
834    }
835
836    if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
837        slices.draw_commands.extend(
838            commands
839                .observed_commands(site.modifier_index)
840                .map(|command| placed_draw_command(command, site)),
841        );
842    }
843
844    if let Some(draw_node) = node.as_draw_node() {
845        collect_draw_closures(draw_node, site, slices);
846    }
847
848    if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
849        slices.mark_layer_draw_boundary();
850        slices.push_graphics_layer(
851            layer_node.layer_snapshot(),
852            layer_node.layer_resolver(site.modifier_index),
853        );
854        slices.enter_layer(site);
855    }
856
857    if any.is::<ClipToBoundsNode>() {
858        slices.mark_layer_draw_boundary();
859        slices.clip_to_bounds = true;
860        slices.enter_layer(site);
861    }
862}
863
864/// A draw node's behind and overlay closures, or what its `draw` records
865/// when it has no overlay closure.
866fn collect_draw_closures(
867    draw_node: &dyn cranpose_foundation::DrawModifierNode,
868    site: &DrawSite,
869    slices: &mut ModifierNodeSlices,
870) {
871    if let Some(closure) = draw_node.create_behind_draw_closure() {
872        slices
873            .draw_commands
874            .push(placed_draw_command(DrawCommand::Behind(closure), site));
875    }
876    if let Some(closure) = draw_node.create_draw_closure() {
877        slices
878            .draw_commands
879            .push(placed_draw_command(DrawCommand::Overlay(closure), site));
880    }
881}
882
883/// `command` drawn where Compose draws a draw modifier: in its coordinator's
884/// rect, sized to it, with what it records moved to that rect.
885fn placed_draw_command(command: DrawCommand, site: &DrawSite) -> DrawCommand {
886    if !site.displaceable {
887        return command;
888    }
889    let place = |draw: crate::draw::DrawCommandFn| -> crate::draw::DrawCommandFn {
890        let coordinator = site.coordinator.clone();
891        Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
892            use cranpose_ui_graphics::DrawScope as _;
893
894            let insets = coordinator.insets(scope.size());
895            if insets.is_zero() {
896                draw(scope);
897            } else {
898                scope.inset(insets, |inner| draw(inner));
899            }
900        })
901    };
902    match command {
903        DrawCommand::Behind(draw) => DrawCommand::Behind(place(draw)),
904        DrawCommand::WithContent(draw) => DrawCommand::WithContent(place(draw)),
905        DrawCommand::Overlay(draw) => DrawCommand::Overlay(place(draw)),
906    }
907}
908
909/// Collects modifier node slices by instantiating a temporary node chain from a [`Modifier`].
910pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
911    let mut handle = ModifierChainHandle::new();
912    let _ = handle.update(modifier);
913    collect_modifier_slices(handle.chain()).with_chain_guard(handle)
914}
915
916#[cfg(test)]
917#[path = "tests/slices_tests.rs"]
918mod tests;