Skip to main content

waft_rendering/
layer.rs

1//! Port of Flutter's `rendering/layer.dart`.
2//!
3//! The layer tree: what a repaint boundary's recording is between paint and compositing, and
4//! what `RenderView.compositeFrame` uploads through a [`SceneBuilder`]. A layer is an arena
5//! object; edges are [`AnyLayer`] / [`AnyContainerLayer`] and lifetime is Flutter's
6//! [`LayerHandle`] count, which ends in `dispose` and `App::release_tree_node`.
7//!
8//! A layer keeps the [`EngineLayer`] its `add_to_scene` last made, a node of the scene's tree, and
9//! hands it to [`SceneBuilder::add_retained`] while nothing in its subtree changed, as Flutter's
10//! retained rendering does (`_needsAddToScene`, `markNeedsAddToScene`, `alwaysNeedsAddToScene`,
11//! `engineLayer`).
12
13use std::any::{Any, TypeId};
14use std::cell::Cell;
15use std::collections::HashSet;
16use std::fmt::{self, Debug};
17use std::hash::{Hash, Hasher};
18use std::rc::Rc;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicU64, Ordering};
21
22use waft_embedder::{
23    BlendMode, Clip, EngineLayer, ImageFilter, Matrix4, Offset, Picture, RRect, Rect, Scene,
24    SceneBuilder, Size,
25};
26use waft_embedder::{CompositionLayer, VideoFrameReader};
27use waft_foundation::{App, Handle, HandleId, Ref};
28use waft_gestures::remove_perspective_transform;
29use waft_scheduler::{FrameCallback, SchedulerBinding};
30
31/// Information collected for an annotation that is found in the layer tree.
32///
33/// See also:
34///
35///  * [`AnyLayer::find_all_annotations`], which creates and uses objects of this type.
36#[derive(Debug)]
37pub struct AnnotationEntry<T> {
38    /// The annotation object that is found.
39    pub annotation: Rc<T>,
40    /// The target location described by the local coordinate space of the annotation object.
41    pub local_position: Offset,
42}
43
44impl<T> AnnotationEntry<T> {
45    /// Create an entry of found annotation by providing the object and related information.
46    pub fn new(annotation: Rc<T>, local_position: Offset) -> AnnotationEntry<T> {
47        AnnotationEntry {
48            annotation,
49            local_position,
50        }
51    }
52}
53
54/// Information collected about a list of annotations that are found in the layer tree.
55///
56/// See also:
57///
58///  * [`AnnotationEntry`], which are members of this type.
59///  * [`AnyLayer::find_all_annotations`], which creates and uses an object of this type.
60#[derive(Debug)]
61pub struct AnnotationResult<T> {
62    entries: Vec<AnnotationEntry<T>>,
63}
64
65impl<T> AnnotationResult<T> {
66    /// An empty result.
67    pub fn new() -> AnnotationResult<T> {
68        AnnotationResult {
69            entries: Vec::new(),
70        }
71    }
72
73    /// Add a new entry to the end of the result.
74    ///
75    /// Usually, entries should be added in order from most specific to least specific,
76    /// typically during an upward walk of the tree.
77    pub fn add(&mut self, entry: AnnotationEntry<T>) {
78        self.entries.push(entry);
79    }
80
81    /// The [`AnnotationEntry`] objects recorded.
82    ///
83    /// The first entry is the most specific, typically the one at the leaf of the tree.
84    pub fn entries(&self) -> &[AnnotationEntry<T>] {
85        &self.entries
86    }
87
88    /// The annotations recorded.
89    ///
90    /// The first entry is the most specific, typically the one at the leaf of the tree. It is
91    /// similar to [`entries`](Self::entries) but does not contain other information.
92    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/// Dart's `AnnotationResult<S>` while a search walks the tree: the type it looks for and what
104/// it has found, erased so [`Layer::find_annotations`] can sit in a vtable. [`AnyLayer::find`]
105/// and [`AnyLayer::find_all_annotations`] turn it back into an [`AnnotationResult<S>`]. See
106/// `PORTING.md`.
107#[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    /// Dart's `T == S`: whether `annotation` is exactly the type this search is for.
122    pub fn accepts(&self, annotation: &dyn Any) -> bool {
123        annotation.type_id() == self.searched
124    }
125
126    /// Dart's `result.add(AnnotationEntry(annotation:, localPosition:))`. Only for an
127    /// annotation [`accepts`](Self::accepts) answered true for.
128    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    /// Dart's `result.entries.isNotEmpty`, negated.
134    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
150/// The callback of [`AnyLayer::add_composition_callback`].
151pub type CompositionCallback = Rc<dyn Fn(&mut App, AnyLayer)>;
152
153static NEXT_CALLBACK_ID: AtomicU64 = AtomicU64::new(0);
154
155/// Flutter's `Layer` fields, held by every layer under the field `layer`
156/// ([`layer_accessors!`]).
157pub struct LayerData {
158    callbacks: Vec<(u64, CompositionCallback)>,
159    composition_callback_count: i32,
160    debug_mutations_locked: bool,
161    /// Set when this layer is appended to a [`ContainerLayer`], and unset when it is removed.
162    ///
163    /// This cannot be set from `attach` or `detach` which is called when an entire subtree is
164    /// attached to or detached from an owner. Layers may be appended to or removed from a
165    /// [`ContainerLayer`] regardless of whether they are attached or detached, and detaching a
166    /// layer from an owner does not imply that it has been removed from its parent.
167    parent_handle: LayerHandle<AnyLayer>,
168    /// Incremented by [`LayerHandle`].
169    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    /// Whether `add_to_scene` must run for this layer: it changed since it was last added, or
177    /// never was. `update_subtree_needs_add_to_scene` folds the descendants' in before a scene
178    /// is built.
179    needs_add_to_scene: bool,
180    /// The node this layer's subtree made when it was last added to a scene, for
181    /// [`SceneBuilder::add_retained`] while nothing in the subtree changed.
182    engine_layer: Option<EngineLayer>,
183}
184
185impl LayerData {
186    /// Flutter's `Layer()` constructor.
187    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/// Implements the [`Layer`] field accessors for a `layer` field.
222///
223/// `layer_accessors!(container)` also records that the type `extends ContainerLayer`, so its
224/// [`AnyLayer`] can be narrowed with [`AnyLayer::as_container_layer`].
225#[macro_export]
226macro_rules! layer_accessors {
227    () => {
228        fn layer_data(
229            self: ::waft_foundation::Handle<Self>,
230            app: &::waft_foundation::App,
231        ) -> &$crate::LayerData {
232            &app.get(self).layer
233        }
234        fn layer_data_mut(
235            self: ::waft_foundation::Handle<Self>,
236            app: &mut ::waft_foundation::App,
237        ) -> &mut $crate::LayerData {
238            &mut app.get_mut(self).layer
239        }
240    };
241    (container) => {
242        $crate::layer_accessors!();
243        const AS_CONTAINER: Option<fn() -> &'static $crate::ContainerLayerVTable> =
244            Some(|| const { &$crate::ContainerLayerVTable::of::<Self>() });
245    };
246}
247
248/// A composited layer.
249///
250/// During painting, the render tree generates a tree of composited layers that are uploaded
251/// into the engine and displayed by the compositor. This class is the base class for all
252/// composited layers.
253///
254/// Most layers can have their properties mutated, and layers can be moved to different parents.
255/// The scene must be explicitly recomposited after such changes are made; the layer tree does
256/// not maintain its own dirty state.
257///
258/// To composite the tree, create a [`SceneBuilder`] object, pass it to the root layer's
259/// [`AnyContainerLayer::build_scene`] and give the [`Scene`] to the view.
260///
261/// ## Memory
262///
263/// Layers retain resources between frames to speed up rendering. A layer will retain these
264/// resources until all [`LayerHandle`]s referring to the layer have nulled out their references.
265///
266/// Layers must not be used after disposal. If a `RenderObject` needs to maintain a layer for
267/// later usage, it must create a handle to that layer. This is handled automatically for the
268/// `RenderObject.layer` property, but additional layers must use their own [`LayerHandle`].
269///
270/// Flutter's abstract `Layer`: the shared bodies are on [`LayerBase`]. A leaf implements this
271/// trait; where Dart runs the inherited body it calls it by name, `LayerBase::attach(self, app,
272/// owner)`.
273pub trait Layer: Sized + 'static {
274    /// Dart's base-class fields, held under the field `layer` ([`layer_accessors!`]).
275    fn layer_data(self: Handle<Self>, app: &App) -> &LayerData;
276
277    /// See [`layer_data`](Self::layer_data).
278    fn layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut LayerData;
279
280    /// The container table when this type `extends ContainerLayer`; `layer_accessors!(container)`
281    /// sets it. Dart's `layer is ContainerLayer`.
282    const AS_CONTAINER: Option<fn() -> &'static ContainerLayerVTable> = None;
283
284    /// Whether or not this layer, or any child layers, can be rasterized with `Scene.toImage`.
285    ///
286    /// If `false`, calling the above methods may yield an image which is incomplete.
287    ///
288    /// This value may change throughout the lifetime of the object, as the child layers
289    /// themselves are added or removed.
290    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
291        let _ = (self, app);
292        true
293    }
294
295    /// Describes the clip that would be applied to contents of this layer, if any.
296    fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
297        let _ = (self, app);
298        None
299    }
300
301    /// Subclasses may override this to true to disable retained rendering.
302    fn always_needs_add_to_scene(self: Handle<Self>, app: &App) -> bool {
303        let _ = (self, app);
304        false
305    }
306
307    /// Clears any retained resources that this layer holds.
308    ///
309    /// This method must dispose resources such as [`Picture`] objects. The layer is still usable
310    /// after this call, but any graphics related resources it holds will need to be recreated.
311    ///
312    /// This method _only_ disposes resources for this layer. For example, if it is a
313    /// [`ContainerLayer`], it does not dispose resources of any children. However,
314    /// [`ContainerLayer`]s do remove any children they have when this method is called, and if
315    /// this layer was the last holder of a removed child handle, the child may recursively clean
316    /// up its resources.
317    ///
318    /// This method automatically gets called when all outstanding [`LayerHandle`]s are disposed.
319    /// [`LayerHandle`] objects are typically held by the parent layer of this layer and any
320    /// `RenderObject`s that participated in creating it.
321    ///
322    /// After calling this method, the object is unusable: the base body gives up the tree's hold
323    /// on it, and the arena frees it at the next checkpoint unless a `Ref` still keeps it.
324    /// An override ends with `LayerBase::dispose(self, app)`.
325    fn dispose(self: Handle<Self>, app: &mut App) {
326        LayerBase::dispose(self, app);
327    }
328
329    /// Mark this layer as attached to the given owner.
330    ///
331    /// Typically called only from the parent's `attach` method, and by the owner to mark the
332    /// root of a tree as attached.
333    ///
334    /// Subclasses with children should override this method to `attach` all their children to
335    /// the same owner after calling the inherited method, `LayerBase::attach(self, app, owner)`.
336    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
337        LayerBase::attach(self, app, owner);
338    }
339
340    /// Mark this layer as detached from its owner.
341    ///
342    /// Typically called only from the parent's `detach`, and by the owner to mark the root of a
343    /// tree as detached.
344    ///
345    /// Subclasses with children should override this method to `detach` all their children
346    /// after calling the inherited method, `LayerBase::detach(self, app)`.
347    fn detach(self: Handle<Self>, app: &mut App) {
348        LayerBase::detach(self, app);
349    }
350
351    /// Adjust the depth of this node's children, if any.
352    ///
353    /// Override this method in subclasses with child nodes to call
354    /// [`AnyContainerLayer::redepth_child`] for each child. Do not call this method directly.
355    fn redepth_children(self: Handle<Self>, app: &mut App) {
356        // ContainerLayer provides an implementation since its the only one that
357        // can actually have children.
358        let _ = (self, app);
359    }
360
361    /// Search this layer and its subtree for annotations of the searched type at the location
362    /// described by `local_position`.
363    ///
364    /// This method is called by the default implementation of [`AnyLayer::find`] and
365    /// [`AnyLayer::find_all_annotations`]. Override this method to customize how the layer
366    /// should search for annotations, or if the layer has its own annotations to add.
367    ///
368    /// The default implementation always returns `false`, which means neither the layer nor its
369    /// children has annotations, and the annotation search is not absorbed either.
370    ///
371    /// The annotations are searched by first visiting each child recursively, then this layer,
372    /// resulting in an order from visually front to back. New annotations found during the walk
373    /// are added to the tail of `result`.
374    ///
375    /// The `only_first` parameter indicates that, if true, the search will stop when it finds
376    /// the first qualified annotation; otherwise, it will walk the entire subtree.
377    ///
378    /// The return value indicates the opacity of this layer and its subtree at this position. If
379    /// it returns true, then this layer's parent should skip the children behind this layer. The
380    /// return value does not affect whether the parent adds its own annotations.
381    fn find_annotations(
382        self: Handle<Self>,
383        app: &App,
384        result: &mut AnnotationSearch,
385        local_position: Offset,
386        only_first: bool,
387    ) -> bool {
388        let _ = (self, app, result, local_position, only_first);
389        false
390    }
391
392    /// Override this method to upload this layer to the engine.
393    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder);
394
395    /// Dart's `_fireCompositionCallbacks`; [`ContainerLayer`] recurses into its children.
396    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
397        LayerBase::fire_composition_callbacks(self, app, include_children);
398    }
399}
400
401/// The bodies of Flutter's `Layer` that a subclass calls as `super`: `LayerBase::dispose(self,
402/// app)` where Dart writes `super.dispose()`. The virtual call is on [`AnyLayer`].
403pub trait LayerBase: Layer {
404    /// `Layer.dispose`.
405    fn dispose(self: Handle<Self>, app: &mut App) {
406        let data = self.layer_data_mut(app);
407        debug_assert!(!data.debug_mutations_locked);
408        debug_assert!(
409            !data.debug_disposed,
410            "Layers must only be disposed once. This is typically handled by LayerHandle. \
411             Subclasses should not directly call dispose, except to call LayerBase::dispose in \
412             an overridden dispose method. Tests must only call dispose once."
413        );
414        debug_assert!(
415            data.ref_count == 0,
416            "Do not directly call dispose on a layer. Instead, use a LayerHandle."
417        );
418        data.debug_disposed = true;
419        // Dart's engine layer is dropped here; the tree's part of the entry goes with it.
420        app.release_tree_node(self);
421    }
422
423    /// `Layer.attach`.
424    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
425        let data = self.layer_data_mut(app);
426        debug_assert!(data.owner.is_none());
427        data.owner = Some(owner);
428    }
429
430    /// `Layer.detach`.
431    fn detach(self: Handle<Self>, app: &mut App) {
432        let data = self.layer_data_mut(app);
433        debug_assert!(data.owner.is_some());
434        data.owner = None;
435        let this = self.as_layer();
436        debug_assert!(
437            this.parent(app)
438                .is_none_or(|parent| this.attached(app) == parent.as_layer().attached(app))
439        );
440    }
441
442    /// `Layer._fireCompositionCallbacks`.
443    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
444        let _ = include_children;
445        let this = self.as_layer();
446        let callbacks: Vec<CompositionCallback> = self
447            .layer_data(app)
448            .callbacks
449            .iter()
450            .map(|(_, callback)| Rc::clone(callback))
451            .collect();
452        for callback in callbacks {
453            this.run_composition_callback(app, &callback);
454        }
455    }
456}
457
458impl<T: Layer> LayerBase for T {}
459
460/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
461fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
462    Handle::from_id(id)
463}
464
465/// The vtable of an erased [`AnyLayer`]: one `&'static` table per type, built from the trait
466/// impl by [`Layer::as_layer`]. Copied out of the handle before a virtual call, so the slot is
467/// not borrowed across it.
468///
469/// Public only so [`layer_accessors!`] can name it from another crate.
470#[doc(hidden)]
471pub struct LayerVTable {
472    layer_data: fn(&App, HandleId) -> &LayerData,
473    layer_data_mut: fn(&mut App, HandleId) -> &mut LayerData,
474    supports_rasterization: fn(&App, HandleId) -> bool,
475    describe_clip_bounds: fn(&App, HandleId) -> Option<Rect>,
476    always_needs_add_to_scene: fn(&App, HandleId) -> bool,
477    dispose: fn(&mut App, HandleId),
478    attach: fn(&mut App, HandleId, HandleId),
479    detach: fn(&mut App, HandleId),
480    redepth_children: fn(&mut App, HandleId),
481    find_annotations: fn(&App, HandleId, &mut AnnotationSearch, Offset, bool) -> bool,
482    add_to_scene: fn(&mut App, HandleId, &mut SceneBuilder),
483    fire_composition_callbacks: fn(&mut App, HandleId, bool),
484    as_container: Option<fn() -> &'static ContainerLayerVTable>,
485}
486
487impl LayerVTable {
488    pub const fn of<T: Layer>() -> LayerVTable {
489        LayerVTable {
490            layer_data: |app, id| T::layer_data(resolve(id), app),
491            layer_data_mut: |app, id| T::layer_data_mut(resolve(id), app),
492            supports_rasterization: |app, id| T::supports_rasterization(resolve(id), app),
493            describe_clip_bounds: |app, id| T::describe_clip_bounds(resolve(id), app),
494            always_needs_add_to_scene: |app, id| T::always_needs_add_to_scene(resolve(id), app),
495            dispose: |app, id| T::dispose(resolve(id), app),
496            attach: |app, id, owner| T::attach(resolve(id), app, owner),
497            detach: |app, id| T::detach(resolve(id), app),
498            redepth_children: |app, id| T::redepth_children(resolve(id), app),
499            find_annotations: |app, id, result, local_position, only_first| {
500                T::find_annotations(resolve(id), app, result, local_position, only_first)
501            },
502            add_to_scene: |app, id, builder| T::add_to_scene(resolve(id), app, builder),
503            fire_composition_callbacks: |app, id, include_children| {
504                T::fire_composition_callbacks(resolve(id), app, include_children)
505            },
506            as_container: T::AS_CONTAINER,
507        }
508    }
509}
510
511/// Erased `Layer`: one identity and a static vtable, the fat pointer rustc cannot build for an
512/// arena id. No lease.
513///
514/// Equality is Dart's `==` on an object reference.
515#[derive(Clone, Copy)]
516pub struct AnyLayer {
517    id: HandleId,
518    vtable: &'static LayerVTable,
519}
520
521impl PartialEq for AnyLayer {
522    fn eq(&self, other: &AnyLayer) -> bool {
523        self.id == other.id
524    }
525}
526
527impl Eq for AnyLayer {}
528
529impl Hash for AnyLayer {
530    fn hash<H: Hasher>(&self, state: &mut H) {
531        self.id.hash(state);
532    }
533}
534
535impl From<AnyLayer> for HandleId {
536    fn from(layer: AnyLayer) -> HandleId {
537        layer.id
538    }
539}
540
541impl Debug for AnyLayer {
542    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543        write!(f, "AnyLayer({:?})", self.id)
544    }
545}
546
547impl AnyLayer {
548    pub fn id(self) -> HandleId {
549        self.id
550    }
551
552    fn data(self, app: &App) -> &LayerData {
553        (self.vtable.layer_data)(app, self.id)
554    }
555
556    fn data_mut(self, app: &mut App) -> &mut LayerData {
557        (self.vtable.layer_data_mut)(app, self.id)
558    }
559
560    /// Dart's `layer as ContainerLayer`, as an `Option`.
561    pub fn as_container_layer(self) -> Option<AnyContainerLayer> {
562        self.vtable
563            .as_container
564            .map(|vtable| AnyContainerLayer::from_vtable(self.id, vtable()))
565    }
566
567    /// Whether the subtree rooted at this layer has any composition callback observers.
568    ///
569    /// This only evaluates to true if the subtree rooted at this node has observers. For
570    /// example, it may evaluate to true on a parent node but false on a child if the parent has
571    /// observers but the child does not.
572    pub fn subtree_has_composition_callbacks(self, app: &App) -> bool {
573        self.data(app).composition_callback_count > 0
574    }
575
576    fn update_subtree_composition_observer_count(self, app: &mut App, delta: i32) {
577        debug_assert!(delta != 0);
578        let data = self.data_mut(app);
579        data.composition_callback_count += delta;
580        debug_assert!(data.composition_callback_count >= 0);
581        if let Some(parent) = data.parent {
582            parent
583                .as_layer()
584                .update_subtree_composition_observer_count(app, delta);
585        }
586    }
587
588    /// See [`Layer::fire_composition_callbacks`].
589    pub(crate) fn fire_composition_callbacks(self, app: &mut App, include_children: bool) {
590        (self.vtable.fire_composition_callbacks)(app, self.id, include_children);
591    }
592
593    /// The closure Dart stores in `_callbacks`: the callback between the mutation-lock asserts.
594    fn run_composition_callback(self, app: &mut App, callback: &CompositionCallback) {
595        if cfg!(debug_assertions) {
596            self.data_mut(app).debug_mutations_locked = true;
597        }
598        callback(app, self);
599        if cfg!(debug_assertions) {
600            self.data_mut(app).debug_mutations_locked = false;
601        }
602    }
603
604    /// See [`Layer::supports_rasterization`].
605    pub fn supports_rasterization(self, app: &App) -> bool {
606        (self.vtable.supports_rasterization)(app, self.id)
607    }
608
609    /// See [`Layer::describe_clip_bounds`].
610    pub fn describe_clip_bounds(self, app: &App) -> Option<Rect> {
611        (self.vtable.describe_clip_bounds)(app, self.id)
612    }
613
614    /// Adds a callback for when the layer tree that this layer is part of gets composited, or
615    /// when it is detached and will not be rendered again.
616    ///
617    /// The callback receives a reference to this layer. The recipient must not mutate the layer
618    /// during the scope of the callback, but may traverse the tree to find information about the
619    /// current transform or clip. The layer may not be attached anymore in this state, but even
620    /// if it is detached it may still have an also detached parent it can visit.
621    ///
622    /// If new callbacks are added or removed within the callback, the new callbacks will fire
623    /// (or stop firing) on the _next_ compositing event.
624    ///
625    /// Composition callbacks are useful in place of pushing a layer that would otherwise try to
626    /// observe the layer tree without actually affecting compositing. For example, a composition
627    /// callback may be used to observe the total transform and clip of the current container
628    /// layer to determine whether a render object drawn into it is visible or not.
629    ///
630    /// Calling the returned callback will remove `callback` from the composition callbacks.
631    pub fn add_composition_callback(
632        self,
633        app: &mut App,
634        callback: CompositionCallback,
635    ) -> Box<dyn FnOnce(&mut App)> {
636        self.update_subtree_composition_observer_count(app, 1);
637        let callback_id = NEXT_CALLBACK_ID.fetch_add(1, Ordering::Relaxed) + 1;
638        self.data_mut(app).callbacks.push((callback_id, callback));
639        // Dart's closure keeps the layer it names alive, disposed or not.
640        let layer = self.id.keep(app);
641        Box::new(move |app: &mut App| {
642            let index = self
643                .data(app)
644                .callbacks
645                .iter()
646                .position(|(id, _)| *id == callback_id);
647            debug_assert!(self.debug_disposed(app) || index.is_some());
648            if let Some(index) = index {
649                self.data_mut(app).callbacks.remove(index);
650            }
651            self.update_subtree_composition_observer_count(app, -1);
652            drop(layer);
653        })
654    }
655
656    /// If asserts are enabled, returns whether `dispose` has been called since the last time any
657    /// retained resources were created.
658    ///
659    /// A disposed layer's arena entry is gone, so a stale handle answers true as well.
660    pub fn debug_disposed(self, app: &App) -> bool {
661        !app.contains(self.id) || self.data(app).debug_disposed
662    }
663
664    /// Called by [`LayerHandle`].
665    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    /// Returns the number of objects holding a [`LayerHandle`] to this layer.
676    pub fn debug_handle_count(self, app: &App) -> u32 {
677        self.data(app).ref_count
678    }
679
680    /// See [`Layer::dispose`].
681    pub fn dispose(self, app: &mut App) {
682        (self.vtable.dispose)(app, self.id);
683    }
684
685    /// This layer's parent in the layer tree.
686    ///
687    /// The parent of the root node in the layer tree is `None`.
688    ///
689    /// Only subclasses of [`ContainerLayer`] can have children in the layer tree. All other
690    /// layer classes are used for leaves in the layer tree.
691    pub fn parent(self, app: &App) -> Option<AnyContainerLayer> {
692        self.data(app).parent
693    }
694
695    /// The owner for this layer (`None` if unattached).
696    ///
697    /// The entire layer tree that this layer belongs to will have the same owner.
698    ///
699    /// Typically the owner is a `RenderView`.
700    pub fn owner(self, app: &App) -> Option<HandleId> {
701        self.data(app).owner
702    }
703
704    /// Whether the layer tree containing this layer is attached to an owner.
705    ///
706    /// This becomes true during the call to `attach`.
707    ///
708    /// This becomes false during the call to `detach`.
709    pub fn attached(self, app: &App) -> bool {
710        self.data(app).owner.is_some()
711    }
712
713    /// See [`Layer::attach`].
714    pub fn attach(self, app: &mut App, owner: HandleId) {
715        (self.vtable.attach)(app, self.id, owner);
716    }
717
718    /// See [`Layer::detach`].
719    pub fn detach(self, app: &mut App) {
720        (self.vtable.detach)(app, self.id);
721    }
722
723    /// The depth of this layer in the layer tree.
724    ///
725    /// The depth of nodes in a tree monotonically increases as you traverse down the tree.
726    /// There's no guarantee regarding depth between siblings.
727    ///
728    /// The depth is used to ensure that nodes are processed in depth order.
729    pub fn depth(self, app: &App) -> i32 {
730        self.data(app).depth
731    }
732
733    /// See [`Layer::redepth_children`].
734    pub fn redepth_children(self, app: &mut App) {
735        (self.vtable.redepth_children)(app, self.id);
736    }
737
738    /// This layer's next sibling in the parent layer's child list.
739    pub fn next_sibling(self, app: &App) -> Option<AnyLayer> {
740        self.data(app).next_sibling
741    }
742
743    /// This layer's previous sibling in the parent layer's child list.
744    pub fn previous_sibling(self, app: &App) -> Option<AnyLayer> {
745        self.data(app).previous_sibling
746    }
747
748    /// Removes this layer from its parent layer's child list.
749    ///
750    /// This has no effect if the layer's parent is already `None`.
751    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    /// See [`Layer::find_annotations`].
759    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    /// Search this layer and its subtree for the first annotation of type `S` under the point
770    /// described by `local_position`.
771    ///
772    /// Returns `None` if no matching annotations are found.
773    ///
774    /// By default this method calls [`find_annotations`](Self::find_annotations) with
775    /// `only_first: true` and returns the annotation of the first result. Prefer overriding
776    /// [`Layer::find_annotations`] instead of this method, because during an annotation search,
777    /// only `find_annotations` is recursively called, while custom behavior in this method is
778    /// ignored.
779    ///
780    /// See also:
781    ///
782    ///  * [`find_all_annotations`](Self::find_all_annotations), which is similar but returns all
783    ///    annotations found at the given position.
784    ///  * `AnnotatedRegionLayer`, for placing values in the layer tree.
785    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    /// Search this layer and its subtree for all annotations of type `S` under the point
797    /// described by `local_position`.
798    ///
799    /// Returns a result with empty entries if no matching annotations are found.
800    ///
801    /// By default this method calls [`find_annotations`](Self::find_annotations) with
802    /// `only_first: false` and returns the annotations of its result. Prefer overriding
803    /// [`Layer::find_annotations`] instead of this method, because during an annotation search,
804    /// only `find_annotations` is recursively called, while custom behavior in this method is
805    /// ignored.
806    ///
807    /// See also:
808    ///
809    ///  * [`find`](Self::find), which is similar but returns the first annotation found at the
810    ///    given position.
811    ///  * `AnnotatedRegionLayer`, for placing values in the layer tree.
812    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    /// See [`Layer::add_to_scene`].
823    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    /// Whether `add_to_scene` must run for this layer when a scene is next built: it changed
828    /// since it was last added, or never was, or a descendant did as far as
829    /// [`update_subtree_needs_add_to_scene`](Self::update_subtree_needs_add_to_scene) has
830    /// found out.
831    pub fn needs_add_to_scene(self, app: &App) -> bool {
832        self.data(app).needs_add_to_scene
833    }
834
835    /// Mark that this layer has changed and `add_to_scene` needs to be called.
836    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        // Already marked. Short-circuit.
844        if self.data(app).needs_add_to_scene {
845            return;
846        }
847        self.data_mut(app).needs_add_to_scene = true;
848    }
849
850    /// See [`Layer::always_needs_add_to_scene`].
851    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    /// The engine layer used to render this layer: the node of the scene's tree its subtree made
856    /// when it was last added to a scene, which [`SceneBuilder::add_retained`] adds again while
857    /// nothing in the subtree changed.
858    pub fn engine_layer(self, app: &App) -> Option<EngineLayer> {
859        self.data(app).engine_layer.clone()
860    }
861
862    /// Sets the engine layer used to render this layer.
863    ///
864    /// Typically this is set to the value [`SceneBuilder::pop`] returned in `add_to_scene`.
865    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            // The parent must build a new engine layer to add this one to, and so is marked as
871            // needing `add_to_scene`. When the whole tree is rendered the parent is adding
872            // itself already and clears the flag when it is done; when an interior layer is
873            // rendered on its own (an `OffsetLayer::to_image`) the mark waits for the frame
874            // that next renders the parent.
875            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    /// Traverses the layer subtree starting from this layer and determines whether it needs
884    /// `add_to_scene`.
885    ///
886    /// A layer needs `add_to_scene` if any of the following is true:
887    ///
888    /// - [`always_needs_add_to_scene`](Self::always_needs_add_to_scene) is true.
889    /// - [`mark_needs_add_to_scene`](Self::mark_needs_add_to_scene) has been called.
890    /// - Any of its descendants need `add_to_scene`.
891    ///
892    /// Dart's `ContainerLayer` override recurses into the children; here the erased handle
893    /// knows whether it is a container.
894    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    /// Dart's `_addToSceneWithRetainedRendering`: the retained engine layer where the subtree
913    /// has not changed, `add_to_scene` otherwise.
914    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        // There can't be a loop by adding a retained layer subtree whose needs_add_to_scene is
917        // false: a retained layer appended to one of its own descendants changes that
918        // descendant's children, which sets the flag.
919        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        // Clearing the flag after `add_to_scene`, not before: it calls the children's, which
927        // may mark this layer.
928        self.data_mut(app).needs_add_to_scene = false;
929    }
930}
931
932/// A layer handle of any concreteness — [`AnyLayer`], [`AnyContainerLayer`], [`AnyOffsetLayer`]
933/// or a typed `Handle<L>` — for what a [`LayerHandle`] can hold. Dart's `T extends Layer`.
934pub trait ErasedLayer: Copy + PartialEq + Debug + 'static {
935    /// Dart's implicit upcast to `Layer`.
936    fn as_layer(self) -> AnyLayer;
937}
938
939impl ErasedLayer for AnyLayer {
940    fn as_layer(self) -> AnyLayer {
941        self
942    }
943}
944
945/// Dart's implicit upcast of a concrete layer to `Layer`: the type-erased handle, through the
946/// table built from the type's `impl Layer`.
947impl<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
956/// A handle to prevent a [`Layer`]'s platform graphics resources from being disposed.
957///
958/// [`Layer`] objects retain native resources such as [`Picture`] objects. These objects may in
959/// turn retain large chunks of texture memory, either directly or indirectly.
960///
961/// The layer's native resources must be retained as long as there is some object that can add
962/// it to a scene. Typically, this is either its parent or an undisposed `RenderObject` that will
963/// append it to a [`ContainerLayer`]. Layers automatically hold a handle to their children, and
964/// `RenderObject`s automatically hold a handle to their `RenderObject.layer` as well as any
965/// [`PictureLayer`]s that they paint into using the `PaintingContext.canvas`. A layer
966/// automatically releases its resources once at least one handle has been acquired and all
967/// handles have been disposed. `RenderObject`s that create additional layer objects must
968/// manually manage the handles for that layer similarly to the implementation of
969/// `RenderObject.layer`.
970///
971/// If a `RenderObject` creates layers in addition to its `RenderObject.layer` and it intends to
972/// reuse those layers separately from `RenderObject.layer`, it must create a handle to that
973/// layer and dispose of it when the layer is no longer needed. For example, if it re-creates or
974/// nulls out an existing layer in `RenderObject.paint`, it should dispose of the handle to the
975/// old layer. It should also dispose of any layer handles it holds in `RenderObject.dispose`.
976///
977/// To dispose of a layer handle, set its layer to `None` with [`set_layer`](Self::set_layer).
978/// The handle lives inside an arena object, so the setter reaches it through the `App` rather
979/// than through `&mut self`; a handle dropped without clearing keeps its layer until the `App`
980/// goes, as a Dart handle that is never nulled would. See `PORTING.md`.
981pub struct LayerHandle<T> {
982    layer: Option<T>,
983}
984
985impl<T> LayerHandle<T> {
986    /// Create a new layer handle referencing no [`Layer`]. Dart's `LayerHandle([layer])` with
987    /// a layer is `new` then [`set_layer`](Self::set_layer).
988    pub const fn new() -> LayerHandle<T> {
989        LayerHandle { layer: None }
990    }
991}
992
993impl<T: ErasedLayer> LayerHandle<T> {
994    /// The [`Layer`] whose resources this object keeps alive.
995    pub fn layer(&self) -> Option<T> {
996        self.layer
997    }
998
999    /// Dart's `handle.layer = layer` for the handle `at` reaches inside `app`.
1000    ///
1001    /// Setting a new value or `None` will dispose the previously held layer if there are no
1002    /// other open handles to that layer.
1003    ///
1004    /// # Panics
1005    ///
1006    /// In debug builds, if `layer` is already disposed.
1007    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        // The write comes before the unref, not after as in Dart: a layer's `parent_handle`
1021        // lives in the layer it holds, and the unref may dispose that layer.
1022        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
1047/// A composited layer containing a [`Picture`].
1048///
1049/// Picture layers are always leaves in the layer tree. They are also responsible for disposing
1050/// of the [`Picture`] object they hold. This is typically done when their parent and all
1051/// `RenderObject`s that participated in painting the picture have been disposed.
1052pub struct PictureLayer {
1053    layer: LayerData,
1054    /// The bounds that were used for the canvas that drew this layer's picture.
1055    ///
1056    /// This is purely advisory. It can help debug why certain drawing commands are being culled.
1057    pub canvas_bounds: Rect,
1058    picture: Option<Arc<Picture>>,
1059    is_complex_hint: bool,
1060    will_change_hint: bool,
1061}
1062
1063impl PictureLayer {
1064    /// Creates a leaf layer for the layer tree.
1065    pub fn new(app: &mut App, canvas_bounds: Rect) -> Handle<PictureLayer> {
1066        app.create(PictureLayer {
1067            layer: LayerData::new(),
1068            canvas_bounds,
1069            picture: None,
1070            is_complex_hint: false,
1071            will_change_hint: false,
1072        })
1073        .into_tree_node(app)
1074    }
1075
1076    /// The picture recorded for this layer.
1077    ///
1078    /// The picture's coordinate system matches this layer's coordinate system.
1079    pub fn picture(self: Handle<Self>, app: &App) -> Option<&Arc<Picture>> {
1080        app.get(self).picture.as_ref()
1081    }
1082
1083    /// See [`picture`](Self::picture). Dart's `_picture?.dispose()` is the drop of the old one.
1084    pub fn set_picture(self: Handle<Self>, app: &mut App, picture: Option<Arc<Picture>>) {
1085        debug_assert!(!app.get(self).layer.debug_disposed);
1086        self.as_layer().mark_needs_add_to_scene(app);
1087        app.get_mut(self).picture = picture;
1088    }
1089
1090    /// Hints that the painting in this layer is complex and would benefit from caching.
1091    ///
1092    /// If this hint is not set, the compositor will apply its own heuristics to decide whether
1093    /// the this layer is complex enough to benefit from caching.
1094    pub fn is_complex_hint(self: Handle<Self>, app: &App) -> bool {
1095        app.get(self).is_complex_hint
1096    }
1097
1098    /// See [`is_complex_hint`](Self::is_complex_hint).
1099    pub fn set_is_complex_hint(self: Handle<Self>, app: &mut App, value: bool) {
1100        if value != app.get(self).is_complex_hint {
1101            app.get_mut(self).is_complex_hint = value;
1102            self.as_layer().mark_needs_add_to_scene(app);
1103        }
1104    }
1105
1106    /// Hints that the painting in this layer is likely to change next frame.
1107    ///
1108    /// This hint tells the compositor not to cache this layer because the cache will not be used
1109    /// in the future. If this hint is not set, the compositor will apply its own heuristics to
1110    /// decide whether this layer is likely to be reused in the future.
1111    pub fn will_change_hint(self: Handle<Self>, app: &App) -> bool {
1112        app.get(self).will_change_hint
1113    }
1114
1115    /// See [`will_change_hint`](Self::will_change_hint).
1116    pub fn set_will_change_hint(self: Handle<Self>, app: &mut App, value: bool) {
1117        if value != app.get(self).will_change_hint {
1118            app.get_mut(self).will_change_hint = value;
1119            self.as_layer().mark_needs_add_to_scene(app);
1120        }
1121    }
1122}
1123
1124impl Layer for PictureLayer {
1125    crate::layer_accessors!();
1126
1127    fn dispose(self: Handle<Self>, app: &mut App) {
1128        self.set_picture(app, None); // Will dispose _picture.
1129        LayerBase::dispose(self, app);
1130    }
1131
1132    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1133        let this = app.get(self);
1134        let picture = this
1135            .picture
1136            .as_ref()
1137            .expect("a PictureLayer has a picture when it is added to the scene");
1138        builder.add_picture(
1139            Offset::ZERO,
1140            picture,
1141            this.is_complex_hint,
1142            this.will_change_hint,
1143        );
1144    }
1145
1146    fn find_annotations(
1147        self: Handle<Self>,
1148        _app: &App,
1149        _result: &mut AnnotationSearch,
1150        _local_position: Offset,
1151        _only_first: bool,
1152    ) -> bool {
1153        false
1154    }
1155}
1156
1157/// A layer that places a composition layer the host composites: Flutter's `PlatformViewLayer`.
1158///
1159/// A leaf, like a picture layer, retained with its ancestors like any other: the scene keeps it
1160/// as a layer of its own, and a host places the composition layer from the tree every frame.
1161pub struct EmbeddedLayer {
1162    layer: LayerData,
1163    composition_layer: Arc<dyn CompositionLayer>,
1164    /// Where the composition layer goes, in this layer's coordinates.
1165    rect: Rect,
1166}
1167
1168impl EmbeddedLayer {
1169    /// A layer placing `composition_layer` at `rect`.
1170    pub fn new(
1171        app: &mut App,
1172        composition_layer: Arc<dyn CompositionLayer>,
1173        rect: Rect,
1174    ) -> Handle<EmbeddedLayer> {
1175        app.create(EmbeddedLayer {
1176            layer: LayerData::new(),
1177            composition_layer,
1178            rect,
1179        })
1180        .into_tree_node(app)
1181    }
1182
1183    pub fn composition_layer(self: Handle<Self>, app: &App) -> &Arc<dyn CompositionLayer> {
1184        &app.get(self).composition_layer
1185    }
1186
1187    pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1188        app.get(self).rect
1189    }
1190}
1191
1192impl Layer for EmbeddedLayer {
1193    crate::layer_accessors!();
1194
1195    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1196        let this = app.get(self);
1197        builder.add_embedded_layer(Arc::clone(&this.composition_layer), this.rect);
1198    }
1199
1200    fn find_annotations(
1201        self: Handle<Self>,
1202        _app: &App,
1203        _result: &mut AnnotationSearch,
1204        _local_position: Offset,
1205        _only_first: bool,
1206    ) -> bool {
1207        false
1208    }
1209}
1210
1211/// A layer that draws a video as part of the picture: Flutter's `TextureLayer` and Chromium's
1212/// `cc::VideoLayer`, over the reader itself in place of a texture id or a frame provider.
1213///
1214/// A leaf, like a picture layer, retained with its ancestors like any other: it holds the reader,
1215/// never a frame, and whoever draws the scene takes the frame then.
1216pub struct VideoLayer {
1217    layer: LayerData,
1218    reader: Arc<dyn VideoFrameReader>,
1219    /// Where the frames are drawn, in this layer's coordinates.
1220    rect: Rect,
1221}
1222
1223impl VideoLayer {
1224    /// A layer drawing `reader`'s frames into `rect`.
1225    pub fn new(app: &mut App, reader: Arc<dyn VideoFrameReader>, rect: Rect) -> Handle<VideoLayer> {
1226        app.create(VideoLayer {
1227            layer: LayerData::new(),
1228            reader,
1229            rect,
1230        })
1231        .into_tree_node(app)
1232    }
1233
1234    pub fn reader(self: Handle<Self>, app: &App) -> &Arc<dyn VideoFrameReader> {
1235        &app.get(self).reader
1236    }
1237
1238    pub fn rect(self: Handle<Self>, app: &App) -> Rect {
1239        app.get(self).rect
1240    }
1241}
1242
1243impl Layer for VideoLayer {
1244    crate::layer_accessors!();
1245
1246    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1247        let this = app.get(self);
1248        builder.add_video(Arc::clone(&this.reader), this.rect);
1249    }
1250
1251    fn find_annotations(
1252        self: Handle<Self>,
1253        _app: &App,
1254        _result: &mut AnnotationSearch,
1255        _local_position: Offset,
1256        _only_first: bool,
1257    ) -> bool {
1258        false
1259    }
1260}
1261
1262/// Flutter's `ContainerLayer` fields, held under the field `container_layer`
1263/// ([`container_layer_accessors!`]).
1264#[derive(Debug, Default)]
1265pub struct ContainerLayerData {
1266    first_child: Option<AnyLayer>,
1267    last_child: Option<AnyLayer>,
1268}
1269
1270impl ContainerLayerData {
1271    /// No children.
1272    pub const fn new() -> ContainerLayerData {
1273        ContainerLayerData {
1274            first_child: None,
1275            last_child: None,
1276        }
1277    }
1278}
1279
1280/// Implements the [`ContainerLayer`] field accessors for a `container_layer` field.
1281///
1282/// `container_layer_accessors!(offset)` also records that the type `extends OffsetLayer`, so
1283/// its [`AnyContainerLayer`] can be narrowed with [`AnyContainerLayer::as_offset_layer`].
1284#[macro_export]
1285macro_rules! container_layer_accessors {
1286    () => {
1287        fn container_layer_data(
1288            self: ::waft_foundation::Handle<Self>,
1289            app: &::waft_foundation::App,
1290        ) -> &$crate::ContainerLayerData {
1291            &app.get(self).container_layer
1292        }
1293        fn container_layer_data_mut(
1294            self: ::waft_foundation::Handle<Self>,
1295            app: &mut ::waft_foundation::App,
1296        ) -> &mut $crate::ContainerLayerData {
1297            &mut app.get_mut(self).container_layer
1298        }
1299    };
1300    (offset) => {
1301        $crate::container_layer_accessors!();
1302        const AS_OFFSET: Option<fn() -> &'static $crate::OffsetLayerVTable> =
1303            Some(|| const { &$crate::OffsetLayerVTable::of::<Self>() });
1304    };
1305}
1306
1307/// A composited layer that has a list of children.
1308///
1309/// A [`ContainerLayer`] instance merely takes a list of children and inserts them into the
1310/// composited rendering in order. There are subclasses of [`ContainerLayer`] which apply more
1311/// elaborate effects in the process.
1312///
1313/// Flutter's `ContainerLayer`: the child list lives on [`AnyContainerLayer`]; this trait holds
1314/// the virtual `apply_transform` and the bodies of the `Layer` methods it overrides. A leaf's
1315/// `impl Layer` forwards to them: `fn attach(..) { ContainerLayer::attach(self, app, owner) }`.
1316pub trait ContainerLayer: Layer {
1317    /// Mixin field access.
1318    fn container_layer_data(self: Handle<Self>, app: &App) -> &ContainerLayerData;
1319
1320    /// See [`container_layer_data`](Self::container_layer_data).
1321    fn container_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut ContainerLayerData;
1322
1323    /// The offset table when this type `extends OffsetLayer`;
1324    /// `container_layer_accessors!(offset)` sets it. Dart's `layer is OffsetLayer`.
1325    const AS_OFFSET: Option<fn() -> &'static OffsetLayerVTable> = None;
1326
1327    /// Dart's implicit upcast of a concrete layer to `ContainerLayer`.
1328    fn as_container_layer(self: Handle<Self>) -> AnyContainerLayer {
1329        AnyContainerLayer {
1330            id: self.id(),
1331            vtable: const { &ContainerLayerVTable::of::<Self>() },
1332        }
1333    }
1334
1335    /// Applies the transform that would be applied when compositing the given child to the
1336    /// given matrix.
1337    ///
1338    /// Specifically, this should apply the transform that is applied to child's _origin_. When
1339    /// using `apply_transform` with a chain of layers, results will be unreliable unless the
1340    /// deepest layer in the chain collapses the `layerOffset` in `add_to_scene` to zero, meaning
1341    /// that it passes [`Offset::ZERO`] to its children, and bakes any incoming `layerOffset` into
1342    /// the [`SceneBuilder`] as (for instance) a transform (which is then also included in the
1343    /// transformation applied by `apply_transform`).
1344    ///
1345    /// This method is only valid immediately after `add_to_scene` has been called, before any of
1346    /// the properties have been changed.
1347    ///
1348    /// The default implementation does nothing, since [`ContainerLayer`], by default, composites
1349    /// its children at the origin of the [`ContainerLayer`] itself.
1350    ///
1351    /// The `child` argument should generally not be `None`, since in principle a layer could
1352    /// transform each child independently. However, certain layers may explicitly allow `None`
1353    /// as a value, for example if they know that they transform all their children identically.
1354    ///
1355    /// Used by `FollowerLayer` to transform its child to a `LeaderLayer`'s position.
1356    fn apply_transform(
1357        self: Handle<Self>,
1358        app: &App,
1359        child: Option<AnyLayer>,
1360        transform: &mut Matrix4,
1361    ) {
1362        let _ = (self, app, transform);
1363        debug_assert!(child.is_some());
1364    }
1365
1366    /// `ContainerLayer._fireCompositionCallbacks`.
1367    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
1368        LayerBase::fire_composition_callbacks(self, app, include_children);
1369        if !include_children {
1370            return;
1371        }
1372        let mut child = self.as_container_layer().first_child(app);
1373        while let Some(layer) = child {
1374            layer.fire_composition_callbacks(app, include_children);
1375            child = layer.next_sibling(app);
1376        }
1377    }
1378
1379    /// `ContainerLayer.supportsRasterization`.
1380    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
1381        let mut child = self.as_container_layer().last_child(app);
1382        while let Some(layer) = child {
1383            if !layer.supports_rasterization(app) {
1384                return false;
1385            }
1386            child = layer.previous_sibling(app);
1387        }
1388        true
1389    }
1390
1391    /// `ContainerLayer.dispose`.
1392    fn dispose(self: Handle<Self>, app: &mut App) {
1393        self.as_container_layer().remove_all_children(app);
1394        self.layer_data_mut(app).callbacks.clear();
1395        LayerBase::dispose(self, app);
1396    }
1397
1398    /// `ContainerLayer.findAnnotations`.
1399    fn find_annotations(
1400        self: Handle<Self>,
1401        app: &App,
1402        result: &mut AnnotationSearch,
1403        local_position: Offset,
1404        only_first: bool,
1405    ) -> bool {
1406        let mut child = self.as_container_layer().last_child(app);
1407        while let Some(layer) = child {
1408            let is_absorbed = layer.find_annotations(app, result, local_position, only_first);
1409            if is_absorbed {
1410                return true;
1411            }
1412            if only_first && !result.is_empty() {
1413                return is_absorbed;
1414            }
1415            child = layer.previous_sibling(app);
1416        }
1417        false
1418    }
1419
1420    /// `ContainerLayer.attach`.
1421    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
1422        debug_assert!(!self.layer_data(app).debug_mutations_locked);
1423        LayerBase::attach(self, app, owner);
1424        let mut child = self.as_container_layer().first_child(app);
1425        while let Some(layer) = child {
1426            layer.attach(app, owner);
1427            child = layer.next_sibling(app);
1428        }
1429    }
1430
1431    /// `ContainerLayer.detach`.
1432    fn detach(self: Handle<Self>, app: &mut App) {
1433        debug_assert!(!self.layer_data(app).debug_mutations_locked);
1434        LayerBase::detach(self, app);
1435        let mut child = self.as_container_layer().first_child(app);
1436        while let Some(layer) = child {
1437            layer.detach(app);
1438            child = layer.next_sibling(app);
1439        }
1440        // Detach indicates that we may never be composited again. Clients
1441        // interested in observing composition need to get an update here because
1442        // they might otherwise never get another one even though the layer is no
1443        // longer visible.
1444        //
1445        // Children fired them already in child.detach().
1446        self.as_layer().fire_composition_callbacks(app, false);
1447    }
1448
1449    /// `ContainerLayer.redepthChildren`.
1450    fn redepth_children(self: Handle<Self>, app: &mut App) {
1451        let this = self.as_container_layer();
1452        let mut child = this.first_child(app);
1453        while let Some(layer) = child {
1454            this.redepth_child(app, layer);
1455            child = layer.next_sibling(app);
1456        }
1457    }
1458
1459    /// `ContainerLayer.addToScene`.
1460    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1461        self.as_container_layer()
1462            .add_children_to_scene(app, builder);
1463    }
1464}
1465
1466/// The vtable of an [`AnyContainerLayer`]: the layer vtable plus the container accessors.
1467///
1468/// Public only so [`layer_accessors!`] can name it from another crate.
1469#[doc(hidden)]
1470pub struct ContainerLayerVTable {
1471    layer: LayerVTable,
1472    container_data: fn(&App, HandleId) -> &ContainerLayerData,
1473    container_data_mut: fn(&mut App, HandleId) -> &mut ContainerLayerData,
1474    apply_transform: fn(&App, HandleId, Option<AnyLayer>, &mut Matrix4),
1475    as_offset: Option<fn() -> &'static OffsetLayerVTable>,
1476}
1477
1478impl ContainerLayerVTable {
1479    pub const fn of<T: ContainerLayer>() -> ContainerLayerVTable {
1480        ContainerLayerVTable {
1481            layer: LayerVTable::of::<T>(),
1482            container_data: |app, id| T::container_layer_data(resolve(id), app),
1483            container_data_mut: |app, id| T::container_layer_data_mut(resolve(id), app),
1484            apply_transform: |app, id, child, transform| {
1485                T::apply_transform(resolve(id), app, child, transform)
1486            },
1487            as_offset: T::AS_OFFSET,
1488        }
1489    }
1490}
1491
1492/// Erased `ContainerLayer`.
1493#[derive(Clone, Copy)]
1494pub struct AnyContainerLayer {
1495    id: HandleId,
1496    vtable: &'static ContainerLayerVTable,
1497}
1498
1499impl PartialEq for AnyContainerLayer {
1500    fn eq(&self, other: &AnyContainerLayer) -> bool {
1501        self.id == other.id
1502    }
1503}
1504
1505impl Eq for AnyContainerLayer {}
1506
1507impl Hash for AnyContainerLayer {
1508    fn hash<H: Hasher>(&self, state: &mut H) {
1509        self.id.hash(state);
1510    }
1511}
1512
1513impl From<AnyContainerLayer> for HandleId {
1514    fn from(layer: AnyContainerLayer) -> HandleId {
1515        layer.id
1516    }
1517}
1518
1519impl Debug for AnyContainerLayer {
1520    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1521        write!(f, "AnyContainerLayer({:?})", self.id)
1522    }
1523}
1524
1525impl ErasedLayer for AnyContainerLayer {
1526    fn as_layer(self) -> AnyLayer {
1527        AnyLayer {
1528            id: self.id,
1529            vtable: &self.vtable.layer,
1530        }
1531    }
1532}
1533
1534impl AnyContainerLayer {
1535    fn from_vtable(id: HandleId, vtable: &'static ContainerLayerVTable) -> AnyContainerLayer {
1536        AnyContainerLayer { id, vtable }
1537    }
1538
1539    pub fn id(self) -> HandleId {
1540        self.id
1541    }
1542
1543    /// Dart's `layer as OffsetLayer`, as an `Option`.
1544    pub fn as_offset_layer(self) -> Option<AnyOffsetLayer> {
1545        self.vtable
1546            .as_offset
1547            .map(|vtable| AnyOffsetLayer::from_vtable(self.id, vtable()))
1548    }
1549
1550    fn data(self, app: &App) -> &ContainerLayerData {
1551        (self.vtable.container_data)(app, self.id)
1552    }
1553
1554    fn data_mut(self, app: &mut App) -> &mut ContainerLayerData {
1555        (self.vtable.container_data_mut)(app, self.id)
1556    }
1557
1558    /// The first composited layer in this layer's child list.
1559    pub fn first_child(self, app: &App) -> Option<AnyLayer> {
1560        self.data(app).first_child
1561    }
1562
1563    /// The last composited layer in this layer's child list.
1564    pub fn last_child(self, app: &App) -> Option<AnyLayer> {
1565        self.data(app).last_child
1566    }
1567
1568    /// Returns whether this layer has at least one child layer.
1569    pub fn has_children(self, app: &App) -> bool {
1570        self.data(app).first_child.is_some()
1571    }
1572
1573    /// Consider this layer as the root and build a scene (a tree of layers) in the engine.
1574    // The reason this method is in the `ContainerLayer` class rather than
1575    // `PipelineOwner` or other singleton level is because this method can be used
1576    // both to render the whole layer tree (e.g. a normal application frame) and
1577    // to render a subtree (e.g. `OffsetLayer.toImage`).
1578    pub fn build_scene(self, app: &mut App, mut builder: SceneBuilder) -> Scene {
1579        let this = self.as_layer();
1580        this.update_subtree_needs_add_to_scene(app);
1581        this.add_to_scene(app, &mut builder);
1582        if this.subtree_has_composition_callbacks(app) {
1583            this.fire_composition_callbacks(app, true);
1584        }
1585        // Clearing the flag after `add_to_scene`, not before: it calls the children's, which
1586        // may mark this layer.
1587        this.data_mut(app).needs_add_to_scene = false;
1588        builder.build()
1589    }
1590
1591    fn debug_ultimate_previous_sibling_of(
1592        self,
1593        app: &App,
1594        mut child: AnyLayer,
1595        equals: Option<AnyLayer>,
1596    ) -> bool {
1597        let attached = self.as_layer().attached(app);
1598        debug_assert!(child.attached(app) == attached);
1599        while let Some(previous) = child.previous_sibling(app) {
1600            debug_assert!(previous != child);
1601            child = previous;
1602            debug_assert!(child.attached(app) == attached);
1603        }
1604        Some(child) == equals
1605    }
1606
1607    fn debug_ultimate_next_sibling_of(
1608        self,
1609        app: &App,
1610        mut child: AnyLayer,
1611        equals: Option<AnyLayer>,
1612    ) -> bool {
1613        let attached = self.as_layer().attached(app);
1614        debug_assert!(child.attached(app) == attached);
1615        while let Some(next) = child.next_sibling(app) {
1616            debug_assert!(next != child);
1617            child = next;
1618            debug_assert!(child.attached(app) == attached);
1619        }
1620        Some(child) == equals
1621    }
1622
1623    /// Adds the given layer to the end of this layer's child list.
1624    pub fn append(self, app: &mut App, child: AnyLayer) {
1625        let this = self.as_layer();
1626        debug_assert!(!this.data(app).debug_mutations_locked);
1627        debug_assert!(child != this);
1628        debug_assert!(Some(child) != self.first_child(app));
1629        debug_assert!(Some(child) != self.last_child(app));
1630        debug_assert!(child.parent(app).is_none());
1631        debug_assert!(!child.attached(app));
1632        debug_assert!(child.next_sibling(app).is_none());
1633        debug_assert!(child.previous_sibling(app).is_none());
1634        debug_assert!(child.data(app).parent_handle.layer().is_none());
1635        debug_assert!(self.debug_root(app) != child); // indicates we are about to create a cycle
1636        self.adopt_child(app, child);
1637        let last_child = self.last_child(app);
1638        child.data_mut(app).previous_sibling = last_child;
1639        if let Some(last_child) = last_child {
1640            last_child.data_mut(app).next_sibling = Some(child);
1641        }
1642        let data = self.data_mut(app);
1643        data.last_child = Some(child);
1644        data.first_child.get_or_insert(child);
1645        LayerHandle::set_layer(
1646            app,
1647            |app| &mut child.data_mut(app).parent_handle,
1648            Some(child),
1649        );
1650        debug_assert!(child.attached(app) == this.attached(app));
1651    }
1652
1653    /// The `assert(() { Layer node = this; while (node.parent != null) … }())` walk of `append`
1654    /// and `_adoptChild`: the root above this layer.
1655    fn debug_root(self, app: &App) -> AnyLayer {
1656        let mut node = self.as_layer();
1657        while let Some(parent) = node.parent(app) {
1658            node = parent.as_layer();
1659        }
1660        node
1661    }
1662
1663    fn adopt_child(self, app: &mut App, child: AnyLayer) {
1664        let this = self.as_layer();
1665        debug_assert!(!this.data(app).debug_mutations_locked);
1666        if !this.always_needs_add_to_scene(app) {
1667            this.mark_needs_add_to_scene(app);
1668        }
1669        let callback_count = child.data(app).composition_callback_count;
1670        if callback_count != 0 {
1671            this.update_subtree_composition_observer_count(app, callback_count);
1672        }
1673        debug_assert!(child.data(app).parent.is_none());
1674        debug_assert!(self.debug_root(app) != child); // indicates we are about to create a cycle
1675        child.data_mut(app).parent = Some(self);
1676        if let Some(owner) = this.owner(app) {
1677            child.attach(app, owner);
1678        }
1679        self.redepth_child(app, child);
1680    }
1681
1682    /// Adjust the depth of the given `child` to be greater than this node's own depth.
1683    ///
1684    /// Only call this method from overrides of [`Layer::redepth_children`].
1685    pub fn redepth_child(self, app: &mut App, child: AnyLayer) {
1686        let this = self.as_layer();
1687        debug_assert!(child.owner(app) == this.owner(app));
1688        let depth = this.depth(app);
1689        if child.depth(app) <= depth {
1690            child.data_mut(app).depth = depth + 1;
1691            child.redepth_children(app);
1692        }
1693    }
1694
1695    // Implementation of [Layer.remove].
1696    pub(crate) fn remove_child(self, app: &mut App, child: AnyLayer) {
1697        let this = self.as_layer();
1698        debug_assert!(child.parent(app) == Some(self));
1699        debug_assert!(child.attached(app) == this.attached(app));
1700        debug_assert!(self.debug_ultimate_previous_sibling_of(app, child, self.first_child(app)));
1701        debug_assert!(self.debug_ultimate_next_sibling_of(app, child, self.last_child(app)));
1702        debug_assert!(child.data(app).parent_handle.layer().is_some());
1703        let previous_sibling = child.previous_sibling(app);
1704        let next_sibling = child.next_sibling(app);
1705        match previous_sibling {
1706            None => {
1707                debug_assert!(self.first_child(app) == Some(child));
1708                self.data_mut(app).first_child = next_sibling;
1709            }
1710            Some(previous) => previous.data_mut(app).next_sibling = next_sibling,
1711        }
1712        match next_sibling {
1713            None => {
1714                debug_assert!(self.last_child(app) == Some(child));
1715                self.data_mut(app).last_child = previous_sibling;
1716            }
1717            Some(next) => next.data_mut(app).previous_sibling = previous_sibling,
1718        }
1719        self.debug_check_child_list(app);
1720        let data = child.data_mut(app);
1721        data.previous_sibling = None;
1722        data.next_sibling = None;
1723        self.drop_child(app, child);
1724        LayerHandle::set_layer(app, |app| &mut child.data_mut(app).parent_handle, None);
1725        // The release may have disposed the child; a disposed layer is detached.
1726        debug_assert!(child.debug_disposed(app) || !child.attached(app));
1727    }
1728
1729    /// The asserts of `_removeChild` after the unlink: the list is consistent end to end.
1730    fn debug_check_child_list(self, app: &App) {
1731        let attached = self.as_layer().attached(app);
1732        let first_child = self.first_child(app);
1733        let last_child = self.last_child(app);
1734        debug_assert!(first_child.is_none() == last_child.is_none());
1735        debug_assert!(first_child.is_none_or(|first| first.attached(app) == attached));
1736        debug_assert!(last_child.is_none_or(|last| last.attached(app) == attached));
1737        debug_assert!(
1738            first_child
1739                .is_none_or(|first| self.debug_ultimate_next_sibling_of(app, first, last_child))
1740        );
1741        debug_assert!(
1742            last_child.is_none_or(|last| self.debug_ultimate_previous_sibling_of(
1743                app,
1744                last,
1745                first_child
1746            ))
1747        );
1748    }
1749
1750    fn drop_child(self, app: &mut App, child: AnyLayer) {
1751        let this = self.as_layer();
1752        debug_assert!(!this.data(app).debug_mutations_locked);
1753        if !this.always_needs_add_to_scene(app) {
1754            this.mark_needs_add_to_scene(app);
1755        }
1756        let callback_count = child.data(app).composition_callback_count;
1757        if callback_count != 0 {
1758            this.update_subtree_composition_observer_count(app, -callback_count);
1759        }
1760        debug_assert!(child.data(app).parent == Some(self));
1761        debug_assert!(child.attached(app) == this.attached(app));
1762        child.data_mut(app).parent = None;
1763        if this.attached(app) {
1764            child.detach(app);
1765        }
1766    }
1767
1768    /// Removes all of this layer's children from its child list.
1769    pub fn remove_all_children(self, app: &mut App) {
1770        let this = self.as_layer();
1771        debug_assert!(!this.data(app).debug_mutations_locked);
1772        let mut child = self.first_child(app);
1773        while let Some(layer) = child {
1774            let next = layer.next_sibling(app);
1775            let data = layer.data_mut(app);
1776            data.previous_sibling = None;
1777            data.next_sibling = None;
1778            debug_assert!(layer.attached(app) == this.attached(app));
1779            self.drop_child(app, layer);
1780            LayerHandle::set_layer(app, |app| &mut layer.data_mut(app).parent_handle, None);
1781            child = next;
1782        }
1783        let data = self.data_mut(app);
1784        data.first_child = None;
1785        data.last_child = None;
1786    }
1787
1788    /// Uploads all of this layer's children to the engine.
1789    ///
1790    /// This method is typically used by `add_to_scene` to insert the children into the scene.
1791    /// Subclasses of [`ContainerLayer`] typically override `add_to_scene` to apply effects to
1792    /// the scene using the [`SceneBuilder`] API, then insert their children using
1793    /// `add_children_to_scene`, then reverse the aforementioned effects before returning from
1794    /// `add_to_scene`.
1795    pub fn add_children_to_scene(self, app: &mut App, builder: &mut SceneBuilder) {
1796        let mut child = self.first_child(app);
1797        while let Some(layer) = child {
1798            layer.add_to_scene_with_retained_rendering(app, builder);
1799            child = layer.next_sibling(app);
1800        }
1801    }
1802
1803    /// See [`ContainerLayer::apply_transform`].
1804    pub fn apply_transform(self, app: &App, child: Option<AnyLayer>, transform: &mut Matrix4) {
1805        (self.vtable.apply_transform)(app, self.id, child, transform);
1806    }
1807
1808    /// Returns the descendants of this layer in depth first order.
1809    pub fn depth_first_iterate_children(self, app: &App) -> Vec<AnyLayer> {
1810        let mut children = Vec::new();
1811        let mut child = self.first_child(app);
1812        while let Some(layer) = child {
1813            children.push(layer);
1814            if let Some(container) = layer.as_container_layer() {
1815                children.extend(container.depth_first_iterate_children(app));
1816            }
1817            child = layer.next_sibling(app);
1818        }
1819        children
1820    }
1821}
1822
1823/// Flutter's `OffsetLayer` fields, held under the field `offset_layer`
1824/// ([`offset_layer_accessors!`]).
1825#[derive(Debug)]
1826pub struct OffsetLayerData {
1827    offset: Offset,
1828}
1829
1830impl OffsetLayerData {
1831    /// Flutter's `OffsetLayer({offset})`.
1832    pub const fn new(offset: Offset) -> OffsetLayerData {
1833        OffsetLayerData { offset }
1834    }
1835}
1836
1837impl Default for OffsetLayerData {
1838    /// Flutter's `OffsetLayer()`: `offset` is zero.
1839    fn default() -> OffsetLayerData {
1840        OffsetLayerData::new(Offset::ZERO)
1841    }
1842}
1843
1844/// Implements the [`OffsetLayerMixin`] field accessors for an `offset_layer` field.
1845#[macro_export]
1846macro_rules! offset_layer_accessors {
1847    () => {
1848        fn offset_layer_data(
1849            self: ::waft_foundation::Handle<Self>,
1850            app: &::waft_foundation::App,
1851        ) -> &$crate::OffsetLayerData {
1852            &app.get(self).offset_layer
1853        }
1854        fn offset_layer_data_mut(
1855            self: ::waft_foundation::Handle<Self>,
1856            app: &mut ::waft_foundation::App,
1857        ) -> &mut $crate::OffsetLayerData {
1858            &mut app.get_mut(self).offset_layer
1859        }
1860    };
1861}
1862
1863/// A layer that is displayed at an offset from its parent layer.
1864///
1865/// Offset layers are key to efficient repainting because they are created by repaint boundaries
1866/// in the `RenderObject` tree (see `RenderObject.isRepaintBoundary`). When a render object that
1867/// is a repaint boundary is asked to paint at given offset in a `PaintingContext`, the render
1868/// object first checks whether it needs to repaint itself. If not, it reuses its existing
1869/// [`OffsetLayer`] (and its entire subtree) by mutating its offset property, cutting off the
1870/// paint walk.
1871///
1872/// Flutter's `OffsetLayer` is a concrete class that `TransformLayer`, `OpacityLayer` and
1873/// `ImageFilterLayer` extend: the bodies are here, [`OffsetLayer`] is the concrete leaf.
1874pub trait OffsetLayerMixin: ContainerLayer {
1875    /// Mixin field access.
1876    fn offset_layer_data(self: Handle<Self>, app: &App) -> &OffsetLayerData;
1877
1878    /// See [`offset_layer_data`](Self::offset_layer_data).
1879    fn offset_layer_data_mut(self: Handle<Self>, app: &mut App) -> &mut OffsetLayerData;
1880
1881    /// Dart's implicit upcast of a concrete layer to `OffsetLayer`.
1882    fn as_offset_layer(self: Handle<Self>) -> AnyOffsetLayer {
1883        AnyOffsetLayer {
1884            id: self.id(),
1885            vtable: const { &OffsetLayerVTable::of::<Self>() },
1886        }
1887    }
1888
1889    /// Offset from parent in the parent's coordinate system.
1890    fn offset(self: Handle<Self>, app: &App) -> Offset {
1891        self.offset_layer_data(app).offset
1892    }
1893
1894    /// See [`offset`](Self::offset).
1895    fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
1896        self.offset_layer_data_mut(app).offset = value;
1897    }
1898
1899    /// `OffsetLayer.findAnnotations`.
1900    fn find_annotations(
1901        self: Handle<Self>,
1902        app: &App,
1903        result: &mut AnnotationSearch,
1904        local_position: Offset,
1905        only_first: bool,
1906    ) -> bool {
1907        let offset = self.offset(app);
1908        ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
1909    }
1910
1911    /// `OffsetLayer.applyTransform`.
1912    fn apply_transform(
1913        self: Handle<Self>,
1914        app: &App,
1915        child: Option<AnyLayer>,
1916        transform: &mut Matrix4,
1917    ) {
1918        debug_assert!(child.is_some());
1919        let offset = self.offset(app);
1920        *transform = transform.then(&Matrix4::translation(
1921            offset.dx() as f32,
1922            offset.dy() as f32,
1923        ));
1924    }
1925
1926    /// `OffsetLayer.addToScene`.
1927    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
1928        // Skia has a fast path for concatenating scale/translation only matrices.
1929        // Hence pushing a translation-only transform layer should be fast. For
1930        // retained rendering, we don't want to push the offset down to each leaf
1931        // node. Otherwise, changing an offset layer on the very high level could
1932        // cascade the change to too many leaves.
1933        let offset = self.offset(app);
1934        builder.push_offset(offset.dx(), offset.dy());
1935        self.as_container_layer()
1936            .add_children_to_scene(app, builder);
1937        let engine_layer = builder.pop();
1938        self.as_layer().set_engine_layer(app, Some(engine_layer));
1939    }
1940}
1941
1942/// The vtable of an [`AnyOffsetLayer`]: the container vtable plus the offset accessors.
1943///
1944/// Public only so [`container_layer_accessors!`] can name it from another crate.
1945#[doc(hidden)]
1946pub struct OffsetLayerVTable {
1947    container: ContainerLayerVTable,
1948    offset_data: fn(&App, HandleId) -> &OffsetLayerData,
1949    offset_data_mut: fn(&mut App, HandleId) -> &mut OffsetLayerData,
1950}
1951
1952impl OffsetLayerVTable {
1953    pub const fn of<T: OffsetLayerMixin>() -> OffsetLayerVTable {
1954        OffsetLayerVTable {
1955            container: ContainerLayerVTable::of::<T>(),
1956            offset_data: |app, id| T::offset_layer_data(resolve(id), app),
1957            offset_data_mut: |app, id| T::offset_layer_data_mut(resolve(id), app),
1958        }
1959    }
1960}
1961
1962/// Erased `OffsetLayer`: what `RenderObject.updateCompositedLayer` returns and
1963/// `PaintingContext` positions.
1964#[derive(Clone, Copy)]
1965pub struct AnyOffsetLayer {
1966    id: HandleId,
1967    vtable: &'static OffsetLayerVTable,
1968}
1969
1970impl PartialEq for AnyOffsetLayer {
1971    fn eq(&self, other: &AnyOffsetLayer) -> bool {
1972        self.id == other.id
1973    }
1974}
1975
1976impl Eq for AnyOffsetLayer {}
1977
1978impl Hash for AnyOffsetLayer {
1979    fn hash<H: Hasher>(&self, state: &mut H) {
1980        self.id.hash(state);
1981    }
1982}
1983
1984impl From<AnyOffsetLayer> for HandleId {
1985    fn from(layer: AnyOffsetLayer) -> HandleId {
1986        layer.id
1987    }
1988}
1989
1990impl Debug for AnyOffsetLayer {
1991    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1992        write!(f, "AnyOffsetLayer({:?})", self.id)
1993    }
1994}
1995
1996impl ErasedLayer for AnyOffsetLayer {
1997    fn as_layer(self) -> AnyLayer {
1998        self.as_container_layer().as_layer()
1999    }
2000}
2001
2002impl AnyOffsetLayer {
2003    fn from_vtable(id: HandleId, vtable: &'static OffsetLayerVTable) -> AnyOffsetLayer {
2004        AnyOffsetLayer { id, vtable }
2005    }
2006
2007    pub fn id(self) -> HandleId {
2008        self.id
2009    }
2010
2011    /// The `ContainerLayer` view of this layer. Free: points into the nested table.
2012    pub fn as_container_layer(self) -> AnyContainerLayer {
2013        AnyContainerLayer::from_vtable(self.id, &self.vtable.container)
2014    }
2015
2016    /// See [`OffsetLayerMixin::offset`].
2017    pub fn offset(self, app: &App) -> Offset {
2018        (self.vtable.offset_data)(app, self.id).offset
2019    }
2020
2021    /// See [`OffsetLayerMixin::set_offset`].
2022    pub fn set_offset(self, app: &mut App, value: Offset) {
2023        if value == self.offset(app) {
2024            return;
2025        }
2026        (self.vtable.offset_data_mut)(app, self.id).offset = value;
2027        if !self.as_layer().always_needs_add_to_scene(app) {
2028            self.as_layer().mark_needs_add_to_scene(app);
2029        }
2030    }
2031}
2032
2033/// Flutter's concrete `OffsetLayer`; the bodies are [`OffsetLayerMixin`].
2034pub struct OffsetLayer {
2035    layer: LayerData,
2036    container_layer: ContainerLayerData,
2037    offset_layer: OffsetLayerData,
2038}
2039
2040impl OffsetLayer {
2041    /// Creates an offset layer.
2042    ///
2043    /// By default, `offset` is zero. It must be set before the compositing phase of the pipeline.
2044    pub fn new(app: &mut App, offset: Offset) -> Handle<OffsetLayer> {
2045        app.create(OffsetLayer {
2046            layer: LayerData::new(),
2047            container_layer: ContainerLayerData::new(),
2048            offset_layer: OffsetLayerData::new(offset),
2049        })
2050        .into_tree_node(app)
2051    }
2052}
2053
2054impl Layer for OffsetLayer {
2055    crate::layer_accessors!(container);
2056
2057    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2058        ContainerLayer::supports_rasterization(self, app)
2059    }
2060
2061    fn dispose(self: Handle<Self>, app: &mut App) {
2062        ContainerLayer::dispose(self, app);
2063    }
2064
2065    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2066        ContainerLayer::attach(self, app, owner);
2067    }
2068
2069    fn detach(self: Handle<Self>, app: &mut App) {
2070        ContainerLayer::detach(self, app);
2071    }
2072
2073    fn redepth_children(self: Handle<Self>, app: &mut App) {
2074        ContainerLayer::redepth_children(self, app);
2075    }
2076
2077    fn find_annotations(
2078        self: Handle<Self>,
2079        app: &App,
2080        result: &mut AnnotationSearch,
2081        local_position: Offset,
2082        only_first: bool,
2083    ) -> bool {
2084        OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2085    }
2086
2087    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2088        OffsetLayerMixin::add_to_scene(self, app, builder);
2089    }
2090
2091    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2092        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2093    }
2094}
2095
2096impl ContainerLayer for OffsetLayer {
2097    crate::container_layer_accessors!(offset);
2098
2099    fn apply_transform(
2100        self: Handle<Self>,
2101        app: &App,
2102        child: Option<AnyLayer>,
2103        transform: &mut Matrix4,
2104    ) {
2105        OffsetLayerMixin::apply_transform(self, app, child, transform);
2106    }
2107}
2108
2109impl OffsetLayerMixin for OffsetLayer {
2110    crate::offset_layer_accessors!();
2111}
2112
2113/// A key that identifies a group of backdrop filters that share one backdrop.
2114///
2115/// Every `BackdropFilterLayer` with the same key blurs the scene once, as of the first of
2116/// them, which is what Flutter's `BackdropGroup` trades for the cost of one filter pass.
2117#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2118pub struct BackdropKey(u64);
2119
2120static NEXT_BACKDROP_KEY: AtomicU64 = AtomicU64::new(0);
2121
2122impl BackdropKey {
2123    /// Create a new [`BackdropKey`].
2124    #[expect(
2125        clippy::new_without_default,
2126        reason = "each call creates a distinct key; Default would suggest a neutral value"
2127    )]
2128    pub fn new() -> BackdropKey {
2129        BackdropKey(NEXT_BACKDROP_KEY.fetch_add(1, Ordering::Relaxed))
2130    }
2131
2132    /// dart:ui's `backdropId` for [`SceneBuilder::push_backdrop_filter`].
2133    pub fn id(self) -> u64 {
2134        self.0
2135    }
2136}
2137
2138/// A composite layer that clips its children using a rectangle.
2139///
2140/// When debugging, setting [`debug_disable_clip_layers`](crate::debug::debug_disable_clip_layers)
2141/// to true will cause this layer to be skipped (directly replaced by its children). This can be
2142/// helpful to track down the cause of performance problems.
2143pub struct ClipRectLayer {
2144    layer: LayerData,
2145    container_layer: ContainerLayerData,
2146    clip_rect: Option<Rect>,
2147    clip_behavior: Clip,
2148}
2149
2150impl ClipRectLayer {
2151    /// Creates a layer with a rectangular clip.
2152    ///
2153    /// The [`clip_rect`](Self::clip_rect) argument must not be null before the compositing phase
2154    /// of the pipeline.
2155    ///
2156    /// The [`clip_behavior`](Self::clip_behavior) argument must not be [`Clip::None`].
2157    pub fn new(app: &mut App) -> Handle<ClipRectLayer> {
2158        debug_assert!(Clip::HardEdge != Clip::None);
2159        app.create(ClipRectLayer {
2160            layer: LayerData::new(),
2161            container_layer: ContainerLayerData::new(),
2162            clip_rect: None,
2163            clip_behavior: Clip::HardEdge,
2164        })
2165        .into_tree_node(app)
2166    }
2167
2168    /// The rectangle to clip in the parent's coordinate system.
2169    ///
2170    /// The scene must be explicitly recomposited after this property is changed (as described at
2171    /// [`Layer`]).
2172    pub fn clip_rect(self: Handle<Self>, app: &App) -> Option<Rect> {
2173        app.get(self).clip_rect
2174    }
2175
2176    /// See [`clip_rect`](Self::clip_rect).
2177    pub fn set_clip_rect(self: Handle<Self>, app: &mut App, value: Option<Rect>) {
2178        if value != app.get(self).clip_rect {
2179            app.get_mut(self).clip_rect = value;
2180            self.as_layer().mark_needs_add_to_scene(app);
2181        }
2182    }
2183
2184    /// Controls how to clip.
2185    ///
2186    /// Must not be set to null or [`Clip::None`].
2187    ///
2188    /// Defaults to [`Clip::HardEdge`].
2189    pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2190        app.get(self).clip_behavior
2191    }
2192
2193    /// See [`clip_behavior`](Self::clip_behavior).
2194    pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2195        debug_assert!(value != Clip::None);
2196        if value != app.get(self).clip_behavior {
2197            app.get_mut(self).clip_behavior = value;
2198            self.as_layer().mark_needs_add_to_scene(app);
2199        }
2200    }
2201}
2202
2203impl Layer for ClipRectLayer {
2204    crate::layer_accessors!(container);
2205
2206    fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2207        self.clip_rect(app)
2208    }
2209
2210    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2211        ContainerLayer::supports_rasterization(self, app)
2212    }
2213
2214    fn dispose(self: Handle<Self>, app: &mut App) {
2215        ContainerLayer::dispose(self, app);
2216    }
2217
2218    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2219        ContainerLayer::attach(self, app, owner);
2220    }
2221
2222    fn detach(self: Handle<Self>, app: &mut App) {
2223        ContainerLayer::detach(self, app);
2224    }
2225
2226    fn redepth_children(self: Handle<Self>, app: &mut App) {
2227        ContainerLayer::redepth_children(self, app);
2228    }
2229
2230    fn find_annotations(
2231        self: Handle<Self>,
2232        app: &App,
2233        result: &mut AnnotationSearch,
2234        local_position: Offset,
2235        only_first: bool,
2236    ) -> bool {
2237        if !self
2238            .clip_rect(app)
2239            .expect("clipRect must be set before searching annotations")
2240            .contains(local_position)
2241        {
2242            return false;
2243        }
2244        ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2245    }
2246
2247    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2248        debug_assert!(self.clip_rect(app).is_some());
2249        let mut enabled = true;
2250        if cfg!(debug_assertions) {
2251            enabled = !crate::debug::debug_disable_clip_layers(app);
2252        }
2253        if enabled {
2254            let clip_rect = self
2255                .clip_rect(app)
2256                .expect("clipRect must be set before compositing");
2257            let clip_behavior = self.clip_behavior(app);
2258            builder.push_clip_rect(clip_rect, clip_behavior);
2259        }
2260        self.as_container_layer()
2261            .add_children_to_scene(app, builder);
2262        let engine_layer = enabled.then(|| builder.pop());
2263        self.as_layer().set_engine_layer(app, engine_layer);
2264    }
2265
2266    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2267        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2268    }
2269}
2270
2271impl ContainerLayer for ClipRectLayer {
2272    crate::container_layer_accessors!();
2273}
2274
2275/// A composite layer that clips its children using a rounded rectangle.
2276///
2277/// When debugging, setting [`debug_disable_clip_layers`](crate::debug::debug_disable_clip_layers)
2278/// to true will cause this layer to be skipped (directly replaced by its children). This can be
2279/// helpful to track down the cause of performance problems.
2280pub struct ClipRRectLayer {
2281    layer: LayerData,
2282    container_layer: ContainerLayerData,
2283    clip_rrect: Option<RRect>,
2284    clip_behavior: Clip,
2285}
2286
2287impl ClipRRectLayer {
2288    /// Creates a layer with a rounded-rectangular clip.
2289    ///
2290    /// The [`clip_rrect`](Self::clip_rrect) and [`clip_behavior`](Self::clip_behavior) properties
2291    /// must be non-null before the compositing phase of the pipeline.
2292    pub fn new(app: &mut App) -> Handle<ClipRRectLayer> {
2293        debug_assert!(Clip::AntiAlias != Clip::None);
2294        app.create(ClipRRectLayer {
2295            layer: LayerData::new(),
2296            container_layer: ContainerLayerData::new(),
2297            clip_rrect: None,
2298            clip_behavior: Clip::AntiAlias,
2299        })
2300        .into_tree_node(app)
2301    }
2302
2303    /// The rounded-rect to clip in the parent's coordinate system.
2304    ///
2305    /// The scene must be explicitly recomposited after this property is changed (as described at
2306    /// [`Layer`]).
2307    pub fn clip_rrect(self: Handle<Self>, app: &App) -> Option<RRect> {
2308        app.get(self).clip_rrect
2309    }
2310
2311    /// See [`clip_rrect`](Self::clip_rrect).
2312    pub fn set_clip_rrect(self: Handle<Self>, app: &mut App, value: Option<RRect>) {
2313        if value != app.get(self).clip_rrect {
2314            app.get_mut(self).clip_rrect = value;
2315            self.as_layer().mark_needs_add_to_scene(app);
2316        }
2317    }
2318
2319    /// Controls how to clip.
2320    ///
2321    /// Must not be set to null or [`Clip::None`].
2322    ///
2323    /// Defaults to [`Clip::AntiAlias`].
2324    pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2325        app.get(self).clip_behavior
2326    }
2327
2328    /// See [`clip_behavior`](Self::clip_behavior).
2329    pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2330        debug_assert!(value != Clip::None);
2331        if value != app.get(self).clip_behavior {
2332            app.get_mut(self).clip_behavior = value;
2333            self.as_layer().mark_needs_add_to_scene(app);
2334        }
2335    }
2336}
2337
2338impl Layer for ClipRRectLayer {
2339    crate::layer_accessors!(container);
2340
2341    fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2342        self.clip_rrect(app).map(RRect::outer_rect)
2343    }
2344
2345    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2346        ContainerLayer::supports_rasterization(self, app)
2347    }
2348
2349    fn dispose(self: Handle<Self>, app: &mut App) {
2350        ContainerLayer::dispose(self, app);
2351    }
2352
2353    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2354        ContainerLayer::attach(self, app, owner);
2355    }
2356
2357    fn detach(self: Handle<Self>, app: &mut App) {
2358        ContainerLayer::detach(self, app);
2359    }
2360
2361    fn redepth_children(self: Handle<Self>, app: &mut App) {
2362        ContainerLayer::redepth_children(self, app);
2363    }
2364
2365    fn find_annotations(
2366        self: Handle<Self>,
2367        app: &App,
2368        result: &mut AnnotationSearch,
2369        local_position: Offset,
2370        only_first: bool,
2371    ) -> bool {
2372        if !self
2373            .clip_rrect(app)
2374            .expect("clipRRect must be set before searching annotations")
2375            .contains(local_position)
2376        {
2377            return false;
2378        }
2379        ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2380    }
2381
2382    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2383        debug_assert!(self.clip_rrect(app).is_some());
2384        let mut enabled = true;
2385        if cfg!(debug_assertions) {
2386            enabled = !crate::debug::debug_disable_clip_layers(app);
2387        }
2388        if enabled {
2389            let clip_rrect = self
2390                .clip_rrect(app)
2391                .expect("clipRRect must be set before compositing");
2392            let clip_behavior = self.clip_behavior(app);
2393            builder.push_clip_rrect(clip_rrect, clip_behavior);
2394        }
2395        self.as_container_layer()
2396            .add_children_to_scene(app, builder);
2397        let engine_layer = enabled.then(|| builder.pop());
2398        self.as_layer().set_engine_layer(app, engine_layer);
2399    }
2400
2401    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2402        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2403    }
2404}
2405
2406impl ContainerLayer for ClipRRectLayer {
2407    crate::container_layer_accessors!();
2408}
2409
2410/// A composite layer that clips its children using a path.
2411///
2412/// When debugging, setting [`debug_disable_clip_layers`](crate::debug::debug_disable_clip_layers)
2413/// to true will cause this layer to be skipped (directly replaced by its children). This can be
2414/// helpful to track down the cause of performance problems.
2415pub struct ClipPathLayer {
2416    layer: LayerData,
2417    container_layer: ContainerLayerData,
2418    clip_path: Option<waft_embedder::Path>,
2419    clip_behavior: Clip,
2420}
2421
2422impl ClipPathLayer {
2423    /// Creates a layer with a path-based clip.
2424    ///
2425    /// The [`clip_path`](Self::clip_path) and [`clip_behavior`](Self::clip_behavior) properties
2426    /// must be non-null before the compositing phase of the pipeline.
2427    pub fn new(app: &mut App) -> Handle<ClipPathLayer> {
2428        debug_assert!(Clip::AntiAlias != Clip::None);
2429        app.create(ClipPathLayer {
2430            layer: LayerData::new(),
2431            container_layer: ContainerLayerData::new(),
2432            clip_path: None,
2433            clip_behavior: Clip::AntiAlias,
2434        })
2435        .into_tree_node(app)
2436    }
2437
2438    /// The path to clip in the parent's coordinate system.
2439    ///
2440    /// The scene must be explicitly recomposited after this property is changed (as described at
2441    /// [`Layer`]).
2442    pub fn clip_path(self: Handle<Self>, app: &App) -> Option<&waft_embedder::Path> {
2443        app.get(self).clip_path.as_ref()
2444    }
2445
2446    /// See [`clip_path`](Self::clip_path).
2447    pub fn set_clip_path(self: Handle<Self>, app: &mut App, value: Option<waft_embedder::Path>) {
2448        app.get_mut(self).clip_path = value;
2449        self.as_layer().mark_needs_add_to_scene(app);
2450    }
2451
2452    /// Controls how to clip.
2453    ///
2454    /// Must not be set to null or [`Clip::None`].
2455    ///
2456    /// Defaults to [`Clip::AntiAlias`].
2457    pub fn clip_behavior(self: Handle<Self>, app: &App) -> Clip {
2458        app.get(self).clip_behavior
2459    }
2460
2461    /// See [`clip_behavior`](Self::clip_behavior).
2462    pub fn set_clip_behavior(self: Handle<Self>, app: &mut App, value: Clip) {
2463        debug_assert!(value != Clip::None);
2464        if value != app.get(self).clip_behavior {
2465            app.get_mut(self).clip_behavior = value;
2466            self.as_layer().mark_needs_add_to_scene(app);
2467        }
2468    }
2469}
2470
2471impl Layer for ClipPathLayer {
2472    crate::layer_accessors!(container);
2473
2474    fn describe_clip_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
2475        Some(app.get(self).clip_path.as_ref()?.get_bounds())
2476    }
2477
2478    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2479        ContainerLayer::supports_rasterization(self, app)
2480    }
2481
2482    fn dispose(self: Handle<Self>, app: &mut App) {
2483        ContainerLayer::dispose(self, app);
2484    }
2485
2486    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2487        ContainerLayer::attach(self, app, owner);
2488    }
2489
2490    fn detach(self: Handle<Self>, app: &mut App) {
2491        ContainerLayer::detach(self, app);
2492    }
2493
2494    fn redepth_children(self: Handle<Self>, app: &mut App) {
2495        ContainerLayer::redepth_children(self, app);
2496    }
2497
2498    fn find_annotations(
2499        self: Handle<Self>,
2500        app: &App,
2501        result: &mut AnnotationSearch,
2502        local_position: Offset,
2503        only_first: bool,
2504    ) -> bool {
2505        let path = app
2506            .get(self)
2507            .clip_path
2508            .as_ref()
2509            .expect("clipPath must be set before searching annotations");
2510        if !path.contains(local_position) {
2511            return false;
2512        }
2513        ContainerLayer::find_annotations(self, app, result, local_position, only_first)
2514    }
2515
2516    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2517        debug_assert!(app.get(self).clip_path.is_some());
2518        let mut enabled = true;
2519        if cfg!(debug_assertions) {
2520            enabled = !crate::debug::debug_disable_clip_layers(app);
2521        }
2522        if enabled {
2523            let clip_path = app
2524                .get(self)
2525                .clip_path
2526                .clone()
2527                .expect("clipPath must be set before compositing");
2528            let clip_behavior = self.clip_behavior(app);
2529            builder.push_clip_path(&clip_path, clip_behavior);
2530        }
2531        self.as_container_layer()
2532            .add_children_to_scene(app, builder);
2533        let engine_layer = enabled.then(|| builder.pop());
2534        self.as_layer().set_engine_layer(app, engine_layer);
2535    }
2536
2537    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2538        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2539    }
2540}
2541
2542impl ContainerLayer for ClipPathLayer {
2543    crate::container_layer_accessors!();
2544}
2545
2546/// Dart's `MatrixUtils.transformPoint`.
2547fn transform_point(transform: &Matrix4, point: Offset) -> Offset {
2548    let storage = transform.to_flutter_array();
2549    let x = point.dx();
2550    let y = point.dy();
2551    let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
2552    let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
2553    let rw = storage[3] as f64 * x + storage[7] as f64 * y + storage[15] as f64;
2554    if rw == 1.0 {
2555        Offset::new(rx, ry)
2556    } else {
2557        Offset::new(rx / rw, ry / rw)
2558    }
2559}
2560
2561/// A composite layer that applies an [`ImageFilter`] to its children.
2562pub struct ImageFilterLayer {
2563    layer: LayerData,
2564    container_layer: ContainerLayerData,
2565    offset_layer: OffsetLayerData,
2566    image_filter: Option<ImageFilter>,
2567}
2568
2569impl ImageFilterLayer {
2570    /// Creates a layer that applies an [`ImageFilter`] to its children.
2571    ///
2572    /// The [`image_filter`](Self::image_filter) property must be non-null before the compositing
2573    /// phase of the pipeline.
2574    pub fn new(app: &mut App) -> Handle<ImageFilterLayer> {
2575        app.create(ImageFilterLayer {
2576            layer: LayerData::new(),
2577            container_layer: ContainerLayerData::new(),
2578            offset_layer: OffsetLayerData::new(Offset::ZERO),
2579            image_filter: None,
2580        })
2581        .into_tree_node(app)
2582    }
2583
2584    /// The image filter to apply to children.
2585    ///
2586    /// The scene must be explicitly recomposited after this property is changed (as described at
2587    /// [`Layer`]).
2588    pub fn image_filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
2589        app.get(self).image_filter.as_ref()
2590    }
2591
2592    /// See [`image_filter`](Self::image_filter).
2593    pub fn set_image_filter(self: Handle<Self>, app: &mut App, value: ImageFilter) {
2594        if app.get(self).image_filter.as_ref() != Some(&value) {
2595            app.get_mut(self).image_filter = Some(value);
2596            self.as_layer().mark_needs_add_to_scene(app);
2597        }
2598    }
2599}
2600
2601impl Layer for ImageFilterLayer {
2602    crate::layer_accessors!(container);
2603
2604    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2605        ContainerLayer::supports_rasterization(self, app)
2606    }
2607
2608    fn dispose(self: Handle<Self>, app: &mut App) {
2609        ContainerLayer::dispose(self, app);
2610    }
2611
2612    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2613        ContainerLayer::attach(self, app, owner);
2614    }
2615
2616    fn detach(self: Handle<Self>, app: &mut App) {
2617        ContainerLayer::detach(self, app);
2618    }
2619
2620    fn redepth_children(self: Handle<Self>, app: &mut App) {
2621        ContainerLayer::redepth_children(self, app);
2622    }
2623
2624    fn find_annotations(
2625        self: Handle<Self>,
2626        app: &App,
2627        result: &mut AnnotationSearch,
2628        local_position: Offset,
2629        only_first: bool,
2630    ) -> bool {
2631        OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2632    }
2633
2634    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2635        debug_assert!(self.image_filter(app).is_some());
2636        let image_filter = self
2637            .image_filter(app)
2638            .cloned()
2639            .expect("image_filter must be set before compositing");
2640        let offset = self.offset(app);
2641        builder.push_image_filter(&image_filter, offset);
2642        self.as_container_layer()
2643            .add_children_to_scene(app, builder);
2644        let engine_layer = builder.pop();
2645        self.as_layer().set_engine_layer(app, Some(engine_layer));
2646    }
2647
2648    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2649        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2650    }
2651}
2652
2653impl ContainerLayer for ImageFilterLayer {
2654    crate::container_layer_accessors!(offset);
2655
2656    fn apply_transform(
2657        self: Handle<Self>,
2658        app: &App,
2659        child: Option<AnyLayer>,
2660        transform: &mut Matrix4,
2661    ) {
2662        OffsetLayerMixin::apply_transform(self, app, child, transform);
2663    }
2664}
2665
2666impl OffsetLayerMixin for ImageFilterLayer {
2667    crate::offset_layer_accessors!();
2668}
2669
2670/// A composited layer that applies a given transformation matrix to its children.
2671///
2672/// This class inherits from [`OffsetLayer`] to make it one of the layers that can be used at the
2673/// root of a `RenderObject` hierarchy.
2674pub struct TransformLayer {
2675    layer: LayerData,
2676    container_layer: ContainerLayerData,
2677    offset_layer: OffsetLayerData,
2678    transform: Option<Matrix4>,
2679    last_effective_transform: Option<Matrix4>,
2680    inverted_transform: Cell<Option<Matrix4>>,
2681    inverse_dirty: Cell<bool>,
2682}
2683
2684impl TransformLayer {
2685    /// Creates a transform layer.
2686    ///
2687    /// The [`transform`](Self::transform) and `offset` properties must be non-null before the
2688    /// compositing phase of the pipeline.
2689    pub fn new(app: &mut App) -> Handle<TransformLayer> {
2690        app.create(TransformLayer {
2691            layer: LayerData::new(),
2692            container_layer: ContainerLayerData::new(),
2693            offset_layer: OffsetLayerData::new(Offset::ZERO),
2694            transform: None,
2695            last_effective_transform: None,
2696            inverted_transform: Cell::new(None),
2697            inverse_dirty: Cell::new(true),
2698        })
2699        .into_tree_node(app)
2700    }
2701
2702    /// The matrix to apply.
2703    ///
2704    /// The scene must be explicitly recomposited after this property is changed (as described at
2705    /// [`Layer`]).
2706    ///
2707    /// This transform is applied before `offset`, if both are set.
2708    ///
2709    /// The [`transform`](Self::transform) property must be non-null before the compositing phase
2710    /// of the pipeline.
2711    pub fn transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
2712        app.get(self).transform
2713    }
2714
2715    /// See [`transform`](Self::transform).
2716    pub fn set_transform(self: Handle<Self>, app: &mut App, value: Matrix4) {
2717        debug_assert!(
2718            value
2719                .to_flutter_array()
2720                .iter()
2721                .all(|component| component.is_finite())
2722        );
2723        if app.get(self).transform == Some(value) {
2724            return;
2725        }
2726        app.get_mut(self).transform = Some(value);
2727        app.get(self).inverse_dirty.set(true);
2728        self.as_layer().mark_needs_add_to_scene(app);
2729    }
2730
2731    fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
2732        if app.get(self).inverse_dirty.get() {
2733            let transform = app
2734                .get(self)
2735                .transform
2736                .expect("transform must be set before searching annotations");
2737            app.get(self)
2738                .inverted_transform
2739                .set(remove_perspective_transform(transform).invert());
2740            app.get(self).inverse_dirty.set(false);
2741        }
2742        app.get(self)
2743            .inverted_transform
2744            .get()
2745            .map(|inverted| transform_point(&inverted, local_position))
2746    }
2747}
2748
2749impl Layer for TransformLayer {
2750    crate::layer_accessors!(container);
2751
2752    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2753        ContainerLayer::supports_rasterization(self, app)
2754    }
2755
2756    fn dispose(self: Handle<Self>, app: &mut App) {
2757        ContainerLayer::dispose(self, app);
2758    }
2759
2760    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2761        ContainerLayer::attach(self, app, owner);
2762    }
2763
2764    fn detach(self: Handle<Self>, app: &mut App) {
2765        ContainerLayer::detach(self, app);
2766    }
2767
2768    fn redepth_children(self: Handle<Self>, app: &mut App) {
2769        ContainerLayer::redepth_children(self, app);
2770    }
2771
2772    fn find_annotations(
2773        self: Handle<Self>,
2774        app: &App,
2775        result: &mut AnnotationSearch,
2776        local_position: Offset,
2777        only_first: bool,
2778    ) -> bool {
2779        let Some(transformed_offset) = self.transform_offset(app, local_position) else {
2780            return false;
2781        };
2782        OffsetLayerMixin::find_annotations(self, app, result, transformed_offset, only_first)
2783    }
2784
2785    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2786        debug_assert!(self.transform(app).is_some());
2787        let mut last_effective = self
2788            .transform(app)
2789            .expect("transform must be set before compositing");
2790        let offset = self.offset(app);
2791        if offset != Offset::ZERO {
2792            last_effective =
2793                Matrix4::translation(offset.dx() as f32, offset.dy() as f32).then(&last_effective);
2794        }
2795        app.get_mut(self).last_effective_transform = Some(last_effective);
2796        builder.push_transform(&last_effective);
2797        self.as_container_layer()
2798            .add_children_to_scene(app, builder);
2799        let engine_layer = builder.pop();
2800        self.as_layer().set_engine_layer(app, Some(engine_layer));
2801    }
2802
2803    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2804        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2805    }
2806}
2807
2808impl ContainerLayer for TransformLayer {
2809    crate::container_layer_accessors!(offset);
2810
2811    fn apply_transform(
2812        self: Handle<Self>,
2813        app: &App,
2814        child: Option<AnyLayer>,
2815        transform: &mut Matrix4,
2816    ) {
2817        debug_assert!(child.is_some());
2818        debug_assert!(
2819            app.get(self).last_effective_transform.is_some() || self.transform(app).is_some()
2820        );
2821        let applied = match app.get(self).last_effective_transform {
2822            None => self
2823                .transform(app)
2824                .expect("transform must be set before applyTransform"),
2825            Some(last_effective) => last_effective,
2826        };
2827        *transform = transform.then(&applied);
2828    }
2829}
2830
2831impl OffsetLayerMixin for TransformLayer {
2832    crate::offset_layer_accessors!();
2833}
2834
2835/// A composited layer that makes its children partially transparent.
2836///
2837/// When debugging, setting
2838/// [`debug_disable_opacity_layers`](crate::debug::debug_disable_opacity_layers) to true will
2839/// cause this layer to be skipped (directly replaced by its children). This can be helpful to
2840/// track down the cause of performance problems.
2841///
2842/// Try to avoid an [`OpacityLayer`] with no children. Remove that layer if possible to save some
2843/// tree walks.
2844pub struct OpacityLayer {
2845    layer: LayerData,
2846    container_layer: ContainerLayerData,
2847    offset_layer: OffsetLayerData,
2848    alpha: Option<i32>,
2849}
2850
2851impl OpacityLayer {
2852    /// Creates an opacity layer.
2853    ///
2854    /// The [`alpha`](Self::alpha) property must be non-null before the compositing phase of the
2855    /// pipeline.
2856    pub fn new(app: &mut App) -> Handle<OpacityLayer> {
2857        app.create(OpacityLayer {
2858            layer: LayerData::new(),
2859            container_layer: ContainerLayerData::new(),
2860            offset_layer: OffsetLayerData::new(Offset::ZERO),
2861            alpha: None,
2862        })
2863        .into_tree_node(app)
2864    }
2865
2866    /// The amount to multiply into the alpha channel.
2867    ///
2868    /// The opacity is expressed as an integer from 0 to 255, where 0 is fully transparent and
2869    /// 255 is fully opaque.
2870    ///
2871    /// The scene must be explicitly recomposited after this property is changed (as described at
2872    /// [`Layer`]).
2873    pub fn alpha(self: Handle<Self>, app: &App) -> Option<i32> {
2874        app.get(self).alpha
2875    }
2876
2877    /// See [`alpha`](Self::alpha).
2878    pub fn set_alpha(self: Handle<Self>, app: &mut App, value: i32) {
2879        if app.get(self).alpha != Some(value) {
2880            app.get_mut(self).alpha = Some(value);
2881            self.as_layer().mark_needs_add_to_scene(app);
2882        }
2883    }
2884}
2885
2886impl Layer for OpacityLayer {
2887    crate::layer_accessors!(container);
2888
2889    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
2890        ContainerLayer::supports_rasterization(self, app)
2891    }
2892
2893    fn dispose(self: Handle<Self>, app: &mut App) {
2894        ContainerLayer::dispose(self, app);
2895    }
2896
2897    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
2898        ContainerLayer::attach(self, app, owner);
2899    }
2900
2901    fn detach(self: Handle<Self>, app: &mut App) {
2902        ContainerLayer::detach(self, app);
2903    }
2904
2905    fn redepth_children(self: Handle<Self>, app: &mut App) {
2906        ContainerLayer::redepth_children(self, app);
2907    }
2908
2909    fn find_annotations(
2910        self: Handle<Self>,
2911        app: &App,
2912        result: &mut AnnotationSearch,
2913        local_position: Offset,
2914        only_first: bool,
2915    ) -> bool {
2916        OffsetLayerMixin::find_annotations(self, app, result, local_position, only_first)
2917    }
2918
2919    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
2920        debug_assert!(self.alpha(app).is_some());
2921
2922        // Don't add this layer if there's no child.
2923        let mut enabled = self.as_container_layer().first_child(app).is_some();
2924        if !enabled {
2925            // Ensure the engine layer is disposed.
2926            self.as_layer().set_engine_layer(app, None);
2927            return;
2928        }
2929
2930        if cfg!(debug_assertions) {
2931            enabled = enabled && !crate::debug::debug_disable_opacity_layers(app);
2932        }
2933
2934        let realized_alpha = self
2935            .alpha(app)
2936            .expect("alpha must be set before compositing");
2937        let offset = self.offset(app);
2938        if enabled && realized_alpha < 255 {
2939            builder.push_opacity(realized_alpha, offset);
2940        } else {
2941            builder.push_offset(offset.dx(), offset.dy());
2942        }
2943        self.as_container_layer()
2944            .add_children_to_scene(app, builder);
2945        let engine_layer = builder.pop();
2946        self.as_layer().set_engine_layer(app, Some(engine_layer));
2947    }
2948
2949    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
2950        ContainerLayer::fire_composition_callbacks(self, app, include_children);
2951    }
2952}
2953
2954impl ContainerLayer for OpacityLayer {
2955    crate::container_layer_accessors!(offset);
2956
2957    fn apply_transform(
2958        self: Handle<Self>,
2959        app: &App,
2960        child: Option<AnyLayer>,
2961        transform: &mut Matrix4,
2962    ) {
2963        OffsetLayerMixin::apply_transform(self, app, child, transform);
2964    }
2965}
2966
2967impl OffsetLayerMixin for OpacityLayer {
2968    crate::offset_layer_accessors!();
2969}
2970
2971/// A composited layer that applies a filter to the existing contents of the scene.
2972pub struct BackdropFilterLayer {
2973    layer: LayerData,
2974    container_layer: ContainerLayerData,
2975    filter: Option<ImageFilter>,
2976    blend_mode: BlendMode,
2977    backdrop_key: Option<BackdropKey>,
2978}
2979
2980impl BackdropFilterLayer {
2981    /// Creates a backdrop filter layer.
2982    ///
2983    /// The [`filter`](Self::filter) property must be non-null before the compositing phase of
2984    /// the pipeline.
2985    ///
2986    /// The [`blend_mode`](Self::blend_mode) property defaults to [`BlendMode::SrcOver`].
2987    pub fn new(app: &mut App) -> Handle<BackdropFilterLayer> {
2988        app.create(BackdropFilterLayer {
2989            layer: LayerData::new(),
2990            container_layer: ContainerLayerData::new(),
2991            filter: None,
2992            blend_mode: BlendMode::SrcOver,
2993            backdrop_key: None,
2994        })
2995        .into_tree_node(app)
2996    }
2997
2998    /// The filter to apply to the existing contents of the scene.
2999    ///
3000    /// The scene must be explicitly recomposited after this property is changed (as described at
3001    /// [`Layer`]).
3002    pub fn filter(self: Handle<Self>, app: &App) -> Option<&ImageFilter> {
3003        app.get(self).filter.as_ref()
3004    }
3005
3006    /// See [`filter`](Self::filter).
3007    pub fn set_filter(self: Handle<Self>, app: &mut App, value: Option<ImageFilter>) {
3008        app.get_mut(self).filter = value;
3009        self.as_layer().mark_needs_add_to_scene(app);
3010    }
3011
3012    /// The blend mode to use to apply the filtered background content onto the background
3013    /// surface.
3014    ///
3015    /// The default value of this property is [`BlendMode::SrcOver`].
3016    ///
3017    /// The scene must be explicitly recomposited after this property is changed (as described at
3018    /// [`Layer`]).
3019    pub fn blend_mode(self: Handle<Self>, app: &App) -> BlendMode {
3020        app.get(self).blend_mode
3021    }
3022
3023    /// See [`blend_mode`](Self::blend_mode).
3024    pub fn set_blend_mode(self: Handle<Self>, app: &mut App, value: BlendMode) {
3025        if value != app.get(self).blend_mode {
3026            app.get_mut(self).blend_mode = value;
3027            self.as_layer().mark_needs_add_to_scene(app);
3028        }
3029    }
3030
3031    /// The backdrop key that identifies the `BackdropGroup` this filter will apply to.
3032    ///
3033    /// The default value for the backdrop key is `None`, meaning that it's not part of a
3034    /// `BackdropGroup`.
3035    ///
3036    /// The scene must be explicitly recomposited after this property is changed (as described at
3037    /// [`Layer`]).
3038    pub fn backdrop_key(self: Handle<Self>, app: &App) -> Option<BackdropKey> {
3039        app.get(self).backdrop_key
3040    }
3041
3042    /// See [`backdrop_key`](Self::backdrop_key).
3043    pub fn set_backdrop_key(self: Handle<Self>, app: &mut App, value: Option<BackdropKey>) {
3044        if value != app.get(self).backdrop_key {
3045            app.get_mut(self).backdrop_key = value;
3046            self.as_layer().mark_needs_add_to_scene(app);
3047        }
3048    }
3049}
3050
3051impl Layer for BackdropFilterLayer {
3052    crate::layer_accessors!(container);
3053
3054    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3055        ContainerLayer::supports_rasterization(self, app)
3056    }
3057
3058    fn dispose(self: Handle<Self>, app: &mut App) {
3059        ContainerLayer::dispose(self, app);
3060    }
3061
3062    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3063        ContainerLayer::attach(self, app, owner);
3064    }
3065
3066    fn detach(self: Handle<Self>, app: &mut App) {
3067        ContainerLayer::detach(self, app);
3068    }
3069
3070    fn redepth_children(self: Handle<Self>, app: &mut App) {
3071        ContainerLayer::redepth_children(self, app);
3072    }
3073
3074    fn find_annotations(
3075        self: Handle<Self>,
3076        app: &App,
3077        result: &mut AnnotationSearch,
3078        local_position: Offset,
3079        only_first: bool,
3080    ) -> bool {
3081        ContainerLayer::find_annotations(self, app, result, local_position, only_first)
3082    }
3083
3084    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3085        debug_assert!(app.get(self).filter.is_some());
3086        let filter = app
3087            .get(self)
3088            .filter
3089            .clone()
3090            .expect("filter must be set before compositing");
3091        let blend_mode = self.blend_mode(app);
3092        let backdrop_id = self.backdrop_key(app).map(BackdropKey::id);
3093        builder.push_backdrop_filter(&filter, blend_mode, backdrop_id);
3094        self.as_container_layer()
3095            .add_children_to_scene(app, builder);
3096        let engine_layer = builder.pop();
3097        self.as_layer().set_engine_layer(app, Some(engine_layer));
3098    }
3099
3100    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3101        ContainerLayer::fire_composition_callbacks(self, app, include_children);
3102    }
3103}
3104
3105impl ContainerLayer for BackdropFilterLayer {
3106    crate::container_layer_accessors!();
3107}
3108
3109/// An object that a [`LeaderLayer`] can register with.
3110///
3111/// An instance of this class should be provided as the [`LeaderLayer::link`] and the
3112/// [`FollowerLayer::link`] properties to cause the [`FollowerLayer`] to follow the
3113/// [`LeaderLayer`].
3114///
3115/// See also:
3116///
3117///  * `CompositedTransformTarget`, the widget that creates a [`LeaderLayer`].
3118///  * `CompositedTransformFollower`, the widget that creates a [`FollowerLayer`].
3119///  * `RenderLeaderLayer` and `RenderFollowerLayer`, the corresponding render objects.
3120pub struct LayerLink {
3121    leader: Option<Handle<LeaderLayer>>,
3122    debug_previous_leaders: Option<HashSet<Handle<LeaderLayer>>>,
3123    debug_leader_check_scheduled: bool,
3124    /// The total size of the content of the connected [`LeaderLayer`].
3125    ///
3126    /// Generally this should be set by the `RenderObject` that paints on the registered
3127    /// [`LeaderLayer`] (for instance a `RenderLeaderLayer` that shares this link with its
3128    /// followers). This size may be outdated before and during layout.
3129    pub leader_size: Option<Size>,
3130}
3131
3132impl LayerLink {
3133    /// Creates a link with no leader.
3134    pub fn new(app: &mut App) -> Ref<LayerLink> {
3135        app.create(LayerLink {
3136            leader: None,
3137            debug_previous_leaders: None,
3138            debug_leader_check_scheduled: false,
3139            leader_size: None,
3140        })
3141    }
3142
3143    /// The [`LeaderLayer`] connected to this link.
3144    pub fn leader(self: Handle<Self>, app: &App) -> Option<Handle<LeaderLayer>> {
3145        app.get(self).leader
3146    }
3147
3148    fn register_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3149        debug_assert_ne!(self.leader(app), Some(leader));
3150        if cfg!(debug_assertions)
3151            && let Some(current) = self.leader(app)
3152        {
3153            let previous = app
3154                .get_mut(self)
3155                .debug_previous_leaders
3156                .get_or_insert_with(HashSet::new);
3157            debug_assert!(previous.insert(current));
3158            self.debug_schedule_leaders_clean_up_check(app);
3159        }
3160        app.get_mut(self).leader = Some(leader);
3161    }
3162
3163    fn unregister_leader(self: Handle<Self>, app: &mut App, leader: Handle<LeaderLayer>) {
3164        if self.leader(app) == Some(leader) {
3165            app.get_mut(self).leader = None;
3166        } else if cfg!(debug_assertions) {
3167            let removed = app
3168                .get_mut(self)
3169                .debug_previous_leaders
3170                .as_mut()
3171                .expect("a replaced leader is tracked")
3172                .remove(&leader);
3173            debug_assert!(removed);
3174        }
3175    }
3176
3177    /// Schedules the check as post frame callback to make sure the `_debugPreviousLeaders` is
3178    /// empty.
3179    fn debug_schedule_leaders_clean_up_check(self: Handle<Self>, app: &mut App) {
3180        debug_assert!(app.get(self).debug_previous_leaders.is_some());
3181        if cfg!(debug_assertions) {
3182            if app.get(self).debug_leader_check_scheduled {
3183                return;
3184            }
3185            app.get_mut(self).debug_leader_check_scheduled = true;
3186            SchedulerBinding::add_post_frame_callback(
3187                app,
3188                FrameCallback::handle_method(self, |this, app, _time_stamp| {
3189                    app.get_mut(this).debug_leader_check_scheduled = false;
3190                    debug_assert!(
3191                        app.get(this)
3192                            .debug_previous_leaders
3193                            .as_ref()
3194                            .expect("a replaced leader is tracked")
3195                            .is_empty()
3196                    );
3197                }),
3198                None,
3199            );
3200        }
3201    }
3202}
3203
3204/// A composited layer that can be followed by a [`FollowerLayer`].
3205///
3206/// This layer collapses the accumulated offset into a transform and passes [`Offset::ZERO`] to
3207/// its child layers in the [`Layer::add_to_scene`] / `add_children_to_scene` methods, so that
3208/// [`ContainerLayer::apply_transform`] will work reliably.
3209pub struct LeaderLayer {
3210    layer: LayerData,
3211    container_layer: ContainerLayerData,
3212    link: Ref<LayerLink>,
3213    offset: Offset,
3214}
3215
3216impl LeaderLayer {
3217    /// Creates a leader layer.
3218    ///
3219    /// The [`link`](Self::link) property must not have been provided to any other [`LeaderLayer`]
3220    /// layers that are attached to the layer tree at the same time.
3221    ///
3222    /// The [`offset`](Self::offset) property must be non-null before the compositing phase of
3223    /// the pipeline.
3224    pub fn new(app: &mut App, link: Ref<LayerLink>) -> Handle<LeaderLayer> {
3225        app.create(LeaderLayer {
3226            layer: LayerData::new(),
3227            container_layer: ContainerLayerData::new(),
3228            link,
3229            offset: Offset::ZERO,
3230        })
3231        .into_tree_node(app)
3232    }
3233
3234    /// The object with which this layer should register.
3235    ///
3236    /// The link will be established when this layer is [`Layer::attach`]ed, and will be cleared
3237    /// when this layer is [`Layer::detach`]ed.
3238    pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3239        app.get(self).link.handle()
3240    }
3241
3242    /// See [`link`](Self::link).
3243    pub fn set_link(self: Handle<Self>, app: &mut App, value: Ref<LayerLink>) {
3244        let current = self.link(app);
3245        if current == value {
3246            return;
3247        }
3248        if self.as_layer().attached(app) {
3249            current.unregister_leader(app, self);
3250            value.register_leader(app, self);
3251        }
3252        app.get_mut(self).link = value;
3253    }
3254
3255    /// Offset from parent in the parent's coordinate system.
3256    ///
3257    /// The scene must be explicitly recomposited after this property is changed (as described at
3258    /// [`Layer`]).
3259    ///
3260    /// The [`offset`](Self::offset) property must be non-null before the compositing phase of
3261    /// the pipeline.
3262    pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3263        app.get(self).offset
3264    }
3265
3266    /// See [`offset`](Self::offset).
3267    pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3268        if value == app.get(self).offset {
3269            return;
3270        }
3271        app.get_mut(self).offset = value;
3272        if !self.as_layer().always_needs_add_to_scene(app) {
3273            self.as_layer().mark_needs_add_to_scene(app);
3274        }
3275    }
3276}
3277
3278impl Layer for LeaderLayer {
3279    crate::layer_accessors!(container);
3280
3281    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3282        ContainerLayer::supports_rasterization(self, app)
3283    }
3284
3285    fn dispose(self: Handle<Self>, app: &mut App) {
3286        ContainerLayer::dispose(self, app);
3287    }
3288
3289    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3290        ContainerLayer::attach(self, app, owner);
3291        let link = self.link(app);
3292        link.register_leader(app, self);
3293    }
3294
3295    fn detach(self: Handle<Self>, app: &mut App) {
3296        let link = self.link(app);
3297        link.unregister_leader(app, self);
3298        ContainerLayer::detach(self, app);
3299    }
3300
3301    fn redepth_children(self: Handle<Self>, app: &mut App) {
3302        ContainerLayer::redepth_children(self, app);
3303    }
3304
3305    fn find_annotations(
3306        self: Handle<Self>,
3307        app: &App,
3308        result: &mut AnnotationSearch,
3309        local_position: Offset,
3310        only_first: bool,
3311    ) -> bool {
3312        let offset = self.offset(app);
3313        ContainerLayer::find_annotations(self, app, result, local_position - offset, only_first)
3314    }
3315
3316    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3317        let offset = self.offset(app);
3318        if offset != Offset::ZERO {
3319            builder.push_transform(&Matrix4::translation(
3320                offset.dx() as f32,
3321                offset.dy() as f32,
3322            ));
3323        }
3324        self.as_container_layer()
3325            .add_children_to_scene(app, builder);
3326        let engine_layer = (offset != Offset::ZERO).then(|| builder.pop());
3327        self.as_layer().set_engine_layer(app, engine_layer);
3328    }
3329
3330    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3331        ContainerLayer::fire_composition_callbacks(self, app, include_children);
3332    }
3333}
3334
3335impl ContainerLayer for LeaderLayer {
3336    crate::container_layer_accessors!();
3337
3338    /// Applies the transform that would be applied when compositing the given child to the given
3339    /// matrix.
3340    ///
3341    /// See [`ContainerLayer::apply_transform`] for details.
3342    ///
3343    /// The `child` argument may be null, as the same transform is applied to all children.
3344    fn apply_transform(
3345        self: Handle<Self>,
3346        app: &App,
3347        _child: Option<AnyLayer>,
3348        transform: &mut Matrix4,
3349    ) {
3350        let offset = self.offset(app);
3351        if offset != Offset::ZERO {
3352            *transform = transform.then(&Matrix4::translation(
3353                offset.dx() as f32,
3354                offset.dy() as f32,
3355            ));
3356        }
3357    }
3358}
3359
3360/// A composited layer that applies a transformation matrix to its children such that they are
3361/// positioned to match a [`LeaderLayer`].
3362///
3363/// If any of the ancestors of this layer have a degenerate matrix (e.g. scaling by zero), then
3364/// the [`FollowerLayer`] will not be able to transform its child to the coordinate space of the
3365/// [`LeaderLayer`].
3366///
3367/// A [`linked_offset`](FollowerLayer::linked_offset) property can be provided to further offset
3368/// the child layer from the leader layer, for example if the child is to follow the linked layer
3369/// at a distance rather than directly overlapping it.
3370pub struct FollowerLayer {
3371    layer: LayerData,
3372    container_layer: ContainerLayerData,
3373    link: Ref<LayerLink>,
3374    show_when_unlinked: bool,
3375    unlinked_offset: Offset,
3376    linked_offset: Offset,
3377    last_offset: Option<Offset>,
3378    last_transform: Option<Matrix4>,
3379    inverted_transform: Cell<Option<Matrix4>>,
3380    inverse_dirty: Cell<bool>,
3381}
3382
3383impl FollowerLayer {
3384    /// Creates a follower layer.
3385    ///
3386    /// The [`unlinked_offset`](Self::unlinked_offset), [`linked_offset`](Self::linked_offset),
3387    /// and [`show_when_unlinked`](Self::show_when_unlinked) properties must be non-null before
3388    /// the compositing phase of the pipeline.
3389    pub fn new(app: &mut App, link: Ref<LayerLink>) -> Handle<FollowerLayer> {
3390        app.create(FollowerLayer {
3391            layer: LayerData::new(),
3392            container_layer: ContainerLayerData::new(),
3393            link,
3394            show_when_unlinked: true,
3395            unlinked_offset: Offset::ZERO,
3396            linked_offset: Offset::ZERO,
3397            last_offset: None,
3398            last_transform: None,
3399            inverted_transform: Cell::new(None),
3400            inverse_dirty: Cell::new(true),
3401        })
3402        .into_tree_node(app)
3403    }
3404
3405    /// The link to the [`LeaderLayer`].
3406    ///
3407    /// The same object should be provided to a [`LeaderLayer`] that is earlier in the layer
3408    /// tree. When this layer is composited, it will apply a transform that moves its children
3409    /// to match the position of the [`LeaderLayer`].
3410    pub fn link(self: Handle<Self>, app: &App) -> Handle<LayerLink> {
3411        app.get(self).link.handle()
3412    }
3413
3414    /// See [`link`](Self::link).
3415    pub fn set_link(self: Handle<Self>, app: &mut App, value: Ref<LayerLink>) {
3416        if self.link(app) == value {
3417            return;
3418        }
3419        app.get_mut(self).link = value;
3420    }
3421
3422    /// Whether to show the layer's contents when the [`link`](Self::link) does not point to a
3423    /// [`LeaderLayer`].
3424    ///
3425    /// When the layer is linked, children layers are positioned such that they have the same
3426    /// global position as the linked [`LeaderLayer`].
3427    ///
3428    /// When the layer is not linked, then: if [`show_when_unlinked`](Self::show_when_unlinked)
3429    /// is true, children are positioned as if the [`FollowerLayer`] was a [`ContainerLayer`];
3430    /// if it is false, then children are hidden.
3431    ///
3432    /// The [`show_when_unlinked`](Self::show_when_unlinked) property must be non-null before the
3433    /// compositing phase of the pipeline.
3434    pub fn show_when_unlinked(self: Handle<Self>, app: &App) -> bool {
3435        app.get(self).show_when_unlinked
3436    }
3437
3438    /// See [`show_when_unlinked`](Self::show_when_unlinked).
3439    pub fn set_show_when_unlinked(self: Handle<Self>, app: &mut App, value: bool) {
3440        app.get_mut(self).show_when_unlinked = value;
3441    }
3442
3443    /// Offset from parent in the parent's coordinate system, used when the layer is not linked
3444    /// to a [`LeaderLayer`].
3445    ///
3446    /// The scene must be explicitly recomposited after this property is changed (as described at
3447    /// [`Layer`]).
3448    ///
3449    /// The [`unlinked_offset`](Self::unlinked_offset) property must be non-null before the
3450    /// compositing phase of the pipeline.
3451    ///
3452    /// See also:
3453    ///
3454    ///  * [`linked_offset`](Self::linked_offset), for when the layers are linked.
3455    pub fn unlinked_offset(self: Handle<Self>, app: &App) -> Offset {
3456        app.get(self).unlinked_offset
3457    }
3458
3459    /// See [`unlinked_offset`](Self::unlinked_offset).
3460    pub fn set_unlinked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3461        app.get_mut(self).unlinked_offset = value;
3462    }
3463
3464    /// Offset from the origin of the leader layer to the origin of the child layers, used when
3465    /// the layer is linked to a [`LeaderLayer`].
3466    ///
3467    /// The scene must be explicitly recomposited after this property is changed (as described at
3468    /// [`Layer`]).
3469    ///
3470    /// The [`linked_offset`](Self::linked_offset) property must be non-null before the
3471    /// compositing phase of the pipeline.
3472    ///
3473    /// See also:
3474    ///
3475    ///  * [`unlinked_offset`](Self::unlinked_offset), for when the layer is not linked.
3476    pub fn linked_offset(self: Handle<Self>, app: &App) -> Offset {
3477        app.get(self).linked_offset
3478    }
3479
3480    /// See [`linked_offset`](Self::linked_offset).
3481    pub fn set_linked_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3482        app.get_mut(self).linked_offset = value;
3483    }
3484
3485    fn transform_offset(self: Handle<Self>, app: &App, local_position: Offset) -> Option<Offset> {
3486        if app.get(self).inverse_dirty.get() {
3487            let last = self.get_last_transform(app).expect(
3488                "FollowerLayer._transformOffset requires getLastTransform after addToScene",
3489            );
3490            app.get(self).inverted_transform.set(last.invert());
3491            app.get(self).inverse_dirty.set(false);
3492        }
3493        let inverted = app.get(self).inverted_transform.get()?;
3494        let storage = inverted.to_flutter_array();
3495        let x = local_position.dx();
3496        let y = local_position.dy();
3497        let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
3498        let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
3499        let linked_offset = self.linked_offset(app);
3500        Some(Offset::new(
3501            rx - linked_offset.dx(),
3502            ry - linked_offset.dy(),
3503        ))
3504    }
3505
3506    /// The transform that was used during the last composition phase.
3507    ///
3508    /// If the [`link`](Self::link) was not linked to a [`LeaderLayer`], or if this layer has a
3509    /// degenerate matrix applied, then this will be `None`.
3510    ///
3511    /// This method returns a new [`Matrix4`] instance each time it is invoked.
3512    pub fn get_last_transform(self: Handle<Self>, app: &App) -> Option<Matrix4> {
3513        let last_transform = app.get(self).last_transform?;
3514        let last_offset = app
3515            .get(self)
3516            .last_offset
3517            .expect("lastOffset is set with lastTransform");
3518        Some(
3519            Matrix4::translation(-last_offset.dx() as f32, -last_offset.dy() as f32)
3520                .then(&last_transform),
3521        )
3522    }
3523
3524    /// Call [`ContainerLayer::apply_transform`] for each layer in the provided list.
3525    ///
3526    /// The list is in reverse order (deepest first). The first layer will be treated as the
3527    /// child of the second, and so forth. The first layer in the list won't have
3528    /// `apply_transform` called on it. The first layer may be null.
3529    fn collect_transform_for_layer_chain(
3530        app: &App,
3531        layers: &[Option<AnyContainerLayer>],
3532    ) -> Matrix4 {
3533        let mut result = Matrix4::IDENTITY;
3534        for index in (1..layers.len()).rev() {
3535            if let Some(layer) = layers[index] {
3536                let child = layers[index - 1].map(AnyContainerLayer::as_layer);
3537                layer.apply_transform(app, child, &mut result);
3538            }
3539        }
3540        result
3541    }
3542
3543    /// Find the common ancestor of two layers `a` and `b` by searching towards the root of the
3544    /// tree, and append each ancestor of `a` or `b` visited along the path to `ancestors_a` and
3545    /// `ancestors_b` respectively.
3546    ///
3547    /// Returns `None` if `a` `b` do not share a common ancestor, in which case the results in
3548    /// `ancestors_a` and `ancestors_b` are undefined.
3549    fn paths_to_common_ancestor(
3550        app: &App,
3551        a: Option<AnyLayer>,
3552        b: Option<AnyLayer>,
3553        ancestors_a: &mut Vec<Option<AnyContainerLayer>>,
3554        ancestors_b: &mut Vec<Option<AnyContainerLayer>>,
3555    ) -> Option<AnyLayer> {
3556        let (a, b) = (a?, b?);
3557        if a == b {
3558            return Some(a);
3559        }
3560        if a.depth(app) < b.depth(app) {
3561            ancestors_b.push(b.parent(app));
3562            return Self::paths_to_common_ancestor(
3563                app,
3564                Some(a),
3565                b.parent(app).map(AnyContainerLayer::as_layer),
3566                ancestors_a,
3567                ancestors_b,
3568            );
3569        } else if a.depth(app) > b.depth(app) {
3570            ancestors_a.push(a.parent(app));
3571            return Self::paths_to_common_ancestor(
3572                app,
3573                a.parent(app).map(AnyContainerLayer::as_layer),
3574                Some(b),
3575                ancestors_a,
3576                ancestors_b,
3577            );
3578        }
3579        ancestors_a.push(a.parent(app));
3580        ancestors_b.push(b.parent(app));
3581        Self::paths_to_common_ancestor(
3582            app,
3583            a.parent(app).map(AnyContainerLayer::as_layer),
3584            b.parent(app).map(AnyContainerLayer::as_layer),
3585            ancestors_a,
3586            ancestors_b,
3587        )
3588    }
3589
3590    fn debug_check_leader_before_follower(
3591        app: &App,
3592        leader_to_common_ancestor: &[Option<AnyContainerLayer>],
3593        follower_to_common_ancestor: &[Option<AnyContainerLayer>],
3594    ) -> bool {
3595        if follower_to_common_ancestor.len() <= 1 {
3596            return false;
3597        }
3598        if leader_to_common_ancestor.len() <= 1 {
3599            return true;
3600        }
3601        let leader_subtree_below_ancestor = leader_to_common_ancestor
3602            [leader_to_common_ancestor.len() - 2]
3603            .expect("the leader subtree below the ancestor is a layer");
3604        let follower_subtree_below_ancestor = follower_to_common_ancestor
3605            [follower_to_common_ancestor.len() - 2]
3606            .expect("the follower subtree below the ancestor is a layer");
3607        let mut sibling = Some(leader_subtree_below_ancestor.as_layer());
3608        while let Some(layer) = sibling {
3609            if layer == follower_subtree_below_ancestor.as_layer() {
3610                return true;
3611            }
3612            sibling = layer.next_sibling(app);
3613        }
3614        false
3615    }
3616
3617    /// Populate `_lastTransform` given the current state of the tree.
3618    fn establish_transform(self: Handle<Self>, app: &mut App) {
3619        app.get_mut(self).last_transform = None;
3620        let Some(leader) = self.link(app).leader(app) else {
3621            return;
3622        };
3623        debug_assert_eq!(
3624            leader.as_layer().owner(app),
3625            self.as_layer().owner(app),
3626            "Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer."
3627        );
3628
3629        let mut forward_layers = vec![Some(leader.as_container_layer())];
3630        let mut inverse_layers = vec![Some(self.as_container_layer())];
3631        let ancestor = Self::paths_to_common_ancestor(
3632            app,
3633            Some(leader.as_layer()),
3634            Some(self.as_layer()),
3635            &mut forward_layers,
3636            &mut inverse_layers,
3637        );
3638        debug_assert!(
3639            ancestor.is_some(),
3640            "LeaderLayer and FollowerLayer do not have a common ancestor."
3641        );
3642        debug_assert!(
3643            Self::debug_check_leader_before_follower(app, &forward_layers, &inverse_layers),
3644            "LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse \
3645             was true."
3646        );
3647
3648        let mut forward_transform = Self::collect_transform_for_layer_chain(app, &forward_layers);
3649        leader
3650            .as_container_layer()
3651            .apply_transform(app, None, &mut forward_transform);
3652        let linked_offset = self.linked_offset(app);
3653        forward_transform = forward_transform.then(&Matrix4::translation(
3654            linked_offset.dx() as f32,
3655            linked_offset.dy() as f32,
3656        ));
3657
3658        let inverse_transform = Self::collect_transform_for_layer_chain(app, &inverse_layers);
3659        let Some(inverse_transform) = inverse_transform.invert() else {
3660            return;
3661        };
3662        app.get_mut(self).last_transform = Some(inverse_transform.then(&forward_transform));
3663        app.get(self).inverse_dirty.set(true);
3664    }
3665}
3666
3667impl Layer for FollowerLayer {
3668    crate::layer_accessors!(container);
3669
3670    /// A [`FollowerLayer`] copies changes from a [`LeaderLayer`] that could be anywhere in the
3671    /// layer tree, and that leader layer could change without notifying the follower layer.
3672    /// Therefore a follower layer's `add_to_scene` is always called.
3673    fn always_needs_add_to_scene(self: Handle<Self>, _app: &App) -> bool {
3674        true
3675    }
3676
3677    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3678        ContainerLayer::supports_rasterization(self, app)
3679    }
3680
3681    fn dispose(self: Handle<Self>, app: &mut App) {
3682        ContainerLayer::dispose(self, app);
3683    }
3684
3685    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3686        ContainerLayer::attach(self, app, owner);
3687    }
3688
3689    fn detach(self: Handle<Self>, app: &mut App) {
3690        ContainerLayer::detach(self, app);
3691    }
3692
3693    fn redepth_children(self: Handle<Self>, app: &mut App) {
3694        ContainerLayer::redepth_children(self, app);
3695    }
3696
3697    fn find_annotations(
3698        self: Handle<Self>,
3699        app: &App,
3700        result: &mut AnnotationSearch,
3701        local_position: Offset,
3702        only_first: bool,
3703    ) -> bool {
3704        if self.link(app).leader(app).is_none() {
3705            if self.show_when_unlinked(app) {
3706                return ContainerLayer::find_annotations(
3707                    self,
3708                    app,
3709                    result,
3710                    local_position - self.unlinked_offset(app),
3711                    only_first,
3712                );
3713            }
3714            return false;
3715        }
3716        let Some(transformed_offset) = self.transform_offset(app, local_position) else {
3717            return false;
3718        };
3719        ContainerLayer::find_annotations(self, app, result, transformed_offset, only_first)
3720    }
3721
3722    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3723        if self.link(app).leader(app).is_none() && !self.show_when_unlinked(app) {
3724            app.get_mut(self).last_transform = None;
3725            app.get_mut(self).last_offset = None;
3726            app.get(self).inverse_dirty.set(true);
3727            self.as_layer().set_engine_layer(app, None);
3728            return;
3729        }
3730        self.establish_transform(app);
3731        if app.get(self).last_transform.is_some() {
3732            let unlinked_offset = self.unlinked_offset(app);
3733            app.get_mut(self).last_offset = Some(unlinked_offset);
3734            let last_transform = app
3735                .get(self)
3736                .last_transform
3737                .expect("lastTransform was just set");
3738            builder.push_transform(&last_transform);
3739            self.as_container_layer()
3740                .add_children_to_scene(app, builder);
3741            let engine_layer = builder.pop();
3742            self.as_layer().set_engine_layer(app, Some(engine_layer));
3743        } else {
3744            app.get_mut(self).last_offset = None;
3745            let unlinked_offset = self.unlinked_offset(app);
3746            let matrix =
3747                Matrix4::translation(unlinked_offset.dx() as f32, unlinked_offset.dy() as f32);
3748            builder.push_transform(&matrix);
3749            self.as_container_layer()
3750                .add_children_to_scene(app, builder);
3751            let engine_layer = builder.pop();
3752            self.as_layer().set_engine_layer(app, Some(engine_layer));
3753        }
3754        app.get(self).inverse_dirty.set(true);
3755    }
3756
3757    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3758        ContainerLayer::fire_composition_callbacks(self, app, include_children);
3759    }
3760}
3761
3762impl ContainerLayer for FollowerLayer {
3763    crate::container_layer_accessors!();
3764
3765    fn apply_transform(
3766        self: Handle<Self>,
3767        app: &App,
3768        child: Option<AnyLayer>,
3769        transform: &mut Matrix4,
3770    ) {
3771        debug_assert!(child.is_some());
3772        if let Some(last_transform) = app.get(self).last_transform {
3773            *transform = transform.then(&last_transform);
3774        } else {
3775            let unlinked_offset = self.unlinked_offset(app);
3776            *transform = transform.then(&Matrix4::translation(
3777                unlinked_offset.dx() as f32,
3778                unlinked_offset.dy() as f32,
3779            ));
3780        }
3781    }
3782}
3783
3784/// A composited layer which annotates its children with a value. Pushing this layer to the tree
3785/// is the common way of adding an annotation.
3786///
3787/// An annotation is an optional object of any type that, when attached with a layer, can be
3788/// retrieved using [`AnyLayer::find`] or [`AnyLayer::find_all_annotations`] with a position. The
3789/// search process is done recursively, controlled by a concept of being opaque to a type of
3790/// annotation, explained in the document of [`Layer::find_annotations`].
3791///
3792/// When an annotation search arrives, this layer defers the same search to each of this layer's
3793/// children, respecting their opacity. Then it adds this layer's annotation if all of the
3794/// following restrictions are met:
3795///
3796/// * The target type must be identical to the annotated type `T`.
3797/// * If [`size`](Self::size) is provided, the target position must be contained within the
3798///   rectangle formed by [`size`](Self::size) and [`offset`](Self::offset).
3799///
3800/// This layer is opaque to a type of annotation if any child is also opaque, or if
3801/// [`opaque`](Self::opaque) is true and the layer's annotation is added.
3802pub struct AnnotatedRegionLayer {
3803    layer: LayerData,
3804    container_layer: ContainerLayerData,
3805    value: Rc<dyn Any>,
3806    size: Option<Size>,
3807    offset: Offset,
3808    opaque: bool,
3809}
3810
3811impl AnnotatedRegionLayer {
3812    /// Creates a new layer that annotates its children with `value`.
3813    pub fn new(app: &mut App, value: Rc<dyn Any>) -> Handle<AnnotatedRegionLayer> {
3814        app.create(AnnotatedRegionLayer {
3815            layer: LayerData::new(),
3816            container_layer: ContainerLayerData::new(),
3817            value,
3818            size: None,
3819            offset: Offset::ZERO,
3820            opaque: false,
3821        })
3822        .into_tree_node(app)
3823    }
3824
3825    /// The annotated object, which is added to the result if all restrictions are met.
3826    pub fn value(self: Handle<Self>, app: &App) -> &Rc<dyn Any> {
3827        &app.get(self).value
3828    }
3829
3830    /// The size of the annotated object.
3831    ///
3832    /// If [`size`](Self::size) is provided, then the annotation is found only if the target
3833    /// position is contained by the rectangle formed by [`size`](Self::size) and
3834    /// [`offset`](Self::offset). Otherwise no such restriction is applied, and clipping can only
3835    /// be done by the ancestor layers.
3836    pub fn size(self: Handle<Self>, app: &App) -> Option<Size> {
3837        app.get(self).size
3838    }
3839
3840    /// See [`size`](Self::size).
3841    pub fn set_size(self: Handle<Self>, app: &mut App, value: Option<Size>) {
3842        app.get_mut(self).size = value;
3843    }
3844
3845    /// The position of the annotated object.
3846    ///
3847    /// The [`offset`](Self::offset) defaults to [`Offset::ZERO`] if not provided, and is ignored
3848    /// if [`size`](Self::size) is not set.
3849    ///
3850    /// The [`offset`](Self::offset) only offsets the clipping rectangle, and does not affect how
3851    /// the painting or annotation search is propagated to its children.
3852    pub fn offset(self: Handle<Self>, app: &App) -> Offset {
3853        app.get(self).offset
3854    }
3855
3856    /// See [`offset`](Self::offset).
3857    pub fn set_offset(self: Handle<Self>, app: &mut App, value: Offset) {
3858        app.get_mut(self).offset = value;
3859    }
3860
3861    /// Whether the annotation of this layer should be opaque during an annotation search of type
3862    /// `T`, preventing siblings visually behind it from being searched.
3863    ///
3864    /// If [`opaque`](Self::opaque) is true, and this layer does add its annotation
3865    /// [`value`](Self::value), then the layer will always be opaque during the search.
3866    ///
3867    /// If [`opaque`](Self::opaque) is false, or if this layer does not add its annotation, then
3868    /// the opacity of this layer will be the one returned by the children, meaning that it will
3869    /// be opaque if any child is opaque.
3870    ///
3871    /// The [`opaque`](Self::opaque) defaults to false.
3872    ///
3873    /// The [`opaque`](Self::opaque) is effectively useless during [`AnyLayer::find`] (more
3874    /// specifically, [`Layer::find_annotations`] with `only_first: true`), since the search
3875    /// process then skips the remaining tree after finding the first annotation.
3876    ///
3877    /// See also:
3878    ///
3879    ///  * [`Layer::find_annotations`], which explains the concept of being opaque to a type of
3880    ///    annotation as the return value.
3881    ///  * `HitTestBehavior`, which controls similar logic when hit-testing in the render tree.
3882    pub fn opaque(self: Handle<Self>, app: &App) -> bool {
3883        app.get(self).opaque
3884    }
3885
3886    /// See [`opaque`](Self::opaque).
3887    pub fn set_opaque(self: Handle<Self>, app: &mut App, value: bool) {
3888        app.get_mut(self).opaque = value;
3889    }
3890}
3891
3892impl Layer for AnnotatedRegionLayer {
3893    crate::layer_accessors!(container);
3894
3895    fn supports_rasterization(self: Handle<Self>, app: &App) -> bool {
3896        ContainerLayer::supports_rasterization(self, app)
3897    }
3898
3899    fn dispose(self: Handle<Self>, app: &mut App) {
3900        ContainerLayer::dispose(self, app);
3901    }
3902
3903    fn attach(self: Handle<Self>, app: &mut App, owner: HandleId) {
3904        ContainerLayer::attach(self, app, owner);
3905    }
3906
3907    fn detach(self: Handle<Self>, app: &mut App) {
3908        ContainerLayer::detach(self, app);
3909    }
3910
3911    fn redepth_children(self: Handle<Self>, app: &mut App) {
3912        ContainerLayer::redepth_children(self, app);
3913    }
3914
3915    /// Searches the subtree for annotations of the searched type at the location `local_position`,
3916    /// then adds the annotation [`value`](Self::value) if applicable.
3917    ///
3918    /// This method always searches its children, and if any child returns `true`, the remaining
3919    /// children are skipped. Regardless of what the children return, this method then adds this
3920    /// layer's annotation if all of the following restrictions are met:
3921    ///
3922    /// * The target type must be identical to the annotated type `T`.
3923    /// * If [`size`](Self::size) is provided, the target position must be contained within the
3924    ///   rectangle formed by [`size`](Self::size) and [`offset`](Self::offset).
3925    ///
3926    /// This search process respects `only_first`, meaning that when `only_first` is true, the
3927    /// search will stop when it finds the first annotation from the children, and the layer's
3928    /// own annotation is checked only when none is given by the children.
3929    ///
3930    /// The return value is true if any child returns `true`, or if [`opaque`](Self::opaque) is
3931    /// true and the layer's annotation is added.
3932    ///
3933    /// For explanation of layer annotations, parameters and return value, refer to
3934    /// [`Layer::find_annotations`].
3935    fn find_annotations(
3936        self: Handle<Self>,
3937        app: &App,
3938        result: &mut AnnotationSearch,
3939        local_position: Offset,
3940        only_first: bool,
3941    ) -> bool {
3942        let mut is_absorbed =
3943            ContainerLayer::find_annotations(self, app, result, local_position, only_first);
3944        if !result.is_empty() && only_first {
3945            return is_absorbed;
3946        }
3947        let (value, size, offset, opaque) = {
3948            let this = app.get(self);
3949            (Rc::clone(&this.value), this.size, this.offset, this.opaque)
3950        };
3951        if let Some(size) = size
3952            && !(offset & size).contains(local_position)
3953        {
3954            return is_absorbed;
3955        }
3956        if result.accepts(&*value) {
3957            is_absorbed = is_absorbed || opaque;
3958            result.add(value, local_position - offset);
3959        }
3960        is_absorbed
3961    }
3962
3963    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
3964        ContainerLayer::add_to_scene(self, app, builder);
3965    }
3966
3967    fn fire_composition_callbacks(self: Handle<Self>, app: &mut App, include_children: bool) {
3968        ContainerLayer::fire_composition_callbacks(self, app, include_children);
3969    }
3970}
3971
3972impl ContainerLayer for AnnotatedRegionLayer {
3973    crate::container_layer_accessors!();
3974}
3975
3976#[cfg(test)]
3977mod tests {
3978    use waft_foundation::AppCell;
3979
3980    use super::*;
3981
3982    fn offset_layer(app: &mut App) -> AnyLayer {
3983        OffsetLayer::new(app, Offset::ZERO).as_layer()
3984    }
3985
3986    #[test]
3987    fn append_links_children_in_order_and_adopts_them() {
3988        let cell = AppCell::new();
3989        let mut app = cell.borrow_mut();
3990        let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
3991        let a = offset_layer(&mut app);
3992        let b = offset_layer(&mut app);
3993        parent.append(&mut app, a);
3994        parent.append(&mut app, b);
3995        assert_eq!(parent.first_child(&app), Some(a));
3996        assert_eq!(parent.last_child(&app), Some(b));
3997        assert_eq!(a.next_sibling(&app), Some(b));
3998        assert_eq!(b.previous_sibling(&app), Some(a));
3999        assert_eq!(a.parent(&app), Some(parent));
4000        assert_eq!(a.depth(&app), 1);
4001        assert_eq!(a.debug_handle_count(&app), 1, "the parent handle");
4002    }
4003
4004    #[test]
4005    fn a_layer_is_disposed_when_its_last_handle_is_released() {
4006        let cell = AppCell::new();
4007        let mut app = cell.borrow_mut();
4008        let layer = offset_layer(&mut app);
4009        let handle = app.create(LayerHandle::<AnyLayer>::new());
4010        LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(layer));
4011        assert_eq!(layer.debug_handle_count(&app), 1);
4012        LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4013        assert!(layer.debug_disposed(&app));
4014        assert!(app.contains(layer.id()), "readable until the checkpoint");
4015        drop(app);
4016        cell.checkpoint();
4017        assert!(
4018            !cell.borrow().contains(layer.id()),
4019            "dispose released the tree's part of the arena entry"
4020        );
4021    }
4022
4023    #[test]
4024    fn removing_a_child_releases_the_parent_handle_and_disposes_it() {
4025        let cell = AppCell::new();
4026        let mut app = cell.borrow_mut();
4027        let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4028        let child = offset_layer(&mut app);
4029        parent.append(&mut app, child);
4030        child.remove(&mut app);
4031        assert!(!parent.has_children(&app));
4032        assert!(child.debug_disposed(&app));
4033    }
4034
4035    #[test]
4036    fn a_child_kept_by_another_handle_survives_removal() {
4037        let cell = AppCell::new();
4038        let mut app = cell.borrow_mut();
4039        let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4040        let child = offset_layer(&mut app);
4041        let handle = app.create(LayerHandle::<AnyLayer>::new());
4042        LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(child));
4043        parent.append(&mut app, child);
4044        child.remove(&mut app);
4045        assert!(!child.debug_disposed(&app));
4046        assert_eq!(child.parent(&app), None);
4047        LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4048        assert!(child.debug_disposed(&app));
4049    }
4050
4051    #[test]
4052    fn attach_and_detach_walk_the_subtree() {
4053        let cell = AppCell::new();
4054        let mut app = cell.borrow_mut();
4055        let owner = app.create(());
4056        let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4057        let child = offset_layer(&mut app);
4058        root.append(&mut app, child);
4059        root.as_layer().attach(&mut app, owner.id());
4060        assert!(child.attached(&app));
4061        let late = offset_layer(&mut app);
4062        root.append(&mut app, late);
4063        assert!(
4064            late.attached(&app),
4065            "appending to an attached tree attaches"
4066        );
4067        root.as_layer().detach(&mut app);
4068        assert!(!child.attached(&app));
4069        assert!(!late.attached(&app));
4070    }
4071
4072    #[test]
4073    fn disposing_a_container_disposes_children_it_alone_held() {
4074        let cell = AppCell::new();
4075        let mut app = cell.borrow_mut();
4076        let parent = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4077        let child = offset_layer(&mut app);
4078        parent.append(&mut app, child);
4079        let handle = app.create(LayerHandle::<AnyContainerLayer>::new());
4080        LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), Some(parent));
4081        LayerHandle::set_layer(&mut app, |app| app.get_mut(&handle), None);
4082        assert!(parent.as_layer().debug_disposed(&app));
4083        assert!(child.debug_disposed(&app));
4084    }
4085
4086    #[test]
4087    fn a_picture_layer_is_a_leaf_that_holds_its_picture() {
4088        let cell = AppCell::new();
4089        let mut app = cell.borrow_mut();
4090        let layer = PictureLayer::new(&mut app, Rect::from_ltwh(0.0, 0.0, 10.0, 10.0));
4091        let picture = Arc::new(waft_embedder::Canvas::new().build());
4092        layer.set_picture(&mut app, Some(picture));
4093        assert!(layer.picture(&app).is_some());
4094        assert!(layer.as_layer().as_container_layer().is_none());
4095        let mut builder = SceneBuilder::new();
4096        layer.as_layer().add_to_scene(&mut app, &mut builder);
4097        let _scene = builder.build();
4098    }
4099
4100    #[test]
4101    fn composition_callbacks_fire_on_build_scene_and_detach() {
4102        use std::cell::Cell;
4103        let cell = AppCell::new();
4104        let mut app = cell.borrow_mut();
4105        let owner = app.create(());
4106        let root = OffsetLayer::new(&mut app, Offset::ZERO).as_container_layer();
4107        let child = offset_layer(&mut app);
4108        root.append(&mut app, child);
4109        let fired = Rc::new(Cell::new(0));
4110        let remove = {
4111            let fired = Rc::clone(&fired);
4112            child
4113                .add_composition_callback(&mut app, Rc::new(move |_, _| fired.set(fired.get() + 1)))
4114        };
4115        assert!(root.as_layer().subtree_has_composition_callbacks(&app));
4116        let _scene = root.build_scene(&mut app, SceneBuilder::new());
4117        assert_eq!(fired.get(), 1);
4118        root.as_layer().attach(&mut app, owner.id());
4119        root.as_layer().detach(&mut app);
4120        assert_eq!(fired.get(), 2, "detach fires once more");
4121        remove(&mut app);
4122        assert!(!root.as_layer().subtree_has_composition_callbacks(&app));
4123    }
4124
4125    #[test]
4126    fn find_walks_children_back_to_front_through_offsets() {
4127        struct Tag(&'static str);
4128        struct Annotated {
4129            layer: LayerData,
4130            tag: Rc<Tag>,
4131        }
4132        impl Layer for Annotated {
4133            crate::layer_accessors!();
4134            fn find_annotations(
4135                self: Handle<Self>,
4136                app: &App,
4137                result: &mut AnnotationSearch,
4138                local_position: Offset,
4139                _only_first: bool,
4140            ) -> bool {
4141                let tag = Rc::clone(&app.get(self).tag);
4142                if result.accepts(&*tag) {
4143                    result.add(tag, local_position);
4144                }
4145                false
4146            }
4147            fn add_to_scene(self: Handle<Self>, _app: &mut App, _builder: &mut SceneBuilder) {}
4148        }
4149        let cell = AppCell::new();
4150        let mut app = cell.borrow_mut();
4151        let root = OffsetLayer::new(&mut app, Offset::new(10.0, 0.0)).as_container_layer();
4152        for name in ["back", "front"] {
4153            let layer = app.create(Annotated {
4154                layer: LayerData::new(),
4155                tag: Rc::new(Tag(name)),
4156            });
4157            root.append(&mut app, layer.as_layer());
4158        }
4159        let found = root.as_layer().find::<Tag>(&app, Offset::new(15.0, 5.0));
4160        assert_eq!(found.map(|tag| tag.0), Some("front"));
4161        let all = root
4162            .as_layer()
4163            .find_all_annotations::<Tag>(&app, Offset::new(15.0, 5.0));
4164        assert_eq!(all.entries().len(), 2);
4165        assert_eq!(all.entries()[0].local_position, Offset::new(5.0, 5.0));
4166        assert!(root.as_layer().find::<String>(&app, Offset::ZERO).is_none());
4167    }
4168
4169    /// An opacity layer over one leaf under a root, with a frame's scene built: the shape
4170    /// retained rendering acts on.
4171    /// A picture layer that draws a square: content a scene keeps, where it
4172    /// drops a subtree that draws nothing.
4173    fn drawn_layer(app: &mut App) -> AnyLayer {
4174        let square = Rect::from_ltwh(0.0, 0.0, 10.0, 10.0);
4175        let mut canvas = waft_embedder::Canvas::new();
4176        canvas.draw_rect(square, &waft_embedder::Paint::default());
4177        let layer = PictureLayer::new(app, square);
4178        layer.set_picture(app, Some(Arc::new(canvas.build())));
4179        layer.as_layer()
4180    }
4181
4182    fn retained_tree(app: &mut App) -> (Handle<OffsetLayer>, Handle<OpacityLayer>) {
4183        let root = OffsetLayer::new(app, Offset::ZERO);
4184        let opacity = OpacityLayer::new(app);
4185        opacity.set_alpha(app, 128);
4186        let leaf = drawn_layer(app);
4187        opacity.as_container_layer().append(app, leaf);
4188        root.as_container_layer().append(app, opacity.as_layer());
4189        let _scene = root
4190            .as_container_layer()
4191            .build_scene(app, SceneBuilder::new());
4192        (root, opacity)
4193    }
4194
4195    /// An embedded layer is retained with its ancestors, as Flutter's `PlatformViewLayer` is:
4196    /// the scene keeps it, and its placement is worked out from the tree every frame.
4197    #[test]
4198    fn an_embedded_layer_is_retained_and_its_composition_layer_placed_every_frame() {
4199        let cell = AppCell::new();
4200        let mut app = cell.borrow_mut();
4201        let root = OffsetLayer::new(&mut app, Offset::new(10.0, 5.0));
4202        let inner = OffsetLayer::new(&mut app, Offset::ZERO);
4203        let composition_layer = waft_embedder::test_support::idle_layer();
4204        let layer = EmbeddedLayer::new(
4205            &mut app,
4206            Arc::clone(&composition_layer),
4207            Rect::from_ltwh(1.0, 2.0, 30.0, 20.0),
4208        );
4209        inner
4210            .as_container_layer()
4211            .append(&mut app, layer.as_layer());
4212        root.as_container_layer().append(&mut app, inner.as_layer());
4213        let mut first_engine_layer = None;
4214        for _frame in 0..2 {
4215            let scene = root
4216                .as_container_layer()
4217                .build_scene(&mut app, SceneBuilder::new());
4218            let slices = waft_embedder::slices(&scene, |_| None);
4219            let (placed, placement) = slices.composition_layers().next().expect("placed");
4220            assert!(Arc::ptr_eq(placed, &composition_layer));
4221            assert_eq!(placement.bounds(), Rect::from_ltwh(11.0, 7.0, 30.0, 20.0));
4222            let engine_layer = inner.as_layer().engine_layer(&app).expect("recorded");
4223            let first = first_engine_layer.get_or_insert_with(|| Arc::clone(&engine_layer));
4224            assert!(Arc::ptr_eq(first, &engine_layer), "retained");
4225        }
4226        assert!(!layer.as_layer().always_needs_add_to_scene(&app));
4227    }
4228
4229    #[test]
4230    fn an_unchanged_subtree_is_retained_across_scenes() {
4231        let cell = AppCell::new();
4232        let mut app = cell.borrow_mut();
4233        let (root, opacity) = retained_tree(&mut app);
4234        let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4235        assert!(!opacity.as_layer().needs_add_to_scene(&app));
4236
4237        let scene = root
4238            .as_container_layer()
4239            .build_scene(&mut app, SceneBuilder::new());
4240        let retained = opacity.as_layer().engine_layer(&app).expect("recorded");
4241        assert!(
4242            Arc::ptr_eq(&recorded, &retained),
4243            "the same node is retained"
4244        );
4245        let root_node = root
4246            .as_layer()
4247            .engine_layer(&app)
4248            .expect("the root is built again");
4249        assert!(
4250            root_node.children.iter().any(|child| matches!(
4251                child,
4252                waft_embedder::Layer::Container(container) if Arc::ptr_eq(container, &retained)
4253            )),
4254            "added again: {:?}",
4255            root_node.children
4256        );
4257        assert_eq!(
4258            waft_embedder::flattened_ops(
4259                &waft_embedder::slices(&scene, |_| None).picture_with_room()
4260            )
4261            .iter()
4262            .filter(|op| matches!(op, waft_embedder::valo::Op::SaveLayer { .. }))
4263            .count(),
4264            1,
4265            "the retained opacity layer still draws"
4266        );
4267    }
4268
4269    #[test]
4270    fn a_changed_property_re_records_the_subtree() {
4271        let cell = AppCell::new();
4272        let mut app = cell.borrow_mut();
4273        let (root, opacity) = retained_tree(&mut app);
4274        let recorded = opacity.as_layer().engine_layer(&app).expect("recorded");
4275
4276        opacity.set_alpha(&mut app, 200);
4277        assert!(opacity.as_layer().needs_add_to_scene(&app));
4278        let _scene = root
4279            .as_container_layer()
4280            .build_scene(&mut app, SceneBuilder::new());
4281        let again = opacity.as_layer().engine_layer(&app).expect("recorded");
4282        assert!(
4283            !Arc::ptr_eq(&recorded, &again),
4284            "a new node for the new alpha"
4285        );
4286        assert!(!opacity.as_layer().needs_add_to_scene(&app));
4287    }
4288
4289    /// Flutter's `ImageFilterLayer.addToScene`: `pushImageFilter` with its filter and offset
4290    /// around its children; an equal filter set again leaves the recorded node retained.
4291    #[test]
4292    fn an_image_filter_layer_pushes_its_filter_at_its_offset() {
4293        let cell = AppCell::new();
4294        let mut app = cell.borrow_mut();
4295        let root = OffsetLayer::new(&mut app, Offset::ZERO);
4296        let filtered = ImageFilterLayer::new(&mut app);
4297        filtered.set_image_filter(&mut app, ImageFilter::blur(4.0, 4.0));
4298        filtered.set_offset(&mut app, Offset::new(3.0, 4.0));
4299        assert!(Layer::supports_rasterization(filtered, &app));
4300        let leaf = drawn_layer(&mut app);
4301        filtered.as_container_layer().append(&mut app, leaf);
4302        root.as_container_layer()
4303            .append(&mut app, filtered.as_layer());
4304        let _scene = root
4305            .as_container_layer()
4306            .build_scene(&mut app, SceneBuilder::new());
4307        let recorded = filtered.as_layer().engine_layer(&app).expect("recorded");
4308        assert_eq!(
4309            recorded.effect,
4310            waft_embedder::Effect::ImageFilter {
4311                filter: ImageFilter::blur(4.0, 4.0),
4312                offset: Offset::new(3.0, 4.0),
4313            }
4314        );
4315        filtered.set_image_filter(&mut app, ImageFilter::blur(4.0, 4.0));
4316        assert!(!filtered.as_layer().needs_add_to_scene(&app));
4317        filtered.set_image_filter(&mut app, ImageFilter::blur(5.0, 5.0));
4318        assert!(filtered.as_layer().needs_add_to_scene(&app));
4319    }
4320
4321    #[test]
4322    fn appending_a_child_marks_the_parent_and_its_ancestors_at_build() {
4323        let cell = AppCell::new();
4324        let mut app = cell.borrow_mut();
4325        let (root, opacity) = retained_tree(&mut app);
4326        assert!(!root.as_layer().needs_add_to_scene(&app));
4327
4328        let leaf = offset_layer(&mut app);
4329        opacity.as_container_layer().append(&mut app, leaf);
4330        assert!(opacity.as_layer().needs_add_to_scene(&app));
4331        assert!(
4332            !root.as_layer().needs_add_to_scene(&app),
4333            "the mark does not climb until the scene is built"
4334        );
4335        root.as_layer().update_subtree_needs_add_to_scene(&mut app);
4336        assert!(root.as_layer().needs_add_to_scene(&app));
4337    }
4338
4339    #[test]
4340    fn a_follower_layer_always_re_records() {
4341        let cell = AppCell::new();
4342        let mut app = cell.borrow_mut();
4343        let link = LayerLink::new(&mut app);
4344        let follower = FollowerLayer::new(&mut app, link);
4345        let child = offset_layer(&mut app);
4346        follower.as_container_layer().append(&mut app, child);
4347        for _ in 0..2 {
4348            let _scene = follower
4349                .as_container_layer()
4350                .build_scene(&mut app, SceneBuilder::new());
4351            assert!(
4352                follower.as_layer().needs_add_to_scene(&app)
4353                    || follower.as_layer().always_needs_add_to_scene(&app)
4354            );
4355        }
4356        let first = follower.as_layer().engine_layer(&app).expect("recorded");
4357        let _scene = follower
4358            .as_container_layer()
4359            .build_scene(&mut app, SceneBuilder::new());
4360        let second = follower.as_layer().engine_layer(&app).expect("recorded");
4361        assert!(!Arc::ptr_eq(&first, &second), "never retained");
4362    }
4363
4364    fn tag(app: &mut App, n: u32) -> Handle<AnnotatedRegionLayer> {
4365        AnnotatedRegionLayer::new(app, Rc::new(n))
4366    }
4367
4368    #[test]
4369    fn clip_layers_reject_annotations_outside_the_clip() {
4370        let cell = AppCell::new();
4371        let mut app = cell.borrow_mut();
4372        let rect = ClipRectLayer::new(&mut app);
4373        rect.set_clip_rect(&mut app, Some(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0)));
4374        let child = tag(&mut app, 7);
4375        rect.as_container_layer().append(&mut app, child.as_layer());
4376        assert_eq!(
4377            rect.as_layer()
4378                .find::<u32>(&app, Offset::new(10.0, 10.0))
4379                .as_deref(),
4380            Some(&7)
4381        );
4382        assert!(
4383            rect.as_layer()
4384                .find::<u32>(&app, Offset::new(60.0, 10.0))
4385                .is_none(),
4386            "outside the clip"
4387        );
4388
4389        let rrect = ClipRRectLayer::new(&mut app);
4390        rrect.set_clip_rrect(
4391            &mut app,
4392            Some(RRect::from_rect_and_radius(
4393                Rect::from_ltwh(0.0, 0.0, 50.0, 50.0),
4394                waft_embedder::Radius::circular(4.0),
4395            )),
4396        );
4397        let child = tag(&mut app, 8);
4398        rrect
4399            .as_container_layer()
4400            .append(&mut app, child.as_layer());
4401        assert_eq!(
4402            rrect
4403                .as_layer()
4404                .find::<u32>(&app, Offset::new(10.0, 10.0))
4405                .as_deref(),
4406            Some(&8)
4407        );
4408        assert!(
4409            rrect
4410                .as_layer()
4411                .find::<u32>(&app, Offset::new(60.0, 10.0))
4412                .is_none()
4413        );
4414
4415        let mut path = waft_embedder::PathBuilder::new();
4416        path.rect(Rect::from_ltwh(0.0, 0.0, 50.0, 50.0).into());
4417        let clip_path = ClipPathLayer::new(&mut app);
4418        clip_path.set_clip_path(&mut app, Some(path.build().into()));
4419        let child = tag(&mut app, 9);
4420        clip_path
4421            .as_container_layer()
4422            .append(&mut app, child.as_layer());
4423        assert_eq!(
4424            clip_path
4425                .as_layer()
4426                .find::<u32>(&app, Offset::new(10.0, 10.0))
4427                .as_deref(),
4428            Some(&9)
4429        );
4430        assert!(
4431            clip_path
4432                .as_layer()
4433                .find::<u32>(&app, Offset::new(60.0, 10.0))
4434                .is_none()
4435        );
4436    }
4437
4438    #[test]
4439    fn transform_layer_transforms_the_annotation_position() {
4440        let cell = AppCell::new();
4441        let mut app = cell.borrow_mut();
4442        let layer = TransformLayer::new(&mut app);
4443        layer.set_transform(&mut app, Matrix4::translation(10.0, 0.0));
4444        let region = tag(&mut app, 7);
4445        region.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4446        layer
4447            .as_container_layer()
4448            .append(&mut app, region.as_layer());
4449        assert!(
4450            layer
4451                .as_layer()
4452                .find::<u32>(&app, Offset::new(15.0, 5.0))
4453                .is_some()
4454        );
4455        assert!(
4456            layer
4457                .as_layer()
4458                .find::<u32>(&app, Offset::new(5.0, 5.0))
4459                .is_none(),
4460            "left of the translated region"
4461        );
4462    }
4463
4464    #[test]
4465    fn opacity_layer_build_scene_succeeds_at_255_and_128() {
4466        let cell = AppCell::new();
4467        let mut app = cell.borrow_mut();
4468        for alpha in [255, 128] {
4469            let layer = OpacityLayer::new(&mut app);
4470            layer.set_alpha(&mut app, alpha);
4471            let child = OffsetLayer::new(&mut app, Offset::ZERO);
4472            layer
4473                .as_container_layer()
4474                .append(&mut app, child.as_layer());
4475            let _scene = layer
4476                .as_container_layer()
4477                .build_scene(&mut app, SceneBuilder::new());
4478        }
4479        let empty = OpacityLayer::new(&mut app);
4480        empty.set_alpha(&mut app, 128);
4481        let _scene = empty
4482            .as_container_layer()
4483            .build_scene(&mut app, SceneBuilder::new());
4484    }
4485
4486    #[test]
4487    fn layer_link_register_unregister_and_leader_getter() {
4488        let cell = AppCell::new();
4489        let mut app = cell.borrow_mut();
4490        let owner = app.create(());
4491        let link = LayerLink::new(&mut app);
4492        assert!(link.leader(&app).is_none());
4493        let leader = LeaderLayer::new(&mut app, link.clone());
4494        leader.as_layer().attach(&mut app, owner.id());
4495        assert_eq!(link.leader(&app), Some(leader));
4496        leader.as_layer().detach(&mut app);
4497        assert!(link.leader(&app).is_none());
4498    }
4499
4500    #[test]
4501    fn leader_layer_attach_registers_and_detach_unregisters() {
4502        let cell = AppCell::new();
4503        let mut app = cell.borrow_mut();
4504        let owner = app.create(());
4505        let root = OffsetLayer::new(&mut app, Offset::ZERO);
4506        let link = LayerLink::new(&mut app);
4507        let leader = LeaderLayer::new(&mut app, link.clone());
4508        root.as_container_layer()
4509            .append(&mut app, leader.as_layer());
4510        root.as_layer().attach(&mut app, owner.id());
4511        assert_eq!(link.leader(&app), Some(leader));
4512        root.as_layer().detach(&mut app);
4513        assert!(link.leader(&app).is_none());
4514    }
4515
4516    #[test]
4517    fn a_replaced_leader_leaves_the_links_new_leader_in_place() {
4518        let cell = AppCell::new();
4519        let mut app = cell.borrow_mut();
4520        let owner = app.create(());
4521        let link = LayerLink::new(&mut app);
4522        let leader1 = LeaderLayer::new(&mut app, link.clone());
4523        let leader2 = LeaderLayer::new(&mut app, link.clone());
4524        leader1.as_layer().attach(&mut app, owner.id());
4525        leader2.as_layer().attach(&mut app, owner.id());
4526        assert_eq!(link.leader(&app), Some(leader2));
4527        leader2.as_layer().detach(&mut app);
4528        leader1.as_layer().detach(&mut app);
4529        assert!(link.leader(&app).is_none());
4530    }
4531
4532    #[test]
4533    fn switching_the_link_of_an_attached_leader_does_not_crash() {
4534        let cell = AppCell::new();
4535        let mut app = cell.borrow_mut();
4536        let owner = app.create(());
4537        let link = LayerLink::new(&mut app);
4538        let leader = LeaderLayer::new(&mut app, link.clone());
4539        leader.as_layer().attach(&mut app, owner.id());
4540        let link2 = LayerLink::new(&mut app);
4541        leader.set_link(&mut app, link2.clone());
4542        leader.as_layer().detach(&mut app);
4543        assert_eq!(leader.link(&app), link2);
4544        assert!(link.leader(&app).is_none());
4545        assert!(link2.leader(&app).is_none());
4546    }
4547
4548    #[test]
4549    fn follower_get_last_transform_after_build_scene_matches_the_leader_offset() {
4550        let cell = AppCell::new();
4551        let mut app = cell.borrow_mut();
4552        let owner = app.create(());
4553        let root = OffsetLayer::new(&mut app, Offset::ZERO);
4554        let link = LayerLink::new(&mut app);
4555        let leader = LeaderLayer::new(&mut app, link.clone());
4556        leader.set_offset(&mut app, Offset::new(10.0, 20.0));
4557        let follower = FollowerLayer::new(&mut app, link);
4558        root.as_container_layer()
4559            .append(&mut app, leader.as_layer());
4560        root.as_container_layer()
4561            .append(&mut app, follower.as_layer());
4562        root.as_layer().attach(&mut app, owner.id());
4563        let _scene = root
4564            .as_container_layer()
4565            .build_scene(&mut app, SceneBuilder::new());
4566        assert_eq!(
4567            follower.get_last_transform(&app).unwrap(),
4568            Matrix4::translation(10.0, 20.0)
4569        );
4570    }
4571
4572    #[test]
4573    fn follower_with_show_when_unlinked_false_pushes_nothing() {
4574        let cell = AppCell::new();
4575        let mut app = cell.borrow_mut();
4576        let link = LayerLink::new(&mut app);
4577        let follower = FollowerLayer::new(&mut app, link);
4578        follower.set_show_when_unlinked(&mut app, false);
4579        let child = offset_layer(&mut app);
4580        follower.as_container_layer().append(&mut app, child);
4581        let _scene = follower
4582            .as_container_layer()
4583            .build_scene(&mut app, SceneBuilder::new());
4584        assert!(follower.get_last_transform(&app).is_none());
4585    }
4586
4587    #[test]
4588    fn annotated_region_layer_find_with_size_offset_and_opaque() {
4589        let cell = AppCell::new();
4590        let mut app = cell.borrow_mut();
4591        let root = OffsetLayer::new(&mut app, Offset::ZERO);
4592        let behind = tag(&mut app, 1);
4593        let front = tag(&mut app, 2);
4594        front.set_opaque(&mut app, true);
4595        root.as_container_layer()
4596            .append(&mut app, behind.as_layer());
4597        root.as_container_layer().append(&mut app, front.as_layer());
4598        let result = root
4599            .as_layer()
4600            .find_all_annotations::<u32>(&app, Offset::ZERO);
4601        assert_eq!(
4602            result
4603                .annotations()
4604                .map(|value| **value)
4605                .collect::<Vec<_>>(),
4606            vec![2],
4607            "an opaque region hides its siblings"
4608        );
4609
4610        let root = OffsetLayer::new(&mut app, Offset::ZERO);
4611        let first = tag(&mut app, 1);
4612        let second = tag(&mut app, 2);
4613        root.as_container_layer().append(&mut app, first.as_layer());
4614        root.as_container_layer()
4615            .append(&mut app, second.as_layer());
4616        let result = root
4617            .as_layer()
4618            .find_all_annotations::<u32>(&app, Offset::ZERO);
4619        assert_eq!(
4620            result
4621                .annotations()
4622                .map(|value| **value)
4623                .collect::<Vec<_>>(),
4624            vec![2, 1],
4625            "front to back when neither is opaque"
4626        );
4627
4628        let sized = tag(&mut app, 3);
4629        sized.set_size(&mut app, Some(Size::new(20.0, 20.0)));
4630        sized.set_offset(&mut app, Offset::new(90.0, 90.0));
4631        assert!(
4632            sized
4633                .as_layer()
4634                .find::<u32>(&app, Offset::new(95.0, 95.0))
4635                .is_some()
4636        );
4637        assert!(
4638            sized.as_layer().find::<u32>(&app, Offset::ZERO).is_none(),
4639            "outside the sized region"
4640        );
4641    }
4642}