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