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