Skip to main content

cranpose_ui/modifier/
slices.rs

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