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