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