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::{PointerEvent, PointerEventKind};
4use cranpose_ui_graphics::{
5    ColorFilter, GraphicsLayer, LayerShape, PointerIcon, Rect, RenderEffect, RoundedCornerShape,
6    Size,
7};
8
9mod snapshot;
10
11pub(crate) use snapshot::SlicesSnapshot;
12pub use snapshot::{collect_modifier_slices, collect_slices_from_modifier};
13
14use super::{ModifierChainHandle, Point, coordinator_rect::CoordinatorRect};
15use crate::{
16    draw::DrawCommand,
17    text::{TextLayoutOptions, TextStyle},
18    text_field_modifier_node::{TextFieldLayoutHandle, TextPanResolver},
19    text_modifier_node::TextPreparedLayoutHandle,
20};
21
22/// Snapshot of modifier node slices that impact draw and pointer subsystems.
23#[derive(Clone, Default)]
24pub struct ModifierNodeSlices {
25    draw_commands: Vec<DrawCommand>,
26    // What the chain's clips and graphics layers give, boxed: few nodes
27    // carry either.
28    layer: Option<Box<LayerSlices>>,
29    text: Option<SliceText>,
30    text_coordinator: Option<CoordinatorRect>,
31    /// Boxed for the same reason: inline they took 150 bytes of every
32    /// node's slices, and on the gauntlet's 5,600 nodes none sets them but the
33    /// 44 animated layers' resolvers.
34    rare: Option<Box<RareSlices>>,
35}
36
37// What a chain's clips and graphics layers give: made at the chain's
38// outermost clip or layer.
39#[derive(Clone)]
40struct LayerSlices {
41    // How many leading draw commands come from modifiers chained before the
42    // outermost clip or layer.
43    draw_boundary: usize,
44    clip_to_bounds: bool,
45    // Where the outermost clip or layer sits: its coordinator, which a later
46    // offset moves the content inside of.
47    coordinator: Option<CoordinatorRect>,
48    // Boxed again: a clip without a layer is common, and a layer takes 240
49    // bytes.
50    graphics_layer: Option<Box<GraphicsLayer>>,
51    // The chain's last corner shape, which rounds the clip.
52    corner_shape: Option<RoundedCornerShape>,
53}
54
55fn publish_pointer_input_size(rare: &RareSlices, size: Size) {
56    for sink in &rare.pointer_input_sizes {
57        sink.set(size);
58    }
59}
60
61/// What few nodes' chains contribute: pointer input, window geometry sinks,
62/// translated content and live layer resolvers.
63#[derive(Clone, Default)]
64struct RareSlices {
65    pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
66    pointer_input_sizes: Vec<Rc<std::cell::Cell<Size>>>,
67    pointer_icon: Option<PointerIcon>,
68    motion_context_animated: bool,
69    translated_content_context: bool,
70    translated_content_context_identity: Option<usize>,
71    translated_content_offset_reader: Option<Rc<dyn Fn() -> Point>>,
72    text_window: Option<Rc<std::cell::Cell<cranpose_ui_graphics::WindowCoordinates>>>,
73    viewport_window_rect: Option<Rc<dyn crate::modifier_nodes::WindowRectSink>>,
74    graphics_layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
75    chain_guard: Option<Rc<ChainGuard>>,
76    z_index: f32,
77}
78
79impl RareSlices {
80    fn is_empty(&self) -> bool {
81        self.pointer_inputs.is_empty()
82            && self.pointer_input_sizes.is_empty()
83            && self.pointer_icon.is_none()
84            && !self.motion_context_animated
85            && !self.translated_content_context
86            && self.translated_content_context_identity.is_none()
87            && self.translated_content_offset_reader.is_none()
88            && self.text_window.is_none()
89            && self.viewport_window_rect.is_none()
90            && self.graphics_layer_resolver.is_none()
91            && self.chain_guard.is_none()
92            && self.z_index == 0.0
93    }
94
95    fn clear(&mut self) {
96        self.pointer_inputs.clear();
97        self.pointer_input_sizes.clear();
98        self.pointer_icon = None;
99        self.motion_context_animated = false;
100        self.translated_content_context = false;
101        self.translated_content_context_identity = None;
102        self.translated_content_offset_reader = None;
103        self.text_window = None;
104        self.viewport_window_rect = None;
105        self.graphics_layer_resolver = None;
106        self.chain_guard = None;
107        self.z_index = 0.0;
108    }
109}
110
111struct ChainGuard {
112    _handle: ModifierChainHandle,
113}
114
115/// Where a draw modifier draws: in its coordinator's rect, which only moves
116/// off the node's own rect when the chain has layout modifiers.
117struct DrawSite {
118    coordinator: CoordinatorRect,
119    displaceable: bool,
120    modifier_index: usize,
121}
122
123/// The text a node shows. A `Text`'s string, style and options are its
124/// prepared layout's, read from there rather than copied into every
125/// rebuild of the slices; a text field's are held here.
126#[derive(Clone)]
127enum SliceText {
128    Text(TextPreparedLayoutHandle),
129    Field(Rc<FieldText>),
130}
131
132/// The text, or a part of it, that a node's slices lend: a `Text`'s is
133/// borrowed from its layout, which an update changes in place; a text
134/// field's is held by the slices.
135pub struct SliceTextRef<'a, T: ?Sized>(TextBorrow<'a, T>);
136
137enum TextBorrow<'a, T: ?Sized> {
138    Layout(Ref<'a, T>),
139    Field(&'a T),
140}
141
142impl<'a, T: ?Sized> SliceTextRef<'a, T> {
143    fn map<U: ?Sized>(self, part: impl FnOnce(&T) -> &U) -> SliceTextRef<'a, U> {
144        SliceTextRef(match self.0 {
145            TextBorrow::Layout(text) => TextBorrow::Layout(Ref::map(text, part)),
146            TextBorrow::Field(text) => TextBorrow::Field(part(text)),
147        })
148    }
149}
150
151impl<T: ?Sized> Deref for SliceTextRef<'_, T> {
152    type Target = T;
153
154    fn deref(&self) -> &T {
155        match &self.0 {
156            TextBorrow::Layout(text) => text,
157            TextBorrow::Field(text) => text,
158        }
159    }
160}
161
162impl<T: ?Sized + fmt::Debug> fmt::Debug for SliceTextRef<'_, T> {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        (**self).fmt(f)
165    }
166}
167
168impl<T: ?Sized + fmt::Display> fmt::Display for SliceTextRef<'_, T> {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        (**self).fmt(f)
171    }
172}
173
174impl PartialEq<str> for SliceTextRef<'_, str> {
175    fn eq(&self, other: &str) -> bool {
176        **self == *other
177    }
178}
179
180impl PartialEq<&str> for SliceTextRef<'_, str> {
181    fn eq(&self, other: &&str) -> bool {
182        **self == **other
183    }
184}
185
186struct FieldText {
187    content: crate::text::AnnotatedString,
188    style: TextStyle,
189    layout: TextFieldLayoutHandle,
190    pan: Option<TextPanResolver>,
191}
192
193/// Counts and capacities of the data that modifier node slices hold, for memory diagnostics.
194#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
195pub struct ModifierNodeSlicesDebugStats {
196    /// Number of draw commands.
197    pub draw_command_count: usize,
198    /// Allocated capacity of the draw command list, in commands.
199    pub draw_command_capacity: usize,
200    /// Number of pointer input handlers.
201    pub pointer_input_count: usize,
202    /// Allocated capacity of the pointer input handler list, in handlers.
203    pub pointer_input_capacity: usize,
204    /// Whether the node shows text.
205    pub has_text_content: bool,
206    /// Whether the node carries a text style.
207    pub has_text_style: bool,
208    /// Whether the node carries text layout options.
209    pub has_text_layout_options: bool,
210    /// Whether the node carries a prepared text layout.
211    pub has_prepared_text_layout: bool,
212    /// Whether the node carries a graphics layer.
213    pub has_graphics_layer: bool,
214    /// Whether the graphics layer is read through a resolver that runs when the layer is used.
215    pub has_graphics_layer_resolver: bool,
216    /// Heap bytes of the draw command and pointer input handler lists, counted by capacity.
217    pub heap_bytes: usize,
218}
219
220fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
221    GraphicsLayer {
222        alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
223        scale: base.scale * overlay.scale,
224        scale_x: base.scale_x * overlay.scale_x,
225        scale_y: base.scale_y * overlay.scale_y,
226        rotation_x: base.rotation_x + overlay.rotation_x,
227        rotation_y: base.rotation_y + overlay.rotation_y,
228        rotation_z: base.rotation_z + overlay.rotation_z,
229        camera_distance: transform_frame(&base, &overlay).camera_distance,
230        transform_origin: transform_frame(&base, &overlay).transform_origin,
231        translation_x: base.translation_x + overlay.translation_x,
232        translation_y: base.translation_y + overlay.translation_y,
233        shadow_elevation: overlay.shadow_elevation,
234        ambient_shadow_color: overlay.ambient_shadow_color,
235        spot_shadow_color: overlay.spot_shadow_color,
236        shape: merged_layer_shape(&base, &overlay),
237        clip: base.clip || overlay.clip,
238        compositing_strategy: overlay.compositing_strategy,
239        blend_mode: overlay.blend_mode,
240        color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
241        render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
242        backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
243        space: overlay.space.or(base.space),
244    }
245}
246
247/// Which of two stacked layers merged into one frames the merged transform:
248/// the later layer when it rotates or scales itself, else the earlier one. A
249/// layer that neither rotates nor scales, such as a glass surface under a
250/// tilt, leaves its camera and pivot at their defaults, and those would
251/// replace the tilt's own.
252fn transform_frame<'a>(base: &'a GraphicsLayer, overlay: &'a GraphicsLayer) -> &'a GraphicsLayer {
253    let transforms = |layer: &GraphicsLayer| {
254        layer.rotation_x != 0.0
255            || layer.rotation_y != 0.0
256            || layer.rotation_z != 0.0
257            || layer.scale != 1.0
258            || layer.scale_x != 1.0
259            || layer.scale_y != 1.0
260    };
261    if transforms(overlay) || !transforms(base) {
262        overlay
263    } else {
264        base
265    }
266}
267
268/// The shape of two stacked layers merged into one: the layer that clips
269/// owns it, else the layer that carries the backdrop (its effect covers that
270/// shape), else the later layer, whose default resets it like every other
271/// parent-local field.
272fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
273    if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
274        overlay.shape
275    } else if base.clip || base.backdrop_effect.is_some() {
276        base.shape
277    } else {
278        overlay.shape
279    }
280}
281
282fn compose_render_effects(
283    outer: Option<RenderEffect>,
284    inner: Option<RenderEffect>,
285) -> Option<RenderEffect> {
286    match (outer, inner) {
287        (None, None) => None,
288        (Some(effect), None) | (None, Some(effect)) => Some(effect),
289        (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
290    }
291}
292
293fn compose_color_filters(
294    base: Option<ColorFilter>,
295    overlay: Option<ColorFilter>,
296) -> Option<ColorFilter> {
297    match (base, overlay) {
298        (None, None) => None,
299        (Some(filter), None) | (None, Some(filter)) => Some(filter),
300        (Some(filter), Some(next)) => Some(filter.compose(&next)),
301    }
302}
303
304impl ModifierNodeSlices {
305    /// Returns the node's draw commands in the order they draw.
306    pub fn draw_commands(&self) -> &[DrawCommand] {
307        &self.draw_commands
308    }
309
310    /// How many leading [`draw_commands`](Self::draw_commands) come from
311    /// modifiers chained before the node's graphics layer or clip. Those draw
312    /// around the layer in the parent's space, outside its clip, alpha and
313    /// transform, exactly as an outer `drawBehind` wraps a `graphicsLayer`.
314    #[inline]
315    pub fn outer_draw_command_count(&self) -> usize {
316        self.layer.as_ref().map_or(0, |layer| layer.draw_boundary)
317    }
318
319    fn insert_background_draw(
320        &mut self,
321        insert_index: usize,
322        precedes_layer: bool,
323        command: DrawCommand,
324    ) {
325        let insert_index = insert_index.min(self.draw_commands.len());
326        self.draw_commands.insert(insert_index, command);
327        if let Some(layer) = self.layer.as_deref_mut()
328            && precedes_layer
329        {
330            layer.draw_boundary += 1;
331        }
332    }
333
334    // The layer part, made at the chain's outermost clip or layer, which
335    // the draw commands so far precede.
336    fn layer_mut(&mut self) -> &mut LayerSlices {
337        let draw_boundary = self.draw_commands.len();
338        self.layer.get_or_insert_with(|| {
339            Box::new(LayerSlices {
340                draw_boundary,
341                clip_to_bounds: false,
342                coordinator: None,
343                graphics_layer: None,
344                corner_shape: None,
345            })
346        })
347    }
348
349    /// The boxed fields when the chain set any; see [`RareSlices`].
350    fn rare(&self) -> Option<&RareSlices> {
351        self.rare.as_deref()
352    }
353
354    fn rare_mut(&mut self) -> &mut RareSlices {
355        self.rare.get_or_insert_with(Box::default)
356    }
357
358    /// Returns the node's pointer input handlers in chain order.
359    pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
360        self.rare().map_or(&[], |rare| &rare.pointer_inputs)
361    }
362
363    /// Dispatches an event whose position is already local to this layout node.
364    /// Consumed events stop propagation except for release and cancellation,
365    /// which reach every handler so each can finish its active interaction.
366    pub fn dispatch_pointer_event(&self, event: PointerEvent) {
367        let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
368        for handler in self.pointer_inputs() {
369            if event.is_consumed() && !terminal {
370                break;
371            }
372            handler(event.clone());
373        }
374    }
375
376    /// The write targets for this node's resolved size, one per pointer-input
377    /// node that exposes a size to its handler. See
378    /// [`ModifierNodeSlices::publish_pointer_input_size`].
379    pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<Size>>] {
380        self.rare().map_or(&[], |rare| &rare.pointer_input_sizes)
381    }
382
383    /// Publishes this layout node's resolved size to every pointer-input
384    /// handler attached to it, so `PointerInputScope::size()` reports the
385    /// node's real dimensions.
386    ///
387    /// Called by every pass that resolves a node's geometry (the layout `place`
388    /// passes and the per-frame scene build), so the size is current before any
389    /// pointer event for that frame is dispatched and tracks resizes.
390    ///
391    /// `size` is the node's layout box — the same box the dispatched
392    /// [`PointerEvent`] positions are made local to — so handlers can compare
393    /// event coordinates against it directly.
394    pub fn publish_pointer_input_size(&self, size: Size) {
395        if let Some(rare) = self.rare() {
396            publish_pointer_input_size(rare, size);
397        }
398    }
399
400    /// Where the node draws among its siblings: the sum of its `z_index`
401    /// modifiers.
402    pub fn z_index(&self) -> f32 {
403        self.rare().map_or(0.0, |rare| rare.z_index)
404    }
405
406    /// The pointer's appearance over this node, when a `pointer_icon`
407    /// modifier names one. The innermost declaration in the chain wins.
408    pub fn pointer_icon(&self) -> Option<&PointerIcon> {
409        self.rare()?.pointer_icon.as_ref()
410    }
411
412    /// Returns whether the node clips its content to its bounds.
413    #[inline]
414    pub fn clip_to_bounds(&self) -> bool {
415        self.layer
416            .as_ref()
417            .is_some_and(|layer| layer.clip_to_bounds)
418    }
419
420    /// The bounds of the node's layer in a node of `node_size`, where its
421    /// clip cuts and its transforms pivot: as in Compose, the rect of the
422    /// coordinator its outermost clip or graphics layer wraps, so an offset
423    /// declared after it moves the content inside the layer rather than the
424    /// layer. The node's own rect when it has neither.
425    #[inline]
426    pub fn layer_bounds(&self, node_size: Size) -> Rect {
427        self.layer
428            .as_ref()
429            .and_then(|layer| layer.coordinator.as_ref())
430            .map_or_else(|| Rect::from_size(node_size), |layer| layer.rect(node_size))
431    }
432
433    /// Publishes geometry in window coordinates through the same transform as
434    /// rendering; none without a `transform`, inside a mesh surface whose
435    /// scene publishes it. Pointer-input sizes stay in the node's local
436    /// coordinates.
437    #[doc(hidden)]
438    pub fn publish_window_geometry(
439        &self,
440        origin: Point,
441        transform: Option<cranpose_ui_graphics::ProjectiveTransform>,
442        size: Size,
443    ) {
444        // Every sink is a rare slice: most nodes have none to publish to.
445        let Some(rare) = self.rare() else {
446            return;
447        };
448        if let Some(transform) = transform
449            && (rare.text_window.is_some() || rare.viewport_window_rect.is_some())
450        {
451            let window = cranpose_ui_graphics::WindowCoordinates {
452                size,
453                local_to_window: cranpose_ui_graphics::ProjectiveTransform::translation(
454                    origin.x, origin.y,
455                )
456                .then(transform),
457            };
458            if let Some(sink) = &rare.text_window {
459                sink.set(window);
460            }
461            if let Some(sink) = &rare.viewport_window_rect {
462                sink.set(window);
463            }
464        }
465        publish_pointer_input_size(rare, size);
466    }
467
468    /// Returns whether a scroll container on this node is moving its content, for example in a
469    /// fling or a settle.
470    pub fn motion_context_animated(&self) -> bool {
471        self.rare().is_some_and(|rare| rare.motion_context_animated)
472    }
473
474    /// Returns whether this node is a scroll container that draws its content translated by
475    /// [`Self::translated_content_offset`].
476    pub fn translated_content_context(&self) -> bool {
477        self.rare()
478            .is_some_and(|rare| rare.translated_content_context)
479    }
480
481    /// Returns an identifier of that scroll container that stays the same while it lives, or `None`
482    /// when the node is not one.
483    pub fn translated_content_context_identity(&self) -> Option<usize> {
484        self.rare()?.translated_content_context_identity
485    }
486
487    /// Returns the offset in logical pixels by which the scroll container translates its content
488    /// now, or `None` when the node has no such offset.
489    pub fn translated_content_offset(&self) -> Option<Point> {
490        self.rare()?
491            .translated_content_offset_reader
492            .as_ref()
493            .map(|reader| reader())
494    }
495
496    /// Whether the node shows a `Text`'s or a text field's text.
497    pub fn has_text(&self) -> bool {
498        self.text.is_some()
499    }
500
501    /// Returns the plain text the node shows, or `None` when the node shows no text.
502    pub fn text_content(&self) -> Option<SliceTextRef<'_, str>> {
503        self.annotated_text()
504            .map(|text| text.map(crate::text::AnnotatedString::text))
505    }
506
507    /// Returns the text the node shows with its span styles, or `None` when the node shows no text.
508    pub fn annotated_text(&self) -> Option<SliceTextRef<'_, crate::text::AnnotatedString>> {
509        Some(SliceTextRef(match self.text.as_ref()? {
510            SliceText::Text(layout) => TextBorrow::Layout(layout.annotated_text()),
511            SliceText::Field(field) => TextBorrow::Field(&field.content),
512        }))
513    }
514
515    /// Where the text draws in a node of `node_size`: the rect its layout put
516    /// the text in, after every layout modifier before it.
517    pub fn text_content_rect(&self, node_size: Size) -> Rect {
518        self.text_coordinator.as_ref().map_or(
519            Rect {
520                x: 0.0,
521                y: 0.0,
522                width: node_size.width,
523                height: node_size.height,
524            },
525            |coordinator| coordinator.rect(node_size),
526        )
527    }
528
529    /// Returns the style of the text the node shows, or `None` when the node shows no text.
530    pub fn text_style(&self) -> Option<SliceTextRef<'_, TextStyle>> {
531        Some(SliceTextRef(match self.text.as_ref()? {
532            SliceText::Text(layout) => TextBorrow::Layout(layout.style()),
533            SliceText::Field(field) => TextBorrow::Field(&field.style),
534        }))
535    }
536
537    /// Returns the layout options of the text the node shows, or `None` when the node shows no
538    /// text. A text field reports the default options.
539    pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
540        match self.text.as_ref()? {
541            SliceText::Text(layout) => Some(layout.options()),
542            SliceText::Field(_) => Some(TextLayoutOptions::default()),
543        }
544    }
545
546    /// Returns the horizontal pan resolver for single-line text fields.
547    ///
548    /// The resolver takes the content viewport width (px) and returns the
549    /// horizontal scroll offset that keeps the cursor visible. Renderers
550    /// subtract this offset from the text origin so the glyphs pan together
551    /// with the cursor and selection.
552    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
553        match self.text.as_ref()? {
554            SliceText::Field(field) => field.pan.clone(),
555            SliceText::Text(_) => None,
556        }
557    }
558
559    /// The write target for a text node's size and local-to-window
560    /// transform, used by editable and selectable text for caret, selection
561    /// and pointer geometry and a focused field's window bounds.
562    pub fn text_window(
563        &self,
564    ) -> Option<&Rc<std::cell::Cell<cranpose_ui_graphics::WindowCoordinates>>> {
565        self.rare()?.text_window.as_ref()
566    }
567
568    /// The write target for a scroll container's composited window rect, if this
569    /// node carries a `report_window_rect` modifier. The layout pass writes the
570    /// node's true on-screen viewport rect here so a `BringIntoViewResponder`
571    /// can scroll a focused field's caret above the soft keyboard.
572    pub fn viewport_window_rect(&self) -> Option<&Rc<dyn crate::modifier_nodes::WindowRectSink>> {
573        self.rare()?.viewport_window_rect.as_ref()
574    }
575
576    /// Returns the text layout this node's `Text` or text field produced when
577    /// layout last measured it, laid out at the same width.
578    ///
579    /// A text field's layout is its current text wrapped at the width its
580    /// caret and selection are placed on. `None` when the node carries no text,
581    /// or carries a `Text` that has not been measured yet.
582    pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
583        match self.text.as_ref()? {
584            SliceText::Text(layout) => layout.measured_layout(),
585            SliceText::Field(field) => Some(field.layout.measured_layout(&field.style)),
586        }
587    }
588
589    /// Returns the graphics layer that the layer modifiers of the chain combine into, or `None`
590    /// when the chain has none: lent when the chain holds it, built when a layer block computes
591    /// it.
592    #[inline]
593    pub fn graphics_layer(&self) -> Option<Cow<'_, GraphicsLayer>> {
594        if let Some(resolve) = self
595            .rare()
596            .and_then(|rare| rare.graphics_layer_resolver.as_ref())
597        {
598            Some(Cow::Owned(resolve()))
599        } else {
600            self.layer
601                .as_ref()
602                .and_then(|layer| layer.graphics_layer.as_deref())
603                .map(Cow::Borrowed)
604        }
605    }
606
607    /// Whether the chain sets a graphics layer, live or fixed, without
608    /// resolving a live one as [`Self::graphics_layer`] does.
609    #[inline]
610    pub fn has_graphics_layer(&self) -> bool {
611        self.held_graphics_layer()
612            || self
613                .rare()
614                .is_some_and(|rare| rare.graphics_layer_resolver.is_some())
615    }
616
617    /// The rounded corner shape the chain's clip to bounds cuts with: the
618    /// chain's last corner shape. `None` when the chain does not clip to
619    /// its bounds or sets no corner shape.
620    pub fn clip_shape(&self) -> Option<RoundedCornerShape> {
621        self.layer
622            .as_deref()
623            .filter(|layer| layer.clip_to_bounds)
624            .and_then(|layer| layer.corner_shape)
625    }
626
627    // Takes `shape`, the chain's last corner shape, for the clip of the
628    // chain's layer; a chain with no clip or layer reads none.
629    fn set_corner_shape(&mut self, shape: Option<RoundedCornerShape>) {
630        if let Some(layer) = self.layer.as_deref_mut() {
631            layer.corner_shape = shape;
632        }
633    }
634
635    /// Records the layer's coordinator when this is the chain's outermost
636    /// clip or graphics layer.
637    fn enter_layer(&mut self, site: &DrawSite) {
638        let layer = self.layer_mut();
639        if layer.coordinator.is_none() {
640            layer.coordinator = Some(site.coordinator.clone());
641        }
642    }
643
644    // Whether the chain holds a fixed graphics layer.
645    fn held_graphics_layer(&self) -> bool {
646        self.layer
647            .as_ref()
648            .is_some_and(|layer| layer.graphics_layer.is_some())
649    }
650
651    fn push_graphics_layer(
652        &mut self,
653        layer: GraphicsLayer,
654        resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
655    ) {
656        let existing_snapshot = self
657            .layer
658            .as_ref()
659            .and_then(|layer| layer.graphics_layer.as_deref().cloned());
660        let next_snapshot = existing_snapshot.as_ref().map_or_else(
661            || layer.clone(),
662            |current| merge_graphics_layers(current.clone(), layer.clone()),
663        );
664        let existing_resolver = self
665            .rare()
666            .and_then(|rare| rare.graphics_layer_resolver.clone());
667
668        match &mut self.layer_mut().graphics_layer {
669            Some(held) => **held = next_snapshot,
670            held @ None => *held = Some(Box::new(next_snapshot)),
671        }
672        let merged_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>> =
673            match (existing_resolver, resolver) {
674                (None, None) => None,
675                (Some(current_resolver), None) => Some(Rc::new(move || {
676                    merge_graphics_layers(current_resolver(), layer.clone())
677                })),
678                (None, Some(next_resolver)) => {
679                    let base = existing_snapshot.unwrap_or_default();
680                    Some(Rc::new(move || {
681                        merge_graphics_layers(base.clone(), next_resolver())
682                    }))
683                }
684                (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
685                    merge_graphics_layers(current_resolver(), next_resolver())
686                })),
687            };
688        if merged_resolver.is_some() {
689            self.rare_mut().graphics_layer_resolver = merged_resolver;
690        }
691    }
692
693    /// Returns these slices holding `handle`, which keeps the node chain they come from alive.
694    pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
695        self.rare_mut().chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
696        self
697    }
698
699    /// Returns counts and capacities of the slices' data, for memory diagnostics.
700    pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
701        let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
702        let pointer_input_capacity = self.rare().map_or(0, |rare| rare.pointer_inputs.capacity());
703        let pointer_input_bytes = pointer_input_capacity * size_of::<Rc<dyn Fn(PointerEvent)>>();
704        ModifierNodeSlicesDebugStats {
705            draw_command_count: self.draw_commands.len(),
706            draw_command_capacity: self.draw_commands.capacity(),
707            pointer_input_count: self.pointer_inputs().len(),
708            pointer_input_capacity,
709            has_text_content: self.text.is_some(),
710            has_text_style: self.text.is_some(),
711            has_text_layout_options: self.text.is_some(),
712            has_prepared_text_layout: self.text.is_some(),
713            has_graphics_layer: self.held_graphics_layer(),
714            has_graphics_layer_resolver: self
715                .rare()
716                .is_some_and(|rare| rare.graphics_layer_resolver.is_some()),
717            heap_bytes: draw_command_bytes + pointer_input_bytes,
718        }
719    }
720
721    // Whether the chain gave nothing: no draws, text, layer, clip, shape or
722    // rare part.
723    fn is_empty(&self) -> bool {
724        self.draw_commands.is_empty()
725            && self.layer.is_none()
726            && self.text.is_none()
727            && self.text_coordinator.is_none()
728            && self.rare.as_deref().is_none_or(RareSlices::is_empty)
729    }
730
731    /// Resets the slice collection for reuse, retaining vector capacity.
732    pub fn clear(&mut self) {
733        self.draw_commands.clear();
734        self.layer = None;
735        self.text = None;
736        self.text_coordinator = None;
737        if let Some(rare) = self.rare.as_deref_mut() {
738            rare.clear();
739        }
740    }
741}
742
743impl fmt::Debug for ModifierNodeSlices {
744    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745        f.debug_struct("ModifierNodeSlices")
746            .field("draw_commands", &self.draw_commands.len())
747            .field("pointer_inputs", &self.pointer_inputs().len())
748            .field("pointer_icon", &self.pointer_icon())
749            .field("clip_to_bounds", &self.clip_to_bounds())
750            .field("motion_context_animated", &self.motion_context_animated())
751            .field(
752                "translated_content_context",
753                &self.translated_content_context(),
754            )
755            .field(
756                "translated_content_context_identity",
757                &self.translated_content_context_identity(),
758            )
759            .field(
760                "translated_content_offset",
761                &self.translated_content_offset(),
762            )
763            .field("text_content", &self.annotated_text())
764            .field("text_style", &self.text_style())
765            .field("text_layout_options", &self.text_layout_options())
766            .field(
767                "graphics_layer",
768                &self
769                    .layer
770                    .as_ref()
771                    .and_then(|layer| layer.graphics_layer.as_ref()),
772            )
773            .field(
774                "graphics_layer_resolver",
775                &self
776                    .rare()
777                    .is_some_and(|rare| rare.graphics_layer_resolver.is_some()),
778            )
779            .field("clip_shape", &self.clip_shape())
780            .finish()
781    }
782}
783
784#[cfg(test)]
785#[path = "tests/slices_tests.rs"]
786mod tests;