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