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