1use std::{borrow::Cow, 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 space: overlay.space.or(base.space),
216 }
217}
218
219fn transform_frame<'a>(base: &'a GraphicsLayer, overlay: &'a GraphicsLayer) -> &'a GraphicsLayer {
225 let transforms = |layer: &GraphicsLayer| {
226 layer.rotation_x != 0.0
227 || layer.rotation_y != 0.0
228 || layer.rotation_z != 0.0
229 || layer.scale != 1.0
230 || layer.scale_x != 1.0
231 || layer.scale_y != 1.0
232 };
233 if transforms(overlay) || !transforms(base) {
234 overlay
235 } else {
236 base
237 }
238}
239
240fn merged_layer_shape(base: &GraphicsLayer, overlay: &GraphicsLayer) -> LayerShape {
245 if overlay.clip || (!base.clip && overlay.backdrop_effect.is_some()) {
246 overlay.shape
247 } else if base.clip || base.backdrop_effect.is_some() {
248 base.shape
249 } else {
250 overlay.shape
251 }
252}
253
254fn compose_render_effects(
255 outer: Option<RenderEffect>,
256 inner: Option<RenderEffect>,
257) -> Option<RenderEffect> {
258 match (outer, inner) {
259 (None, None) => None,
260 (Some(effect), None) | (None, Some(effect)) => Some(effect),
261 (Some(outer_effect), Some(inner_effect)) => Some(inner_effect.then(outer_effect)),
262 }
263}
264
265fn compose_color_filters(
266 base: Option<ColorFilter>,
267 overlay: Option<ColorFilter>,
268) -> Option<ColorFilter> {
269 match (base, overlay) {
270 (None, None) => None,
271 (Some(filter), None) | (None, Some(filter)) => Some(filter),
272 (Some(filter), Some(next)) => Some(filter.compose(&next)),
273 }
274}
275
276impl ModifierNodeSlices {
277 pub fn draw_commands(&self) -> &[DrawCommand] {
279 &self.draw_commands
280 }
281
282 pub fn outer_draw_command_count(&self) -> usize {
287 self.layer_draw_boundary.unwrap_or(0)
288 }
289
290 fn insert_background_draw(
291 &mut self,
292 insert_index: usize,
293 precedes_layer: bool,
294 command: DrawCommand,
295 ) {
296 let insert_index = insert_index.min(self.draw_commands.len());
297 self.draw_commands.insert(insert_index, command);
298 if let Some(boundary) = self.layer_draw_boundary.as_mut()
299 && precedes_layer
300 {
301 *boundary += 1;
302 }
303 }
304
305 fn mark_layer_draw_boundary(&mut self) {
306 if self.layer_draw_boundary.is_none() {
307 self.layer_draw_boundary = Some(self.draw_commands.len());
308 }
309 }
310
311 fn rare(&self) -> Option<&RareSlices> {
313 self.rare.as_deref()
314 }
315
316 fn rare_mut(&mut self) -> &mut RareSlices {
317 self.rare.get_or_insert_with(Box::default)
318 }
319
320 pub fn pointer_inputs(&self) -> &[Rc<dyn Fn(PointerEvent)>] {
322 self.rare().map_or(&[], |rare| &rare.pointer_inputs)
323 }
324
325 pub fn dispatch_pointer_event(&self, event: PointerEvent) {
329 let terminal = matches!(event.kind, PointerEventKind::Up | PointerEventKind::Cancel);
330 for handler in self.pointer_inputs() {
331 if event.is_consumed() && !terminal {
332 break;
333 }
334 handler(event.clone());
335 }
336 }
337
338 pub fn pointer_input_size_sinks(&self) -> &[Rc<std::cell::Cell<cranpose_ui_graphics::Size>>] {
342 self.rare().map_or(&[], |rare| &rare.pointer_input_sizes)
343 }
344
345 pub fn publish_pointer_input_size(&self, size: cranpose_ui_graphics::Size) {
357 if let Some(rare) = self.rare() {
358 publish_pointer_input_size(rare, size);
359 }
360 }
361
362 pub fn z_index(&self) -> f32 {
365 self.rare().map_or(0.0, |rare| rare.z_index)
366 }
367
368 pub fn pointer_icon(&self) -> Option<&PointerIcon> {
371 self.rare()?.pointer_icon.as_ref()
372 }
373
374 pub fn clip_to_bounds(&self) -> bool {
376 self.clip_to_bounds
377 }
378
379 pub fn layer_bounds(&self, node_size: Size) -> Rect {
385 self.layer_coordinator
386 .as_ref()
387 .map_or_else(|| Rect::from_size(node_size), |layer| layer.rect(node_size))
388 }
389
390 #[doc(hidden)]
393 pub fn publish_window_geometry(
394 &self,
395 origin: Point,
396 transform: cranpose_ui_graphics::ProjectiveTransform,
397 size: Size,
398 ) {
399 let Some(rare) = self.rare() else {
401 return;
402 };
403 if rare.text_window.is_some() || rare.viewport_window_rect.is_some() {
404 let window = cranpose_ui_graphics::WindowCoordinates {
405 size,
406 local_to_window: cranpose_ui_graphics::ProjectiveTransform::translation(
407 origin.x, origin.y,
408 )
409 .then(transform),
410 };
411 if let Some(sink) = &rare.text_window {
412 sink.set(window);
413 }
414 if let Some(sink) = &rare.viewport_window_rect {
415 sink.set(window);
416 }
417 }
418 publish_pointer_input_size(rare, size);
419 }
420
421 pub fn motion_context_animated(&self) -> bool {
424 self.rare().is_some_and(|rare| rare.motion_context_animated)
425 }
426
427 pub fn translated_content_context(&self) -> bool {
430 self.rare()
431 .is_some_and(|rare| rare.translated_content_context)
432 }
433
434 pub fn translated_content_context_identity(&self) -> Option<usize> {
437 self.rare()?.translated_content_context_identity
438 }
439
440 pub fn translated_content_offset(&self) -> Option<Point> {
443 self.rare()?
444 .translated_content_offset_reader
445 .as_ref()
446 .map(|reader| reader())
447 }
448
449 pub fn has_text(&self) -> bool {
451 self.text.is_some()
452 }
453
454 pub fn text_content(&self) -> Option<SliceTextRef<'_, str>> {
456 self.annotated_text()
457 .map(|text| text.map(|text| text.text.as_str()))
458 }
459
460 pub fn annotated_text(&self) -> Option<SliceTextRef<'_, Rc<crate::text::AnnotatedString>>> {
462 Some(SliceTextRef(match self.text.as_ref()? {
463 SliceText::Text(layout) => TextBorrow::Layout(layout.annotated_text()),
464 SliceText::Field(field) => TextBorrow::Field(&field.content),
465 }))
466 }
467
468 pub fn text_content_rect(&self, node_size: Size) -> Rect {
471 self.text_coordinator.as_ref().map_or(
472 Rect {
473 x: 0.0,
474 y: 0.0,
475 width: node_size.width,
476 height: node_size.height,
477 },
478 |coordinator| coordinator.rect(node_size),
479 )
480 }
481
482 pub fn text_style(&self) -> Option<SliceTextRef<'_, TextStyle>> {
484 Some(SliceTextRef(match self.text.as_ref()? {
485 SliceText::Text(layout) => TextBorrow::Layout(layout.style()),
486 SliceText::Field(field) => TextBorrow::Field(&field.style),
487 }))
488 }
489
490 pub fn text_layout_options(&self) -> Option<TextLayoutOptions> {
493 match self.text.as_ref()? {
494 SliceText::Text(layout) => Some(layout.options()),
495 SliceText::Field(_) => Some(TextLayoutOptions::default()),
496 }
497 }
498
499 pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
506 match self.text.as_ref()? {
507 SliceText::Field(field) => field.pan.clone(),
508 SliceText::Text(_) => None,
509 }
510 }
511
512 pub fn text_window(
516 &self,
517 ) -> Option<&Rc<std::cell::Cell<cranpose_ui_graphics::WindowCoordinates>>> {
518 self.rare()?.text_window.as_ref()
519 }
520
521 pub fn viewport_window_rect(&self) -> Option<&Rc<dyn crate::modifier_nodes::WindowRectSink>> {
526 self.rare()?.viewport_window_rect.as_ref()
527 }
528
529 pub fn measured_text_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
536 match self.text.as_ref()? {
537 SliceText::Text(layout) => layout.measured_layout(),
538 SliceText::Field(field) => Some(field.layout.measured_layout(&field.style)),
539 }
540 }
541
542 #[inline]
546 pub fn graphics_layer(&self) -> Option<Cow<'_, GraphicsLayer>> {
547 if let Some(resolve) = self
548 .rare()
549 .and_then(|rare| rare.graphics_layer_resolver.as_ref())
550 {
551 Some(Cow::Owned(resolve()))
552 } else {
553 self.graphics_layer.as_deref().map(Cow::Borrowed)
554 }
555 }
556
557 pub fn corner_shape(&self) -> Option<RoundedCornerShape> {
559 self.corner_shape
560 }
561
562 fn enter_layer(&mut self, site: &DrawSite) {
565 if self.layer_coordinator.is_none() {
566 self.layer_coordinator = Some(site.coordinator.clone());
567 }
568 }
569
570 fn push_graphics_layer(
571 &mut self,
572 layer: GraphicsLayer,
573 resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
574 ) {
575 let existing_snapshot = self.graphics_layer.as_deref().cloned();
576 let next_snapshot = existing_snapshot.as_ref().map_or_else(
577 || layer.clone(),
578 |current| merge_graphics_layers(current.clone(), layer.clone()),
579 );
580 let existing_resolver = self
581 .rare()
582 .and_then(|rare| rare.graphics_layer_resolver.clone());
583
584 match &mut self.graphics_layer {
585 Some(held) => **held = next_snapshot,
586 None => self.graphics_layer = Some(Box::new(next_snapshot)),
587 }
588 let merged_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>> =
589 match (existing_resolver, resolver) {
590 (None, None) => None,
591 (Some(current_resolver), None) => Some(Rc::new(move || {
592 merge_graphics_layers(current_resolver(), layer.clone())
593 })),
594 (None, Some(next_resolver)) => {
595 let base = existing_snapshot.unwrap_or_default();
596 Some(Rc::new(move || {
597 merge_graphics_layers(base.clone(), next_resolver())
598 }))
599 }
600 (Some(current_resolver), Some(next_resolver)) => Some(Rc::new(move || {
601 merge_graphics_layers(current_resolver(), next_resolver())
602 })),
603 };
604 if merged_resolver.is_some() {
605 self.rare_mut().graphics_layer_resolver = merged_resolver;
606 }
607 }
608
609 pub fn with_chain_guard(mut self, handle: ModifierChainHandle) -> Self {
611 self.rare_mut().chain_guard = Some(Rc::new(ChainGuard { _handle: handle }));
612 self
613 }
614
615 pub fn debug_stats(&self) -> ModifierNodeSlicesDebugStats {
617 let draw_command_bytes = self.draw_commands.capacity() * size_of::<DrawCommand>();
618 let pointer_input_capacity = self.rare().map_or(0, |rare| rare.pointer_inputs.capacity());
619 let pointer_input_bytes = pointer_input_capacity * size_of::<Rc<dyn Fn(PointerEvent)>>();
620 ModifierNodeSlicesDebugStats {
621 draw_command_count: self.draw_commands.len(),
622 draw_command_capacity: self.draw_commands.capacity(),
623 pointer_input_count: self.pointer_inputs().len(),
624 pointer_input_capacity,
625 has_text_content: self.text.is_some(),
626 has_text_style: self.text.is_some(),
627 has_text_layout_options: self.text.is_some(),
628 has_prepared_text_layout: self.text.is_some(),
629 has_graphics_layer: self.graphics_layer.is_some(),
630 has_graphics_layer_resolver: self
631 .rare()
632 .is_some_and(|rare| rare.graphics_layer_resolver.is_some()),
633 heap_bytes: draw_command_bytes + pointer_input_bytes,
634 }
635 }
636
637 pub fn clear(&mut self) {
639 self.draw_commands.clear();
640 self.layer_draw_boundary = None;
641 self.clip_to_bounds = false;
642 self.layer_coordinator = None;
643 self.text = None;
644 self.text_coordinator = None;
645 self.graphics_layer = None;
646 self.corner_shape = None;
647 if let Some(rare) = self.rare.as_deref_mut() {
648 rare.clear();
649 }
650 }
651}
652
653impl fmt::Debug for ModifierNodeSlices {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 f.debug_struct("ModifierNodeSlices")
656 .field("draw_commands", &self.draw_commands.len())
657 .field("pointer_inputs", &self.pointer_inputs().len())
658 .field("pointer_icon", &self.pointer_icon())
659 .field("clip_to_bounds", &self.clip_to_bounds)
660 .field("motion_context_animated", &self.motion_context_animated())
661 .field(
662 "translated_content_context",
663 &self.translated_content_context(),
664 )
665 .field(
666 "translated_content_context_identity",
667 &self.translated_content_context_identity(),
668 )
669 .field(
670 "translated_content_offset",
671 &self.translated_content_offset(),
672 )
673 .field("text_content", &self.annotated_text())
674 .field("text_style", &self.text_style())
675 .field("text_layout_options", &self.text_layout_options())
676 .field("graphics_layer", &self.graphics_layer)
677 .field(
678 "graphics_layer_resolver",
679 &self
680 .rare()
681 .is_some_and(|rare| rare.graphics_layer_resolver.is_some()),
682 )
683 .field("corner_shape", &self.corner_shape)
684 .finish()
685 }
686}
687
688fn collect_pointer_icon(node: &dyn std::any::Any, slices: &mut ModifierNodeSlices) {
694 if let Some(icon_node) = node.downcast_ref::<PointerIconNode>() {
695 slices.rare_mut().pointer_icon = Some(icon_node.icon().clone());
696 }
697}
698
699pub fn collect_modifier_slices(chain: &ModifierNodeChain) -> ModifierNodeSlices {
702 let mut slices = ModifierNodeSlices::default();
703 collect_modifier_slices_into(chain, &mut slices, &Rc::default(), 1.0);
704 slices
705}
706
707#[derive(Default)]
711pub(crate) struct SlicesSnapshot(std::cell::Cell<Option<Rc<ModifierNodeSlices>>>);
712
713impl SlicesSnapshot {
714 pub(crate) fn get(&self) -> Rc<ModifierNodeSlices> {
715 let snapshot = self.0.take();
716 let shared = snapshot.clone();
717 self.0.set(snapshot);
718 shared.unwrap_or_else(|| {
719 crate::thread_state::with(|state| {
720 Rc::clone(state.empty_slices.get_or_init(Rc::default))
721 })
722 })
723 }
724
725 pub(crate) fn collect(
732 &self,
733 chain: &ModifierNodeChain,
734 geometry: &Rc<CoordinatorGeometry>,
735 density: f32,
736 ) {
737 if !chain.capabilities().intersects(
738 NodeCapabilities::POINTER_INPUT | NodeCapabilities::DRAW | NodeCapabilities::LAYOUT,
739 ) {
740 self.0.set(None);
741 return;
742 }
743 let mut snapshot = self.0.take();
744 if !snapshot
745 .as_mut()
746 .is_some_and(|slices| Rc::get_mut(slices).is_some())
747 {
748 snapshot = Some(Rc::default());
749 }
750 if let Some(slices) = snapshot.as_mut().and_then(Rc::get_mut) {
751 collect_modifier_slices_into(chain, slices, geometry, density);
752 }
753 self.0.set(snapshot);
754 }
755}
756
757fn collect_modifier_slices_into(
758 chain: &ModifierNodeChain,
759 slices: &mut ModifierNodeSlices,
760 geometry: &Rc<CoordinatorGeometry>,
761 density: f32,
762) {
763 slices.clear();
764
765 let caps = chain.capabilities();
766 let has_pointer = caps.intersects(NodeCapabilities::POINTER_INPUT);
767 let has_draw = caps.intersects(NodeCapabilities::DRAW);
768 let has_layout = caps.intersects(NodeCapabilities::LAYOUT);
769
770 if !has_pointer && !has_draw && !has_layout {
771 return;
772 }
773
774 let mut backgrounds = Backgrounds::default();
775 let mut padding = EdgeInsets::default();
776 let mut layout_ordinal = 0_usize;
780
781 for (modifier_index, node_ref) in chain.head_to_tail().enumerate() {
782 let node_caps = node_ref.kind_set();
783
784 node_ref.with_node(|node| {
785 let any = node.as_any();
786
787 if has_pointer
788 && node_caps.intersects(NodeCapabilities::POINTER_INPUT)
789 && let Some(pointer_node) = node.as_pointer_input_node()
790 {
791 if let Some(handler) = pointer_node.pointer_input_handler() {
792 slices.rare_mut().pointer_inputs.push(handler);
793 }
794 if let Some(sink) = pointer_node.layout_size_sink() {
795 slices.rare_mut().pointer_input_sizes.push(sink);
796 }
797 collect_pointer_icon(any, slices);
798 }
799
800 if has_draw && node_caps.intersects(NodeCapabilities::DRAW) {
801 let draw = DrawSite {
802 coordinator: CoordinatorRect::new(geometry, layout_ordinal, padding),
803 displaceable: has_layout,
804 modifier_index,
805 };
806 collect_draw_node(node, &draw, slices, &mut backgrounds);
807 }
808
809 if has_layout && node_caps.intersects(NodeCapabilities::LAYOUT) {
812 if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
813 padding +=
814 crate::modifier_nodes::device_padding(padding_node.padding(), density);
815 }
816
817 if let Some(motion_context_node) = any.downcast_ref::<MotionContextAnimatedNode>() {
818 slices.rare_mut().motion_context_animated = motion_context_node.is_active();
819 }
820
821 collect_window_geometry_sink(
822 any,
823 CoordinatorRect::new(geometry, layout_ordinal + 1, padding),
825 slices,
826 );
827
828 if let Some(translated_content_node) =
829 any.downcast_ref::<TranslatedContentContextNode>()
830 {
831 let rare = slices.rare_mut();
832 rare.translated_content_context = translated_content_node.is_active();
833 rare.translated_content_context_identity =
834 Some(translated_content_node.identity());
835 rare.translated_content_offset_reader =
836 translated_content_node.content_offset_reader();
837 }
838
839 if let Some(text_node) = any.downcast_ref::<TextModifierNode>() {
840 slices.text_coordinator =
841 Some(CoordinatorRect::new(geometry, layout_ordinal, padding));
842 slices.text = Some(SliceText::Text(text_node.prepared_layout_handle()));
843 }
844
845 if let Some(text_field_node) = any.downcast_ref::<TextFieldModifierNode>() {
846 slices.text = Some(SliceText::Field(Rc::new(FieldText {
847 content: text_field_node.shown_text(),
848 style: text_field_node.style().clone(),
849 layout: text_field_node.layout_handle(),
850 pan: text_field_node.text_pan_resolver(),
851 })));
852 slices.rare_mut().text_window = Some(text_field_node.window_sink());
853
854 let coordinator = CoordinatorRect::new(geometry, layout_ordinal, padding);
855 text_field_node.set_content_origin(coordinator.clone());
856 slices.text_coordinator = Some(coordinator);
857 }
858 layout_ordinal += 1;
859 }
860 });
861 }
862
863 backgrounds.insert_into(slices);
864}
865
866struct DrawSite {
869 coordinator: CoordinatorRect,
870 displaceable: bool,
871 modifier_index: usize,
872}
873
874#[derive(Default)]
879struct Backgrounds {
880 slots: SmallVec<[BackgroundSlot; 2]>,
881 pending_shape: Option<RoundedCornerShape>,
882 last_shape: Option<RoundedCornerShape>,
883}
884
885struct BackgroundSlot {
886 color: crate::modifier::Color,
887 coordinator: CoordinatorRect,
888 insert_index: usize,
889 precedes_layer: bool,
890 corner_shape: Option<RoundedCornerShape>,
891}
892
893impl Backgrounds {
894 fn push(
895 &mut self,
896 color: crate::modifier::Color,
897 shape: Option<RoundedCornerShape>,
898 site: &DrawSite,
899 slices: &ModifierNodeSlices,
900 ) {
901 let corner_shape = shape.or_else(|| self.pending_shape.take());
902 if shape.is_some() {
903 self.last_shape = shape;
904 }
905 self.slots.push(BackgroundSlot {
906 color,
907 coordinator: site.coordinator.clone(),
908 insert_index: slices.draw_commands.len(),
909 precedes_layer: slices.layer_draw_boundary.is_none(),
910 corner_shape,
911 });
912 }
913
914 fn shape(&mut self, shape: RoundedCornerShape) {
915 self.last_shape = Some(shape);
916 match self.slots.last_mut() {
917 Some(slot) => slot.corner_shape = Some(shape),
918 None => self.pending_shape = Some(shape),
919 }
920 }
921
922 fn insert_into(self, slices: &mut ModifierNodeSlices) {
925 slices.corner_shape = self.last_shape;
926 for slot in self.slots.into_iter().rev() {
927 let BackgroundSlot {
928 color,
929 coordinator,
930 insert_index,
931 precedes_layer,
932 corner_shape,
933 } = slot;
934 let draw_cmd = Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
935 use cranpose_ui_graphics::{CornerRadii, DrawScope as _};
936
937 use crate::modifier::Brush;
938
939 let rect = coordinator.rect(scope.size());
940 let brush = Brush::solid(color);
941 if let Some(shape) = corner_shape {
942 let radii: CornerRadii = shape.resolve(rect.width, rect.height);
943 scope.draw_round_rect_at(rect, brush, radii);
944 } else {
945 scope.draw_rect_at(rect, brush);
946 }
947 });
948 slices.insert_background_draw(
949 insert_index,
950 precedes_layer,
951 DrawCommand::Behind(draw_cmd),
952 );
953 }
954 }
955}
956
957fn collect_window_geometry_sink(
960 any: &dyn std::any::Any,
961 text: CoordinatorRect,
962 slices: &mut ModifierNodeSlices,
963) {
964 if let Some(reporter) = any.downcast_ref::<WindowRectReporterNode>() {
965 slices.rare_mut().viewport_window_rect = Some(reporter.window_rect_sink());
966 }
967 if let Some(selectable) = any.downcast_ref::<SelectableTextNode>() {
968 slices.rare_mut().text_window = Some(selectable.geometry().window_sink());
969 selectable.geometry().set_content_origin(text);
970 }
971}
972
973fn collect_draw_node(
975 node: &dyn cranpose_foundation::ModifierNode,
976 site: &DrawSite,
977 slices: &mut ModifierNodeSlices,
978 backgrounds: &mut Backgrounds,
979) {
980 let any = node.as_any();
981 if let Some(bg_node) = any.downcast_ref::<BackgroundNode>() {
982 backgrounds.push(bg_node.color(), bg_node.shape(), site, slices);
983 }
984
985 if let Some(shape_node) = any.downcast_ref::<CornerShapeNode>() {
986 backgrounds.shape(shape_node.shape());
987 }
988
989 if let Some(z_index_node) = any.downcast_ref::<super::z_index::ZIndexNode>() {
990 slices.rare_mut().z_index += z_index_node.z_index();
991 }
992
993 if let Some(commands) = any.downcast_ref::<DrawCommandNode>() {
994 slices.draw_commands.extend(
995 commands
996 .observed_commands(site.modifier_index)
997 .map(|command| placed_draw_command(command, site)),
998 );
999 }
1000
1001 if let Some(draw_node) = node.as_draw_node() {
1002 collect_draw_closures(draw_node, site, slices);
1003 }
1004
1005 if let Some(layer_node) = any.downcast_ref::<GraphicsLayerNode>() {
1006 slices.mark_layer_draw_boundary();
1007 slices.push_graphics_layer(
1008 layer_node.layer_snapshot(),
1009 layer_node.layer_resolver(site.modifier_index),
1010 );
1011 slices.enter_layer(site);
1012 }
1013
1014 if any.is::<ClipToBoundsNode>() {
1015 slices.mark_layer_draw_boundary();
1016 slices.clip_to_bounds = true;
1017 slices.enter_layer(site);
1018 }
1019}
1020
1021fn collect_draw_closures(
1024 draw_node: &dyn cranpose_foundation::DrawModifierNode,
1025 site: &DrawSite,
1026 slices: &mut ModifierNodeSlices,
1027) {
1028 if let Some(closure) = draw_node.create_behind_draw_closure() {
1029 slices
1030 .draw_commands
1031 .push(placed_draw_command(DrawCommand::Behind(closure), site));
1032 }
1033 if let Some(closure) = draw_node.create_draw_closure() {
1034 slices
1035 .draw_commands
1036 .push(placed_draw_command(DrawCommand::Overlay(closure), site));
1037 }
1038}
1039
1040fn placed_draw_command(command: DrawCommand, site: &DrawSite) -> DrawCommand {
1043 if !site.displaceable {
1044 return command;
1045 }
1046 let place = |draw: crate::draw::DrawCommandFn| -> crate::draw::DrawCommandFn {
1047 let coordinator = site.coordinator.clone();
1048 Rc::new(move |scope: &mut cranpose_ui_graphics::DrawScopeDefault| {
1049 use cranpose_ui_graphics::DrawScope as _;
1050
1051 let insets = coordinator.insets(scope.size());
1052 if insets.is_zero() {
1053 draw(scope);
1054 } else {
1055 scope.draw_inset(insets, |inner| draw(inner));
1056 }
1057 })
1058 };
1059 match command {
1060 DrawCommand::Behind(draw) => DrawCommand::Behind(place(draw)),
1061 DrawCommand::WithContent(draw) => DrawCommand::WithContent(place(draw)),
1062 DrawCommand::Overlay(draw) => DrawCommand::Overlay(place(draw)),
1063 }
1064}
1065
1066pub fn collect_slices_from_modifier(modifier: &Modifier) -> ModifierNodeSlices {
1068 let mut handle = ModifierChainHandle::new();
1069 let _ = handle.update(modifier);
1070 collect_modifier_slices(handle.chain()).with_chain_guard(handle)
1071}
1072
1073#[cfg(test)]
1074#[path = "tests/slices_tests.rs"]
1075mod tests;