Skip to main content

cranpose_ui/modifier/
slices.rs

1use std::fmt;
2use std::mem::size_of;
3use std::rc::Rc;
4
5use cranpose_foundation::{ModifierNodeChain, NodeCapabilities, PointerEvent};
6use cranpose_ui_graphics::{ColorFilter, GraphicsLayer, RenderEffect, RoundedCornerShape};
7
8use super::{ModifierChainHandle, Point};
9use crate::draw::DrawCommand;
10use crate::modifier::scroll::{MotionContextAnimatedNode, TranslatedContentContextNode};
11use crate::modifier::Modifier;
12use crate::modifier_nodes::{
13    BackgroundNode, ClipToBoundsNode, CornerShapeNode, DrawCommandNode, GraphicsLayerNode,
14    PaddingNode,
15};
16use crate::text::{TextLayoutOptions, TextStyle};
17use crate::text_field_modifier_node::{TextFieldModifierNode, TextPanResolver};
18use crate::text_modifier_node::{TextModifierNode, TextPreparedLayoutHandle};
19use cranpose_ui_graphics::EdgeInsets;
20
21/// Snapshot of modifier node slices that impact draw and pointer subsystems.
22#[derive(Default)]
23pub struct ModifierNodeSlices {
24    draw_commands: Vec<DrawCommand>,
25    pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
26    click_handlers: Vec<Rc<dyn Fn(Point)>>,
27    clip_to_bounds: bool,
28    motion_context_animated: bool,
29    translated_content_context: bool,
30    translated_content_context_identity: Option<usize>,
31    translated_content_offset_reader: Option<Rc<dyn Fn() -> Point>>,
32    text_content: Option<Rc<crate::text::AnnotatedString>>,
33    text_style: Option<TextStyle>,
34    text_layout_options: Option<TextLayoutOptions>,
35    prepared_text_layout: Option<TextPreparedLayoutHandle>,
36    text_pan: Option<TextPanResolver>,
37    graphics_layer: Option<GraphicsLayer>,
38    graphics_layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
39    corner_shape: Option<RoundedCornerShape>,
40    chain_guard: Option<Rc<ChainGuard>>,
41}
42
43struct ChainGuard {
44    _handle: ModifierChainHandle,
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub struct ModifierNodeSlicesDebugStats {
49    pub draw_command_count: usize,
50    pub draw_command_capacity: usize,
51    pub pointer_input_count: usize,
52    pub pointer_input_capacity: usize,
53    pub click_handler_count: usize,
54    pub click_handler_capacity: usize,
55    pub has_text_content: bool,
56    pub has_text_style: bool,
57    pub has_text_layout_options: bool,
58    pub has_prepared_text_layout: bool,
59    pub has_graphics_layer: bool,
60    pub has_graphics_layer_resolver: bool,
61    pub heap_bytes: usize,
62}
63
64impl Clone for ModifierNodeSlices {
65    fn clone(&self) -> Self {
66        Self {
67            draw_commands: self.draw_commands.clone(),
68            pointer_inputs: self.pointer_inputs.clone(),
69            click_handlers: self.click_handlers.clone(),
70            clip_to_bounds: self.clip_to_bounds,
71            motion_context_animated: self.motion_context_animated,
72            translated_content_context: self.translated_content_context,
73            translated_content_context_identity: self.translated_content_context_identity,
74            translated_content_offset_reader: self.translated_content_offset_reader.clone(),
75            text_content: self.text_content.clone(),
76            text_style: self.text_style.clone(),
77            text_layout_options: self.text_layout_options,
78            prepared_text_layout: self.prepared_text_layout.clone(),
79            text_pan: self.text_pan.clone(),
80            graphics_layer: self.graphics_layer.clone(),
81            graphics_layer_resolver: self.graphics_layer_resolver.clone(),
82            corner_shape: self.corner_shape,
83            chain_guard: self.chain_guard.clone(),
84        }
85    }
86}
87
88/// Compose two nested graphics layers (`base` outer, `overlay` inner) into one
89/// flattened layer snapshot used by render pipelines.
90///
91/// Composition rules follow how nested transforms/effects behave visually:
92/// - Multiplicative: `alpha`, `scale`, `scale_x`, `scale_y`
93/// - Additive: `rotation_*`, `translation_*`
94/// - Boolean OR: `clip`
95/// - Overlay-wins when explicitly set: camera distance, transform origin,
96///   shadow elevation/colors, shape, compositing strategy, blend mode
97/// - Filters/effects are composed in draw order:
98///   - color filters are multiplied where possible
99///   - render effects chain inner-first then outer (`inner.then(outer)`)
100/// - Backdrop effect keeps the most local explicit backdrop effect because
101///   backdrop sampling cannot be safely flattened as a deterministic chain.
102fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
103    GraphicsLayer {
104        alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
105        scale: base.scale * overlay.scale,
106        scale_x: base.scale_x * overlay.scale_x,
107        scale_y: base.scale_y * overlay.scale_y,
108        rotation_x: base.rotation_x + overlay.rotation_x,
109        rotation_y: base.rotation_y + overlay.rotation_y,
110        rotation_z: base.rotation_z + overlay.rotation_z,
111        camera_distance: overlay.camera_distance,
112        transform_origin: overlay.transform_origin,
113        translation_x: base.translation_x + overlay.translation_x,
114        translation_y: base.translation_y + overlay.translation_y,
115        shadow_elevation: overlay.shadow_elevation,
116        ambient_shadow_color: overlay.ambient_shadow_color,
117        spot_shadow_color: overlay.spot_shadow_color,
118        shape: overlay.shape,
119        clip: base.clip || overlay.clip,
120        compositing_strategy: overlay.compositing_strategy,
121        blend_mode: overlay.blend_mode,
122        color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
123        // Modifiers are traversed outer -> inner. Layer effects therefore compose
124        // inner-first, then outer, matching nested layer rendering semantics.
125        render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
126        // Backdrop effects cannot be represented as a deterministic chain on a
127        // flattened single layer, so keep the most local explicit backdrop.
128        backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
129    }
130}
131
132fn compose_render_effects(
133    outer: Option<RenderEffect>,
134    inner: Option<RenderEffect>,
135) -> Option<RenderEffect> {
136    match (outer, inner) {
137        (None, None) => None,
138        (Some(effect), None) | (None, Some(effect)) => Some(effect),
139        (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
140    }
141}
142
143fn compose_color_filters(
144    base: Option<ColorFilter>,
145    overlay: Option<ColorFilter>,
146) -> Option<ColorFilter> {
147    match (base, overlay) {
148        (None, None) => None,
149        (Some(filter), None) | (None, Some(filter)) => Some(filter),
150        (Some(filter), Some(next)) => Some(filter.compose(next)),
151    }
152}
153
154impl ModifierNodeSlices {
155    pub fn draw_commands(&self) -> &[DrawCommand] {
156        &self.draw_commands
157    }
158
159    pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
160        &self.pointer_inputs
161    }
162
163    pub fn click_handlers(&self) -> &[Rc<dyn Fn(Point)>] {
164        &self.click_handlers
165    }
166
167    pub fn clip_to_bounds(&self) -> bool {
168        self.clip_to_bounds
169    }
170
171    pub fn motion_context_animated(&self) -> bool {
172        self.motion_context_animated
173    }
174
175    pub fn translated_content_context(&self) -> bool {
176        self.translated_content_context
177    }
178
179    pub fn translated_content_context_identity(&self) -> Option<usize> {
180        self.translated_content_context_identity
181    }
182
183    pub fn translated_content_offset(&self) -> Option<Point> {
184        self.translated_content_offset_reader
185            .as_ref()
186            .map(|reader| reader())
187    }
188
189    pub fn text_content(&self) -> Option<&str> {
190        self.text_content.as_ref().map(|a| a.text.as_str())
191    }
192
193    pub fn annotated_text(&self) -> Option<&crate::text::AnnotatedString> {
194        self.text_content.as_deref()
195    }
196
197    pub fn annotated_string(&self) -> Option<crate::text::AnnotatedString> {
198        self.annotated_text().cloned()
199    }
200
201    pub fn text_style(&self) -> Option<&TextStyle> {
202        self.text_style.as_ref()
203    }
204
205    pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
206        self.text_layout_options
207    }
208
209    /// Returns the horizontal pan resolver for single-line text fields.
210    ///
211    /// The resolver takes the content viewport width (px) and returns the
212    /// horizontal scroll offset that keeps the cursor visible. Renderers
213    /// subtract this offset from the text origin so the glyphs pan together
214    /// with the cursor and selection.
215    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
216        self.text_pan.clone()
217    }
218
219    pub fn prepare_text_layout(
220        &self,
221        max_width: Option<f32>,
222    ) -> Option<crate::text::PreparedTextLayout> {
223        if let Some(handle) = &self.prepared_text_layout {
224            return Some(handle.prepare(max_width));
225        }
226
227        let text = self.annotated_text()?;
228        let style = self.text_style.clone().unwrap_or_default();
229        Some(crate::text::prepare_text_layout(
230            text,
231            &style,
232            self.text_layout_options.unwrap_or_default(),
233            max_width,
234        ))
235    }
236
237    pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
238        if let Some(resolve) = &self.graphics_layer_resolver {
239            Some(resolve())
240        } else {
241            self.graphics_layer.clone()
242        }
243    }
244
245    pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
246        self.corner_shape
247    }
248
249    fn push_graphics_layer(
250        &mut self,
251        layer: GraphicsLayer,
252        resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
253    ) {
254        let existing_snapshot = self.graphics_layer.clone();
255        let next_snapshot = existing_snapshot
256            .as_ref()
257            .map(|current| merge_graphics_layers(current.clone(), layer.clone()))
258            .unwrap_or_else(|| layer.clone());
259        let existing_resolver = self.graphics_layer_resolver.clone();
260
261        self.graphics_layer = Some(next_snapshot);
262        self.graphics_layer_resolver = match (existing_resolver, resolver) {
263            (None, None) => None,
264            (Some(current_resolver), None) => {
265                let layer = layer.clone();
266                Some(Rc::new(move || {
267                    merge_graphics_layers(current_resolver(), layer.clone())
268                }))
269            }
270            (None, Some(next_resolver)) => {
271                let base = existing_snapshot.unwrap_or_default();
272                Some(Rc::new(move || {
273                    merge_graphics_layers(base.clone(), next_resolver())
274                }))
275            }
276            (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
277                merge_graphics_layers(current_resolver(), next_resolver())
278            })),
279        };
280    }
281
282    pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
283        self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
284        self
285    }
286
287    pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
288        let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
289        let pointer_input_bytes =
290            self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
291        let click_handler_bytes = self.click_handlers.capacity() * size_of::<Rc<dyn Fn(Point)>>();
292        ModifierNodeSlicesDebugStats {
293            draw_command_count: self.draw_commands.len(),
294            draw_command_capacity: self.draw_commands.capacity(),
295            pointer_input_count: self.pointer_inputs.len(),
296            pointer_input_capacity: self.pointer_inputs.capacity(),
297            click_handler_count: self.click_handlers.len(),
298            click_handler_capacity: self.click_handlers.capacity(),
299            has_text_content: self.text_content.is_some(),
300            has_text_style: self.text_style.is_some(),
301            has_text_layout_options: self.text_layout_options.is_some(),
302            has_prepared_text_layout: self.prepared_text_layout.is_some(),
303            has_graphics_layer: self.graphics_layer.is_some(),
304            has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
305            heap_bytes: draw_command_bytes + pointer_input_bytes + click_handler_bytes,
306        }
307    }
308
309    /// Resets the slice collection for reuse, retaining vector capacity.
310    pub fn clear(&mut self) {
311        self.draw_commands.clear();
312        self.pointer_inputs.clear();
313        self.click_handlers.clear();
314        self.clip_to_bounds = false;
315        self.motion_context_animated = false;
316        self.translated_content_context = false;
317        self.translated_content_context_identity = None;
318        self.translated_content_offset_reader = None;
319        self.text_content = None;
320        self.text_style = None;
321        self.text_layout_options = None;
322        self.prepared_text_layout = None;
323        self.text_pan = None;
324        self.graphics_layer = None;
325        self.graphics_layer_resolver = None;
326        self.corner_shape = None;
327        self.chain_guard = None;
328    }
329}
330
331impl fmt::Debug for ModifierNodeSlices {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        f.debug_struct("ModifierNodeSlices")
334            .field("draw_commands", &self.draw_commands.len())
335            .field("pointer_inputs", &self.pointer_inputs.len())
336            .field("click_handlers", &self.click_handlers.len())
337            .field("clip_to_bounds", &self.clip_to_bounds)
338            .field("motion_context_animated", &self.motion_context_animated)
339            .field(
340                "translated_content_context",
341                &self.translated_content_context,
342            )
343            .field(
344                "translated_content_context_identity",
345                &self.translated_content_context_identity,
346            )
347            .field(
348                "translated_content_offset",
349                &self.translated_content_offset(),
350            )
351            .field("text_content", &self.text_content)
352            .field("text_style", &self.text_style)
353            .field("text_layout_options", &self.text_layout_options)
354            .field("prepared_text_layout", &self.prepared_text_layout.is_some())
355            .field("graphics_layer", &self.graphics_layer)
356            .field(
357                "graphics_layer_resolver",
358                &self.graphics_layer_resolver.is_some(),
359            )
360            .field("corner_shape", &self.corner_shape)
361            .finish()
362    }
363}
364
365/// Collects modifier node slices directly from a reconciled [`ModifierNodeChain`].
366pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
367    let mut slices = ModifierNodeSlices::default();
368    collect_modifier_slices_into(chain, &mut slices);
369    slices
370}
371
372/// Collects modifier node slices into an existing buffer to reuse allocations.
373///
374/// Single-pass: iterates the chain once instead of 4 separate capability-filtered
375/// traversals, reducing per-node `RefCell::borrow()` overhead.
376pub fn collect_modifier_slices_into(chain: &ModifierNodeChain, slices: &mut ModifierNodeSlices) {
377    slices.clear();
378
379    let caps = chain.capabilities();
380    let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
381    let has_draw = caps.intersects(NodeCapabilities::DRAW);
382    let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
383
384    if !has_pointer && !has_draw && !has_layout {
385        return;
386    }
387
388    let mut background_color = None;
389    let mut background_insert_index = None::<usize>;
390    let mut corner_shape = None;
391    let mut padding = EdgeInsets::default();
392
393    for node_ref in chain.head_to_tail() {
394        let node_caps = node_ref.kind_set();
395
396        node_ref.with_node(|node| {
397            let any = node.as_any();
398
399            // POINTER_INPUT collection
400            if has_pointer && node_caps.intersects(NodeCapabilities::POINTER_INPUT) {
401                if let Some(handler) = node
402                    .as_pointer_input_node()
403                    .and_then(|n| n.pointer_input_handler())
404                {
405                    slices.pointer_inputs.push(handler);
406                }
407            }
408
409            // DRAW collection
410            if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
411                if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
412                    background_color = Some(bg_node.color());
413                    background_insert_index = Some(slices.draw_commands.len());
414                    if bg_node.shape().is_some() {
415                        corner_shape = bg_node.shape();
416                    }
417                }
418
419                if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
420                    corner_shape = Some(shape_node.shape());
421                }
422
423                if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
424                    slices.draw_commands.extend(commands.observed_commands());
425                }
426
427                if let Some(draw_node) = node.as_draw_node() {
428                    if let Some(closure) = draw_node.create_draw_closure() {
429                        slices.draw_commands.push(DrawCommand::Overlay(closure));
430                    } else {
431                        use cranpose_ui_graphics::{DrawScope as _, DrawScopeDefault};
432                        let mut scope = DrawScopeDefault::new(crate::modifier::Size {
433                            width: 0.0,
434                            height: 0.0,
435                        });
436                        draw_node.draw(&mut scope);
437                        let primitives = scope.into_primitives();
438                        if !primitives.is_empty() {
439                            let draw_cmd =
440                                Rc::new(move |_size: crate::modifier::Size| primitives.clone());
441                            slices.draw_commands.push(DrawCommand::Overlay(draw_cmd));
442                        }
443                    }
444                }
445
446                if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
447                    slices.push_graphics_layer(
448                        layer_node.layer_snapshot(),
449                        layer_node.layer_resolver(),
450                    );
451                }
452
453                if any.is::<ClipToBoundsNode>() {
454                    slices.clip_to_bounds = true;
455                }
456            }
457
458            // LAYOUT collection (padding + text)
459            if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
460                if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
461                    let p = padding_node.padding();
462                    padding.left += p.left;
463                    padding.top += p.top;
464                    padding.right += p.right;
465                    padding.bottom += p.bottom;
466                }
467
468                if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
469                    slices.motion_context_animated = motion_context_node.is_active();
470                }
471
472                if let Some(translated_content_node) =
473                    any.downcast_ref::<TranslatedContentContextNode>()
474                {
475                    slices.translated_content_context = translated_content_node.is_active();
476                    slices.translated_content_context_identity =
477                        Some(translated_content_node.identity());
478                    slices.translated_content_offset_reader =
479                        translated_content_node.content_offset_reader();
480                }
481
482                if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
483                    slices.text_content = Some(text_node.annotated_text());
484                    slices.text_style = Some(text_node.style().clone());
485                    slices.text_layout_options = Some(text_node.options());
486                    slices.prepared_text_layout = Some(text_node.prepared_layout_handle());
487                }
488
489                if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
490                    let text = text_field_node.text();
491                    slices.text_content = Some(Rc::new(crate::text::AnnotatedString::from(text)));
492                    slices.text_style = Some(text_field_node.style().clone());
493                    slices.text_layout_options = Some(TextLayoutOptions::default());
494                    slices.prepared_text_layout = None;
495                    slices.text_pan = text_field_node.text_pan_resolver();
496
497                    text_field_node.set_content_offset(padding.left);
498                    text_field_node.set_content_y_offset(padding.top);
499                }
500            }
501        });
502    }
503
504    slices.corner_shape = corner_shape;
505
506    // Convert background + shape into a draw command
507    if let Some(color) = background_color {
508        let draw_cmd = Rc::new(move |size: crate::modifier::Size| {
509            use crate::modifier::{Brush, Rect};
510            use cranpose_ui_graphics::DrawPrimitive;
511
512            let brush = Brush::solid(color);
513            let rect = Rect {
514                x: 0.0,
515                y: 0.0,
516                width: size.width,
517                height: size.height,
518            };
519
520            if let Some(shape) = corner_shape {
521                let radii = shape.resolve(size.width, size.height);
522                vec![DrawPrimitive::RoundRect { rect, brush, radii }]
523            } else {
524                vec![DrawPrimitive::Rect { rect, brush }]
525            }
526        });
527
528        let insert_index = background_insert_index
529            .unwrap_or(0)
530            .min(slices.draw_commands.len());
531        slices
532            .draw_commands
533            .insert(insert_index, DrawCommand::Behind(draw_cmd));
534    }
535}
536
537/// Collects modifier node slices by instantiating a temporary node chain from a [`Modifier`].
538pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
539    let mut handle = ModifierChainHandle::new();
540    let _ = handle.update(modifier);
541    collect_modifier_slices(handle.chain()).with_chain_guard(handle)
542}