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, Clip, EngineLayer, ImageFilter, Matrix4, Offset, Picture, RRect, Rect, Scene,
24 SceneBuilder, Size,
25};
26use waft_embedder::{CompositionLayer, VideoFrameReader};
27use waft_foundation::{App, Handle, HandleId, Ref};
28use waft_gestures::remove_perspective_transform;
29use waft_scheduler::{FrameCallback, SchedulerBinding};
30
31#[derive(Debug)]
37pub struct AnnotationEntry<T> {
38 pub annotation: Rc<T>,
40 pub local_position: Offset,
42}
43
44impl<T> AnnotationEntry<T> {
45 pub fn new(annotation: Rc<T>, local_position: Offset) -> AnnotationEntry<T> {
47 AnnotationEntry {
48 annotation,
49 local_position,
50 }
51 }
52}
53
54#[derive(Debug)]
61pub struct AnnotationResult<T> {
62 entries: Vec<AnnotationEntry<T>>,
63}
64
65impl<T> AnnotationResult<T> {
66 pub fn new() -> AnnotationResult<T> {
68 AnnotationResult {
69 entries: Vec::new(),
70 }
71 }
72
73 pub fn add(&mut self, entry: AnnotationEntry<T>) {
78 self.entries.push(entry);
79 }
80
81 pub fn entries(&self) -> &[AnnotationEntry<T>] {
85 &self.entries
86 }
87
88 pub fn annotations(&self) -> impl Iterator<Item = &Rc<T>> {
93 self.entries.iter().map(|entry| &entry.annotation)
94 }
95}
96
97impl<T> Default for AnnotationResult<T> {
98 fn default() -> AnnotationResult<T> {
99 AnnotationResult::new()
100 }
101}
102
103#[derive(Debug)]
108pub struct AnnotationSearch {
109 searched: TypeId,
110 entries: Vec<(Rc<dyn Any>, Offset)>,
111}
112
113impl AnnotationSearch {
114 fn new<S: 'static>() -> AnnotationSearch {
115 AnnotationSearch {
116 searched: TypeId::of::<S>(),
117 entries: Vec::new(),
118 }
119 }
120
121 pub fn accepts(&self, annotation: &dyn Any) -> bool {
123 annotation.type_id() == self.searched
124 }
125
126 pub fn add(&mut self, annotation: Rc<dyn Any>, local_position: Offset) {
129 debug_assert!(self.accepts(&*annotation));
130 self.entries.push((annotation, local_position));
131 }
132
133 pub fn is_empty(&self) -> bool {
135 self.entries.is_empty()
136 }
137
138 fn into_result<S: 'static>(self) -> AnnotationResult<S> {
139 let mut result = AnnotationResult::new();
140 for (annotation, local_position) in self.entries {
141 let annotation = annotation
142 .downcast::<S>()
143 .expect("an accepted annotation is the searched type");
144 result.add(AnnotationEntry::new(annotation, local_position));
145 }
146 result
147 }
148}
149
150pub type CompositionCallback = Rc<dyn Fn(&mut App, AnyLayer)>;
152
153static NEXT_CALLBACK_ID: AtomicU64 = AtomicU64::new(0);
154
155pub struct LayerData {
158 callbacks: Vec<(u64, CompositionCallback)>,
159 composition_callback_count: i32,
160 debug_mutations_locked: bool,
161 parent_handle: LayerHandle<AnyLayer>,
168 ref_count: u32,
170 debug_disposed: bool,
171 parent: Option<AnyContainerLayer>,
172 owner: Option<HandleId>,
173 depth: i32,
174 next_sibling: Option<AnyLayer>,
175 previous_sibling: Option<AnyLayer>,
176 needs_add_to_scene: bool,
180 engine_layer: Option<EngineLayer>,
183}
184
185impl LayerData {
186 pub const fn new() -> LayerData {
188 LayerData {
189 callbacks: Vec::new(),
190 composition_callback_count: 0,
191 debug_mutations_locked: false,
192 parent_handle: LayerHandle::new(),
193 ref_count: 0,
194 debug_disposed: false,
195 parent: None,
196 owner: None,
197 depth: 0,
198 next_sibling: None,
199 previous_sibling: None,
200 needs_add_to_scene: true,
201 engine_layer: None,
202 }
203 }
204}
205
206impl Default for LayerData {
207 fn default() -> LayerData {
208 LayerData::new()
209 }
210}
211
212impl Debug for LayerData {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 f.debug_struct("Layer")
215 .field("owner", &self.owner)
216 .field("handles", &self.ref_count)
217 .finish_non_exhaustive()
218 }
219}
220
221#[macro_export]
226macro_rules! layer_accessors {
227 () => {
228 fn layer_data(
229 self: ::waft_foundation::Handle<Self>,
230 app: &::waft_foundation::App,
231 ) -> &$crate::LayerData {
232 &app.get(self).layer
233 }
234 fn layer_data_mut(
235 self: ::waft_foundation::Handle<Self>,
236 app: &mut ::waft_foundation::App,
237 ) -> &mut $crate::LayerData {
238 &mut app.get_mut(self).layer
239 }
240 };
241 (container) => {
242 $crate::layer_accessors!();
243 const AS_CONTAINER: Option<fn() -> &'static $crate::ContainerLayerVTable> =
244 Some(|| const { &$crate::ContainerLayerVTable::of::<Self>() });
245 };
246}
247
248pub trait Layer: Sized + 'static {
274 fn layer_data(self: Handle<Self>, app: &App) -> &LayerData;
276
277 fn layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut LayerData;
279
280 const AS_CONTAINER: Option<fn() -> &'static ContainerLayerVTable> = None;
283
284 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
291 let _ = (self, app);
292 true
293 }
294
295 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
297 let _ = (self, app);
298 None
299 }
300
301 fn always_needs_add_to_scene(self: Handle<Self>, app: &App) -> bool {
303 let _ = (self, app);
304 false
305 }
306
307 fn dispose(self: Handle<Self>, app: &mut App) {
326 LayerBase::dispose(self, app);
327 }
328
329 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
337 LayerBase::attach(self, app, owner);
338 }
339
340 fn detach(self: Handle<Self>, app: &mut App) {
348 LayerBase::detach(self, app);
349 }
350
351 fn redepth_children(self: Handle<Self>, app: &mut App) {
356 let _ = (self, app);
359 }
360
361 fn find_annotations(
382 self: Handle<Self>,
383 app: &App,
384 result: &mut AnnotationSearch,
385 local_position: Offset,
386 only_first: bool,
387 ) -> bool {
388 let _ = (self, app, result, local_position, only_first);
389 false
390 }
391
392 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder);
394
395 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
397 LayerBase::fire_composition_callbacks(self, app, include_children);
398 }
399}
400
401pub trait LayerBase: Layer {
404 fn dispose(self: Handle<Self>, app: &mut App) {
406 let data = self.layer_data_mut(app);
407 debug_assert!(!data.debug_mutations_locked);
408 debug_assert!(
409 !data.debug_disposed,
410 "Layers must only be disposed once. This is typically handled by LayerHandle. \
411 Subclasses should not directly call dispose, except to call LayerBase::dispose in \
412 an overridden dispose method. Tests must only call dispose once."
413 );
414 debug_assert!(
415 data.ref_count == 0,
416 "Do not directly call dispose on a layer. Instead, use a LayerHandle."
417 );
418 data.debug_disposed = true;
419 app.release_tree_node(self);
421 }
422
423 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
425 let data = self.layer_data_mut(app);
426 debug_assert!(data.owner.is_none());
427 data.owner = Some(owner);
428 }
429
430 fn detach(self: Handle<Self>, app: &mut App) {
432 let data = self.layer_data_mut(app);
433 debug_assert!(data.owner.is_some());
434 data.owner = None;
435 let this = self.as_layer();
436 debug_assert!(
437 this.parent(app)
438 .is_none_or(|parent| this.attached(app) == parent.as_layer().attached(app))
439 );
440 }
441
442 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
444 let _ = include_children;
445 let this = self.as_layer();
446 let callbacks: Vec<CompositionCallback> = self
447 .layer_data(app)
448 .callbacks
449 .iter()
450 .map(|(_, callback)| Rc::clone(callback))
451 .collect();
452 for callback in callbacks {
453 this.run_composition_callback(app, &callback);
454 }
455 }
456}
457
458impl<T: Layer> LayerBase for T {}
459
460fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
462 Handle::from_id(id)
463}
464
465#[doc(hidden)]
471pub struct LayerVTable {
472 layer_data: fn(&App, HandleId) -> &LayerData,
473 layer_data_mut: fn(&mut App, HandleId) -> &mut LayerData,
474 supports_rasterization: fn(&App, HandleId) -> bool,
475 describe_clip_bounds: fn(&App, HandleId) -> Option<Rect>,
476 always_needs_add_to_scene: fn(&App, HandleId) -> bool,
477 dispose: fn(&mut App, HandleId),
478 attach: fn(&mut App, HandleId, HandleId),
479 detach: fn(&mut App, HandleId),
480 redepth_children: fn(&mut App, HandleId),
481 find_annotations: fn(&App, HandleId, &mut AnnotationSearch, Offset, bool) -> bool,
482 add_to_scene: fn(&mut App, HandleId, &mut SceneBuilder),
483 fire_composition_callbacks: fn(&mut App, HandleId, bool),
484 as_container: Option<fn() -> &'static ContainerLayerVTable>,
485}
486
487impl LayerVTable {
488 pub const fn of<T: Layer>() -> LayerVTable {
489 LayerVTable {
490 layer_data: |app, id| T::layer_data(resolve(id), app),
491 layer_data_mut: |app, id| T::layer_data_mut(resolve(id), app),
492 supports_rasterization: |app, id| T::supports_rasterization(resolve(id), app),
493 describe_clip_bounds: |app, id| T::describe_clip_bounds(resolve(id), app),
494 always_needs_add_to_scene: |app, id| T::always_needs_add_to_scene(resolve(id), app),
495 dispose: |app, id| T::dispose(resolve(id), app),
496 attach: |app, id, owner| T::attach(resolve(id), app, owner),
497 detach: |app, id| T::detach(resolve(id), app),
498 redepth_children: |app, id| T::redepth_children(resolve(id), app),
499 find_annotations: |app, id, result, local_position, only_first| {
500 T::find_annotations(resolve(id), app, result, local_position, only_first)
501 },
502 add_to_scene: |app, id, builder| T::add_to_scene(resolve(id), app, builder),
503 fire_composition_callbacks: |app, id, include_children| {
504 T::fire_composition_callbacks(resolve(id), app, include_children)
505 },
506 as_container: T::AS_CONTAINER,
507 }
508 }
509}
510
511#[derive(Clone, Copy)]
516pub struct AnyLayer {
517 id: HandleId,
518 vtable: &'static LayerVTable,
519}
520
521impl PartialEq for AnyLayer {
522 fn eq(&self, other: &AnyLayer) -> bool {
523 self.id == other.id
524 }
525}
526
527impl Eq for AnyLayer {}
528
529impl Hash for AnyLayer {
530 fn hash<H: Hasher>(&self, state: &mut H) {
531 self.id.hash(state);
532 }
533}
534
535impl From<AnyLayer> for HandleId {
536 fn from(layer: AnyLayer) -> HandleId {
537 layer.id
538 }
539}
540
541impl Debug for AnyLayer {
542 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543 write!(f, "AnyLayer({:?})", self.id)
544 }
545}
546
547impl AnyLayer {
548 pub fn id(self) -> HandleId {
549 self.id
550 }
551
552 fn data(self, app: &App) -> &LayerData {
553 (self.vtable.layer_data)(app, self.id)
554 }
555
556 fn data_mut(self, app: &mut App) -> &mut LayerData {
557 (self.vtable.layer_data_mut)(app, self.id)
558 }
559
560 pub fn as_container_layer(self) -> Option<AnyContainerLayer> {
562 self.vtable
563 .as_container
564 .map(|vtable| AnyContainerLayer::from_vtable(self.id, vtable()))
565 }
566
567 pub fn subtree_has_composition_callbacks(self, app: &App) -> bool {
573 self.data(app).composition_callback_count > 0
574 }
575
576 fn update_subtree_composition_observer_count(self, app: &mut App, delta: i32) {
577 debug_assert!(delta != 0);
578 let data = self.data_mut(app);
579 data.composition_callback_count += delta;
580 debug_assert!(data.composition_callback_count >= 0);
581 if let Some(parent) = data.parent {
582 parent
583 .as_layer()
584 .update_subtree_composition_observer_count(app, delta);
585 }
586 }
587
588 pub(crate) fn fire_composition_callbacks(self, app: &mut App, include_children: bool) {
590 (self.vtable.fire_composition_callbacks)(app, self.id, include_children);
591 }
592
593 fn run_composition_callback(self, app: &mut App, callback: &CompositionCallback) {
595 if cfg!(debug_assertions) {
596 self.data_mut(app).debug_mutations_locked = true;
597 }
598 callback(app, self);
599 if cfg!(debug_assertions) {
600 self.data_mut(app).debug_mutations_locked = false;
601 }
602 }
603
604 pub fn supports_rasterization(self, app: &App) -> bool {
606 (self.vtable.supports_rasterization)(app, self.id)
607 }
608
609 pub fn describe_clip_bounds(self, app: &App) -> Option<Rect> {
611 (self.vtable.describe_clip_bounds)(app, self.id)
612 }
613
614 pub fn add_composition_callback(
632 self,
633 app: &mut App,
634 callback: CompositionCallback,
635 ) -> Box<dyn FnOnce(&mut App)> {
636 self.update_subtree_composition_observer_count(app, 1);
637 let callback_id = NEXT_CALLBACK_ID.fetch_add(1, Ordering::Relaxed) + 1;
638 self.data_mut(app).callbacks.push((callback_id, callback));
639 let layer = self.id.keep(app);
641 Box::new(move |app: &mut App| {
642 let index = self
643 .data(app)
644 .callbacks
645 .iter()
646 .position(|(id, _)| *id == callback_id);
647 debug_assert!(self.debug_disposed(app) || index.is_some());
648 if let Some(index) = index {
649 self.data_mut(app).callbacks.remove(index);
650 }
651 self.update_subtree_composition_observer_count(app, -1);
652 drop(layer);
653 })
654 }
655
656 pub fn debug_disposed(self, app: &App) -> bool {
661 !app.contains(self.id) || self.data(app).debug_disposed
662 }
663
664 fn unref(self, app: &mut App) {
666 let data = self.data_mut(app);
667 debug_assert!(!data.debug_mutations_locked);
668 debug_assert!(data.ref_count > 0);
669 data.ref_count -= 1;
670 if data.ref_count == 0 {
671 self.dispose(app);
672 }
673 }
674
675 pub fn debug_handle_count(self, app: &App) -> u32 {
677 self.data(app).ref_count
678 }
679
680 pub fn dispose(self, app: &mut App) {
682 (self.vtable.dispose)(app, self.id);
683 }
684
685 pub fn parent(self, app: &App) -> Option<AnyContainerLayer> {
692 self.data(app).parent
693 }
694
695 pub fn owner(self, app: &App) -> Option<HandleId> {
701 self.data(app).owner
702 }
703
704 pub fn attached(self, app: &App) -> bool {
710 self.data(app).owner.is_some()
711 }
712
713 pub fn attach(self, app: &mut App, owner: HandleId) {
715 (self.vtable.attach)(app, self.id, owner);
716 }
717
718 pub fn detach(self, app: &mut App) {
720 (self.vtable.detach)(app, self.id);
721 }
722
723 pub fn depth(self, app: &App) -> i32 {
730 self.data(app).depth
731 }
732
733 pub fn redepth_children(self, app: &mut App) {
735 (self.vtable.redepth_children)(app, self.id);
736 }
737
738 pub fn next_sibling(self, app: &App) -> Option<AnyLayer> {
740 self.data(app).next_sibling
741 }
742
743 pub fn previous_sibling(self, app: &App) -> Option<AnyLayer> {
745 self.data(app).previous_sibling
746 }
747
748 pub fn remove(self, app: &mut App) {
752 debug_assert!(!self.data(app).debug_mutations_locked);
753 if let Some(parent) = self.parent(app) {
754 parent.remove_child(app, self);
755 }
756 }
757
758 pub fn find_annotations(
760 self,
761 app: &App,
762 result: &mut AnnotationSearch,
763 local_position: Offset,
764 only_first: bool,
765 ) -> bool {
766 (self.vtable.find_annotations)(app, self.id, result, local_position, only_first)
767 }
768
769 pub fn find<S: 'static>(self, app: &App, local_position: Offset) -> Option<Rc<S>> {
786 let mut result = AnnotationSearch::new::<S>();
787 self.find_annotations(app, &mut result, local_position, true);
788 result
789 .into_result::<S>()
790 .entries
791 .into_iter()
792 .next()
793 .map(|entry| entry.annotation)
794 }
795
796 pub fn find_all_annotations<S: 'static>(
813 self,
814 app: &App,
815 local_position: Offset,
816 ) -> AnnotationResult<S> {
817 let mut result = AnnotationSearch::new::<S>();
818 self.find_annotations(app, &mut result, local_position, false);
819 result.into_result::<S>()
820 }
821
822 pub fn add_to_scene(self, app: &mut App, builder: &mut SceneBuilder) {
824 (self.vtable.add_to_scene)(app, self.id, builder);
825 }
826
827 pub fn needs_add_to_scene(self, app: &App) -> bool {
832 self.data(app).needs_add_to_scene
833 }
834
835 pub fn mark_needs_add_to_scene(self, app: &mut App) {
837 debug_assert!(!self.data(app).debug_mutations_locked);
838 debug_assert!(
839 !self.always_needs_add_to_scene(app),
840 "a layer with always_needs_add_to_scene set called mark_needs_add_to_scene"
841 );
842 debug_assert!(!self.data(app).debug_disposed);
843 if self.data(app).needs_add_to_scene {
845 return;
846 }
847 self.data_mut(app).needs_add_to_scene = true;
848 }
849
850 pub fn always_needs_add_to_scene(self, app: &App) -> bool {
852 (self.vtable.always_needs_add_to_scene)(app, self.id)
853 }
854
855 pub fn engine_layer(self, app: &App) -> Option<EngineLayer> {
859 self.data(app).engine_layer.clone()
860 }
861
862 pub fn set_engine_layer(self, app: &mut App, value: Option<EngineLayer>) {
866 debug_assert!(!self.data(app).debug_mutations_locked);
867 debug_assert!(!self.data(app).debug_disposed);
868 self.data_mut(app).engine_layer = value;
869 if !self.always_needs_add_to_scene(app) {
870 if let Some(parent) = self.parent(app)
876 && !parent.as_layer().always_needs_add_to_scene(app)
877 {
878 parent.as_layer().mark_needs_add_to_scene(app);
879 }
880 }
881 }
882
883 pub fn update_subtree_needs_add_to_scene(self, app: &mut App) {
895 debug_assert!(!self.data(app).debug_mutations_locked);
896 let always = self.always_needs_add_to_scene(app);
897 let data = self.data_mut(app);
898 data.needs_add_to_scene = data.needs_add_to_scene || always;
899 let Some(container) = self.as_container_layer() else {
900 return;
901 };
902 let mut child = container.first_child(app);
903 while let Some(layer) = child {
904 layer.update_subtree_needs_add_to_scene(app);
905 if layer.data(app).needs_add_to_scene {
906 self.data_mut(app).needs_add_to_scene = true;
907 }
908 child = layer.next_sibling(app);
909 }
910 }
911
912 pub fn add_to_scene_with_retained_rendering(self, app: &mut App, builder: &mut SceneBuilder) {
915 debug_assert!(!self.data(app).debug_mutations_locked);
916 if !self.data(app).needs_add_to_scene
920 && let Some(engine_layer) = self.engine_layer(app)
921 {
922 builder.add_retained(&engine_layer);
923 return;
924 }
925 self.add_to_scene(app, builder);
926 self.data_mut(app).needs_add_to_scene = false;
929 }
930}
931
932pub trait ErasedLayer: Copy + PartialEq + Debug + 'static {
935 fn as_layer(self) -> AnyLayer;
937}
938
939impl ErasedLayer for AnyLayer {
940 fn as_layer(self) -> AnyLayer {
941 self
942 }
943}
944
945impl<T: Layer> ErasedLayer for Handle<T> {
948 fn as_layer(self) -> AnyLayer {
949 AnyLayer {
950 id: self.id(),
951 vtable: const { &LayerVTable::of::<T>() },
952 }
953 }
954}
955
956pub struct LayerHandle<T> {
982 layer: Option<T>,
983}
984
985impl<T> LayerHandle<T> {
986 pub const fn new() -> LayerHandle<T> {
989 LayerHandle { layer: None }
990 }
991}
992
993impl<T: ErasedLayer> LayerHandle<T> {
994 pub fn layer(&self) -> Option<T> {
996 self.layer
997 }
998
999 pub fn set_layer(
1008 app: &mut App,
1009 at: impl Fn(&mut App) -> &mut LayerHandle<T>,
1010 layer: Option<T>,
1011 ) {
1012 debug_assert!(
1013 layer.is_none_or(|layer| !layer.as_layer().debug_disposed(app)),
1014 "Attempted to create a handle to an already disposed layer: {layer:?}."
1015 );
1016 let old = at(app).layer;
1017 if layer == old {
1018 return;
1019 }
1020 at(app).layer = layer;
1023 if let Some(layer) = layer {
1024 layer.as_layer().data_mut(app).ref_count += 1;
1025 }
1026 if let Some(old) = old {
1027 old.as_layer().unref(app);
1028 }
1029 }
1030}
1031
1032impl<T> Default for LayerHandle<T> {
1033 fn default() -> LayerHandle<T> {
1034 LayerHandle::new()
1035 }
1036}
1037
1038impl<T: Debug> Debug for LayerHandle<T> {
1039 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1040 match &self.layer {
1041 Some(layer) => write!(f, "LayerHandle({layer:?})"),
1042 None => write!(f, "LayerHandle(DISPOSED)"),
1043 }
1044 }
1045}
1046
1047pub struct PictureLayer {
1053 layer: LayerData,
1054 pub canvas_bounds: Rect,
1058 picture: Option<Arc<Picture>>,
1059 is_complex_hint: bool,
1060 will_change_hint: bool,
1061}
1062
1063impl PictureLayer {
1064 pub fn new(app: &mut App, canvas_bounds: Rect) -> Handle<PictureLayer> {
1066 app.create(PictureLayer {
1067 layer: LayerData::new(),
1068 canvas_bounds,
1069 picture: None,
1070 is_complex_hint: false,
1071 will_change_hint: false,
1072 })
1073 .into_tree_node(app)
1074 }
1075
1076 pub fn picture(self: Handle<Self>, app: &App) -> Option<&Arc<Picture>> {
1080 app.get(self).picture.as_ref()
1081 }
1082
1083 pub fn set_picture(self: Handle<Self>, app: &mut App, picture: Option<Arc<Picture>>) {
1085 debug_assert!(!app.get(self).layer.debug_disposed);
1086 self.as_layer().mark_needs_add_to_scene(app);
1087 app.get_mut(self).picture = picture;
1088 }
1089
1090 pub fn is_complex_hint(self: Handle<Self>, app: &App) -> bool {
1095 app.get(self).is_complex_hint
1096 }
1097
1098 pub fn set_is_complex_hint(self: Handle<Self>, app: &mut App, value: bool) {
1100 if value != app.get(self).is_complex_hint {
1101 app.get_mut(self).is_complex_hint = value;
1102 self.as_layer().mark_needs_add_to_scene(app);
1103 }
1104 }
1105
1106 pub fn will_change_hint(self: Handle<Self>, app: &App) -> bool {
1112 app.get(self).will_change_hint
1113 }
1114
1115 pub fn set_will_change_hint(self: Handle<Self>, app: &mut App, value: bool) {
1117 if value != app.get(self).will_change_hint {
1118 app.get_mut(self).will_change_hint = value;
1119 self.as_layer().mark_needs_add_to_scene(app);
1120 }
1121 }
1122}
1123
1124impl Layer for PictureLayer {
1125 crate::layer_accessors!();
1126
1127 fn dispose(self: Handle<Self>, app: &mut App) {
1128 self.set_picture(app, None); LayerBase::dispose(self, app);
1130 }
1131
1132 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1133 let this = app.get(self);
1134 let picture = this
1135 .picture
1136 .as_ref()
1137 .expect("a PictureLayer has a picture when it is added to the scene");
1138 builder.add_picture(
1139 Offset::ZERO,
1140 picture,
1141 this.is_complex_hint,
1142 this.will_change_hint,
1143 );
1144 }
1145
1146 fn find_annotations(
1147 self: Handle<Self>,
1148 _app: &App,
1149 _result: &mut AnnotationSearch,
1150 _local_position: Offset,
1151 _only_first: bool,
1152 ) -> bool {
1153 false
1154 }
1155}
1156
1157pub struct EmbeddedLayer {
1162 layer: LayerData,
1163 composition_layer: Arc<dyn CompositionLayer>,
1164 rect: Rect,
1166}
1167
1168impl EmbeddedLayer {
1169 pub fn new(
1171 app: &mut App,
1172 composition_layer: Arc<dyn CompositionLayer>,
1173 rect: Rect,
1174 ) -> Handle<EmbeddedLayer> {
1175 app.create(EmbeddedLayer {
1176 layer: LayerData::new(),
1177 composition_layer,
1178 rect,
1179 })
1180 .into_tree_node(app)
1181 }
1182
1183 pub fn composition_layer(self: Handle<Self>, app: &App) -> &Arc<dyn CompositionLayer> {
1184 &app.get(self).composition_layer
1185 }
1186
1187 pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1188 app.get(self).rect
1189 }
1190}
1191
1192impl Layer for EmbeddedLayer {
1193 crate::layer_accessors!();
1194
1195 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1196 let this = app.get(self);
1197 builder.add_embedded_layer(Arc::clone(&this.composition_layer), this.rect);
1198 }
1199
1200 fn find_annotations(
1201 self: Handle<Self>,
1202 _app: &App,
1203 _result: &mut AnnotationSearch,
1204 _local_position: Offset,
1205 _only_first: bool,
1206 ) -> bool {
1207 false
1208 }
1209}
1210
1211pub struct VideoLayer {
1217 layer: LayerData,
1218 reader: Arc<dyn VideoFrameReader>,
1219 rect: Rect,
1221}
1222
1223impl VideoLayer {
1224 pub fn new(app: &mut App, reader: Arc<dyn VideoFrameReader>, rect: Rect) -> Handle<VideoLayer> {
1226 app.create(VideoLayer {
1227 layer: LayerData::new(),
1228 reader,
1229 rect,
1230 })
1231 .into_tree_node(app)
1232 }
1233
1234 pub fn reader(self: Handle<Self>, app: &App) -> &Arc<dyn VideoFrameReader> {
1235 &app.get(self).reader
1236 }
1237
1238 pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1239 app.get(self).rect
1240 }
1241}
1242
1243impl Layer for VideoLayer {
1244 crate::layer_accessors!();
1245
1246 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1247 let this = app.get(self);
1248 builder.add_video(Arc::clone(&this.reader), this.rect);
1249 }
1250
1251 fn find_annotations(
1252 self: Handle<Self>,
1253 _app: &App,
1254 _result: &mut AnnotationSearch,
1255 _local_position: Offset,
1256 _only_first: bool,
1257 ) -> bool {
1258 false
1259 }
1260}
1261
1262#[derive(Debug, Default)]
1265pub struct ContainerLayerData {
1266 first_child: Option<AnyLayer>,
1267 last_child: Option<AnyLayer>,
1268}
1269
1270impl ContainerLayerData {
1271 pub const fn new() -> ContainerLayerData {
1273 ContainerLayerData {
1274 first_child: None,
1275 last_child: None,
1276 }
1277 }
1278}
1279
1280#[macro_export]
1285macro_rules! container_layer_accessors {
1286 () => {
1287 fn container_layer_data(
1288 self: ::waft_foundation::Handle<Self>,
1289 app: &::waft_foundation::App,
1290 ) -> &$crate::ContainerLayerData {
1291 &app.get(self).container_layer
1292 }
1293 fn container_layer_data_mut(
1294 self: ::waft_foundation::Handle<Self>,
1295 app: &mut ::waft_foundation::App,
1296 ) -> &mut $crate::ContainerLayerData {
1297 &mut app.get_mut(self).container_layer
1298 }
1299 };
1300 (offset) => {
1301 $crate::container_layer_accessors!();
1302 const AS_OFFSET: Option<fn() -> &'static $crate::OffsetLayerVTable> =
1303 Some(|| const { &$crate::OffsetLayerVTable::of::<Self>() });
1304 };
1305}
1306
1307pub trait ContainerLayer: Layer {
1317 fn container_layer_data(self: Handle<Self>, app: &App) -> &ContainerLayerData;
1319
1320 fn container_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut ContainerLayerData;
1322
1323 const AS_OFFSET: Option<fn() -> &'static OffsetLayerVTable> = None;
1326
1327 fn as_container_layer(self: Handle<Self>) -> AnyContainerLayer {
1329 AnyContainerLayer {
1330 id: self.id(),
1331 vtable: const { &ContainerLayerVTable::of::<Self>() },
1332 }
1333 }
1334
1335 fn apply_transform(
1357 self: Handle<Self>,
1358 app: &App,
1359 child: Option<AnyLayer>,
1360 transform: &mut Matrix4,
1361 ) {
1362 let _ = (self, app, transform);
1363 debug_assert!(child.is_some());
1364 }
1365
1366 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
1368 LayerBase::fire_composition_callbacks(self, app, include_children);
1369 if !include_children {
1370 return;
1371 }
1372 let mut child = self.as_container_layer().first_child(app);
1373 while let Some(layer) = child {
1374 layer.fire_composition_callbacks(app, include_children);
1375 child = layer.next_sibling(app);
1376 }
1377 }
1378
1379 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
1381 let mut child = self.as_container_layer().last_child(app);
1382 while let Some(layer) = child {
1383 if !layer.supports_rasterization(app) {
1384 return false;
1385 }
1386 child = layer.previous_sibling(app);
1387 }
1388 true
1389 }
1390
1391 fn dispose(self: Handle<Self>, app: &mut App) {
1393 self.as_container_layer().remove_all_children(app);
1394 self.layer_data_mut(app).callbacks.clear();
1395 LayerBase::dispose(self, app);
1396 }
1397
1398 fn find_annotations(
1400 self: Handle<Self>,
1401 app: &App,
1402 result: &mut AnnotationSearch,
1403 local_position: Offset,
1404 only_first: bool,
1405 ) -> bool {
1406 let mut child = self.as_container_layer().last_child(app);
1407 while let Some(layer) = child {
1408 let is_absorbed = layer.find_annotations(app, result, local_position, only_first);
1409 if is_absorbed {
1410 return true;
1411 }
1412 if only_first && !result.is_empty() {
1413 return is_absorbed;
1414 }
1415 child = layer.previous_sibling(app);
1416 }
1417 false
1418 }
1419
1420 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
1422 debug_assert!(!self.layer_data(app).debug_mutations_locked);
1423 LayerBase::attach(self, app, owner);
1424 let mut child = self.as_container_layer().first_child(app);
1425 while let Some(layer) = child {
1426 layer.attach(app, owner);
1427 child = layer.next_sibling(app);
1428 }
1429 }
1430
1431 fn detach(self: Handle<Self>, app: &mut App) {
1433 debug_assert!(!self.layer_data(app).debug_mutations_locked);
1434 LayerBase::detach(self, app);
1435 let mut child = self.as_container_layer().first_child(app);
1436 while let Some(layer) = child {
1437 layer.detach(app);
1438 child = layer.next_sibling(app);
1439 }
1440 self.as_layer().fire_composition_callbacks(app, false);
1447 }
1448
1449 fn redepth_children(self: Handle<Self>, app: &mut App) {
1451 let this = self.as_container_layer();
1452 let mut child = this.first_child(app);
1453 while let Some(layer) = child {
1454 this.redepth_child(app, layer);
1455 child = layer.next_sibling(app);
1456 }
1457 }
1458
1459 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1461 self.as_container_layer()
1462 .add_children_to_scene(app, builder);
1463 }
1464}
1465
1466#[doc(hidden)]
1470pub struct ContainerLayerVTable {
1471 layer: LayerVTable,
1472 container_data: fn(&App, HandleId) -> &ContainerLayerData,
1473 container_data_mut: fn(&mut App, HandleId) -> &mut ContainerLayerData,
1474 apply_transform: fn(&App, HandleId, Option<AnyLayer>, &mut Matrix4),
1475 as_offset: Option<fn() -> &'static OffsetLayerVTable>,
1476}
1477
1478impl ContainerLayerVTable {
1479 pub const fn of<T: ContainerLayer>() -> ContainerLayerVTable {
1480 ContainerLayerVTable {
1481 layer: LayerVTable::of::<T>(),
1482 container_data: |app, id| T::container_layer_data(resolve(id), app),
1483 container_data_mut: |app, id| T::container_layer_data_mut(resolve(id), app),
1484 apply_transform: |app, id, child, transform| {
1485 T::apply_transform(resolve(id), app, child, transform)
1486 },
1487 as_offset: T::AS_OFFSET,
1488 }
1489 }
1490}
1491
1492#[derive(Clone, Copy)]
1494pub struct AnyContainerLayer {
1495 id: HandleId,
1496 vtable: &'static ContainerLayerVTable,
1497}
1498
1499impl PartialEq for AnyContainerLayer {
1500 fn eq(&self, other: &AnyContainerLayer) -> bool {
1501 self.id == other.id
1502 }
1503}
1504
1505impl Eq for AnyContainerLayer {}
1506
1507impl Hash for AnyContainerLayer {
1508 fn hash<H: Hasher>(&self, state: &mut H) {
1509 self.id.hash(state);
1510 }
1511}
1512
1513impl From<AnyContainerLayer> for HandleId {
1514 fn from(layer: AnyContainerLayer) -> HandleId {
1515 layer.id
1516 }
1517}
1518
1519impl Debug for AnyContainerLayer {
1520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1521 write!(f, "AnyContainerLayer({:?})", self.id)
1522 }
1523}
1524
1525impl ErasedLayer for AnyContainerLayer {
1526 fn as_layer(self) -> AnyLayer {
1527 AnyLayer {
1528 id: self.id,
1529 vtable: &self.vtable.layer,
1530 }
1531 }
1532}
1533
1534impl AnyContainerLayer {
1535 fn from_vtable(id: HandleId, vtable: &'static ContainerLayerVTable) -> AnyContainerLayer {
1536 AnyContainerLayer { id, vtable }
1537 }
1538
1539 pub fn id(self) -> HandleId {
1540 self.id
1541 }
1542
1543 pub fn as_offset_layer(self) -> Option<AnyOffsetLayer> {
1545 self.vtable
1546 .as_offset
1547 .map(|vtable| AnyOffsetLayer::from_vtable(self.id, vtable()))
1548 }
1549
1550 fn data(self, app: &App) -> &ContainerLayerData {
1551 (self.vtable.container_data)(app, self.id)
1552 }
1553
1554 fn data_mut(self, app: &mut App) -> &mut ContainerLayerData {
1555 (self.vtable.container_data_mut)(app, self.id)
1556 }
1557
1558 pub fn first_child(self, app: &App) -> Option<AnyLayer> {
1560 self.data(app).first_child
1561 }
1562
1563 pub fn last_child(self, app: &App) -> Option<AnyLayer> {
1565 self.data(app).last_child
1566 }
1567
1568 pub fn has_children(self, app: &App) -> bool {
1570 self.data(app).first_child.is_some()
1571 }
1572
1573 pub fn build_scene(self, app: &mut App, mut builder: SceneBuilder) -> Scene {
1579 let this = self.as_layer();
1580 this.update_subtree_needs_add_to_scene(app);
1581 this.add_to_scene(app, &mut builder);
1582 if this.subtree_has_composition_callbacks(app) {
1583 this.fire_composition_callbacks(app, true);
1584 }
1585 this.data_mut(app).needs_add_to_scene = false;
1588 builder.build()
1589 }
1590
1591 fn debug_ultimate_previous_sibling_of(
1592 self,
1593 app: &App,
1594 mut child: AnyLayer,
1595 equals: Option<AnyLayer>,
1596 ) -> bool {
1597 let attached = self.as_layer().attached(app);
1598 debug_assert!(child.attached(app) == attached);
1599 while let Some(previous) = child.previous_sibling(app) {
1600 debug_assert!(previous != child);
1601 child = previous;
1602 debug_assert!(child.attached(app) == attached);
1603 }
1604 Some(child) == equals
1605 }
1606
1607 fn debug_ultimate_next_sibling_of(
1608 self,
1609 app: &App,
1610 mut child: AnyLayer,
1611 equals: Option<AnyLayer>,
1612 ) -> bool {
1613 let attached = self.as_layer().attached(app);
1614 debug_assert!(child.attached(app) == attached);
1615 while let Some(next) = child.next_sibling(app) {
1616 debug_assert!(next != child);
1617 child = next;
1618 debug_assert!(child.attached(app) == attached);
1619 }
1620 Some(child) == equals
1621 }
1622
1623 pub fn append(self, app: &mut App, child: AnyLayer) {
1625 let this = self.as_layer();
1626 debug_assert!(!this.data(app).debug_mutations_locked);
1627 debug_assert!(child != this);
1628 debug_assert!(Some(child) != self.first_child(app));
1629 debug_assert!(Some(child) != self.last_child(app));
1630 debug_assert!(child.parent(app).is_none());
1631 debug_assert!(!child.attached(app));
1632 debug_assert!(child.next_sibling(app).is_none());
1633 debug_assert!(child.previous_sibling(app).is_none());
1634 debug_assert!(child.data(app).parent_handle.layer().is_none());
1635 debug_assert!(self.debug_root(app) != child); self.adopt_child(app, child);
1637 let last_child = self.last_child(app);
1638 child.data_mut(app).previous_sibling = last_child;
1639 if let Some(last_child) = last_child {
1640 last_child.data_mut(app).next_sibling = Some(child);
1641 }
1642 let data = self.data_mut(app);
1643 data.last_child = Some(child);
1644 data.first_child.get_or_insert(child);
1645 LayerHandle::set_layer(
1646 app,
1647 |app| &mut child.data_mut(app).parent_handle,
1648 Some(child),
1649 );
1650 debug_assert!(child.attached(app) == this.attached(app));
1651 }
1652
1653 fn debug_root(self, app: &App) -> AnyLayer {
1656 let mut node = self.as_layer();
1657 while let Some(parent) = node.parent(app) {
1658 node = parent.as_layer();
1659 }
1660 node
1661 }
1662
1663 fn adopt_child(self, app: &mut App, child: AnyLayer) {
1664 let this = self.as_layer();
1665 debug_assert!(!this.data(app).debug_mutations_locked);
1666 if !this.always_needs_add_to_scene(app) {
1667 this.mark_needs_add_to_scene(app);
1668 }
1669 let callback_count = child.data(app).composition_callback_count;
1670 if callback_count != 0 {
1671 this.update_subtree_composition_observer_count(app, callback_count);
1672 }
1673 debug_assert!(child.data(app).parent.is_none());
1674 debug_assert!(self.debug_root(app) != child); child.data_mut(app).parent = Some(self);
1676 if let Some(owner) = this.owner(app) {
1677 child.attach(app, owner);
1678 }
1679 self.redepth_child(app, child);
1680 }
1681
1682 pub fn redepth_child(self, app: &mut App, child: AnyLayer) {
1686 let this = self.as_layer();
1687 debug_assert!(child.owner(app) == this.owner(app));
1688 let depth = this.depth(app);
1689 if child.depth(app) <= depth {
1690 child.data_mut(app).depth = depth + 1;
1691 child.redepth_children(app);
1692 }
1693 }
1694
1695 pub(crate) fn remove_child(self, app: &mut App, child: AnyLayer) {
1697 let this = self.as_layer();
1698 debug_assert!(child.parent(app) == Some(self));
1699 debug_assert!(child.attached(app) == this.attached(app));
1700 debug_assert!(self.debug_ultimate_previous_sibling_of(app, child, self.first_child(app)));
1701 debug_assert!(self.debug_ultimate_next_sibling_of(app, child, self.last_child(app)));
1702 debug_assert!(child.data(app).parent_handle.layer().is_some());
1703 let previous_sibling = child.previous_sibling(app);
1704 let next_sibling = child.next_sibling(app);
1705 match previous_sibling {
1706 None => {
1707 debug_assert!(self.first_child(app) == Some(child));
1708 self.data_mut(app).first_child = next_sibling;
1709 }
1710 Some(previous) => previous.data_mut(app).next_sibling = next_sibling,
1711 }
1712 match next_sibling {
1713 None => {
1714 debug_assert!(self.last_child(app) == Some(child));
1715 self.data_mut(app).last_child = previous_sibling;
1716 }
1717 Some(next) => next.data_mut(app).previous_sibling = previous_sibling,
1718 }
1719 self.debug_check_child_list(app);
1720 let data = child.data_mut(app);
1721 data.previous_sibling = None;
1722 data.next_sibling = None;
1723 self.drop_child(app, child);
1724 LayerHandle::set_layer(app, |app| &mut child.data_mut(app).parent_handle, None);
1725 debug_assert!(child.debug_disposed(app) || !child.attached(app));
1727 }
1728
1729 fn debug_check_child_list(self, app: &App) {
1731 let attached = self.as_layer().attached(app);
1732 let first_child = self.first_child(app);
1733 let last_child = self.last_child(app);
1734 debug_assert!(first_child.is_none() == last_child.is_none());
1735 debug_assert!(first_child.is_none_or(|first| first.attached(app) == attached));
1736 debug_assert!(last_child.is_none_or(|last| last.attached(app) == attached));
1737 debug_assert!(
1738 first_child
1739 .is_none_or(|first| self.debug_ultimate_next_sibling_of(app, first, last_child))
1740 );
1741 debug_assert!(
1742 last_child.is_none_or(|last| self.debug_ultimate_previous_sibling_of(
1743 app,
1744 last,
1745 first_child
1746 ))
1747 );
1748 }
1749
1750 fn drop_child(self, app: &mut App, child: AnyLayer) {
1751 let this = self.as_layer();
1752 debug_assert!(!this.data(app).debug_mutations_locked);
1753 if !this.always_needs_add_to_scene(app) {
1754 this.mark_needs_add_to_scene(app);
1755 }
1756 let callback_count = child.data(app).composition_callback_count;
1757 if callback_count != 0 {
1758 this.update_subtree_composition_observer_count(app, -callback_count);
1759 }
1760 debug_assert!(child.data(app).parent == Some(self));
1761 debug_assert!(child.attached(app) == this.attached(app));
1762 child.data_mut(app).parent = None;
1763 if this.attached(app) {
1764 child.detach(app);
1765 }
1766 }
1767
1768 pub fn remove_all_children(self, app: &mut App) {
1770 let this = self.as_layer();
1771 debug_assert!(!this.data(app).debug_mutations_locked);
1772 let mut child = self.first_child(app);
1773 while let Some(layer) = child {
1774 let next = layer.next_sibling(app);
1775 let data = layer.data_mut(app);
1776 data.previous_sibling = None;
1777 data.next_sibling = None;
1778 debug_assert!(layer.attached(app) == this.attached(app));
1779 self.drop_child(app, layer);
1780 LayerHandle::set_layer(app, |app| &mut layer.data_mut(app).parent_handle, None);
1781 child = next;
1782 }
1783 let data = self.data_mut(app);
1784 data.first_child = None;
1785 data.last_child = None;
1786 }
1787
1788 pub fn add_children_to_scene(self, app: &mut App, builder: &mut SceneBuilder) {
1796 let mut child = self.first_child(app);
1797 while let Some(layer) = child {
1798 layer.add_to_scene_with_retained_rendering(app, builder);
1799 child = layer.next_sibling(app);
1800 }
1801 }
1802
1803 pub fn apply_transform(self, app: &App, child: Option<AnyLayer>, transform: &mut Matrix4) {
1805 (self.vtable.apply_transform)(app, self.id, child, transform);
1806 }
1807
1808 pub fn depth_first_iterate_children(self, app: &App) -> Vec<AnyLayer> {
1810 let mut children = Vec::new();
1811 let mut child = self.first_child(app);
1812 while let Some(layer) = child {
1813 children.push(layer);
1814 if let Some(container) = layer.as_container_layer() {
1815 children.extend(container.depth_first_iterate_children(app));
1816 }
1817 child = layer.next_sibling(app);
1818 }
1819 children
1820 }
1821}
1822
1823#[derive(Debug)]
1826pub struct OffsetLayerData {
1827 offset: Offset,
1828}
1829
1830impl OffsetLayerData {
1831 pub const fn new(offset: Offset) -> OffsetLayerData {
1833 OffsetLayerData { offset }
1834 }
1835}
1836
1837impl Default for OffsetLayerData {
1838 fn default() -> OffsetLayerData {
1840 OffsetLayerData::new(Offset::ZERO)
1841 }
1842}
1843
1844#[macro_export]
1846macro_rules! offset_layer_accessors {
1847 () => {
1848 fn offset_layer_data(
1849 self: ::waft_foundation::Handle<Self>,
1850 app: &::waft_foundation::App,
1851 ) -> &$crate::OffsetLayerData {
1852 &app.get(self).offset_layer
1853 }
1854 fn offset_layer_data_mut(
1855 self: ::waft_foundation::Handle<Self>,
1856 app: &mut ::waft_foundation::App,
1857 ) -> &mut $crate::OffsetLayerData {
1858 &mut app.get_mut(self).offset_layer
1859 }
1860 };
1861}
1862
1863pub trait OffsetLayerMixin: ContainerLayer {
1875 fn offset_layer_data(self: Handle<Self>, app: &App) -> &OffsetLayerData;
1877
1878 fn offset_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut OffsetLayerData;
1880
1881 fn as_offset_layer(self: Handle<Self>) -> AnyOffsetLayer {
1883 AnyOffsetLayer {
1884 id: self.id(),
1885 vtable: const { &OffsetLayerVTable::of::<Self>() },
1886 }
1887 }
1888
1889 fn offset(self: Handle<Self>, app: &App) -> Offset {
1891 self.offset_layer_data(app).offset
1892 }
1893
1894 fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
1896 self.offset_layer_data_mut(app).offset = value;
1897 }
1898
1899 fn find_annotations(
1901 self: Handle<Self>,
1902 app: &App,
1903 result: &mut AnnotationSearch,
1904 local_position: Offset,
1905 only_first: bool,
1906 ) -> bool {
1907 let offset = self.offset(app);
1908 ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
1909 }
1910
1911 fn apply_transform(
1913 self: Handle<Self>,
1914 app: &App,
1915 child: Option<AnyLayer>,
1916 transform: &mut Matrix4,
1917 ) {
1918 debug_assert!(child.is_some());
1919 let offset = self.offset(app);
1920 *transform = transform.then(&Matrix4::translation(
1921 offset.dx() as f32,
1922 offset.dy() as f32,
1923 ));
1924 }
1925
1926 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1928 let offset = self.offset(app);
1934 builder.push_offset(offset.dx(), offset.dy());
1935 self.as_container_layer()
1936 .add_children_to_scene(app, builder);
1937 let engine_layer = builder.pop();
1938 self.as_layer().set_engine_layer(app, Some(engine_layer));
1939 }
1940}
1941
1942#[doc(hidden)]
1946pub struct OffsetLayerVTable {
1947 container: ContainerLayerVTable,
1948 offset_data: fn(&App, HandleId) -> &OffsetLayerData,
1949 offset_data_mut: fn(&mut App, HandleId) -> &mut OffsetLayerData,
1950}
1951
1952impl OffsetLayerVTable {
1953 pub const fn of<T: OffsetLayerMixin>() -> OffsetLayerVTable {
1954 OffsetLayerVTable {
1955 container: ContainerLayerVTable::of::<T>(),
1956 offset_data: |app, id| T::offset_layer_data(resolve(id), app),
1957 offset_data_mut: |app, id| T::offset_layer_data_mut(resolve(id), app),
1958 }
1959 }
1960}
1961
1962#[derive(Clone, Copy)]
1965pub struct AnyOffsetLayer {
1966 id: HandleId,
1967 vtable: &'static OffsetLayerVTable,
1968}
1969
1970impl PartialEq for AnyOffsetLayer {
1971 fn eq(&self, other: &AnyOffsetLayer) -> bool {
1972 self.id == other.id
1973 }
1974}
1975
1976impl Eq for AnyOffsetLayer {}
1977
1978impl Hash for AnyOffsetLayer {
1979 fn hash<H: Hasher>(&self, state: &mut H) {
1980 self.id.hash(state);
1981 }
1982}
1983
1984impl From<AnyOffsetLayer> for HandleId {
1985 fn from(layer: AnyOffsetLayer) -> HandleId {
1986 layer.id
1987 }
1988}
1989
1990impl Debug for AnyOffsetLayer {
1991 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1992 write!(f, "AnyOffsetLayer({:?})", self.id)
1993 }
1994}
1995
1996impl ErasedLayer for AnyOffsetLayer {
1997 fn as_layer(self) -> AnyLayer {
1998 self.as_container_layer().as_layer()
1999 }
2000}
2001
2002impl AnyOffsetLayer {
2003 fn from_vtable(id: HandleId, vtable: &'static OffsetLayerVTable) -> AnyOffsetLayer {
2004 AnyOffsetLayer { id, vtable }
2005 }
2006
2007 pub fn id(self) -> HandleId {
2008 self.id
2009 }
2010
2011 pub fn as_container_layer(self) -> AnyContainerLayer {
2013 AnyContainerLayer::from_vtable(self.id, &self.vtable.container)
2014 }
2015
2016 pub fn offset(self, app: &App) -> Offset {
2018 (self.vtable.offset_data)(app, self.id).offset
2019 }
2020
2021 pub fn set_offset(self, app: &mut App, value: Offset) {
2023 if value == self.offset(app) {
2024 return;
2025 }
2026 (self.vtable.offset_data_mut)(app, self.id).offset = value;
2027 if !self.as_layer().always_needs_add_to_scene(app) {
2028 self.as_layer().mark_needs_add_to_scene(app);
2029 }
2030 }
2031}
2032
2033pub struct OffsetLayer {
2035 layer: LayerData,
2036 container_layer: ContainerLayerData,
2037 offset_layer: OffsetLayerData,
2038}
2039
2040impl OffsetLayer {
2041 pub fn new(app: &mut App, offset: Offset) -> Handle<OffsetLayer> {
2045 app.create(OffsetLayer {
2046 layer: LayerData::new(),
2047 container_layer: ContainerLayerData::new(),
2048 offset_layer: OffsetLayerData::new(offset),
2049 })
2050 .into_tree_node(app)
2051 }
2052}
2053
2054impl Layer for OffsetLayer {
2055 crate::layer_accessors!(container);
2056
2057 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2058 ContainerLayer::supports_rasterization(self, app)
2059 }
2060
2061 fn dispose(self: Handle<Self>, app: &mut App) {
2062 ContainerLayer::dispose(self, app);
2063 }
2064
2065 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2066 ContainerLayer::attach(self, app, owner);
2067 }
2068
2069 fn detach(self: Handle<Self>, app: &mut App) {
2070 ContainerLayer::detach(self, app);
2071 }
2072
2073 fn redepth_children(self: Handle<Self>, app: &mut App) {
2074 ContainerLayer::redepth_children(self, app);
2075 }
2076
2077 fn find_annotations(
2078 self: Handle<Self>,
2079 app: &App,
2080 result: &mut AnnotationSearch,
2081 local_position: Offset,
2082 only_first: bool,
2083 ) -> bool {
2084 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2085 }
2086
2087 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2088 OffsetLayerMixin::add_to_scene(self, app, builder);
2089 }
2090
2091 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2092 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2093 }
2094}
2095
2096impl ContainerLayer for OffsetLayer {
2097 crate::container_layer_accessors!(offset);
2098
2099 fn apply_transform(
2100 self: Handle<Self>,
2101 app: &App,
2102 child: Option<AnyLayer>,
2103 transform: &mut Matrix4,
2104 ) {
2105 OffsetLayerMixin::apply_transform(self, app, child, transform);
2106 }
2107}
2108
2109impl OffsetLayerMixin for OffsetLayer {
2110 crate::offset_layer_accessors!();
2111}
2112
2113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2118pub struct BackdropKey(u64);
2119
2120static NEXT_BACKDROP_KEY: AtomicU64 = AtomicU64::new(0);
2121
2122impl BackdropKey {
2123 #[expect(
2125 clippy::new_without_default,
2126 reason = "each call creates a distinct key; Default would suggest a neutral value"
2127 )]
2128 pub fn new() -> BackdropKey {
2129 BackdropKey(NEXT_BACKDROP_KEY.fetch_add(1, Ordering::Relaxed))
2130 }
2131
2132 pub fn id(self) -> u64 {
2134 self.0
2135 }
2136}
2137
2138pub struct ClipRectLayer {
2144 layer: LayerData,
2145 container_layer: ContainerLayerData,
2146 clip_rect: Option<Rect>,
2147 clip_behavior: Clip,
2148}
2149
2150impl ClipRectLayer {
2151 pub fn new(app: &mut App) -> Handle<ClipRectLayer> {
2158 debug_assert!(Clip::HardEdge != Clip::None);
2159 app.create(ClipRectLayer {
2160 layer: LayerData::new(),
2161 container_layer: ContainerLayerData::new(),
2162 clip_rect: None,
2163 clip_behavior: Clip::HardEdge,
2164 })
2165 .into_tree_node(app)
2166 }
2167
2168 pub fn clip_rect(self: Handle<Self>, app: &App) -> Option<Rect> {
2173 app.get(self).clip_rect
2174 }
2175
2176 pub fn set_clip_rect(self: Handle<Self>, app: &mut App, value: Option<Rect>) {
2178 if value != app.get(self).clip_rect {
2179 app.get_mut(self).clip_rect = value;
2180 self.as_layer().mark_needs_add_to_scene(app);
2181 }
2182 }
2183
2184 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2190 app.get(self).clip_behavior
2191 }
2192
2193 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2195 debug_assert!(value != Clip::None);
2196 if value != app.get(self).clip_behavior {
2197 app.get_mut(self).clip_behavior = value;
2198 self.as_layer().mark_needs_add_to_scene(app);
2199 }
2200 }
2201}
2202
2203impl Layer for ClipRectLayer {
2204 crate::layer_accessors!(container);
2205
2206 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2207 self.clip_rect(app)
2208 }
2209
2210 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2211 ContainerLayer::supports_rasterization(self, app)
2212 }
2213
2214 fn dispose(self: Handle<Self>, app: &mut App) {
2215 ContainerLayer::dispose(self, app);
2216 }
2217
2218 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2219 ContainerLayer::attach(self, app, owner);
2220 }
2221
2222 fn detach(self: Handle<Self>, app: &mut App) {
2223 ContainerLayer::detach(self, app);
2224 }
2225
2226 fn redepth_children(self: Handle<Self>, app: &mut App) {
2227 ContainerLayer::redepth_children(self, app);
2228 }
2229
2230 fn find_annotations(
2231 self: Handle<Self>,
2232 app: &App,
2233 result: &mut AnnotationSearch,
2234 local_position: Offset,
2235 only_first: bool,
2236 ) -> bool {
2237 if !self
2238 .clip_rect(app)
2239 .expect("clipRect must be set before searching annotations")
2240 .contains(local_position)
2241 {
2242 return false;
2243 }
2244 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2245 }
2246
2247 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2248 debug_assert!(self.clip_rect(app).is_some());
2249 let mut enabled = true;
2250 if cfg!(debug_assertions) {
2251 enabled = !crate::debug::debug_disable_clip_layers(app);
2252 }
2253 if enabled {
2254 let clip_rect = self
2255 .clip_rect(app)
2256 .expect("clipRect must be set before compositing");
2257 let clip_behavior = self.clip_behavior(app);
2258 builder.push_clip_rect(clip_rect, clip_behavior);
2259 }
2260 self.as_container_layer()
2261 .add_children_to_scene(app, builder);
2262 let engine_layer = enabled.then(|| builder.pop());
2263 self.as_layer().set_engine_layer(app, engine_layer);
2264 }
2265
2266 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2267 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2268 }
2269}
2270
2271impl ContainerLayer for ClipRectLayer {
2272 crate::container_layer_accessors!();
2273}
2274
2275pub struct ClipRRectLayer {
2281 layer: LayerData,
2282 container_layer: ContainerLayerData,
2283 clip_rrect: Option<RRect>,
2284 clip_behavior: Clip,
2285}
2286
2287impl ClipRRectLayer {
2288 pub fn new(app: &mut App) -> Handle<ClipRRectLayer> {
2293 debug_assert!(Clip::AntiAlias != Clip::None);
2294 app.create(ClipRRectLayer {
2295 layer: LayerData::new(),
2296 container_layer: ContainerLayerData::new(),
2297 clip_rrect: None,
2298 clip_behavior: Clip::AntiAlias,
2299 })
2300 .into_tree_node(app)
2301 }
2302
2303 pub fn clip_rrect(self: Handle<Self>, app: &App) -> Option<RRect> {
2308 app.get(self).clip_rrect
2309 }
2310
2311 pub fn set_clip_rrect(self: Handle<Self>, app: &mut App, value: Option<RRect>) {
2313 if value != app.get(self).clip_rrect {
2314 app.get_mut(self).clip_rrect = value;
2315 self.as_layer().mark_needs_add_to_scene(app);
2316 }
2317 }
2318
2319 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2325 app.get(self).clip_behavior
2326 }
2327
2328 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2330 debug_assert!(value != Clip::None);
2331 if value != app.get(self).clip_behavior {
2332 app.get_mut(self).clip_behavior = value;
2333 self.as_layer().mark_needs_add_to_scene(app);
2334 }
2335 }
2336}
2337
2338impl Layer for ClipRRectLayer {
2339 crate::layer_accessors!(container);
2340
2341 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2342 self.clip_rrect(app).map(RRect::outer_rect)
2343 }
2344
2345 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2346 ContainerLayer::supports_rasterization(self, app)
2347 }
2348
2349 fn dispose(self: Handle<Self>, app: &mut App) {
2350 ContainerLayer::dispose(self, app);
2351 }
2352
2353 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2354 ContainerLayer::attach(self, app, owner);
2355 }
2356
2357 fn detach(self: Handle<Self>, app: &mut App) {
2358 ContainerLayer::detach(self, app);
2359 }
2360
2361 fn redepth_children(self: Handle<Self>, app: &mut App) {
2362 ContainerLayer::redepth_children(self, app);
2363 }
2364
2365 fn find_annotations(
2366 self: Handle<Self>,
2367 app: &App,
2368 result: &mut AnnotationSearch,
2369 local_position: Offset,
2370 only_first: bool,
2371 ) -> bool {
2372 if !self
2373 .clip_rrect(app)
2374 .expect("clipRRect must be set before searching annotations")
2375 .contains(local_position)
2376 {
2377 return false;
2378 }
2379 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2380 }
2381
2382 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2383 debug_assert!(self.clip_rrect(app).is_some());
2384 let mut enabled = true;
2385 if cfg!(debug_assertions) {
2386 enabled = !crate::debug::debug_disable_clip_layers(app);
2387 }
2388 if enabled {
2389 let clip_rrect = self
2390 .clip_rrect(app)
2391 .expect("clipRRect must be set before compositing");
2392 let clip_behavior = self.clip_behavior(app);
2393 builder.push_clip_rrect(clip_rrect, clip_behavior);
2394 }
2395 self.as_container_layer()
2396 .add_children_to_scene(app, builder);
2397 let engine_layer = enabled.then(|| builder.pop());
2398 self.as_layer().set_engine_layer(app, engine_layer);
2399 }
2400
2401 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2402 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2403 }
2404}
2405
2406impl ContainerLayer for ClipRRectLayer {
2407 crate::container_layer_accessors!();
2408}
2409
2410pub struct ClipPathLayer {
2416 layer: LayerData,
2417 container_layer: ContainerLayerData,
2418 clip_path: Option<waft_embedder::Path>,
2419 clip_behavior: Clip,
2420}
2421
2422impl ClipPathLayer {
2423 pub fn new(app: &mut App) -> Handle<ClipPathLayer> {
2428 debug_assert!(Clip::AntiAlias != Clip::None);
2429 app.create(ClipPathLayer {
2430 layer: LayerData::new(),
2431 container_layer: ContainerLayerData::new(),
2432 clip_path: None,
2433 clip_behavior: Clip::AntiAlias,
2434 })
2435 .into_tree_node(app)
2436 }
2437
2438 pub fn clip_path(self: Handle<Self>, app: &App) -> Option<&waft_embedder::Path> {
2443 app.get(self).clip_path.as_ref()
2444 }
2445
2446 pub fn set_clip_path(self: Handle<Self>, app: &mut App, value: Option<waft_embedder::Path>) {
2448 app.get_mut(self).clip_path = value;
2449 self.as_layer().mark_needs_add_to_scene(app);
2450 }
2451
2452 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2458 app.get(self).clip_behavior
2459 }
2460
2461 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2463 debug_assert!(value != Clip::None);
2464 if value != app.get(self).clip_behavior {
2465 app.get_mut(self).clip_behavior = value;
2466 self.as_layer().mark_needs_add_to_scene(app);
2467 }
2468 }
2469}
2470
2471impl Layer for ClipPathLayer {
2472 crate::layer_accessors!(container);
2473
2474 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2475 Some(app.get(self).clip_path.as_ref()?.get_bounds())
2476 }
2477
2478 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2479 ContainerLayer::supports_rasterization(self, app)
2480 }
2481
2482 fn dispose(self: Handle<Self>, app: &mut App) {
2483 ContainerLayer::dispose(self, app);
2484 }
2485
2486 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2487 ContainerLayer::attach(self, app, owner);
2488 }
2489
2490 fn detach(self: Handle<Self>, app: &mut App) {
2491 ContainerLayer::detach(self, app);
2492 }
2493
2494 fn redepth_children(self: Handle<Self>, app: &mut App) {
2495 ContainerLayer::redepth_children(self, app);
2496 }
2497
2498 fn find_annotations(
2499 self: Handle<Self>,
2500 app: &App,
2501 result: &mut AnnotationSearch,
2502 local_position: Offset,
2503 only_first: bool,
2504 ) -> bool {
2505 let path = app
2506 .get(self)
2507 .clip_path
2508 .as_ref()
2509 .expect("clipPath must be set before searching annotations");
2510 if !path.contains(local_position) {
2511 return false;
2512 }
2513 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2514 }
2515
2516 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2517 debug_assert!(app.get(self).clip_path.is_some());
2518 let mut enabled = true;
2519 if cfg!(debug_assertions) {
2520 enabled = !crate::debug::debug_disable_clip_layers(app);
2521 }
2522 if enabled {
2523 let clip_path = app
2524 .get(self)
2525 .clip_path
2526 .clone()
2527 .expect("clipPath must be set before compositing");
2528 let clip_behavior = self.clip_behavior(app);
2529 builder.push_clip_path(&clip_path, clip_behavior);
2530 }
2531 self.as_container_layer()
2532 .add_children_to_scene(app, builder);
2533 let engine_layer = enabled.then(|| builder.pop());
2534 self.as_layer().set_engine_layer(app, engine_layer);
2535 }
2536
2537 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2538 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2539 }
2540}
2541
2542impl ContainerLayer for ClipPathLayer {
2543 crate::container_layer_accessors!();
2544}
2545
2546fn transform_point(transform: &Matrix4, point: Offset) -> Offset {
2548 let storage = transform.to_flutter_array();
2549 let x = point.dx();
2550 let y = point.dy();
2551 let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
2552 let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
2553 let rw = storage[3] as f64 * x + storage[7] as f64 * y + storage[15] as f64;
2554 if rw == 1.0 {
2555 Offset::new(rx, ry)
2556 } else {
2557 Offset::new(rx / rw, ry / rw)
2558 }
2559}
2560
2561pub struct ImageFilterLayer {
2563 layer: LayerData,
2564 container_layer: ContainerLayerData,
2565 offset_layer: OffsetLayerData,
2566 image_filter: Option<ImageFilter>,
2567}
2568
2569impl ImageFilterLayer {
2570 pub fn new(app: &mut App) -> Handle<ImageFilterLayer> {
2575 app.create(ImageFilterLayer {
2576 layer: LayerData::new(),
2577 container_layer: ContainerLayerData::new(),
2578 offset_layer: OffsetLayerData::new(Offset::ZERO),
2579 image_filter: None,
2580 })
2581 .into_tree_node(app)
2582 }
2583
2584 pub fn image_filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
2589 app.get(self).image_filter.as_ref()
2590 }
2591
2592 pub fn set_image_filter(self: Handle<Self>, app: &mut App, value: ImageFilter) {
2594 if app.get(self).image_filter.as_ref() != Some(&value) {
2595 app.get_mut(self).image_filter = Some(value);
2596 self.as_layer().mark_needs_add_to_scene(app);
2597 }
2598 }
2599}
2600
2601impl Layer for ImageFilterLayer {
2602 crate::layer_accessors!(container);
2603
2604 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2605 ContainerLayer::supports_rasterization(self, app)
2606 }
2607
2608 fn dispose(self: Handle<Self>, app: &mut App) {
2609 ContainerLayer::dispose(self, app);
2610 }
2611
2612 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2613 ContainerLayer::attach(self, app, owner);
2614 }
2615
2616 fn detach(self: Handle<Self>, app: &mut App) {
2617 ContainerLayer::detach(self, app);
2618 }
2619
2620 fn redepth_children(self: Handle<Self>, app: &mut App) {
2621 ContainerLayer::redepth_children(self, app);
2622 }
2623
2624 fn find_annotations(
2625 self: Handle<Self>,
2626 app: &App,
2627 result: &mut AnnotationSearch,
2628 local_position: Offset,
2629 only_first: bool,
2630 ) -> bool {
2631 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2632 }
2633
2634 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2635 debug_assert!(self.image_filter(app).is_some());
2636 let image_filter = self
2637 .image_filter(app)
2638 .cloned()
2639 .expect("image_filter must be set before compositing");
2640 let offset = self.offset(app);
2641 builder.push_image_filter(&image_filter, offset);
2642 self.as_container_layer()
2643 .add_children_to_scene(app, builder);
2644 let engine_layer = builder.pop();
2645 self.as_layer().set_engine_layer(app, Some(engine_layer));
2646 }
2647
2648 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2649 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2650 }
2651}
2652
2653impl ContainerLayer for ImageFilterLayer {
2654 crate::container_layer_accessors!(offset);
2655
2656 fn apply_transform(
2657 self: Handle<Self>,
2658 app: &App,
2659 child: Option<AnyLayer>,
2660 transform: &mut Matrix4,
2661 ) {
2662 OffsetLayerMixin::apply_transform(self, app, child, transform);
2663 }
2664}
2665
2666impl OffsetLayerMixin for ImageFilterLayer {
2667 crate::offset_layer_accessors!();
2668}
2669
2670pub struct TransformLayer {
2675 layer: LayerData,
2676 container_layer: ContainerLayerData,
2677 offset_layer: OffsetLayerData,
2678 transform: Option<Matrix4>,
2679 last_effective_transform: Option<Matrix4>,
2680 inverted_transform: Cell<Option<Matrix4>>,
2681 inverse_dirty: Cell<bool>,
2682}
2683
2684impl TransformLayer {
2685 pub fn new(app: &mut App) -> Handle<TransformLayer> {
2690 app.create(TransformLayer {
2691 layer: LayerData::new(),
2692 container_layer: ContainerLayerData::new(),
2693 offset_layer: OffsetLayerData::new(Offset::ZERO),
2694 transform: None,
2695 last_effective_transform: None,
2696 inverted_transform: Cell::new(None),
2697 inverse_dirty: Cell::new(true),
2698 })
2699 .into_tree_node(app)
2700 }
2701
2702 pub fn transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
2712 app.get(self).transform
2713 }
2714
2715 pub fn set_transform(self: Handle<Self>, app: &mut App, value: Matrix4) {
2717 debug_assert!(
2718 value
2719 .to_flutter_array()
2720 .iter()
2721 .all(|component| component.is_finite())
2722 );
2723 if app.get(self).transform == Some(value) {
2724 return;
2725 }
2726 app.get_mut(self).transform = Some(value);
2727 app.get(self).inverse_dirty.set(true);
2728 self.as_layer().mark_needs_add_to_scene(app);
2729 }
2730
2731 fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
2732 if app.get(self).inverse_dirty.get() {
2733 let transform = app
2734 .get(self)
2735 .transform
2736 .expect("transform must be set before searching annotations");
2737 app.get(self)
2738 .inverted_transform
2739 .set(remove_perspective_transform(transform).invert());
2740 app.get(self).inverse_dirty.set(false);
2741 }
2742 app.get(self)
2743 .inverted_transform
2744 .get()
2745 .map(|inverted| transform_point(&inverted, local_position))
2746 }
2747}
2748
2749impl Layer for TransformLayer {
2750 crate::layer_accessors!(container);
2751
2752 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2753 ContainerLayer::supports_rasterization(self, app)
2754 }
2755
2756 fn dispose(self: Handle<Self>, app: &mut App) {
2757 ContainerLayer::dispose(self, app);
2758 }
2759
2760 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2761 ContainerLayer::attach(self, app, owner);
2762 }
2763
2764 fn detach(self: Handle<Self>, app: &mut App) {
2765 ContainerLayer::detach(self, app);
2766 }
2767
2768 fn redepth_children(self: Handle<Self>, app: &mut App) {
2769 ContainerLayer::redepth_children(self, app);
2770 }
2771
2772 fn find_annotations(
2773 self: Handle<Self>,
2774 app: &App,
2775 result: &mut AnnotationSearch,
2776 local_position: Offset,
2777 only_first: bool,
2778 ) -> bool {
2779 let Some(transformed_offset) = self.transform_offset(app, local_position) else {
2780 return false;
2781 };
2782 OffsetLayerMixin::find_annotations(self, app, result, transformed_offset, only_first)
2783 }
2784
2785 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2786 debug_assert!(self.transform(app).is_some());
2787 let mut last_effective = self
2788 .transform(app)
2789 .expect("transform must be set before compositing");
2790 let offset = self.offset(app);
2791 if offset != Offset::ZERO {
2792 last_effective =
2793 Matrix4::translation(offset.dx() as f32, offset.dy() as f32).then(&last_effective);
2794 }
2795 app.get_mut(self).last_effective_transform = Some(last_effective);
2796 builder.push_transform(&last_effective);
2797 self.as_container_layer()
2798 .add_children_to_scene(app, builder);
2799 let engine_layer = builder.pop();
2800 self.as_layer().set_engine_layer(app, Some(engine_layer));
2801 }
2802
2803 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2804 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2805 }
2806}
2807
2808impl ContainerLayer for TransformLayer {
2809 crate::container_layer_accessors!(offset);
2810
2811 fn apply_transform(
2812 self: Handle<Self>,
2813 app: &App,
2814 child: Option<AnyLayer>,
2815 transform: &mut Matrix4,
2816 ) {
2817 debug_assert!(child.is_some());
2818 debug_assert!(
2819 app.get(self).last_effective_transform.is_some() || self.transform(app).is_some()
2820 );
2821 let applied = match app.get(self).last_effective_transform {
2822 None => self
2823 .transform(app)
2824 .expect("transform must be set before applyTransform"),
2825 Some(last_effective) => last_effective,
2826 };
2827 *transform = transform.then(&applied);
2828 }
2829}
2830
2831impl OffsetLayerMixin for TransformLayer {
2832 crate::offset_layer_accessors!();
2833}
2834
2835pub struct OpacityLayer {
2845 layer: LayerData,
2846 container_layer: ContainerLayerData,
2847 offset_layer: OffsetLayerData,
2848 alpha: Option<i32>,
2849}
2850
2851impl OpacityLayer {
2852 pub fn new(app: &mut App) -> Handle<OpacityLayer> {
2857 app.create(OpacityLayer {
2858 layer: LayerData::new(),
2859 container_layer: ContainerLayerData::new(),
2860 offset_layer: OffsetLayerData::new(Offset::ZERO),
2861 alpha: None,
2862 })
2863 .into_tree_node(app)
2864 }
2865
2866 pub fn alpha(self: Handle<Self>, app: &App) -> Option<i32> {
2874 app.get(self).alpha
2875 }
2876
2877 pub fn set_alpha(self: Handle<Self>, app: &mut App, value: i32) {
2879 if app.get(self).alpha != Some(value) {
2880 app.get_mut(self).alpha = Some(value);
2881 self.as_layer().mark_needs_add_to_scene(app);
2882 }
2883 }
2884}
2885
2886impl Layer for OpacityLayer {
2887 crate::layer_accessors!(container);
2888
2889 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2890 ContainerLayer::supports_rasterization(self, app)
2891 }
2892
2893 fn dispose(self: Handle<Self>, app: &mut App) {
2894 ContainerLayer::dispose(self, app);
2895 }
2896
2897 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2898 ContainerLayer::attach(self, app, owner);
2899 }
2900
2901 fn detach(self: Handle<Self>, app: &mut App) {
2902 ContainerLayer::detach(self, app);
2903 }
2904
2905 fn redepth_children(self: Handle<Self>, app: &mut App) {
2906 ContainerLayer::redepth_children(self, app);
2907 }
2908
2909 fn find_annotations(
2910 self: Handle<Self>,
2911 app: &App,
2912 result: &mut AnnotationSearch,
2913 local_position: Offset,
2914 only_first: bool,
2915 ) -> bool {
2916 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2917 }
2918
2919 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2920 debug_assert!(self.alpha(app).is_some());
2921
2922 let mut enabled = self.as_container_layer().first_child(app).is_some();
2924 if !enabled {
2925 self.as_layer().set_engine_layer(app, None);
2927 return;
2928 }
2929
2930 if cfg!(debug_assertions) {
2931 enabled = enabled && !crate::debug::debug_disable_opacity_layers(app);
2932 }
2933
2934 let realized_alpha = self
2935 .alpha(app)
2936 .expect("alpha must be set before compositing");
2937 let offset = self.offset(app);
2938 if enabled && realized_alpha < 255 {
2939 builder.push_opacity(realized_alpha, offset);
2940 } else {
2941 builder.push_offset(offset.dx(), offset.dy());
2942 }
2943 self.as_container_layer()
2944 .add_children_to_scene(app, builder);
2945 let engine_layer = builder.pop();
2946 self.as_layer().set_engine_layer(app, Some(engine_layer));
2947 }
2948
2949 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2950 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2951 }
2952}
2953
2954impl ContainerLayer for OpacityLayer {
2955 crate::container_layer_accessors!(offset);
2956
2957 fn apply_transform(
2958 self: Handle<Self>,
2959 app: &App,
2960 child: Option<AnyLayer>,
2961 transform: &mut Matrix4,
2962 ) {
2963 OffsetLayerMixin::apply_transform(self, app, child, transform);
2964 }
2965}
2966
2967impl OffsetLayerMixin for OpacityLayer {
2968 crate::offset_layer_accessors!();
2969}
2970
2971pub struct BackdropFilterLayer {
2973 layer: LayerData,
2974 container_layer: ContainerLayerData,
2975 filter: Option<ImageFilter>,
2976 blend_mode: BlendMode,
2977 backdrop_key: Option<BackdropKey>,
2978}
2979
2980impl BackdropFilterLayer {
2981 pub fn new(app: &mut App) -> Handle<BackdropFilterLayer> {
2988 app.create(BackdropFilterLayer {
2989 layer: LayerData::new(),
2990 container_layer: ContainerLayerData::new(),
2991 filter: None,
2992 blend_mode: BlendMode::SrcOver,
2993 backdrop_key: None,
2994 })
2995 .into_tree_node(app)
2996 }
2997
2998 pub fn filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
3003 app.get(self).filter.as_ref()
3004 }
3005
3006 pub fn set_filter(self: Handle<Self>, app: &mut App, value: Option<ImageFilter>) {
3008 app.get_mut(self).filter = value;
3009 self.as_layer().mark_needs_add_to_scene(app);
3010 }
3011
3012 pub fn blend_mode(self: Handle<Self>, app: &App) -> BlendMode {
3020 app.get(self).blend_mode
3021 }
3022
3023 pub fn set_blend_mode(self: Handle<Self>, app: &mut App, value: BlendMode) {
3025 if value != app.get(self).blend_mode {
3026 app.get_mut(self).blend_mode = value;
3027 self.as_layer().mark_needs_add_to_scene(app);
3028 }
3029 }
3030
3031 pub fn backdrop_key(self: Handle<Self>, app: &App) -> Option<BackdropKey> {
3039 app.get(self).backdrop_key
3040 }
3041
3042 pub fn set_backdrop_key(self: Handle<Self>, app: &mut App, value: Option<BackdropKey>) {
3044 if value != app.get(self).backdrop_key {
3045 app.get_mut(self).backdrop_key = value;
3046 self.as_layer().mark_needs_add_to_scene(app);
3047 }
3048 }
3049}
3050
3051impl Layer for BackdropFilterLayer {
3052 crate::layer_accessors!(container);
3053
3054 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3055 ContainerLayer::supports_rasterization(self, app)
3056 }
3057
3058 fn dispose(self: Handle<Self>, app: &mut App) {
3059 ContainerLayer::dispose(self, app);
3060 }
3061
3062 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3063 ContainerLayer::attach(self, app, owner);
3064 }
3065
3066 fn detach(self: Handle<Self>, app: &mut App) {
3067 ContainerLayer::detach(self, app);
3068 }
3069
3070 fn redepth_children(self: Handle<Self>, app: &mut App) {
3071 ContainerLayer::redepth_children(self, app);
3072 }
3073
3074 fn find_annotations(
3075 self: Handle<Self>,
3076 app: &App,
3077 result: &mut AnnotationSearch,
3078 local_position: Offset,
3079 only_first: bool,
3080 ) -> bool {
3081 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
3082 }
3083
3084 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3085 debug_assert!(app.get(self).filter.is_some());
3086 let filter = app
3087 .get(self)
3088 .filter
3089 .clone()
3090 .expect("filter must be set before compositing");
3091 let blend_mode = self.blend_mode(app);
3092 let backdrop_id = self.backdrop_key(app).map(BackdropKey::id);
3093 builder.push_backdrop_filter(&filter, blend_mode, backdrop_id);
3094 self.as_container_layer()
3095 .add_children_to_scene(app, builder);
3096 let engine_layer = builder.pop();
3097 self.as_layer().set_engine_layer(app, Some(engine_layer));
3098 }
3099
3100 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3101 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3102 }
3103}
3104
3105impl ContainerLayer for BackdropFilterLayer {
3106 crate::container_layer_accessors!();
3107}
3108
3109pub struct LayerLink {
3121 leader: Option<Handle<LeaderLayer>>,
3122 debug_previous_leaders: Option<HashSet<Handle<LeaderLayer>>>,
3123 debug_leader_check_scheduled: bool,
3124 pub leader_size: Option<Size>,
3130}
3131
3132impl LayerLink {
3133 pub fn new(app: &mut App) -> Ref<LayerLink> {
3135 app.create(LayerLink {
3136 leader: None,
3137 debug_previous_leaders: None,
3138 debug_leader_check_scheduled: false,
3139 leader_size: None,
3140 })
3141 }
3142
3143 pub fn leader(self: Handle<Self>, app: &App) -> Option<Handle<LeaderLayer>> {
3145 app.get(self).leader
3146 }
3147
3148 fn register_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3149 debug_assert_ne!(self.leader(app), Some(leader));
3150 if cfg!(debug_assertions)
3151 && let Some(current) = self.leader(app)
3152 {
3153 let previous = app
3154 .get_mut(self)
3155 .debug_previous_leaders
3156 .get_or_insert_with(HashSet::new);
3157 debug_assert!(previous.insert(current));
3158 self.debug_schedule_leaders_clean_up_check(app);
3159 }
3160 app.get_mut(self).leader = Some(leader);
3161 }
3162
3163 fn unregister_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3164 if self.leader(app) == Some(leader) {
3165 app.get_mut(self).leader = None;
3166 } else if cfg!(debug_assertions) {
3167 let removed = app
3168 .get_mut(self)
3169 .debug_previous_leaders
3170 .as_mut()
3171 .expect("a replaced leader is tracked")
3172 .remove(&leader);
3173 debug_assert!(removed);
3174 }
3175 }
3176
3177 fn debug_schedule_leaders_clean_up_check(self: Handle<Self>, app: &mut App) {
3180 debug_assert!(app.get(self).debug_previous_leaders.is_some());
3181 if cfg!(debug_assertions) {
3182 if app.get(self).debug_leader_check_scheduled {
3183 return;
3184 }
3185 app.get_mut(self).debug_leader_check_scheduled = true;
3186 SchedulerBinding::add_post_frame_callback(
3187 app,
3188 FrameCallback::handle_method(self, |this, app, _time_stamp| {
3189 app.get_mut(this).debug_leader_check_scheduled = false;
3190 debug_assert!(
3191 app.get(this)
3192 .debug_previous_leaders
3193 .as_ref()
3194 .expect("a replaced leader is tracked")
3195 .is_empty()
3196 );
3197 }),
3198 None,
3199 );
3200 }
3201 }
3202}
3203
3204pub struct LeaderLayer {
3210 layer: LayerData,
3211 container_layer: ContainerLayerData,
3212 link: Ref<LayerLink>,
3213 offset: Offset,
3214}
3215
3216impl LeaderLayer {
3217 pub fn new(app: &mut App, link: Ref<LayerLink>) -> Handle<LeaderLayer> {
3225 app.create(LeaderLayer {
3226 layer: LayerData::new(),
3227 container_layer: ContainerLayerData::new(),
3228 link,
3229 offset: Offset::ZERO,
3230 })
3231 .into_tree_node(app)
3232 }
3233
3234 pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3239 app.get(self).link.handle()
3240 }
3241
3242 pub fn set_link(self: Handle<Self>, app: &mut App, value: Ref<LayerLink>) {
3244 let current = self.link(app);
3245 if current == value {
3246 return;
3247 }
3248 if self.as_layer().attached(app) {
3249 current.unregister_leader(app, self);
3250 value.register_leader(app, self);
3251 }
3252 app.get_mut(self).link = value;
3253 }
3254
3255 pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3263 app.get(self).offset
3264 }
3265
3266 pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3268 if value == app.get(self).offset {
3269 return;
3270 }
3271 app.get_mut(self).offset = value;
3272 if !self.as_layer().always_needs_add_to_scene(app) {
3273 self.as_layer().mark_needs_add_to_scene(app);
3274 }
3275 }
3276}
3277
3278impl Layer for LeaderLayer {
3279 crate::layer_accessors!(container);
3280
3281 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3282 ContainerLayer::supports_rasterization(self, app)
3283 }
3284
3285 fn dispose(self: Handle<Self>, app: &mut App) {
3286 ContainerLayer::dispose(self, app);
3287 }
3288
3289 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3290 ContainerLayer::attach(self, app, owner);
3291 let link = self.link(app);
3292 link.register_leader(app, self);
3293 }
3294
3295 fn detach(self: Handle<Self>, app: &mut App) {
3296 let link = self.link(app);
3297 link.unregister_leader(app, self);
3298 ContainerLayer::detach(self, app);
3299 }
3300
3301 fn redepth_children(self: Handle<Self>, app: &mut App) {
3302 ContainerLayer::redepth_children(self, app);
3303 }
3304
3305 fn find_annotations(
3306 self: Handle<Self>,
3307 app: &App,
3308 result: &mut AnnotationSearch,
3309 local_position: Offset,
3310 only_first: bool,
3311 ) -> bool {
3312 let offset = self.offset(app);
3313 ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
3314 }
3315
3316 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3317 let offset = self.offset(app);
3318 if offset != Offset::ZERO {
3319 builder.push_transform(&Matrix4::translation(
3320 offset.dx() as f32,
3321 offset.dy() as f32,
3322 ));
3323 }
3324 self.as_container_layer()
3325 .add_children_to_scene(app, builder);
3326 let engine_layer = (offset != Offset::ZERO).then(|| builder.pop());
3327 self.as_layer().set_engine_layer(app, engine_layer);
3328 }
3329
3330 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3331 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3332 }
3333}
3334
3335impl ContainerLayer for LeaderLayer {
3336 crate::container_layer_accessors!();
3337
3338 fn apply_transform(
3345 self: Handle<Self>,
3346 app: &App,
3347 _child: Option<AnyLayer>,
3348 transform: &mut Matrix4,
3349 ) {
3350 let offset = self.offset(app);
3351 if offset != Offset::ZERO {
3352 *transform = transform.then(&Matrix4::translation(
3353 offset.dx() as f32,
3354 offset.dy() as f32,
3355 ));
3356 }
3357 }
3358}
3359
3360pub struct FollowerLayer {
3371 layer: LayerData,
3372 container_layer: ContainerLayerData,
3373 link: Ref<LayerLink>,
3374 show_when_unlinked: bool,
3375 unlinked_offset: Offset,
3376 linked_offset: Offset,
3377 last_offset: Option<Offset>,
3378 last_transform: Option<Matrix4>,
3379 inverted_transform: Cell<Option<Matrix4>>,
3380 inverse_dirty: Cell<bool>,
3381}
3382
3383impl FollowerLayer {
3384 pub fn new(app: &mut App, link: Ref<LayerLink>) -> Handle<FollowerLayer> {
3390 app.create(FollowerLayer {
3391 layer: LayerData::new(),
3392 container_layer: ContainerLayerData::new(),
3393 link,
3394 show_when_unlinked: true,
3395 unlinked_offset: Offset::ZERO,
3396 linked_offset: Offset::ZERO,
3397 last_offset: None,
3398 last_transform: None,
3399 inverted_transform: Cell::new(None),
3400 inverse_dirty: Cell::new(true),
3401 })
3402 .into_tree_node(app)
3403 }
3404
3405 pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3411 app.get(self).link.handle()
3412 }
3413
3414 pub fn set_link(self: Handle<Self>, app: &mut App, value: Ref<LayerLink>) {
3416 if self.link(app) == value {
3417 return;
3418 }
3419 app.get_mut(self).link = value;
3420 }
3421
3422 pub fn show_when_unlinked(self: Handle<Self>, app: &App) -> bool {
3435 app.get(self).show_when_unlinked
3436 }
3437
3438 pub fn set_show_when_unlinked(self: Handle<Self>, app: &mut App, value: bool) {
3440 app.get_mut(self).show_when_unlinked = value;
3441 }
3442
3443 pub fn unlinked_offset(self: Handle<Self>, app: &App) -> Offset {
3456 app.get(self).unlinked_offset
3457 }
3458
3459 pub fn set_unlinked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3461 app.get_mut(self).unlinked_offset = value;
3462 }
3463
3464 pub fn linked_offset(self: Handle<Self>, app: &App) -> Offset {
3477 app.get(self).linked_offset
3478 }
3479
3480 pub fn set_linked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3482 app.get_mut(self).linked_offset = value;
3483 }
3484
3485 fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
3486 if app.get(self).inverse_dirty.get() {
3487 let last = self.get_last_transform(app).expect(
3488 "FollowerLayer._transformOffset requires getLastTransform after addToScene",
3489 );
3490 app.get(self).inverted_transform.set(last.invert());
3491 app.get(self).inverse_dirty.set(false);
3492 }
3493 let inverted = app.get(self).inverted_transform.get()?;
3494 let storage = inverted.to_flutter_array();
3495 let x = local_position.dx();
3496 let y = local_position.dy();
3497 let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
3498 let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
3499 let linked_offset = self.linked_offset(app);
3500 Some(Offset::new(
3501 rx - linked_offset.dx(),
3502 ry - linked_offset.dy(),
3503 ))
3504 }
3505
3506 pub fn get_last_transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
3513 let last_transform = app.get(self).last_transform?;
3514 let last_offset = app
3515 .get(self)
3516 .last_offset
3517 .expect("lastOffset is set with lastTransform");
3518 Some(
3519 Matrix4::translation(-last_offset.dx() as f32, -last_offset.dy() as f32)
3520 .then(&last_transform),
3521 )
3522 }
3523
3524 fn collect_transform_for_layer_chain(
3530 app: &App,
3531 layers: &[Option<AnyContainerLayer>],
3532 ) -> Matrix4 {
3533 let mut result = Matrix4::IDENTITY;
3534 for index in (1..layers.len()).rev() {
3535 if let Some(layer) = layers[index] {
3536 let child = layers[index - 1].map(AnyContainerLayer::as_layer);
3537 layer.apply_transform(app, child, &mut result);
3538 }
3539 }
3540 result
3541 }
3542
3543 fn paths_to_common_ancestor(
3550 app: &App,
3551 a: Option<AnyLayer>,
3552 b: Option<AnyLayer>,
3553 ancestors_a: &mut Vec<Option<AnyContainerLayer>>,
3554 ancestors_b: &mut Vec<Option<AnyContainerLayer>>,
3555 ) -> Option<AnyLayer> {
3556 let (a, b) = (a?, b?);
3557 if a == b {
3558 return Some(a);
3559 }
3560 if a.depth(app) < b.depth(app) {
3561 ancestors_b.push(b.parent(app));
3562 return Self::paths_to_common_ancestor(
3563 app,
3564 Some(a),
3565 b.parent(app).map(AnyContainerLayer::as_layer),
3566 ancestors_a,
3567 ancestors_b,
3568 );
3569 } else if a.depth(app) > b.depth(app) {
3570 ancestors_a.push(a.parent(app));
3571 return Self::paths_to_common_ancestor(
3572 app,
3573 a.parent(app).map(AnyContainerLayer::as_layer),
3574 Some(b),
3575 ancestors_a,
3576 ancestors_b,
3577 );
3578 }
3579 ancestors_a.push(a.parent(app));
3580 ancestors_b.push(b.parent(app));
3581 Self::paths_to_common_ancestor(
3582 app,
3583 a.parent(app).map(AnyContainerLayer::as_layer),
3584 b.parent(app).map(AnyContainerLayer::as_layer),
3585 ancestors_a,
3586 ancestors_b,
3587 )
3588 }
3589
3590 fn debug_check_leader_before_follower(
3591 app: &App,
3592 leader_to_common_ancestor: &[Option<AnyContainerLayer>],
3593 follower_to_common_ancestor: &[Option<AnyContainerLayer>],
3594 ) -> bool {
3595 if follower_to_common_ancestor.len() <= 1 {
3596 return false;
3597 }
3598 if leader_to_common_ancestor.len() <= 1 {
3599 return true;
3600 }
3601 let leader_subtree_below_ancestor = leader_to_common_ancestor
3602 [leader_to_common_ancestor.len() - 2]
3603 .expect("the leader subtree below the ancestor is a layer");
3604 let follower_subtree_below_ancestor = follower_to_common_ancestor
3605 [follower_to_common_ancestor.len() - 2]
3606 .expect("the follower subtree below the ancestor is a layer");
3607 let mut sibling = Some(leader_subtree_below_ancestor.as_layer());
3608 while let Some(layer) = sibling {
3609 if layer == follower_subtree_below_ancestor.as_layer() {
3610 return true;
3611 }
3612 sibling = layer.next_sibling(app);
3613 }
3614 false
3615 }
3616
3617 fn establish_transform(self: Handle<Self>, app: &mut App) {
3619 app.get_mut(self).last_transform = None;
3620 let Some(leader) = self.link(app).leader(app) else {
3621 return;
3622 };
3623 debug_assert_eq!(
3624 leader.as_layer().owner(app),
3625 self.as_layer().owner(app),
3626 "Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer."
3627 );
3628
3629 let mut forward_layers = vec![Some(leader.as_container_layer())];
3630 let mut inverse_layers = vec![Some(self.as_container_layer())];
3631 let ancestor = Self::paths_to_common_ancestor(
3632 app,
3633 Some(leader.as_layer()),
3634 Some(self.as_layer()),
3635 &mut forward_layers,
3636 &mut inverse_layers,
3637 );
3638 debug_assert!(
3639 ancestor.is_some(),
3640 "LeaderLayer and FollowerLayer do not have a common ancestor."
3641 );
3642 debug_assert!(
3643 Self::debug_check_leader_before_follower(app, &forward_layers, &inverse_layers),
3644 "LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse \
3645 was true."
3646 );
3647
3648 let mut forward_transform = Self::collect_transform_for_layer_chain(app, &forward_layers);
3649 leader
3650 .as_container_layer()
3651 .apply_transform(app, None, &mut forward_transform);
3652 let linked_offset = self.linked_offset(app);
3653 forward_transform = forward_transform.then(&Matrix4::translation(
3654 linked_offset.dx() as f32,
3655 linked_offset.dy() as f32,
3656 ));
3657
3658 let inverse_transform = Self::collect_transform_for_layer_chain(app, &inverse_layers);
3659 let Some(inverse_transform) = inverse_transform.invert() else {
3660 return;
3661 };
3662 app.get_mut(self).last_transform = Some(inverse_transform.then(&forward_transform));
3663 app.get(self).inverse_dirty.set(true);
3664 }
3665}
3666
3667impl Layer for FollowerLayer {
3668 crate::layer_accessors!(container);
3669
3670 fn always_needs_add_to_scene(self: Handle<Self>, _app: &App) -> bool {
3674 true
3675 }
3676
3677 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3678 ContainerLayer::supports_rasterization(self, app)
3679 }
3680
3681 fn dispose(self: Handle<Self>, app: &mut App) {
3682 ContainerLayer::dispose(self, app);
3683 }
3684
3685 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3686 ContainerLayer::attach(self, app, owner);
3687 }
3688
3689 fn detach(self: Handle<Self>, app: &mut App) {
3690 ContainerLayer::detach(self, app);
3691 }
3692
3693 fn redepth_children(self: Handle<Self>, app: &mut App) {
3694 ContainerLayer::redepth_children(self, app);
3695 }
3696
3697 fn find_annotations(
3698 self: Handle<Self>,
3699 app: &App,
3700 result: &mut AnnotationSearch,
3701 local_position: Offset,
3702 only_first: bool,
3703 ) -> bool {
3704 if self.link(app).leader(app).is_none() {
3705 if self.show_when_unlinked(app) {
3706 return ContainerLayer::find_annotations(
3707 self,
3708 app,
3709 result,
3710 local_position - self.unlinked_offset(app),
3711 only_first,
3712 );
3713 }
3714 return false;
3715 }
3716 let Some(transformed_offset) = self.transform_offset(app, local_position) else {
3717 return false;
3718 };
3719 ContainerLayer::find_annotations(self, app, result, transformed_offset, only_first)
3720 }
3721
3722 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3723 if self.link(app).leader(app).is_none() && !self.show_when_unlinked(app) {
3724 app.get_mut(self).last_transform = None;
3725 app.get_mut(self).last_offset = None;
3726 app.get(self).inverse_dirty.set(true);
3727 self.as_layer().set_engine_layer(app, None);
3728 return;
3729 }
3730 self.establish_transform(app);
3731 if app.get(self).last_transform.is_some() {
3732 let unlinked_offset = self.unlinked_offset(app);
3733 app.get_mut(self).last_offset = Some(unlinked_offset);
3734 let last_transform = app
3735 .get(self)
3736 .last_transform
3737 .expect("lastTransform was just set");
3738 builder.push_transform(&last_transform);
3739 self.as_container_layer()
3740 .add_children_to_scene(app, builder);
3741 let engine_layer = builder.pop();
3742 self.as_layer().set_engine_layer(app, Some(engine_layer));
3743 } else {
3744 app.get_mut(self).last_offset = None;
3745 let unlinked_offset = self.unlinked_offset(app);
3746 let matrix =
3747 Matrix4::translation(unlinked_offset.dx() as f32, unlinked_offset.dy() as f32);
3748 builder.push_transform(&matrix);
3749 self.as_container_layer()
3750 .add_children_to_scene(app, builder);
3751 let engine_layer = builder.pop();
3752 self.as_layer().set_engine_layer(app, Some(engine_layer));
3753 }
3754 app.get(self).inverse_dirty.set(true);
3755 }
3756
3757 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3758 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3759 }
3760}
3761
3762impl ContainerLayer for FollowerLayer {
3763 crate::container_layer_accessors!();
3764
3765 fn apply_transform(
3766 self: Handle<Self>,
3767 app: &App,
3768 child: Option<AnyLayer>,
3769 transform: &mut Matrix4,
3770 ) {
3771 debug_assert!(child.is_some());
3772 if let Some(last_transform) = app.get(self).last_transform {
3773 *transform = transform.then(&last_transform);
3774 } else {
3775 let unlinked_offset = self.unlinked_offset(app);
3776 *transform = transform.then(&Matrix4::translation(
3777 unlinked_offset.dx() as f32,
3778 unlinked_offset.dy() as f32,
3779 ));
3780 }
3781 }
3782}
3783
3784pub struct AnnotatedRegionLayer {
3803 layer: LayerData,
3804 container_layer: ContainerLayerData,
3805 value: Rc<dyn Any>,
3806 size: Option<Size>,
3807 offset: Offset,
3808 opaque: bool,
3809}
3810
3811impl AnnotatedRegionLayer {
3812 pub fn new(app: &mut App, value: Rc<dyn Any>) -> Handle<AnnotatedRegionLayer> {
3814 app.create(AnnotatedRegionLayer {
3815 layer: LayerData::new(),
3816 container_layer: ContainerLayerData::new(),
3817 value,
3818 size: None,
3819 offset: Offset::ZERO,
3820 opaque: false,
3821 })
3822 .into_tree_node(app)
3823 }
3824
3825 pub fn value(self: Handle<Self>, app: &App) -> &Rc<dyn Any> {
3827 &app.get(self).value
3828 }
3829
3830 pub fn size(self: Handle<Self>, app: &App) -> Option<Size> {
3837 app.get(self).size
3838 }
3839
3840 pub fn set_size(self: Handle<Self>, app: &mut App, value: Option<Size>) {
3842 app.get_mut(self).size = value;
3843 }
3844
3845 pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3853 app.get(self).offset
3854 }
3855
3856 pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3858 app.get_mut(self).offset = value;
3859 }
3860
3861 pub fn opaque(self: Handle<Self>, app: &App) -> bool {
3883 app.get(self).opaque
3884 }
3885
3886 pub fn set_opaque(self: Handle<Self>, app: &mut App, value: bool) {
3888 app.get_mut(self).opaque = value;
3889 }
3890}
3891
3892impl Layer for AnnotatedRegionLayer {
3893 crate::layer_accessors!(container);
3894
3895 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3896 ContainerLayer::supports_rasterization(self, app)
3897 }
3898
3899 fn dispose(self: Handle<Self>, app: &mut App) {
3900 ContainerLayer::dispose(self, app);
3901 }
3902
3903 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3904 ContainerLayer::attach(self, app, owner);
3905 }
3906
3907 fn detach(self: Handle<Self>, app: &mut App) {
3908 ContainerLayer::detach(self, app);
3909 }
3910
3911 fn redepth_children(self: Handle<Self>, app: &mut App) {
3912 ContainerLayer::redepth_children(self, app);
3913 }
3914
3915 fn find_annotations(
3936 self: Handle<Self>,
3937 app: &App,
3938 result: &mut AnnotationSearch,
3939 local_position: Offset,
3940 only_first: bool,
3941 ) -> bool {
3942 let mut is_absorbed =
3943 ContainerLayer::find_annotations(self, app, result, local_position, only_first);
3944 if !result.is_empty() && only_first {
3945 return is_absorbed;
3946 }
3947 let (value, size, offset, opaque) = {
3948 let this = app.get(self);
3949 (Rc::clone(&this.value), this.size, this.offset, this.opaque)
3950 };
3951 if let Some(size) = size
3952 && !(offset & size).contains(local_position)
3953 {
3954 return is_absorbed;
3955 }
3956 if result.accepts(&*value) {
3957 is_absorbed = is_absorbed || opaque;
3958 result.add(value, local_position - offset);
3959 }
3960 is_absorbed
3961 }
3962
3963 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3964 ContainerLayer::add_to_scene(self, app, builder);
3965 }
3966
3967 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3968 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3969 }
3970}
3971
3972impl ContainerLayer for AnnotatedRegionLayer {
3973 crate::container_layer_accessors!();
3974}
3975
3976#[cfg(test)]
3977mod tests {
3978 use waft_foundation::AppCell;
3979
3980 use super::*;
3981
3982 fn offset_layer(app: &mut App) -> AnyLayer {
3983 OffsetLayer::new(app, Offset::ZERO).as_layer()
3984 }
3985
3986 #[test]
3987 fn append_links_children_in_order_and_adopts_them() {
3988 let cell = AppCell::new();
3989 let mut app = cell.borrow_mut();
3990 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3991 let a = offset_layer(&mut app);
3992 let b = offset_layer(&mut app);
3993 parent.append(&mut app, a);
3994 parent.append(&mut app, b);
3995 assert_eq!(parent.first_child(&app), Some(a));
3996 assert_eq!(parent.last_child(&app), Some(b));
3997 assert_eq!(a.next_sibling(&app), Some(b));
3998 assert_eq!(b.previous_sibling(&app), Some(a));
3999 assert_eq!(a.parent(&app), Some(parent));
4000 assert_eq!(a.depth(&app), 1);
4001 assert_eq!(a.debug_handle_count(&app), 1, "the parent handle");
4002 }
4003
4004 #[test]
4005 fn a_layer_is_disposed_when_its_last_handle_is_released() {
4006 let cell = AppCell::new();
4007 let mut app = cell.borrow_mut();
4008 let layer = offset_layer(&mut app);
4009 let handle = app.create(LayerHandle::<AnyLayer>::new());
4010 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(layer));
4011 assert_eq!(layer.debug_handle_count(&app), 1);
4012 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4013 assert!(layer.debug_disposed(&app));
4014 assert!(app.contains(layer.id()), "readable until the checkpoint");
4015 drop(app);
4016 cell.checkpoint();
4017 assert!(
4018 !cell.borrow().contains(layer.id()),
4019 "dispose released the tree's part of the arena entry"
4020 );
4021 }
4022
4023 #[test]
4024 fn removing_a_child_releases_the_parent_handle_and_disposes_it() {
4025 let cell = AppCell::new();
4026 let mut app = cell.borrow_mut();
4027 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4028 let child = offset_layer(&mut app);
4029 parent.append(&mut app, child);
4030 child.remove(&mut app);
4031 assert!(!parent.has_children(&app));
4032 assert!(child.debug_disposed(&app));
4033 }
4034
4035 #[test]
4036 fn a_child_kept_by_another_handle_survives_removal() {
4037 let cell = AppCell::new();
4038 let mut app = cell.borrow_mut();
4039 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4040 let child = offset_layer(&mut app);
4041 let handle = app.create(LayerHandle::<AnyLayer>::new());
4042 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(child));
4043 parent.append(&mut app, child);
4044 child.remove(&mut app);
4045 assert!(!child.debug_disposed(&app));
4046 assert_eq!(child.parent(&app), None);
4047 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4048 assert!(child.debug_disposed(&app));
4049 }
4050
4051 #[test]
4052 fn attach_and_detach_walk_the_subtree() {
4053 let cell = AppCell::new();
4054 let mut app = cell.borrow_mut();
4055 let owner = app.create(());
4056 let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4057 let child = offset_layer(&mut app);
4058 root.append(&mut app, child);
4059 root.as_layer().attach(&mut app, owner.id());
4060 assert!(child.attached(&app));
4061 let late = offset_layer(&mut app);
4062 root.append(&mut app, late);
4063 assert!(
4064 late.attached(&app),
4065 "appending to an attached tree attaches"
4066 );
4067 root.as_layer().detach(&mut app);
4068 assert!(!child.attached(&app));
4069 assert!(!late.attached(&app));
4070 }
4071
4072 #[test]
4073 fn disposing_a_container_disposes_children_it_alone_held() {
4074 let cell = AppCell::new();
4075 let mut app = cell.borrow_mut();
4076 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4077 let child = offset_layer(&mut app);
4078 parent.append(&mut app, child);
4079 let handle = app.create(LayerHandle::<AnyContainerLayer>::new());
4080 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(parent));
4081 LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4082 assert!(parent.as_layer().debug_disposed(&app));
4083 assert!(child.debug_disposed(&app));
4084 }
4085
4086 #[test]
4087 fn a_picture_layer_is_a_leaf_that_holds_its_picture() {
4088 let cell = AppCell::new();
4089 let mut app = cell.borrow_mut();
4090 let layer = PictureLayer::new(&mut app, Rect::from_ltwh(0.0, 0.0, 10.0, 10.0));
4091 let picture = Arc::new(waft_embedder::Canvas::new().build());
4092 layer.set_picture(&mut app, Some(picture));
4093 assert!(layer.picture(&app).is_some());
4094 assert!(layer.as_layer().as_container_layer().is_none());
4095 let mut builder = SceneBuilder::new();
4096 layer.as_layer().add_to_scene(&mut app, &mut builder);
4097 let _scene = builder.build();
4098 }
4099
4100 #[test]
4101 fn composition_callbacks_fire_on_build_scene_and_detach() {
4102 use std::cell::Cell;
4103 let cell = AppCell::new();
4104 let mut app = cell.borrow_mut();
4105 let owner = app.create(());
4106 let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4107 let child = offset_layer(&mut app);
4108 root.append(&mut app, child);
4109 let fired = Rc::new(Cell::new(0));
4110 let remove = {
4111 let fired = Rc::clone(&fired);
4112 child
4113 .add_composition_callback(&mut app, Rc::new(move |_, _| fired.set(fired.get() + 1)))
4114 };
4115 assert!(root.as_layer().subtree_has_composition_callbacks(&app));
4116 let _scene = root.build_scene(&mut app, SceneBuilder::new());
4117 assert_eq!(fired.get(), 1);
4118 root.as_layer().attach(&mut app, owner.id());
4119 root.as_layer().detach(&mut app);
4120 assert_eq!(fired.get(), 2, "detach fires once more");
4121 remove(&mut app);
4122 assert!(!root.as_layer().subtree_has_composition_callbacks(&app));
4123 }
4124
4125 #[test]
4126 fn find_walks_children_back_to_front_through_offsets() {
4127 struct Tag(&'static str);
4128 struct Annotated {
4129 layer: LayerData,
4130 tag: Rc<Tag>,
4131 }
4132 impl Layer for Annotated {
4133 crate::layer_accessors!();
4134 fn find_annotations(
4135 self: Handle<Self>,
4136 app: &App,
4137 result: &mut AnnotationSearch,
4138 local_position: Offset,
4139 _only_first: bool,
4140 ) -> bool {
4141 let tag = Rc::clone(&app.get(self).tag);
4142 if result.accepts(&*tag) {
4143 result.add(tag, local_position);
4144 }
4145 false
4146 }
4147 fn add_to_scene(self: Handle<Self>, _app: &mut App, _builder: &mut SceneBuilder) {}
4148 }
4149 let cell = AppCell::new();
4150 let mut app = cell.borrow_mut();
4151 let root = OffsetLayer::new(&mut app, Offset::new(10.0, 0.0)).as_container_layer();
4152 for name in ["back", "front"] {
4153 let layer = app.create(Annotated {
4154 layer: LayerData::new(),
4155 tag: Rc::new(Tag(name)),
4156 });
4157 root.append(&mut app, layer.as_layer());
4158 }
4159 let found = root.as_layer().find::<Tag>(&app, Offset::new(15.0, 5.0));
4160 assert_eq!(found.map(|tag| tag.0), Some("front"));
4161 let all = root
4162 .as_layer()
4163 .find_all_annotations::<Tag>(&app, Offset::new(15.0, 5.0));
4164 assert_eq!(all.entries().len(), 2);
4165 assert_eq!(all.entries()[0].local_position, Offset::new(5.0, 5.0));
4166 assert!(root.as_layer().find::<String>(&app, Offset::ZERO).is_none());
4167 }
4168
4169 fn drawn_layer(app: &mut App) -> AnyLayer {
4174 let square = Rect::from_ltwh(0.0, 0.0, 10.0, 10.0);
4175 let mut canvas = waft_embedder::Canvas::new();
4176 canvas.draw_rect(square, &waft_embedder::Paint::default());
4177 let layer = PictureLayer::new(app, square);
4178 layer.set_picture(app, Some(Arc::new(canvas.build())));
4179 layer.as_layer()
4180 }
4181
4182 fn retained_tree(app: &mut App) -> (Handle<OffsetLayer>, Handle<OpacityLayer>) {
4183 let root = OffsetLayer::new(app, Offset::ZERO);
4184 let opacity = OpacityLayer::new(app);
4185 opacity.set_alpha(app, 128);
4186 let leaf = drawn_layer(app);
4187 opacity.as_container_layer().append(app, leaf);
4188 root.as_container_layer().append(app, opacity.as_layer());
4189 let _scene = root
4190 .as_container_layer()
4191 .build_scene(app, SceneBuilder::new());
4192 (root, opacity)
4193 }
4194
4195 #[test]
4198 fn an_embedded_layer_is_retained_and_its_composition_layer_placed_every_frame() {
4199 let cell = AppCell::new();
4200 let mut app = cell.borrow_mut();
4201 let root = OffsetLayer::new(&mut app, Offset::new(10.0, 5.0));
4202 let inner = OffsetLayer::new(&mut app, Offset::ZERO);
4203 let composition_layer = waft_embedder::test_support::idle_layer();
4204 let layer = EmbeddedLayer::new(
4205 &mut app,
4206 Arc::clone(&composition_layer),
4207 Rect::from_ltwh(1.0, 2.0, 30.0, 20.0),
4208 );
4209 inner
4210 .as_container_layer()
4211 .append(&mut app, layer.as_layer());
4212 root.as_container_layer().append(&mut app, inner.as_layer());
4213 let mut first_engine_layer = None;
4214 for _frame in 0..2 {
4215 let scene = root
4216 .as_container_layer()
4217 .build_scene(&mut app, SceneBuilder::new());
4218 let slices = waft_embedder::slices(&scene, |_| None);
4219 let (placed, placement) = slices.composition_layers().next().expect("placed");
4220 assert!(Arc::ptr_eq(placed, &composition_layer));
4221 assert_eq!(placement.bounds(), Rect::from_ltwh(11.0, 7.0, 30.0, 20.0));
4222 let engine_layer = inner.as_layer().engine_layer(&app).expect("recorded");
4223 let first = first_engine_layer.get_or_insert_with(|| Arc::clone(&engine_layer));
4224 assert!(Arc::ptr_eq(first, &engine_layer), "retained");
4225 }
4226 assert!(!layer.as_layer().always_needs_add_to_scene(&app));
4227 }
4228
4229 #[test]
4230 fn an_unchanged_subtree_is_retained_across_scenes() {
4231 let cell = AppCell::new();
4232 let mut app = cell.borrow_mut();
4233 let (root, opacity) = retained_tree(&mut app);
4234 let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4235 assert!(!opacity.as_layer().needs_add_to_scene(&app));
4236
4237 let scene = root
4238 .as_container_layer()
4239 .build_scene(&mut app, SceneBuilder::new());
4240 let retained = opacity.as_layer().engine_layer(&app).expect("recorded");
4241 assert!(
4242 Arc::ptr_eq(&recorded, &retained),
4243 "the same node is retained"
4244 );
4245 let root_node = root
4246 .as_layer()
4247 .engine_layer(&app)
4248 .expect("the root is built again");
4249 assert!(
4250 root_node.children.iter().any(|child| matches!(
4251 child,
4252 waft_embedder::Layer::Container(container) if Arc::ptr_eq(container, &retained)
4253 )),
4254 "added again: {:?}",
4255 root_node.children
4256 );
4257 assert_eq!(
4258 waft_embedder::flattened_ops(
4259 &waft_embedder::slices(&scene, |_| None).picture_with_room()
4260 )
4261 .iter()
4262 .filter(|op| matches!(op, waft_embedder::valo::Op::SaveLayer { .. }))
4263 .count(),
4264 1,
4265 "the retained opacity layer still draws"
4266 );
4267 }
4268
4269 #[test]
4270 fn a_changed_property_re_records_the_subtree() {
4271 let cell = AppCell::new();
4272 let mut app = cell.borrow_mut();
4273 let (root, opacity) = retained_tree(&mut app);
4274 let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4275
4276 opacity.set_alpha(&mut app, 200);
4277 assert!(opacity.as_layer().needs_add_to_scene(&app));
4278 let _scene = root
4279 .as_container_layer()
4280 .build_scene(&mut app, SceneBuilder::new());
4281 let again = opacity.as_layer().engine_layer(&app).expect("recorded");
4282 assert!(
4283 !Arc::ptr_eq(&recorded, &again),
4284 "a new node for the new alpha"
4285 );
4286 assert!(!opacity.as_layer().needs_add_to_scene(&app));
4287 }
4288
4289 #[test]
4292 fn an_image_filter_layer_pushes_its_filter_at_its_offset() {
4293 let cell = AppCell::new();
4294 let mut app = cell.borrow_mut();
4295 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4296 let filtered = ImageFilterLayer::new(&mut app);
4297 filtered.set_image_filter(&mut app, ImageFilter::blur(4.0, 4.0));
4298 filtered.set_offset(&mut app, Offset::new(3.0, 4.0));
4299 assert!(Layer::supports_rasterization(filtered, &app));
4300 let leaf = drawn_layer(&mut app);
4301 filtered.as_container_layer().append(&mut app, leaf);
4302 root.as_container_layer()
4303 .append(&mut app, filtered.as_layer());
4304 let _scene = root
4305 .as_container_layer()
4306 .build_scene(&mut app, SceneBuilder::new());
4307 let recorded = filtered.as_layer().engine_layer(&app).expect("recorded");
4308 assert_eq!(
4309 recorded.effect,
4310 waft_embedder::Effect::ImageFilter {
4311 filter: ImageFilter::blur(4.0, 4.0),
4312 offset: Offset::new(3.0, 4.0),
4313 }
4314 );
4315 filtered.set_image_filter(&mut app, ImageFilter::blur(4.0, 4.0));
4316 assert!(!filtered.as_layer().needs_add_to_scene(&app));
4317 filtered.set_image_filter(&mut app, ImageFilter::blur(5.0, 5.0));
4318 assert!(filtered.as_layer().needs_add_to_scene(&app));
4319 }
4320
4321 #[test]
4322 fn appending_a_child_marks_the_parent_and_its_ancestors_at_build() {
4323 let cell = AppCell::new();
4324 let mut app = cell.borrow_mut();
4325 let (root, opacity) = retained_tree(&mut app);
4326 assert!(!root.as_layer().needs_add_to_scene(&app));
4327
4328 let leaf = offset_layer(&mut app);
4329 opacity.as_container_layer().append(&mut app, leaf);
4330 assert!(opacity.as_layer().needs_add_to_scene(&app));
4331 assert!(
4332 !root.as_layer().needs_add_to_scene(&app),
4333 "the mark does not climb until the scene is built"
4334 );
4335 root.as_layer().update_subtree_needs_add_to_scene(&mut app);
4336 assert!(root.as_layer().needs_add_to_scene(&app));
4337 }
4338
4339 #[test]
4340 fn a_follower_layer_always_re_records() {
4341 let cell = AppCell::new();
4342 let mut app = cell.borrow_mut();
4343 let link = LayerLink::new(&mut app);
4344 let follower = FollowerLayer::new(&mut app, link);
4345 let child = offset_layer(&mut app);
4346 follower.as_container_layer().append(&mut app, child);
4347 for _ in 0..2 {
4348 let _scene = follower
4349 .as_container_layer()
4350 .build_scene(&mut app, SceneBuilder::new());
4351 assert!(
4352 follower.as_layer().needs_add_to_scene(&app)
4353 || follower.as_layer().always_needs_add_to_scene(&app)
4354 );
4355 }
4356 let first = follower.as_layer().engine_layer(&app).expect("recorded");
4357 let _scene = follower
4358 .as_container_layer()
4359 .build_scene(&mut app, SceneBuilder::new());
4360 let second = follower.as_layer().engine_layer(&app).expect("recorded");
4361 assert!(!Arc::ptr_eq(&first, &second), "never retained");
4362 }
4363
4364 fn tag(app: &mut App, n: u32) -> Handle<AnnotatedRegionLayer> {
4365 AnnotatedRegionLayer::new(app, Rc::new(n))
4366 }
4367
4368 #[test]
4369 fn clip_layers_reject_annotations_outside_the_clip() {
4370 let cell = AppCell::new();
4371 let mut app = cell.borrow_mut();
4372 let rect = ClipRectLayer::new(&mut app);
4373 rect.set_clip_rect(&mut app, Some(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0)));
4374 let child = tag(&mut app, 7);
4375 rect.as_container_layer().append(&mut app, child.as_layer());
4376 assert_eq!(
4377 rect.as_layer()
4378 .find::<u32>(&app, Offset::new(10.0, 10.0))
4379 .as_deref(),
4380 Some(&7)
4381 );
4382 assert!(
4383 rect.as_layer()
4384 .find::<u32>(&app, Offset::new(60.0, 10.0))
4385 .is_none(),
4386 "outside the clip"
4387 );
4388
4389 let rrect = ClipRRectLayer::new(&mut app);
4390 rrect.set_clip_rrect(
4391 &mut app,
4392 Some(RRect::from_rect_and_radius(
4393 Rect::from_ltwh(0.0, 0.0, 50.0, 50.0),
4394 waft_embedder::Radius::circular(4.0),
4395 )),
4396 );
4397 let child = tag(&mut app, 8);
4398 rrect
4399 .as_container_layer()
4400 .append(&mut app, child.as_layer());
4401 assert_eq!(
4402 rrect
4403 .as_layer()
4404 .find::<u32>(&app, Offset::new(10.0, 10.0))
4405 .as_deref(),
4406 Some(&8)
4407 );
4408 assert!(
4409 rrect
4410 .as_layer()
4411 .find::<u32>(&app, Offset::new(60.0, 10.0))
4412 .is_none()
4413 );
4414
4415 let mut path = waft_embedder::PathBuilder::new();
4416 path.rect(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0).into());
4417 let clip_path = ClipPathLayer::new(&mut app);
4418 clip_path.set_clip_path(&mut app, Some(path.build().into()));
4419 let child = tag(&mut app, 9);
4420 clip_path
4421 .as_container_layer()
4422 .append(&mut app, child.as_layer());
4423 assert_eq!(
4424 clip_path
4425 .as_layer()
4426 .find::<u32>(&app, Offset::new(10.0, 10.0))
4427 .as_deref(),
4428 Some(&9)
4429 );
4430 assert!(
4431 clip_path
4432 .as_layer()
4433 .find::<u32>(&app, Offset::new(60.0, 10.0))
4434 .is_none()
4435 );
4436 }
4437
4438 #[test]
4439 fn transform_layer_transforms_the_annotation_position() {
4440 let cell = AppCell::new();
4441 let mut app = cell.borrow_mut();
4442 let layer = TransformLayer::new(&mut app);
4443 layer.set_transform(&mut app, Matrix4::translation(10.0, 0.0));
4444 let region = tag(&mut app, 7);
4445 region.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4446 layer
4447 .as_container_layer()
4448 .append(&mut app, region.as_layer());
4449 assert!(
4450 layer
4451 .as_layer()
4452 .find::<u32>(&app, Offset::new(15.0, 5.0))
4453 .is_some()
4454 );
4455 assert!(
4456 layer
4457 .as_layer()
4458 .find::<u32>(&app, Offset::new(5.0, 5.0))
4459 .is_none(),
4460 "left of the translated region"
4461 );
4462 }
4463
4464 #[test]
4465 fn opacity_layer_build_scene_succeeds_at_255_and_128() {
4466 let cell = AppCell::new();
4467 let mut app = cell.borrow_mut();
4468 for alpha in [255, 128] {
4469 let layer = OpacityLayer::new(&mut app);
4470 layer.set_alpha(&mut app, alpha);
4471 let child = OffsetLayer::new(&mut app, Offset::ZERO);
4472 layer
4473 .as_container_layer()
4474 .append(&mut app, child.as_layer());
4475 let _scene = layer
4476 .as_container_layer()
4477 .build_scene(&mut app, SceneBuilder::new());
4478 }
4479 let empty = OpacityLayer::new(&mut app);
4480 empty.set_alpha(&mut app, 128);
4481 let _scene = empty
4482 .as_container_layer()
4483 .build_scene(&mut app, SceneBuilder::new());
4484 }
4485
4486 #[test]
4487 fn layer_link_register_unregister_and_leader_getter() {
4488 let cell = AppCell::new();
4489 let mut app = cell.borrow_mut();
4490 let owner = app.create(());
4491 let link = LayerLink::new(&mut app);
4492 assert!(link.leader(&app).is_none());
4493 let leader = LeaderLayer::new(&mut app, link.clone());
4494 leader.as_layer().attach(&mut app, owner.id());
4495 assert_eq!(link.leader(&app), Some(leader));
4496 leader.as_layer().detach(&mut app);
4497 assert!(link.leader(&app).is_none());
4498 }
4499
4500 #[test]
4501 fn leader_layer_attach_registers_and_detach_unregisters() {
4502 let cell = AppCell::new();
4503 let mut app = cell.borrow_mut();
4504 let owner = app.create(());
4505 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4506 let link = LayerLink::new(&mut app);
4507 let leader = LeaderLayer::new(&mut app, link.clone());
4508 root.as_container_layer()
4509 .append(&mut app, leader.as_layer());
4510 root.as_layer().attach(&mut app, owner.id());
4511 assert_eq!(link.leader(&app), Some(leader));
4512 root.as_layer().detach(&mut app);
4513 assert!(link.leader(&app).is_none());
4514 }
4515
4516 #[test]
4517 fn a_replaced_leader_leaves_the_links_new_leader_in_place() {
4518 let cell = AppCell::new();
4519 let mut app = cell.borrow_mut();
4520 let owner = app.create(());
4521 let link = LayerLink::new(&mut app);
4522 let leader1 = LeaderLayer::new(&mut app, link.clone());
4523 let leader2 = LeaderLayer::new(&mut app, link.clone());
4524 leader1.as_layer().attach(&mut app, owner.id());
4525 leader2.as_layer().attach(&mut app, owner.id());
4526 assert_eq!(link.leader(&app), Some(leader2));
4527 leader2.as_layer().detach(&mut app);
4528 leader1.as_layer().detach(&mut app);
4529 assert!(link.leader(&app).is_none());
4530 }
4531
4532 #[test]
4533 fn switching_the_link_of_an_attached_leader_does_not_crash() {
4534 let cell = AppCell::new();
4535 let mut app = cell.borrow_mut();
4536 let owner = app.create(());
4537 let link = LayerLink::new(&mut app);
4538 let leader = LeaderLayer::new(&mut app, link.clone());
4539 leader.as_layer().attach(&mut app, owner.id());
4540 let link2 = LayerLink::new(&mut app);
4541 leader.set_link(&mut app, link2.clone());
4542 leader.as_layer().detach(&mut app);
4543 assert_eq!(leader.link(&app), link2);
4544 assert!(link.leader(&app).is_none());
4545 assert!(link2.leader(&app).is_none());
4546 }
4547
4548 #[test]
4549 fn follower_get_last_transform_after_build_scene_matches_the_leader_offset() {
4550 let cell = AppCell::new();
4551 let mut app = cell.borrow_mut();
4552 let owner = app.create(());
4553 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4554 let link = LayerLink::new(&mut app);
4555 let leader = LeaderLayer::new(&mut app, link.clone());
4556 leader.set_offset(&mut app, Offset::new(10.0, 20.0));
4557 let follower = FollowerLayer::new(&mut app, link);
4558 root.as_container_layer()
4559 .append(&mut app, leader.as_layer());
4560 root.as_container_layer()
4561 .append(&mut app, follower.as_layer());
4562 root.as_layer().attach(&mut app, owner.id());
4563 let _scene = root
4564 .as_container_layer()
4565 .build_scene(&mut app, SceneBuilder::new());
4566 assert_eq!(
4567 follower.get_last_transform(&app).unwrap(),
4568 Matrix4::translation(10.0, 20.0)
4569 );
4570 }
4571
4572 #[test]
4573 fn follower_with_show_when_unlinked_false_pushes_nothing() {
4574 let cell = AppCell::new();
4575 let mut app = cell.borrow_mut();
4576 let link = LayerLink::new(&mut app);
4577 let follower = FollowerLayer::new(&mut app, link);
4578 follower.set_show_when_unlinked(&mut app, false);
4579 let child = offset_layer(&mut app);
4580 follower.as_container_layer().append(&mut app, child);
4581 let _scene = follower
4582 .as_container_layer()
4583 .build_scene(&mut app, SceneBuilder::new());
4584 assert!(follower.get_last_transform(&app).is_none());
4585 }
4586
4587 #[test]
4588 fn annotated_region_layer_find_with_size_offset_and_opaque() {
4589 let cell = AppCell::new();
4590 let mut app = cell.borrow_mut();
4591 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4592 let behind = tag(&mut app, 1);
4593 let front = tag(&mut app, 2);
4594 front.set_opaque(&mut app, true);
4595 root.as_container_layer()
4596 .append(&mut app, behind.as_layer());
4597 root.as_container_layer().append(&mut app, front.as_layer());
4598 let result = root
4599 .as_layer()
4600 .find_all_annotations::<u32>(&app, Offset::ZERO);
4601 assert_eq!(
4602 result
4603 .annotations()
4604 .map(|value| **value)
4605 .collect::<Vec<_>>(),
4606 vec![2],
4607 "an opaque region hides its siblings"
4608 );
4609
4610 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4611 let first = tag(&mut app, 1);
4612 let second = tag(&mut app, 2);
4613 root.as_container_layer().append(&mut app, first.as_layer());
4614 root.as_container_layer()
4615 .append(&mut app, second.as_layer());
4616 let result = root
4617 .as_layer()
4618 .find_all_annotations::<u32>(&app, Offset::ZERO);
4619 assert_eq!(
4620 result
4621 .annotations()
4622 .map(|value| **value)
4623 .collect::<Vec<_>>(),
4624 vec![2, 1],
4625 "front to back when neither is opaque"
4626 );
4627
4628 let sized = tag(&mut app, 3);
4629 sized.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4630 sized.set_offset(&mut app, Offset::new(90.0, 90.0));
4631 assert!(
4632 sized
4633 .as_layer()
4634 .find::<u32>(&app, Offset::new(95.0, 95.0))
4635 .is_some()
4636 );
4637 assert!(
4638 sized.as_layer().find::<u32>(&app, Offset::ZERO).is_none(),
4639 "outside the sized region"
4640 );
4641 }
4642}