1use std::{fmt, mem::size_of, rc::Rc};
2
3use cranpose_foundation::{ModifierNodeChain, NodeCapabilities, PointerEvent, PointerEventKind};
4use cranpose_ui_graphics::{
5 ColorFilter, EdgeInsets, GraphicsLayer, LayerShape, PointerIcon, Rect, RenderEffect,
6 RoundedCornerShape, Size,
7};
8use smallvec::SmallVec;
9
10use super::{
11 ModifierChainHandle, Point,
12 coordinator_geometry::{CoordinatorGeometry, CoordinatorRect},
13};
14use crate::{
15 draw::DrawCommand,
16 modifier::{
17 Modifier,
18 scroll::{MotionContextAnimatedNode, TranslatedContentContextNode},
19 },
20 modifier_nodes::{
21 BackgroundNode, ClipToBoundsNode, CornerShapeNode, DrawCommandNode, GraphicsLayerNode,
22 PaddingNode, PointerIconNode, SelectableTextNode, WindowRectReporterNode,
23 },
24 text::{TextLayoutOptions, TextStyle},
25 text_field_modifier_node::{TextFieldLayoutHandle, TextFieldModifierNode, TextPanResolver},
26 text_modifier_node::{TextModifierNode, TextPreparedLayoutHandle},
27};
28
29#[derive(Default)]
31pub struct ModifierNodeSlices {
32 draw_commands: Vec<DrawCommand>,
33 layer_draw_boundary: Option<usize>,
34 pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
35 pointer_input_sizes: Vec<Rc<std::cell::Cell<cranpose_ui_graphics::Size>>>,
36 pointer_icon: Option<PointerIcon>,
37 clip_to_bounds: bool,
38 layer_coordinator: Option<CoordinatorRect>,
41 motion_context_animated: bool,
42 translated_content_context: bool,
43 translated_content_context_identity: Option<usize>,
44 translated_content_offset_reader: Option<Rc<dyn Fn() -> Point>>,
45 text_content: Option<Rc<crate::text::AnnotatedString>>,
46 text_coordinator: Option<CoordinatorRect>,
47 text_style: Option<TextStyle>,
48 text_layout_options: Option<TextLayoutOptions>,
49 prepared_text_layout: Option<MeasuredTextLayoutSource>,
50 text_pan: Option<TextPanResolver>,
51 text_window_origin: Option<Rc<std::cell::Cell<Point>>>,
52 viewport_window_rect: Option<Rc<dyn crate::modifier_nodes::WindowRectSink>>,
53 graphics_layer: Option<GraphicsLayer>,
54 graphics_layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
55 corner_shape: Option<RoundedCornerShape>,
56 chain_guard: Option<Rc<ChainGuard>>,
57}
58
59struct ChainGuard {
60 _handle: ModifierChainHandle,
61}
62
63#[derive(Clone)]
64enum MeasuredTextLayoutSource {
65 Text(TextPreparedLayoutHandle),
66 TextField(TextFieldLayoutHandle),
67}
68
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub struct ModifierNodeSlicesDebugStats {
71 pub draw_command_count: usize,
72 pub draw_command_capacity: usize,
73 pub pointer_input_count: usize,
74 pub pointer_input_capacity: usize,
75 pub has_text_content: bool,
76 pub has_text_style: bool,
77 pub has_text_layout_options: bool,
78 pub has_prepared_text_layout: bool,
79 pub has_graphics_layer: bool,
80 pub has_graphics_layer_resolver: bool,
81 pub heap_bytes: usize,
82}
83
84impl Clone for ModifierNodeSlices {
85 fn clone(&self) -> Self {
86 Self {
87 draw_commands: self.draw_commands.clone(),
88 layer_draw_boundary: self.layer_draw_boundary,
89 pointer_inputs: self.pointer_inputs.clone(),
90 pointer_input_sizes: self.pointer_input_sizes.clone(),
91 pointer_icon: self.pointer_icon.clone(),
92 clip_to_bounds: self.clip_to_bounds,
93 layer_coordinator: self.layer_coordinator.clone(),
94 motion_context_animated: self.motion_context_animated,
95 translated_content_context: self.translated_content_context,
96 translated_content_context_identity: self.translated_content_context_identity,
97 translated_content_offset_reader: self.translated_content_offset_reader.clone(),
98 text_content: self.text_content.clone(),
99 text_coordinator: self.text_coordinator.clone(),
100 text_style: self.text_style.clone(),
101 text_layout_options: self.text_layout_options,
102 prepared_text_layout: self.prepared_text_layout.clone(),
103 text_pan: self.text_pan.clone(),
104 text_window_origin: self.text_window_origin.clone(),
105 viewport_window_rect: self.viewport_window_rect.clone(),
106 graphics_layer: self.graphics_layer.clone(),
107 graphics_layer_resolver: self.graphics_layer_resolver.clone(),
108 corner_shape: self.corner_shape,
109 chain_guard: self.chain_guard.clone(),
110 }
111 }
112}
113
114fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
115 GraphicsLayer {
116 alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
117 scale: base.scale * overlay.scale,
118 scale_x: base.scale_x * overlay.scale_x,
119 scale_y: base.scale_y * overlay.scale_y,
120 rotation_x: base.rotation_x + overlay.rotation_x,
121 rotation_y: base.rotation_y + overlay.rotation_y,
122 rotation_z: base.rotation_z + overlay.rotation_z,
123 camera_distance: transform_frame(&base, &overlay).camera_distance,
124 transform_origin: transform_frame(&base, &overlay).transform_origin,
125 translation_x: base.translation_x + overlay.translation_x,
126 translation_y: base.translation_y + overlay.translation_y,
127 shadow_elevation: overlay.shadow_elevation,
128 ambient_shadow_color: overlay.ambient_shadow_color,
129 spot_shadow_color: overlay.spot_shadow_color,
130 shape: merged_layer_shape(&base, &overlay),
131 clip: base.clip || overlay.clip,
132 compositing_strategy: overlay.compositing_strategy,
133 blend_mode: overlay.blend_mode,
134 color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
135 render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
136 backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
137 }
138}
139
140fn transform_frame<'a>(base: &'a GraphicsLayer, overlay: &'a GraphicsLayer) -> &'a GraphicsLayer {
146 let transforms = |layer: &GraphicsLayer| {
147 layer.rotation_x != 0.0
148 || layer.rotation_y != 0.0
149 || layer.rotation_z != 0.0
150 || layer.scale != 1.0
151 || layer.scale_x != 1.0
152 || layer.scale_y != 1.0
153 };
154 if transforms(overlay) || !transforms(base) {
155 overlay
156 } else {
157 base
158 }
159}
160
161fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
166 if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
167 overlay.shape
168 } else if base.clip || base.backdrop_effect.is_some() {
169 base.shape
170 } else {
171 overlay.shape
172 }
173}
174
175fn compose_render_effects(
176 outer: Option<RenderEffect>,
177 inner: Option<RenderEffect>,
178) -> Option<RenderEffect> {
179 match (outer, inner) {
180 (None, None) => None,
181 (Some(effect), None) | (None, Some(effect)) => Some(effect),
182 (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
183 }
184}
185
186fn compose_color_filters(
187 base: Option<ColorFilter>,
188 overlay: Option<ColorFilter>,
189) -> Option<ColorFilter> {
190 match (base, overlay) {
191 (None, None) => None,
192 (Some(filter), None) | (None, Some(filter)) => Some(filter),
193 (Some(filter), Some(next)) => Some(filter.compose(next)),
194 }
195}
196
197impl ModifierNodeSlices {
198 pub fn draw_commands(&self) -> &[DrawCommand] {
199 &self.draw_commands
200 }
201
202 pub fn outer_draw_command_count(&self) -> usize {
207 self.layer_draw_boundary.unwrap_or(0)
208 }
209
210 fn insert_background_draw(
211 &mut self,
212 insert_index: usize,
213 precedes_layer: bool,
214 command: DrawCommand,
215 ) {
216 let insert_index = insert_index.min(self.draw_commands.len());
217 self.draw_commands.insert(insert_index, command);
218 if let Some(boundary) = self.layer_draw_boundary.as_mut()
219 && precedes_layer
220 {
221 *boundary += 1;
222 }
223 }
224
225 fn mark_layer_draw_boundary(&mut self) {
226 if self.layer_draw_boundary.is_none() {
227 self.layer_draw_boundary = Some(self.draw_commands.len());
228 }
229 }
230
231 pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
232 &self.pointer_inputs
233 }
234
235 pub fn dispatch_pointer_event(&self, event: PointerEvent) {
239 let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
240 for handler in &self.pointer_inputs {
241 if event.is_consumed() && !terminal {
242 break;
243 }
244 handler(event.clone());
245 }
246 }
247
248 pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<cranpose_ui_graphics::Size>>] {
252 &self.pointer_input_sizes
253 }
254
255 pub fn publish_pointer_input_size(&self, size: cranpose_ui_graphics::Size) {
267 for sink in &self.pointer_input_sizes {
268 sink.set(size);
269 }
270 }
271
272 pub fn pointer_icon(&self) -> Option<&PointerIcon> {
275 self.pointer_icon.as_ref()
276 }
277
278 pub fn clip_to_bounds(&self) -> bool {
279 self.clip_to_bounds
280 }
281
282 pub fn layer_bounds(&self, node_size: Size) -> Rect {
288 self.layer_coordinator
289 .as_ref()
290 .map_or_else(|| Rect::from_size(node_size), |layer| layer.rect(node_size))
291 }
292
293 pub fn motion_context_animated(&self) -> bool {
294 self.motion_context_animated
295 }
296
297 pub fn translated_content_context(&self) -> bool {
298 self.translated_content_context
299 }
300
301 pub fn translated_content_context_identity(&self) -> Option<usize> {
302 self.translated_content_context_identity
303 }
304
305 pub fn translated_content_offset(&self) -> Option<Point> {
306 self.translated_content_offset_reader
307 .as_ref()
308 .map(|reader| reader())
309 }
310
311 pub fn text_content(&self) -> Option<&str> {
312 self.text_content.as_ref().map(|a| a.text.as_str())
313 }
314
315 pub fn annotated_text(&self) -> Option<&Rc<crate::text::AnnotatedString>> {
316 self.text_content.as_ref()
317 }
318
319 pub fn text_content_rect(&self, node_size: Size) -> Rect {
322 self.text_coordinator.as_ref().map_or(
323 Rect {
324 x: 0.0,
325 y: 0.0,
326 width: node_size.width,
327 height: node_size.height,
328 },
329 |coordinator| coordinator.rect(node_size),
330 )
331 }
332
333 pub fn text_style(&self) -> Option<&TextStyle> {
334 self.text_style.as_ref()
335 }
336
337 pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
338 self.text_layout_options
339 }
340
341 pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
348 self.text_pan.clone()
349 }
350
351 pub fn text_window_origin(&self) -> Option<Rc<std::cell::Cell<Point>>> {
357 self.text_window_origin.clone()
358 }
359
360 pub fn viewport_window_rect(&self) -> Option<Rc<dyn crate::modifier_nodes::WindowRectSink>> {
365 self.viewport_window_rect.clone()
366 }
367
368 pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
375 match self.prepared_text_layout.as_ref()? {
376 MeasuredTextLayoutSource::Text(handle) => handle.measured_layout(),
377 MeasuredTextLayoutSource::TextField(handle) => {
378 Some(handle.measured_layout(self.text_style.as_ref()?))
379 }
380 }
381 }
382
383 pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
384 if let Some(resolve) = &self.graphics_layer_resolver {
385 Some(resolve())
386 } else {
387 self.graphics_layer.clone()
388 }
389 }
390
391 pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
392 self.corner_shape
393 }
394
395 fn enter_layer(&mut self, site: &DrawSite) {
398 if self.layer_coordinator.is_none() {
399 self.layer_coordinator = Some(site.coordinator.clone());
400 }
401 }
402
403 fn push_graphics_layer(
404 &mut self,
405 layer: GraphicsLayer,
406 resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
407 ) {
408 let existing_snapshot = self.graphics_layer.clone();
409 let next_snapshot = existing_snapshot.as_ref().map_or_else(
410 || layer.clone(),
411 |current| merge_graphics_layers(current.clone(), layer.clone()),
412 );
413 let existing_resolver = self.graphics_layer_resolver.clone();
414
415 self.graphics_layer = Some(next_snapshot);
416 self.graphics_layer_resolver = match (existing_resolver, resolver) {
417 (None, None) => None,
418 (Some(current_resolver), None) => Some(Rc::new(move || {
419 merge_graphics_layers(current_resolver(), layer.clone())
420 })),
421 (None, Some(next_resolver)) => {
422 let base = existing_snapshot.unwrap_or_default();
423 Some(Rc::new(move || {
424 merge_graphics_layers(base.clone(), next_resolver())
425 }))
426 }
427 (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
428 merge_graphics_layers(current_resolver(), next_resolver())
429 })),
430 };
431 }
432
433 pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
434 self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
435 self
436 }
437
438 pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
439 let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
440 let pointer_input_bytes =
441 self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
442 ModifierNodeSlicesDebugStats {
443 draw_command_count: self.draw_commands.len(),
444 draw_command_capacity: self.draw_commands.capacity(),
445 pointer_input_count: self.pointer_inputs.len(),
446 pointer_input_capacity: self.pointer_inputs.capacity(),
447 has_text_content: self.text_content.is_some(),
448 has_text_style: self.text_style.is_some(),
449 has_text_layout_options: self.text_layout_options.is_some(),
450 has_prepared_text_layout: self.prepared_text_layout.is_some(),
451 has_graphics_layer: self.graphics_layer.is_some(),
452 has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
453 heap_bytes: draw_command_bytes + pointer_input_bytes,
454 }
455 }
456
457 pub fn clear(&mut self) {
459 self.draw_commands.clear();
460 self.layer_draw_boundary = None;
461 self.pointer_inputs.clear();
462 self.pointer_input_sizes.clear();
463 self.pointer_icon = None;
464 self.clip_to_bounds = false;
465 self.layer_coordinator = None;
466 self.motion_context_animated = false;
467 self.translated_content_context = false;
468 self.translated_content_context_identity = None;
469 self.translated_content_offset_reader = None;
470 self.text_content = None;
471 self.text_coordinator = None;
472 self.text_style = None;
473 self.text_layout_options = None;
474 self.prepared_text_layout = None;
475 self.text_pan = None;
476 self.graphics_layer = None;
477 self.graphics_layer_resolver = None;
478 self.corner_shape = None;
479 self.chain_guard = None;
480 }
481}
482
483impl fmt::Debug for ModifierNodeSlices {
484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485 f.debug_struct("ModifierNodeSlices")
486 .field("draw_commands", &self.draw_commands.len())
487 .field("pointer_inputs", &self.pointer_inputs.len())
488 .field("pointer_icon", &self.pointer_icon)
489 .field("clip_to_bounds", &self.clip_to_bounds)
490 .field("motion_context_animated", &self.motion_context_animated)
491 .field(
492 "translated_content_context",
493 &self.translated_content_context,
494 )
495 .field(
496 "translated_content_context_identity",
497 &self.translated_content_context_identity,
498 )
499 .field(
500 "translated_content_offset",
501 &self.translated_content_offset(),
502 )
503 .field("text_content", &self.text_content)
504 .field("text_style", &self.text_style)
505 .field("text_layout_options", &self.text_layout_options)
506 .field("prepared_text_layout", &self.prepared_text_layout.is_some())
507 .field("graphics_layer", &self.graphics_layer)
508 .field(
509 "graphics_layer_resolver",
510 &self.graphics_layer_resolver.is_some(),
511 )
512 .field("corner_shape", &self.corner_shape)
513 .finish()
514 }
515}
516
517fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
523 if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
524 slices.pointer_icon = Some(icon_node.icon().clone());
525 }
526}
527
528pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
531 let mut slices = ModifierNodeSlices::default();
532 collect_modifier_slices_into(chain, &mut slices, &Rc::default(), 1.0);
533 slices
534}
535
536pub(crate) fn collect_modifier_slices_into_shared(
547 chain: &ModifierNodeChain,
548 slices: &mut Rc<ModifierNodeSlices>,
549 geometry: &Rc<CoordinatorGeometry>,
550 density: f32,
551) {
552 if Rc::get_mut(slices).is_none() {
553 *slices = Rc::default();
554 }
555 if let Some(slices) = Rc::get_mut(slices) {
556 collect_modifier_slices_into(chain, slices, geometry, density);
557 }
558}
559
560fn collect_modifier_slices_into(
561 chain: &ModifierNodeChain,
562 slices: &mut ModifierNodeSlices,
563 geometry: &Rc<CoordinatorGeometry>,
564 density: f32,
565) {
566 slices.clear();
567
568 let caps = chain.capabilities();
569 let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
570 let has_draw = caps.intersects(NodeCapabilities::DRAW);
571 let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
572
573 if !has_pointer && !has_draw && !has_layout {
574 return;
575 }
576
577 let mut backgrounds = Backgrounds::default();
578 let mut padding = EdgeInsets::default();
579 let mut layout_ordinal = 0_usize;
583
584 for node_ref in chain.head_to_tail() {
585 let node_caps = node_ref.kind_set();
586
587 node_ref.with_node(|node| {
588 let any = node.as_any();
589
590 if has_pointer
591 && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
592 && let Some(pointer_node) = node.as_pointer_input_node()
593 {
594 if let Some(handler) = pointer_node.pointer_input_handler() {
595 slices.pointer_inputs.push(handler);
596 }
597 if let Some(sink) = pointer_node.layout_size_sink() {
598 slices.pointer_input_sizes.push(sink);
599 }
600 collect_pointer_icon(any, slices);
601 }
602
603 if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
604 let draw = DrawSite {
605 coordinator: CoordinatorRect::new(geometry, layout_ordinal, padding),
606 displaceable: has_layout,
607 };
608 collect_draw_node(node, &draw, slices, &mut backgrounds);
609 }
610
611 if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
612 if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
613 padding +=
614 crate::modifier_nodes::device_padding(padding_node.padding(), density);
615 }
616
617 if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
618 slices.motion_context_animated = motion_context_node.is_active();
619 }
620
621 collect_window_geometry_sink(
622 any,
623 CoordinatorRect::new(geometry, layout_ordinal + 1, padding),
625 slices,
626 );
627
628 if let Some(translated_content_node) =
629 any.downcast_ref::<TranslatedContentContextNode>()
630 {
631 slices.translated_content_context = translated_content_node.is_active();
632 slices.translated_content_context_identity =
633 Some(translated_content_node.identity());
634 slices.translated_content_offset_reader =
635 translated_content_node.content_offset_reader();
636 }
637
638 if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
639 slices.text_content = Some(text_node.annotated_text());
640 slices.text_coordinator =
641 Some(CoordinatorRect::new(geometry, layout_ordinal, padding));
642 slices.text_style = Some(text_node.style().clone());
643 slices.text_layout_options = Some(text_node.options());
644 slices.prepared_text_layout = Some(MeasuredTextLayoutSource::Text(
645 text_node.prepared_layout_handle(),
646 ));
647 }
648
649 if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
650 let text = text_field_node.text();
651 slices.text_content = Some(Rc::new(crate::text::AnnotatedString::from(text)));
652 slices.text_style = Some(text_field_node.style().clone());
653 slices.text_layout_options = Some(TextLayoutOptions::default());
654 slices.prepared_text_layout = Some(MeasuredTextLayoutSource::TextField(
655 text_field_node.layout_handle(),
656 ));
657 slices.text_pan = text_field_node.text_pan_resolver();
658 slices.text_window_origin = Some(text_field_node.window_origin_sink());
659
660 let coordinator = CoordinatorRect::new(geometry, layout_ordinal, padding);
661 text_field_node.set_content_origin(coordinator.clone());
662 slices.text_coordinator = Some(coordinator);
663 }
664 layout_ordinal += 1;
665 }
666 });
667 }
668
669 backgrounds.insert_into(slices);
670}
671
672struct DrawSite {
675 coordinator: CoordinatorRect,
676 displaceable: bool,
677}
678
679#[derive(Default)]
684struct Backgrounds {
685 slots: SmallVec<[BackgroundSlot; 2]>,
686 pending_shape: Option<RoundedCornerShape>,
687 last_shape: Option<RoundedCornerShape>,
688}
689
690struct BackgroundSlot {
691 color: crate::modifier::Color,
692 coordinator: CoordinatorRect,
693 insert_index: usize,
694 precedes_layer: bool,
695 corner_shape: Option<RoundedCornerShape>,
696}
697
698impl Backgrounds {
699 fn push(
700 &mut self,
701 color: crate::modifier::Color,
702 shape: Option<RoundedCornerShape>,
703 site: &DrawSite,
704 slices: &ModifierNodeSlices,
705 ) {
706 let corner_shape = shape.or_else(|| self.pending_shape.take());
707 if shape.is_some() {
708 self.last_shape = shape;
709 }
710 self.slots.push(BackgroundSlot {
711 color,
712 coordinator: site.coordinator.clone(),
713 insert_index: slices.draw_commands.len(),
714 precedes_layer: slices.layer_draw_boundary.is_none(),
715 corner_shape,
716 });
717 }
718
719 fn shape(&mut self, shape: RoundedCornerShape) {
720 self.last_shape = Some(shape);
721 match self.slots.last_mut() {
722 Some(slot) => slot.corner_shape = Some(shape),
723 None => self.pending_shape = Some(shape),
724 }
725 }
726
727 fn insert_into(self, slices: &mut ModifierNodeSlices) {
730 slices.corner_shape = self.last_shape;
731 for slot in self.slots.into_iter().rev() {
732 let BackgroundSlot {
733 color,
734 coordinator,
735 insert_index,
736 precedes_layer,
737 corner_shape,
738 } = slot;
739 let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
740 use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
741
742 use crate::modifier::Brush;
743
744 let rect = coordinator.rect(scope.size());
745 let brush = Brush::solid(color);
746 if let Some(shape) = corner_shape {
747 let radii: CornerRadii = shape.resolve(rect.width, rect.height);
748 scope.draw_round_rect_at(rect, brush, radii);
749 } else {
750 scope.draw_rect_at(rect, brush);
751 }
752 });
753 slices.insert_background_draw(
754 insert_index,
755 precedes_layer,
756 DrawCommand::Behind(draw_cmd),
757 );
758 }
759 }
760}
761
762fn collect_window_geometry_sink(
765 any: &dyn std::any::Any,
766 text: CoordinatorRect,
767 slices: &mut ModifierNodeSlices,
768) {
769 if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
770 slices.viewport_window_rect = Some(reporter.window_rect_sink());
771 }
772 if let Some(selectable) = any.downcast_ref::<SelectableTextNode>() {
773 slices.text_window_origin = Some(selectable.geometry().node_origin_sink());
774 selectable.geometry().set_content_origin(text);
775 }
776}
777
778fn collect_draw_node(
780 node: &dyn cranpose_foundation::ModifierNode,
781 site: &DrawSite,
782 slices: &mut ModifierNodeSlices,
783 backgrounds: &mut Backgrounds,
784) {
785 let any = node.as_any();
786 if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
787 backgrounds.push(bg_node.color(), bg_node.shape(), site, slices);
788 }
789
790 if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
791 backgrounds.shape(shape_node.shape());
792 }
793
794 if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
795 slices.draw_commands.extend(
796 commands
797 .observed_commands()
798 .into_iter()
799 .map(|command| placed_draw_command(command, site)),
800 );
801 }
802
803 if let Some(draw_node) = node.as_draw_node() {
804 collect_draw_closures(draw_node, site, slices);
805 }
806
807 if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
808 slices.mark_layer_draw_boundary();
809 slices.push_graphics_layer(layer_node.layer_snapshot(), layer_node.layer_resolver());
810 slices.enter_layer(site);
811 }
812
813 if any.is::<ClipToBoundsNode>() {
814 slices.mark_layer_draw_boundary();
815 slices.clip_to_bounds = true;
816 slices.enter_layer(site);
817 }
818}
819
820fn collect_draw_closures(
823 draw_node: &dyn cranpose_foundation::DrawModifierNode,
824 site: &DrawSite,
825 slices: &mut ModifierNodeSlices,
826) {
827 if let Some(closure) = draw_node.create_behind_draw_closure() {
828 slices
829 .draw_commands
830 .push(placed_draw_command(DrawCommand::Behind(closure), site));
831 }
832 if let Some(closure) = draw_node.create_draw_closure() {
833 slices
834 .draw_commands
835 .push(placed_draw_command(DrawCommand::Overlay(closure), site));
836 }
837}
838
839fn placed_draw_command(command: DrawCommand, site: &DrawSite) -> DrawCommand {
842 if !site.displaceable {
843 return command;
844 }
845 let place = |draw: crate::draw::DrawCommandFn| -> crate::draw::DrawCommandFn {
846 let coordinator = site.coordinator.clone();
847 Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
848 use cranpose_ui_graphics::DrawScope as _;
849
850 let insets = coordinator.insets(scope.size());
851 if insets.is_zero() {
852 draw(scope);
853 } else {
854 scope.inset(insets, |inner| draw(inner));
855 }
856 })
857 };
858 match command {
859 DrawCommand::Behind(draw) => DrawCommand::Behind(place(draw)),
860 DrawCommand::WithContent(draw) => DrawCommand::WithContent(place(draw)),
861 DrawCommand::Overlay(draw) => DrawCommand::Overlay(place(draw)),
862 }
863}
864
865pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
867 let mut handle = ModifierChainHandle::new();
868 let _ = handle.update(modifier);
869 collect_modifier_slices(handle.chain()).with_chain_guard(handle)
870}
871
872#[cfg(test)]
873#[path = "tests/slices_tests.rs"]
874mod tests;