1use std::any::{Any, TypeId};
14use std::cell::Cell;
15use std::collections::HashSet;
16use std::fmt::{self, Debug};
17use std::hash::{Hash, Hasher};
18use std::rc::Rc;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicU64, Ordering};
21
22use waft_embedder::{
23 BlendMode, Canvas, Clip, EngineLayer, ImageFilter, Matrix4, Offset, Picture, RRect, Rect,
24 Scene, SceneBuilder, Size, slices,
25};
26use waft_embedder::{CompositionLayer, VideoFrameReader};
27use waft_foundation::{
28 App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
29 DiagnosticsProperty, EnumProperty, Handle, HandleId, IntProperty, IntoPropertyName, Ref,
30 bare_type_name, describe_identity,
31};
32use waft_gestures::remove_perspective_transform;
33use waft_painting::TransformProperty;
34use waft_scheduler::{FrameCallback, SchedulerBinding};
35
36#[derive(Debug)]
42pub struct AnnotationEntry<T> {
43 pub annotation: Rc<T>,
45 pub local_position: Offset,
47}
48
49impl<T> AnnotationEntry<T> {
50 pub fn new(annotation: Rc<T>, local_position: Offset) -> AnnotationEntry<T> {
52 AnnotationEntry {
53 annotation,
54 local_position,
55 }
56 }
57}
58
59#[derive(Debug)]
66pub struct AnnotationResult<T> {
67 entries: Vec<AnnotationEntry<T>>,
68}
69
70impl<T> AnnotationResult<T> {
71 pub fn new() -> AnnotationResult<T> {
73 AnnotationResult {
74 entries: Vec::new(),
75 }
76 }
77
78 pub fn add(&mut self, entry: AnnotationEntry<T>) {
83 self.entries.push(entry);
84 }
85
86 pub fn entries(&self) -> &[AnnotationEntry<T>] {
90 &self.entries
91 }
92
93 pub fn annotations(&self) -> impl Iterator<Item = &Rc<T>> {
98 self.entries.iter().map(|entry| &entry.annotation)
99 }
100}
101
102impl<T> Default for AnnotationResult<T> {
103 fn default() -> AnnotationResult<T> {
104 AnnotationResult::new()
105 }
106}
107
108#[derive(Debug)]
113pub struct AnnotationSearch {
114 searched: TypeId,
115 entries: Vec<(Rc<dyn Any>, Offset)>,
116}
117
118impl AnnotationSearch {
119 fn new<S: 'static>() -> AnnotationSearch {
120 AnnotationSearch {
121 searched: TypeId::of::<S>(),
122 entries: Vec::new(),
123 }
124 }
125
126 pub fn accepts(&self, annotation: &dyn Any) -> bool {
128 annotation.type_id() == self.searched
129 }
130
131 pub fn add(&mut self, annotation: Rc<dyn Any>, local_position: Offset) {
134 debug_assert!(self.accepts(&*annotation));
135 self.entries.push((annotation, local_position));
136 }
137
138 pub fn is_empty(&self) -> bool {
140 self.entries.is_empty()
141 }
142
143 fn into_result<S: 'static>(self) -> AnnotationResult<S> {
144 let mut result = AnnotationResult::new();
145 for (annotation, local_position) in self.entries {
146 let annotation = annotation
147 .downcast::<S>()
148 .expect("an accepted annotation is the searched type");
149 result.add(AnnotationEntry::new(annotation, local_position));
150 }
151 result
152 }
153}
154
155pub type CompositionCallback = Rc<dyn Fn(&mut App, AnyLayer)>;
157
158static NEXT_CALLBACK_ID: AtomicU64 = AtomicU64::new(0);
159
160pub struct LayerData {
163 callbacks: Vec<(u64, CompositionCallback)>,
164 composition_callback_count: i32,
165 debug_mutations_locked: bool,
166 parent_handle: LayerHandle<AnyLayer>,
173 ref_count: u32,
175 debug_disposed: bool,
176 parent: Option<AnyContainerLayer>,
177 owner: Option<HandleId>,
178 depth: i32,
179 next_sibling: Option<AnyLayer>,
180 previous_sibling: Option<AnyLayer>,
181 needs_add_to_scene: bool,
185 engine_layer: Option<EngineLayer>,
188}
189
190impl LayerData {
191 pub const fn new() -> LayerData {
193 LayerData {
194 callbacks: Vec::new(),
195 composition_callback_count: 0,
196 debug_mutations_locked: false,
197 parent_handle: LayerHandle::new(),
198 ref_count: 0,
199 debug_disposed: false,
200 parent: None,
201 owner: None,
202 depth: 0,
203 next_sibling: None,
204 previous_sibling: None,
205 needs_add_to_scene: true,
206 engine_layer: None,
207 }
208 }
209}
210
211impl Default for LayerData {
212 fn default() -> LayerData {
213 LayerData::new()
214 }
215}
216
217impl Debug for LayerData {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 f.debug_struct("Layer")
220 .field("owner", &self.owner)
221 .field("handles", &self.ref_count)
222 .finish_non_exhaustive()
223 }
224}
225
226#[macro_export]
231macro_rules! layer_accessors {
232 () => {
233 fn layer_data(
234 self: ::waft_foundation::Handle<Self>,
235 app: &::waft_foundation::App,
236 ) -> &$crate::LayerData {
237 &app.get(self).layer
238 }
239 fn layer_data_mut(
240 self: ::waft_foundation::Handle<Self>,
241 app: &mut ::waft_foundation::App,
242 ) -> &mut $crate::LayerData {
243 &mut app.get_mut(self).layer
244 }
245 };
246 (container) => {
247 $crate::layer_accessors!();
248 const AS_CONTAINER: Option<fn() -> &'static $crate::ContainerLayerVTable> =
249 Some(|| const { &$crate::ContainerLayerVTable::of::<Self>() });
250 };
251}
252
253pub trait Layer: Sized + 'static {
279 fn layer_data(self: Handle<Self>, app: &App) -> &LayerData;
281
282 fn layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut LayerData;
284
285 const AS_CONTAINER: Option<fn() -> &'static ContainerLayerVTable> = None;
288
289 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
296 let _ = (self, app);
297 true
298 }
299
300 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
302 let _ = (self, app);
303 None
304 }
305
306 fn always_needs_add_to_scene(self: Handle<Self>, app: &App) -> bool {
308 let _ = (self, app);
309 false
310 }
311
312 fn dispose(self: Handle<Self>, app: &mut App) {
331 LayerBase::dispose(self, app);
332 }
333
334 fn debug_fill_properties(
338 self: Handle<Self>,
339 _app: &App,
340 _properties: &mut DiagnosticPropertiesBuilder,
341 ) {
342 let _ = self;
343 }
344
345 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
353 LayerBase::attach(self, app, owner);
354 }
355
356 fn detach(self: Handle<Self>, app: &mut App) {
364 LayerBase::detach(self, app);
365 }
366
367 fn redepth_children(self: Handle<Self>, app: &mut App) {
372 let _ = (self, app);
375 }
376
377 fn find_annotations(
398 self: Handle<Self>,
399 app: &App,
400 result: &mut AnnotationSearch,
401 local_position: Offset,
402 only_first: bool,
403 ) -> bool {
404 let _ = (self, app, result, local_position, only_first);
405 false
406 }
407
408 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder);
410
411 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
413 LayerBase::fire_composition_callbacks(self, app, include_children);
414 }
415}
416
417pub trait LayerBase: Layer {
420 fn dispose(self: Handle<Self>, app: &mut App) {
422 let data = self.layer_data_mut(app);
423 debug_assert!(!data.debug_mutations_locked);
424 debug_assert!(
425 !data.debug_disposed,
426 "Layers must only be disposed once. This is typically handled by LayerHandle. \
427 Subclasses should not directly call dispose, except to call LayerBase::dispose in \
428 an overridden dispose method. Tests must only call dispose once."
429 );
430 debug_assert!(
431 data.ref_count == 0,
432 "Do not directly call dispose on a layer. Instead, use a LayerHandle."
433 );
434 data.debug_disposed = true;
435 app.release_tree_node(self);
437 }
438
439 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
441 let data = self.layer_data_mut(app);
442 debug_assert!(data.owner.is_none());
443 data.owner = Some(owner);
444 }
445
446 fn detach(self: Handle<Self>, app: &mut App) {
448 let data = self.layer_data_mut(app);
449 debug_assert!(data.owner.is_some());
450 data.owner = None;
451 let this = self.as_layer();
452 debug_assert!(
453 this.parent(app)
454 .is_none_or(|parent| this.attached(app) == parent.as_layer().attached(app))
455 );
456 }
457
458 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
460 let _ = include_children;
461 let this = self.as_layer();
462 let callbacks: Vec<CompositionCallback> = self
463 .layer_data(app)
464 .callbacks
465 .iter()
466 .map(|(_, callback)| Rc::clone(callback))
467 .collect();
468 for callback in callbacks {
469 this.run_composition_callback(app, &callback);
470 }
471 }
472}
473
474impl<T: Layer> LayerBase for T {}
475
476fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
478 Handle::from_id(id)
479}
480
481#[doc(hidden)]
487pub struct LayerVTable {
488 layer_data: fn(&App, HandleId) -> &LayerData,
489 layer_data_mut: fn(&mut App, HandleId) -> &mut LayerData,
490 supports_rasterization: fn(&App, HandleId) -> bool,
491 describe_clip_bounds: fn(&App, HandleId) -> Option<Rect>,
492 always_needs_add_to_scene: fn(&App, HandleId) -> bool,
493 dispose: fn(&mut App, HandleId),
494 attach: fn(&mut App, HandleId, HandleId),
495 detach: fn(&mut App, HandleId),
496 redepth_children: fn(&mut App, HandleId),
497 find_annotations: fn(&App, HandleId, &mut AnnotationSearch, Offset, bool) -> bool,
498 add_to_scene: fn(&mut App, HandleId, &mut SceneBuilder),
499 fire_composition_callbacks: fn(&mut App, HandleId, bool),
500 as_container: Option<fn() -> &'static ContainerLayerVTable>,
501 type_name: fn() -> &'static str,
503 debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
504}
505
506impl LayerVTable {
507 pub const fn of<T: Layer>() -> LayerVTable {
508 LayerVTable {
509 type_name: std::any::type_name::<T>,
510 debug_fill_properties: |app, id, properties| {
511 T::debug_fill_properties(resolve(id), app, properties)
512 },
513 layer_data: |app, id| T::layer_data(resolve(id), app),
514 layer_data_mut: |app, id| T::layer_data_mut(resolve(id), app),
515 supports_rasterization: |app, id| T::supports_rasterization(resolve(id), app),
516 describe_clip_bounds: |app, id| T::describe_clip_bounds(resolve(id), app),
517 always_needs_add_to_scene: |app, id| T::always_needs_add_to_scene(resolve(id), app),
518 dispose: |app, id| T::dispose(resolve(id), app),
519 attach: |app, id, owner| T::attach(resolve(id), app, owner),
520 detach: |app, id| T::detach(resolve(id), app),
521 redepth_children: |app, id| T::redepth_children(resolve(id), app),
522 find_annotations: |app, id, result, local_position, only_first| {
523 T::find_annotations(resolve(id), app, result, local_position, only_first)
524 },
525 add_to_scene: |app, id, builder| T::add_to_scene(resolve(id), app, builder),
526 fire_composition_callbacks: |app, id, include_children| {
527 T::fire_composition_callbacks(resolve(id), app, include_children)
528 },
529 as_container: T::AS_CONTAINER,
530 }
531 }
532}
533
534#[derive(Clone, Copy)]
539pub struct AnyLayer {
540 id: HandleId,
541 vtable: &'static LayerVTable,
542}
543
544impl PartialEq for AnyLayer {
545 fn eq(&self, other: &AnyLayer) -> bool {
546 self.id == other.id
547 }
548}
549
550impl Eq for AnyLayer {}
551
552impl Hash for AnyLayer {
553 fn hash<H: Hasher>(&self, state: &mut H) {
554 self.id.hash(state);
555 }
556}
557
558impl From<AnyLayer> for HandleId {
559 fn from(layer: AnyLayer) -> HandleId {
560 layer.id
561 }
562}
563
564impl Debug for AnyLayer {
565 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566 write!(f, "AnyLayer({:?})", self.id)
567 }
568}
569
570impl AnyLayer {
571 pub fn id(self) -> HandleId {
572 self.id
573 }
574
575 pub fn to_string_short(self, _app: &App) -> String {
577 describe_identity(
578 bare_type_name((self.vtable.type_name)()),
579 self.id.identity_hash(),
580 )
581 }
582
583 pub fn to_diagnostics_node(
587 self,
588 app: &App,
589 name: impl IntoPropertyName,
590 ) -> DiagnosticableTreeNode {
591 let mut properties = DiagnosticPropertiesBuilder::new();
592 let data = self.data(app);
593 if let Some(engine_layer) = &data.engine_layer {
594 properties.add(DiagnosticsProperty::<String>::new(
595 "engine layer",
596 describe_engine_layer(engine_layer),
597 ));
598 }
599 properties.add(DiagnosticsProperty::<u32>::new("handles", data.ref_count));
600 (self.vtable.debug_fill_properties)(app, self.id, &mut properties);
601 let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
602 if let Some(container) = self.as_container_layer() {
603 let mut child = container.first_child(app);
604 while let Some(current) = child {
605 let name = format!("child {}", children.len() + 1);
606 children.push(Rc::new(current.to_diagnostics_node(app, name)));
607 child = current.next_sibling(app);
608 }
609 }
610 DiagnosticableTreeNode::from_parts(name, self.to_string_short(app), properties, children)
611 }
612
613 pub fn to_string_deep(self, app: &App) -> String {
615 self.to_diagnostics_node(app, None).to_string_deep_with(
616 "",
617 Some(""),
618 None,
619 DiagnosticLevel::Debug,
620 65,
621 )
622 }
623
624 fn data(self, app: &App) -> &LayerData {
625 (self.vtable.layer_data)(app, self.id)
626 }
627
628 fn data_mut(self, app: &mut App) -> &mut LayerData {
629 (self.vtable.layer_data_mut)(app, self.id)
630 }
631
632 pub fn as_container_layer(self) -> Option<AnyContainerLayer> {
634 self.vtable
635 .as_container
636 .map(|vtable| AnyContainerLayer::from_vtable(self.id, vtable()))
637 }
638
639 pub fn subtree_has_composition_callbacks(self, app: &App) -> bool {
645 self.data(app).composition_callback_count > 0
646 }
647
648 fn update_subtree_composition_observer_count(self, app: &mut App, delta: i32) {
649 debug_assert!(delta != 0);
650 let data = self.data_mut(app);
651 data.composition_callback_count += delta;
652 debug_assert!(data.composition_callback_count >= 0);
653 if let Some(parent) = data.parent {
654 parent
655 .as_layer()
656 .update_subtree_composition_observer_count(app, delta);
657 }
658 }
659
660 pub(crate) fn fire_composition_callbacks(self, app: &mut App, include_children: bool) {
662 (self.vtable.fire_composition_callbacks)(app, self.id, include_children);
663 }
664
665 fn run_composition_callback(self, app: &mut App, callback: &CompositionCallback) {
667 if cfg!(debug_assertions) {
668 self.data_mut(app).debug_mutations_locked = true;
669 }
670 callback(app, self);
671 if cfg!(debug_assertions) {
672 self.data_mut(app).debug_mutations_locked = false;
673 }
674 }
675
676 pub fn supports_rasterization(self, app: &App) -> bool {
678 (self.vtable.supports_rasterization)(app, self.id)
679 }
680
681 pub fn describe_clip_bounds(self, app: &App) -> Option<Rect> {
683 (self.vtable.describe_clip_bounds)(app, self.id)
684 }
685
686 pub fn add_composition_callback(
704 self,
705 app: &mut App,
706 callback: CompositionCallback,
707 ) -> Box<dyn FnOnce(&mut App)> {
708 self.update_subtree_composition_observer_count(app, 1);
709 let callback_id = NEXT_CALLBACK_ID.fetch_add(1, Ordering::Relaxed) + 1;
710 self.data_mut(app).callbacks.push((callback_id, callback));
711 let layer = self.id.keep(app);
713 Box::new(move |app: &mut App| {
714 let index = self
715 .data(app)
716 .callbacks
717 .iter()
718 .position(|(id, _)| *id == callback_id);
719 debug_assert!(self.debug_disposed(app) || index.is_some());
720 if let Some(index) = index {
721 self.data_mut(app).callbacks.remove(index);
722 }
723 self.update_subtree_composition_observer_count(app, -1);
724 drop(layer);
725 })
726 }
727
728 pub fn debug_disposed(self, app: &App) -> bool {
733 !app.contains(self.id) || self.data(app).debug_disposed
734 }
735
736 fn unref(self, app: &mut App) {
738 let data = self.data_mut(app);
739 debug_assert!(!data.debug_mutations_locked);
740 debug_assert!(data.ref_count > 0);
741 data.ref_count -= 1;
742 if data.ref_count == 0 {
743 self.dispose(app);
744 }
745 }
746
747 pub fn debug_handle_count(self, app: &App) -> u32 {
749 self.data(app).ref_count
750 }
751
752 pub fn dispose(self, app: &mut App) {
754 (self.vtable.dispose)(app, self.id);
755 }
756
757 pub fn parent(self, app: &App) -> Option<AnyContainerLayer> {
764 self.data(app).parent
765 }
766
767 pub fn owner(self, app: &App) -> Option<HandleId> {
773 self.data(app).owner
774 }
775
776 pub fn attached(self, app: &App) -> bool {
782 self.data(app).owner.is_some()
783 }
784
785 pub fn attach(self, app: &mut App, owner: HandleId) {
787 (self.vtable.attach)(app, self.id, owner);
788 }
789
790 pub fn detach(self, app: &mut App) {
792 (self.vtable.detach)(app, self.id);
793 }
794
795 pub fn depth(self, app: &App) -> i32 {
802 self.data(app).depth
803 }
804
805 pub fn redepth_children(self, app: &mut App) {
807 (self.vtable.redepth_children)(app, self.id);
808 }
809
810 pub fn next_sibling(self, app: &App) -> Option<AnyLayer> {
812 self.data(app).next_sibling
813 }
814
815 pub fn previous_sibling(self, app: &App) -> Option<AnyLayer> {
817 self.data(app).previous_sibling
818 }
819
820 pub fn remove(self, app: &mut App) {
824 debug_assert!(!self.data(app).debug_mutations_locked);
825 if let Some(parent) = self.parent(app) {
826 parent.remove_child(app, self);
827 }
828 }
829
830 pub fn find_annotations(
832 self,
833 app: &App,
834 result: &mut AnnotationSearch,
835 local_position: Offset,
836 only_first: bool,
837 ) -> bool {
838 (self.vtable.find_annotations)(app, self.id, result, local_position, only_first)
839 }
840
841 pub fn find<S: 'static>(self, app: &App, local_position: Offset) -> Option<Rc<S>> {
858 let mut result = AnnotationSearch::new::<S>();
859 self.find_annotations(app, &mut result, local_position, true);
860 result
861 .into_result::<S>()
862 .entries
863 .into_iter()
864 .next()
865 .map(|entry| entry.annotation)
866 }
867
868 pub fn find_all_annotations<S: 'static>(
885 self,
886 app: &App,
887 local_position: Offset,
888 ) -> AnnotationResult<S> {
889 let mut result = AnnotationSearch::new::<S>();
890 self.find_annotations(app, &mut result, local_position, false);
891 result.into_result::<S>()
892 }
893
894 pub fn add_to_scene(self, app: &mut App, builder: &mut SceneBuilder) {
896 (self.vtable.add_to_scene)(app, self.id, builder);
897 }
898
899 pub fn needs_add_to_scene(self, app: &App) -> bool {
904 self.data(app).needs_add_to_scene
905 }
906
907 pub fn mark_needs_add_to_scene(self, app: &mut App) {
909 debug_assert!(!self.data(app).debug_mutations_locked);
910 debug_assert!(
911 !self.always_needs_add_to_scene(app),
912 "a layer with always_needs_add_to_scene set called mark_needs_add_to_scene"
913 );
914 debug_assert!(!self.data(app).debug_disposed);
915 if self.data(app).needs_add_to_scene {
917 return;
918 }
919 self.data_mut(app).needs_add_to_scene = true;
920 }
921
922 pub fn always_needs_add_to_scene(self, app: &App) -> bool {
924 (self.vtable.always_needs_add_to_scene)(app, self.id)
925 }
926
927 pub fn engine_layer(self, app: &App) -> Option<EngineLayer> {
931 self.data(app).engine_layer.clone()
932 }
933
934 pub fn set_engine_layer(self, app: &mut App, value: Option<EngineLayer>) {
938 debug_assert!(!self.data(app).debug_mutations_locked);
939 debug_assert!(!self.data(app).debug_disposed);
940 self.data_mut(app).engine_layer = value;
941 if !self.always_needs_add_to_scene(app) {
942 if let Some(parent) = self.parent(app)
948 && !parent.as_layer().always_needs_add_to_scene(app)
949 {
950 parent.as_layer().mark_needs_add_to_scene(app);
951 }
952 }
953 }
954
955 pub fn update_subtree_needs_add_to_scene(self, app: &mut App) {
967 debug_assert!(!self.data(app).debug_mutations_locked);
968 let always = self.always_needs_add_to_scene(app);
969 let data = self.data_mut(app);
970 data.needs_add_to_scene = data.needs_add_to_scene || always;
971 let Some(container) = self.as_container_layer() else {
972 return;
973 };
974 let mut child = container.first_child(app);
975 while let Some(layer) = child {
976 layer.update_subtree_needs_add_to_scene(app);
977 if layer.data(app).needs_add_to_scene {
978 self.data_mut(app).needs_add_to_scene = true;
979 }
980 child = layer.next_sibling(app);
981 }
982 }
983
984 pub fn add_to_scene_with_retained_rendering(self, app: &mut App, builder: &mut SceneBuilder) {
987 debug_assert!(!self.data(app).debug_mutations_locked);
988 if !self.data(app).needs_add_to_scene
992 && let Some(engine_layer) = self.engine_layer(app)
993 {
994 builder.add_retained(&engine_layer);
995 return;
996 }
997 self.add_to_scene(app, builder);
998 self.data_mut(app).needs_add_to_scene = false;
1001 }
1002}
1003
1004pub trait ErasedLayer: Copy + PartialEq + Debug + 'static {
1007 fn as_layer(self) -> AnyLayer;
1009}
1010
1011impl ErasedLayer for AnyLayer {
1012 fn as_layer(self) -> AnyLayer {
1013 self
1014 }
1015}
1016
1017impl<T: Layer> ErasedLayer for Handle<T> {
1020 fn as_layer(self) -> AnyLayer {
1021 AnyLayer {
1022 id: self.id(),
1023 vtable: const { &LayerVTable::of::<T>() },
1024 }
1025 }
1026}
1027
1028pub struct LayerHandle<T> {
1054 layer: Option<T>,
1055}
1056
1057impl<T> LayerHandle<T> {
1058 pub const fn new() -> LayerHandle<T> {
1061 LayerHandle { layer: None }
1062 }
1063}
1064
1065impl<T: ErasedLayer> LayerHandle<T> {
1066 pub fn layer(&self) -> Option<T> {
1068 self.layer
1069 }
1070
1071 pub fn set_layer(
1080 app: &mut App,
1081 at: impl Fn(&mut App) -> &mut LayerHandle<T>,
1082 layer: Option<T>,
1083 ) {
1084 debug_assert!(
1085 layer.is_none_or(|layer| !layer.as_layer().debug_disposed(app)),
1086 "Attempted to create a handle to an already disposed layer: {layer:?}."
1087 );
1088 let old = at(app).layer;
1089 if layer == old {
1090 return;
1091 }
1092 at(app).layer = layer;
1095 if let Some(layer) = layer {
1096 layer.as_layer().data_mut(app).ref_count += 1;
1097 }
1098 if let Some(old) = old {
1099 old.as_layer().unref(app);
1100 }
1101 }
1102}
1103
1104impl<T> Default for LayerHandle<T> {
1105 fn default() -> LayerHandle<T> {
1106 LayerHandle::new()
1107 }
1108}
1109
1110impl<T: Debug> Debug for LayerHandle<T> {
1111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1112 match &self.layer {
1113 Some(layer) => write!(f, "LayerHandle({layer:?})"),
1114 None => write!(f, "LayerHandle(DISPOSED)"),
1115 }
1116 }
1117}
1118
1119pub struct PictureLayer {
1125 layer: LayerData,
1126 pub canvas_bounds: Rect,
1130 picture: Option<Arc<Picture>>,
1131 is_complex_hint: bool,
1132 will_change_hint: bool,
1133}
1134
1135impl PictureLayer {
1136 pub fn new(app: &mut App, canvas_bounds: Rect) -> Handle<PictureLayer> {
1138 app.create(PictureLayer {
1139 layer: LayerData::new(),
1140 canvas_bounds,
1141 picture: None,
1142 is_complex_hint: false,
1143 will_change_hint: false,
1144 })
1145 .into_tree_node(app)
1146 }
1147
1148 pub fn picture(self: Handle<Self>, app: &App) -> Option<&Arc<Picture>> {
1152 app.get(self).picture.as_ref()
1153 }
1154
1155 pub fn set_picture(self: Handle<Self>, app: &mut App, picture: Option<Arc<Picture>>) {
1157 debug_assert!(!app.get(self).layer.debug_disposed);
1158 self.as_layer().mark_needs_add_to_scene(app);
1159 app.get_mut(self).picture = picture;
1160 }
1161
1162 pub fn is_complex_hint(self: Handle<Self>, app: &App) -> bool {
1167 app.get(self).is_complex_hint
1168 }
1169
1170 pub fn set_is_complex_hint(self: Handle<Self>, app: &mut App, value: bool) {
1172 if value != app.get(self).is_complex_hint {
1173 app.get_mut(self).is_complex_hint = value;
1174 self.as_layer().mark_needs_add_to_scene(app);
1175 }
1176 }
1177
1178 pub fn will_change_hint(self: Handle<Self>, app: &App) -> bool {
1184 app.get(self).will_change_hint
1185 }
1186
1187 pub fn set_will_change_hint(self: Handle<Self>, app: &mut App, value: bool) {
1189 if value != app.get(self).will_change_hint {
1190 app.get_mut(self).will_change_hint = value;
1191 self.as_layer().mark_needs_add_to_scene(app);
1192 }
1193 }
1194}
1195
1196impl Layer for PictureLayer {
1197 crate::layer_accessors!();
1198
1199 fn dispose(self: Handle<Self>, app: &mut App) {
1200 self.set_picture(app, None); LayerBase::dispose(self, app);
1202 }
1203
1204 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1205 let this = app.get(self);
1206 let picture = this
1207 .picture
1208 .as_ref()
1209 .expect("a PictureLayer has a picture when it is added to the scene");
1210 builder.add_picture(
1211 Offset::ZERO,
1212 picture,
1213 this.is_complex_hint,
1214 this.will_change_hint,
1215 );
1216 }
1217
1218 fn find_annotations(
1219 self: Handle<Self>,
1220 _app: &App,
1221 _result: &mut AnnotationSearch,
1222 _local_position: Offset,
1223 _only_first: bool,
1224 ) -> bool {
1225 false
1226 }
1227
1228 fn debug_fill_properties(
1229 self: Handle<Self>,
1230 app: &App,
1231 properties: &mut DiagnosticPropertiesBuilder,
1232 ) {
1233 let this = app.get(self);
1234 properties.add(DiagnosticsProperty::new("paint bounds", this.canvas_bounds));
1235 let picture = match &this.picture {
1236 Some(picture) => {
1237 describe_identity("Picture", Arc::as_ptr(picture) as usize as u64 >> 4)
1238 }
1239 None => describe_identity("Null", 0),
1240 };
1241 properties.add(DiagnosticsProperty::<String>::new("picture", Some(picture)));
1242 properties.add(DiagnosticsProperty::<String>::new(
1243 "raster cache hints",
1244 Some(format!(
1245 "isComplex = {}, willChange = {}",
1246 this.is_complex_hint, this.will_change_hint
1247 )),
1248 ));
1249 }
1250}
1251
1252pub struct EmbeddedLayer {
1257 layer: LayerData,
1258 composition_layer: Arc<dyn CompositionLayer>,
1259 rect: Rect,
1261}
1262
1263impl EmbeddedLayer {
1264 pub fn new(
1266 app: &mut App,
1267 composition_layer: Arc<dyn CompositionLayer>,
1268 rect: Rect,
1269 ) -> Handle<EmbeddedLayer> {
1270 app.create(EmbeddedLayer {
1271 layer: LayerData::new(),
1272 composition_layer,
1273 rect,
1274 })
1275 .into_tree_node(app)
1276 }
1277
1278 pub fn composition_layer(self: Handle<Self>, app: &App) -> &Arc<dyn CompositionLayer> {
1279 &app.get(self).composition_layer
1280 }
1281
1282 pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1283 app.get(self).rect
1284 }
1285}
1286
1287impl Layer for EmbeddedLayer {
1288 crate::layer_accessors!();
1289
1290 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1291 let this = app.get(self);
1292 builder.add_embedded_layer(Arc::clone(&this.composition_layer), this.rect);
1293 }
1294
1295 fn find_annotations(
1296 self: Handle<Self>,
1297 _app: &App,
1298 _result: &mut AnnotationSearch,
1299 _local_position: Offset,
1300 _only_first: bool,
1301 ) -> bool {
1302 false
1303 }
1304}
1305
1306pub struct VideoLayer {
1312 layer: LayerData,
1313 reader: Arc<dyn VideoFrameReader>,
1314 rect: Rect,
1316}
1317
1318impl VideoLayer {
1319 pub fn new(app: &mut App, reader: Arc<dyn VideoFrameReader>, rect: Rect) -> Handle<VideoLayer> {
1321 app.create(VideoLayer {
1322 layer: LayerData::new(),
1323 reader,
1324 rect,
1325 })
1326 .into_tree_node(app)
1327 }
1328
1329 pub fn reader(self: Handle<Self>, app: &App) -> &Arc<dyn VideoFrameReader> {
1330 &app.get(self).reader
1331 }
1332
1333 pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1334 app.get(self).rect
1335 }
1336}
1337
1338impl Layer for VideoLayer {
1339 crate::layer_accessors!();
1340
1341 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1342 let this = app.get(self);
1343 builder.add_video(Arc::clone(&this.reader), this.rect);
1344 }
1345
1346 fn find_annotations(
1347 self: Handle<Self>,
1348 _app: &App,
1349 _result: &mut AnnotationSearch,
1350 _local_position: Offset,
1351 _only_first: bool,
1352 ) -> bool {
1353 false
1354 }
1355}
1356
1357#[derive(Debug, Default)]
1360pub struct ContainerLayerData {
1361 first_child: Option<AnyLayer>,
1362 last_child: Option<AnyLayer>,
1363}
1364
1365impl ContainerLayerData {
1366 pub const fn new() -> ContainerLayerData {
1368 ContainerLayerData {
1369 first_child: None,
1370 last_child: None,
1371 }
1372 }
1373}
1374
1375#[macro_export]
1380macro_rules! container_layer_accessors {
1381 () => {
1382 fn container_layer_data(
1383 self: ::waft_foundation::Handle<Self>,
1384 app: &::waft_foundation::App,
1385 ) -> &$crate::ContainerLayerData {
1386 &app.get(self).container_layer
1387 }
1388 fn container_layer_data_mut(
1389 self: ::waft_foundation::Handle<Self>,
1390 app: &mut ::waft_foundation::App,
1391 ) -> &mut $crate::ContainerLayerData {
1392 &mut app.get_mut(self).container_layer
1393 }
1394 };
1395 (offset) => {
1396 $crate::container_layer_accessors!();
1397 const AS_OFFSET: Option<fn() -> &'static $crate::OffsetLayerVTable> =
1398 Some(|| const { &$crate::OffsetLayerVTable::of::<Self>() });
1399 };
1400}
1401
1402pub trait ContainerLayer: Layer {
1412 fn container_layer_data(self: Handle<Self>, app: &App) -> &ContainerLayerData;
1414
1415 fn container_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut ContainerLayerData;
1417
1418 const AS_OFFSET: Option<fn() -> &'static OffsetLayerVTable> = None;
1421
1422 fn as_container_layer(self: Handle<Self>) -> AnyContainerLayer {
1424 AnyContainerLayer {
1425 id: self.id(),
1426 vtable: const { &ContainerLayerVTable::of::<Self>() },
1427 }
1428 }
1429
1430 fn apply_transform(
1452 self: Handle<Self>,
1453 app: &App,
1454 child: Option<AnyLayer>,
1455 transform: &mut Matrix4,
1456 ) {
1457 let _ = (self, app, transform);
1458 debug_assert!(child.is_some());
1459 }
1460
1461 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
1463 LayerBase::fire_composition_callbacks(self, app, include_children);
1464 if !include_children {
1465 return;
1466 }
1467 let mut child = self.as_container_layer().first_child(app);
1468 while let Some(layer) = child {
1469 layer.fire_composition_callbacks(app, include_children);
1470 child = layer.next_sibling(app);
1471 }
1472 }
1473
1474 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
1476 let mut child = self.as_container_layer().last_child(app);
1477 while let Some(layer) = child {
1478 if !layer.supports_rasterization(app) {
1479 return false;
1480 }
1481 child = layer.previous_sibling(app);
1482 }
1483 true
1484 }
1485
1486 fn dispose(self: Handle<Self>, app: &mut App) {
1488 self.as_container_layer().remove_all_children(app);
1489 self.layer_data_mut(app).callbacks.clear();
1490 LayerBase::dispose(self, app);
1491 }
1492
1493 fn find_annotations(
1495 self: Handle<Self>,
1496 app: &App,
1497 result: &mut AnnotationSearch,
1498 local_position: Offset,
1499 only_first: bool,
1500 ) -> bool {
1501 let mut child = self.as_container_layer().last_child(app);
1502 while let Some(layer) = child {
1503 let is_absorbed = layer.find_annotations(app, result, local_position, only_first);
1504 if is_absorbed {
1505 return true;
1506 }
1507 if only_first && !result.is_empty() {
1508 return is_absorbed;
1509 }
1510 child = layer.previous_sibling(app);
1511 }
1512 false
1513 }
1514
1515 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
1517 debug_assert!(!self.layer_data(app).debug_mutations_locked);
1518 LayerBase::attach(self, app, owner);
1519 let mut child = self.as_container_layer().first_child(app);
1520 while let Some(layer) = child {
1521 layer.attach(app, owner);
1522 child = layer.next_sibling(app);
1523 }
1524 }
1525
1526 fn detach(self: Handle<Self>, app: &mut App) {
1528 debug_assert!(!self.layer_data(app).debug_mutations_locked);
1529 LayerBase::detach(self, app);
1530 let mut child = self.as_container_layer().first_child(app);
1531 while let Some(layer) = child {
1532 layer.detach(app);
1533 child = layer.next_sibling(app);
1534 }
1535 self.as_layer().fire_composition_callbacks(app, false);
1542 }
1543
1544 fn redepth_children(self: Handle<Self>, app: &mut App) {
1546 let this = self.as_container_layer();
1547 let mut child = this.first_child(app);
1548 while let Some(layer) = child {
1549 this.redepth_child(app, layer);
1550 child = layer.next_sibling(app);
1551 }
1552 }
1553
1554 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1556 self.as_container_layer()
1557 .add_children_to_scene(app, builder);
1558 }
1559}
1560
1561#[doc(hidden)]
1565pub struct ContainerLayerVTable {
1566 layer: LayerVTable,
1567 container_data: fn(&App, HandleId) -> &ContainerLayerData,
1568 container_data_mut: fn(&mut App, HandleId) -> &mut ContainerLayerData,
1569 apply_transform: fn(&App, HandleId, Option<AnyLayer>, &mut Matrix4),
1570 as_offset: Option<fn() -> &'static OffsetLayerVTable>,
1571}
1572
1573impl ContainerLayerVTable {
1574 pub const fn of<T: ContainerLayer>() -> ContainerLayerVTable {
1575 ContainerLayerVTable {
1576 layer: LayerVTable::of::<T>(),
1577 container_data: |app, id| T::container_layer_data(resolve(id), app),
1578 container_data_mut: |app, id| T::container_layer_data_mut(resolve(id), app),
1579 apply_transform: |app, id, child, transform| {
1580 T::apply_transform(resolve(id), app, child, transform)
1581 },
1582 as_offset: T::AS_OFFSET,
1583 }
1584 }
1585}
1586
1587#[derive(Clone, Copy)]
1589pub struct AnyContainerLayer {
1590 id: HandleId,
1591 vtable: &'static ContainerLayerVTable,
1592}
1593
1594impl PartialEq for AnyContainerLayer {
1595 fn eq(&self, other: &AnyContainerLayer) -> bool {
1596 self.id == other.id
1597 }
1598}
1599
1600impl Eq for AnyContainerLayer {}
1601
1602impl Hash for AnyContainerLayer {
1603 fn hash<H: Hasher>(&self, state: &mut H) {
1604 self.id.hash(state);
1605 }
1606}
1607
1608impl From<AnyContainerLayer> for HandleId {
1609 fn from(layer: AnyContainerLayer) -> HandleId {
1610 layer.id
1611 }
1612}
1613
1614impl Debug for AnyContainerLayer {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 write!(f, "AnyContainerLayer({:?})", self.id)
1617 }
1618}
1619
1620impl ErasedLayer for AnyContainerLayer {
1621 fn as_layer(self) -> AnyLayer {
1622 AnyLayer {
1623 id: self.id,
1624 vtable: &self.vtable.layer,
1625 }
1626 }
1627}
1628
1629impl AnyContainerLayer {
1630 fn from_vtable(id: HandleId, vtable: &'static ContainerLayerVTable) -> AnyContainerLayer {
1631 AnyContainerLayer { id, vtable }
1632 }
1633
1634 pub fn id(self) -> HandleId {
1635 self.id
1636 }
1637
1638 pub fn as_offset_layer(self) -> Option<AnyOffsetLayer> {
1640 self.vtable
1641 .as_offset
1642 .map(|vtable| AnyOffsetLayer::from_vtable(self.id, vtable()))
1643 }
1644
1645 fn data(self, app: &App) -> &ContainerLayerData {
1646 (self.vtable.container_data)(app, self.id)
1647 }
1648
1649 fn data_mut(self, app: &mut App) -> &mut ContainerLayerData {
1650 (self.vtable.container_data_mut)(app, self.id)
1651 }
1652
1653 pub fn first_child(self, app: &App) -> Option<AnyLayer> {
1655 self.data(app).first_child
1656 }
1657
1658 pub fn last_child(self, app: &App) -> Option<AnyLayer> {
1660 self.data(app).last_child
1661 }
1662
1663 pub fn has_children(self, app: &App) -> bool {
1665 self.data(app).first_child.is_some()
1666 }
1667
1668 pub fn build_scene(self, app: &mut App, mut builder: SceneBuilder) -> Scene {
1674 let this = self.as_layer();
1675 this.update_subtree_needs_add_to_scene(app);
1676 this.add_to_scene(app, &mut builder);
1677 if this.subtree_has_composition_callbacks(app) {
1678 this.fire_composition_callbacks(app, true);
1679 }
1680 this.data_mut(app).needs_add_to_scene = false;
1683 builder.build()
1684 }
1685
1686 fn debug_ultimate_previous_sibling_of(
1687 self,
1688 app: &App,
1689 mut child: AnyLayer,
1690 equals: Option<AnyLayer>,
1691 ) -> bool {
1692 let attached = self.as_layer().attached(app);
1693 debug_assert!(child.attached(app) == attached);
1694 while let Some(previous) = child.previous_sibling(app) {
1695 debug_assert!(previous != child);
1696 child = previous;
1697 debug_assert!(child.attached(app) == attached);
1698 }
1699 Some(child) == equals
1700 }
1701
1702 fn debug_ultimate_next_sibling_of(
1703 self,
1704 app: &App,
1705 mut child: AnyLayer,
1706 equals: Option<AnyLayer>,
1707 ) -> bool {
1708 let attached = self.as_layer().attached(app);
1709 debug_assert!(child.attached(app) == attached);
1710 while let Some(next) = child.next_sibling(app) {
1711 debug_assert!(next != child);
1712 child = next;
1713 debug_assert!(child.attached(app) == attached);
1714 }
1715 Some(child) == equals
1716 }
1717
1718 pub fn append(self, app: &mut App, child: AnyLayer) {
1720 let this = self.as_layer();
1721 debug_assert!(!this.data(app).debug_mutations_locked);
1722 debug_assert!(child != this);
1723 debug_assert!(Some(child) != self.first_child(app));
1724 debug_assert!(Some(child) != self.last_child(app));
1725 debug_assert!(child.parent(app).is_none());
1726 debug_assert!(!child.attached(app));
1727 debug_assert!(child.next_sibling(app).is_none());
1728 debug_assert!(child.previous_sibling(app).is_none());
1729 debug_assert!(child.data(app).parent_handle.layer().is_none());
1730 debug_assert!(self.debug_root(app) != child); self.adopt_child(app, child);
1732 let last_child = self.last_child(app);
1733 child.data_mut(app).previous_sibling = last_child;
1734 if let Some(last_child) = last_child {
1735 last_child.data_mut(app).next_sibling = Some(child);
1736 }
1737 let data = self.data_mut(app);
1738 data.last_child = Some(child);
1739 data.first_child.get_or_insert(child);
1740 LayerHandle::set_layer(
1741 app,
1742 |app| &mut child.data_mut(app).parent_handle,
1743 Some(child),
1744 );
1745 debug_assert!(child.attached(app) == this.attached(app));
1746 }
1747
1748 fn debug_root(self, app: &App) -> AnyLayer {
1751 let mut node = self.as_layer();
1752 while let Some(parent) = node.parent(app) {
1753 node = parent.as_layer();
1754 }
1755 node
1756 }
1757
1758 fn adopt_child(self, app: &mut App, child: AnyLayer) {
1759 let this = self.as_layer();
1760 debug_assert!(!this.data(app).debug_mutations_locked);
1761 if !this.always_needs_add_to_scene(app) {
1762 this.mark_needs_add_to_scene(app);
1763 }
1764 let callback_count = child.data(app).composition_callback_count;
1765 if callback_count != 0 {
1766 this.update_subtree_composition_observer_count(app, callback_count);
1767 }
1768 debug_assert!(child.data(app).parent.is_none());
1769 debug_assert!(self.debug_root(app) != child); child.data_mut(app).parent = Some(self);
1771 if let Some(owner) = this.owner(app) {
1772 child.attach(app, owner);
1773 }
1774 self.redepth_child(app, child);
1775 }
1776
1777 pub fn redepth_child(self, app: &mut App, child: AnyLayer) {
1781 let this = self.as_layer();
1782 debug_assert!(child.owner(app) == this.owner(app));
1783 let depth = this.depth(app);
1784 if child.depth(app) <= depth {
1785 child.data_mut(app).depth = depth + 1;
1786 child.redepth_children(app);
1787 }
1788 }
1789
1790 pub(crate) fn remove_child(self, app: &mut App, child: AnyLayer) {
1792 let this = self.as_layer();
1793 debug_assert!(child.parent(app) == Some(self));
1794 debug_assert!(child.attached(app) == this.attached(app));
1795 debug_assert!(self.debug_ultimate_previous_sibling_of(app, child, self.first_child(app)));
1796 debug_assert!(self.debug_ultimate_next_sibling_of(app, child, self.last_child(app)));
1797 debug_assert!(child.data(app).parent_handle.layer().is_some());
1798 let previous_sibling = child.previous_sibling(app);
1799 let next_sibling = child.next_sibling(app);
1800 match previous_sibling {
1801 None => {
1802 debug_assert!(self.first_child(app) == Some(child));
1803 self.data_mut(app).first_child = next_sibling;
1804 }
1805 Some(previous) => previous.data_mut(app).next_sibling = next_sibling,
1806 }
1807 match next_sibling {
1808 None => {
1809 debug_assert!(self.last_child(app) == Some(child));
1810 self.data_mut(app).last_child = previous_sibling;
1811 }
1812 Some(next) => next.data_mut(app).previous_sibling = previous_sibling,
1813 }
1814 self.debug_check_child_list(app);
1815 let data = child.data_mut(app);
1816 data.previous_sibling = None;
1817 data.next_sibling = None;
1818 self.drop_child(app, child);
1819 LayerHandle::set_layer(app, |app| &mut child.data_mut(app).parent_handle, None);
1820 debug_assert!(child.debug_disposed(app) || !child.attached(app));
1822 }
1823
1824 fn debug_check_child_list(self, app: &App) {
1826 let attached = self.as_layer().attached(app);
1827 let first_child = self.first_child(app);
1828 let last_child = self.last_child(app);
1829 debug_assert!(first_child.is_none() == last_child.is_none());
1830 debug_assert!(first_child.is_none_or(|first| first.attached(app) == attached));
1831 debug_assert!(last_child.is_none_or(|last| last.attached(app) == attached));
1832 debug_assert!(
1833 first_child
1834 .is_none_or(|first| self.debug_ultimate_next_sibling_of(app, first, last_child))
1835 );
1836 debug_assert!(
1837 last_child.is_none_or(|last| self.debug_ultimate_previous_sibling_of(
1838 app,
1839 last,
1840 first_child
1841 ))
1842 );
1843 }
1844
1845 fn drop_child(self, app: &mut App, child: AnyLayer) {
1846 let this = self.as_layer();
1847 debug_assert!(!this.data(app).debug_mutations_locked);
1848 if !this.always_needs_add_to_scene(app) {
1849 this.mark_needs_add_to_scene(app);
1850 }
1851 let callback_count = child.data(app).composition_callback_count;
1852 if callback_count != 0 {
1853 this.update_subtree_composition_observer_count(app, -callback_count);
1854 }
1855 debug_assert!(child.data(app).parent == Some(self));
1856 debug_assert!(child.attached(app) == this.attached(app));
1857 child.data_mut(app).parent = None;
1858 if this.attached(app) {
1859 child.detach(app);
1860 }
1861 }
1862
1863 pub fn remove_all_children(self, app: &mut App) {
1865 let this = self.as_layer();
1866 debug_assert!(!this.data(app).debug_mutations_locked);
1867 let mut child = self.first_child(app);
1868 while let Some(layer) = child {
1869 let next = layer.next_sibling(app);
1870 let data = layer.data_mut(app);
1871 data.previous_sibling = None;
1872 data.next_sibling = None;
1873 debug_assert!(layer.attached(app) == this.attached(app));
1874 self.drop_child(app, layer);
1875 LayerHandle::set_layer(app, |app| &mut layer.data_mut(app).parent_handle, None);
1876 child = next;
1877 }
1878 let data = self.data_mut(app);
1879 data.first_child = None;
1880 data.last_child = None;
1881 }
1882
1883 pub fn add_children_to_scene(self, app: &mut App, builder: &mut SceneBuilder) {
1891 let mut child = self.first_child(app);
1892 while let Some(layer) = child {
1893 layer.add_to_scene_with_retained_rendering(app, builder);
1894 child = layer.next_sibling(app);
1895 }
1896 }
1897
1898 pub fn apply_transform(self, app: &App, child: Option<AnyLayer>, transform: &mut Matrix4) {
1900 (self.vtable.apply_transform)(app, self.id, child, transform);
1901 }
1902
1903 pub fn depth_first_iterate_children(self, app: &App) -> Vec<AnyLayer> {
1905 let mut children = Vec::new();
1906 let mut child = self.first_child(app);
1907 while let Some(layer) = child {
1908 children.push(layer);
1909 if let Some(container) = layer.as_container_layer() {
1910 children.extend(container.depth_first_iterate_children(app));
1911 }
1912 child = layer.next_sibling(app);
1913 }
1914 children
1915 }
1916}
1917
1918#[derive(Debug)]
1921pub struct OffsetLayerData {
1922 offset: Offset,
1923}
1924
1925impl OffsetLayerData {
1926 pub const fn new(offset: Offset) -> OffsetLayerData {
1928 OffsetLayerData { offset }
1929 }
1930}
1931
1932impl Default for OffsetLayerData {
1933 fn default() -> OffsetLayerData {
1935 OffsetLayerData::new(Offset::ZERO)
1936 }
1937}
1938
1939#[macro_export]
1941macro_rules! offset_layer_accessors {
1942 () => {
1943 fn offset_layer_data(
1944 self: ::waft_foundation::Handle<Self>,
1945 app: &::waft_foundation::App,
1946 ) -> &$crate::OffsetLayerData {
1947 &app.get(self).offset_layer
1948 }
1949 fn offset_layer_data_mut(
1950 self: ::waft_foundation::Handle<Self>,
1951 app: &mut ::waft_foundation::App,
1952 ) -> &mut $crate::OffsetLayerData {
1953 &mut app.get_mut(self).offset_layer
1954 }
1955 };
1956}
1957
1958pub trait OffsetLayerMixin: ContainerLayer {
1970 fn offset_layer_data(self: Handle<Self>, app: &App) -> &OffsetLayerData;
1972
1973 fn offset_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut OffsetLayerData;
1975
1976 fn as_offset_layer(self: Handle<Self>) -> AnyOffsetLayer {
1978 AnyOffsetLayer {
1979 id: self.id(),
1980 vtable: const { &OffsetLayerVTable::of::<Self>() },
1981 }
1982 }
1983
1984 fn offset(self: Handle<Self>, app: &App) -> Offset {
1986 self.offset_layer_data(app).offset
1987 }
1988
1989 fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
1991 self.offset_layer_data_mut(app).offset = value;
1992 }
1993
1994 fn find_annotations(
1996 self: Handle<Self>,
1997 app: &App,
1998 result: &mut AnnotationSearch,
1999 local_position: Offset,
2000 only_first: bool,
2001 ) -> bool {
2002 let offset = self.offset(app);
2003 ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
2004 }
2005
2006 fn apply_transform(
2008 self: Handle<Self>,
2009 app: &App,
2010 child: Option<AnyLayer>,
2011 transform: &mut Matrix4,
2012 ) {
2013 debug_assert!(child.is_some());
2014 let offset = self.offset(app);
2015 *transform = transform.then(&Matrix4::translation(
2016 offset.dx() as f32,
2017 offset.dy() as f32,
2018 ));
2019 }
2020
2021 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2023 let offset = self.offset(app);
2029 builder.push_offset(offset.dx(), offset.dy());
2030 self.as_container_layer()
2031 .add_children_to_scene(app, builder);
2032 let engine_layer = builder.pop();
2033 self.as_layer().set_engine_layer(app, Some(engine_layer));
2034 }
2035}
2036
2037#[doc(hidden)]
2041pub struct OffsetLayerVTable {
2042 container: ContainerLayerVTable,
2043 offset_data: fn(&App, HandleId) -> &OffsetLayerData,
2044 offset_data_mut: fn(&mut App, HandleId) -> &mut OffsetLayerData,
2045}
2046
2047impl OffsetLayerVTable {
2048 pub const fn of<T: OffsetLayerMixin>() -> OffsetLayerVTable {
2049 OffsetLayerVTable {
2050 container: ContainerLayerVTable::of::<T>(),
2051 offset_data: |app, id| T::offset_layer_data(resolve(id), app),
2052 offset_data_mut: |app, id| T::offset_layer_data_mut(resolve(id), app),
2053 }
2054 }
2055}
2056
2057#[derive(Clone, Copy)]
2060pub struct AnyOffsetLayer {
2061 id: HandleId,
2062 vtable: &'static OffsetLayerVTable,
2063}
2064
2065impl PartialEq for AnyOffsetLayer {
2066 fn eq(&self, other: &AnyOffsetLayer) -> bool {
2067 self.id == other.id
2068 }
2069}
2070
2071impl Eq for AnyOffsetLayer {}
2072
2073impl Hash for AnyOffsetLayer {
2074 fn hash<H: Hasher>(&self, state: &mut H) {
2075 self.id.hash(state);
2076 }
2077}
2078
2079impl From<AnyOffsetLayer> for HandleId {
2080 fn from(layer: AnyOffsetLayer) -> HandleId {
2081 layer.id
2082 }
2083}
2084
2085impl Debug for AnyOffsetLayer {
2086 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2087 write!(f, "AnyOffsetLayer({:?})", self.id)
2088 }
2089}
2090
2091impl ErasedLayer for AnyOffsetLayer {
2092 fn as_layer(self) -> AnyLayer {
2093 self.as_container_layer().as_layer()
2094 }
2095}
2096
2097impl AnyOffsetLayer {
2098 fn from_vtable(id: HandleId, vtable: &'static OffsetLayerVTable) -> AnyOffsetLayer {
2099 AnyOffsetLayer { id, vtable }
2100 }
2101
2102 pub fn id(self) -> HandleId {
2103 self.id
2104 }
2105
2106 pub fn as_container_layer(self) -> AnyContainerLayer {
2108 AnyContainerLayer::from_vtable(self.id, &self.vtable.container)
2109 }
2110
2111 pub fn offset(self, app: &App) -> Offset {
2113 (self.vtable.offset_data)(app, self.id).offset
2114 }
2115
2116 pub fn to_picture(self, app: &mut App, bounds: Rect, pixel_ratio: f64) -> Picture {
2123 let offset = self.offset(app);
2124 scene_picture(app, self.as_container_layer(), bounds, offset, pixel_ratio)
2125 }
2126
2127 pub fn set_offset(self, app: &mut App, value: Offset) {
2129 if value == self.offset(app) {
2130 return;
2131 }
2132 (self.vtable.offset_data_mut)(app, self.id).offset = value;
2133 if !self.as_layer().always_needs_add_to_scene(app) {
2134 self.as_layer().mark_needs_add_to_scene(app);
2135 }
2136 }
2137}
2138
2139fn fill_offset_debug_properties<T: OffsetLayerMixin>(
2142 this: Handle<T>,
2143 app: &App,
2144 properties: &mut DiagnosticPropertiesBuilder,
2145) {
2146 properties.add(DiagnosticsProperty::new("offset", this.offset(app)));
2147}
2148
2149pub struct OffsetLayer {
2151 layer: LayerData,
2152 container_layer: ContainerLayerData,
2153 offset_layer: OffsetLayerData,
2154}
2155
2156impl OffsetLayer {
2157 pub fn new(app: &mut App, offset: Offset) -> Handle<OffsetLayer> {
2161 app.create(OffsetLayer {
2162 layer: LayerData::new(),
2163 container_layer: ContainerLayerData::new(),
2164 offset_layer: OffsetLayerData::new(offset),
2165 })
2166 .into_tree_node(app)
2167 }
2168}
2169
2170impl Layer for OffsetLayer {
2171 crate::layer_accessors!(container);
2172
2173 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2174 ContainerLayer::supports_rasterization(self, app)
2175 }
2176
2177 fn dispose(self: Handle<Self>, app: &mut App) {
2178 ContainerLayer::dispose(self, app);
2179 }
2180
2181 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2182 ContainerLayer::attach(self, app, owner);
2183 }
2184
2185 fn detach(self: Handle<Self>, app: &mut App) {
2186 ContainerLayer::detach(self, app);
2187 }
2188
2189 fn redepth_children(self: Handle<Self>, app: &mut App) {
2190 ContainerLayer::redepth_children(self, app);
2191 }
2192
2193 fn find_annotations(
2194 self: Handle<Self>,
2195 app: &App,
2196 result: &mut AnnotationSearch,
2197 local_position: Offset,
2198 only_first: bool,
2199 ) -> bool {
2200 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2201 }
2202
2203 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2204 OffsetLayerMixin::add_to_scene(self, app, builder);
2205 }
2206
2207 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2208 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2209 }
2210
2211 fn debug_fill_properties(
2212 self: Handle<Self>,
2213 app: &App,
2214 properties: &mut DiagnosticPropertiesBuilder,
2215 ) {
2216 fill_offset_debug_properties(self, app, properties);
2217 }
2218}
2219
2220impl ContainerLayer for OffsetLayer {
2221 crate::container_layer_accessors!(offset);
2222
2223 fn apply_transform(
2224 self: Handle<Self>,
2225 app: &App,
2226 child: Option<AnyLayer>,
2227 transform: &mut Matrix4,
2228 ) {
2229 OffsetLayerMixin::apply_transform(self, app, child, transform);
2230 }
2231}
2232
2233impl OffsetLayerMixin for OffsetLayer {
2234 crate::offset_layer_accessors!();
2235}
2236
2237#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2242pub struct BackdropKey(u64);
2243
2244static NEXT_BACKDROP_KEY: AtomicU64 = AtomicU64::new(0);
2245
2246impl BackdropKey {
2247 #[expect(
2249 clippy::new_without_default,
2250 reason = "each call creates a distinct key; Default would suggest a neutral value"
2251 )]
2252 pub fn new() -> BackdropKey {
2253 BackdropKey(NEXT_BACKDROP_KEY.fetch_add(1, Ordering::Relaxed))
2254 }
2255
2256 pub fn id(self) -> u64 {
2258 self.0
2259 }
2260}
2261
2262pub struct ClipRectLayer {
2268 layer: LayerData,
2269 container_layer: ContainerLayerData,
2270 clip_rect: Option<Rect>,
2271 clip_behavior: Clip,
2272}
2273
2274impl ClipRectLayer {
2275 pub fn new(app: &mut App) -> Handle<ClipRectLayer> {
2282 debug_assert!(Clip::HardEdge != Clip::None);
2283 app.create(ClipRectLayer {
2284 layer: LayerData::new(),
2285 container_layer: ContainerLayerData::new(),
2286 clip_rect: None,
2287 clip_behavior: Clip::HardEdge,
2288 })
2289 .into_tree_node(app)
2290 }
2291
2292 pub fn clip_rect(self: Handle<Self>, app: &App) -> Option<Rect> {
2297 app.get(self).clip_rect
2298 }
2299
2300 pub fn set_clip_rect(self: Handle<Self>, app: &mut App, value: Option<Rect>) {
2302 if value != app.get(self).clip_rect {
2303 app.get_mut(self).clip_rect = value;
2304 self.as_layer().mark_needs_add_to_scene(app);
2305 }
2306 }
2307
2308 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2314 app.get(self).clip_behavior
2315 }
2316
2317 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2319 debug_assert!(value != Clip::None);
2320 if value != app.get(self).clip_behavior {
2321 app.get_mut(self).clip_behavior = value;
2322 self.as_layer().mark_needs_add_to_scene(app);
2323 }
2324 }
2325}
2326
2327impl Layer for ClipRectLayer {
2328 crate::layer_accessors!(container);
2329
2330 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2331 self.clip_rect(app)
2332 }
2333
2334 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2335 ContainerLayer::supports_rasterization(self, app)
2336 }
2337
2338 fn dispose(self: Handle<Self>, app: &mut App) {
2339 ContainerLayer::dispose(self, app);
2340 }
2341
2342 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2343 ContainerLayer::attach(self, app, owner);
2344 }
2345
2346 fn detach(self: Handle<Self>, app: &mut App) {
2347 ContainerLayer::detach(self, app);
2348 }
2349
2350 fn redepth_children(self: Handle<Self>, app: &mut App) {
2351 ContainerLayer::redepth_children(self, app);
2352 }
2353
2354 fn find_annotations(
2355 self: Handle<Self>,
2356 app: &App,
2357 result: &mut AnnotationSearch,
2358 local_position: Offset,
2359 only_first: bool,
2360 ) -> bool {
2361 if !self
2362 .clip_rect(app)
2363 .expect("clipRect must be set before searching annotations")
2364 .contains(local_position)
2365 {
2366 return false;
2367 }
2368 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2369 }
2370
2371 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2372 debug_assert!(self.clip_rect(app).is_some());
2373 let mut enabled = true;
2374 if cfg!(debug_assertions) {
2375 enabled = !crate::debug::debug_disable_clip_layers(app);
2376 }
2377 if enabled {
2378 let clip_rect = self
2379 .clip_rect(app)
2380 .expect("clipRect must be set before compositing");
2381 let clip_behavior = self.clip_behavior(app);
2382 builder.push_clip_rect(clip_rect, clip_behavior);
2383 }
2384 self.as_container_layer()
2385 .add_children_to_scene(app, builder);
2386 let engine_layer = enabled.then(|| builder.pop());
2387 self.as_layer().set_engine_layer(app, engine_layer);
2388 }
2389
2390 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2391 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2392 }
2393
2394 fn debug_fill_properties(
2395 self: Handle<Self>,
2396 app: &App,
2397 properties: &mut DiagnosticPropertiesBuilder,
2398 ) {
2399 properties.add(DiagnosticsProperty::<Rect>::new(
2400 "clipRect",
2401 self.clip_rect(app),
2402 ));
2403 properties.add(DiagnosticsProperty::<Clip>::new(
2404 "clipBehavior",
2405 self.clip_behavior(app),
2406 ));
2407 }
2408}
2409
2410impl ContainerLayer for ClipRectLayer {
2411 crate::container_layer_accessors!();
2412}
2413
2414pub struct ClipRRectLayer {
2420 layer: LayerData,
2421 container_layer: ContainerLayerData,
2422 clip_rrect: Option<RRect>,
2423 clip_behavior: Clip,
2424}
2425
2426impl ClipRRectLayer {
2427 pub fn new(app: &mut App) -> Handle<ClipRRectLayer> {
2432 debug_assert!(Clip::AntiAlias != Clip::None);
2433 app.create(ClipRRectLayer {
2434 layer: LayerData::new(),
2435 container_layer: ContainerLayerData::new(),
2436 clip_rrect: None,
2437 clip_behavior: Clip::AntiAlias,
2438 })
2439 .into_tree_node(app)
2440 }
2441
2442 pub fn clip_rrect(self: Handle<Self>, app: &App) -> Option<RRect> {
2447 app.get(self).clip_rrect
2448 }
2449
2450 pub fn set_clip_rrect(self: Handle<Self>, app: &mut App, value: Option<RRect>) {
2452 if value != app.get(self).clip_rrect {
2453 app.get_mut(self).clip_rrect = value;
2454 self.as_layer().mark_needs_add_to_scene(app);
2455 }
2456 }
2457
2458 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2464 app.get(self).clip_behavior
2465 }
2466
2467 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2469 debug_assert!(value != Clip::None);
2470 if value != app.get(self).clip_behavior {
2471 app.get_mut(self).clip_behavior = value;
2472 self.as_layer().mark_needs_add_to_scene(app);
2473 }
2474 }
2475}
2476
2477impl Layer for ClipRRectLayer {
2478 crate::layer_accessors!(container);
2479
2480 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2481 self.clip_rrect(app).map(RRect::outer_rect)
2482 }
2483
2484 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2485 ContainerLayer::supports_rasterization(self, app)
2486 }
2487
2488 fn dispose(self: Handle<Self>, app: &mut App) {
2489 ContainerLayer::dispose(self, app);
2490 }
2491
2492 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2493 ContainerLayer::attach(self, app, owner);
2494 }
2495
2496 fn detach(self: Handle<Self>, app: &mut App) {
2497 ContainerLayer::detach(self, app);
2498 }
2499
2500 fn redepth_children(self: Handle<Self>, app: &mut App) {
2501 ContainerLayer::redepth_children(self, app);
2502 }
2503
2504 fn find_annotations(
2505 self: Handle<Self>,
2506 app: &App,
2507 result: &mut AnnotationSearch,
2508 local_position: Offset,
2509 only_first: bool,
2510 ) -> bool {
2511 if !self
2512 .clip_rrect(app)
2513 .expect("clipRRect must be set before searching annotations")
2514 .contains(local_position)
2515 {
2516 return false;
2517 }
2518 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2519 }
2520
2521 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2522 debug_assert!(self.clip_rrect(app).is_some());
2523 let mut enabled = true;
2524 if cfg!(debug_assertions) {
2525 enabled = !crate::debug::debug_disable_clip_layers(app);
2526 }
2527 if enabled {
2528 let clip_rrect = self
2529 .clip_rrect(app)
2530 .expect("clipRRect must be set before compositing");
2531 let clip_behavior = self.clip_behavior(app);
2532 builder.push_clip_rrect(clip_rrect, clip_behavior);
2533 }
2534 self.as_container_layer()
2535 .add_children_to_scene(app, builder);
2536 let engine_layer = enabled.then(|| builder.pop());
2537 self.as_layer().set_engine_layer(app, engine_layer);
2538 }
2539
2540 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2541 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2542 }
2543
2544 fn debug_fill_properties(
2545 self: Handle<Self>,
2546 app: &App,
2547 properties: &mut DiagnosticPropertiesBuilder,
2548 ) {
2549 properties.add(DiagnosticsProperty::<RRect>::new(
2550 "clipRRect",
2551 self.clip_rrect(app),
2552 ));
2553 properties.add(DiagnosticsProperty::<Clip>::new(
2554 "clipBehavior",
2555 self.clip_behavior(app),
2556 ));
2557 }
2558}
2559
2560impl ContainerLayer for ClipRRectLayer {
2561 crate::container_layer_accessors!();
2562}
2563
2564pub struct ClipPathLayer {
2570 layer: LayerData,
2571 container_layer: ContainerLayerData,
2572 clip_path: Option<waft_embedder::Path>,
2573 clip_behavior: Clip,
2574}
2575
2576impl ClipPathLayer {
2577 pub fn new(app: &mut App) -> Handle<ClipPathLayer> {
2582 debug_assert!(Clip::AntiAlias != Clip::None);
2583 app.create(ClipPathLayer {
2584 layer: LayerData::new(),
2585 container_layer: ContainerLayerData::new(),
2586 clip_path: None,
2587 clip_behavior: Clip::AntiAlias,
2588 })
2589 .into_tree_node(app)
2590 }
2591
2592 pub fn clip_path(self: Handle<Self>, app: &App) -> Option<&waft_embedder::Path> {
2597 app.get(self).clip_path.as_ref()
2598 }
2599
2600 pub fn set_clip_path(self: Handle<Self>, app: &mut App, value: Option<waft_embedder::Path>) {
2602 app.get_mut(self).clip_path = value;
2603 self.as_layer().mark_needs_add_to_scene(app);
2604 }
2605
2606 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2612 app.get(self).clip_behavior
2613 }
2614
2615 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2617 debug_assert!(value != Clip::None);
2618 if value != app.get(self).clip_behavior {
2619 app.get_mut(self).clip_behavior = value;
2620 self.as_layer().mark_needs_add_to_scene(app);
2621 }
2622 }
2623}
2624
2625impl Layer for ClipPathLayer {
2626 crate::layer_accessors!(container);
2627
2628 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2629 Some(app.get(self).clip_path.as_ref()?.get_bounds())
2630 }
2631
2632 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2633 ContainerLayer::supports_rasterization(self, app)
2634 }
2635
2636 fn dispose(self: Handle<Self>, app: &mut App) {
2637 ContainerLayer::dispose(self, app);
2638 }
2639
2640 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2641 ContainerLayer::attach(self, app, owner);
2642 }
2643
2644 fn detach(self: Handle<Self>, app: &mut App) {
2645 ContainerLayer::detach(self, app);
2646 }
2647
2648 fn redepth_children(self: Handle<Self>, app: &mut App) {
2649 ContainerLayer::redepth_children(self, app);
2650 }
2651
2652 fn find_annotations(
2653 self: Handle<Self>,
2654 app: &App,
2655 result: &mut AnnotationSearch,
2656 local_position: Offset,
2657 only_first: bool,
2658 ) -> bool {
2659 let path = app
2660 .get(self)
2661 .clip_path
2662 .as_ref()
2663 .expect("clipPath must be set before searching annotations");
2664 if !path.contains(local_position) {
2665 return false;
2666 }
2667 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2668 }
2669
2670 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2671 debug_assert!(app.get(self).clip_path.is_some());
2672 let mut enabled = true;
2673 if cfg!(debug_assertions) {
2674 enabled = !crate::debug::debug_disable_clip_layers(app);
2675 }
2676 if enabled {
2677 let clip_path = app
2678 .get(self)
2679 .clip_path
2680 .clone()
2681 .expect("clipPath must be set before compositing");
2682 let clip_behavior = self.clip_behavior(app);
2683 builder.push_clip_path(&clip_path, clip_behavior);
2684 }
2685 self.as_container_layer()
2686 .add_children_to_scene(app, builder);
2687 let engine_layer = enabled.then(|| builder.pop());
2688 self.as_layer().set_engine_layer(app, engine_layer);
2689 }
2690
2691 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2692 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2693 }
2694
2695 fn debug_fill_properties(
2696 self: Handle<Self>,
2697 app: &App,
2698 properties: &mut DiagnosticPropertiesBuilder,
2699 ) {
2700 properties.add(DiagnosticsProperty::<Clip>::new(
2701 "clipBehavior",
2702 self.clip_behavior(app),
2703 ));
2704 }
2705}
2706
2707impl ContainerLayer for ClipPathLayer {
2708 crate::container_layer_accessors!();
2709}
2710
2711fn transform_point(transform: &Matrix4, point: Offset) -> Offset {
2713 let storage = transform.to_flutter_array();
2714 let x = point.dx();
2715 let y = point.dy();
2716 let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
2717 let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
2718 let rw = storage[3] as f64 * x + storage[7] as f64 * y + storage[15] as f64;
2719 if rw == 1.0 {
2720 Offset::new(rx, ry)
2721 } else {
2722 Offset::new(rx / rw, ry / rw)
2723 }
2724}
2725
2726pub struct ImageFilterLayer {
2728 layer: LayerData,
2729 container_layer: ContainerLayerData,
2730 offset_layer: OffsetLayerData,
2731 image_filter: Option<ImageFilter>,
2732}
2733
2734impl ImageFilterLayer {
2735 pub fn new(app: &mut App) -> Handle<ImageFilterLayer> {
2740 app.create(ImageFilterLayer {
2741 layer: LayerData::new(),
2742 container_layer: ContainerLayerData::new(),
2743 offset_layer: OffsetLayerData::new(Offset::ZERO),
2744 image_filter: None,
2745 })
2746 .into_tree_node(app)
2747 }
2748
2749 pub fn image_filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
2754 app.get(self).image_filter.as_ref()
2755 }
2756
2757 pub fn set_image_filter(self: Handle<Self>, app: &mut App, value: ImageFilter) {
2759 if app.get(self).image_filter.as_ref() != Some(&value) {
2760 app.get_mut(self).image_filter = Some(value);
2761 self.as_layer().mark_needs_add_to_scene(app);
2762 }
2763 }
2764}
2765
2766impl Layer for ImageFilterLayer {
2767 crate::layer_accessors!(container);
2768
2769 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2770 ContainerLayer::supports_rasterization(self, app)
2771 }
2772
2773 fn dispose(self: Handle<Self>, app: &mut App) {
2774 ContainerLayer::dispose(self, app);
2775 }
2776
2777 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2778 ContainerLayer::attach(self, app, owner);
2779 }
2780
2781 fn detach(self: Handle<Self>, app: &mut App) {
2782 ContainerLayer::detach(self, app);
2783 }
2784
2785 fn redepth_children(self: Handle<Self>, app: &mut App) {
2786 ContainerLayer::redepth_children(self, app);
2787 }
2788
2789 fn find_annotations(
2790 self: Handle<Self>,
2791 app: &App,
2792 result: &mut AnnotationSearch,
2793 local_position: Offset,
2794 only_first: bool,
2795 ) -> bool {
2796 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2797 }
2798
2799 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2800 debug_assert!(self.image_filter(app).is_some());
2801 let image_filter = self
2802 .image_filter(app)
2803 .cloned()
2804 .expect("image_filter must be set before compositing");
2805 let offset = self.offset(app);
2806 builder.push_image_filter(&image_filter, offset);
2807 self.as_container_layer()
2808 .add_children_to_scene(app, builder);
2809 let engine_layer = builder.pop();
2810 self.as_layer().set_engine_layer(app, Some(engine_layer));
2811 }
2812
2813 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2814 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2815 }
2816
2817 fn debug_fill_properties(
2818 self: Handle<Self>,
2819 app: &App,
2820 properties: &mut DiagnosticPropertiesBuilder,
2821 ) {
2822 fill_offset_debug_properties(self, app, properties);
2823 properties.add(DiagnosticsProperty::<ImageFilter>::new(
2824 "imageFilter",
2825 self.image_filter(app).cloned(),
2826 ));
2827 }
2828}
2829
2830impl ContainerLayer for ImageFilterLayer {
2831 crate::container_layer_accessors!(offset);
2832
2833 fn apply_transform(
2834 self: Handle<Self>,
2835 app: &App,
2836 child: Option<AnyLayer>,
2837 transform: &mut Matrix4,
2838 ) {
2839 OffsetLayerMixin::apply_transform(self, app, child, transform);
2840 }
2841}
2842
2843impl OffsetLayerMixin for ImageFilterLayer {
2844 crate::offset_layer_accessors!();
2845}
2846
2847pub struct TransformLayer {
2852 layer: LayerData,
2853 container_layer: ContainerLayerData,
2854 offset_layer: OffsetLayerData,
2855 transform: Option<Matrix4>,
2856 last_effective_transform: Option<Matrix4>,
2857 inverted_transform: Cell<Option<Matrix4>>,
2858 inverse_dirty: Cell<bool>,
2859}
2860
2861impl TransformLayer {
2862 pub fn new(app: &mut App) -> Handle<TransformLayer> {
2867 app.create(TransformLayer {
2868 layer: LayerData::new(),
2869 container_layer: ContainerLayerData::new(),
2870 offset_layer: OffsetLayerData::new(Offset::ZERO),
2871 transform: None,
2872 last_effective_transform: None,
2873 inverted_transform: Cell::new(None),
2874 inverse_dirty: Cell::new(true),
2875 })
2876 .into_tree_node(app)
2877 }
2878
2879 pub fn transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
2889 app.get(self).transform
2890 }
2891
2892 pub fn set_transform(self: Handle<Self>, app: &mut App, value: Matrix4) {
2894 debug_assert!(
2895 value
2896 .to_flutter_array()
2897 .iter()
2898 .all(|component| component.is_finite())
2899 );
2900 if app.get(self).transform == Some(value) {
2901 return;
2902 }
2903 app.get_mut(self).transform = Some(value);
2904 app.get(self).inverse_dirty.set(true);
2905 self.as_layer().mark_needs_add_to_scene(app);
2906 }
2907
2908 fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
2909 if app.get(self).inverse_dirty.get() {
2910 let transform = app
2911 .get(self)
2912 .transform
2913 .expect("transform must be set before searching annotations");
2914 app.get(self)
2915 .inverted_transform
2916 .set(remove_perspective_transform(transform).invert());
2917 app.get(self).inverse_dirty.set(false);
2918 }
2919 app.get(self)
2920 .inverted_transform
2921 .get()
2922 .map(|inverted| transform_point(&inverted, local_position))
2923 }
2924}
2925
2926impl Layer for TransformLayer {
2927 crate::layer_accessors!(container);
2928
2929 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2930 ContainerLayer::supports_rasterization(self, app)
2931 }
2932
2933 fn dispose(self: Handle<Self>, app: &mut App) {
2934 ContainerLayer::dispose(self, app);
2935 }
2936
2937 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2938 ContainerLayer::attach(self, app, owner);
2939 }
2940
2941 fn detach(self: Handle<Self>, app: &mut App) {
2942 ContainerLayer::detach(self, app);
2943 }
2944
2945 fn redepth_children(self: Handle<Self>, app: &mut App) {
2946 ContainerLayer::redepth_children(self, app);
2947 }
2948
2949 fn find_annotations(
2950 self: Handle<Self>,
2951 app: &App,
2952 result: &mut AnnotationSearch,
2953 local_position: Offset,
2954 only_first: bool,
2955 ) -> bool {
2956 let Some(transformed_offset) = self.transform_offset(app, local_position) else {
2957 return false;
2958 };
2959 OffsetLayerMixin::find_annotations(self, app, result, transformed_offset, only_first)
2960 }
2961
2962 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2963 debug_assert!(self.transform(app).is_some());
2964 let mut last_effective = self
2965 .transform(app)
2966 .expect("transform must be set before compositing");
2967 let offset = self.offset(app);
2968 if offset != Offset::ZERO {
2969 last_effective =
2970 Matrix4::translation(offset.dx() as f32, offset.dy() as f32).then(&last_effective);
2971 }
2972 app.get_mut(self).last_effective_transform = Some(last_effective);
2973 builder.push_transform(&last_effective);
2974 self.as_container_layer()
2975 .add_children_to_scene(app, builder);
2976 let engine_layer = builder.pop();
2977 self.as_layer().set_engine_layer(app, Some(engine_layer));
2978 }
2979
2980 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2981 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2982 }
2983
2984 fn debug_fill_properties(
2985 self: Handle<Self>,
2986 app: &App,
2987 properties: &mut DiagnosticPropertiesBuilder,
2988 ) {
2989 fill_offset_debug_properties(self, app, properties);
2990 properties.add(TransformProperty::new("transform", self.transform(app)));
2991 }
2992}
2993
2994impl ContainerLayer for TransformLayer {
2995 crate::container_layer_accessors!(offset);
2996
2997 fn apply_transform(
2998 self: Handle<Self>,
2999 app: &App,
3000 child: Option<AnyLayer>,
3001 transform: &mut Matrix4,
3002 ) {
3003 debug_assert!(child.is_some());
3004 debug_assert!(
3005 app.get(self).last_effective_transform.is_some() || self.transform(app).is_some()
3006 );
3007 let applied = match app.get(self).last_effective_transform {
3008 None => self
3009 .transform(app)
3010 .expect("transform must be set before applyTransform"),
3011 Some(last_effective) => last_effective,
3012 };
3013 *transform = transform.then(&applied);
3014 }
3015}
3016
3017impl OffsetLayerMixin for TransformLayer {
3018 crate::offset_layer_accessors!();
3019}
3020
3021pub struct OpacityLayer {
3031 layer: LayerData,
3032 container_layer: ContainerLayerData,
3033 offset_layer: OffsetLayerData,
3034 alpha: Option<i32>,
3035}
3036
3037impl OpacityLayer {
3038 pub fn new(app: &mut App) -> Handle<OpacityLayer> {
3043 app.create(OpacityLayer {
3044 layer: LayerData::new(),
3045 container_layer: ContainerLayerData::new(),
3046 offset_layer: OffsetLayerData::new(Offset::ZERO),
3047 alpha: None,
3048 })
3049 .into_tree_node(app)
3050 }
3051
3052 pub fn alpha(self: Handle<Self>, app: &App) -> Option<i32> {
3060 app.get(self).alpha
3061 }
3062
3063 pub fn set_alpha(self: Handle<Self>, app: &mut App, value: i32) {
3065 if app.get(self).alpha != Some(value) {
3066 app.get_mut(self).alpha = Some(value);
3067 self.as_layer().mark_needs_add_to_scene(app);
3068 }
3069 }
3070}
3071
3072impl Layer for OpacityLayer {
3073 crate::layer_accessors!(container);
3074
3075 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3076 ContainerLayer::supports_rasterization(self, app)
3077 }
3078
3079 fn dispose(self: Handle<Self>, app: &mut App) {
3080 ContainerLayer::dispose(self, app);
3081 }
3082
3083 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3084 ContainerLayer::attach(self, app, owner);
3085 }
3086
3087 fn detach(self: Handle<Self>, app: &mut App) {
3088 ContainerLayer::detach(self, app);
3089 }
3090
3091 fn redepth_children(self: Handle<Self>, app: &mut App) {
3092 ContainerLayer::redepth_children(self, app);
3093 }
3094
3095 fn find_annotations(
3096 self: Handle<Self>,
3097 app: &App,
3098 result: &mut AnnotationSearch,
3099 local_position: Offset,
3100 only_first: bool,
3101 ) -> bool {
3102 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
3103 }
3104
3105 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3106 debug_assert!(self.alpha(app).is_some());
3107
3108 let mut enabled = self.as_container_layer().first_child(app).is_some();
3110 if !enabled {
3111 self.as_layer().set_engine_layer(app, None);
3113 return;
3114 }
3115
3116 if cfg!(debug_assertions) {
3117 enabled = enabled && !crate::debug::debug_disable_opacity_layers(app);
3118 }
3119
3120 let realized_alpha = self
3121 .alpha(app)
3122 .expect("alpha must be set before compositing");
3123 let offset = self.offset(app);
3124 if enabled && realized_alpha < 255 {
3125 builder.push_opacity(realized_alpha, offset);
3126 } else {
3127 builder.push_offset(offset.dx(), offset.dy());
3128 }
3129 self.as_container_layer()
3130 .add_children_to_scene(app, builder);
3131 let engine_layer = builder.pop();
3132 self.as_layer().set_engine_layer(app, Some(engine_layer));
3133 }
3134
3135 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3136 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3137 }
3138
3139 fn debug_fill_properties(
3140 self: Handle<Self>,
3141 app: &App,
3142 properties: &mut DiagnosticPropertiesBuilder,
3143 ) {
3144 fill_offset_debug_properties(self, app, properties);
3145 properties.add(IntProperty::<i32>::new("alpha", self.alpha(app)));
3146 }
3147}
3148
3149impl ContainerLayer for OpacityLayer {
3150 crate::container_layer_accessors!(offset);
3151
3152 fn apply_transform(
3153 self: Handle<Self>,
3154 app: &App,
3155 child: Option<AnyLayer>,
3156 transform: &mut Matrix4,
3157 ) {
3158 OffsetLayerMixin::apply_transform(self, app, child, transform);
3159 }
3160}
3161
3162impl OffsetLayerMixin for OpacityLayer {
3163 crate::offset_layer_accessors!();
3164}
3165
3166pub struct BackdropFilterLayer {
3168 layer: LayerData,
3169 container_layer: ContainerLayerData,
3170 filter: Option<ImageFilter>,
3171 blend_mode: BlendMode,
3172 backdrop_key: Option<BackdropKey>,
3173}
3174
3175impl BackdropFilterLayer {
3176 pub fn new(app: &mut App) -> Handle<BackdropFilterLayer> {
3183 app.create(BackdropFilterLayer {
3184 layer: LayerData::new(),
3185 container_layer: ContainerLayerData::new(),
3186 filter: None,
3187 blend_mode: BlendMode::SrcOver,
3188 backdrop_key: None,
3189 })
3190 .into_tree_node(app)
3191 }
3192
3193 pub fn filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
3198 app.get(self).filter.as_ref()
3199 }
3200
3201 pub fn set_filter(self: Handle<Self>, app: &mut App, value: Option<ImageFilter>) {
3203 app.get_mut(self).filter = value;
3204 self.as_layer().mark_needs_add_to_scene(app);
3205 }
3206
3207 pub fn blend_mode(self: Handle<Self>, app: &App) -> BlendMode {
3215 app.get(self).blend_mode
3216 }
3217
3218 pub fn set_blend_mode(self: Handle<Self>, app: &mut App, value: BlendMode) {
3220 if value != app.get(self).blend_mode {
3221 app.get_mut(self).blend_mode = value;
3222 self.as_layer().mark_needs_add_to_scene(app);
3223 }
3224 }
3225
3226 pub fn backdrop_key(self: Handle<Self>, app: &App) -> Option<BackdropKey> {
3234 app.get(self).backdrop_key
3235 }
3236
3237 pub fn set_backdrop_key(self: Handle<Self>, app: &mut App, value: Option<BackdropKey>) {
3239 if value != app.get(self).backdrop_key {
3240 app.get_mut(self).backdrop_key = value;
3241 self.as_layer().mark_needs_add_to_scene(app);
3242 }
3243 }
3244}
3245
3246impl Layer for BackdropFilterLayer {
3247 crate::layer_accessors!(container);
3248
3249 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3250 ContainerLayer::supports_rasterization(self, app)
3251 }
3252
3253 fn dispose(self: Handle<Self>, app: &mut App) {
3254 ContainerLayer::dispose(self, app);
3255 }
3256
3257 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3258 ContainerLayer::attach(self, app, owner);
3259 }
3260
3261 fn detach(self: Handle<Self>, app: &mut App) {
3262 ContainerLayer::detach(self, app);
3263 }
3264
3265 fn redepth_children(self: Handle<Self>, app: &mut App) {
3266 ContainerLayer::redepth_children(self, app);
3267 }
3268
3269 fn find_annotations(
3270 self: Handle<Self>,
3271 app: &App,
3272 result: &mut AnnotationSearch,
3273 local_position: Offset,
3274 only_first: bool,
3275 ) -> bool {
3276 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
3277 }
3278
3279 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3280 debug_assert!(app.get(self).filter.is_some());
3281 let filter = app
3282 .get(self)
3283 .filter
3284 .clone()
3285 .expect("filter must be set before compositing");
3286 let blend_mode = self.blend_mode(app);
3287 let backdrop_id = self.backdrop_key(app).map(BackdropKey::id);
3288 builder.push_backdrop_filter(&filter, blend_mode, backdrop_id);
3289 self.as_container_layer()
3290 .add_children_to_scene(app, builder);
3291 let engine_layer = builder.pop();
3292 self.as_layer().set_engine_layer(app, Some(engine_layer));
3293 }
3294
3295 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3296 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3297 }
3298
3299 fn debug_fill_properties(
3300 self: Handle<Self>,
3301 app: &App,
3302 properties: &mut DiagnosticPropertiesBuilder,
3303 ) {
3304 properties.add(DiagnosticsProperty::<ImageFilter>::new(
3305 "filter",
3306 self.filter(app).cloned(),
3307 ));
3308 properties.add(EnumProperty::new("blendMode", self.blend_mode(app)));
3309 properties.add(IntProperty::<i64>::new(
3310 "backdropKey",
3311 self.backdrop_key(app).map(|key| key.id() as i64),
3312 ));
3313 }
3314}
3315
3316impl ContainerLayer for BackdropFilterLayer {
3317 crate::container_layer_accessors!();
3318}
3319
3320pub struct LayerLink {
3332 leader: Option<Handle<LeaderLayer>>,
3333 debug_previous_leaders: Option<HashSet<Handle<LeaderLayer>>>,
3334 debug_leader_check_scheduled: bool,
3335 pub leader_size: Option<Size>,
3341}
3342
3343impl LayerLink {
3344 pub fn new(app: &mut App) -> Ref<LayerLink> {
3346 app.create(LayerLink {
3347 leader: None,
3348 debug_previous_leaders: None,
3349 debug_leader_check_scheduled: false,
3350 leader_size: None,
3351 })
3352 }
3353
3354 pub fn leader(self: Handle<Self>, app: &App) -> Option<Handle<LeaderLayer>> {
3356 app.get(self).leader
3357 }
3358
3359 pub fn to_string_with_app(self: Handle<Self>, app: &App) -> String {
3362 let state = if self.leader(app).is_some() {
3363 "<linked>"
3364 } else {
3365 "<dangling>"
3366 };
3367 format!(
3368 "{}({state})",
3369 describe_identity("LayerLink", self.id().identity_hash())
3370 )
3371 }
3372
3373 fn register_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3374 debug_assert_ne!(self.leader(app), Some(leader));
3375 if cfg!(debug_assertions)
3376 && let Some(current) = self.leader(app)
3377 {
3378 let previous = app
3379 .get_mut(self)
3380 .debug_previous_leaders
3381 .get_or_insert_with(HashSet::new);
3382 debug_assert!(previous.insert(current));
3383 self.debug_schedule_leaders_clean_up_check(app);
3384 }
3385 app.get_mut(self).leader = Some(leader);
3386 }
3387
3388 fn unregister_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3389 if self.leader(app) == Some(leader) {
3390 app.get_mut(self).leader = None;
3391 } else if cfg!(debug_assertions) {
3392 let removed = app
3393 .get_mut(self)
3394 .debug_previous_leaders
3395 .as_mut()
3396 .expect("a replaced leader is tracked")
3397 .remove(&leader);
3398 debug_assert!(removed);
3399 }
3400 }
3401
3402 fn debug_schedule_leaders_clean_up_check(self: Handle<Self>, app: &mut App) {
3405 debug_assert!(app.get(self).debug_previous_leaders.is_some());
3406 if cfg!(debug_assertions) {
3407 if app.get(self).debug_leader_check_scheduled {
3408 return;
3409 }
3410 app.get_mut(self).debug_leader_check_scheduled = true;
3411 SchedulerBinding::add_post_frame_callback(
3412 app,
3413 FrameCallback::handle_method(self, |this, app, _time_stamp| {
3414 app.get_mut(this).debug_leader_check_scheduled = false;
3415 debug_assert!(
3416 app.get(this)
3417 .debug_previous_leaders
3418 .as_ref()
3419 .expect("a replaced leader is tracked")
3420 .is_empty()
3421 );
3422 }),
3423 None,
3424 );
3425 }
3426 }
3427}
3428
3429pub struct LeaderLayer {
3435 layer: LayerData,
3436 container_layer: ContainerLayerData,
3437 link: Ref<LayerLink>,
3438 offset: Offset,
3439}
3440
3441impl LeaderLayer {
3442 pub fn new(app: &mut App, link: Ref<LayerLink>) -> Handle<LeaderLayer> {
3450 app.create(LeaderLayer {
3451 layer: LayerData::new(),
3452 container_layer: ContainerLayerData::new(),
3453 link,
3454 offset: Offset::ZERO,
3455 })
3456 .into_tree_node(app)
3457 }
3458
3459 pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3464 app.get(self).link.handle()
3465 }
3466
3467 pub fn set_link(self: Handle<Self>, app: &mut App, value: Ref<LayerLink>) {
3469 let current = self.link(app);
3470 if current == value {
3471 return;
3472 }
3473 if self.as_layer().attached(app) {
3474 current.unregister_leader(app, self);
3475 value.register_leader(app, self);
3476 }
3477 app.get_mut(self).link = value;
3478 }
3479
3480 pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3488 app.get(self).offset
3489 }
3490
3491 pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3493 if value == app.get(self).offset {
3494 return;
3495 }
3496 app.get_mut(self).offset = value;
3497 if !self.as_layer().always_needs_add_to_scene(app) {
3498 self.as_layer().mark_needs_add_to_scene(app);
3499 }
3500 }
3501}
3502
3503impl Layer for LeaderLayer {
3504 crate::layer_accessors!(container);
3505
3506 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3507 ContainerLayer::supports_rasterization(self, app)
3508 }
3509
3510 fn dispose(self: Handle<Self>, app: &mut App) {
3511 ContainerLayer::dispose(self, app);
3512 }
3513
3514 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3515 ContainerLayer::attach(self, app, owner);
3516 let link = self.link(app);
3517 link.register_leader(app, self);
3518 }
3519
3520 fn detach(self: Handle<Self>, app: &mut App) {
3521 let link = self.link(app);
3522 link.unregister_leader(app, self);
3523 ContainerLayer::detach(self, app);
3524 }
3525
3526 fn redepth_children(self: Handle<Self>, app: &mut App) {
3527 ContainerLayer::redepth_children(self, app);
3528 }
3529
3530 fn find_annotations(
3531 self: Handle<Self>,
3532 app: &App,
3533 result: &mut AnnotationSearch,
3534 local_position: Offset,
3535 only_first: bool,
3536 ) -> bool {
3537 let offset = self.offset(app);
3538 ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
3539 }
3540
3541 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3542 let offset = self.offset(app);
3543 if offset != Offset::ZERO {
3544 builder.push_transform(&Matrix4::translation(
3545 offset.dx() as f32,
3546 offset.dy() as f32,
3547 ));
3548 }
3549 self.as_container_layer()
3550 .add_children_to_scene(app, builder);
3551 let engine_layer = (offset != Offset::ZERO).then(|| builder.pop());
3552 self.as_layer().set_engine_layer(app, engine_layer);
3553 }
3554
3555 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3556 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3557 }
3558
3559 fn debug_fill_properties(
3560 self: Handle<Self>,
3561 app: &App,
3562 properties: &mut DiagnosticPropertiesBuilder,
3563 ) {
3564 properties.add(DiagnosticsProperty::new("offset", self.offset(app)));
3565 properties.add(DiagnosticsProperty::<String>::new(
3566 "link",
3567 Some(self.link(app).to_string_with_app(app)),
3568 ));
3569 }
3570}
3571
3572impl ContainerLayer for LeaderLayer {
3573 crate::container_layer_accessors!();
3574
3575 fn apply_transform(
3582 self: Handle<Self>,
3583 app: &App,
3584 _child: Option<AnyLayer>,
3585 transform: &mut Matrix4,
3586 ) {
3587 let offset = self.offset(app);
3588 if offset != Offset::ZERO {
3589 *transform = transform.then(&Matrix4::translation(
3590 offset.dx() as f32,
3591 offset.dy() as f32,
3592 ));
3593 }
3594 }
3595}
3596
3597pub struct FollowerLayer {
3608 layer: LayerData,
3609 container_layer: ContainerLayerData,
3610 link: Ref<LayerLink>,
3611 show_when_unlinked: bool,
3612 unlinked_offset: Offset,
3613 linked_offset: Offset,
3614 last_offset: Option<Offset>,
3615 last_transform: Option<Matrix4>,
3616 inverted_transform: Cell<Option<Matrix4>>,
3617 inverse_dirty: Cell<bool>,
3618}
3619
3620impl FollowerLayer {
3621 pub fn new(app: &mut App, link: Ref<LayerLink>) -> Handle<FollowerLayer> {
3627 app.create(FollowerLayer {
3628 layer: LayerData::new(),
3629 container_layer: ContainerLayerData::new(),
3630 link,
3631 show_when_unlinked: true,
3632 unlinked_offset: Offset::ZERO,
3633 linked_offset: Offset::ZERO,
3634 last_offset: None,
3635 last_transform: None,
3636 inverted_transform: Cell::new(None),
3637 inverse_dirty: Cell::new(true),
3638 })
3639 .into_tree_node(app)
3640 }
3641
3642 pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3648 app.get(self).link.handle()
3649 }
3650
3651 pub fn set_link(self: Handle<Self>, app: &mut App, value: Ref<LayerLink>) {
3653 if self.link(app) == value {
3654 return;
3655 }
3656 app.get_mut(self).link = value;
3657 }
3658
3659 pub fn show_when_unlinked(self: Handle<Self>, app: &App) -> bool {
3672 app.get(self).show_when_unlinked
3673 }
3674
3675 pub fn set_show_when_unlinked(self: Handle<Self>, app: &mut App, value: bool) {
3677 app.get_mut(self).show_when_unlinked = value;
3678 }
3679
3680 pub fn unlinked_offset(self: Handle<Self>, app: &App) -> Offset {
3693 app.get(self).unlinked_offset
3694 }
3695
3696 pub fn set_unlinked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3698 app.get_mut(self).unlinked_offset = value;
3699 }
3700
3701 pub fn linked_offset(self: Handle<Self>, app: &App) -> Offset {
3714 app.get(self).linked_offset
3715 }
3716
3717 pub fn set_linked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3719 app.get_mut(self).linked_offset = value;
3720 }
3721
3722 fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
3723 if app.get(self).inverse_dirty.get() {
3724 let last = self.get_last_transform(app).expect(
3725 "FollowerLayer._transformOffset requires getLastTransform after addToScene",
3726 );
3727 app.get(self).inverted_transform.set(last.invert());
3728 app.get(self).inverse_dirty.set(false);
3729 }
3730 let inverted = app.get(self).inverted_transform.get()?;
3731 let storage = inverted.to_flutter_array();
3732 let x = local_position.dx();
3733 let y = local_position.dy();
3734 let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
3735 let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
3736 let linked_offset = self.linked_offset(app);
3737 Some(Offset::new(
3738 rx - linked_offset.dx(),
3739 ry - linked_offset.dy(),
3740 ))
3741 }
3742
3743 pub fn get_last_transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
3750 let last_transform = app.get(self).last_transform?;
3751 let last_offset = app
3752 .get(self)
3753 .last_offset
3754 .expect("lastOffset is set with lastTransform");
3755 Some(
3756 Matrix4::translation(-last_offset.dx() as f32, -last_offset.dy() as f32)
3757 .then(&last_transform),
3758 )
3759 }
3760
3761 fn collect_transform_for_layer_chain(
3767 app: &App,
3768 layers: &[Option<AnyContainerLayer>],
3769 ) -> Matrix4 {
3770 let mut result = Matrix4::IDENTITY;
3771 for index in (1..layers.len()).rev() {
3772 if let Some(layer) = layers[index] {
3773 let child = layers[index - 1].map(AnyContainerLayer::as_layer);
3774 layer.apply_transform(app, child, &mut result);
3775 }
3776 }
3777 result
3778 }
3779
3780 fn paths_to_common_ancestor(
3787 app: &App,
3788 a: Option<AnyLayer>,
3789 b: Option<AnyLayer>,
3790 ancestors_a: &mut Vec<Option<AnyContainerLayer>>,
3791 ancestors_b: &mut Vec<Option<AnyContainerLayer>>,
3792 ) -> Option<AnyLayer> {
3793 let (a, b) = (a?, b?);
3794 if a == b {
3795 return Some(a);
3796 }
3797 if a.depth(app) < b.depth(app) {
3798 ancestors_b.push(b.parent(app));
3799 return Self::paths_to_common_ancestor(
3800 app,
3801 Some(a),
3802 b.parent(app).map(AnyContainerLayer::as_layer),
3803 ancestors_a,
3804 ancestors_b,
3805 );
3806 } else if a.depth(app) > b.depth(app) {
3807 ancestors_a.push(a.parent(app));
3808 return Self::paths_to_common_ancestor(
3809 app,
3810 a.parent(app).map(AnyContainerLayer::as_layer),
3811 Some(b),
3812 ancestors_a,
3813 ancestors_b,
3814 );
3815 }
3816 ancestors_a.push(a.parent(app));
3817 ancestors_b.push(b.parent(app));
3818 Self::paths_to_common_ancestor(
3819 app,
3820 a.parent(app).map(AnyContainerLayer::as_layer),
3821 b.parent(app).map(AnyContainerLayer::as_layer),
3822 ancestors_a,
3823 ancestors_b,
3824 )
3825 }
3826
3827 fn debug_check_leader_before_follower(
3828 app: &App,
3829 leader_to_common_ancestor: &[Option<AnyContainerLayer>],
3830 follower_to_common_ancestor: &[Option<AnyContainerLayer>],
3831 ) -> bool {
3832 if follower_to_common_ancestor.len() <= 1 {
3833 return false;
3834 }
3835 if leader_to_common_ancestor.len() <= 1 {
3836 return true;
3837 }
3838 let leader_subtree_below_ancestor = leader_to_common_ancestor
3839 [leader_to_common_ancestor.len() - 2]
3840 .expect("the leader subtree below the ancestor is a layer");
3841 let follower_subtree_below_ancestor = follower_to_common_ancestor
3842 [follower_to_common_ancestor.len() - 2]
3843 .expect("the follower subtree below the ancestor is a layer");
3844 let mut sibling = Some(leader_subtree_below_ancestor.as_layer());
3845 while let Some(layer) = sibling {
3846 if layer == follower_subtree_below_ancestor.as_layer() {
3847 return true;
3848 }
3849 sibling = layer.next_sibling(app);
3850 }
3851 false
3852 }
3853
3854 fn establish_transform(self: Handle<Self>, app: &mut App) {
3856 app.get_mut(self).last_transform = None;
3857 let Some(leader) = self.link(app).leader(app) else {
3858 return;
3859 };
3860 debug_assert_eq!(
3861 leader.as_layer().owner(app),
3862 self.as_layer().owner(app),
3863 "Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer."
3864 );
3865
3866 let mut forward_layers = vec![Some(leader.as_container_layer())];
3867 let mut inverse_layers = vec![Some(self.as_container_layer())];
3868 let ancestor = Self::paths_to_common_ancestor(
3869 app,
3870 Some(leader.as_layer()),
3871 Some(self.as_layer()),
3872 &mut forward_layers,
3873 &mut inverse_layers,
3874 );
3875 debug_assert!(
3876 ancestor.is_some(),
3877 "LeaderLayer and FollowerLayer do not have a common ancestor."
3878 );
3879 debug_assert!(
3880 Self::debug_check_leader_before_follower(app, &forward_layers, &inverse_layers),
3881 "LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse \
3882 was true."
3883 );
3884
3885 let mut forward_transform = Self::collect_transform_for_layer_chain(app, &forward_layers);
3886 leader
3887 .as_container_layer()
3888 .apply_transform(app, None, &mut forward_transform);
3889 let linked_offset = self.linked_offset(app);
3890 forward_transform = forward_transform.then(&Matrix4::translation(
3891 linked_offset.dx() as f32,
3892 linked_offset.dy() as f32,
3893 ));
3894
3895 let inverse_transform = Self::collect_transform_for_layer_chain(app, &inverse_layers);
3896 let Some(inverse_transform) = inverse_transform.invert() else {
3897 return;
3898 };
3899 app.get_mut(self).last_transform = Some(inverse_transform.then(&forward_transform));
3900 app.get(self).inverse_dirty.set(true);
3901 }
3902}
3903
3904impl Layer for FollowerLayer {
3905 crate::layer_accessors!(container);
3906
3907 fn always_needs_add_to_scene(self: Handle<Self>, _app: &App) -> bool {
3911 true
3912 }
3913
3914 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3915 ContainerLayer::supports_rasterization(self, app)
3916 }
3917
3918 fn dispose(self: Handle<Self>, app: &mut App) {
3919 ContainerLayer::dispose(self, app);
3920 }
3921
3922 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3923 ContainerLayer::attach(self, app, owner);
3924 }
3925
3926 fn detach(self: Handle<Self>, app: &mut App) {
3927 ContainerLayer::detach(self, app);
3928 }
3929
3930 fn redepth_children(self: Handle<Self>, app: &mut App) {
3931 ContainerLayer::redepth_children(self, app);
3932 }
3933
3934 fn find_annotations(
3935 self: Handle<Self>,
3936 app: &App,
3937 result: &mut AnnotationSearch,
3938 local_position: Offset,
3939 only_first: bool,
3940 ) -> bool {
3941 if self.link(app).leader(app).is_none() {
3942 if self.show_when_unlinked(app) {
3943 return ContainerLayer::find_annotations(
3944 self,
3945 app,
3946 result,
3947 local_position - self.unlinked_offset(app),
3948 only_first,
3949 );
3950 }
3951 return false;
3952 }
3953 let Some(transformed_offset) = self.transform_offset(app, local_position) else {
3954 return false;
3955 };
3956 ContainerLayer::find_annotations(self, app, result, transformed_offset, only_first)
3957 }
3958
3959 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3960 if self.link(app).leader(app).is_none() && !self.show_when_unlinked(app) {
3961 app.get_mut(self).last_transform = None;
3962 app.get_mut(self).last_offset = None;
3963 app.get(self).inverse_dirty.set(true);
3964 self.as_layer().set_engine_layer(app, None);
3965 return;
3966 }
3967 self.establish_transform(app);
3968 if app.get(self).last_transform.is_some() {
3969 let unlinked_offset = self.unlinked_offset(app);
3970 app.get_mut(self).last_offset = Some(unlinked_offset);
3971 let last_transform = app
3972 .get(self)
3973 .last_transform
3974 .expect("lastTransform was just set");
3975 builder.push_transform(&last_transform);
3976 self.as_container_layer()
3977 .add_children_to_scene(app, builder);
3978 let engine_layer = builder.pop();
3979 self.as_layer().set_engine_layer(app, Some(engine_layer));
3980 } else {
3981 app.get_mut(self).last_offset = None;
3982 let unlinked_offset = self.unlinked_offset(app);
3983 let matrix =
3984 Matrix4::translation(unlinked_offset.dx() as f32, unlinked_offset.dy() as f32);
3985 builder.push_transform(&matrix);
3986 self.as_container_layer()
3987 .add_children_to_scene(app, builder);
3988 let engine_layer = builder.pop();
3989 self.as_layer().set_engine_layer(app, Some(engine_layer));
3990 }
3991 app.get(self).inverse_dirty.set(true);
3992 }
3993
3994 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3995 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3996 }
3997
3998 fn debug_fill_properties(
3999 self: Handle<Self>,
4000 app: &App,
4001 properties: &mut DiagnosticPropertiesBuilder,
4002 ) {
4003 properties.add(DiagnosticsProperty::<String>::new(
4004 "link",
4005 Some(self.link(app).to_string_with_app(app)),
4006 ));
4007 properties.add(
4008 TransformProperty::new("transform", self.get_last_transform(app)).default_value(None),
4009 );
4010 }
4011}
4012
4013impl ContainerLayer for FollowerLayer {
4014 crate::container_layer_accessors!();
4015
4016 fn apply_transform(
4017 self: Handle<Self>,
4018 app: &App,
4019 child: Option<AnyLayer>,
4020 transform: &mut Matrix4,
4021 ) {
4022 debug_assert!(child.is_some());
4023 if let Some(last_transform) = app.get(self).last_transform {
4024 *transform = transform.then(&last_transform);
4025 } else {
4026 let unlinked_offset = self.unlinked_offset(app);
4027 *transform = transform.then(&Matrix4::translation(
4028 unlinked_offset.dx() as f32,
4029 unlinked_offset.dy() as f32,
4030 ));
4031 }
4032 }
4033}
4034
4035pub struct AnnotatedRegionLayer {
4054 layer: LayerData,
4055 container_layer: ContainerLayerData,
4056 value: Rc<dyn Any>,
4057 size: Option<Size>,
4058 offset: Offset,
4059 opaque: bool,
4060}
4061
4062impl AnnotatedRegionLayer {
4063 pub fn new(app: &mut App, value: Rc<dyn Any>) -> Handle<AnnotatedRegionLayer> {
4065 app.create(AnnotatedRegionLayer {
4066 layer: LayerData::new(),
4067 container_layer: ContainerLayerData::new(),
4068 value,
4069 size: None,
4070 offset: Offset::ZERO,
4071 opaque: false,
4072 })
4073 .into_tree_node(app)
4074 }
4075
4076 pub fn value(self: Handle<Self>, app: &App) -> &Rc<dyn Any> {
4078 &app.get(self).value
4079 }
4080
4081 pub fn size(self: Handle<Self>, app: &App) -> Option<Size> {
4088 app.get(self).size
4089 }
4090
4091 pub fn set_size(self: Handle<Self>, app: &mut App, value: Option<Size>) {
4093 app.get_mut(self).size = value;
4094 }
4095
4096 pub fn offset(self: Handle<Self>, app: &App) -> Offset {
4104 app.get(self).offset
4105 }
4106
4107 pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
4109 app.get_mut(self).offset = value;
4110 }
4111
4112 pub fn opaque(self: Handle<Self>, app: &App) -> bool {
4134 app.get(self).opaque
4135 }
4136
4137 pub fn set_opaque(self: Handle<Self>, app: &mut App, value: bool) {
4139 app.get_mut(self).opaque = value;
4140 }
4141}
4142
4143impl Layer for AnnotatedRegionLayer {
4144 crate::layer_accessors!(container);
4145
4146 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
4147 ContainerLayer::supports_rasterization(self, app)
4148 }
4149
4150 fn dispose(self: Handle<Self>, app: &mut App) {
4151 ContainerLayer::dispose(self, app);
4152 }
4153
4154 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
4155 ContainerLayer::attach(self, app, owner);
4156 }
4157
4158 fn detach(self: Handle<Self>, app: &mut App) {
4159 ContainerLayer::detach(self, app);
4160 }
4161
4162 fn redepth_children(self: Handle<Self>, app: &mut App) {
4163 ContainerLayer::redepth_children(self, app);
4164 }
4165
4166 fn find_annotations(
4187 self: Handle<Self>,
4188 app: &App,
4189 result: &mut AnnotationSearch,
4190 local_position: Offset,
4191 only_first: bool,
4192 ) -> bool {
4193 let mut is_absorbed =
4194 ContainerLayer::find_annotations(self, app, result, local_position, only_first);
4195 if !result.is_empty() && only_first {
4196 return is_absorbed;
4197 }
4198 let (value, size, offset, opaque) = {
4199 let this = app.get(self);
4200 (Rc::clone(&this.value), this.size, this.offset, this.opaque)
4201 };
4202 if let Some(size) = size
4203 && !(offset & size).contains(local_position)
4204 {
4205 return is_absorbed;
4206 }
4207 if result.accepts(&*value) {
4208 is_absorbed = is_absorbed || opaque;
4209 result.add(value, local_position - offset);
4210 }
4211 is_absorbed
4212 }
4213
4214 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
4215 ContainerLayer::add_to_scene(self, app, builder);
4216 }
4217
4218 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
4219 ContainerLayer::fire_composition_callbacks(self, app, include_children);
4220 }
4221
4222 fn debug_fill_properties(
4223 self: Handle<Self>,
4224 app: &App,
4225 properties: &mut DiagnosticPropertiesBuilder,
4226 ) {
4227 properties
4230 .add(DiagnosticsProperty::<Size>::new("size", self.size(app)).default_value(None));
4231 properties.add(
4232 DiagnosticsProperty::<Offset>::new("offset", self.offset(app)).default_value(None),
4233 );
4234 properties.add(
4235 DiagnosticsProperty::<bool>::new("opaque", self.opaque(app)).default_value(Some(false)),
4236 );
4237 }
4238}
4239
4240impl ContainerLayer for AnnotatedRegionLayer {
4241 crate::container_layer_accessors!();
4242}
4243
4244fn describe_engine_layer(engine_layer: &EngineLayer) -> String {
4248 let effect = format!("{:?}", engine_layer.effect);
4249 let kind = effect
4250 .split(|c: char| !c.is_ascii_alphanumeric())
4251 .next()
4252 .unwrap_or_default();
4253 let kind = if kind == "None" { "Container" } else { kind };
4254 describe_identity(
4255 &format!("{kind}EngineLayer"),
4256 (std::sync::Arc::as_ptr(engine_layer) as usize as u64) >> 4,
4257 )
4258}
4259
4260pub(crate) fn scene_picture(
4265 app: &mut App,
4266 container: AnyContainerLayer,
4267 bounds: Rect,
4268 origin: Offset,
4269 pixel_ratio: f64,
4270) -> Picture {
4271 let scene = container.build_scene(app, SceneBuilder::new());
4272 let painted = slices(&scene, |_| None).picture_with_room();
4273 let mut canvas = Canvas::new();
4274 canvas.scale(pixel_ratio as f32, pixel_ratio as f32);
4275 canvas.translate(
4276 -(bounds.left + origin.dx()) as f32,
4277 -(bounds.top + origin.dy()) as f32,
4278 );
4279 canvas.draw_display_list(&Arc::new(painted));
4280 canvas.build()
4281}
4282
4283#[cfg(test)]
4284mod tests {
4285 use waft_foundation::AppCell;
4286
4287 use super::*;
4288
4289 fn offset_layer(app: &mut App) -> AnyLayer {
4290 OffsetLayer::new(app, Offset::ZERO).as_layer()
4291 }
4292
4293 fn debug_info<T: Layer>(layer: Handle<T>, app: &App) -> Vec<String> {
4295 let mut builder = DiagnosticPropertiesBuilder::new();
4296 Layer::debug_fill_properties(layer, app, &mut builder);
4297 builder
4298 .properties
4299 .iter()
4300 .filter(|node| !node.is_filtered(DiagnosticLevel::Info))
4301 .map(ToString::to_string)
4302 .collect()
4303 }
4304
4305 #[test]
4307 fn a_clip_rect_layer_prints_its_clip_behavior_in_debug_info() {
4308 let cell = AppCell::new();
4309 let mut app = cell.borrow_mut();
4310 let layer = ClipRectLayer::new(&mut app);
4311 assert!(debug_info(layer, &app).contains(&"clipBehavior: Clip.hardEdge".to_owned()));
4312 layer.set_clip_behavior(&mut app, Clip::AntiAliasWithSaveLayer);
4313 assert!(
4314 debug_info(layer, &app)
4315 .contains(&"clipBehavior: Clip.antiAliasWithSaveLayer".to_owned())
4316 );
4317 }
4318
4319 #[test]
4321 fn a_clip_rrect_layer_prints_its_clip_behavior_in_debug_info() {
4322 let cell = AppCell::new();
4323 let mut app = cell.borrow_mut();
4324 let layer = ClipRRectLayer::new(&mut app);
4325 assert!(debug_info(layer, &app).contains(&"clipBehavior: Clip.antiAlias".to_owned()));
4326 layer.set_clip_behavior(&mut app, Clip::AntiAliasWithSaveLayer);
4327 assert!(
4328 debug_info(layer, &app)
4329 .contains(&"clipBehavior: Clip.antiAliasWithSaveLayer".to_owned())
4330 );
4331 }
4332
4333 #[test]
4335 fn a_clip_path_layer_prints_its_clip_behavior_in_debug_info() {
4336 let cell = AppCell::new();
4337 let mut app = cell.borrow_mut();
4338 let layer = ClipPathLayer::new(&mut app);
4339 assert!(debug_info(layer, &app).contains(&"clipBehavior: Clip.antiAlias".to_owned()));
4340 layer.set_clip_behavior(&mut app, Clip::AntiAliasWithSaveLayer);
4341 assert!(
4342 debug_info(layer, &app)
4343 .contains(&"clipBehavior: Clip.antiAliasWithSaveLayer".to_owned())
4344 );
4345 }
4346
4347 #[test]
4350 fn a_backdrop_filter_layer_prints_its_filter_and_blend_mode_in_debug_info() {
4351 let cell = AppCell::new();
4352 let mut app = cell.borrow_mut();
4353 let layer = BackdropFilterLayer::new(&mut app);
4354 layer.set_filter(
4355 &mut app,
4356 Some(ImageFilter::Blur {
4357 sigma_x: 1.0,
4358 sigma_y: 1.0,
4359 bounds: None,
4360 }),
4361 );
4362 layer.set_blend_mode(&mut app, BlendMode::Clear);
4363 let info = debug_info(layer, &app);
4364 assert!(info.contains(&"filter: ImageFilter.blur(1, 1, unspecified)".to_owned()));
4365 assert!(info.contains(&"blendMode: clear".to_owned()));
4366 }
4367
4368 #[test]
4370 fn a_picture_layer_prints_its_picture_and_raster_cache_hints_in_debug_info() {
4371 let cell = AppCell::new();
4372 let mut app = cell.borrow_mut();
4373 let layer = PictureLayer::new(&mut app, Rect::from_ltrb(0.0, 0.0, 1.0, 1.0));
4374 let picture = Arc::new(Canvas::new().build());
4375 layer.set_picture(&mut app, Some(Arc::clone(&picture)));
4376 layer.set_is_complex_hint(&mut app, true);
4377 layer.set_will_change_hint(&mut app, false);
4378 let info = debug_info(layer, &app);
4379 assert!(info.contains(&format!(
4380 "picture: {}",
4381 describe_identity("Picture", Arc::as_ptr(&picture) as usize as u64 >> 4)
4382 )));
4383 assert!(
4384 info.contains(&"raster cache hints: isComplex = true, willChange = false".to_owned())
4385 );
4386 }
4387
4388 #[test]
4389 fn a_layer_dump_shows_each_layers_handles_and_its_children_in_order() {
4390 let cell = AppCell::new();
4391 let mut app = cell.borrow_mut();
4392 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4393 let a = offset_layer(&mut app);
4394 let b = offset_layer(&mut app);
4395 parent.append(&mut app, a);
4396 parent.append(&mut app, b);
4397 let dump = parent.as_layer().to_string_deep(&app);
4398 let names: Vec<&str> = dump
4399 .lines()
4400 .filter_map(|line| line.split_once("OffsetLayer#").map(|(head, _)| head))
4401 .collect();
4402 assert_eq!(names, ["", " ├─child 1: ", " └─child 2: "], "{dump}");
4403 assert_eq!(dump.matches("handles: 1").count(), 2, "{dump}");
4404 assert!(
4405 dump.contains(" │ handles: 0\n"),
4406 "the parent is kept by no handle:\n{dump}"
4407 );
4408 assert_eq!(
4409 dump.matches("offset: Offset(0.0, 0.0)").count(),
4410 3,
4411 "each layer fills its own offset:\n{dump}"
4412 );
4413 }
4414
4415 #[test]
4416 fn append_links_children_in_order_and_adopts_them() {
4417 let cell = AppCell::new();
4418 let mut app = cell.borrow_mut();
4419 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4420 let a = offset_layer(&mut app);
4421 let b = offset_layer(&mut app);
4422 parent.append(&mut app, a);
4423 parent.append(&mut app, b);
4424 assert_eq!(parent.first_child(&app), Some(a));
4425 assert_eq!(parent.last_child(&app), Some(b));
4426 assert_eq!(a.next_sibling(&app), Some(b));
4427 assert_eq!(b.previous_sibling(&app), Some(a));
4428 assert_eq!(a.parent(&app), Some(parent));
4429 assert_eq!(a.depth(&app), 1);
4430 assert_eq!(a.debug_handle_count(&app), 1, "the parent handle");
4431 }
4432
4433 #[test]
4434 fn a_layer_is_disposed_when_its_last_handle_is_released() {
4435 let cell = AppCell::new();
4436 let mut app = cell.borrow_mut();
4437 let layer = offset_layer(&mut app);
4438 let handle = app.create(LayerHandle::<AnyLayer>::new());
4439 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(layer));
4440 assert_eq!(layer.debug_handle_count(&app), 1);
4441 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4442 assert!(layer.debug_disposed(&app));
4443 assert!(app.contains(layer.id()), "readable until the checkpoint");
4444 drop(app);
4445 cell.checkpoint();
4446 assert!(
4447 !cell.borrow().contains(layer.id()),
4448 "dispose released the tree's part of the arena entry"
4449 );
4450 }
4451
4452 #[test]
4453 fn removing_a_child_releases_the_parent_handle_and_disposes_it() {
4454 let cell = AppCell::new();
4455 let mut app = cell.borrow_mut();
4456 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4457 let child = offset_layer(&mut app);
4458 parent.append(&mut app, child);
4459 child.remove(&mut app);
4460 assert!(!parent.has_children(&app));
4461 assert!(child.debug_disposed(&app));
4462 }
4463
4464 #[test]
4465 fn a_child_kept_by_another_handle_survives_removal() {
4466 let cell = AppCell::new();
4467 let mut app = cell.borrow_mut();
4468 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4469 let child = offset_layer(&mut app);
4470 let handle = app.create(LayerHandle::<AnyLayer>::new());
4471 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(child));
4472 parent.append(&mut app, child);
4473 child.remove(&mut app);
4474 assert!(!child.debug_disposed(&app));
4475 assert_eq!(child.parent(&app), None);
4476 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4477 assert!(child.debug_disposed(&app));
4478 }
4479
4480 #[test]
4481 fn attach_and_detach_walk_the_subtree() {
4482 let cell = AppCell::new();
4483 let mut app = cell.borrow_mut();
4484 let owner = app.create(());
4485 let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4486 let child = offset_layer(&mut app);
4487 root.append(&mut app, child);
4488 root.as_layer().attach(&mut app, owner.id());
4489 assert!(child.attached(&app));
4490 let late = offset_layer(&mut app);
4491 root.append(&mut app, late);
4492 assert!(
4493 late.attached(&app),
4494 "appending to an attached tree attaches"
4495 );
4496 root.as_layer().detach(&mut app);
4497 assert!(!child.attached(&app));
4498 assert!(!late.attached(&app));
4499 }
4500
4501 #[test]
4502 fn disposing_a_container_disposes_children_it_alone_held() {
4503 let cell = AppCell::new();
4504 let mut app = cell.borrow_mut();
4505 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4506 let child = offset_layer(&mut app);
4507 parent.append(&mut app, child);
4508 let handle = app.create(LayerHandle::<AnyContainerLayer>::new());
4509 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(parent));
4510 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4511 assert!(parent.as_layer().debug_disposed(&app));
4512 assert!(child.debug_disposed(&app));
4513 }
4514
4515 #[test]
4516 fn a_picture_layer_is_a_leaf_that_holds_its_picture() {
4517 let cell = AppCell::new();
4518 let mut app = cell.borrow_mut();
4519 let layer = PictureLayer::new(&mut app, Rect::from_ltwh(0.0, 0.0, 10.0, 10.0));
4520 let picture = Arc::new(waft_embedder::Canvas::new().build());
4521 layer.set_picture(&mut app, Some(picture));
4522 assert!(layer.picture(&app).is_some());
4523 assert!(layer.as_layer().as_container_layer().is_none());
4524 let mut builder = SceneBuilder::new();
4525 layer.as_layer().add_to_scene(&mut app, &mut builder);
4526 let _scene = builder.build();
4527 }
4528
4529 #[test]
4530 fn composition_callbacks_fire_on_build_scene_and_detach() {
4531 use std::cell::Cell;
4532 let cell = AppCell::new();
4533 let mut app = cell.borrow_mut();
4534 let owner = app.create(());
4535 let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4536 let child = offset_layer(&mut app);
4537 root.append(&mut app, child);
4538 let fired = Rc::new(Cell::new(0));
4539 let remove = {
4540 let fired = Rc::clone(&fired);
4541 child
4542 .add_composition_callback(&mut app, Rc::new(move |_, _| fired.set(fired.get() + 1)))
4543 };
4544 assert!(root.as_layer().subtree_has_composition_callbacks(&app));
4545 let _scene = root.build_scene(&mut app, SceneBuilder::new());
4546 assert_eq!(fired.get(), 1);
4547 root.as_layer().attach(&mut app, owner.id());
4548 root.as_layer().detach(&mut app);
4549 assert_eq!(fired.get(), 2, "detach fires once more");
4550 remove(&mut app);
4551 assert!(!root.as_layer().subtree_has_composition_callbacks(&app));
4552 }
4553
4554 #[test]
4555 fn find_walks_children_back_to_front_through_offsets() {
4556 struct Tag(&'static str);
4557 struct Annotated {
4558 layer: LayerData,
4559 tag: Rc<Tag>,
4560 }
4561 impl Layer for Annotated {
4562 crate::layer_accessors!();
4563 fn find_annotations(
4564 self: Handle<Self>,
4565 app: &App,
4566 result: &mut AnnotationSearch,
4567 local_position: Offset,
4568 _only_first: bool,
4569 ) -> bool {
4570 let tag = Rc::clone(&app.get(self).tag);
4571 if result.accepts(&*tag) {
4572 result.add(tag, local_position);
4573 }
4574 false
4575 }
4576 fn add_to_scene(self: Handle<Self>, _app: &mut App, _builder: &mut SceneBuilder) {}
4577 }
4578 let cell = AppCell::new();
4579 let mut app = cell.borrow_mut();
4580 let root = OffsetLayer::new(&mut app, Offset::new(10.0, 0.0)).as_container_layer();
4581 for name in ["back", "front"] {
4582 let layer = app.create(Annotated {
4583 layer: LayerData::new(),
4584 tag: Rc::new(Tag(name)),
4585 });
4586 root.append(&mut app, layer.as_layer());
4587 }
4588 let found = root.as_layer().find::<Tag>(&app, Offset::new(15.0, 5.0));
4589 assert_eq!(found.map(|tag| tag.0), Some("front"));
4590 let all = root
4591 .as_layer()
4592 .find_all_annotations::<Tag>(&app, Offset::new(15.0, 5.0));
4593 assert_eq!(all.entries().len(), 2);
4594 assert_eq!(all.entries()[0].local_position, Offset::new(5.0, 5.0));
4595 assert!(root.as_layer().find::<String>(&app, Offset::ZERO).is_none());
4596 }
4597
4598 fn drawn_layer(app: &mut App) -> AnyLayer {
4603 let square = Rect::from_ltwh(0.0, 0.0, 10.0, 10.0);
4604 let mut canvas = waft_embedder::Canvas::new();
4605 canvas.draw_rect(square, &waft_embedder::Paint::default());
4606 let layer = PictureLayer::new(app, square);
4607 layer.set_picture(app, Some(Arc::new(canvas.build())));
4608 layer.as_layer()
4609 }
4610
4611 fn retained_tree(app: &mut App) -> (Handle<OffsetLayer>, Handle<OpacityLayer>) {
4612 let root = OffsetLayer::new(app, Offset::ZERO);
4613 let opacity = OpacityLayer::new(app);
4614 opacity.set_alpha(app, 128);
4615 let leaf = drawn_layer(app);
4616 opacity.as_container_layer().append(app, leaf);
4617 root.as_container_layer().append(app, opacity.as_layer());
4618 let _scene = root
4619 .as_container_layer()
4620 .build_scene(app, SceneBuilder::new());
4621 (root, opacity)
4622 }
4623
4624 #[test]
4627 fn an_embedded_layer_is_retained_and_its_composition_layer_placed_every_frame() {
4628 let cell = AppCell::new();
4629 let mut app = cell.borrow_mut();
4630 let root = OffsetLayer::new(&mut app, Offset::new(10.0, 5.0));
4631 let inner = OffsetLayer::new(&mut app, Offset::ZERO);
4632 let composition_layer = waft_embedder::test_support::idle_layer();
4633 let layer = EmbeddedLayer::new(
4634 &mut app,
4635 Arc::clone(&composition_layer),
4636 Rect::from_ltwh(1.0, 2.0, 30.0, 20.0),
4637 );
4638 inner
4639 .as_container_layer()
4640 .append(&mut app, layer.as_layer());
4641 root.as_container_layer().append(&mut app, inner.as_layer());
4642 let mut first_engine_layer = None;
4643 for _frame in 0..2 {
4644 let scene = root
4645 .as_container_layer()
4646 .build_scene(&mut app, SceneBuilder::new());
4647 let slices = waft_embedder::slices(&scene, |_| None);
4648 let (placed, placement) = slices.composition_layers().next().expect("placed");
4649 assert!(Arc::ptr_eq(placed, &composition_layer));
4650 assert_eq!(placement.bounds(), Rect::from_ltwh(11.0, 7.0, 30.0, 20.0));
4651 let engine_layer = inner.as_layer().engine_layer(&app).expect("recorded");
4652 let first = first_engine_layer.get_or_insert_with(|| Arc::clone(&engine_layer));
4653 assert!(Arc::ptr_eq(first, &engine_layer), "retained");
4654 }
4655 assert!(!layer.as_layer().always_needs_add_to_scene(&app));
4656 }
4657
4658 #[test]
4659 fn an_unchanged_subtree_is_retained_across_scenes() {
4660 let cell = AppCell::new();
4661 let mut app = cell.borrow_mut();
4662 let (root, opacity) = retained_tree(&mut app);
4663 let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4664 assert!(!opacity.as_layer().needs_add_to_scene(&app));
4665
4666 let scene = root
4667 .as_container_layer()
4668 .build_scene(&mut app, SceneBuilder::new());
4669 let retained = opacity.as_layer().engine_layer(&app).expect("recorded");
4670 assert!(
4671 Arc::ptr_eq(&recorded, &retained),
4672 "the same node is retained"
4673 );
4674 let root_node = root
4675 .as_layer()
4676 .engine_layer(&app)
4677 .expect("the root is built again");
4678 assert!(
4679 root_node.children.iter().any(|child| matches!(
4680 child,
4681 waft_embedder::Layer::Container(container) if Arc::ptr_eq(container, &retained)
4682 )),
4683 "added again: {:?}",
4684 root_node.children
4685 );
4686 assert_eq!(
4687 waft_embedder::flattened_ops(
4688 &waft_embedder::slices(&scene, |_| None).picture_with_room()
4689 )
4690 .iter()
4691 .filter(|op| matches!(op, waft_embedder::valo::Op::SaveLayer { .. }))
4692 .count(),
4693 1,
4694 "the retained opacity layer still draws"
4695 );
4696 }
4697
4698 #[test]
4699 fn a_changed_property_re_records_the_subtree() {
4700 let cell = AppCell::new();
4701 let mut app = cell.borrow_mut();
4702 let (root, opacity) = retained_tree(&mut app);
4703 let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4704
4705 opacity.set_alpha(&mut app, 200);
4706 assert!(opacity.as_layer().needs_add_to_scene(&app));
4707 let _scene = root
4708 .as_container_layer()
4709 .build_scene(&mut app, SceneBuilder::new());
4710 let again = opacity.as_layer().engine_layer(&app).expect("recorded");
4711 assert!(
4712 !Arc::ptr_eq(&recorded, &again),
4713 "a new node for the new alpha"
4714 );
4715 assert!(!opacity.as_layer().needs_add_to_scene(&app));
4716 }
4717
4718 #[test]
4721 fn an_image_filter_layer_pushes_its_filter_at_its_offset() {
4722 let cell = AppCell::new();
4723 let mut app = cell.borrow_mut();
4724 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4725 let filtered = ImageFilterLayer::new(&mut app);
4726 filtered.set_image_filter(&mut app, ImageFilter::blur(4.0, 4.0));
4727 filtered.set_offset(&mut app, Offset::new(3.0, 4.0));
4728 assert!(Layer::supports_rasterization(filtered, &app));
4729 let leaf = drawn_layer(&mut app);
4730 filtered.as_container_layer().append(&mut app, leaf);
4731 root.as_container_layer()
4732 .append(&mut app, filtered.as_layer());
4733 let _scene = root
4734 .as_container_layer()
4735 .build_scene(&mut app, SceneBuilder::new());
4736 let recorded = filtered.as_layer().engine_layer(&app).expect("recorded");
4737 assert_eq!(
4738 recorded.effect,
4739 waft_embedder::Effect::ImageFilter {
4740 filter: ImageFilter::blur(4.0, 4.0),
4741 offset: Offset::new(3.0, 4.0),
4742 }
4743 );
4744 let info = debug_info(filtered, &app);
4745 assert!(info.contains(&"offset: Offset(3.0, 4.0)".to_owned()));
4746 assert!(info.contains(&"imageFilter: ImageFilter.blur(4, 4, unspecified)".to_owned()));
4747 filtered.set_image_filter(&mut app, ImageFilter::blur(4.0, 4.0));
4748 assert!(!filtered.as_layer().needs_add_to_scene(&app));
4749 filtered.set_image_filter(&mut app, ImageFilter::blur(5.0, 5.0));
4750 assert!(filtered.as_layer().needs_add_to_scene(&app));
4751 }
4752
4753 #[test]
4754 fn appending_a_child_marks_the_parent_and_its_ancestors_at_build() {
4755 let cell = AppCell::new();
4756 let mut app = cell.borrow_mut();
4757 let (root, opacity) = retained_tree(&mut app);
4758 assert!(!root.as_layer().needs_add_to_scene(&app));
4759
4760 let leaf = offset_layer(&mut app);
4761 opacity.as_container_layer().append(&mut app, leaf);
4762 assert!(opacity.as_layer().needs_add_to_scene(&app));
4763 assert!(
4764 !root.as_layer().needs_add_to_scene(&app),
4765 "the mark does not climb until the scene is built"
4766 );
4767 root.as_layer().update_subtree_needs_add_to_scene(&mut app);
4768 assert!(root.as_layer().needs_add_to_scene(&app));
4769 }
4770
4771 #[test]
4772 fn a_follower_layer_always_re_records() {
4773 let cell = AppCell::new();
4774 let mut app = cell.borrow_mut();
4775 let link = LayerLink::new(&mut app);
4776 let follower = FollowerLayer::new(&mut app, link);
4777 let child = offset_layer(&mut app);
4778 follower.as_container_layer().append(&mut app, child);
4779 for _ in 0..2 {
4780 let _scene = follower
4781 .as_container_layer()
4782 .build_scene(&mut app, SceneBuilder::new());
4783 assert!(
4784 follower.as_layer().needs_add_to_scene(&app)
4785 || follower.as_layer().always_needs_add_to_scene(&app)
4786 );
4787 }
4788 let first = follower.as_layer().engine_layer(&app).expect("recorded");
4789 let _scene = follower
4790 .as_container_layer()
4791 .build_scene(&mut app, SceneBuilder::new());
4792 let second = follower.as_layer().engine_layer(&app).expect("recorded");
4793 assert!(!Arc::ptr_eq(&first, &second), "never retained");
4794 }
4795
4796 fn tag(app: &mut App, n: u32) -> Handle<AnnotatedRegionLayer> {
4797 AnnotatedRegionLayer::new(app, Rc::new(n))
4798 }
4799
4800 #[test]
4803 fn an_annotated_region_layer_prints_its_size_offset_and_opaque() {
4804 let cell = AppCell::new();
4805 let mut app = cell.borrow_mut();
4806 let plain = tag(&mut app, 1);
4807 let info = debug_info(plain, &app);
4808 assert!(!info.iter().any(|property| property.starts_with("size")));
4809 assert!(info.contains(&"offset: Offset(0.0, 0.0)".to_owned()));
4812 assert!(!info.iter().any(|property| property.starts_with("opaque")));
4813
4814 let layer = tag(&mut app, 2);
4815 layer.set_size(&mut app, Some(Size::new(20.0, 30.0)));
4816 layer.set_offset(&mut app, Offset::new(4.0, 5.0));
4817 layer.set_opaque(&mut app, true);
4818 let info = debug_info(layer, &app);
4819 assert!(info.contains(&"size: Size(20.0, 30.0)".to_owned()));
4820 assert!(info.contains(&"offset: Offset(4.0, 5.0)".to_owned()));
4821 assert!(info.contains(&"opaque: true".to_owned()));
4822 assert!(!info.iter().any(|property| property.starts_with("value")));
4823 }
4824
4825 #[test]
4826 fn clip_layers_reject_annotations_outside_the_clip() {
4827 let cell = AppCell::new();
4828 let mut app = cell.borrow_mut();
4829 let rect = ClipRectLayer::new(&mut app);
4830 rect.set_clip_rect(&mut app, Some(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0)));
4831 let child = tag(&mut app, 7);
4832 rect.as_container_layer().append(&mut app, child.as_layer());
4833 assert_eq!(
4834 rect.as_layer()
4835 .find::<u32>(&app, Offset::new(10.0, 10.0))
4836 .as_deref(),
4837 Some(&7)
4838 );
4839 assert!(
4840 rect.as_layer()
4841 .find::<u32>(&app, Offset::new(60.0, 10.0))
4842 .is_none(),
4843 "outside the clip"
4844 );
4845
4846 let rrect = ClipRRectLayer::new(&mut app);
4847 rrect.set_clip_rrect(
4848 &mut app,
4849 Some(RRect::from_rect_and_radius(
4850 Rect::from_ltwh(0.0, 0.0, 50.0, 50.0),
4851 waft_embedder::Radius::circular(4.0),
4852 )),
4853 );
4854 let child = tag(&mut app, 8);
4855 rrect
4856 .as_container_layer()
4857 .append(&mut app, child.as_layer());
4858 assert_eq!(
4859 rrect
4860 .as_layer()
4861 .find::<u32>(&app, Offset::new(10.0, 10.0))
4862 .as_deref(),
4863 Some(&8)
4864 );
4865 assert!(
4866 rrect
4867 .as_layer()
4868 .find::<u32>(&app, Offset::new(60.0, 10.0))
4869 .is_none()
4870 );
4871
4872 let mut path = waft_embedder::PathBuilder::new();
4873 path.rect(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0).into());
4874 let clip_path = ClipPathLayer::new(&mut app);
4875 clip_path.set_clip_path(&mut app, Some(path.build().into()));
4876 let child = tag(&mut app, 9);
4877 clip_path
4878 .as_container_layer()
4879 .append(&mut app, child.as_layer());
4880 assert_eq!(
4881 clip_path
4882 .as_layer()
4883 .find::<u32>(&app, Offset::new(10.0, 10.0))
4884 .as_deref(),
4885 Some(&9)
4886 );
4887 assert!(
4888 clip_path
4889 .as_layer()
4890 .find::<u32>(&app, Offset::new(60.0, 10.0))
4891 .is_none()
4892 );
4893 }
4894
4895 #[test]
4896 fn transform_layer_transforms_the_annotation_position() {
4897 let cell = AppCell::new();
4898 let mut app = cell.borrow_mut();
4899 let layer = TransformLayer::new(&mut app);
4900 layer.set_transform(&mut app, Matrix4::translation(10.0, 0.0));
4901 let region = tag(&mut app, 7);
4902 region.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4903 layer
4904 .as_container_layer()
4905 .append(&mut app, region.as_layer());
4906 assert!(
4907 layer
4908 .as_layer()
4909 .find::<u32>(&app, Offset::new(15.0, 5.0))
4910 .is_some()
4911 );
4912 assert!(
4913 layer
4914 .as_layer()
4915 .find::<u32>(&app, Offset::new(5.0, 5.0))
4916 .is_none(),
4917 "left of the translated region"
4918 );
4919 }
4920
4921 #[test]
4922 fn opacity_layer_build_scene_succeeds_at_255_and_128() {
4923 let cell = AppCell::new();
4924 let mut app = cell.borrow_mut();
4925 for alpha in [255, 128] {
4926 let layer = OpacityLayer::new(&mut app);
4927 layer.set_alpha(&mut app, alpha);
4928 let child = OffsetLayer::new(&mut app, Offset::ZERO);
4929 layer
4930 .as_container_layer()
4931 .append(&mut app, child.as_layer());
4932 let _scene = layer
4933 .as_container_layer()
4934 .build_scene(&mut app, SceneBuilder::new());
4935 }
4936 let empty = OpacityLayer::new(&mut app);
4937 empty.set_alpha(&mut app, 128);
4938 let _scene = empty
4939 .as_container_layer()
4940 .build_scene(&mut app, SceneBuilder::new());
4941 }
4942
4943 #[test]
4944 fn layer_link_register_unregister_and_leader_getter() {
4945 let cell = AppCell::new();
4946 let mut app = cell.borrow_mut();
4947 let owner = app.create(());
4948 let link = LayerLink::new(&mut app);
4949 assert!(link.leader(&app).is_none());
4950 let leader = LeaderLayer::new(&mut app, link.clone());
4951 leader.as_layer().attach(&mut app, owner.id());
4952 assert_eq!(link.leader(&app), Some(leader));
4953 leader.as_layer().detach(&mut app);
4954 assert!(link.leader(&app).is_none());
4955 }
4956
4957 #[test]
4958 fn leader_layer_attach_registers_and_detach_unregisters() {
4959 let cell = AppCell::new();
4960 let mut app = cell.borrow_mut();
4961 let owner = app.create(());
4962 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4963 let link = LayerLink::new(&mut app);
4964 let leader = LeaderLayer::new(&mut app, link.clone());
4965 root.as_container_layer()
4966 .append(&mut app, leader.as_layer());
4967 root.as_layer().attach(&mut app, owner.id());
4968 assert_eq!(link.leader(&app), Some(leader));
4969 root.as_layer().detach(&mut app);
4970 assert!(link.leader(&app).is_none());
4971 }
4972
4973 #[test]
4974 fn a_replaced_leader_leaves_the_links_new_leader_in_place() {
4975 let cell = AppCell::new();
4976 let mut app = cell.borrow_mut();
4977 let owner = app.create(());
4978 let link = LayerLink::new(&mut app);
4979 let leader1 = LeaderLayer::new(&mut app, link.clone());
4980 let leader2 = LeaderLayer::new(&mut app, link.clone());
4981 leader1.as_layer().attach(&mut app, owner.id());
4982 leader2.as_layer().attach(&mut app, owner.id());
4983 assert_eq!(link.leader(&app), Some(leader2));
4984 leader2.as_layer().detach(&mut app);
4985 leader1.as_layer().detach(&mut app);
4986 assert!(link.leader(&app).is_none());
4987 }
4988
4989 #[test]
4990 fn switching_the_link_of_an_attached_leader_does_not_crash() {
4991 let cell = AppCell::new();
4992 let mut app = cell.borrow_mut();
4993 let owner = app.create(());
4994 let link = LayerLink::new(&mut app);
4995 let leader = LeaderLayer::new(&mut app, link.clone());
4996 leader.as_layer().attach(&mut app, owner.id());
4997 let link2 = LayerLink::new(&mut app);
4998 leader.set_link(&mut app, link2.clone());
4999 leader.as_layer().detach(&mut app);
5000 assert_eq!(leader.link(&app), link2);
5001 assert!(link.leader(&app).is_none());
5002 assert!(link2.leader(&app).is_none());
5003 }
5004
5005 #[test]
5006 fn follower_get_last_transform_after_build_scene_matches_the_leader_offset() {
5007 let cell = AppCell::new();
5008 let mut app = cell.borrow_mut();
5009 let owner = app.create(());
5010 let root = OffsetLayer::new(&mut app, Offset::ZERO);
5011 let link = LayerLink::new(&mut app);
5012 let leader = LeaderLayer::new(&mut app, link.clone());
5013 leader.set_offset(&mut app, Offset::new(10.0, 20.0));
5014 let follower = FollowerLayer::new(&mut app, link);
5015 root.as_container_layer()
5016 .append(&mut app, leader.as_layer());
5017 root.as_container_layer()
5018 .append(&mut app, follower.as_layer());
5019 root.as_layer().attach(&mut app, owner.id());
5020 let _scene = root
5021 .as_container_layer()
5022 .build_scene(&mut app, SceneBuilder::new());
5023 assert_eq!(
5024 follower.get_last_transform(&app).unwrap(),
5025 Matrix4::translation(10.0, 20.0)
5026 );
5027 let info = debug_info(follower, &app);
5028 assert!(
5029 info.iter()
5030 .any(|property| property.contains("link: LayerLink#")),
5031 "{info:?}"
5032 );
5033 assert!(
5034 info.iter()
5035 .any(|property| property.contains("[0] 1.0,0.0,0.0,10.0")),
5036 "{info:?}"
5037 );
5038 }
5039
5040 #[test]
5041 fn follower_with_show_when_unlinked_false_pushes_nothing() {
5042 let cell = AppCell::new();
5043 let mut app = cell.borrow_mut();
5044 let link = LayerLink::new(&mut app);
5045 let follower = FollowerLayer::new(&mut app, link);
5046 follower.set_show_when_unlinked(&mut app, false);
5047 let child = offset_layer(&mut app);
5048 follower.as_container_layer().append(&mut app, child);
5049 let _scene = follower
5050 .as_container_layer()
5051 .build_scene(&mut app, SceneBuilder::new());
5052 assert!(follower.get_last_transform(&app).is_none());
5053 }
5054
5055 #[test]
5056 fn annotated_region_layer_find_with_size_offset_and_opaque() {
5057 let cell = AppCell::new();
5058 let mut app = cell.borrow_mut();
5059 let root = OffsetLayer::new(&mut app, Offset::ZERO);
5060 let behind = tag(&mut app, 1);
5061 let front = tag(&mut app, 2);
5062 front.set_opaque(&mut app, true);
5063 root.as_container_layer()
5064 .append(&mut app, behind.as_layer());
5065 root.as_container_layer().append(&mut app, front.as_layer());
5066 let result = root
5067 .as_layer()
5068 .find_all_annotations::<u32>(&app, Offset::ZERO);
5069 assert_eq!(
5070 result
5071 .annotations()
5072 .map(|value| **value)
5073 .collect::<Vec<_>>(),
5074 vec![2],
5075 "an opaque region hides its siblings"
5076 );
5077
5078 let root = OffsetLayer::new(&mut app, Offset::ZERO);
5079 let first = tag(&mut app, 1);
5080 let second = tag(&mut app, 2);
5081 root.as_container_layer().append(&mut app, first.as_layer());
5082 root.as_container_layer()
5083 .append(&mut app, second.as_layer());
5084 let result = root
5085 .as_layer()
5086 .find_all_annotations::<u32>(&app, Offset::ZERO);
5087 assert_eq!(
5088 result
5089 .annotations()
5090 .map(|value| **value)
5091 .collect::<Vec<_>>(),
5092 vec![2, 1],
5093 "front to back when neither is opaque"
5094 );
5095
5096 let sized = tag(&mut app, 3);
5097 sized.set_size(&mut app, Some(Size::new(20.0, 20.0)));
5098 sized.set_offset(&mut app, Offset::new(90.0, 90.0));
5099 assert!(
5100 sized
5101 .as_layer()
5102 .find::<u32>(&app, Offset::new(95.0, 95.0))
5103 .is_some()
5104 );
5105 assert!(
5106 sized.as_layer().find::<u32>(&app, Offset::ZERO).is_none(),
5107 "outside the sized region"
5108 );
5109 }
5110}