1use std::{
2 cell::Cell,
3 hash::{Hash, Hasher},
4 rc::Rc,
5};
6
7use cranpose_core::NodeId;
8use cranpose_foundation::{
9 Constraints, DelegatableNode, DrawModifierNode, InvalidationKind, LayoutModifierNode,
10 Measurable, ModifierNode, ModifierNodeContext, ModifierNodeElement, NodeCapabilities,
11 NodeState, PointerEvent, PointerInputNode, Size,
12};
13use cranpose_ui_graphics::{ColorFilter, DrawScope, PointerIcon};
14
15mod alignment;
16mod background;
17mod clickable;
18mod clip;
19mod fill;
20mod intrinsic_size;
21mod offset;
22mod padding;
23mod size;
24mod weight;
25
26pub(crate) use alignment::AlignmentElement;
27pub use background::{BackgroundElement, CornerShapeElement};
28pub use clickable::{ClickableElement, ClickableNode};
29pub(crate) use clip::ClipToBoundsElement;
30pub use fill::{FillDirection, FillElement};
31pub(crate) use intrinsic_size::IntrinsicSizeElement;
32pub use offset::{FractionalOffsetElement, OffsetElement};
33pub use padding::PaddingElement;
34pub(crate) use padding::device_padding;
35pub use size::SizeElement;
36pub(crate) use weight::WeightElement;
37
38use crate::{
39 draw::DrawCommand,
40 modifier::{BlendMode, Brush, CompositingStrategy, GraphicsLayer, RoundedCornerShape},
41};
42
43fn hash_f32_value<H: Hasher>(state: &mut H, value: f32) {
44 state.write_u32(value.to_bits());
45}
46
47fn hash_space<H: Hasher>(state: &mut H, space: Option<&cranpose_ui_graphics::space::LayerSpace>) {
50 use cranpose_ui_graphics::space::LayerSpace;
51 match space {
52 None => state.write_u8(0),
53 Some(LayerSpace::Scene(_)) => state.write_u8(1),
54 Some(LayerSpace::Surface(surfaces)) => {
55 state.write_u8(2);
56 state.write_u64(surfaces.owner().mesh.id());
57 }
58 Some(LayerSpace::Transform(_)) => state.write_u8(3),
59 }
60}
61
62fn hash_graphics_layer<H: Hasher>(state: &mut H, layer: &GraphicsLayer) {
63 hash_f32_value(state, layer.alpha);
64 hash_f32_value(state, layer.scale);
65 hash_f32_value(state, layer.scale_x);
66 hash_f32_value(state, layer.scale_y);
67 hash_f32_value(state, layer.rotation_x);
68 hash_f32_value(state, layer.rotation_y);
69 hash_f32_value(state, layer.rotation_z);
70 hash_f32_value(state, layer.camera_distance);
71 hash_f32_value(state, layer.transform_origin.pivot_fraction_x);
72 hash_f32_value(state, layer.transform_origin.pivot_fraction_y);
73 hash_f32_value(state, layer.translation_x);
74 hash_f32_value(state, layer.translation_y);
75 hash_space(state, layer.space.as_deref());
76 hash_f32_value(state, layer.shadow_elevation);
77 hash_f32_value(state, layer.ambient_shadow_color.r());
78 hash_f32_value(state, layer.ambient_shadow_color.g());
79 hash_f32_value(state, layer.ambient_shadow_color.b());
80 hash_f32_value(state, layer.ambient_shadow_color.a());
81 hash_f32_value(state, layer.spot_shadow_color.r());
82 hash_f32_value(state, layer.spot_shadow_color.g());
83 hash_f32_value(state, layer.spot_shadow_color.b());
84 hash_f32_value(state, layer.spot_shadow_color.a());
85 match layer.shape {
86 crate::modifier::LayerShape::Rectangle => {
87 state.write_u8(0);
88 }
89 crate::modifier::LayerShape::Rounded(shape) => {
90 state.write_u8(1);
91 let radii = shape.radii();
92 hash_f32_value(state, radii.top_left);
93 hash_f32_value(state, radii.top_right);
94 hash_f32_value(state, radii.bottom_right);
95 hash_f32_value(state, radii.bottom_left);
96 }
97 }
98 state.write_u8(layer.clip as u8);
99 match &layer.color_filter {
100 Some(ColorFilter::Tint(color)) => {
101 state.write_u8(1);
102 hash_f32_value(state, color.r());
103 hash_f32_value(state, color.g());
104 hash_f32_value(state, color.b());
105 hash_f32_value(state, color.a());
106 }
107 Some(ColorFilter::Modulate(color)) => {
108 state.write_u8(2);
109 hash_f32_value(state, color.r());
110 hash_f32_value(state, color.g());
111 hash_f32_value(state, color.b());
112 hash_f32_value(state, color.a());
113 }
114 Some(ColorFilter::Matrix(matrix)) => {
115 state.write_u8(3);
116 for &value in matrix.iter() {
117 hash_f32_value(state, value);
118 }
119 }
120 None => state.write_u8(0),
121 }
122 state.write_u8(layer.render_effect.is_some() as u8);
123 state.write_u8(layer.backdrop_effect.is_some() as u8);
124 let compositing_tag = match layer.compositing_strategy {
125 CompositingStrategy::Auto => 0,
126 CompositingStrategy::Offscreen => 1,
127 CompositingStrategy::ModulateAlpha => 2,
128 };
129 state.write_u8(compositing_tag);
130 let blend_tag = match layer.blend_mode {
131 BlendMode::Clear => 0,
132 BlendMode::Src => 1,
133 BlendMode::Dst => 2,
134 BlendMode::SrcOver => 3,
135 BlendMode::DstOver => 4,
136 BlendMode::SrcIn => 5,
137 BlendMode::DstIn => 6,
138 BlendMode::SrcOut => 7,
139 BlendMode::DstOut => 8,
140 BlendMode::SrcAtop => 9,
141 BlendMode::DstAtop => 10,
142 BlendMode::Xor => 11,
143 BlendMode::Plus => 12,
144 BlendMode::Modulate => 13,
145 BlendMode::Screen => 14,
146 BlendMode::Overlay => 15,
147 BlendMode::Darken => 16,
148 BlendMode::Lighten => 17,
149 BlendMode::ColorDodge => 18,
150 BlendMode::ColorBurn => 19,
151 BlendMode::HardLight => 20,
152 BlendMode::SoftLight => 21,
153 BlendMode::Difference => 22,
154 BlendMode::Exclusion => 23,
155 BlendMode::Multiply => 24,
156 BlendMode::Hue => 25,
157 BlendMode::Saturation => 26,
158 BlendMode::Color => 27,
159 BlendMode::Luminosity => 28,
160 };
161 state.write_u8(blend_tag);
162}
163
164macro_rules! impl_layout_modifier_node {
165 ($ty:ty) => {
166 impl ModifierNode for $ty {
167 fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
168 Some(self)
169 }
170
171 fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
172 Some(self)
173 }
174 }
175 };
176 ($ty:ty, invalidate = $invalidation:expr) => {
177 impl ModifierNode for $ty {
178 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
179 context.invalidate($invalidation);
180 }
181
182 fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
183 Some(self)
184 }
185
186 fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
187 Some(self)
188 }
189 }
190 };
191}
192pub(crate) use impl_layout_modifier_node;
193
194macro_rules! impl_draw_modifier_node {
195 ($ty:ty) => {
196 impl ModifierNode for $ty {
197 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
198 context.invalidate(InvalidationKind::Draw);
199 }
200
201 fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
202 Some(self)
203 }
204
205 fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
206 Some(self)
207 }
208 }
209
210 impl DrawModifierNode for $ty {}
211 };
212}
213
214macro_rules! impl_sink_reporter_element {
215 ($element:ty, $node:ty) => {
216 impl ModifierNodeElement for $element {
217 type Node = $node;
218
219 fn create(&self) -> Self::Node {
220 <$node>::new(self.sink.clone())
221 }
222
223 fn update(&self, node: &mut Self::Node) {
224 node.sink = self.sink.clone();
225 }
226
227 fn capabilities(&self) -> NodeCapabilities {
228 NodeCapabilities::LAYOUT
229 }
230 }
231 };
232}
233
234fn measure_pass_through(
235 measurable: &dyn Measurable,
236 constraints: Constraints,
237 offset: impl FnOnce(Size) -> (f32, f32),
238) -> cranpose_ui_layout::LayoutModifierMeasureResult {
239 let placeable = measurable.measure(constraints);
240 let size = Size {
241 width: placeable.width(),
242 height: placeable.height(),
243 };
244 let (x, y) = offset(size);
245 cranpose_ui_layout::LayoutModifierMeasureResult::new(size, x, y)
246}
247
248fn attach_draw_observer(
249 node_id_cell: &Cell<Option<NodeId>>,
250 context: &mut dyn ModifierNodeContext,
251) {
252 node_id_cell.set(context.node_id());
253 context.invalidate(InvalidationKind::Draw);
254}
255
256fn detach_draw_observer(node_id_cell: &Cell<Option<NodeId>>) {
257 if let Some(node_id) = node_id_cell.replace(None) {
258 crate::render_state::clear_draw_observations_for_node(node_id);
259 }
260}
261
262#[derive(Debug, Clone, PartialEq)]
263pub(crate) struct BorderElement {
264 width: f32,
265 brush: Brush,
266 shape: RoundedCornerShape,
267}
268
269impl BorderElement {
270 pub(crate) fn new(width: f32, brush: Brush, shape: RoundedCornerShape) -> Self {
271 Self {
272 width,
273 brush,
274 shape,
275 }
276 }
277
278 pub(crate) fn command(&self) -> DrawCommand {
280 let Self {
281 width,
282 brush,
283 shape,
284 } = self.clone();
285 DrawCommand::Overlay(Rc::new(move |scope| {
286 let size = scope.size();
287 if width <= 0.0 || size.width <= 0.0 || size.height <= 0.0 {
288 return;
289 }
290 let radii = shape.resolve(size.width, size.height);
291 let half = width / 2.0;
292 if width * 2.0 >= size.width.min(size.height) {
293 scope.draw_round_rect(brush.clone(), radii);
295 return;
296 }
297 let inset = |radius: f32| (radius - half).max(0.0);
298 scope.draw_round_rect_at_stroked(
299 cranpose_ui_graphics::Rect {
300 x: half,
301 y: half,
302 width: size.width - width,
303 height: size.height - width,
304 },
305 brush.clone(),
306 cranpose_ui_graphics::CornerRadii {
307 top_left: inset(radii.top_left),
308 top_right: inset(radii.top_right),
309 bottom_right: inset(radii.bottom_right),
310 bottom_left: inset(radii.bottom_left),
311 },
312 cranpose_ui_graphics::Stroke::new(width),
313 );
314 }))
315 }
316}
317
318impl Hash for BorderElement {
319 fn hash<H: Hasher>(&self, state: &mut H) {
320 hash_f32_value(state, self.width);
321 std::mem::discriminant(&self.brush).hash(state);
322 if let Brush::Solid(color) = self.brush {
323 hash_f32_value(state, color.0);
324 hash_f32_value(state, color.1);
325 hash_f32_value(state, color.2);
326 hash_f32_value(state, color.3);
327 }
328 let radii = self.shape.radii();
329 hash_f32_value(state, radii.top_left);
330 hash_f32_value(state, radii.top_right);
331 hash_f32_value(state, radii.bottom_right);
332 hash_f32_value(state, radii.bottom_left);
333 }
334}
335
336impl ModifierNodeElement for BorderElement {
337 type Node = DrawCommandNode;
338
339 fn create(&self) -> Self::Node {
340 DrawCommandNode::new(vec![self.command()])
341 }
342
343 fn update(&self, node: &mut Self::Node) {
344 node.commands = vec![self.command()];
345 }
346
347 fn capabilities(&self) -> NodeCapabilities {
348 NodeCapabilities::DRAW
349 }
350}
351
352pub(crate) struct GraphicsLayerNode {
353 layer: GraphicsLayer,
354 layer_resolver: Option<Rc<dyn Fn() -> GraphicsLayer>>,
355 node_id: Rc<Cell<Option<NodeId>>>,
356 state: NodeState,
357}
358
359impl GraphicsLayerNode {
360 pub(crate) fn new(layer: GraphicsLayer) -> Self {
361 Self {
362 layer,
363 layer_resolver: None,
364 node_id: Rc::new(Cell::new(None)),
365 state: NodeState::new(),
366 }
367 }
368
369 pub(crate) fn new_lazy(layer_resolver: Rc<dyn Fn() -> GraphicsLayer>) -> Self {
370 Self {
371 layer: GraphicsLayer::default(),
372 layer_resolver: Some(layer_resolver),
373 node_id: Rc::new(Cell::new(None)),
374 state: NodeState::new(),
375 }
376 }
377
378 #[cfg(test)]
379 pub(crate) fn layer(&self) -> GraphicsLayer {
380 if let Some(resolve) = self.layer_resolver(0) {
381 resolve()
382 } else {
383 self.layer.clone()
384 }
385 }
386
387 pub(crate) fn layer_snapshot(&self) -> GraphicsLayer {
388 self.layer.clone()
389 }
390
391 pub(crate) fn layer_resolver(
392 &self,
393 modifier_index: usize,
394 ) -> Option<Rc<dyn Fn() -> GraphicsLayer>> {
395 self.layer_resolver.as_ref().map(|resolve| {
396 let resolve = Rc::clone(resolve);
397 let node_id = Rc::clone(&self.node_id);
398 Rc::new(move || {
399 if let Some(node_id) = node_id.get() {
400 let scope = crate::render_state::DrawObservationScope::layer_properties(
401 node_id,
402 modifier_index,
403 );
404 crate::render_state::observe_draw_reads(scope, || resolve())
405 } else {
406 resolve()
407 }
408 }) as Rc<dyn Fn() -> GraphicsLayer>
409 })
410 }
411
412 fn set_static(&mut self, layer: GraphicsLayer) {
413 let changed = self.layer != layer || self.layer_resolver.is_some();
414 self.layer = layer;
415 self.layer_resolver = None;
416 if changed && let Some(node_id) = self.node_id.get() {
417 crate::render_state::schedule_draw_repass(node_id);
418 }
419 }
420
421 pub(crate) fn set_lazy(&mut self, layer_resolver: Rc<dyn Fn() -> GraphicsLayer>) {
422 let changed = self
423 .layer_resolver
424 .as_ref()
425 .is_none_or(|current| !Rc::ptr_eq(current, &layer_resolver));
426 self.layer_resolver = Some(layer_resolver);
427 if changed && let Some(node_id) = self.node_id.get() {
428 crate::render_state::schedule_draw_repass(node_id);
429 }
430 }
431}
432
433impl DelegatableNode for GraphicsLayerNode {
434 fn node_state(&self) -> &NodeState {
435 &self.state
436 }
437}
438
439impl ModifierNode for GraphicsLayerNode {
440 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
441 attach_draw_observer(&self.node_id, context);
442 }
443
444 fn on_detach(&mut self) {
445 detach_draw_observer(&self.node_id);
446 }
447}
448
449impl std::fmt::Debug for GraphicsLayerNode {
450 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
451 f.debug_struct("GraphicsLayerNode")
452 .field("layer", &self.layer)
453 .field("lazy", &self.layer_resolver.is_some())
454 .finish()
455 }
456}
457
458#[derive(Debug, Clone, PartialEq)]
459pub(crate) struct GraphicsLayerElement {
460 layer: GraphicsLayer,
461}
462
463impl GraphicsLayerElement {
464 pub(crate) fn new(layer: GraphicsLayer) -> Self {
465 Self { layer }
466 }
467}
468
469impl Hash for GraphicsLayerElement {
470 fn hash<H: Hasher>(&self, state: &mut H) {
471 hash_graphics_layer(state, &self.layer);
472 }
473}
474
475impl ModifierNodeElement for GraphicsLayerElement {
476 type Node = GraphicsLayerNode;
477
478 fn create(&self) -> Self::Node {
479 GraphicsLayerNode::new(self.layer.clone())
480 }
481
482 fn update(&self, node: &mut Self::Node) {
483 node.set_static(self.layer.clone());
484 }
485
486 fn capabilities(&self) -> NodeCapabilities {
487 NodeCapabilities::DRAW
488 }
489}
490
491#[derive(Clone)]
492pub(crate) struct LazyGraphicsLayerElement {
493 layer_resolver: Rc<dyn Fn() -> GraphicsLayer>,
494}
495
496impl LazyGraphicsLayerElement {
497 pub(crate) fn new(layer_resolver: Rc<dyn Fn() -> GraphicsLayer>) -> Self {
498 Self { layer_resolver }
499 }
500}
501
502impl std::fmt::Debug for LazyGraphicsLayerElement {
503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504 f.debug_struct("LazyGraphicsLayerElement")
505 .field("resolver", &"<closure>")
506 .finish()
507 }
508}
509
510impl PartialEq for LazyGraphicsLayerElement {
511 fn eq(&self, other: &Self) -> bool {
512 Rc::ptr_eq(&self.layer_resolver, &other.layer_resolver)
513 }
514}
515
516impl Eq for LazyGraphicsLayerElement {}
517
518impl Hash for LazyGraphicsLayerElement {
519 fn hash<H: Hasher>(&self, state: &mut H) {
520 let ptr = Rc::as_ptr(&self.layer_resolver) as *const ();
521 ptr.hash(state);
522 }
523}
524
525impl ModifierNodeElement for LazyGraphicsLayerElement {
526 type Node = GraphicsLayerNode;
527
528 fn create(&self) -> Self::Node {
529 GraphicsLayerNode::new_lazy(Rc::clone(&self.layer_resolver))
530 }
531
532 fn update(&self, node: &mut Self::Node) {
533 node.set_lazy(Rc::clone(&self.layer_resolver));
534 }
535
536 fn capabilities(&self) -> NodeCapabilities {
537 NodeCapabilities::DRAW
538 }
539
540 fn always_update(&self) -> bool {
541 true
542 }
543
544 fn auto_invalidate_on_update(&self) -> bool {
545 false
546 }
547}
548
549#[derive(Debug)]
550pub(crate) struct PointerIconNode {
551 icon: PointerIcon,
552 state: NodeState,
553}
554
555impl PointerIconNode {
556 pub(crate) fn new(icon: PointerIcon) -> Self {
557 Self {
558 icon,
559 state: NodeState::new(),
560 }
561 }
562
563 pub(crate) fn icon(&self) -> &PointerIcon {
564 &self.icon
565 }
566}
567
568impl DelegatableNode for PointerIconNode {
569 fn node_state(&self) -> &NodeState {
570 &self.state
571 }
572}
573
574impl ModifierNode for PointerIconNode {
575 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
576 context.invalidate(InvalidationKind::PointerInput);
577 }
578
579 fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
580 Some(self)
581 }
582
583 fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
584 Some(self)
585 }
586}
587
588impl PointerInputNode for PointerIconNode {
589 fn on_pointer_event(
590 &mut self,
591 _context: &mut dyn ModifierNodeContext,
592 _event: &PointerEvent,
593 ) -> bool {
594 false
595 }
596
597 fn hit_test(&self, _x: f32, _y: f32) -> bool {
598 true
599 }
600
601 fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
602 None
603 }
604}
605
606#[derive(Clone, Debug, PartialEq, Eq, Hash)]
607pub(crate) struct PointerIconElement {
608 icon: PointerIcon,
609}
610
611impl PointerIconElement {
612 pub(crate) fn new(icon: PointerIcon) -> Self {
613 Self { icon }
614 }
615}
616
617impl ModifierNodeElement for PointerIconElement {
618 type Node = PointerIconNode;
619
620 fn create(&self) -> Self::Node {
621 PointerIconNode::new(self.icon.clone())
622 }
623
624 fn update(&self, node: &mut Self::Node) {
625 node.icon = self.icon.clone();
626 }
627
628 fn capabilities(&self) -> NodeCapabilities {
629 NodeCapabilities::POINTER_INPUT
630 }
631}
632
633#[derive(Debug)]
635pub struct AlphaNode {
636 alpha: f32,
637 state: NodeState,
638}
639
640impl AlphaNode {
641 pub fn new(alpha: f32) -> Self {
643 Self {
644 alpha: alpha.clamp(0.0, 1.0),
645 state: NodeState::new(),
646 }
647 }
648}
649
650impl DelegatableNode for AlphaNode {
651 fn node_state(&self) -> &NodeState {
652 &self.state
653 }
654}
655
656impl_draw_modifier_node!(AlphaNode);
657
658#[derive(Debug, Clone, PartialEq)]
660pub struct AlphaElement {
661 alpha: f32,
662}
663
664impl AlphaElement {
665 pub fn new(alpha: f32) -> Self {
668 Self {
669 alpha: alpha.clamp(0.0, 1.0),
670 }
671 }
672}
673
674impl Hash for AlphaElement {
675 fn hash<H: Hasher>(&self, state: &mut H) {
676 hash_f32_value(state, self.alpha);
677 }
678}
679
680impl ModifierNodeElement for AlphaElement {
681 type Node = AlphaNode;
682
683 fn create(&self) -> Self::Node {
684 AlphaNode::new(self.alpha)
685 }
686
687 fn update(&self, node: &mut Self::Node) {
688 let new_alpha = self.alpha.clamp(0.0, 1.0);
689 if (node.alpha - new_alpha).abs() > f32::EPSILON {
690 node.alpha = new_alpha;
691 }
692 }
693
694 fn capabilities(&self) -> NodeCapabilities {
695 NodeCapabilities::DRAW
696 }
697}
698
699pub trait WindowRectSink {
700 fn set(&self, coordinates: cranpose_ui_graphics::WindowCoordinates);
701}
702
703impl WindowRectSink for Cell<cranpose_ui_graphics::Rect> {
704 fn set(&self, coordinates: cranpose_ui_graphics::WindowCoordinates) {
705 Self::set(self, coordinates.bounds());
706 }
707}
708
709impl WindowRectSink for Cell<cranpose_ui_graphics::WindowCoordinates> {
710 fn set(&self, coordinates: cranpose_ui_graphics::WindowCoordinates) {
711 Self::set(self, coordinates);
712 }
713}
714
715struct StateWindowRectSink(cranpose_core::MutableState<cranpose_ui_graphics::Rect>);
716
717impl WindowRectSink for StateWindowRectSink {
718 fn set(&self, coordinates: cranpose_ui_graphics::WindowCoordinates) {
719 self.0.set(coordinates.bounds());
720 }
721}
722
723pub(crate) struct WindowRectReporterNode {
724 sink: Rc<dyn WindowRectSink>,
725 state: NodeState,
726}
727
728impl WindowRectReporterNode {
729 pub(crate) fn new(sink: Rc<dyn WindowRectSink>) -> Self {
730 Self {
731 sink,
732 state: NodeState::new(),
733 }
734 }
735
736 pub(crate) fn window_rect_sink(&self) -> Rc<dyn WindowRectSink> {
737 Rc::clone(&self.sink)
738 }
739}
740
741impl DelegatableNode for WindowRectReporterNode {
742 fn node_state(&self) -> &NodeState {
743 &self.state
744 }
745}
746
747impl_layout_modifier_node!(WindowRectReporterNode);
748
749impl LayoutModifierNode for WindowRectReporterNode {
750 fn measure(
751 &self,
752 _context: &mut dyn ModifierNodeContext,
753 measurable: &dyn Measurable,
754 constraints: Constraints,
755 ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
756 measure_pass_through(measurable, constraints, |_| (0.0, 0.0))
757 }
758}
759
760#[derive(Clone)]
761pub(crate) struct WindowRectReporterElement {
762 sink: Rc<dyn WindowRectSink>,
763}
764
765impl WindowRectReporterElement {
766 pub(crate) fn new(sink: Rc<Cell<cranpose_ui_graphics::Rect>>) -> Self {
767 Self { sink }
768 }
769
770 pub(crate) fn from_coordinates(
771 sink: Rc<Cell<cranpose_ui_graphics::WindowCoordinates>>,
772 ) -> Self {
773 Self { sink }
774 }
775
776 pub(crate) fn from_state(
777 sink: cranpose_core::MutableState<cranpose_ui_graphics::Rect>,
778 ) -> Self {
779 Self {
780 sink: Rc::new(StateWindowRectSink(sink)),
781 }
782 }
783}
784
785impl std::fmt::Debug for WindowRectReporterElement {
786 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
787 f.debug_struct("WindowRectReporterElement").finish()
788 }
789}
790
791impl PartialEq for WindowRectReporterElement {
792 fn eq(&self, other: &Self) -> bool {
793 Rc::ptr_eq(&self.sink, &other.sink)
794 }
795}
796
797impl Eq for WindowRectReporterElement {}
798
799impl Hash for WindowRectReporterElement {
800 fn hash<H: Hasher>(&self, state: &mut H) {
801 std::ptr::hash(Rc::as_ptr(&self.sink).cast::<()>(), state);
802 }
803}
804
805impl_sink_reporter_element!(WindowRectReporterElement, WindowRectReporterNode);
806
807pub(crate) struct SelectableTextNode {
808 sink: Rc<crate::selection_container::SelectableGeometry>,
809 state: NodeState,
810}
811
812impl SelectableTextNode {
813 pub(crate) fn new(sink: Rc<crate::selection_container::SelectableGeometry>) -> Self {
814 Self {
815 sink,
816 state: NodeState::new(),
817 }
818 }
819
820 pub(crate) fn geometry(&self) -> &crate::selection_container::SelectableGeometry {
821 &self.sink
822 }
823}
824
825impl DelegatableNode for SelectableTextNode {
826 fn node_state(&self) -> &NodeState {
827 &self.state
828 }
829}
830
831impl_layout_modifier_node!(SelectableTextNode);
832
833impl LayoutModifierNode for SelectableTextNode {
834 fn measure(
835 &self,
836 _context: &mut dyn ModifierNodeContext,
837 measurable: &dyn Measurable,
838 constraints: Constraints,
839 ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
840 measure_pass_through(measurable, constraints, |_| (0.0, 0.0))
841 }
842}
843
844#[derive(Clone)]
845pub(crate) struct SelectableTextElement {
846 sink: Rc<crate::selection_container::SelectableGeometry>,
847}
848
849impl SelectableTextElement {
850 pub(crate) fn new(sink: Rc<crate::selection_container::SelectableGeometry>) -> Self {
851 Self { sink }
852 }
853}
854
855impl std::fmt::Debug for SelectableTextElement {
856 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
857 f.debug_struct("SelectableTextElement").finish()
858 }
859}
860
861impl PartialEq for SelectableTextElement {
862 fn eq(&self, other: &Self) -> bool {
863 Rc::ptr_eq(&self.sink, &other.sink)
864 }
865}
866
867impl Eq for SelectableTextElement {}
868
869impl Hash for SelectableTextElement {
870 fn hash<H: Hasher>(&self, state: &mut H) {
871 std::ptr::hash(Rc::as_ptr(&self.sink), state);
872 }
873}
874
875impl_sink_reporter_element!(SelectableTextElement, SelectableTextNode);
876
877pub(crate) trait SizeSink {
878 fn set(&self, size: Size);
879}
880
881impl SizeSink for Cell<Size> {
882 fn set(&self, size: Size) {
883 Self::set(self, size);
884 }
885}
886
887struct StateSizeSink(cranpose_core::MutableState<Size>);
888
889impl SizeSink for StateSizeSink {
890 fn set(&self, size: Size) {
891 self.0.set(size);
892 }
893}
894
895pub(crate) struct SizeReporterNode {
896 sink: Rc<dyn SizeSink>,
897 state: NodeState,
898 #[cfg(debug_assertions)]
899 oscillation: Cell<(Size, Size, u32)>,
900}
901
902impl SizeReporterNode {
903 pub(crate) fn new(sink: Rc<dyn SizeSink>) -> Self {
904 Self {
905 sink,
906 state: NodeState::new(),
907 #[cfg(debug_assertions)]
908 oscillation: Cell::new((Size::default(), Size::default(), 0)),
909 }
910 }
911
912 #[cfg(debug_assertions)]
913 fn check_oscillation(&self, size: Size) {
914 const ALTERNATION_CEILING: u32 = 64;
915 let (last, second_last, count) = self.oscillation.get();
916 let count = if size == second_last && size != last {
917 count + 1
918 } else if size == last {
919 count
920 } else {
921 0
922 };
923 assert!(
924 count <= ALTERNATION_CEILING,
925 "size-reactive feedback loop: this node's measured size has \
926 alternated between {last:?} and {size:?} for {count} passes — \
927 its content's size depends on the size it reports (the \
928 onSizeChanged self-reference hazard). Break the cycle by making \
929 the reported size feed only content that does not change this \
930 node's own measured size."
931 );
932 self.oscillation.set((size, last, count));
933 }
934}
935
936impl DelegatableNode for SizeReporterNode {
937 fn node_state(&self) -> &NodeState {
938 &self.state
939 }
940}
941
942impl_layout_modifier_node!(SizeReporterNode);
943
944impl LayoutModifierNode for SizeReporterNode {
945 fn measure(
946 &self,
947 _context: &mut dyn ModifierNodeContext,
948 measurable: &dyn Measurable,
949 constraints: Constraints,
950 ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
951 measure_pass_through(measurable, constraints, |size| {
952 #[cfg(debug_assertions)]
953 self.check_oscillation(size);
954 self.sink.set(size);
955 (0.0, 0.0)
956 })
957 }
958}
959
960#[derive(Clone)]
961pub(crate) struct SizeReporterElement {
962 sink: Rc<dyn SizeSink>,
963}
964
965impl SizeReporterElement {
966 pub(crate) fn new(sink: Rc<Cell<Size>>) -> Self {
967 Self { sink }
968 }
969
970 pub(crate) fn from_state(sink: cranpose_core::MutableState<Size>) -> Self {
971 Self {
972 sink: Rc::new(StateSizeSink(sink)),
973 }
974 }
975}
976
977impl std::fmt::Debug for SizeReporterElement {
978 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
979 f.debug_struct("SizeReporterElement").finish()
980 }
981}
982
983impl PartialEq for SizeReporterElement {
984 fn eq(&self, other: &Self) -> bool {
985 std::ptr::addr_eq(Rc::as_ptr(&self.sink), Rc::as_ptr(&other.sink))
986 }
987}
988
989impl Hash for SizeReporterElement {
990 fn hash<H: Hasher>(&self, state: &mut H) {
991 (Rc::as_ptr(&self.sink) as *const () as usize).hash(state);
992 }
993}
994
995impl_sink_reporter_element!(SizeReporterElement, SizeReporterNode);
996
997pub(crate) struct DrawCommandNode {
998 commands: Vec<DrawCommand>,
999 node_id: Cell<Option<NodeId>>,
1000 state: NodeState,
1001}
1002
1003impl DrawCommandNode {
1004 pub(crate) fn new(commands: Vec<DrawCommand>) -> Self {
1005 Self {
1006 commands,
1007 node_id: Cell::new(None),
1008 state: NodeState::new(),
1009 }
1010 }
1011
1012 #[cfg(test)]
1013 pub(crate) fn commands(&self) -> &[DrawCommand] {
1014 &self.commands
1015 }
1016
1017 pub(crate) fn observed_commands(
1018 &self,
1019 modifier_index: usize,
1020 ) -> impl Iterator<Item = DrawCommand> + '_ {
1021 let node_id = self.node_id.get();
1022 self.commands
1023 .iter()
1024 .cloned()
1025 .enumerate()
1026 .map(move |(index, command)| {
1027 observe_draw_command(command, node_id, modifier_index, index)
1028 })
1029 }
1030}
1031
1032impl DelegatableNode for DrawCommandNode {
1033 fn node_state(&self) -> &NodeState {
1034 &self.state
1035 }
1036}
1037
1038impl ModifierNode for DrawCommandNode {
1039 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
1040 attach_draw_observer(&self.node_id, context);
1041 }
1042
1043 fn on_detach(&mut self) {
1044 detach_draw_observer(&self.node_id);
1045 }
1046
1047 fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
1048 Some(self)
1049 }
1050
1051 fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
1052 Some(self)
1053 }
1054}
1055
1056impl DrawModifierNode for DrawCommandNode {}
1057
1058fn observe_draw_command(
1059 command: DrawCommand,
1060 node_id: Option<NodeId>,
1061 modifier_index: usize,
1062 command_index: usize,
1063) -> DrawCommand {
1064 let Some(node_id) = node_id else {
1065 return command;
1066 };
1067 let observation =
1068 crate::render_state::DrawObservationScope::new(node_id, modifier_index, command_index);
1069 match command {
1070 DrawCommand::Behind(draw) => DrawCommand::Behind(Rc::new(move |scope| {
1071 crate::render_state::observe_draw_reads(observation, || draw(scope));
1072 })),
1073 DrawCommand::WithContent(draw) => DrawCommand::WithContent(Rc::new(move |scope| {
1074 crate::render_state::observe_draw_reads(observation, || draw(scope));
1075 })),
1076 DrawCommand::Overlay(draw) => DrawCommand::Overlay(Rc::new(move |scope| {
1077 crate::render_state::observe_draw_reads(observation, || draw(scope));
1078 })),
1079 background @ DrawCommand::Background(_) => background,
1081 }
1082}
1083
1084fn draw_command_closure_identity(cmd: &DrawCommand) -> Option<*const ()> {
1085 match cmd {
1086 DrawCommand::Behind(f) | DrawCommand::WithContent(f) | DrawCommand::Overlay(f) => {
1087 Some(Rc::as_ptr(f) as *const ())
1088 }
1089 DrawCommand::Background(_) => None,
1090 }
1091}
1092
1093#[derive(Clone)]
1094pub(crate) struct DrawCommandElement {
1095 commands: Vec<DrawCommand>,
1096}
1097
1098impl DrawCommandElement {
1099 pub(crate) fn new(command: DrawCommand) -> Self {
1100 Self {
1101 commands: vec![command],
1102 }
1103 }
1104
1105 pub(crate) fn from_commands(commands: Vec<DrawCommand>) -> Self {
1106 Self { commands }
1107 }
1108}
1109
1110impl std::fmt::Debug for DrawCommandElement {
1111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112 f.debug_struct("DrawCommandElement")
1113 .field("commands", &self.commands.len())
1114 .finish()
1115 }
1116}
1117
1118impl PartialEq for DrawCommandElement {
1119 fn eq(&self, other: &Self) -> bool {
1120 if self.commands.len() != other.commands.len() {
1121 return false;
1122 }
1123 self.commands
1124 .iter()
1125 .zip(other.commands.iter())
1126 .all(|(a, b)| a.same_as(b))
1127 }
1128}
1129
1130impl Eq for DrawCommandElement {}
1131
1132impl Hash for DrawCommandElement {
1133 fn hash<H: Hasher>(&self, state: &mut H) {
1134 "draw_commands".hash(state);
1135 self.commands.len().hash(state);
1136 for command in &self.commands {
1137 std::mem::discriminant(command).hash(state);
1138 draw_command_closure_identity(command).hash(state);
1139 }
1140 }
1141}
1142
1143impl ModifierNodeElement for DrawCommandElement {
1144 type Node = DrawCommandNode;
1145
1146 fn create(&self) -> Self::Node {
1147 DrawCommandNode::new(self.commands.clone())
1148 }
1149
1150 fn update(&self, node: &mut Self::Node) {
1151 node.commands.clone_from(&self.commands);
1152 }
1153
1154 fn capabilities(&self) -> NodeCapabilities {
1155 NodeCapabilities::DRAW
1156 }
1157}
1158
1159#[cfg(test)]
1160#[path = "tests/modifier_nodes_tests.rs"]
1161mod tests;