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 inset_embedder::Surface;
23use inset_embedder::{
24 BlendMode, Clip, EngineLayer, FillRule, ImageFilter, Matrix4, Offset, Picture, RRect, Rect,
25 Scene, SceneBuilder, Size,
26};
27use inset_foundation::{App, Handle, HandleId, RetainedHandle};
28use inset_gestures::remove_perspective_transform;
29use inset_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: ::inset_foundation::Handle<Self>,
230 app: &::inset_foundation::App,
231 ) -> &$crate::LayerData {
232 &app.get(self).layer
233 }
234 fn layer_data_mut(
235 self: ::inset_foundation::Handle<Self>,
236 app: &mut ::inset_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) {
325 LayerBase::dispose(self, app);
326 }
327
328 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
336 LayerBase::attach(self, app, owner);
337 }
338
339 fn detach(self: Handle<Self>, app: &mut App) {
347 LayerBase::detach(self, app);
348 }
349
350 fn redepth_children(self: Handle<Self>, app: &mut App) {
355 let _ = (self, app);
358 }
359
360 fn find_annotations(
381 self: Handle<Self>,
382 app: &App,
383 result: &mut AnnotationSearch,
384 local_position: Offset,
385 only_first: bool,
386 ) -> bool {
387 let _ = (self, app, result, local_position, only_first);
388 false
389 }
390
391 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder);
393
394 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
396 LayerBase::fire_composition_callbacks(self, app, include_children);
397 }
398}
399
400pub trait LayerBase: Layer {
403 fn dispose(self: Handle<Self>, app: &mut App) {
405 let data = self.layer_data_mut(app);
406 debug_assert!(!data.debug_mutations_locked);
407 debug_assert!(
408 !data.debug_disposed,
409 "Layers must only be disposed once. This is typically handled by LayerHandle. \
410 Subclasses should not directly call dispose, except to call LayerBase::dispose in \
411 an overridden dispose method. Tests must only call dispose once."
412 );
413 debug_assert!(
414 data.ref_count == 0,
415 "Do not directly call dispose on a layer. Instead, use a LayerHandle."
416 );
417 data.debug_disposed = true;
418 app.destroy(self);
420 }
421
422 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
424 let data = self.layer_data_mut(app);
425 debug_assert!(data.owner.is_none());
426 data.owner = Some(owner);
427 }
428
429 fn detach(self: Handle<Self>, app: &mut App) {
431 let data = self.layer_data_mut(app);
432 debug_assert!(data.owner.is_some());
433 data.owner = None;
434 let this = self.as_layer();
435 debug_assert!(
436 this.parent(app)
437 .is_none_or(|parent| this.attached(app) == parent.as_layer().attached(app))
438 );
439 }
440
441 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
443 let _ = include_children;
444 let this = self.as_layer();
445 let callbacks: Vec<CompositionCallback> = self
446 .layer_data(app)
447 .callbacks
448 .iter()
449 .map(|(_, callback)| Rc::clone(callback))
450 .collect();
451 for callback in callbacks {
452 this.run_composition_callback(app, &callback);
453 }
454 }
455}
456
457impl<T: Layer> LayerBase for T {}
458
459fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
461 Handle::from_id(id)
462}
463
464#[doc(hidden)]
470pub struct LayerVTable {
471 layer_data: fn(&App, HandleId) -> &LayerData,
472 layer_data_mut: fn(&mut App, HandleId) -> &mut LayerData,
473 supports_rasterization: fn(&App, HandleId) -> bool,
474 describe_clip_bounds: fn(&App, HandleId) -> Option<Rect>,
475 always_needs_add_to_scene: fn(&App, HandleId) -> bool,
476 dispose: fn(&mut App, HandleId),
477 attach: fn(&mut App, HandleId, HandleId),
478 detach: fn(&mut App, HandleId),
479 redepth_children: fn(&mut App, HandleId),
480 find_annotations: fn(&App, HandleId, &mut AnnotationSearch, Offset, bool) -> bool,
481 add_to_scene: fn(&mut App, HandleId, &mut SceneBuilder),
482 fire_composition_callbacks: fn(&mut App, HandleId, bool),
483 as_container: Option<fn() -> &'static ContainerLayerVTable>,
484}
485
486impl LayerVTable {
487 pub const fn of<T: Layer>() -> LayerVTable {
488 LayerVTable {
489 layer_data: |app, id| T::layer_data(resolve(id), app),
490 layer_data_mut: |app, id| T::layer_data_mut(resolve(id), app),
491 supports_rasterization: |app, id| T::supports_rasterization(resolve(id), app),
492 describe_clip_bounds: |app, id| T::describe_clip_bounds(resolve(id), app),
493 always_needs_add_to_scene: |app, id| T::always_needs_add_to_scene(resolve(id), app),
494 dispose: |app, id| T::dispose(resolve(id), app),
495 attach: |app, id, owner| T::attach(resolve(id), app, owner),
496 detach: |app, id| T::detach(resolve(id), app),
497 redepth_children: |app, id| T::redepth_children(resolve(id), app),
498 find_annotations: |app, id, result, local_position, only_first| {
499 T::find_annotations(resolve(id), app, result, local_position, only_first)
500 },
501 add_to_scene: |app, id, builder| T::add_to_scene(resolve(id), app, builder),
502 fire_composition_callbacks: |app, id, include_children| {
503 T::fire_composition_callbacks(resolve(id), app, include_children)
504 },
505 as_container: T::AS_CONTAINER,
506 }
507 }
508}
509
510#[derive(Clone, Copy)]
515pub struct AnyLayer {
516 id: HandleId,
517 vtable: &'static LayerVTable,
518}
519
520impl PartialEq for AnyLayer {
521 fn eq(&self, other: &AnyLayer) -> bool {
522 self.id == other.id
523 }
524}
525
526impl Eq for AnyLayer {}
527
528impl Hash for AnyLayer {
529 fn hash<H: Hasher>(&self, state: &mut H) {
530 self.id.hash(state);
531 }
532}
533
534impl From<AnyLayer> for HandleId {
535 fn from(layer: AnyLayer) -> HandleId {
536 layer.id
537 }
538}
539
540impl Debug for AnyLayer {
541 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542 write!(f, "AnyLayer({:?})", self.id)
543 }
544}
545
546impl AnyLayer {
547 pub fn id(self) -> HandleId {
548 self.id
549 }
550
551 fn data(self, app: &App) -> &LayerData {
552 (self.vtable.layer_data)(app, self.id)
553 }
554
555 fn data_mut(self, app: &mut App) -> &mut LayerData {
556 (self.vtable.layer_data_mut)(app, self.id)
557 }
558
559 pub fn as_container_layer(self) -> Option<AnyContainerLayer> {
561 self.vtable
562 .as_container
563 .map(|vtable| AnyContainerLayer::from_vtable(self.id, vtable()))
564 }
565
566 pub fn subtree_has_composition_callbacks(self, app: &App) -> bool {
572 self.data(app).composition_callback_count > 0
573 }
574
575 fn update_subtree_composition_observer_count(self, app: &mut App, delta: i32) {
576 debug_assert!(delta != 0);
577 let data = self.data_mut(app);
578 data.composition_callback_count += delta;
579 debug_assert!(data.composition_callback_count >= 0);
580 if let Some(parent) = data.parent {
581 parent
582 .as_layer()
583 .update_subtree_composition_observer_count(app, delta);
584 }
585 }
586
587 pub(crate) fn fire_composition_callbacks(self, app: &mut App, include_children: bool) {
589 (self.vtable.fire_composition_callbacks)(app, self.id, include_children);
590 }
591
592 fn run_composition_callback(self, app: &mut App, callback: &CompositionCallback) {
594 if cfg!(debug_assertions) {
595 self.data_mut(app).debug_mutations_locked = true;
596 }
597 callback(app, self);
598 if cfg!(debug_assertions) {
599 self.data_mut(app).debug_mutations_locked = false;
600 }
601 }
602
603 pub fn supports_rasterization(self, app: &App) -> bool {
605 (self.vtable.supports_rasterization)(app, self.id)
606 }
607
608 pub fn describe_clip_bounds(self, app: &App) -> Option<Rect> {
610 (self.vtable.describe_clip_bounds)(app, self.id)
611 }
612
613 pub fn add_composition_callback(
631 self,
632 app: &mut App,
633 callback: CompositionCallback,
634 ) -> Box<dyn FnOnce(&mut App)> {
635 self.update_subtree_composition_observer_count(app, 1);
636 let callback_id = NEXT_CALLBACK_ID.fetch_add(1, Ordering::Relaxed) + 1;
637 self.data_mut(app).callbacks.push((callback_id, callback));
638 Box::new(move |app: &mut App| {
639 if !app.contains(self.id) {
641 return;
642 }
643 let index = self
644 .data(app)
645 .callbacks
646 .iter()
647 .position(|(id, _)| *id == callback_id);
648 debug_assert!(self.debug_disposed(app) || index.is_some());
649 if let Some(index) = index {
650 self.data_mut(app).callbacks.remove(index);
651 }
652 self.update_subtree_composition_observer_count(app, -1);
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 }
1074
1075 pub fn picture(self: Handle<Self>, app: &App) -> Option<&Arc<Picture>> {
1079 app.get(self).picture.as_ref()
1080 }
1081
1082 pub fn set_picture(self: Handle<Self>, app: &mut App, picture: Option<Arc<Picture>>) {
1084 debug_assert!(!app.get(self).layer.debug_disposed);
1085 self.as_layer().mark_needs_add_to_scene(app);
1086 app.get_mut(self).picture = picture;
1087 }
1088
1089 pub fn is_complex_hint(self: Handle<Self>, app: &App) -> bool {
1094 app.get(self).is_complex_hint
1095 }
1096
1097 pub fn set_is_complex_hint(self: Handle<Self>, app: &mut App, value: bool) {
1099 if value != app.get(self).is_complex_hint {
1100 app.get_mut(self).is_complex_hint = value;
1101 self.as_layer().mark_needs_add_to_scene(app);
1102 }
1103 }
1104
1105 pub fn will_change_hint(self: Handle<Self>, app: &App) -> bool {
1111 app.get(self).will_change_hint
1112 }
1113
1114 pub fn set_will_change_hint(self: Handle<Self>, app: &mut App, value: bool) {
1116 if value != app.get(self).will_change_hint {
1117 app.get_mut(self).will_change_hint = value;
1118 self.as_layer().mark_needs_add_to_scene(app);
1119 }
1120 }
1121}
1122
1123impl Layer for PictureLayer {
1124 crate::layer_accessors!();
1125
1126 fn dispose(self: Handle<Self>, app: &mut App) {
1127 self.set_picture(app, None); LayerBase::dispose(self, app);
1129 }
1130
1131 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1132 let this = app.get(self);
1133 let picture = this
1134 .picture
1135 .as_ref()
1136 .expect("a PictureLayer has a picture when it is added to the scene");
1137 builder.add_picture(
1138 Offset::ZERO,
1139 picture,
1140 this.is_complex_hint,
1141 this.will_change_hint,
1142 );
1143 }
1144
1145 fn find_annotations(
1146 self: Handle<Self>,
1147 _app: &App,
1148 _result: &mut AnnotationSearch,
1149 _local_position: Offset,
1150 _only_first: bool,
1151 ) -> bool {
1152 false
1153 }
1154}
1155
1156pub struct SurfaceLayer {
1161 layer: LayerData,
1162 surface: Arc<dyn Surface>,
1163 rect: Rect,
1165}
1166
1167impl SurfaceLayer {
1168 pub fn new(app: &mut App, surface: Arc<dyn Surface>, rect: Rect) -> Handle<SurfaceLayer> {
1170 app.create(SurfaceLayer {
1171 layer: LayerData::new(),
1172 surface,
1173 rect,
1174 })
1175 }
1176
1177 pub fn surface(self: Handle<Self>, app: &App) -> &Arc<dyn Surface> {
1178 &app.get(self).surface
1179 }
1180
1181 pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1182 app.get(self).rect
1183 }
1184}
1185
1186impl Layer for SurfaceLayer {
1187 crate::layer_accessors!();
1188
1189 fn always_needs_add_to_scene(self: Handle<Self>, _app: &App) -> bool {
1190 true
1191 }
1192
1193 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1194 let this = app.get(self);
1195 builder.add_surface(Arc::clone(&this.surface), this.rect);
1196 }
1197
1198 fn find_annotations(
1199 self: Handle<Self>,
1200 _app: &App,
1201 _result: &mut AnnotationSearch,
1202 _local_position: Offset,
1203 _only_first: bool,
1204 ) -> bool {
1205 false
1206 }
1207}
1208
1209#[derive(Debug, Default)]
1212pub struct ContainerLayerData {
1213 first_child: Option<AnyLayer>,
1214 last_child: Option<AnyLayer>,
1215}
1216
1217impl ContainerLayerData {
1218 pub const fn new() -> ContainerLayerData {
1220 ContainerLayerData {
1221 first_child: None,
1222 last_child: None,
1223 }
1224 }
1225}
1226
1227#[macro_export]
1232macro_rules! container_layer_accessors {
1233 () => {
1234 fn container_layer_data(
1235 self: ::inset_foundation::Handle<Self>,
1236 app: &::inset_foundation::App,
1237 ) -> &$crate::ContainerLayerData {
1238 &app.get(self).container_layer
1239 }
1240 fn container_layer_data_mut(
1241 self: ::inset_foundation::Handle<Self>,
1242 app: &mut ::inset_foundation::App,
1243 ) -> &mut $crate::ContainerLayerData {
1244 &mut app.get_mut(self).container_layer
1245 }
1246 };
1247 (offset) => {
1248 $crate::container_layer_accessors!();
1249 const AS_OFFSET: Option<fn() -> &'static $crate::OffsetLayerVTable> =
1250 Some(|| const { &$crate::OffsetLayerVTable::of::<Self>() });
1251 };
1252}
1253
1254pub trait ContainerLayer: Layer {
1264 fn container_layer_data(self: Handle<Self>, app: &App) -> &ContainerLayerData;
1266
1267 fn container_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut ContainerLayerData;
1269
1270 const AS_OFFSET: Option<fn() -> &'static OffsetLayerVTable> = None;
1273
1274 fn as_container_layer(self: Handle<Self>) -> AnyContainerLayer {
1276 AnyContainerLayer {
1277 id: self.id(),
1278 vtable: const { &ContainerLayerVTable::of::<Self>() },
1279 }
1280 }
1281
1282 fn apply_transform(
1304 self: Handle<Self>,
1305 app: &App,
1306 child: Option<AnyLayer>,
1307 transform: &mut Matrix4,
1308 ) {
1309 let _ = (self, app, transform);
1310 debug_assert!(child.is_some());
1311 }
1312
1313 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
1315 LayerBase::fire_composition_callbacks(self, app, include_children);
1316 if !include_children {
1317 return;
1318 }
1319 let mut child = self.as_container_layer().first_child(app);
1320 while let Some(layer) = child {
1321 layer.fire_composition_callbacks(app, include_children);
1322 child = layer.next_sibling(app);
1323 }
1324 }
1325
1326 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
1328 let mut child = self.as_container_layer().last_child(app);
1329 while let Some(layer) = child {
1330 if !layer.supports_rasterization(app) {
1331 return false;
1332 }
1333 child = layer.previous_sibling(app);
1334 }
1335 true
1336 }
1337
1338 fn dispose(self: Handle<Self>, app: &mut App) {
1340 self.as_container_layer().remove_all_children(app);
1341 self.layer_data_mut(app).callbacks.clear();
1342 LayerBase::dispose(self, app);
1343 }
1344
1345 fn find_annotations(
1347 self: Handle<Self>,
1348 app: &App,
1349 result: &mut AnnotationSearch,
1350 local_position: Offset,
1351 only_first: bool,
1352 ) -> bool {
1353 let mut child = self.as_container_layer().last_child(app);
1354 while let Some(layer) = child {
1355 let is_absorbed = layer.find_annotations(app, result, local_position, only_first);
1356 if is_absorbed {
1357 return true;
1358 }
1359 if only_first && !result.is_empty() {
1360 return is_absorbed;
1361 }
1362 child = layer.previous_sibling(app);
1363 }
1364 false
1365 }
1366
1367 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
1369 debug_assert!(!self.layer_data(app).debug_mutations_locked);
1370 LayerBase::attach(self, app, owner);
1371 let mut child = self.as_container_layer().first_child(app);
1372 while let Some(layer) = child {
1373 layer.attach(app, owner);
1374 child = layer.next_sibling(app);
1375 }
1376 }
1377
1378 fn detach(self: Handle<Self>, app: &mut App) {
1380 debug_assert!(!self.layer_data(app).debug_mutations_locked);
1381 LayerBase::detach(self, app);
1382 let mut child = self.as_container_layer().first_child(app);
1383 while let Some(layer) = child {
1384 layer.detach(app);
1385 child = layer.next_sibling(app);
1386 }
1387 self.as_layer().fire_composition_callbacks(app, false);
1394 }
1395
1396 fn redepth_children(self: Handle<Self>, app: &mut App) {
1398 let this = self.as_container_layer();
1399 let mut child = this.first_child(app);
1400 while let Some(layer) = child {
1401 this.redepth_child(app, layer);
1402 child = layer.next_sibling(app);
1403 }
1404 }
1405
1406 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1408 self.as_container_layer()
1409 .add_children_to_scene(app, builder);
1410 }
1411}
1412
1413#[doc(hidden)]
1417pub struct ContainerLayerVTable {
1418 layer: LayerVTable,
1419 container_data: fn(&App, HandleId) -> &ContainerLayerData,
1420 container_data_mut: fn(&mut App, HandleId) -> &mut ContainerLayerData,
1421 apply_transform: fn(&App, HandleId, Option<AnyLayer>, &mut Matrix4),
1422 as_offset: Option<fn() -> &'static OffsetLayerVTable>,
1423}
1424
1425impl ContainerLayerVTable {
1426 pub const fn of<T: ContainerLayer>() -> ContainerLayerVTable {
1427 ContainerLayerVTable {
1428 layer: LayerVTable::of::<T>(),
1429 container_data: |app, id| T::container_layer_data(resolve(id), app),
1430 container_data_mut: |app, id| T::container_layer_data_mut(resolve(id), app),
1431 apply_transform: |app, id, child, transform| {
1432 T::apply_transform(resolve(id), app, child, transform)
1433 },
1434 as_offset: T::AS_OFFSET,
1435 }
1436 }
1437}
1438
1439#[derive(Clone, Copy)]
1441pub struct AnyContainerLayer {
1442 id: HandleId,
1443 vtable: &'static ContainerLayerVTable,
1444}
1445
1446impl PartialEq for AnyContainerLayer {
1447 fn eq(&self, other: &AnyContainerLayer) -> bool {
1448 self.id == other.id
1449 }
1450}
1451
1452impl Eq for AnyContainerLayer {}
1453
1454impl Hash for AnyContainerLayer {
1455 fn hash<H: Hasher>(&self, state: &mut H) {
1456 self.id.hash(state);
1457 }
1458}
1459
1460impl From<AnyContainerLayer> for HandleId {
1461 fn from(layer: AnyContainerLayer) -> HandleId {
1462 layer.id
1463 }
1464}
1465
1466impl Debug for AnyContainerLayer {
1467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1468 write!(f, "AnyContainerLayer({:?})", self.id)
1469 }
1470}
1471
1472impl ErasedLayer for AnyContainerLayer {
1473 fn as_layer(self) -> AnyLayer {
1474 AnyLayer {
1475 id: self.id,
1476 vtable: &self.vtable.layer,
1477 }
1478 }
1479}
1480
1481impl AnyContainerLayer {
1482 fn from_vtable(id: HandleId, vtable: &'static ContainerLayerVTable) -> AnyContainerLayer {
1483 AnyContainerLayer { id, vtable }
1484 }
1485
1486 pub fn id(self) -> HandleId {
1487 self.id
1488 }
1489
1490 pub fn as_offset_layer(self) -> Option<AnyOffsetLayer> {
1492 self.vtable
1493 .as_offset
1494 .map(|vtable| AnyOffsetLayer::from_vtable(self.id, vtable()))
1495 }
1496
1497 fn data(self, app: &App) -> &ContainerLayerData {
1498 (self.vtable.container_data)(app, self.id)
1499 }
1500
1501 fn data_mut(self, app: &mut App) -> &mut ContainerLayerData {
1502 (self.vtable.container_data_mut)(app, self.id)
1503 }
1504
1505 pub fn first_child(self, app: &App) -> Option<AnyLayer> {
1507 self.data(app).first_child
1508 }
1509
1510 pub fn last_child(self, app: &App) -> Option<AnyLayer> {
1512 self.data(app).last_child
1513 }
1514
1515 pub fn has_children(self, app: &App) -> bool {
1517 self.data(app).first_child.is_some()
1518 }
1519
1520 pub fn build_scene(self, app: &mut App, mut builder: SceneBuilder) -> Scene {
1526 let this = self.as_layer();
1527 this.update_subtree_needs_add_to_scene(app);
1528 this.add_to_scene(app, &mut builder);
1529 if this.subtree_has_composition_callbacks(app) {
1530 this.fire_composition_callbacks(app, true);
1531 }
1532 this.data_mut(app).needs_add_to_scene = false;
1535 builder.build()
1536 }
1537
1538 fn debug_ultimate_previous_sibling_of(
1539 self,
1540 app: &App,
1541 mut child: AnyLayer,
1542 equals: Option<AnyLayer>,
1543 ) -> bool {
1544 let attached = self.as_layer().attached(app);
1545 debug_assert!(child.attached(app) == attached);
1546 while let Some(previous) = child.previous_sibling(app) {
1547 debug_assert!(previous != child);
1548 child = previous;
1549 debug_assert!(child.attached(app) == attached);
1550 }
1551 Some(child) == equals
1552 }
1553
1554 fn debug_ultimate_next_sibling_of(
1555 self,
1556 app: &App,
1557 mut child: AnyLayer,
1558 equals: Option<AnyLayer>,
1559 ) -> bool {
1560 let attached = self.as_layer().attached(app);
1561 debug_assert!(child.attached(app) == attached);
1562 while let Some(next) = child.next_sibling(app) {
1563 debug_assert!(next != child);
1564 child = next;
1565 debug_assert!(child.attached(app) == attached);
1566 }
1567 Some(child) == equals
1568 }
1569
1570 pub fn append(self, app: &mut App, child: AnyLayer) {
1572 let this = self.as_layer();
1573 debug_assert!(!this.data(app).debug_mutations_locked);
1574 debug_assert!(child != this);
1575 debug_assert!(Some(child) != self.first_child(app));
1576 debug_assert!(Some(child) != self.last_child(app));
1577 debug_assert!(child.parent(app).is_none());
1578 debug_assert!(!child.attached(app));
1579 debug_assert!(child.next_sibling(app).is_none());
1580 debug_assert!(child.previous_sibling(app).is_none());
1581 debug_assert!(child.data(app).parent_handle.layer().is_none());
1582 debug_assert!(self.debug_root(app) != child); self.adopt_child(app, child);
1584 let last_child = self.last_child(app);
1585 child.data_mut(app).previous_sibling = last_child;
1586 if let Some(last_child) = last_child {
1587 last_child.data_mut(app).next_sibling = Some(child);
1588 }
1589 let data = self.data_mut(app);
1590 data.last_child = Some(child);
1591 data.first_child.get_or_insert(child);
1592 LayerHandle::set_layer(
1593 app,
1594 |app| &mut child.data_mut(app).parent_handle,
1595 Some(child),
1596 );
1597 debug_assert!(child.attached(app) == this.attached(app));
1598 }
1599
1600 fn debug_root(self, app: &App) -> AnyLayer {
1603 let mut node = self.as_layer();
1604 while let Some(parent) = node.parent(app) {
1605 node = parent.as_layer();
1606 }
1607 node
1608 }
1609
1610 fn adopt_child(self, app: &mut App, child: AnyLayer) {
1611 let this = self.as_layer();
1612 debug_assert!(!this.data(app).debug_mutations_locked);
1613 if !this.always_needs_add_to_scene(app) {
1614 this.mark_needs_add_to_scene(app);
1615 }
1616 let callback_count = child.data(app).composition_callback_count;
1617 if callback_count != 0 {
1618 this.update_subtree_composition_observer_count(app, callback_count);
1619 }
1620 debug_assert!(child.data(app).parent.is_none());
1621 debug_assert!(self.debug_root(app) != child); child.data_mut(app).parent = Some(self);
1623 if let Some(owner) = this.owner(app) {
1624 child.attach(app, owner);
1625 }
1626 self.redepth_child(app, child);
1627 }
1628
1629 pub fn redepth_child(self, app: &mut App, child: AnyLayer) {
1633 let this = self.as_layer();
1634 debug_assert!(child.owner(app) == this.owner(app));
1635 let depth = this.depth(app);
1636 if child.depth(app) <= depth {
1637 child.data_mut(app).depth = depth + 1;
1638 child.redepth_children(app);
1639 }
1640 }
1641
1642 pub(crate) fn remove_child(self, app: &mut App, child: AnyLayer) {
1644 let this = self.as_layer();
1645 debug_assert!(child.parent(app) == Some(self));
1646 debug_assert!(child.attached(app) == this.attached(app));
1647 debug_assert!(self.debug_ultimate_previous_sibling_of(app, child, self.first_child(app)));
1648 debug_assert!(self.debug_ultimate_next_sibling_of(app, child, self.last_child(app)));
1649 debug_assert!(child.data(app).parent_handle.layer().is_some());
1650 let previous_sibling = child.previous_sibling(app);
1651 let next_sibling = child.next_sibling(app);
1652 match previous_sibling {
1653 None => {
1654 debug_assert!(self.first_child(app) == Some(child));
1655 self.data_mut(app).first_child = next_sibling;
1656 }
1657 Some(previous) => previous.data_mut(app).next_sibling = next_sibling,
1658 }
1659 match next_sibling {
1660 None => {
1661 debug_assert!(self.last_child(app) == Some(child));
1662 self.data_mut(app).last_child = previous_sibling;
1663 }
1664 Some(next) => next.data_mut(app).previous_sibling = previous_sibling,
1665 }
1666 self.debug_check_child_list(app);
1667 let data = child.data_mut(app);
1668 data.previous_sibling = None;
1669 data.next_sibling = None;
1670 self.drop_child(app, child);
1671 LayerHandle::set_layer(app, |app| &mut child.data_mut(app).parent_handle, None);
1672 debug_assert!(child.debug_disposed(app) || !child.attached(app));
1674 }
1675
1676 fn debug_check_child_list(self, app: &App) {
1678 let attached = self.as_layer().attached(app);
1679 let first_child = self.first_child(app);
1680 let last_child = self.last_child(app);
1681 debug_assert!(first_child.is_none() == last_child.is_none());
1682 debug_assert!(first_child.is_none_or(|first| first.attached(app) == attached));
1683 debug_assert!(last_child.is_none_or(|last| last.attached(app) == attached));
1684 debug_assert!(
1685 first_child
1686 .is_none_or(|first| self.debug_ultimate_next_sibling_of(app, first, last_child))
1687 );
1688 debug_assert!(
1689 last_child.is_none_or(|last| self.debug_ultimate_previous_sibling_of(
1690 app,
1691 last,
1692 first_child
1693 ))
1694 );
1695 }
1696
1697 fn drop_child(self, app: &mut App, child: AnyLayer) {
1698 let this = self.as_layer();
1699 debug_assert!(!this.data(app).debug_mutations_locked);
1700 if !this.always_needs_add_to_scene(app) {
1701 this.mark_needs_add_to_scene(app);
1702 }
1703 let callback_count = child.data(app).composition_callback_count;
1704 if callback_count != 0 {
1705 this.update_subtree_composition_observer_count(app, -callback_count);
1706 }
1707 debug_assert!(child.data(app).parent == Some(self));
1708 debug_assert!(child.attached(app) == this.attached(app));
1709 child.data_mut(app).parent = None;
1710 if this.attached(app) {
1711 child.detach(app);
1712 }
1713 }
1714
1715 pub fn remove_all_children(self, app: &mut App) {
1717 let this = self.as_layer();
1718 debug_assert!(!this.data(app).debug_mutations_locked);
1719 let mut child = self.first_child(app);
1720 while let Some(layer) = child {
1721 let next = layer.next_sibling(app);
1722 let data = layer.data_mut(app);
1723 data.previous_sibling = None;
1724 data.next_sibling = None;
1725 debug_assert!(layer.attached(app) == this.attached(app));
1726 self.drop_child(app, layer);
1727 LayerHandle::set_layer(app, |app| &mut layer.data_mut(app).parent_handle, None);
1728 child = next;
1729 }
1730 let data = self.data_mut(app);
1731 data.first_child = None;
1732 data.last_child = None;
1733 }
1734
1735 pub fn add_children_to_scene(self, app: &mut App, builder: &mut SceneBuilder) {
1743 let mut child = self.first_child(app);
1744 while let Some(layer) = child {
1745 layer.add_to_scene_with_retained_rendering(app, builder);
1746 child = layer.next_sibling(app);
1747 }
1748 }
1749
1750 pub fn apply_transform(self, app: &App, child: Option<AnyLayer>, transform: &mut Matrix4) {
1752 (self.vtable.apply_transform)(app, self.id, child, transform);
1753 }
1754
1755 pub fn depth_first_iterate_children(self, app: &App) -> Vec<AnyLayer> {
1757 let mut children = Vec::new();
1758 let mut child = self.first_child(app);
1759 while let Some(layer) = child {
1760 children.push(layer);
1761 if let Some(container) = layer.as_container_layer() {
1762 children.extend(container.depth_first_iterate_children(app));
1763 }
1764 child = layer.next_sibling(app);
1765 }
1766 children
1767 }
1768}
1769
1770#[derive(Debug)]
1773pub struct OffsetLayerData {
1774 offset: Offset,
1775}
1776
1777impl OffsetLayerData {
1778 pub const fn new(offset: Offset) -> OffsetLayerData {
1780 OffsetLayerData { offset }
1781 }
1782}
1783
1784impl Default for OffsetLayerData {
1785 fn default() -> OffsetLayerData {
1787 OffsetLayerData::new(Offset::ZERO)
1788 }
1789}
1790
1791#[macro_export]
1793macro_rules! offset_layer_accessors {
1794 () => {
1795 fn offset_layer_data(
1796 self: ::inset_foundation::Handle<Self>,
1797 app: &::inset_foundation::App,
1798 ) -> &$crate::OffsetLayerData {
1799 &app.get(self).offset_layer
1800 }
1801 fn offset_layer_data_mut(
1802 self: ::inset_foundation::Handle<Self>,
1803 app: &mut ::inset_foundation::App,
1804 ) -> &mut $crate::OffsetLayerData {
1805 &mut app.get_mut(self).offset_layer
1806 }
1807 };
1808}
1809
1810pub trait OffsetLayerMixin: ContainerLayer {
1822 fn offset_layer_data(self: Handle<Self>, app: &App) -> &OffsetLayerData;
1824
1825 fn offset_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut OffsetLayerData;
1827
1828 fn as_offset_layer(self: Handle<Self>) -> AnyOffsetLayer {
1830 AnyOffsetLayer {
1831 id: self.id(),
1832 vtable: const { &OffsetLayerVTable::of::<Self>() },
1833 }
1834 }
1835
1836 fn offset(self: Handle<Self>, app: &App) -> Offset {
1838 self.offset_layer_data(app).offset
1839 }
1840
1841 fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
1843 self.offset_layer_data_mut(app).offset = value;
1844 }
1845
1846 fn find_annotations(
1848 self: Handle<Self>,
1849 app: &App,
1850 result: &mut AnnotationSearch,
1851 local_position: Offset,
1852 only_first: bool,
1853 ) -> bool {
1854 let offset = self.offset(app);
1855 ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
1856 }
1857
1858 fn apply_transform(
1860 self: Handle<Self>,
1861 app: &App,
1862 child: Option<AnyLayer>,
1863 transform: &mut Matrix4,
1864 ) {
1865 debug_assert!(child.is_some());
1866 let offset = self.offset(app);
1867 *transform = transform.then(&Matrix4::translation(
1868 offset.dx() as f32,
1869 offset.dy() as f32,
1870 ));
1871 }
1872
1873 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1875 let offset = self.offset(app);
1881 builder.push_offset(offset.dx(), offset.dy());
1882 self.as_container_layer()
1883 .add_children_to_scene(app, builder);
1884 let engine_layer = builder.pop();
1885 self.as_layer().set_engine_layer(app, Some(engine_layer));
1886 }
1887}
1888
1889#[doc(hidden)]
1893pub struct OffsetLayerVTable {
1894 container: ContainerLayerVTable,
1895 offset_data: fn(&App, HandleId) -> &OffsetLayerData,
1896 offset_data_mut: fn(&mut App, HandleId) -> &mut OffsetLayerData,
1897}
1898
1899impl OffsetLayerVTable {
1900 pub const fn of<T: OffsetLayerMixin>() -> OffsetLayerVTable {
1901 OffsetLayerVTable {
1902 container: ContainerLayerVTable::of::<T>(),
1903 offset_data: |app, id| T::offset_layer_data(resolve(id), app),
1904 offset_data_mut: |app, id| T::offset_layer_data_mut(resolve(id), app),
1905 }
1906 }
1907}
1908
1909#[derive(Clone, Copy)]
1912pub struct AnyOffsetLayer {
1913 id: HandleId,
1914 vtable: &'static OffsetLayerVTable,
1915}
1916
1917impl PartialEq for AnyOffsetLayer {
1918 fn eq(&self, other: &AnyOffsetLayer) -> bool {
1919 self.id == other.id
1920 }
1921}
1922
1923impl Eq for AnyOffsetLayer {}
1924
1925impl Hash for AnyOffsetLayer {
1926 fn hash<H: Hasher>(&self, state: &mut H) {
1927 self.id.hash(state);
1928 }
1929}
1930
1931impl From<AnyOffsetLayer> for HandleId {
1932 fn from(layer: AnyOffsetLayer) -> HandleId {
1933 layer.id
1934 }
1935}
1936
1937impl Debug for AnyOffsetLayer {
1938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1939 write!(f, "AnyOffsetLayer({:?})", self.id)
1940 }
1941}
1942
1943impl ErasedLayer for AnyOffsetLayer {
1944 fn as_layer(self) -> AnyLayer {
1945 self.as_container_layer().as_layer()
1946 }
1947}
1948
1949impl AnyOffsetLayer {
1950 fn from_vtable(id: HandleId, vtable: &'static OffsetLayerVTable) -> AnyOffsetLayer {
1951 AnyOffsetLayer { id, vtable }
1952 }
1953
1954 pub fn id(self) -> HandleId {
1955 self.id
1956 }
1957
1958 pub fn as_container_layer(self) -> AnyContainerLayer {
1960 AnyContainerLayer::from_vtable(self.id, &self.vtable.container)
1961 }
1962
1963 pub fn offset(self, app: &App) -> Offset {
1965 (self.vtable.offset_data)(app, self.id).offset
1966 }
1967
1968 pub fn set_offset(self, app: &mut App, value: Offset) {
1970 if value == self.offset(app) {
1971 return;
1972 }
1973 (self.vtable.offset_data_mut)(app, self.id).offset = value;
1974 if !self.as_layer().always_needs_add_to_scene(app) {
1975 self.as_layer().mark_needs_add_to_scene(app);
1976 }
1977 }
1978}
1979
1980pub struct OffsetLayer {
1982 layer: LayerData,
1983 container_layer: ContainerLayerData,
1984 offset_layer: OffsetLayerData,
1985}
1986
1987impl OffsetLayer {
1988 pub fn new(app: &mut App, offset: Offset) -> Handle<OffsetLayer> {
1992 app.create(OffsetLayer {
1993 layer: LayerData::new(),
1994 container_layer: ContainerLayerData::new(),
1995 offset_layer: OffsetLayerData::new(offset),
1996 })
1997 }
1998}
1999
2000impl Layer for OffsetLayer {
2001 crate::layer_accessors!(container);
2002
2003 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2004 ContainerLayer::supports_rasterization(self, app)
2005 }
2006
2007 fn dispose(self: Handle<Self>, app: &mut App) {
2008 ContainerLayer::dispose(self, app);
2009 }
2010
2011 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2012 ContainerLayer::attach(self, app, owner);
2013 }
2014
2015 fn detach(self: Handle<Self>, app: &mut App) {
2016 ContainerLayer::detach(self, app);
2017 }
2018
2019 fn redepth_children(self: Handle<Self>, app: &mut App) {
2020 ContainerLayer::redepth_children(self, app);
2021 }
2022
2023 fn find_annotations(
2024 self: Handle<Self>,
2025 app: &App,
2026 result: &mut AnnotationSearch,
2027 local_position: Offset,
2028 only_first: bool,
2029 ) -> bool {
2030 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2031 }
2032
2033 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2034 OffsetLayerMixin::add_to_scene(self, app, builder);
2035 }
2036
2037 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2038 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2039 }
2040}
2041
2042impl ContainerLayer for OffsetLayer {
2043 crate::container_layer_accessors!(offset);
2044
2045 fn apply_transform(
2046 self: Handle<Self>,
2047 app: &App,
2048 child: Option<AnyLayer>,
2049 transform: &mut Matrix4,
2050 ) {
2051 OffsetLayerMixin::apply_transform(self, app, child, transform);
2052 }
2053}
2054
2055impl OffsetLayerMixin for OffsetLayer {
2056 crate::offset_layer_accessors!();
2057}
2058
2059#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2064pub struct BackdropKey(u64);
2065
2066static NEXT_BACKDROP_KEY: AtomicU64 = AtomicU64::new(0);
2067
2068impl BackdropKey {
2069 #[expect(
2071 clippy::new_without_default,
2072 reason = "each call creates a distinct key; Default would suggest a neutral value"
2073 )]
2074 pub fn new() -> BackdropKey {
2075 BackdropKey(NEXT_BACKDROP_KEY.fetch_add(1, Ordering::Relaxed))
2076 }
2077
2078 pub fn id(self) -> u64 {
2080 self.0
2081 }
2082}
2083
2084pub struct ClipRectLayer {
2090 layer: LayerData,
2091 container_layer: ContainerLayerData,
2092 clip_rect: Option<Rect>,
2093 clip_behavior: Clip,
2094}
2095
2096impl ClipRectLayer {
2097 pub fn new(app: &mut App) -> Handle<ClipRectLayer> {
2104 debug_assert!(Clip::HardEdge != Clip::None);
2105 app.create(ClipRectLayer {
2106 layer: LayerData::new(),
2107 container_layer: ContainerLayerData::new(),
2108 clip_rect: None,
2109 clip_behavior: Clip::HardEdge,
2110 })
2111 }
2112
2113 pub fn clip_rect(self: Handle<Self>, app: &App) -> Option<Rect> {
2118 app.get(self).clip_rect
2119 }
2120
2121 pub fn set_clip_rect(self: Handle<Self>, app: &mut App, value: Option<Rect>) {
2123 if value != app.get(self).clip_rect {
2124 app.get_mut(self).clip_rect = value;
2125 self.as_layer().mark_needs_add_to_scene(app);
2126 }
2127 }
2128
2129 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2135 app.get(self).clip_behavior
2136 }
2137
2138 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2140 debug_assert!(value != Clip::None);
2141 if value != app.get(self).clip_behavior {
2142 app.get_mut(self).clip_behavior = value;
2143 self.as_layer().mark_needs_add_to_scene(app);
2144 }
2145 }
2146}
2147
2148impl Layer for ClipRectLayer {
2149 crate::layer_accessors!(container);
2150
2151 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2152 self.clip_rect(app)
2153 }
2154
2155 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2156 ContainerLayer::supports_rasterization(self, app)
2157 }
2158
2159 fn dispose(self: Handle<Self>, app: &mut App) {
2160 ContainerLayer::dispose(self, app);
2161 }
2162
2163 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2164 ContainerLayer::attach(self, app, owner);
2165 }
2166
2167 fn detach(self: Handle<Self>, app: &mut App) {
2168 ContainerLayer::detach(self, app);
2169 }
2170
2171 fn redepth_children(self: Handle<Self>, app: &mut App) {
2172 ContainerLayer::redepth_children(self, app);
2173 }
2174
2175 fn find_annotations(
2176 self: Handle<Self>,
2177 app: &App,
2178 result: &mut AnnotationSearch,
2179 local_position: Offset,
2180 only_first: bool,
2181 ) -> bool {
2182 if !self
2183 .clip_rect(app)
2184 .expect("clipRect must be set before searching annotations")
2185 .contains(local_position)
2186 {
2187 return false;
2188 }
2189 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2190 }
2191
2192 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2193 debug_assert!(self.clip_rect(app).is_some());
2194 let mut enabled = true;
2195 if cfg!(debug_assertions) {
2196 enabled = !crate::debug::debug_disable_clip_layers();
2197 }
2198 if enabled {
2199 let clip_rect = self
2200 .clip_rect(app)
2201 .expect("clipRect must be set before compositing");
2202 let clip_behavior = self.clip_behavior(app);
2203 builder.push_clip_rect(clip_rect, clip_behavior);
2204 }
2205 self.as_container_layer()
2206 .add_children_to_scene(app, builder);
2207 let engine_layer = enabled.then(|| builder.pop());
2208 self.as_layer().set_engine_layer(app, engine_layer);
2209 }
2210
2211 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2212 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2213 }
2214}
2215
2216impl ContainerLayer for ClipRectLayer {
2217 crate::container_layer_accessors!();
2218}
2219
2220pub struct ClipRRectLayer {
2226 layer: LayerData,
2227 container_layer: ContainerLayerData,
2228 clip_rrect: Option<RRect>,
2229 clip_behavior: Clip,
2230}
2231
2232impl ClipRRectLayer {
2233 pub fn new(app: &mut App) -> Handle<ClipRRectLayer> {
2238 debug_assert!(Clip::AntiAlias != Clip::None);
2239 app.create(ClipRRectLayer {
2240 layer: LayerData::new(),
2241 container_layer: ContainerLayerData::new(),
2242 clip_rrect: None,
2243 clip_behavior: Clip::AntiAlias,
2244 })
2245 }
2246
2247 pub fn clip_rrect(self: Handle<Self>, app: &App) -> Option<RRect> {
2252 app.get(self).clip_rrect
2253 }
2254
2255 pub fn set_clip_rrect(self: Handle<Self>, app: &mut App, value: Option<RRect>) {
2257 if value != app.get(self).clip_rrect {
2258 app.get_mut(self).clip_rrect = value;
2259 self.as_layer().mark_needs_add_to_scene(app);
2260 }
2261 }
2262
2263 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2269 app.get(self).clip_behavior
2270 }
2271
2272 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2274 debug_assert!(value != Clip::None);
2275 if value != app.get(self).clip_behavior {
2276 app.get_mut(self).clip_behavior = value;
2277 self.as_layer().mark_needs_add_to_scene(app);
2278 }
2279 }
2280}
2281
2282impl Layer for ClipRRectLayer {
2283 crate::layer_accessors!(container);
2284
2285 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2286 self.clip_rrect(app).map(RRect::outer_rect)
2287 }
2288
2289 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2290 ContainerLayer::supports_rasterization(self, app)
2291 }
2292
2293 fn dispose(self: Handle<Self>, app: &mut App) {
2294 ContainerLayer::dispose(self, app);
2295 }
2296
2297 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2298 ContainerLayer::attach(self, app, owner);
2299 }
2300
2301 fn detach(self: Handle<Self>, app: &mut App) {
2302 ContainerLayer::detach(self, app);
2303 }
2304
2305 fn redepth_children(self: Handle<Self>, app: &mut App) {
2306 ContainerLayer::redepth_children(self, app);
2307 }
2308
2309 fn find_annotations(
2310 self: Handle<Self>,
2311 app: &App,
2312 result: &mut AnnotationSearch,
2313 local_position: Offset,
2314 only_first: bool,
2315 ) -> bool {
2316 if !self
2317 .clip_rrect(app)
2318 .expect("clipRRect must be set before searching annotations")
2319 .contains(local_position)
2320 {
2321 return false;
2322 }
2323 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2324 }
2325
2326 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2327 debug_assert!(self.clip_rrect(app).is_some());
2328 let mut enabled = true;
2329 if cfg!(debug_assertions) {
2330 enabled = !crate::debug::debug_disable_clip_layers();
2331 }
2332 if enabled {
2333 let clip_rrect = self
2334 .clip_rrect(app)
2335 .expect("clipRRect must be set before compositing");
2336 let clip_behavior = self.clip_behavior(app);
2337 builder.push_clip_rrect(clip_rrect, clip_behavior);
2338 }
2339 self.as_container_layer()
2340 .add_children_to_scene(app, builder);
2341 let engine_layer = enabled.then(|| builder.pop());
2342 self.as_layer().set_engine_layer(app, engine_layer);
2343 }
2344
2345 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2346 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2347 }
2348}
2349
2350impl ContainerLayer for ClipRRectLayer {
2351 crate::container_layer_accessors!();
2352}
2353
2354pub struct ClipPathLayer {
2360 layer: LayerData,
2361 container_layer: ContainerLayerData,
2362 clip_path: Option<Arc<inset_embedder::Path>>,
2363 clip_behavior: Clip,
2364}
2365
2366impl ClipPathLayer {
2367 pub fn new(app: &mut App) -> Handle<ClipPathLayer> {
2372 debug_assert!(Clip::AntiAlias != Clip::None);
2373 app.create(ClipPathLayer {
2374 layer: LayerData::new(),
2375 container_layer: ContainerLayerData::new(),
2376 clip_path: None,
2377 clip_behavior: Clip::AntiAlias,
2378 })
2379 }
2380
2381 pub fn clip_path(self: Handle<Self>, app: &App) -> Option<&Arc<inset_embedder::Path>> {
2386 app.get(self).clip_path.as_ref()
2387 }
2388
2389 pub fn set_clip_path(
2391 self: Handle<Self>,
2392 app: &mut App,
2393 value: Option<Arc<inset_embedder::Path>>,
2394 ) {
2395 app.get_mut(self).clip_path = value;
2396 self.as_layer().mark_needs_add_to_scene(app);
2397 }
2398
2399 pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2405 app.get(self).clip_behavior
2406 }
2407
2408 pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2410 debug_assert!(value != Clip::None);
2411 if value != app.get(self).clip_behavior {
2412 app.get_mut(self).clip_behavior = value;
2413 self.as_layer().mark_needs_add_to_scene(app);
2414 }
2415 }
2416}
2417
2418impl Layer for ClipPathLayer {
2419 crate::layer_accessors!(container);
2420
2421 fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2422 let bounds = app.get(self).clip_path.as_ref()?.bounds();
2423 Some(Rect::from_ltwh(
2424 bounds.x as f64,
2425 bounds.y as f64,
2426 bounds.width as f64,
2427 bounds.height as f64,
2428 ))
2429 }
2430
2431 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2432 ContainerLayer::supports_rasterization(self, app)
2433 }
2434
2435 fn dispose(self: Handle<Self>, app: &mut App) {
2436 ContainerLayer::dispose(self, app);
2437 }
2438
2439 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2440 ContainerLayer::attach(self, app, owner);
2441 }
2442
2443 fn detach(self: Handle<Self>, app: &mut App) {
2444 ContainerLayer::detach(self, app);
2445 }
2446
2447 fn redepth_children(self: Handle<Self>, app: &mut App) {
2448 ContainerLayer::redepth_children(self, app);
2449 }
2450
2451 fn find_annotations(
2452 self: Handle<Self>,
2453 app: &App,
2454 result: &mut AnnotationSearch,
2455 local_position: Offset,
2456 only_first: bool,
2457 ) -> bool {
2458 let path = app
2459 .get(self)
2460 .clip_path
2461 .as_ref()
2462 .expect("clipPath must be set before searching annotations");
2463 if !path.contains(local_position.into(), FillRule::NonZero) {
2464 return false;
2465 }
2466 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2467 }
2468
2469 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2470 debug_assert!(app.get(self).clip_path.is_some());
2471 let mut enabled = true;
2472 if cfg!(debug_assertions) {
2473 enabled = !crate::debug::debug_disable_clip_layers();
2474 }
2475 if enabled {
2476 let clip_path = Arc::clone(
2477 app.get(self)
2478 .clip_path
2479 .as_ref()
2480 .expect("clipPath must be set before compositing"),
2481 );
2482 let clip_behavior = self.clip_behavior(app);
2483 builder.push_clip_path(&clip_path, clip_behavior);
2484 }
2485 self.as_container_layer()
2486 .add_children_to_scene(app, builder);
2487 let engine_layer = enabled.then(|| builder.pop());
2488 self.as_layer().set_engine_layer(app, engine_layer);
2489 }
2490
2491 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2492 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2493 }
2494}
2495
2496impl ContainerLayer for ClipPathLayer {
2497 crate::container_layer_accessors!();
2498}
2499
2500fn transform_point(transform: &Matrix4, point: Offset) -> Offset {
2502 let storage = transform.to_flutter_array();
2503 let x = point.dx();
2504 let y = point.dy();
2505 let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
2506 let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
2507 let rw = storage[3] as f64 * x + storage[7] as f64 * y + storage[15] as f64;
2508 if rw == 1.0 {
2509 Offset::new(rx, ry)
2510 } else {
2511 Offset::new(rx / rw, ry / rw)
2512 }
2513}
2514
2515pub struct TransformLayer {
2520 layer: LayerData,
2521 container_layer: ContainerLayerData,
2522 offset_layer: OffsetLayerData,
2523 transform: Option<Matrix4>,
2524 last_effective_transform: Option<Matrix4>,
2525 inverted_transform: Cell<Option<Matrix4>>,
2526 inverse_dirty: Cell<bool>,
2527}
2528
2529impl TransformLayer {
2530 pub fn new(app: &mut App) -> Handle<TransformLayer> {
2535 app.create(TransformLayer {
2536 layer: LayerData::new(),
2537 container_layer: ContainerLayerData::new(),
2538 offset_layer: OffsetLayerData::new(Offset::ZERO),
2539 transform: None,
2540 last_effective_transform: None,
2541 inverted_transform: Cell::new(None),
2542 inverse_dirty: Cell::new(true),
2543 })
2544 }
2545
2546 pub fn transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
2556 app.get(self).transform
2557 }
2558
2559 pub fn set_transform(self: Handle<Self>, app: &mut App, value: Matrix4) {
2561 debug_assert!(
2562 value
2563 .to_flutter_array()
2564 .iter()
2565 .all(|component| component.is_finite())
2566 );
2567 if app.get(self).transform == Some(value) {
2568 return;
2569 }
2570 app.get_mut(self).transform = Some(value);
2571 app.get(self).inverse_dirty.set(true);
2572 self.as_layer().mark_needs_add_to_scene(app);
2573 }
2574
2575 fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
2576 if app.get(self).inverse_dirty.get() {
2577 let transform = app
2578 .get(self)
2579 .transform
2580 .expect("transform must be set before searching annotations");
2581 app.get(self)
2582 .inverted_transform
2583 .set(remove_perspective_transform(transform).invert());
2584 app.get(self).inverse_dirty.set(false);
2585 }
2586 app.get(self)
2587 .inverted_transform
2588 .get()
2589 .map(|inverted| transform_point(&inverted, local_position))
2590 }
2591}
2592
2593impl Layer for TransformLayer {
2594 crate::layer_accessors!(container);
2595
2596 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2597 ContainerLayer::supports_rasterization(self, app)
2598 }
2599
2600 fn dispose(self: Handle<Self>, app: &mut App) {
2601 ContainerLayer::dispose(self, app);
2602 }
2603
2604 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2605 ContainerLayer::attach(self, app, owner);
2606 }
2607
2608 fn detach(self: Handle<Self>, app: &mut App) {
2609 ContainerLayer::detach(self, app);
2610 }
2611
2612 fn redepth_children(self: Handle<Self>, app: &mut App) {
2613 ContainerLayer::redepth_children(self, app);
2614 }
2615
2616 fn find_annotations(
2617 self: Handle<Self>,
2618 app: &App,
2619 result: &mut AnnotationSearch,
2620 local_position: Offset,
2621 only_first: bool,
2622 ) -> bool {
2623 let Some(transformed_offset) = self.transform_offset(app, local_position) else {
2624 return false;
2625 };
2626 OffsetLayerMixin::find_annotations(self, app, result, transformed_offset, only_first)
2627 }
2628
2629 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2630 debug_assert!(self.transform(app).is_some());
2631 let mut last_effective = self
2632 .transform(app)
2633 .expect("transform must be set before compositing");
2634 let offset = self.offset(app);
2635 if offset != Offset::ZERO {
2636 last_effective =
2637 Matrix4::translation(offset.dx() as f32, offset.dy() as f32).then(&last_effective);
2638 }
2639 app.get_mut(self).last_effective_transform = Some(last_effective);
2640 builder.push_transform(&last_effective);
2641 self.as_container_layer()
2642 .add_children_to_scene(app, builder);
2643 let engine_layer = builder.pop();
2644 self.as_layer().set_engine_layer(app, Some(engine_layer));
2645 }
2646
2647 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2648 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2649 }
2650}
2651
2652impl ContainerLayer for TransformLayer {
2653 crate::container_layer_accessors!(offset);
2654
2655 fn apply_transform(
2656 self: Handle<Self>,
2657 app: &App,
2658 child: Option<AnyLayer>,
2659 transform: &mut Matrix4,
2660 ) {
2661 debug_assert!(child.is_some());
2662 debug_assert!(
2663 app.get(self).last_effective_transform.is_some() || self.transform(app).is_some()
2664 );
2665 let applied = match app.get(self).last_effective_transform {
2666 None => self
2667 .transform(app)
2668 .expect("transform must be set before applyTransform"),
2669 Some(last_effective) => last_effective,
2670 };
2671 *transform = transform.then(&applied);
2672 }
2673}
2674
2675impl OffsetLayerMixin for TransformLayer {
2676 crate::offset_layer_accessors!();
2677}
2678
2679pub struct OpacityLayer {
2689 layer: LayerData,
2690 container_layer: ContainerLayerData,
2691 offset_layer: OffsetLayerData,
2692 alpha: Option<i32>,
2693}
2694
2695impl OpacityLayer {
2696 pub fn new(app: &mut App) -> Handle<OpacityLayer> {
2701 app.create(OpacityLayer {
2702 layer: LayerData::new(),
2703 container_layer: ContainerLayerData::new(),
2704 offset_layer: OffsetLayerData::new(Offset::ZERO),
2705 alpha: None,
2706 })
2707 }
2708
2709 pub fn alpha(self: Handle<Self>, app: &App) -> Option<i32> {
2717 app.get(self).alpha
2718 }
2719
2720 pub fn set_alpha(self: Handle<Self>, app: &mut App, value: i32) {
2722 if app.get(self).alpha != Some(value) {
2723 app.get_mut(self).alpha = Some(value);
2724 self.as_layer().mark_needs_add_to_scene(app);
2725 }
2726 }
2727}
2728
2729impl Layer for OpacityLayer {
2730 crate::layer_accessors!(container);
2731
2732 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2733 ContainerLayer::supports_rasterization(self, app)
2734 }
2735
2736 fn dispose(self: Handle<Self>, app: &mut App) {
2737 ContainerLayer::dispose(self, app);
2738 }
2739
2740 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2741 ContainerLayer::attach(self, app, owner);
2742 }
2743
2744 fn detach(self: Handle<Self>, app: &mut App) {
2745 ContainerLayer::detach(self, app);
2746 }
2747
2748 fn redepth_children(self: Handle<Self>, app: &mut App) {
2749 ContainerLayer::redepth_children(self, app);
2750 }
2751
2752 fn find_annotations(
2753 self: Handle<Self>,
2754 app: &App,
2755 result: &mut AnnotationSearch,
2756 local_position: Offset,
2757 only_first: bool,
2758 ) -> bool {
2759 OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2760 }
2761
2762 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2763 debug_assert!(self.alpha(app).is_some());
2764
2765 let mut enabled = self.as_container_layer().first_child(app).is_some();
2767 if !enabled {
2768 self.as_layer().set_engine_layer(app, None);
2770 return;
2771 }
2772
2773 if cfg!(debug_assertions) {
2774 enabled = enabled && !crate::debug::debug_disable_opacity_layers();
2775 }
2776
2777 let realized_alpha = self
2778 .alpha(app)
2779 .expect("alpha must be set before compositing");
2780 let offset = self.offset(app);
2781 if enabled && realized_alpha < 255 {
2782 builder.push_opacity(realized_alpha, offset);
2783 } else {
2784 builder.push_offset(offset.dx(), offset.dy());
2785 }
2786 self.as_container_layer()
2787 .add_children_to_scene(app, builder);
2788 let engine_layer = builder.pop();
2789 self.as_layer().set_engine_layer(app, Some(engine_layer));
2790 }
2791
2792 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2793 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2794 }
2795}
2796
2797impl ContainerLayer for OpacityLayer {
2798 crate::container_layer_accessors!(offset);
2799
2800 fn apply_transform(
2801 self: Handle<Self>,
2802 app: &App,
2803 child: Option<AnyLayer>,
2804 transform: &mut Matrix4,
2805 ) {
2806 OffsetLayerMixin::apply_transform(self, app, child, transform);
2807 }
2808}
2809
2810impl OffsetLayerMixin for OpacityLayer {
2811 crate::offset_layer_accessors!();
2812}
2813
2814pub struct BackdropFilterLayer {
2816 layer: LayerData,
2817 container_layer: ContainerLayerData,
2818 filter: Option<ImageFilter>,
2819 blend_mode: BlendMode,
2820 backdrop_key: Option<BackdropKey>,
2821}
2822
2823impl BackdropFilterLayer {
2824 pub fn new(app: &mut App) -> Handle<BackdropFilterLayer> {
2831 app.create(BackdropFilterLayer {
2832 layer: LayerData::new(),
2833 container_layer: ContainerLayerData::new(),
2834 filter: None,
2835 blend_mode: BlendMode::SrcOver,
2836 backdrop_key: None,
2837 })
2838 }
2839
2840 pub fn filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
2845 app.get(self).filter.as_ref()
2846 }
2847
2848 pub fn set_filter(self: Handle<Self>, app: &mut App, value: Option<ImageFilter>) {
2850 app.get_mut(self).filter = value;
2851 self.as_layer().mark_needs_add_to_scene(app);
2852 }
2853
2854 pub fn blend_mode(self: Handle<Self>, app: &App) -> BlendMode {
2862 app.get(self).blend_mode
2863 }
2864
2865 pub fn set_blend_mode(self: Handle<Self>, app: &mut App, value: BlendMode) {
2867 if value != app.get(self).blend_mode {
2868 app.get_mut(self).blend_mode = value;
2869 self.as_layer().mark_needs_add_to_scene(app);
2870 }
2871 }
2872
2873 pub fn backdrop_key(self: Handle<Self>, app: &App) -> Option<BackdropKey> {
2881 app.get(self).backdrop_key
2882 }
2883
2884 pub fn set_backdrop_key(self: Handle<Self>, app: &mut App, value: Option<BackdropKey>) {
2886 if value != app.get(self).backdrop_key {
2887 app.get_mut(self).backdrop_key = value;
2888 self.as_layer().mark_needs_add_to_scene(app);
2889 }
2890 }
2891}
2892
2893impl Layer for BackdropFilterLayer {
2894 crate::layer_accessors!(container);
2895
2896 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2897 ContainerLayer::supports_rasterization(self, app)
2898 }
2899
2900 fn dispose(self: Handle<Self>, app: &mut App) {
2901 ContainerLayer::dispose(self, app);
2902 }
2903
2904 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2905 ContainerLayer::attach(self, app, owner);
2906 }
2907
2908 fn detach(self: Handle<Self>, app: &mut App) {
2909 ContainerLayer::detach(self, app);
2910 }
2911
2912 fn redepth_children(self: Handle<Self>, app: &mut App) {
2913 ContainerLayer::redepth_children(self, app);
2914 }
2915
2916 fn find_annotations(
2917 self: Handle<Self>,
2918 app: &App,
2919 result: &mut AnnotationSearch,
2920 local_position: Offset,
2921 only_first: bool,
2922 ) -> bool {
2923 ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2924 }
2925
2926 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2927 debug_assert!(app.get(self).filter.is_some());
2928 let filter = app
2929 .get(self)
2930 .filter
2931 .clone()
2932 .expect("filter must be set before compositing");
2933 let blend_mode = self.blend_mode(app);
2934 let backdrop_id = self.backdrop_key(app).map(BackdropKey::id);
2935 builder.push_backdrop_filter(&filter, blend_mode, backdrop_id);
2936 self.as_container_layer()
2937 .add_children_to_scene(app, builder);
2938 let engine_layer = builder.pop();
2939 self.as_layer().set_engine_layer(app, Some(engine_layer));
2940 }
2941
2942 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2943 ContainerLayer::fire_composition_callbacks(self, app, include_children);
2944 }
2945}
2946
2947impl ContainerLayer for BackdropFilterLayer {
2948 crate::container_layer_accessors!();
2949}
2950
2951pub struct LayerLink {
2963 leader: Option<Handle<LeaderLayer>>,
2964 debug_previous_leaders: Option<HashSet<Handle<LeaderLayer>>>,
2965 debug_leader_check_scheduled: bool,
2966 pub leader_size: Option<Size>,
2972}
2973
2974impl LayerLink {
2975 pub fn new(app: &mut App) -> Handle<LayerLink> {
2977 app.create(LayerLink {
2978 leader: None,
2979 debug_previous_leaders: None,
2980 debug_leader_check_scheduled: false,
2981 leader_size: None,
2982 })
2983 }
2984
2985 pub fn leader(self: Handle<Self>, app: &App) -> Option<Handle<LeaderLayer>> {
2987 app.get(self).leader
2988 }
2989
2990 fn register_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
2991 debug_assert_ne!(self.leader(app), Some(leader));
2992 if cfg!(debug_assertions)
2993 && let Some(current) = self.leader(app)
2994 {
2995 let previous = app
2996 .get_mut(self)
2997 .debug_previous_leaders
2998 .get_or_insert_with(HashSet::new);
2999 debug_assert!(previous.insert(current));
3000 self.debug_schedule_leaders_clean_up_check(app);
3001 }
3002 app.get_mut(self).leader = Some(leader);
3003 }
3004
3005 fn unregister_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3006 if self.leader(app) == Some(leader) {
3007 app.get_mut(self).leader = None;
3008 } else if cfg!(debug_assertions) {
3009 let removed = app
3010 .get_mut(self)
3011 .debug_previous_leaders
3012 .as_mut()
3013 .expect("a replaced leader is tracked")
3014 .remove(&leader);
3015 debug_assert!(removed);
3016 }
3017 }
3018
3019 fn debug_schedule_leaders_clean_up_check(self: Handle<Self>, app: &mut App) {
3022 debug_assert!(app.get(self).debug_previous_leaders.is_some());
3023 if cfg!(debug_assertions) {
3024 if app.get(self).debug_leader_check_scheduled {
3025 return;
3026 }
3027 app.get_mut(self).debug_leader_check_scheduled = true;
3028 SchedulerBinding::add_post_frame_callback(
3029 app,
3030 FrameCallback::handle_method(self, |this, app, _time_stamp| {
3031 app.get_mut(this).debug_leader_check_scheduled = false;
3032 debug_assert!(
3033 app.get(this)
3034 .debug_previous_leaders
3035 .as_ref()
3036 .expect("a replaced leader is tracked")
3037 .is_empty()
3038 );
3039 }),
3040 None,
3041 );
3042 }
3043 }
3044}
3045
3046pub struct LeaderLayer {
3052 layer: LayerData,
3053 container_layer: ContainerLayerData,
3054 link: Option<RetainedHandle<Handle<LayerLink>>>,
3057 offset: Offset,
3058}
3059
3060impl LeaderLayer {
3061 pub fn new(app: &mut App, link: Handle<LayerLink>) -> Handle<LeaderLayer> {
3069 let link = app.retain(link);
3070 app.create(LeaderLayer {
3071 layer: LayerData::new(),
3072 container_layer: ContainerLayerData::new(),
3073 link: Some(link),
3074 offset: Offset::ZERO,
3075 })
3076 }
3077
3078 pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3083 app.get(self)
3084 .link
3085 .as_ref()
3086 .expect("a LeaderLayer holds its link until dispose")
3087 .get()
3088 }
3089
3090 pub fn set_link(self: Handle<Self>, app: &mut App, value: Handle<LayerLink>) {
3092 let current = self.link(app);
3093 if current == value {
3094 return;
3095 }
3096 if self.as_layer().attached(app) {
3097 current.unregister_leader(app, self);
3098 value.register_leader(app, self);
3099 }
3100 let retained = app.retain(value);
3101 let old = app
3102 .get_mut(self)
3103 .link
3104 .replace(retained)
3105 .expect("a LeaderLayer holds its link until dispose");
3106 app.release(old);
3107 }
3108
3109 pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3117 app.get(self).offset
3118 }
3119
3120 pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3122 if value == app.get(self).offset {
3123 return;
3124 }
3125 app.get_mut(self).offset = value;
3126 if !self.as_layer().always_needs_add_to_scene(app) {
3127 self.as_layer().mark_needs_add_to_scene(app);
3128 }
3129 }
3130}
3131
3132impl Layer for LeaderLayer {
3133 crate::layer_accessors!(container);
3134
3135 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3136 ContainerLayer::supports_rasterization(self, app)
3137 }
3138
3139 fn dispose(self: Handle<Self>, app: &mut App) {
3140 let link = app
3141 .get_mut(self)
3142 .link
3143 .take()
3144 .expect("a LeaderLayer holds its link until dispose");
3145 ContainerLayer::dispose(self, app);
3146 app.release(link);
3147 }
3148
3149 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3150 ContainerLayer::attach(self, app, owner);
3151 let link = self.link(app);
3152 link.register_leader(app, self);
3153 }
3154
3155 fn detach(self: Handle<Self>, app: &mut App) {
3156 let link = self.link(app);
3157 link.unregister_leader(app, self);
3158 ContainerLayer::detach(self, app);
3159 }
3160
3161 fn redepth_children(self: Handle<Self>, app: &mut App) {
3162 ContainerLayer::redepth_children(self, app);
3163 }
3164
3165 fn find_annotations(
3166 self: Handle<Self>,
3167 app: &App,
3168 result: &mut AnnotationSearch,
3169 local_position: Offset,
3170 only_first: bool,
3171 ) -> bool {
3172 let offset = self.offset(app);
3173 ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
3174 }
3175
3176 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3177 let offset = self.offset(app);
3178 if offset != Offset::ZERO {
3179 builder.push_transform(&Matrix4::translation(
3180 offset.dx() as f32,
3181 offset.dy() as f32,
3182 ));
3183 }
3184 self.as_container_layer()
3185 .add_children_to_scene(app, builder);
3186 let engine_layer = (offset != Offset::ZERO).then(|| builder.pop());
3187 self.as_layer().set_engine_layer(app, engine_layer);
3188 }
3189
3190 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3191 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3192 }
3193}
3194
3195impl ContainerLayer for LeaderLayer {
3196 crate::container_layer_accessors!();
3197
3198 fn apply_transform(
3205 self: Handle<Self>,
3206 app: &App,
3207 _child: Option<AnyLayer>,
3208 transform: &mut Matrix4,
3209 ) {
3210 let offset = self.offset(app);
3211 if offset != Offset::ZERO {
3212 *transform = transform.then(&Matrix4::translation(
3213 offset.dx() as f32,
3214 offset.dy() as f32,
3215 ));
3216 }
3217 }
3218}
3219
3220pub struct FollowerLayer {
3231 layer: LayerData,
3232 container_layer: ContainerLayerData,
3233 link: Option<RetainedHandle<Handle<LayerLink>>>,
3236 show_when_unlinked: bool,
3237 unlinked_offset: Offset,
3238 linked_offset: Offset,
3239 last_offset: Option<Offset>,
3240 last_transform: Option<Matrix4>,
3241 inverted_transform: Cell<Option<Matrix4>>,
3242 inverse_dirty: Cell<bool>,
3243}
3244
3245impl FollowerLayer {
3246 pub fn new(app: &mut App, link: Handle<LayerLink>) -> Handle<FollowerLayer> {
3252 let link = app.retain(link);
3253 app.create(FollowerLayer {
3254 layer: LayerData::new(),
3255 container_layer: ContainerLayerData::new(),
3256 link: Some(link),
3257 show_when_unlinked: true,
3258 unlinked_offset: Offset::ZERO,
3259 linked_offset: Offset::ZERO,
3260 last_offset: None,
3261 last_transform: None,
3262 inverted_transform: Cell::new(None),
3263 inverse_dirty: Cell::new(true),
3264 })
3265 }
3266
3267 pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3273 app.get(self)
3274 .link
3275 .as_ref()
3276 .expect("a FollowerLayer holds its link until dispose")
3277 .get()
3278 }
3279
3280 pub fn set_link(self: Handle<Self>, app: &mut App, value: Handle<LayerLink>) {
3282 if self.link(app) == value {
3283 return;
3284 }
3285 let retained = app.retain(value);
3286 let old = app
3287 .get_mut(self)
3288 .link
3289 .replace(retained)
3290 .expect("a FollowerLayer holds its link until dispose");
3291 app.release(old);
3292 }
3293
3294 pub fn show_when_unlinked(self: Handle<Self>, app: &App) -> bool {
3307 app.get(self).show_when_unlinked
3308 }
3309
3310 pub fn set_show_when_unlinked(self: Handle<Self>, app: &mut App, value: bool) {
3312 app.get_mut(self).show_when_unlinked = value;
3313 }
3314
3315 pub fn unlinked_offset(self: Handle<Self>, app: &App) -> Offset {
3328 app.get(self).unlinked_offset
3329 }
3330
3331 pub fn set_unlinked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3333 app.get_mut(self).unlinked_offset = value;
3334 }
3335
3336 pub fn linked_offset(self: Handle<Self>, app: &App) -> Offset {
3349 app.get(self).linked_offset
3350 }
3351
3352 pub fn set_linked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3354 app.get_mut(self).linked_offset = value;
3355 }
3356
3357 fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
3358 if app.get(self).inverse_dirty.get() {
3359 let last = self.get_last_transform(app).expect(
3360 "FollowerLayer._transformOffset requires getLastTransform after addToScene",
3361 );
3362 app.get(self).inverted_transform.set(last.invert());
3363 app.get(self).inverse_dirty.set(false);
3364 }
3365 let inverted = app.get(self).inverted_transform.get()?;
3366 let storage = inverted.to_flutter_array();
3367 let x = local_position.dx();
3368 let y = local_position.dy();
3369 let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
3370 let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
3371 let linked_offset = self.linked_offset(app);
3372 Some(Offset::new(
3373 rx - linked_offset.dx(),
3374 ry - linked_offset.dy(),
3375 ))
3376 }
3377
3378 pub fn get_last_transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
3385 let last_transform = app.get(self).last_transform?;
3386 let last_offset = app
3387 .get(self)
3388 .last_offset
3389 .expect("lastOffset is set with lastTransform");
3390 Some(
3391 Matrix4::translation(-last_offset.dx() as f32, -last_offset.dy() as f32)
3392 .then(&last_transform),
3393 )
3394 }
3395
3396 fn collect_transform_for_layer_chain(
3402 app: &App,
3403 layers: &[Option<AnyContainerLayer>],
3404 ) -> Matrix4 {
3405 let mut result = Matrix4::IDENTITY;
3406 for index in (1..layers.len()).rev() {
3407 if let Some(layer) = layers[index] {
3408 let child = layers[index - 1].map(AnyContainerLayer::as_layer);
3409 layer.apply_transform(app, child, &mut result);
3410 }
3411 }
3412 result
3413 }
3414
3415 fn paths_to_common_ancestor(
3422 app: &App,
3423 a: Option<AnyLayer>,
3424 b: Option<AnyLayer>,
3425 ancestors_a: &mut Vec<Option<AnyContainerLayer>>,
3426 ancestors_b: &mut Vec<Option<AnyContainerLayer>>,
3427 ) -> Option<AnyLayer> {
3428 let (a, b) = (a?, b?);
3429 if a == b {
3430 return Some(a);
3431 }
3432 if a.depth(app) < b.depth(app) {
3433 ancestors_b.push(b.parent(app));
3434 return Self::paths_to_common_ancestor(
3435 app,
3436 Some(a),
3437 b.parent(app).map(AnyContainerLayer::as_layer),
3438 ancestors_a,
3439 ancestors_b,
3440 );
3441 } else if a.depth(app) > b.depth(app) {
3442 ancestors_a.push(a.parent(app));
3443 return Self::paths_to_common_ancestor(
3444 app,
3445 a.parent(app).map(AnyContainerLayer::as_layer),
3446 Some(b),
3447 ancestors_a,
3448 ancestors_b,
3449 );
3450 }
3451 ancestors_a.push(a.parent(app));
3452 ancestors_b.push(b.parent(app));
3453 Self::paths_to_common_ancestor(
3454 app,
3455 a.parent(app).map(AnyContainerLayer::as_layer),
3456 b.parent(app).map(AnyContainerLayer::as_layer),
3457 ancestors_a,
3458 ancestors_b,
3459 )
3460 }
3461
3462 fn debug_check_leader_before_follower(
3463 app: &App,
3464 leader_to_common_ancestor: &[Option<AnyContainerLayer>],
3465 follower_to_common_ancestor: &[Option<AnyContainerLayer>],
3466 ) -> bool {
3467 if follower_to_common_ancestor.len() <= 1 {
3468 return false;
3469 }
3470 if leader_to_common_ancestor.len() <= 1 {
3471 return true;
3472 }
3473 let leader_subtree_below_ancestor = leader_to_common_ancestor
3474 [leader_to_common_ancestor.len() - 2]
3475 .expect("the leader subtree below the ancestor is a layer");
3476 let follower_subtree_below_ancestor = follower_to_common_ancestor
3477 [follower_to_common_ancestor.len() - 2]
3478 .expect("the follower subtree below the ancestor is a layer");
3479 let mut sibling = Some(leader_subtree_below_ancestor.as_layer());
3480 while let Some(layer) = sibling {
3481 if layer == follower_subtree_below_ancestor.as_layer() {
3482 return true;
3483 }
3484 sibling = layer.next_sibling(app);
3485 }
3486 false
3487 }
3488
3489 fn establish_transform(self: Handle<Self>, app: &mut App) {
3491 app.get_mut(self).last_transform = None;
3492 let Some(leader) = self.link(app).leader(app) else {
3493 return;
3494 };
3495 debug_assert_eq!(
3496 leader.as_layer().owner(app),
3497 self.as_layer().owner(app),
3498 "Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer."
3499 );
3500
3501 let mut forward_layers = vec![Some(leader.as_container_layer())];
3502 let mut inverse_layers = vec![Some(self.as_container_layer())];
3503 let ancestor = Self::paths_to_common_ancestor(
3504 app,
3505 Some(leader.as_layer()),
3506 Some(self.as_layer()),
3507 &mut forward_layers,
3508 &mut inverse_layers,
3509 );
3510 debug_assert!(
3511 ancestor.is_some(),
3512 "LeaderLayer and FollowerLayer do not have a common ancestor."
3513 );
3514 debug_assert!(
3515 Self::debug_check_leader_before_follower(app, &forward_layers, &inverse_layers),
3516 "LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse \
3517 was true."
3518 );
3519
3520 let mut forward_transform = Self::collect_transform_for_layer_chain(app, &forward_layers);
3521 leader
3522 .as_container_layer()
3523 .apply_transform(app, None, &mut forward_transform);
3524 let linked_offset = self.linked_offset(app);
3525 forward_transform = forward_transform.then(&Matrix4::translation(
3526 linked_offset.dx() as f32,
3527 linked_offset.dy() as f32,
3528 ));
3529
3530 let inverse_transform = Self::collect_transform_for_layer_chain(app, &inverse_layers);
3531 let Some(inverse_transform) = inverse_transform.invert() else {
3532 return;
3533 };
3534 app.get_mut(self).last_transform = Some(inverse_transform.then(&forward_transform));
3535 app.get(self).inverse_dirty.set(true);
3536 }
3537}
3538
3539impl Layer for FollowerLayer {
3540 crate::layer_accessors!(container);
3541
3542 fn always_needs_add_to_scene(self: Handle<Self>, _app: &App) -> bool {
3546 true
3547 }
3548
3549 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3550 ContainerLayer::supports_rasterization(self, app)
3551 }
3552
3553 fn dispose(self: Handle<Self>, app: &mut App) {
3554 let link = app
3555 .get_mut(self)
3556 .link
3557 .take()
3558 .expect("a FollowerLayer holds its link until dispose");
3559 ContainerLayer::dispose(self, app);
3560 app.release(link);
3561 }
3562
3563 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3564 ContainerLayer::attach(self, app, owner);
3565 }
3566
3567 fn detach(self: Handle<Self>, app: &mut App) {
3568 ContainerLayer::detach(self, app);
3569 }
3570
3571 fn redepth_children(self: Handle<Self>, app: &mut App) {
3572 ContainerLayer::redepth_children(self, app);
3573 }
3574
3575 fn find_annotations(
3576 self: Handle<Self>,
3577 app: &App,
3578 result: &mut AnnotationSearch,
3579 local_position: Offset,
3580 only_first: bool,
3581 ) -> bool {
3582 if self.link(app).leader(app).is_none() {
3583 if self.show_when_unlinked(app) {
3584 return ContainerLayer::find_annotations(
3585 self,
3586 app,
3587 result,
3588 local_position - self.unlinked_offset(app),
3589 only_first,
3590 );
3591 }
3592 return false;
3593 }
3594 let Some(transformed_offset) = self.transform_offset(app, local_position) else {
3595 return false;
3596 };
3597 ContainerLayer::find_annotations(self, app, result, transformed_offset, only_first)
3598 }
3599
3600 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3601 if self.link(app).leader(app).is_none() && !self.show_when_unlinked(app) {
3602 app.get_mut(self).last_transform = None;
3603 app.get_mut(self).last_offset = None;
3604 app.get(self).inverse_dirty.set(true);
3605 self.as_layer().set_engine_layer(app, None);
3606 return;
3607 }
3608 self.establish_transform(app);
3609 if app.get(self).last_transform.is_some() {
3610 let unlinked_offset = self.unlinked_offset(app);
3611 app.get_mut(self).last_offset = Some(unlinked_offset);
3612 let last_transform = app
3613 .get(self)
3614 .last_transform
3615 .expect("lastTransform was just set");
3616 builder.push_transform(&last_transform);
3617 self.as_container_layer()
3618 .add_children_to_scene(app, builder);
3619 let engine_layer = builder.pop();
3620 self.as_layer().set_engine_layer(app, Some(engine_layer));
3621 } else {
3622 app.get_mut(self).last_offset = None;
3623 let unlinked_offset = self.unlinked_offset(app);
3624 let matrix =
3625 Matrix4::translation(unlinked_offset.dx() as f32, unlinked_offset.dy() as f32);
3626 builder.push_transform(&matrix);
3627 self.as_container_layer()
3628 .add_children_to_scene(app, builder);
3629 let engine_layer = builder.pop();
3630 self.as_layer().set_engine_layer(app, Some(engine_layer));
3631 }
3632 app.get(self).inverse_dirty.set(true);
3633 }
3634
3635 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3636 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3637 }
3638}
3639
3640impl ContainerLayer for FollowerLayer {
3641 crate::container_layer_accessors!();
3642
3643 fn apply_transform(
3644 self: Handle<Self>,
3645 app: &App,
3646 child: Option<AnyLayer>,
3647 transform: &mut Matrix4,
3648 ) {
3649 debug_assert!(child.is_some());
3650 if let Some(last_transform) = app.get(self).last_transform {
3651 *transform = transform.then(&last_transform);
3652 } else {
3653 let unlinked_offset = self.unlinked_offset(app);
3654 *transform = transform.then(&Matrix4::translation(
3655 unlinked_offset.dx() as f32,
3656 unlinked_offset.dy() as f32,
3657 ));
3658 }
3659 }
3660}
3661
3662pub struct AnnotatedRegionLayer {
3681 layer: LayerData,
3682 container_layer: ContainerLayerData,
3683 value: Rc<dyn Any>,
3684 size: Option<Size>,
3685 offset: Offset,
3686 opaque: bool,
3687}
3688
3689impl AnnotatedRegionLayer {
3690 pub fn new(app: &mut App, value: Rc<dyn Any>) -> Handle<AnnotatedRegionLayer> {
3692 app.create(AnnotatedRegionLayer {
3693 layer: LayerData::new(),
3694 container_layer: ContainerLayerData::new(),
3695 value,
3696 size: None,
3697 offset: Offset::ZERO,
3698 opaque: false,
3699 })
3700 }
3701
3702 pub fn value(self: Handle<Self>, app: &App) -> &Rc<dyn Any> {
3704 &app.get(self).value
3705 }
3706
3707 pub fn size(self: Handle<Self>, app: &App) -> Option<Size> {
3714 app.get(self).size
3715 }
3716
3717 pub fn set_size(self: Handle<Self>, app: &mut App, value: Option<Size>) {
3719 app.get_mut(self).size = value;
3720 }
3721
3722 pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3730 app.get(self).offset
3731 }
3732
3733 pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3735 app.get_mut(self).offset = value;
3736 }
3737
3738 pub fn opaque(self: Handle<Self>, app: &App) -> bool {
3760 app.get(self).opaque
3761 }
3762
3763 pub fn set_opaque(self: Handle<Self>, app: &mut App, value: bool) {
3765 app.get_mut(self).opaque = value;
3766 }
3767}
3768
3769impl Layer for AnnotatedRegionLayer {
3770 crate::layer_accessors!(container);
3771
3772 fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3773 ContainerLayer::supports_rasterization(self, app)
3774 }
3775
3776 fn dispose(self: Handle<Self>, app: &mut App) {
3777 ContainerLayer::dispose(self, app);
3778 }
3779
3780 fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3781 ContainerLayer::attach(self, app, owner);
3782 }
3783
3784 fn detach(self: Handle<Self>, app: &mut App) {
3785 ContainerLayer::detach(self, app);
3786 }
3787
3788 fn redepth_children(self: Handle<Self>, app: &mut App) {
3789 ContainerLayer::redepth_children(self, app);
3790 }
3791
3792 fn find_annotations(
3813 self: Handle<Self>,
3814 app: &App,
3815 result: &mut AnnotationSearch,
3816 local_position: Offset,
3817 only_first: bool,
3818 ) -> bool {
3819 let mut is_absorbed =
3820 ContainerLayer::find_annotations(self, app, result, local_position, only_first);
3821 if !result.is_empty() && only_first {
3822 return is_absorbed;
3823 }
3824 let (value, size, offset, opaque) = {
3825 let this = app.get(self);
3826 (Rc::clone(&this.value), this.size, this.offset, this.opaque)
3827 };
3828 if let Some(size) = size
3829 && !(offset & size).contains(local_position)
3830 {
3831 return is_absorbed;
3832 }
3833 if result.accepts(&*value) {
3834 is_absorbed = is_absorbed || opaque;
3835 result.add(value, local_position - offset);
3836 }
3837 is_absorbed
3838 }
3839
3840 fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3841 ContainerLayer::add_to_scene(self, app, builder);
3842 }
3843
3844 fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3845 ContainerLayer::fire_composition_callbacks(self, app, include_children);
3846 }
3847}
3848
3849impl ContainerLayer for AnnotatedRegionLayer {
3850 crate::container_layer_accessors!();
3851}
3852
3853#[cfg(test)]
3854mod tests {
3855 use inset_foundation::AppCell;
3856
3857 use super::*;
3858
3859 fn offset_layer(app: &mut App) -> AnyLayer {
3860 OffsetLayer::new(app, Offset::ZERO).as_layer()
3861 }
3862
3863 #[test]
3864 fn append_links_children_in_order_and_adopts_them() {
3865 let cell = AppCell::new();
3866 let mut app = cell.borrow_mut();
3867 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3868 let a = offset_layer(&mut app);
3869 let b = offset_layer(&mut app);
3870 parent.append(&mut app, a);
3871 parent.append(&mut app, b);
3872 assert_eq!(parent.first_child(&app), Some(a));
3873 assert_eq!(parent.last_child(&app), Some(b));
3874 assert_eq!(a.next_sibling(&app), Some(b));
3875 assert_eq!(b.previous_sibling(&app), Some(a));
3876 assert_eq!(a.parent(&app), Some(parent));
3877 assert_eq!(a.depth(&app), 1);
3878 assert_eq!(a.debug_handle_count(&app), 1, "the parent handle");
3879 }
3880
3881 #[test]
3882 fn a_layer_is_disposed_when_its_last_handle_is_released() {
3883 let cell = AppCell::new();
3884 let mut app = cell.borrow_mut();
3885 let layer = offset_layer(&mut app);
3886 let handle = app.create(LayerHandle::<AnyLayer>::new());
3887 LayerHandle::set_layer(&mut app, |app| app.get_mut(handle), Some(layer));
3888 assert_eq!(layer.debug_handle_count(&app), 1);
3889 LayerHandle::set_layer(&mut app, |app| app.get_mut(handle), None);
3890 assert!(layer.debug_disposed(&app));
3891 assert!(
3892 !app.contains(layer.id()),
3893 "dispose destroys the arena entry"
3894 );
3895 }
3896
3897 #[test]
3898 fn removing_a_child_releases_the_parent_handle_and_disposes_it() {
3899 let cell = AppCell::new();
3900 let mut app = cell.borrow_mut();
3901 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3902 let child = offset_layer(&mut app);
3903 parent.append(&mut app, child);
3904 child.remove(&mut app);
3905 assert!(!parent.has_children(&app));
3906 assert!(child.debug_disposed(&app));
3907 }
3908
3909 #[test]
3910 fn a_child_kept_by_another_handle_survives_removal() {
3911 let cell = AppCell::new();
3912 let mut app = cell.borrow_mut();
3913 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3914 let child = offset_layer(&mut app);
3915 let handle = app.create(LayerHandle::<AnyLayer>::new());
3916 LayerHandle::set_layer(&mut app, |app| app.get_mut(handle), Some(child));
3917 parent.append(&mut app, child);
3918 child.remove(&mut app);
3919 assert!(!child.debug_disposed(&app));
3920 assert_eq!(child.parent(&app), None);
3921 LayerHandle::set_layer(&mut app, |app| app.get_mut(handle), None);
3922 assert!(child.debug_disposed(&app));
3923 }
3924
3925 #[test]
3926 fn attach_and_detach_walk_the_subtree() {
3927 let cell = AppCell::new();
3928 let mut app = cell.borrow_mut();
3929 let owner = app.create(());
3930 let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3931 let child = offset_layer(&mut app);
3932 root.append(&mut app, child);
3933 root.as_layer().attach(&mut app, owner.id());
3934 assert!(child.attached(&app));
3935 let late = offset_layer(&mut app);
3936 root.append(&mut app, late);
3937 assert!(
3938 late.attached(&app),
3939 "appending to an attached tree attaches"
3940 );
3941 root.as_layer().detach(&mut app);
3942 assert!(!child.attached(&app));
3943 assert!(!late.attached(&app));
3944 }
3945
3946 #[test]
3947 fn disposing_a_container_disposes_children_it_alone_held() {
3948 let cell = AppCell::new();
3949 let mut app = cell.borrow_mut();
3950 let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3951 let child = offset_layer(&mut app);
3952 parent.append(&mut app, child);
3953 let handle = app.create(LayerHandle::<AnyContainerLayer>::new());
3954 LayerHandle::set_layer(&mut app, |app| app.get_mut(handle), Some(parent));
3955 LayerHandle::set_layer(&mut app, |app| app.get_mut(handle), None);
3956 assert!(parent.as_layer().debug_disposed(&app));
3957 assert!(child.debug_disposed(&app));
3958 }
3959
3960 #[test]
3961 fn a_picture_layer_is_a_leaf_that_holds_its_picture() {
3962 let cell = AppCell::new();
3963 let mut app = cell.borrow_mut();
3964 let layer = PictureLayer::new(&mut app, Rect::from_ltwh(0.0, 0.0, 10.0, 10.0));
3965 let picture = Arc::new(inset_embedder::Canvas::new().build());
3966 layer.set_picture(&mut app, Some(picture));
3967 assert!(layer.picture(&app).is_some());
3968 assert!(layer.as_layer().as_container_layer().is_none());
3969 let mut builder = SceneBuilder::new();
3970 layer.as_layer().add_to_scene(&mut app, &mut builder);
3971 let _scene = builder.build();
3972 }
3973
3974 #[test]
3975 fn composition_callbacks_fire_on_build_scene_and_detach() {
3976 use std::cell::Cell;
3977 let cell = AppCell::new();
3978 let mut app = cell.borrow_mut();
3979 let owner = app.create(());
3980 let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3981 let child = offset_layer(&mut app);
3982 root.append(&mut app, child);
3983 let fired = Rc::new(Cell::new(0));
3984 let remove = {
3985 let fired = Rc::clone(&fired);
3986 child
3987 .add_composition_callback(&mut app, Rc::new(move |_, _| fired.set(fired.get() + 1)))
3988 };
3989 assert!(root.as_layer().subtree_has_composition_callbacks(&app));
3990 let _scene = root.build_scene(&mut app, SceneBuilder::new());
3991 assert_eq!(fired.get(), 1);
3992 root.as_layer().attach(&mut app, owner.id());
3993 root.as_layer().detach(&mut app);
3994 assert_eq!(fired.get(), 2, "detach fires once more");
3995 remove(&mut app);
3996 assert!(!root.as_layer().subtree_has_composition_callbacks(&app));
3997 }
3998
3999 #[test]
4000 fn find_walks_children_back_to_front_through_offsets() {
4001 struct Tag(&'static str);
4002 struct Annotated {
4003 layer: LayerData,
4004 tag: Rc<Tag>,
4005 }
4006 impl Layer for Annotated {
4007 crate::layer_accessors!();
4008 fn find_annotations(
4009 self: Handle<Self>,
4010 app: &App,
4011 result: &mut AnnotationSearch,
4012 local_position: Offset,
4013 _only_first: bool,
4014 ) -> bool {
4015 let tag = Rc::clone(&app.get(self).tag);
4016 if result.accepts(&*tag) {
4017 result.add(tag, local_position);
4018 }
4019 false
4020 }
4021 fn add_to_scene(self: Handle<Self>, _app: &mut App, _builder: &mut SceneBuilder) {}
4022 }
4023 let cell = AppCell::new();
4024 let mut app = cell.borrow_mut();
4025 let root = OffsetLayer::new(&mut app, Offset::new(10.0, 0.0)).as_container_layer();
4026 for name in ["back", "front"] {
4027 let layer = app.create(Annotated {
4028 layer: LayerData::new(),
4029 tag: Rc::new(Tag(name)),
4030 });
4031 root.append(&mut app, layer.as_layer());
4032 }
4033 let found = root.as_layer().find::<Tag>(&app, Offset::new(15.0, 5.0));
4034 assert_eq!(found.map(|tag| tag.0), Some("front"));
4035 let all = root
4036 .as_layer()
4037 .find_all_annotations::<Tag>(&app, Offset::new(15.0, 5.0));
4038 assert_eq!(all.entries().len(), 2);
4039 assert_eq!(all.entries()[0].local_position, Offset::new(5.0, 5.0));
4040 assert!(root.as_layer().find::<String>(&app, Offset::ZERO).is_none());
4041 }
4042
4043 fn drawn_layer(app: &mut App) -> AnyLayer {
4048 let square = Rect::from_ltwh(0.0, 0.0, 10.0, 10.0);
4049 let mut canvas = inset_embedder::Canvas::new();
4050 canvas.draw_rect(square, &inset_embedder::Paint::default());
4051 let layer = PictureLayer::new(app, square);
4052 layer.set_picture(app, Some(Arc::new(canvas.build())));
4053 layer.as_layer()
4054 }
4055
4056 fn retained_tree(app: &mut App) -> (Handle<OffsetLayer>, Handle<OpacityLayer>) {
4057 let root = OffsetLayer::new(app, Offset::ZERO);
4058 let opacity = OpacityLayer::new(app);
4059 opacity.set_alpha(app, 128);
4060 let leaf = drawn_layer(app);
4061 opacity.as_container_layer().append(app, leaf);
4062 root.as_container_layer().append(app, opacity.as_layer());
4063 let _scene = root
4064 .as_container_layer()
4065 .build_scene(app, SceneBuilder::new());
4066 (root, opacity)
4067 }
4068
4069 #[test]
4070 fn a_surface_layer_places_its_surface_under_its_offset_every_frame() {
4071 let cell = AppCell::new();
4072 let mut app = cell.borrow_mut();
4073 let root = OffsetLayer::new(&mut app, Offset::new(10.0, 5.0));
4074 let surface = inset_embedder::test_support::idle_surface();
4075 let layer = SurfaceLayer::new(
4076 &mut app,
4077 Arc::clone(&surface),
4078 Rect::from_ltwh(1.0, 2.0, 30.0, 20.0),
4079 );
4080 root.as_container_layer().append(&mut app, layer.as_layer());
4081 for _frame in 0..2 {
4082 let scene = root
4083 .as_container_layer()
4084 .build_scene(&mut app, SceneBuilder::new());
4085 assert_eq!(
4086 scene.surfaces,
4087 [inset_embedder::SurfacePlacement {
4088 surface: Arc::clone(&surface),
4089 rect: Rect::from_ltwh(11.0, 7.0, 30.0, 20.0),
4090 scale: 1.0,
4091 clip: Rect::from_ltwh(11.0, 7.0, 30.0, 20.0),
4092 }]
4093 );
4094 }
4095 assert!(layer.as_layer().always_needs_add_to_scene(&app));
4096 }
4097
4098 #[test]
4099 fn an_unchanged_subtree_is_retained_across_scenes() {
4100 let cell = AppCell::new();
4101 let mut app = cell.borrow_mut();
4102 let (root, opacity) = retained_tree(&mut app);
4103 let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4104 assert!(!opacity.as_layer().needs_add_to_scene(&app));
4105
4106 let scene = root
4107 .as_container_layer()
4108 .build_scene(&mut app, SceneBuilder::new());
4109 let retained = opacity.as_layer().engine_layer(&app).expect("recorded");
4110 assert!(
4111 Arc::ptr_eq(&recorded, &retained),
4112 "the same list is retained"
4113 );
4114 let root_list = root
4115 .as_layer()
4116 .engine_layer(&app)
4117 .expect("the root re-records");
4118 assert!(
4119 root_list.ops().iter().any(|op| matches!(
4120 op,
4121 inset_embedder::valo::Op::DrawDisplayList { list, .. } if Arc::ptr_eq(list, &retained)
4122 )),
4123 "embedded again: {:?}",
4124 root_list.ops()
4125 );
4126 assert_eq!(
4127 inset_embedder::flattened_ops(&scene.picture)
4128 .iter()
4129 .filter(|op| matches!(op, inset_embedder::valo::Op::SaveLayer { .. }))
4130 .count(),
4131 1,
4132 "the retained opacity layer still draws"
4133 );
4134 }
4135
4136 #[test]
4137 fn a_changed_property_re_records_the_subtree() {
4138 let cell = AppCell::new();
4139 let mut app = cell.borrow_mut();
4140 let (root, opacity) = retained_tree(&mut app);
4141 let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4142
4143 opacity.set_alpha(&mut app, 200);
4144 assert!(opacity.as_layer().needs_add_to_scene(&app));
4145 let _scene = root
4146 .as_container_layer()
4147 .build_scene(&mut app, SceneBuilder::new());
4148 let again = opacity.as_layer().engine_layer(&app).expect("recorded");
4149 assert!(
4150 !Arc::ptr_eq(&recorded, &again),
4151 "a new list for the new alpha"
4152 );
4153 assert!(!opacity.as_layer().needs_add_to_scene(&app));
4154 }
4155
4156 #[test]
4157 fn appending_a_child_marks_the_parent_and_its_ancestors_at_build() {
4158 let cell = AppCell::new();
4159 let mut app = cell.borrow_mut();
4160 let (root, opacity) = retained_tree(&mut app);
4161 assert!(!root.as_layer().needs_add_to_scene(&app));
4162
4163 let leaf = offset_layer(&mut app);
4164 opacity.as_container_layer().append(&mut app, leaf);
4165 assert!(opacity.as_layer().needs_add_to_scene(&app));
4166 assert!(
4167 !root.as_layer().needs_add_to_scene(&app),
4168 "the mark does not climb until the scene is built"
4169 );
4170 root.as_layer().update_subtree_needs_add_to_scene(&mut app);
4171 assert!(root.as_layer().needs_add_to_scene(&app));
4172 }
4173
4174 #[test]
4175 fn a_follower_layer_always_re_records() {
4176 let cell = AppCell::new();
4177 let mut app = cell.borrow_mut();
4178 let link = LayerLink::new(&mut app);
4179 let follower = FollowerLayer::new(&mut app, link);
4180 let child = offset_layer(&mut app);
4181 follower.as_container_layer().append(&mut app, child);
4182 for _ in 0..2 {
4183 let _scene = follower
4184 .as_container_layer()
4185 .build_scene(&mut app, SceneBuilder::new());
4186 assert!(
4187 follower.as_layer().needs_add_to_scene(&app)
4188 || follower.as_layer().always_needs_add_to_scene(&app)
4189 );
4190 }
4191 let first = follower.as_layer().engine_layer(&app).expect("recorded");
4192 let _scene = follower
4193 .as_container_layer()
4194 .build_scene(&mut app, SceneBuilder::new());
4195 let second = follower.as_layer().engine_layer(&app).expect("recorded");
4196 assert!(!Arc::ptr_eq(&first, &second), "never retained");
4197 }
4198
4199 fn tag(app: &mut App, n: u32) -> Handle<AnnotatedRegionLayer> {
4200 AnnotatedRegionLayer::new(app, Rc::new(n))
4201 }
4202
4203 #[test]
4204 fn clip_layers_reject_annotations_outside_the_clip() {
4205 let cell = AppCell::new();
4206 let mut app = cell.borrow_mut();
4207 let rect = ClipRectLayer::new(&mut app);
4208 rect.set_clip_rect(&mut app, Some(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0)));
4209 let child = tag(&mut app, 7);
4210 rect.as_container_layer().append(&mut app, child.as_layer());
4211 assert_eq!(
4212 rect.as_layer()
4213 .find::<u32>(&app, Offset::new(10.0, 10.0))
4214 .as_deref(),
4215 Some(&7)
4216 );
4217 assert!(
4218 rect.as_layer()
4219 .find::<u32>(&app, Offset::new(60.0, 10.0))
4220 .is_none(),
4221 "outside the clip"
4222 );
4223
4224 let rrect = ClipRRectLayer::new(&mut app);
4225 rrect.set_clip_rrect(
4226 &mut app,
4227 Some(RRect::from_rect_and_radius(
4228 Rect::from_ltwh(0.0, 0.0, 50.0, 50.0),
4229 inset_embedder::Radius::circular(4.0),
4230 )),
4231 );
4232 let child = tag(&mut app, 8);
4233 rrect
4234 .as_container_layer()
4235 .append(&mut app, child.as_layer());
4236 assert_eq!(
4237 rrect
4238 .as_layer()
4239 .find::<u32>(&app, Offset::new(10.0, 10.0))
4240 .as_deref(),
4241 Some(&8)
4242 );
4243 assert!(
4244 rrect
4245 .as_layer()
4246 .find::<u32>(&app, Offset::new(60.0, 10.0))
4247 .is_none()
4248 );
4249
4250 let mut path = inset_embedder::PathBuilder::new();
4251 path.rect(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0).into());
4252 let clip_path = ClipPathLayer::new(&mut app);
4253 clip_path.set_clip_path(&mut app, Some(path.build()));
4254 let child = tag(&mut app, 9);
4255 clip_path
4256 .as_container_layer()
4257 .append(&mut app, child.as_layer());
4258 assert_eq!(
4259 clip_path
4260 .as_layer()
4261 .find::<u32>(&app, Offset::new(10.0, 10.0))
4262 .as_deref(),
4263 Some(&9)
4264 );
4265 assert!(
4266 clip_path
4267 .as_layer()
4268 .find::<u32>(&app, Offset::new(60.0, 10.0))
4269 .is_none()
4270 );
4271 }
4272
4273 #[test]
4274 fn transform_layer_transforms_the_annotation_position() {
4275 let cell = AppCell::new();
4276 let mut app = cell.borrow_mut();
4277 let layer = TransformLayer::new(&mut app);
4278 layer.set_transform(&mut app, Matrix4::translation(10.0, 0.0));
4279 let region = tag(&mut app, 7);
4280 region.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4281 layer
4282 .as_container_layer()
4283 .append(&mut app, region.as_layer());
4284 assert!(
4285 layer
4286 .as_layer()
4287 .find::<u32>(&app, Offset::new(15.0, 5.0))
4288 .is_some()
4289 );
4290 assert!(
4291 layer
4292 .as_layer()
4293 .find::<u32>(&app, Offset::new(5.0, 5.0))
4294 .is_none(),
4295 "left of the translated region"
4296 );
4297 }
4298
4299 #[test]
4300 fn opacity_layer_build_scene_succeeds_at_255_and_128() {
4301 let cell = AppCell::new();
4302 let mut app = cell.borrow_mut();
4303 for alpha in [255, 128] {
4304 let layer = OpacityLayer::new(&mut app);
4305 layer.set_alpha(&mut app, alpha);
4306 let child = OffsetLayer::new(&mut app, Offset::ZERO);
4307 layer
4308 .as_container_layer()
4309 .append(&mut app, child.as_layer());
4310 let _scene = layer
4311 .as_container_layer()
4312 .build_scene(&mut app, SceneBuilder::new());
4313 }
4314 let empty = OpacityLayer::new(&mut app);
4315 empty.set_alpha(&mut app, 128);
4316 let _scene = empty
4317 .as_container_layer()
4318 .build_scene(&mut app, SceneBuilder::new());
4319 }
4320
4321 #[test]
4322 fn layer_link_register_unregister_and_leader_getter() {
4323 let cell = AppCell::new();
4324 let mut app = cell.borrow_mut();
4325 let owner = app.create(());
4326 let link = LayerLink::new(&mut app);
4327 assert!(link.leader(&app).is_none());
4328 let leader = LeaderLayer::new(&mut app, link);
4329 leader.as_layer().attach(&mut app, owner.id());
4330 assert_eq!(link.leader(&app), Some(leader));
4331 leader.as_layer().detach(&mut app);
4332 assert!(link.leader(&app).is_none());
4333 }
4334
4335 #[test]
4336 fn leader_layer_attach_registers_and_detach_unregisters() {
4337 let cell = AppCell::new();
4338 let mut app = cell.borrow_mut();
4339 let owner = app.create(());
4340 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4341 let link = LayerLink::new(&mut app);
4342 let leader = LeaderLayer::new(&mut app, link);
4343 root.as_container_layer()
4344 .append(&mut app, leader.as_layer());
4345 root.as_layer().attach(&mut app, owner.id());
4346 assert_eq!(link.leader(&app), Some(leader));
4347 root.as_layer().detach(&mut app);
4348 assert!(link.leader(&app).is_none());
4349 }
4350
4351 #[test]
4352 fn a_replaced_leader_leaves_the_links_new_leader_in_place() {
4353 let cell = AppCell::new();
4354 let mut app = cell.borrow_mut();
4355 let owner = app.create(());
4356 let link = LayerLink::new(&mut app);
4357 let leader1 = LeaderLayer::new(&mut app, link);
4358 let leader2 = LeaderLayer::new(&mut app, link);
4359 leader1.as_layer().attach(&mut app, owner.id());
4360 leader2.as_layer().attach(&mut app, owner.id());
4361 assert_eq!(link.leader(&app), Some(leader2));
4362 leader2.as_layer().detach(&mut app);
4363 leader1.as_layer().detach(&mut app);
4364 assert!(link.leader(&app).is_none());
4365 }
4366
4367 #[test]
4368 fn switching_the_link_of_an_attached_leader_does_not_crash() {
4369 let cell = AppCell::new();
4370 let mut app = cell.borrow_mut();
4371 let owner = app.create(());
4372 let link = LayerLink::new(&mut app);
4373 let leader = LeaderLayer::new(&mut app, link);
4374 leader.as_layer().attach(&mut app, owner.id());
4375 let link2 = LayerLink::new(&mut app);
4376 leader.set_link(&mut app, link2);
4377 leader.as_layer().detach(&mut app);
4378 assert_eq!(leader.link(&app), link2);
4379 assert!(link.leader(&app).is_none());
4380 assert!(link2.leader(&app).is_none());
4381 }
4382
4383 #[test]
4384 fn follower_get_last_transform_after_build_scene_matches_the_leader_offset() {
4385 let cell = AppCell::new();
4386 let mut app = cell.borrow_mut();
4387 let owner = app.create(());
4388 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4389 let link = LayerLink::new(&mut app);
4390 let leader = LeaderLayer::new(&mut app, link);
4391 leader.set_offset(&mut app, Offset::new(10.0, 20.0));
4392 let follower = FollowerLayer::new(&mut app, link);
4393 root.as_container_layer()
4394 .append(&mut app, leader.as_layer());
4395 root.as_container_layer()
4396 .append(&mut app, follower.as_layer());
4397 root.as_layer().attach(&mut app, owner.id());
4398 let _scene = root
4399 .as_container_layer()
4400 .build_scene(&mut app, SceneBuilder::new());
4401 assert_eq!(
4402 follower.get_last_transform(&app).unwrap(),
4403 Matrix4::translation(10.0, 20.0)
4404 );
4405 }
4406
4407 #[test]
4408 fn follower_with_show_when_unlinked_false_pushes_nothing() {
4409 let cell = AppCell::new();
4410 let mut app = cell.borrow_mut();
4411 let link = LayerLink::new(&mut app);
4412 let follower = FollowerLayer::new(&mut app, link);
4413 follower.set_show_when_unlinked(&mut app, false);
4414 let child = offset_layer(&mut app);
4415 follower.as_container_layer().append(&mut app, child);
4416 let _scene = follower
4417 .as_container_layer()
4418 .build_scene(&mut app, SceneBuilder::new());
4419 assert!(follower.get_last_transform(&app).is_none());
4420 }
4421
4422 #[test]
4423 fn annotated_region_layer_find_with_size_offset_and_opaque() {
4424 let cell = AppCell::new();
4425 let mut app = cell.borrow_mut();
4426 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4427 let behind = tag(&mut app, 1);
4428 let front = tag(&mut app, 2);
4429 front.set_opaque(&mut app, true);
4430 root.as_container_layer()
4431 .append(&mut app, behind.as_layer());
4432 root.as_container_layer().append(&mut app, front.as_layer());
4433 let result = root
4434 .as_layer()
4435 .find_all_annotations::<u32>(&app, Offset::ZERO);
4436 assert_eq!(
4437 result
4438 .annotations()
4439 .map(|value| **value)
4440 .collect::<Vec<_>>(),
4441 vec![2],
4442 "an opaque region hides its siblings"
4443 );
4444
4445 let root = OffsetLayer::new(&mut app, Offset::ZERO);
4446 let first = tag(&mut app, 1);
4447 let second = tag(&mut app, 2);
4448 root.as_container_layer().append(&mut app, first.as_layer());
4449 root.as_container_layer()
4450 .append(&mut app, second.as_layer());
4451 let result = root
4452 .as_layer()
4453 .find_all_annotations::<u32>(&app, Offset::ZERO);
4454 assert_eq!(
4455 result
4456 .annotations()
4457 .map(|value| **value)
4458 .collect::<Vec<_>>(),
4459 vec![2, 1],
4460 "front to back when neither is opaque"
4461 );
4462
4463 let sized = tag(&mut app, 3);
4464 sized.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4465 sized.set_offset(&mut app, Offset::new(90.0, 90.0));
4466 assert!(
4467 sized
4468 .as_layer()
4469 .find::<u32>(&app, Offset::new(95.0, 95.0))
4470 .is_some()
4471 );
4472 assert!(
4473 sized.as_layer().find::<u32>(&app, Offset::ZERO).is_none(),
4474 "outside the sized region"
4475 );
4476 }
4477}