Skip to main content

cranpose_ui/modifier/
slices.rs

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