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(Clone, Default)]
31pub struct ModifierNodeSlices {
32 draw_commands: Vec<DrawCommand>,
33 layer_draw_boundary: Option<usize>,
34 clip_to_bounds: bool,
35 layer_coordinator: Option<CoordinatorRect>,
38 text: Option<SliceText>,
39 text_coordinator: Option<CoordinatorRect>,
40 graphics_layer: Option<Box<GraphicsLayer>>,
43 corner_shape: Option<RoundedCornerShape>,
44 rare: Option<Box<RareSlices>>,
48}
49
50fn publish_pointer_input_size(rare: &RareSlices, size: cranpose_ui_graphics::Size) {
51 for sink in &rare.pointer_input_sizes {
52 sink.set(size);
53 }
54}
55
56#[derive(Clone, Default)]
59struct RareSlices {
60 pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
61 pointer_input_sizes: Vec<Rc<std::cell::Cell<cranpose_ui_graphics::Size>>>,
62 pointer_icon: Option<PointerIcon>,
63 motion_context_animated: bool,
64 translated_content_context: bool,
65 translated_content_context_identity: Option<usize>,
66 translated_content_offset_reader: Option<Rc<dyn Fn() -> Point>>,
67 text_window: Option<Rc<std::cell::Cell<cranpose_ui_graphics::WindowCoordinates>>>,
68 viewport_window_rect: Option<Rc<dyn crate::modifier_nodes::WindowRectSink>>,
69 graphics_layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
70 chain_guard: Option<Rc<ChainGuard>>,
71 z_index: f32,
72}
73
74impl RareSlices {
75 fn clear(&mut self) {
76 self.pointer_inputs.clear();
77 self.pointer_input_sizes.clear();
78 self.pointer_icon = None;
79 self.motion_context_animated = false;
80 self.translated_content_context = false;
81 self.translated_content_context_identity = None;
82 self.translated_content_offset_reader = None;
83 self.text_window = None;
84 self.viewport_window_rect = None;
85 self.graphics_layer_resolver = None;
86 self.chain_guard = None;
87 self.z_index = 0.0;
88 }
89}
90
91struct ChainGuard {
92 _handle: ModifierChainHandle,
93}
94
95#[derive(Clone)]
99enum SliceText {
100 Text(TextPreparedLayoutHandle),
101 Field(Rc<FieldText>),
102}
103
104pub struct SliceTextRef<'a, T: ?Sized>(TextBorrow<'a, T>);
108
109enum TextBorrow<'a, T: ?Sized> {
110 Layout(Ref<'a, T>),
111 Field(&'a T),
112}
113
114impl<'a, T: ?Sized> SliceTextRef<'a, T> {
115 fn map<U: ?Sized>(self, part: impl FnOnce(&T) -> &U) -> SliceTextRef<'a, U> {
116 SliceTextRef(match self.0 {
117 TextBorrow::Layout(text) => TextBorrow::Layout(Ref::map(text, part)),
118 TextBorrow::Field(text) => TextBorrow::Field(part(text)),
119 })
120 }
121}
122
123impl<T: ?Sized> Deref for SliceTextRef<'_, T> {
124 type Target = T;
125
126 fn deref(&self) -> &T {
127 match &self.0 {
128 TextBorrow::Layout(text) => text,
129 TextBorrow::Field(text) => text,
130 }
131 }
132}
133
134impl<T: ?Sized + fmt::Debug> fmt::Debug for SliceTextRef<'_, T> {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 (**self).fmt(f)
137 }
138}
139
140impl<T: ?Sized + fmt::Display> fmt::Display for SliceTextRef<'_, T> {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 (**self).fmt(f)
143 }
144}
145
146impl PartialEq<str> for SliceTextRef<'_, str> {
147 fn eq(&self, other: &str) -> bool {
148 **self == *other
149 }
150}
151
152impl PartialEq<&str> for SliceTextRef<'_, str> {
153 fn eq(&self, other: &&str) -> bool {
154 **self == **other
155 }
156}
157
158struct FieldText {
159 content: Rc<crate::text::AnnotatedString>,
160 style: TextStyle,
161 layout: TextFieldLayoutHandle,
162 pan: Option<TextPanResolver>,
163}
164
165#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
167pub struct ModifierNodeSlicesDebugStats {
168 pub draw_command_count: usize,
170 pub draw_command_capacity: usize,
172 pub pointer_input_count: usize,
174 pub pointer_input_capacity: usize,
176 pub has_text_content: bool,
178 pub has_text_style: bool,
180 pub has_text_layout_options: bool,
182 pub has_prepared_text_layout: bool,
184 pub has_graphics_layer: bool,
186 pub has_graphics_layer_resolver: bool,
188 pub heap_bytes: usize,
190}
191
192fn merge_graphics_layers(base: GraphicsLayer, overlay: GraphicsLayer) -> GraphicsLayer {
193 GraphicsLayer {
194 alpha: (base.alpha * overlay.alpha).clamp(0.0, 1.0),
195 scale: base.scale * overlay.scale,
196 scale_x: base.scale_x * overlay.scale_x,
197 scale_y: base.scale_y * overlay.scale_y,
198 rotation_x: base.rotation_x + overlay.rotation_x,
199 rotation_y: base.rotation_y + overlay.rotation_y,
200 rotation_z: base.rotation_z + overlay.rotation_z,
201 camera_distance: transform_frame(&base, &overlay).camera_distance,
202 transform_origin: transform_frame(&base, &overlay).transform_origin,
203 translation_x: base.translation_x + overlay.translation_x,
204 translation_y: base.translation_y + overlay.translation_y,
205 shadow_elevation: overlay.shadow_elevation,
206 ambient_shadow_color: overlay.ambient_shadow_color,
207 spot_shadow_color: overlay.spot_shadow_color,
208 shape: merged_layer_shape(&base, &overlay),
209 clip: base.clip || overlay.clip,
210 compositing_strategy: overlay.compositing_strategy,
211 blend_mode: overlay.blend_mode,
212 color_filter: compose_color_filters(base.color_filter, overlay.color_filter),
213 render_effect: compose_render_effects(base.render_effect, overlay.render_effect),
214 backdrop_effect: overlay.backdrop_effect.or(base.backdrop_effect),
215 }
216}
217
218fn transform_frame<'a>(base: &'a GraphicsLayer, overlay: &'a GraphicsLayer) -> &'a GraphicsLayer {
224 let transforms = |layer: &GraphicsLayer| {
225 layer.rotation_x != 0.0
226 || layer.rotation_y != 0.0
227 || layer.rotation_z != 0.0
228 || layer.scale != 1.0
229 || layer.scale_x != 1.0
230 || layer.scale_y != 1.0
231 };
232 if transforms(overlay) || !transforms(base) {
233 overlay
234 } else {
235 base
236 }
237}
238
239fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
244 if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
245 overlay.shape
246 } else if base.clip || base.backdrop_effect.is_some() {
247 base.shape
248 } else {
249 overlay.shape
250 }
251}
252
253fn compose_render_effects(
254 outer: Option<RenderEffect>,
255 inner: Option<RenderEffect>,
256) -> Option<RenderEffect> {
257 match (outer, inner) {
258 (None, None) => None,
259 (Some(effect), None) | (None, Some(effect)) => Some(effect),
260 (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
261 }
262}
263
264fn compose_color_filters(
265 base: Option<ColorFilter>,
266 overlay: Option<ColorFilter>,
267) -> Option<ColorFilter> {
268 match (base, overlay) {
269 (None, None) => None,
270 (Some(filter), None) | (None, Some(filter)) => Some(filter),
271 (Some(filter), Some(next)) => Some(filter.compose(next)),
272 }
273}
274
275impl ModifierNodeSlices {
276 pub fn draw_commands(&self) -> &[DrawCommand] {
278 &self.draw_commands
279 }
280
281 pub fn outer_draw_command_count(&self) -> usize {
286 self.layer_draw_boundary.unwrap_or(0)
287 }
288
289 fn insert_background_draw(
290 &mut self,
291 insert_index: usize,
292 precedes_layer: bool,
293 command: DrawCommand,
294 ) {
295 let insert_index = insert_index.min(self.draw_commands.len());
296 self.draw_commands.insert(insert_index, command);
297 if let Some(boundary) = self.layer_draw_boundary.as_mut()
298 && precedes_layer
299 {
300 *boundary += 1;
301 }
302 }
303
304 fn mark_layer_draw_boundary(&mut self) {
305 if self.layer_draw_boundary.is_none() {
306 self.layer_draw_boundary = Some(self.draw_commands.len());
307 }
308 }
309
310 fn rare(&self) -> Option<&RareSlices> {
312 self.rare.as_deref()
313 }
314
315 fn rare_mut(&mut self) -> &mut RareSlices {
316 self.rare.get_or_insert_with(Box::default)
317 }
318
319 pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
321 self.rare().map_or(&[], |rare| &rare.pointer_inputs)
322 }
323
324 pub fn dispatch_pointer_event(&self, event: PointerEvent) {
328 let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
329 for handler in self.pointer_inputs() {
330 if event.is_consumed() && !terminal {
331 break;
332 }
333 handler(event.clone());
334 }
335 }
336
337 pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<cranpose_ui_graphics::Size>>] {
341 self.rare().map_or(&[], |rare| &rare.pointer_input_sizes)
342 }
343
344 pub fn publish_pointer_input_size(&self, size: cranpose_ui_graphics::Size) {
356 if let Some(rare) = self.rare() {
357 publish_pointer_input_size(rare, size);
358 }
359 }
360
361 pub fn z_index(&self) -> f32 {
364 self.rare().map_or(0.0, |rare| rare.z_index)
365 }
366
367 pub fn pointer_icon(&self) -> Option<&PointerIcon> {
370 self.rare()?.pointer_icon.as_ref()
371 }
372
373 pub fn clip_to_bounds(&self) -> bool {
375 self.clip_to_bounds
376 }
377
378 pub fn layer_bounds(&self, node_size: Size) -> Rect {
384 self.layer_coordinator
385 .as_ref()
386 .map_or_else(|| Rect::from_size(node_size), |layer| layer.rect(node_size))
387 }
388
389 #[doc(hidden)]
392 pub fn publish_window_geometry(
393 &self,
394 origin: Point,
395 transform: cranpose_ui_graphics::ProjectiveTransform,
396 size: Size,
397 ) {
398 let Some(rare) = self.rare() else {
400 return;
401 };
402 if rare.text_window.is_some() || rare.viewport_window_rect.is_some() {
403 let window = cranpose_ui_graphics::WindowCoordinates {
404 size,
405 local_to_window: cranpose_ui_graphics::ProjectiveTransform::translation(
406 origin.x, origin.y,
407 )
408 .then(transform),
409 };
410 if let Some(sink) = &rare.text_window {
411 sink.set(window);
412 }
413 if let Some(sink) = &rare.viewport_window_rect {
414 sink.set(window);
415 }
416 }
417 publish_pointer_input_size(rare, size);
418 }
419
420 pub fn motion_context_animated(&self) -> bool {
423 self.rare().is_some_and(|rare| rare.motion_context_animated)
424 }
425
426 pub fn translated_content_context(&self) -> bool {
429 self.rare()
430 .is_some_and(|rare| rare.translated_content_context)
431 }
432
433 pub fn translated_content_context_identity(&self) -> Option<usize> {
436 self.rare()?.translated_content_context_identity
437 }
438
439 pub fn translated_content_offset(&self) -> Option<Point> {
442 self.rare()?
443 .translated_content_offset_reader
444 .as_ref()
445 .map(|reader| reader())
446 }
447
448 pub fn has_text(&self) -> bool {
450 self.text.is_some()
451 }
452
453 pub fn text_content(&self) -> Option<SliceTextRef<'_, str>> {
455 self.annotated_text()
456 .map(|text| text.map(|text| text.text.as_str()))
457 }
458
459 pub fn annotated_text(&self) -> Option<SliceTextRef<'_, Rc<crate::text::AnnotatedString>>> {
461 Some(SliceTextRef(match self.text.as_ref()? {
462 SliceText::Text(layout) => TextBorrow::Layout(layout.annotated_text()),
463 SliceText::Field(field) => TextBorrow::Field(&field.content),
464 }))
465 }
466
467 pub fn text_content_rect(&self, node_size: Size) -> Rect {
470 self.text_coordinator.as_ref().map_or(
471 Rect {
472 x: 0.0,
473 y: 0.0,
474 width: node_size.width,
475 height: node_size.height,
476 },
477 |coordinator| coordinator.rect(node_size),
478 )
479 }
480
481 pub fn text_style(&self) -> Option<SliceTextRef<'_, TextStyle>> {
483 Some(SliceTextRef(match self.text.as_ref()? {
484 SliceText::Text(layout) => TextBorrow::Layout(layout.style()),
485 SliceText::Field(field) => TextBorrow::Field(&field.style),
486 }))
487 }
488
489 pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
492 match self.text.as_ref()? {
493 SliceText::Text(layout) => Some(layout.options()),
494 SliceText::Field(_) => Some(TextLayoutOptions::default()),
495 }
496 }
497
498 pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
505 match self.text.as_ref()? {
506 SliceText::Field(field) => field.pan.clone(),
507 SliceText::Text(_) => None,
508 }
509 }
510
511 pub fn text_window(
515 &self,
516 ) -> Option<&Rc<std::cell::Cell<cranpose_ui_graphics::WindowCoordinates>>> {
517 self.rare()?.text_window.as_ref()
518 }
519
520 pub fn viewport_window_rect(&self) -> Option<&Rc<dyn crate::modifier_nodes::WindowRectSink>> {
525 self.rare()?.viewport_window_rect.as_ref()
526 }
527
528 pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
535 match self.text.as_ref()? {
536 SliceText::Text(layout) => layout.measured_layout(),
537 SliceText::Field(field) => Some(field.layout.measured_layout(&field.style)),
538 }
539 }
540
541 pub fn graphics_layer(&self) -> Option<GraphicsLayer> {
544 if let Some(resolve) = self
545 .rare()
546 .and_then(|rare| rare.graphics_layer_resolver.as_ref())
547 {
548 Some(resolve())
549 } else {
550 self.graphics_layer.as_deref().cloned()
551 }
552 }
553
554 pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
556 self.corner_shape
557 }
558
559 fn enter_layer(&mut self, site: &DrawSite) {
562 if self.layer_coordinator.is_none() {
563 self.layer_coordinator = Some(site.coordinator.clone());
564 }
565 }
566
567 fn push_graphics_layer(
568 &mut self,
569 layer: GraphicsLayer,
570 resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
571 ) {
572 let existing_snapshot = self.graphics_layer.as_deref().cloned();
573 let next_snapshot = existing_snapshot.as_ref().map_or_else(
574 || layer.clone(),
575 |current| merge_graphics_layers(current.clone(), layer.clone()),
576 );
577 let existing_resolver = self
578 .rare()
579 .and_then(|rare| rare.graphics_layer_resolver.clone());
580
581 match &mut self.graphics_layer {
582 Some(held) => **held = next_snapshot,
583 None => self.graphics_layer = Some(Box::new(next_snapshot)),
584 }
585 let merged_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>> =
586 match (existing_resolver, resolver) {
587 (None, None) => None,
588 (Some(current_resolver), None) => Some(Rc::new(move || {
589 merge_graphics_layers(current_resolver(), layer.clone())
590 })),
591 (None, Some(next_resolver)) => {
592 let base = existing_snapshot.unwrap_or_default();
593 Some(Rc::new(move || {
594 merge_graphics_layers(base.clone(), next_resolver())
595 }))
596 }
597 (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
598 merge_graphics_layers(current_resolver(), next_resolver())
599 })),
600 };
601 if merged_resolver.is_some() {
602 self.rare_mut().graphics_layer_resolver = merged_resolver;
603 }
604 }
605
606 pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
608 self.rare_mut().chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
609 self
610 }
611
612 pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
614 let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
615 let pointer_input_capacity = self.rare().map_or(0, |rare| rare.pointer_inputs.capacity());
616 let pointer_input_bytes = pointer_input_capacity * size_of::<Rc<dyn Fn(PointerEvent)>>();
617 ModifierNodeSlicesDebugStats {
618 draw_command_count: self.draw_commands.len(),
619 draw_command_capacity: self.draw_commands.capacity(),
620 pointer_input_count: self.pointer_inputs().len(),
621 pointer_input_capacity,
622 has_text_content: self.text.is_some(),
623 has_text_style: self.text.is_some(),
624 has_text_layout_options: self.text.is_some(),
625 has_prepared_text_layout: self.text.is_some(),
626 has_graphics_layer: self.graphics_layer.is_some(),
627 has_graphics_layer_resolver: self
628 .rare()
629 .is_some_and(|rare| rare.graphics_layer_resolver.is_some()),
630 heap_bytes: draw_command_bytes + pointer_input_bytes,
631 }
632 }
633
634 pub fn clear(&mut self) {
636 self.draw_commands.clear();
637 self.layer_draw_boundary = None;
638 self.clip_to_bounds = false;
639 self.layer_coordinator = None;
640 self.text = None;
641 self.text_coordinator = None;
642 self.graphics_layer = None;
643 self.corner_shape = None;
644 if let Some(rare) = self.rare.as_deref_mut() {
645 rare.clear();
646 }
647 }
648}
649
650impl fmt::Debug for ModifierNodeSlices {
651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 f.debug_struct("ModifierNodeSlices")
653 .field("draw_commands", &self.draw_commands.len())
654 .field("pointer_inputs", &self.pointer_inputs().len())
655 .field("pointer_icon", &self.pointer_icon())
656 .field("clip_to_bounds", &self.clip_to_bounds)
657 .field("motion_context_animated", &self.motion_context_animated())
658 .field(
659 "translated_content_context",
660 &self.translated_content_context(),
661 )
662 .field(
663 "translated_content_context_identity",
664 &self.translated_content_context_identity(),
665 )
666 .field(
667 "translated_content_offset",
668 &self.translated_content_offset(),
669 )
670 .field("text_content", &self.annotated_text())
671 .field("text_style", &self.text_style())
672 .field("text_layout_options", &self.text_layout_options())
673 .field("graphics_layer", &self.graphics_layer)
674 .field(
675 "graphics_layer_resolver",
676 &self
677 .rare()
678 .is_some_and(|rare| rare.graphics_layer_resolver.is_some()),
679 )
680 .field("corner_shape", &self.corner_shape)
681 .finish()
682 }
683}
684
685fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
691 if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
692 slices.rare_mut().pointer_icon = Some(icon_node.icon().clone());
693 }
694}
695
696pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
699 let mut slices = ModifierNodeSlices::default();
700 collect_modifier_slices_into(chain, &mut slices, &Rc::default(), 1.0);
701 slices
702}
703
704#[derive(Default)]
708pub(crate) struct SlicesSnapshot(std::cell::Cell<Option<Rc<ModifierNodeSlices>>>);
709
710impl SlicesSnapshot {
711 pub(crate) fn get(&self) -> Rc<ModifierNodeSlices> {
712 let snapshot = self.0.take();
713 let shared = snapshot.clone();
714 self.0.set(snapshot);
715 shared.unwrap_or_else(|| {
716 crate::thread_state::with(|state| {
717 Rc::clone(state.empty_slices.get_or_init(Rc::default))
718 })
719 })
720 }
721
722 pub(crate) fn collect(
729 &self,
730 chain: &ModifierNodeChain,
731 geometry: &Rc<CoordinatorGeometry>,
732 density: f32,
733 ) {
734 if !chain.capabilities().intersects(
735 NodeCapabilities::POINTER_INPUT | NodeCapabilities::DRAW | NodeCapabilities::LAYOUT,
736 ) {
737 self.0.set(None);
738 return;
739 }
740 let mut snapshot = self.0.take();
741 if !snapshot
742 .as_mut()
743 .is_some_and(|slices| Rc::get_mut(slices).is_some())
744 {
745 snapshot = Some(Rc::default());
746 }
747 if let Some(slices) = snapshot.as_mut().and_then(Rc::get_mut) {
748 collect_modifier_slices_into(chain, slices, geometry, density);
749 }
750 self.0.set(snapshot);
751 }
752}
753
754fn collect_modifier_slices_into(
755 chain: &ModifierNodeChain,
756 slices: &mut ModifierNodeSlices,
757 geometry: &Rc<CoordinatorGeometry>,
758 density: f32,
759) {
760 slices.clear();
761
762 let caps = chain.capabilities();
763 let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
764 let has_draw = caps.intersects(NodeCapabilities::DRAW);
765 let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
766
767 if !has_pointer && !has_draw && !has_layout {
768 return;
769 }
770
771 let mut backgrounds = Backgrounds::default();
772 let mut padding = EdgeInsets::default();
773 let mut layout_ordinal = 0_usize;
777
778 for (modifier_index, node_ref) in chain.head_to_tail().enumerate() {
779 let node_caps = node_ref.kind_set();
780
781 node_ref.with_node(|node| {
782 let any = node.as_any();
783
784 if has_pointer
785 && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
786 && let Some(pointer_node) = node.as_pointer_input_node()
787 {
788 if let Some(handler) = pointer_node.pointer_input_handler() {
789 slices.rare_mut().pointer_inputs.push(handler);
790 }
791 if let Some(sink) = pointer_node.layout_size_sink() {
792 slices.rare_mut().pointer_input_sizes.push(sink);
793 }
794 collect_pointer_icon(any, slices);
795 }
796
797 if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
798 let draw = DrawSite {
799 coordinator: CoordinatorRect::new(geometry, layout_ordinal, padding),
800 displaceable: has_layout,
801 modifier_index,
802 };
803 collect_draw_node(node, &draw, slices, &mut backgrounds);
804 }
805
806 if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
807 if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
808 padding +=
809 crate::modifier_nodes::device_padding(padding_node.padding(), density);
810 }
811
812 if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
813 slices.rare_mut().motion_context_animated = motion_context_node.is_active();
814 }
815
816 collect_window_geometry_sink(
817 any,
818 CoordinatorRect::new(geometry, layout_ordinal + 1, padding),
820 slices,
821 );
822
823 if let Some(translated_content_node) =
824 any.downcast_ref::<TranslatedContentContextNode>()
825 {
826 let rare = slices.rare_mut();
827 rare.translated_content_context = translated_content_node.is_active();
828 rare.translated_content_context_identity =
829 Some(translated_content_node.identity());
830 rare.translated_content_offset_reader =
831 translated_content_node.content_offset_reader();
832 }
833
834 if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
835 slices.text_coordinator =
836 Some(CoordinatorRect::new(geometry, layout_ordinal, padding));
837 slices.text = Some(SliceText::Text(text_node.prepared_layout_handle()));
838 }
839
840 if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
841 slices.text = Some(SliceText::Field(Rc::new(FieldText {
842 content: text_field_node.shown_text(),
843 style: text_field_node.style().clone(),
844 layout: text_field_node.layout_handle(),
845 pan: text_field_node.text_pan_resolver(),
846 })));
847 slices.rare_mut().text_window = Some(text_field_node.window_sink());
848
849 let coordinator = CoordinatorRect::new(geometry, layout_ordinal, padding);
850 text_field_node.set_content_origin(coordinator.clone());
851 slices.text_coordinator = Some(coordinator);
852 }
853 layout_ordinal += 1;
854 }
855 });
856 }
857
858 backgrounds.insert_into(slices);
859}
860
861struct DrawSite {
864 coordinator: CoordinatorRect,
865 displaceable: bool,
866 modifier_index: usize,
867}
868
869#[derive(Default)]
874struct Backgrounds {
875 slots: SmallVec<[BackgroundSlot; 2]>,
876 pending_shape: Option<RoundedCornerShape>,
877 last_shape: Option<RoundedCornerShape>,
878}
879
880struct BackgroundSlot {
881 color: crate::modifier::Color,
882 coordinator: CoordinatorRect,
883 insert_index: usize,
884 precedes_layer: bool,
885 corner_shape: Option<RoundedCornerShape>,
886}
887
888impl Backgrounds {
889 fn push(
890 &mut self,
891 color: crate::modifier::Color,
892 shape: Option<RoundedCornerShape>,
893 site: &DrawSite,
894 slices: &ModifierNodeSlices,
895 ) {
896 let corner_shape = shape.or_else(|| self.pending_shape.take());
897 if shape.is_some() {
898 self.last_shape = shape;
899 }
900 self.slots.push(BackgroundSlot {
901 color,
902 coordinator: site.coordinator.clone(),
903 insert_index: slices.draw_commands.len(),
904 precedes_layer: slices.layer_draw_boundary.is_none(),
905 corner_shape,
906 });
907 }
908
909 fn shape(&mut self, shape: RoundedCornerShape) {
910 self.last_shape = Some(shape);
911 match self.slots.last_mut() {
912 Some(slot) => slot.corner_shape = Some(shape),
913 None => self.pending_shape = Some(shape),
914 }
915 }
916
917 fn insert_into(self, slices: &mut ModifierNodeSlices) {
920 slices.corner_shape = self.last_shape;
921 for slot in self.slots.into_iter().rev() {
922 let BackgroundSlot {
923 color,
924 coordinator,
925 insert_index,
926 precedes_layer,
927 corner_shape,
928 } = slot;
929 let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
930 use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
931
932 use crate::modifier::Brush;
933
934 let rect = coordinator.rect(scope.size());
935 let brush = Brush::solid(color);
936 if let Some(shape) = corner_shape {
937 let radii: CornerRadii = shape.resolve(rect.width, rect.height);
938 scope.draw_round_rect_at(rect, brush, radii);
939 } else {
940 scope.draw_rect_at(rect, brush);
941 }
942 });
943 slices.insert_background_draw(
944 insert_index,
945 precedes_layer,
946 DrawCommand::Behind(draw_cmd),
947 );
948 }
949 }
950}
951
952fn collect_window_geometry_sink(
955 any: &dyn std::any::Any,
956 text: CoordinatorRect,
957 slices: &mut ModifierNodeSlices,
958) {
959 if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
960 slices.rare_mut().viewport_window_rect = Some(reporter.window_rect_sink());
961 }
962 if let Some(selectable) = any.downcast_ref::<SelectableTextNode>() {
963 slices.rare_mut().text_window = Some(selectable.geometry().window_sink());
964 selectable.geometry().set_content_origin(text);
965 }
966}
967
968fn collect_draw_node(
970 node: &dyn cranpose_foundation::ModifierNode,
971 site: &DrawSite,
972 slices: &mut ModifierNodeSlices,
973 backgrounds: &mut Backgrounds,
974) {
975 let any = node.as_any();
976 if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
977 backgrounds.push(bg_node.color(), bg_node.shape(), site, slices);
978 }
979
980 if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
981 backgrounds.shape(shape_node.shape());
982 }
983
984 if let Some(z_index_node) = any.downcast_ref::<super::z_index::ZIndexNode>() {
985 slices.rare_mut().z_index += z_index_node.z_index();
986 }
987
988 if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
989 slices.draw_commands.extend(
990 commands
991 .observed_commands(site.modifier_index)
992 .map(|command| placed_draw_command(command, site)),
993 );
994 }
995
996 if let Some(draw_node) = node.as_draw_node() {
997 collect_draw_closures(draw_node, site, slices);
998 }
999
1000 if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
1001 slices.mark_layer_draw_boundary();
1002 slices.push_graphics_layer(
1003 layer_node.layer_snapshot(),
1004 layer_node.layer_resolver(site.modifier_index),
1005 );
1006 slices.enter_layer(site);
1007 }
1008
1009 if any.is::<ClipToBoundsNode>() {
1010 slices.mark_layer_draw_boundary();
1011 slices.clip_to_bounds = true;
1012 slices.enter_layer(site);
1013 }
1014}
1015
1016fn collect_draw_closures(
1019 draw_node: &dyn cranpose_foundation::DrawModifierNode,
1020 site: &DrawSite,
1021 slices: &mut ModifierNodeSlices,
1022) {
1023 if let Some(closure) = draw_node.create_behind_draw_closure() {
1024 slices
1025 .draw_commands
1026 .push(placed_draw_command(DrawCommand::Behind(closure), site));
1027 }
1028 if let Some(closure) = draw_node.create_draw_closure() {
1029 slices
1030 .draw_commands
1031 .push(placed_draw_command(DrawCommand::Overlay(closure), site));
1032 }
1033}
1034
1035fn placed_draw_command(command: DrawCommand, site: &DrawSite) -> DrawCommand {
1038 if !site.displaceable {
1039 return command;
1040 }
1041 let place = |draw: crate::draw::DrawCommandFn| -> crate::draw::DrawCommandFn {
1042 let coordinator = site.coordinator.clone();
1043 Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
1044 use cranpose_ui_graphics::DrawScope as _;
1045
1046 let insets = coordinator.insets(scope.size());
1047 if insets.is_zero() {
1048 draw(scope);
1049 } else {
1050 scope.inset(insets, |inner| draw(inner));
1051 }
1052 })
1053 };
1054 match command {
1055 DrawCommand::Behind(draw) => DrawCommand::Behind(place(draw)),
1056 DrawCommand::WithContent(draw) => DrawCommand::WithContent(place(draw)),
1057 DrawCommand::Overlay(draw) => DrawCommand::Overlay(place(draw)),
1058 }
1059}
1060
1061pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
1063 let mut handle = ModifierChainHandle::new();
1064 let _ = handle.update(modifier);
1065 collect_modifier_slices(handle.chain()).with_chain_guard(handle)
1066}
1067
1068#[cfg(test)]
1069#[path = "tests/slices_tests.rs"]
1070mod tests;