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