Skip to main content

cranpose_ui/modifier/
slices.rs

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