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    pub fn text_content(&self) -> Option<&str> {
342        self.annotated_text().map(|text| text.text.as_str())
343    }
344
345    pub fn annotated_text(&self) -> Option<&Rc<crate::text::AnnotatedString>> {
346        match self.text.as_ref()? {
347            SliceText::Text(layout) => Some(layout.annotated_text()),
348            SliceText::Field(field) => Some(&field.content),
349        }
350    }
351
352    /// Where the text draws in a node of `node_size`: the rect its layout put
353    /// the text in, after every layout modifier before it.
354    pub fn text_content_rect(&self, node_size: Size) -> Rect {
355        self.text_coordinator.as_ref().map_or(
356            Rect {
357                x: 0.0,
358                y: 0.0,
359                width: node_size.width,
360                height: node_size.height,
361            },
362            |coordinator| coordinator.rect(node_size),
363        )
364    }
365
366    pub fn text_style(&self) -> Option<&TextStyle> {
367        match self.text.as_ref()? {
368            SliceText::Text(layout) => Some(layout.style()),
369            SliceText::Field(field) => Some(&field.style),
370        }
371    }
372
373    pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
374        match self.text.as_ref()? {
375            SliceText::Text(layout) => Some(layout.options()),
376            SliceText::Field(_) => Some(TextLayoutOptions::default()),
377        }
378    }
379
380    /// Returns the horizontal pan resolver for single-line text fields.
381    ///
382    /// The resolver takes the content viewport width (px) and returns the
383    /// horizontal scroll offset that keeps the cursor visible. Renderers
384    /// subtract this offset from the text origin so the glyphs pan together
385    /// with the cursor and selection.
386    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
387        match self.text.as_ref()? {
388            SliceText::Field(field) => field.pan.clone(),
389            SliceText::Text(_) => None,
390        }
391    }
392
393    /// The write target for a text node's local-to-window transform, used by
394    /// editable and selectable text for caret, selection and pointer geometry.
395    pub fn text_window_transform(
396        &self,
397    ) -> Option<&Rc<std::cell::Cell<cranpose_ui_graphics::ProjectiveTransform>>> {
398        self.text_window_transform.as_ref()
399    }
400
401    /// The write target for a scroll container's composited window rect, if this
402    /// node carries a `report_window_rect` modifier. The layout pass writes the
403    /// node's true on-screen viewport rect here so a `BringIntoViewResponder`
404    /// can scroll a focused field's caret above the soft keyboard.
405    pub fn viewport_window_rect(&self) -> Option<&Rc<dyn crate::modifier_nodes::WindowRectSink>> {
406        self.viewport_window_rect.as_ref()
407    }
408
409    /// Returns the text layout this node's `Text` or text field produced when
410    /// layout last measured it, laid out at the same width.
411    ///
412    /// A text field's layout is its current text wrapped at the width its
413    /// caret and selection are placed on. `None` when the node carries no text,
414    /// or carries a `Text` that has not been measured yet.
415    pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
416        match self.text.as_ref()? {
417            SliceText::Text(layout) => layout.measured_layout(),
418            SliceText::Field(field) => Some(field.layout.measured_layout(&field.style)),
419        }
420    }
421
422    pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
423        if let Some(resolve) = &self.graphics_layer_resolver {
424            Some(resolve())
425        } else {
426            self.graphics_layer.as_deref().cloned()
427        }
428    }
429
430    pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
431        self.corner_shape
432    }
433
434    /// Records the layer's coordinator when this is the chain's outermost
435    /// clip or graphics layer.
436    fn enter_layer(&mut self, site: &DrawSite) {
437        if self.layer_coordinator.is_none() {
438            self.layer_coordinator = Some(site.coordinator.clone());
439        }
440    }
441
442    fn push_graphics_layer(
443        &mut self,
444        layer: GraphicsLayer,
445        resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
446    ) {
447        let existing_snapshot = self.graphics_layer.as_deref().cloned();
448        let next_snapshot = existing_snapshot.as_ref().map_or_else(
449            || layer.clone(),
450            |current| merge_graphics_layers(current.clone(), layer.clone()),
451        );
452        let existing_resolver = self.graphics_layer_resolver.clone();
453
454        match &mut self.graphics_layer {
455            Some(held) => **held = next_snapshot,
456            None => self.graphics_layer = Some(Box::new(next_snapshot)),
457        }
458        self.graphics_layer_resolver = match (existing_resolver, resolver) {
459            (None, None) => None,
460            (Some(current_resolver), None) => Some(Rc::new(move || {
461                merge_graphics_layers(current_resolver(), layer.clone())
462            })),
463            (None, Some(next_resolver)) => {
464                let base = existing_snapshot.unwrap_or_default();
465                Some(Rc::new(move || {
466                    merge_graphics_layers(base.clone(), next_resolver())
467                }))
468            }
469            (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
470                merge_graphics_layers(current_resolver(), next_resolver())
471            })),
472        };
473    }
474
475    pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
476        self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
477        self
478    }
479
480    pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
481        let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
482        let pointer_input_bytes =
483            self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
484        ModifierNodeSlicesDebugStats {
485            draw_command_count: self.draw_commands.len(),
486            draw_command_capacity: self.draw_commands.capacity(),
487            pointer_input_count: self.pointer_inputs.len(),
488            pointer_input_capacity: self.pointer_inputs.capacity(),
489            has_text_content: self.text.is_some(),
490            has_text_style: self.text.is_some(),
491            has_text_layout_options: self.text.is_some(),
492            has_prepared_text_layout: self.text.is_some(),
493            has_graphics_layer: self.graphics_layer.is_some(),
494            has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
495            heap_bytes: draw_command_bytes + pointer_input_bytes,
496        }
497    }
498
499    /// Resets the slice collection for reuse, retaining vector capacity.
500    pub fn clear(&mut self) {
501        self.draw_commands.clear();
502        self.layer_draw_boundary = None;
503        self.pointer_inputs.clear();
504        self.pointer_input_sizes.clear();
505        self.pointer_icon = None;
506        self.clip_to_bounds = false;
507        self.layer_coordinator = None;
508        self.motion_context_animated = false;
509        self.translated_content_context = false;
510        self.translated_content_context_identity = None;
511        self.translated_content_offset_reader = None;
512        self.text = None;
513        self.text_coordinator = None;
514        self.text_window_transform = None;
515        self.viewport_window_rect = None;
516        self.graphics_layer = None;
517        self.graphics_layer_resolver = None;
518        self.corner_shape = None;
519        self.chain_guard = None;
520    }
521}
522
523impl fmt::Debug for ModifierNodeSlices {
524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525        f.debug_struct("ModifierNodeSlices")
526            .field("draw_commands", &self.draw_commands.len())
527            .field("pointer_inputs", &self.pointer_inputs.len())
528            .field("pointer_icon", &self.pointer_icon)
529            .field("clip_to_bounds", &self.clip_to_bounds)
530            .field("motion_context_animated", &self.motion_context_animated)
531            .field(
532                "translated_content_context",
533                &self.translated_content_context,
534            )
535            .field(
536                "translated_content_context_identity",
537                &self.translated_content_context_identity,
538            )
539            .field(
540                "translated_content_offset",
541                &self.translated_content_offset(),
542            )
543            .field("text_content", &self.annotated_text())
544            .field("text_style", &self.text_style())
545            .field("text_layout_options", &self.text_layout_options())
546            .field("graphics_layer", &self.graphics_layer)
547            .field(
548                "graphics_layer_resolver",
549                &self.graphics_layer_resolver.is_some(),
550            )
551            .field("corner_shape", &self.corner_shape)
552            .finish()
553    }
554}
555
556/// Records `node`'s pointer icon when it declares one, leaving the icon already
557/// collected in place when it does not.
558///
559/// The chain is walked head to tail, so the innermost declaration is the last
560/// one written and the one that survives.
561fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
562    if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
563        slices.pointer_icon = Some(icon_node.icon().clone());
564    }
565}
566
567/// Collects modifier node slices directly from a reconciled [`ModifierNodeChain`]
568/// that no layout places: its draws sit inside the padding before them.
569pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
570    let mut slices = ModifierNodeSlices::default();
571    collect_modifier_slices_into(chain, &mut slices, &Rc::default(), 1.0);
572    slices
573}
574
575/// Collects modifier node slices into an existing buffer to reuse allocations.
576///
577/// Single-pass: iterates the chain once instead of 4 separate capability-filtered
578/// traversals, reducing per-node `RefCell::borrow()` overhead.
579/// Collects `chain`'s slices into the node's shared snapshot. The snapshot's
580/// storage is reused when nothing else holds it; one the render graph still
581/// shares is left to the graph and replaced, not cloned only to be cleared.
582/// Its draws and text read their place from `geometry`, which the node's
583/// layout writes, and until then sit inside the padding before them on the
584/// device pixel grid of `density`.
585pub(crate) fn collect_modifier_slices_into_shared(
586    chain: &ModifierNodeChain,
587    slices: &mut Rc<ModifierNodeSlices>,
588    geometry: &Rc<CoordinatorGeometry>,
589    density: f32,
590) {
591    if Rc::get_mut(slices).is_none() {
592        *slices = Rc::default();
593    }
594    if let Some(slices) = Rc::get_mut(slices) {
595        collect_modifier_slices_into(chain, slices, geometry, density);
596    }
597}
598
599fn collect_modifier_slices_into(
600    chain: &ModifierNodeChain,
601    slices: &mut ModifierNodeSlices,
602    geometry: &Rc<CoordinatorGeometry>,
603    density: f32,
604) {
605    slices.clear();
606
607    let caps = chain.capabilities();
608    let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
609    let has_draw = caps.intersects(NodeCapabilities::DRAW);
610    let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
611
612    if !has_pointer && !has_draw && !has_layout {
613        return;
614    }
615
616    let mut backgrounds = Backgrounds::default();
617    let mut padding = EdgeInsets::default();
618    // The layout nodes walked so far: the index of the coordinator the next
619    // draw belongs to, which is the next layout node's (or a layout node's
620    // own) or, past the last one, the node's content.
621    let mut layout_ordinal = 0_usize;
622
623    for (modifier_index, node_ref) in chain.head_to_tail().enumerate() {
624        let node_caps = node_ref.kind_set();
625
626        node_ref.with_node(|node| {
627            let any = node.as_any();
628
629            if has_pointer
630                && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
631                && let Some(pointer_node) = node.as_pointer_input_node()
632            {
633                if let Some(handler) = pointer_node.pointer_input_handler() {
634                    slices.pointer_inputs.push(handler);
635                }
636                if let Some(sink) = pointer_node.layout_size_sink() {
637                    slices.pointer_input_sizes.push(sink);
638                }
639                collect_pointer_icon(any, slices);
640            }
641
642            if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
643                let draw = DrawSite {
644                    coordinator: CoordinatorRect::new(geometry, layout_ordinal, padding),
645                    displaceable: has_layout,
646                    modifier_index,
647                };
648                collect_draw_node(node, &draw, slices, &mut backgrounds);
649            }
650
651            if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
652                if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
653                    padding +=
654                        crate::modifier_nodes::device_padding(padding_node.padding(), density);
655                }
656
657                if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
658                    slices.motion_context_animated = motion_context_node.is_active();
659                }
660
661                collect_window_geometry_sink(
662                    any,
663                    // The text a selectable wraps is the layout node after it.
664                    CoordinatorRect::new(geometry, layout_ordinal + 1, padding),
665                    slices,
666                );
667
668                if let Some(translated_content_node) =
669                    any.downcast_ref::<TranslatedContentContextNode>()
670                {
671                    slices.translated_content_context = translated_content_node.is_active();
672                    slices.translated_content_context_identity =
673                        Some(translated_content_node.identity());
674                    slices.translated_content_offset_reader =
675                        translated_content_node.content_offset_reader();
676                }
677
678                if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
679                    slices.text_coordinator =
680                        Some(CoordinatorRect::new(geometry, layout_ordinal, padding));
681                    slices.text = Some(SliceText::Text(text_node.prepared_layout_handle()));
682                }
683
684                if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
685                    slices.text = Some(SliceText::Field(Rc::new(FieldText {
686                        content: Rc::new(crate::text::AnnotatedString::from(
687                            text_field_node.text(),
688                        )),
689                        style: text_field_node.style().clone(),
690                        layout: text_field_node.layout_handle(),
691                        pan: text_field_node.text_pan_resolver(),
692                    })));
693                    slices.text_window_transform = Some(text_field_node.window_transform_sink());
694
695                    let coordinator = CoordinatorRect::new(geometry, layout_ordinal, padding);
696                    text_field_node.set_content_origin(coordinator.clone());
697                    slices.text_coordinator = Some(coordinator);
698                }
699                layout_ordinal += 1;
700            }
701        });
702    }
703
704    backgrounds.insert_into(slices);
705}
706
707/// Where a draw modifier draws: in its coordinator's rect, which only moves
708/// off the node's own rect when the chain has layout modifiers.
709struct DrawSite {
710    coordinator: CoordinatorRect,
711    displaceable: bool,
712    modifier_index: usize,
713}
714
715/// The chain's backgrounds as the walk finds them. Each draws at its place in
716/// the draw order, in its coordinator's rect, as Compose draws every
717/// background of a chain; a corner shape shapes the nearest background
718/// before it, or the next one when none comes before.
719#[derive(Default)]
720struct Backgrounds {
721    slots: SmallVec<[BackgroundSlot; 2]>,
722    pending_shape: Option<RoundedCornerShape>,
723    last_shape: Option<RoundedCornerShape>,
724}
725
726struct BackgroundSlot {
727    color: crate::modifier::Color,
728    coordinator: CoordinatorRect,
729    insert_index: usize,
730    precedes_layer: bool,
731    corner_shape: Option<RoundedCornerShape>,
732}
733
734impl Backgrounds {
735    fn push(
736        &mut self,
737        color: crate::modifier::Color,
738        shape: Option<RoundedCornerShape>,
739        site: &DrawSite,
740        slices: &ModifierNodeSlices,
741    ) {
742        let corner_shape = shape.or_else(|| self.pending_shape.take());
743        if shape.is_some() {
744            self.last_shape = shape;
745        }
746        self.slots.push(BackgroundSlot {
747            color,
748            coordinator: site.coordinator.clone(),
749            insert_index: slices.draw_commands.len(),
750            precedes_layer: slices.layer_draw_boundary.is_none(),
751            corner_shape,
752        });
753    }
754
755    fn shape(&mut self, shape: RoundedCornerShape) {
756        self.last_shape = Some(shape);
757        match self.slots.last_mut() {
758            Some(slot) => slot.corner_shape = Some(shape),
759            None => self.pending_shape = Some(shape),
760        }
761    }
762
763    /// Inserts every background at its place, the last first so the places
764    /// of those before it still hold.
765    fn insert_into(self, slices: &mut ModifierNodeSlices) {
766        slices.corner_shape = self.last_shape;
767        for slot in self.slots.into_iter().rev() {
768            let BackgroundSlot {
769                color,
770                coordinator,
771                insert_index,
772                precedes_layer,
773                corner_shape,
774            } = slot;
775            let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
776                use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
777
778                use crate::modifier::Brush;
779
780                let rect = coordinator.rect(scope.size());
781                let brush = Brush::solid(color);
782                if let Some(shape) = corner_shape {
783                    let radii: CornerRadii = shape.resolve(rect.width, rect.height);
784                    scope.draw_round_rect_at(rect, brush, radii);
785                } else {
786                    scope.draw_rect_at(rect, brush);
787                }
788            });
789            slices.insert_background_draw(
790                insert_index,
791                precedes_layer,
792                DrawCommand::Behind(draw_cmd),
793            );
794        }
795    }
796}
797
798/// Where layout reports a node's window geometry: a scroll viewport's rect,
799/// or the origin of a selectable text, whose content is `text`'s rect.
800fn collect_window_geometry_sink(
801    any: &dyn std::any::Any,
802    text: CoordinatorRect,
803    slices: &mut ModifierNodeSlices,
804) {
805    if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
806        slices.viewport_window_rect = Some(reporter.window_rect_sink());
807    }
808    if let Some(selectable) = any.downcast_ref::<SelectableTextNode>() {
809        slices.text_window_transform = Some(selectable.geometry().window_transform_sink());
810        selectable.geometry().set_content_origin(text);
811    }
812}
813
814/// Collects what a draw-capable node contributes, drawn at `site`.
815fn collect_draw_node(
816    node: &dyn cranpose_foundation::ModifierNode,
817    site: &DrawSite,
818    slices: &mut ModifierNodeSlices,
819    backgrounds: &mut Backgrounds,
820) {
821    let any = node.as_any();
822    if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
823        backgrounds.push(bg_node.color(), bg_node.shape(), site, slices);
824    }
825
826    if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
827        backgrounds.shape(shape_node.shape());
828    }
829
830    if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
831        slices.draw_commands.extend(
832            commands
833                .observed_commands(site.modifier_index)
834                .map(|command| placed_draw_command(command, site)),
835        );
836    }
837
838    if let Some(draw_node) = node.as_draw_node() {
839        collect_draw_closures(draw_node, site, slices);
840    }
841
842    if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
843        slices.mark_layer_draw_boundary();
844        slices.push_graphics_layer(
845            layer_node.layer_snapshot(),
846            layer_node.layer_resolver(site.modifier_index),
847        );
848        slices.enter_layer(site);
849    }
850
851    if any.is::<ClipToBoundsNode>() {
852        slices.mark_layer_draw_boundary();
853        slices.clip_to_bounds = true;
854        slices.enter_layer(site);
855    }
856}
857
858/// A draw node's behind and overlay closures, or what its `draw` records
859/// when it has no overlay closure.
860fn collect_draw_closures(
861    draw_node: &dyn cranpose_foundation::DrawModifierNode,
862    site: &DrawSite,
863    slices: &mut ModifierNodeSlices,
864) {
865    if let Some(closure) = draw_node.create_behind_draw_closure() {
866        slices
867            .draw_commands
868            .push(placed_draw_command(DrawCommand::Behind(closure), site));
869    }
870    if let Some(closure) = draw_node.create_draw_closure() {
871        slices
872            .draw_commands
873            .push(placed_draw_command(DrawCommand::Overlay(closure), site));
874    }
875}
876
877/// `command` drawn where Compose draws a draw modifier: in its coordinator's
878/// rect, sized to it, with what it records moved to that rect.
879fn placed_draw_command(command: DrawCommand, site: &DrawSite) -> DrawCommand {
880    if !site.displaceable {
881        return command;
882    }
883    let place = |draw: crate::draw::DrawCommandFn| -> crate::draw::DrawCommandFn {
884        let coordinator = site.coordinator.clone();
885        Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
886            use cranpose_ui_graphics::DrawScope as _;
887
888            let insets = coordinator.insets(scope.size());
889            if insets.is_zero() {
890                draw(scope);
891            } else {
892                scope.inset(insets, |inner| draw(inner));
893            }
894        })
895    };
896    match command {
897        DrawCommand::Behind(draw) => DrawCommand::Behind(place(draw)),
898        DrawCommand::WithContent(draw) => DrawCommand::WithContent(place(draw)),
899        DrawCommand::Overlay(draw) => DrawCommand::Overlay(place(draw)),
900    }
901}
902
903/// Collects modifier node slices by instantiating a temporary node chain from a [`Modifier`].
904pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
905    let mut handle = ModifierChainHandle::new();
906    let _ = handle.update(modifier);
907    collect_modifier_slices(handle.chain()).with_chain_guard(handle)
908}
909
910#[cfg(test)]
911#[path = "tests/slices_tests.rs"]
912mod tests;