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