1use std::{cell::Ref, fmt, mem::size_of, ops::Deref, 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_transform: Option<Rc<std::cell::Cell<cranpose_ui_graphics::ProjectiveTransform>>>,
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
70pub struct SliceTextRef<'a, T: ?Sized>(TextBorrow<'a, T>);
74
75enum TextBorrow<'a, T: ?Sized> {
76 Layout(Ref<'a, T>),
77 Field(&'a T),
78}
79
80impl<'a, T: ?Sized> SliceTextRef<'a, T> {
81 fn map<U: ?Sized>(self, part: impl FnOnce(&T) -> &U) -> SliceTextRef<'a, U> {
82 SliceTextRef(match self.0 {
83 TextBorrow::Layout(text) => TextBorrow::Layout(Ref::map(text, part)),
84 TextBorrow::Field(text) => TextBorrow::Field(part(text)),
85 })
86 }
87}
88
89impl<T: ?Sized> Deref for SliceTextRef<'_, T> {
90 type Target = T;
91
92 fn deref(&self) -> &T {
93 match &self.0 {
94 TextBorrow::Layout(text) => text,
95 TextBorrow::Field(text) => text,
96 }
97 }
98}
99
100impl<T: ?Sized + fmt::Debug> fmt::Debug for SliceTextRef<'_, T> {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 (**self).fmt(f)
103 }
104}
105
106impl<T: ?Sized + fmt::Display> fmt::Display for SliceTextRef<'_, T> {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 (**self).fmt(f)
109 }
110}
111
112impl PartialEq<str> for SliceTextRef<'_, str> {
113 fn eq(&self, other: &str) -> bool {
114 **self == *other
115 }
116}
117
118impl PartialEq<&str> for SliceTextRef<'_, str> {
119 fn eq(&self, other: &&str) -> bool {
120 **self == **other
121 }
122}
123
124struct FieldText {
125 content: Rc<crate::text::AnnotatedString>,
126 style: TextStyle,
127 layout: TextFieldLayoutHandle,
128 pan: Option<TextPanResolver>,
129}
130
131#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub struct ModifierNodeSlicesDebugStats {
133 pub draw_command_count: usize,
134 pub draw_command_capacity: usize,
135 pub pointer_input_count: usize,
136 pub pointer_input_capacity: usize,
137 pub has_text_content: bool,
138 pub has_text_style: bool,
139 pub has_text_layout_options: bool,
140 pub has_prepared_text_layout: bool,
141 pub has_graphics_layer: bool,
142 pub has_graphics_layer_resolver: bool,
143 pub heap_bytes: usize,
144}
145
146impl Clone for ModifierNodeSlices {
147 fn clone(&self) -> Self {
148 Self {
149 draw_commands: self.draw_commands.clone(),
150 layer_draw_boundary: self.layer_draw_boundary,
151 pointer_inputs: self.pointer_inputs.clone(),
152 pointer_input_sizes: self.pointer_input_sizes.clone(),
153 pointer_icon: self.pointer_icon.clone(),
154 clip_to_bounds: self.clip_to_bounds,
155 layer_coordinator: self.layer_coordinator.clone(),
156 motion_context_animated: self.motion_context_animated,
157 translated_content_context: self.translated_content_context,
158 translated_content_context_identity: self.translated_content_context_identity,
159 translated_content_offset_reader: self.translated_content_offset_reader.clone(),
160 text: self.text.clone(),
161 text_coordinator: self.text_coordinator.clone(),
162 text_window_transform: self.text_window_transform.clone(),
163 viewport_window_rect: self.viewport_window_rect.clone(),
164 graphics_layer: self.graphics_layer.clone(),
165 graphics_layer_resolver: self.graphics_layer_resolver.clone(),
166 corner_shape: self.corner_shape,
167 chain_guard: self.chain_guard.clone(),
168 }
169 }
170}
171
172fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
173 GraphicsLayer {
174 alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
175 scale: base.scale * overlay.scale,
176 scale_x: base.scale_x * overlay.scale_x,
177 scale_y: base.scale_y * overlay.scale_y,
178 rotation_x: base.rotation_x + overlay.rotation_x,
179 rotation_y: base.rotation_y + overlay.rotation_y,
180 rotation_z: base.rotation_z + overlay.rotation_z,
181 camera_distance: transform_frame(&base, &overlay).camera_distance,
182 transform_origin: transform_frame(&base, &overlay).transform_origin,
183 translation_x: base.translation_x + overlay.translation_x,
184 translation_y: base.translation_y + overlay.translation_y,
185 shadow_elevation: overlay.shadow_elevation,
186 ambient_shadow_color: overlay.ambient_shadow_color,
187 spot_shadow_color: overlay.spot_shadow_color,
188 shape: merged_layer_shape(&base, &overlay),
189 clip: base.clip || overlay.clip,
190 compositing_strategy: overlay.compositing_strategy,
191 blend_mode: overlay.blend_mode,
192 color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
193 render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
194 backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
195 }
196}
197
198fn transform_frame<'a>(base: &'a GraphicsLayer, overlay: &'a GraphicsLayer) -> &'a GraphicsLayer {
204 let transforms = |layer: &GraphicsLayer| {
205 layer.rotation_x != 0.0
206 || layer.rotation_y != 0.0
207 || layer.rotation_z != 0.0
208 || layer.scale != 1.0
209 || layer.scale_x != 1.0
210 || layer.scale_y != 1.0
211 };
212 if transforms(overlay) || !transforms(base) {
213 overlay
214 } else {
215 base
216 }
217}
218
219fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
224 if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
225 overlay.shape
226 } else if base.clip || base.backdrop_effect.is_some() {
227 base.shape
228 } else {
229 overlay.shape
230 }
231}
232
233fn compose_render_effects(
234 outer: Option<RenderEffect>,
235 inner: Option<RenderEffect>,
236) -> Option<RenderEffect> {
237 match (outer, inner) {
238 (None, None) => None,
239 (Some(effect), None) | (None, Some(effect)) => Some(effect),
240 (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
241 }
242}
243
244fn compose_color_filters(
245 base: Option<ColorFilter>,
246 overlay: Option<ColorFilter>,
247) -> Option<ColorFilter> {
248 match (base, overlay) {
249 (None, None) => None,
250 (Some(filter), None) | (None, Some(filter)) => Some(filter),
251 (Some(filter), Some(next)) => Some(filter.compose(next)),
252 }
253}
254
255impl ModifierNodeSlices {
256 pub fn draw_commands(&self) -> &[DrawCommand] {
257 &self.draw_commands
258 }
259
260 pub fn outer_draw_command_count(&self) -> usize {
265 self.layer_draw_boundary.unwrap_or(0)
266 }
267
268 fn insert_background_draw(
269 &mut self,
270 insert_index: usize,
271 precedes_layer: bool,
272 command: DrawCommand,
273 ) {
274 let insert_index = insert_index.min(self.draw_commands.len());
275 self.draw_commands.insert(insert_index, command);
276 if let Some(boundary) = self.layer_draw_boundary.as_mut()
277 && precedes_layer
278 {
279 *boundary += 1;
280 }
281 }
282
283 fn mark_layer_draw_boundary(&mut self) {
284 if self.layer_draw_boundary.is_none() {
285 self.layer_draw_boundary = Some(self.draw_commands.len());
286 }
287 }
288
289 pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
290 &self.pointer_inputs
291 }
292
293 pub fn dispatch_pointer_event(&self, event: PointerEvent) {
297 let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
298 for handler in &self.pointer_inputs {
299 if event.is_consumed() && !terminal {
300 break;
301 }
302 handler(event.clone());
303 }
304 }
305
306 pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<cranpose_ui_graphics::Size>>] {
310 &self.pointer_input_sizes
311 }
312
313 pub fn publish_pointer_input_size(&self, size: cranpose_ui_graphics::Size) {
325 for sink in &self.pointer_input_sizes {
326 sink.set(size);
327 }
328 }
329
330 pub fn pointer_icon(&self) -> Option<&PointerIcon> {
333 self.pointer_icon.as_ref()
334 }
335
336 pub fn clip_to_bounds(&self) -> bool {
337 self.clip_to_bounds
338 }
339
340 pub fn layer_bounds(&self, node_size: Size) -> Rect {
346 self.layer_coordinator
347 .as_ref()
348 .map_or_else(|| Rect::from_size(node_size), |layer| layer.rect(node_size))
349 }
350
351 #[doc(hidden)]
354 pub fn publish_window_geometry(
355 &self,
356 origin: Point,
357 transform: cranpose_ui_graphics::ProjectiveTransform,
358 size: Size,
359 ) {
360 if self.text_window_transform.is_some() || self.viewport_window_rect.is_some() {
361 let local_to_window =
362 cranpose_ui_graphics::ProjectiveTransform::translation(origin.x, origin.y)
363 .then(transform);
364 if let Some(sink) = self.text_window_transform() {
365 sink.set(local_to_window);
366 }
367 if let Some(sink) = self.viewport_window_rect() {
368 sink.set(cranpose_ui_graphics::WindowCoordinates {
369 size,
370 local_to_window,
371 });
372 }
373 }
374 self.publish_pointer_input_size(size);
375 }
376
377 pub fn motion_context_animated(&self) -> bool {
378 self.motion_context_animated
379 }
380
381 pub fn translated_content_context(&self) -> bool {
382 self.translated_content_context
383 }
384
385 pub fn translated_content_context_identity(&self) -> Option<usize> {
386 self.translated_content_context_identity
387 }
388
389 pub fn translated_content_offset(&self) -> Option<Point> {
390 self.translated_content_offset_reader
391 .as_ref()
392 .map(|reader| reader())
393 }
394
395 pub fn has_text(&self) -> bool {
397 self.text.is_some()
398 }
399
400 pub fn text_content(&self) -> Option<SliceTextRef<'_, str>> {
401 self.annotated_text()
402 .map(|text| text.map(|text| text.text.as_str()))
403 }
404
405 pub fn annotated_text(&self) -> Option<SliceTextRef<'_, Rc<crate::text::AnnotatedString>>> {
406 Some(SliceTextRef(match self.text.as_ref()? {
407 SliceText::Text(layout) => TextBorrow::Layout(layout.annotated_text()),
408 SliceText::Field(field) => TextBorrow::Field(&field.content),
409 }))
410 }
411
412 pub fn text_content_rect(&self, node_size: Size) -> Rect {
415 self.text_coordinator.as_ref().map_or(
416 Rect {
417 x: 0.0,
418 y: 0.0,
419 width: node_size.width,
420 height: node_size.height,
421 },
422 |coordinator| coordinator.rect(node_size),
423 )
424 }
425
426 pub fn text_style(&self) -> Option<SliceTextRef<'_, TextStyle>> {
427 Some(SliceTextRef(match self.text.as_ref()? {
428 SliceText::Text(layout) => TextBorrow::Layout(layout.style()),
429 SliceText::Field(field) => TextBorrow::Field(&field.style),
430 }))
431 }
432
433 pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
434 match self.text.as_ref()? {
435 SliceText::Text(layout) => Some(layout.options()),
436 SliceText::Field(_) => Some(TextLayoutOptions::default()),
437 }
438 }
439
440 pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
447 match self.text.as_ref()? {
448 SliceText::Field(field) => field.pan.clone(),
449 SliceText::Text(_) => None,
450 }
451 }
452
453 pub fn text_window_transform(
456 &self,
457 ) -> Option<&Rc<std::cell::Cell<cranpose_ui_graphics::ProjectiveTransform>>> {
458 self.text_window_transform.as_ref()
459 }
460
461 pub fn viewport_window_rect(&self) -> Option<&Rc<dyn crate::modifier_nodes::WindowRectSink>> {
466 self.viewport_window_rect.as_ref()
467 }
468
469 pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
476 match self.text.as_ref()? {
477 SliceText::Text(layout) => layout.measured_layout(),
478 SliceText::Field(field) => Some(field.layout.measured_layout(&field.style)),
479 }
480 }
481
482 pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
483 if let Some(resolve) = &self.graphics_layer_resolver {
484 Some(resolve())
485 } else {
486 self.graphics_layer.as_deref().cloned()
487 }
488 }
489
490 pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
491 self.corner_shape
492 }
493
494 fn enter_layer(&mut self, site: &DrawSite) {
497 if self.layer_coordinator.is_none() {
498 self.layer_coordinator = Some(site.coordinator.clone());
499 }
500 }
501
502 fn push_graphics_layer(
503 &mut self,
504 layer: GraphicsLayer,
505 resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
506 ) {
507 let existing_snapshot = self.graphics_layer.as_deref().cloned();
508 let next_snapshot = existing_snapshot.as_ref().map_or_else(
509 || layer.clone(),
510 |current| merge_graphics_layers(current.clone(), layer.clone()),
511 );
512 let existing_resolver = self.graphics_layer_resolver.clone();
513
514 match &mut self.graphics_layer {
515 Some(held) => **held = next_snapshot,
516 None => self.graphics_layer = Some(Box::new(next_snapshot)),
517 }
518 self.graphics_layer_resolver = match (existing_resolver, resolver) {
519 (None, None) => None,
520 (Some(current_resolver), None) => Some(Rc::new(move || {
521 merge_graphics_layers(current_resolver(), layer.clone())
522 })),
523 (None, Some(next_resolver)) => {
524 let base = existing_snapshot.unwrap_or_default();
525 Some(Rc::new(move || {
526 merge_graphics_layers(base.clone(), next_resolver())
527 }))
528 }
529 (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
530 merge_graphics_layers(current_resolver(), next_resolver())
531 })),
532 };
533 }
534
535 pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
536 self.chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
537 self
538 }
539
540 pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
541 let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
542 let pointer_input_bytes =
543 self.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>();
544 ModifierNodeSlicesDebugStats {
545 draw_command_count: self.draw_commands.len(),
546 draw_command_capacity: self.draw_commands.capacity(),
547 pointer_input_count: self.pointer_inputs.len(),
548 pointer_input_capacity: self.pointer_inputs.capacity(),
549 has_text_content: self.text.is_some(),
550 has_text_style: self.text.is_some(),
551 has_text_layout_options: self.text.is_some(),
552 has_prepared_text_layout: self.text.is_some(),
553 has_graphics_layer: self.graphics_layer.is_some(),
554 has_graphics_layer_resolver: self.graphics_layer_resolver.is_some(),
555 heap_bytes: draw_command_bytes + pointer_input_bytes,
556 }
557 }
558
559 pub fn clear(&mut self) {
561 self.draw_commands.clear();
562 self.layer_draw_boundary = None;
563 self.pointer_inputs.clear();
564 self.pointer_input_sizes.clear();
565 self.pointer_icon = None;
566 self.clip_to_bounds = false;
567 self.layer_coordinator = None;
568 self.motion_context_animated = false;
569 self.translated_content_context = false;
570 self.translated_content_context_identity = None;
571 self.translated_content_offset_reader = None;
572 self.text = None;
573 self.text_coordinator = None;
574 self.text_window_transform = None;
575 self.viewport_window_rect = None;
576 self.graphics_layer = None;
577 self.graphics_layer_resolver = None;
578 self.corner_shape = None;
579 self.chain_guard = None;
580 }
581}
582
583impl fmt::Debug for ModifierNodeSlices {
584 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
585 f.debug_struct("ModifierNodeSlices")
586 .field("draw_commands", &self.draw_commands.len())
587 .field("pointer_inputs", &self.pointer_inputs.len())
588 .field("pointer_icon", &self.pointer_icon)
589 .field("clip_to_bounds", &self.clip_to_bounds)
590 .field("motion_context_animated", &self.motion_context_animated)
591 .field(
592 "translated_content_context",
593 &self.translated_content_context,
594 )
595 .field(
596 "translated_content_context_identity",
597 &self.translated_content_context_identity,
598 )
599 .field(
600 "translated_content_offset",
601 &self.translated_content_offset(),
602 )
603 .field("text_content", &self.annotated_text())
604 .field("text_style", &self.text_style())
605 .field("text_layout_options", &self.text_layout_options())
606 .field("graphics_layer", &self.graphics_layer)
607 .field(
608 "graphics_layer_resolver",
609 &self.graphics_layer_resolver.is_some(),
610 )
611 .field("corner_shape", &self.corner_shape)
612 .finish()
613 }
614}
615
616fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
622 if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
623 slices.pointer_icon = Some(icon_node.icon().clone());
624 }
625}
626
627pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
630 let mut slices = ModifierNodeSlices::default();
631 collect_modifier_slices_into(chain, &mut slices, &Rc::default(), 1.0);
632 slices
633}
634
635pub(crate) fn collect_modifier_slices_into_shared(
646 chain: &ModifierNodeChain,
647 slices: &mut Rc<ModifierNodeSlices>,
648 geometry: &Rc<CoordinatorGeometry>,
649 density: f32,
650) {
651 if Rc::get_mut(slices).is_none() {
652 *slices = Rc::default();
653 }
654 if let Some(slices) = Rc::get_mut(slices) {
655 collect_modifier_slices_into(chain, slices, geometry, density);
656 }
657}
658
659fn collect_modifier_slices_into(
660 chain: &ModifierNodeChain,
661 slices: &mut ModifierNodeSlices,
662 geometry: &Rc<CoordinatorGeometry>,
663 density: f32,
664) {
665 slices.clear();
666
667 let caps = chain.capabilities();
668 let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
669 let has_draw = caps.intersects(NodeCapabilities::DRAW);
670 let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
671
672 if !has_pointer && !has_draw && !has_layout {
673 return;
674 }
675
676 let mut backgrounds = Backgrounds::default();
677 let mut padding = EdgeInsets::default();
678 let mut layout_ordinal = 0_usize;
682
683 for (modifier_index, node_ref) in chain.head_to_tail().enumerate() {
684 let node_caps = node_ref.kind_set();
685
686 node_ref.with_node(|node| {
687 let any = node.as_any();
688
689 if has_pointer
690 && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
691 && let Some(pointer_node) = node.as_pointer_input_node()
692 {
693 if let Some(handler) = pointer_node.pointer_input_handler() {
694 slices.pointer_inputs.push(handler);
695 }
696 if let Some(sink) = pointer_node.layout_size_sink() {
697 slices.pointer_input_sizes.push(sink);
698 }
699 collect_pointer_icon(any, slices);
700 }
701
702 if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
703 let draw = DrawSite {
704 coordinator: CoordinatorRect::new(geometry, layout_ordinal, padding),
705 displaceable: has_layout,
706 modifier_index,
707 };
708 collect_draw_node(node, &draw, slices, &mut backgrounds);
709 }
710
711 if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
712 if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
713 padding +=
714 crate::modifier_nodes::device_padding(padding_node.padding(), density);
715 }
716
717 if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
718 slices.motion_context_animated = motion_context_node.is_active();
719 }
720
721 collect_window_geometry_sink(
722 any,
723 CoordinatorRect::new(geometry, layout_ordinal + 1, padding),
725 slices,
726 );
727
728 if let Some(translated_content_node) =
729 any.downcast_ref::<TranslatedContentContextNode>()
730 {
731 slices.translated_content_context = translated_content_node.is_active();
732 slices.translated_content_context_identity =
733 Some(translated_content_node.identity());
734 slices.translated_content_offset_reader =
735 translated_content_node.content_offset_reader();
736 }
737
738 if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
739 slices.text_coordinator =
740 Some(CoordinatorRect::new(geometry, layout_ordinal, padding));
741 slices.text = Some(SliceText::Text(text_node.prepared_layout_handle()));
742 }
743
744 if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
745 slices.text = Some(SliceText::Field(Rc::new(FieldText {
746 content: Rc::new(crate::text::AnnotatedString::from(
747 text_field_node.text(),
748 )),
749 style: text_field_node.style().clone(),
750 layout: text_field_node.layout_handle(),
751 pan: text_field_node.text_pan_resolver(),
752 })));
753 slices.text_window_transform = Some(text_field_node.window_transform_sink());
754
755 let coordinator = CoordinatorRect::new(geometry, layout_ordinal, padding);
756 text_field_node.set_content_origin(coordinator.clone());
757 slices.text_coordinator = Some(coordinator);
758 }
759 layout_ordinal += 1;
760 }
761 });
762 }
763
764 backgrounds.insert_into(slices);
765}
766
767struct DrawSite {
770 coordinator: CoordinatorRect,
771 displaceable: bool,
772 modifier_index: usize,
773}
774
775#[derive(Default)]
780struct Backgrounds {
781 slots: SmallVec<[BackgroundSlot; 2]>,
782 pending_shape: Option<RoundedCornerShape>,
783 last_shape: Option<RoundedCornerShape>,
784}
785
786struct BackgroundSlot {
787 color: crate::modifier::Color,
788 coordinator: CoordinatorRect,
789 insert_index: usize,
790 precedes_layer: bool,
791 corner_shape: Option<RoundedCornerShape>,
792}
793
794impl Backgrounds {
795 fn push(
796 &mut self,
797 color: crate::modifier::Color,
798 shape: Option<RoundedCornerShape>,
799 site: &DrawSite,
800 slices: &ModifierNodeSlices,
801 ) {
802 let corner_shape = shape.or_else(|| self.pending_shape.take());
803 if shape.is_some() {
804 self.last_shape = shape;
805 }
806 self.slots.push(BackgroundSlot {
807 color,
808 coordinator: site.coordinator.clone(),
809 insert_index: slices.draw_commands.len(),
810 precedes_layer: slices.layer_draw_boundary.is_none(),
811 corner_shape,
812 });
813 }
814
815 fn shape(&mut self, shape: RoundedCornerShape) {
816 self.last_shape = Some(shape);
817 match self.slots.last_mut() {
818 Some(slot) => slot.corner_shape = Some(shape),
819 None => self.pending_shape = Some(shape),
820 }
821 }
822
823 fn insert_into(self, slices: &mut ModifierNodeSlices) {
826 slices.corner_shape = self.last_shape;
827 for slot in self.slots.into_iter().rev() {
828 let BackgroundSlot {
829 color,
830 coordinator,
831 insert_index,
832 precedes_layer,
833 corner_shape,
834 } = slot;
835 let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
836 use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
837
838 use crate::modifier::Brush;
839
840 let rect = coordinator.rect(scope.size());
841 let brush = Brush::solid(color);
842 if let Some(shape) = corner_shape {
843 let radii: CornerRadii = shape.resolve(rect.width, rect.height);
844 scope.draw_round_rect_at(rect, brush, radii);
845 } else {
846 scope.draw_rect_at(rect, brush);
847 }
848 });
849 slices.insert_background_draw(
850 insert_index,
851 precedes_layer,
852 DrawCommand::Behind(draw_cmd),
853 );
854 }
855 }
856}
857
858fn collect_window_geometry_sink(
861 any: &dyn std::any::Any,
862 text: CoordinatorRect,
863 slices: &mut ModifierNodeSlices,
864) {
865 if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
866 slices.viewport_window_rect = Some(reporter.window_rect_sink());
867 }
868 if let Some(selectable) = any.downcast_ref::<SelectableTextNode>() {
869 slices.text_window_transform = Some(selectable.geometry().window_transform_sink());
870 selectable.geometry().set_content_origin(text);
871 }
872}
873
874fn collect_draw_node(
876 node: &dyn cranpose_foundation::ModifierNode,
877 site: &DrawSite,
878 slices: &mut ModifierNodeSlices,
879 backgrounds: &mut Backgrounds,
880) {
881 let any = node.as_any();
882 if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
883 backgrounds.push(bg_node.color(), bg_node.shape(), site, slices);
884 }
885
886 if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
887 backgrounds.shape(shape_node.shape());
888 }
889
890 if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
891 slices.draw_commands.extend(
892 commands
893 .observed_commands(site.modifier_index)
894 .map(|command| placed_draw_command(command, site)),
895 );
896 }
897
898 if let Some(draw_node) = node.as_draw_node() {
899 collect_draw_closures(draw_node, site, slices);
900 }
901
902 if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
903 slices.mark_layer_draw_boundary();
904 slices.push_graphics_layer(
905 layer_node.layer_snapshot(),
906 layer_node.layer_resolver(site.modifier_index),
907 );
908 slices.enter_layer(site);
909 }
910
911 if any.is::<ClipToBoundsNode>() {
912 slices.mark_layer_draw_boundary();
913 slices.clip_to_bounds = true;
914 slices.enter_layer(site);
915 }
916}
917
918fn collect_draw_closures(
921 draw_node: &dyn cranpose_foundation::DrawModifierNode,
922 site: &DrawSite,
923 slices: &mut ModifierNodeSlices,
924) {
925 if let Some(closure) = draw_node.create_behind_draw_closure() {
926 slices
927 .draw_commands
928 .push(placed_draw_command(DrawCommand::Behind(closure), site));
929 }
930 if let Some(closure) = draw_node.create_draw_closure() {
931 slices
932 .draw_commands
933 .push(placed_draw_command(DrawCommand::Overlay(closure), site));
934 }
935}
936
937fn placed_draw_command(command: DrawCommand, site: &DrawSite) -> DrawCommand {
940 if !site.displaceable {
941 return command;
942 }
943 let place = |draw: crate::draw::DrawCommandFn| -> crate::draw::DrawCommandFn {
944 let coordinator = site.coordinator.clone();
945 Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
946 use cranpose_ui_graphics::DrawScope as _;
947
948 let insets = coordinator.insets(scope.size());
949 if insets.is_zero() {
950 draw(scope);
951 } else {
952 scope.inset(insets, |inner| draw(inner));
953 }
954 })
955 };
956 match command {
957 DrawCommand::Behind(draw) => DrawCommand::Behind(place(draw)),
958 DrawCommand::WithContent(draw) => DrawCommand::WithContent(place(draw)),
959 DrawCommand::Overlay(draw) => DrawCommand::Overlay(place(draw)),
960 }
961}
962
963pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
965 let mut handle = ModifierChainHandle::new();
966 let _ = handle.update(modifier);
967 collect_modifier_slices(handle.chain()).with_chain_guard(handle)
968}
969
970#[cfg(test)]
971#[path = "tests/slices_tests.rs"]
972mod tests;