Skip to main content

cranpose_ui/modifier/
slices.rs

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