Skip to main content

waft_rendering/
object.rs

1//! Flutter counterpart: `rendering/object.dart` (`Constraints`, `ParentData`,
2//! `RenderObject` tree / layout / paint marks). `PaintingContext` is in
3//! `painting_context.rs`, `PipelineOwner` in `pipeline_owner.rs`.
4//!
5//! Semantics wait. A concrete node is [`RenderHandle<T>`] over the authored
6//! struct. A link to another node is the type-erased handle [`AnyRenderObject`].
7//! Authored methods take `self: RenderHandle<Self>`.
8
9use std::any::{Any, TypeId};
10use std::cell::Cell;
11use std::fmt::{self, Debug, Display};
12use std::hash::{Hash, Hasher};
13use std::ops::Receiver;
14use std::rc::Rc;
15use std::time::Duration;
16
17use waft_animation::Curve;
18use waft_embedder::{Matrix4, Offset, Rect, Size};
19use waft_foundation::{
20    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
21    DiagnosticsProperty, FlagProperty, Handle, HandleId, IntoPropertyName, bare_type_name,
22    describe_identity,
23};
24use waft_services::MouseTrackerAnnotation;
25
26use crate::layer::{
27    AnyContainerLayer, AnyOffsetLayer, ErasedLayer, LayerHandle, OffsetLayer, OffsetLayerMixin,
28};
29use crate::painting_context::PaintingContext;
30use crate::pipeline_owner::PipelineOwner;
31
32thread_local! {
33    static DEBUG_ACTIVE_LAYOUT: Cell<Option<AnyRenderObject>> = const { Cell::new(None) };
34    static DEBUG_ACTIVE_PAINT: Cell<Option<AnyRenderObject>> = const { Cell::new(None) };
35    static DEBUG_CHECKING_INTRINSICS: Cell<bool> = const { Cell::new(false) };
36}
37
38/// Whether the framework is currently checking a render object's intrinsic sizes, dry layout, or
39/// dry baseline against its real layout.
40///
41/// Flutter's `RenderObject.debugCheckingIntrinsics`. While this is true, an intrinsic
42/// computation neither caches its result nor throws where it cannot answer.
43pub fn debug_checking_intrinsics() -> bool {
44    DEBUG_CHECKING_INTRINSICS.get()
45}
46
47/// Sets [`debug_checking_intrinsics`].
48pub fn set_debug_checking_intrinsics(value: bool) {
49    DEBUG_CHECKING_INTRINSICS.set(value);
50}
51
52/// Immutable layout constraints.
53///
54/// Flutter's counterpart is the abstract `Constraints` class.
55pub trait Constraints {
56    /// Whether there is exactly one size possible given these constraints.
57    fn is_tight(&self) -> bool;
58
59    /// Whether the constraint is expressed in a consistent manner.
60    fn is_normalized(&self) -> bool;
61
62    /// Asserts that the constraints are valid.
63    ///
64    /// Returns the same as [`is_normalized`](Self::is_normalized) if asserts
65    /// are disabled.
66    fn debug_assert_is_valid(&self, is_applied_constraint: bool) -> bool {
67        let _ = is_applied_constraint;
68        debug_assert!(self.is_normalized());
69        self.is_normalized()
70    }
71}
72
73/// Data associated with a child by its parent.
74///
75/// Flutter's counterpart is the `ParentData` class. Subclasses are ordinary
76/// Rust types that implement this trait.
77pub trait ParentData: Any + Debug + Display {
78    /// Called when the render object is removed from the tree.
79    fn detach(&mut self) {}
80
81    /// The half of this parent data whose type is `id`, if it embeds one.
82    ///
83    /// Dart's `parentData as BoxParentData` and `parentData is KeepAliveParentDataMixin`: a
84    /// half answers for its own type, and a type that embeds one answers for its own type first
85    /// and then asks the half, so a chain of halves composes. Every box parent must answer
86    /// [`crate::BoxParentData`], or a child of it cannot be positioned by the box protocol.
87    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
88        let _ = id;
89        None
90    }
91
92    /// See [`provide`](Self::provide); mirrors it exactly.
93    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
94        let _ = id;
95        None
96    }
97}
98
99impl dyn ParentData {
100    /// The `P` half of this parent data: the value itself when it is a `P`, else what
101    /// [`provide`](ParentData::provide) answers.
102    pub fn part<P: 'static>(&self) -> Option<&P> {
103        let any: &dyn Any = self;
104        any.downcast_ref()
105            .or_else(|| self.provide(TypeId::of::<P>())?.downcast_ref())
106    }
107
108    /// The `P` half of this parent data, mutably: see [`part`](Self::part).
109    pub fn part_mut<P: 'static>(&mut self) -> Option<&mut P> {
110        if (self as &dyn Any).is::<P>() {
111            return (self as &mut dyn Any).downcast_mut();
112        }
113        self.provide_mut(TypeId::of::<P>())?.downcast_mut()
114    }
115}
116
117/// Flutter's `ParentData()` — no subclass fields.
118#[derive(Debug, Default)]
119pub struct EmptyParentData;
120
121impl ParentData for EmptyParentData {}
122
123impl Display for EmptyParentData {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str("<none>")
126    }
127}
128
129/// Flutter's `RenderObject` fields.
130pub struct RenderObjectData {
131    /// The erased vtable, recorded by the protocol constructor (`RenderHandle::new_box`,
132    /// `RenderHandle::new_sliver`). Dart upcasts a subclass reference to `RenderObject` for
133    /// free; here the fat pointer has to be built, and only the protocol knows the table.
134    pub(crate) object_vtable: Option<&'static RenderObjectVTable>,
135    pub(crate) parent: Option<AnyRenderObject>,
136    pub(crate) owner: Option<Handle<PipelineOwner>>,
137    pub(crate) depth: i32,
138    pub(crate) parent_data: Option<Box<dyn ParentData>>,
139    pub(crate) needs_layout: bool,
140    pub(crate) needs_paint: bool,
141    pub(crate) needs_composited_layer_update: bool,
142    pub(crate) needs_compositing_bits_update: bool,
143    pub(crate) needs_compositing: bool,
144    pub(crate) was_repaint_boundary: bool,
145    /// Flutter's `_layerHandle`.
146    pub(crate) layer: LayerHandle<AnyContainerLayer>,
147    pub(crate) is_relayout_boundary: Option<bool>,
148    pub(crate) doing_this_layout_with_callback: bool,
149    pub(crate) debug_doing_this_layout: bool,
150    pub(crate) debug_doing_this_resize: bool,
151    pub(crate) debug_doing_this_paint: bool,
152    pub(crate) debug_can_parent_use_size: Option<bool>,
153    pub(crate) debug_mutations_locked: bool,
154}
155
156impl RenderObjectData {
157    /// Empty tree state for a newly constructed render object.
158    pub fn new() -> RenderObjectData {
159        RenderObjectData {
160            object_vtable: None,
161            parent: None,
162            owner: None,
163            depth: 0,
164            parent_data: None,
165            needs_layout: true,
166            needs_paint: true,
167            needs_composited_layer_update: false,
168            needs_compositing_bits_update: false,
169            needs_compositing: false,
170            was_repaint_boundary: false,
171            layer: LayerHandle::new(),
172            is_relayout_boundary: None,
173            doing_this_layout_with_callback: false,
174            debug_doing_this_layout: false,
175            debug_doing_this_resize: false,
176            debug_doing_this_paint: false,
177            debug_can_parent_use_size: None,
178            debug_mutations_locked: false,
179        }
180    }
181}
182
183impl Default for RenderObjectData {
184    fn default() -> RenderObjectData {
185        RenderObjectData::new()
186    }
187}
188
189/// Flutter's `RenderObjectWithChildMixin` child slot.
190pub struct RenderObjectWithChildData<C> {
191    pub(crate) child: Option<C>,
192}
193
194impl<C> RenderObjectWithChildData<C> {
195    /// No child.
196    pub const fn new() -> RenderObjectWithChildData<C> {
197        RenderObjectWithChildData { child: None }
198    }
199}
200
201impl<C> Default for RenderObjectWithChildData<C> {
202    fn default() -> RenderObjectWithChildData<C> {
203        RenderObjectWithChildData::new()
204    }
205}
206
207/// Flutter's `ContainerParentDataMixin` fields: the links of a doubly-linked child list.
208#[derive(Debug)]
209pub struct ContainerParentData<ChildType> {
210    pub(crate) previous_sibling: Option<ChildType>,
211    pub(crate) next_sibling: Option<ChildType>,
212}
213
214impl<ChildType> ContainerParentData<ChildType> {
215    /// No siblings.
216    pub const fn new() -> ContainerParentData<ChildType> {
217        ContainerParentData {
218            previous_sibling: None,
219            next_sibling: None,
220        }
221    }
222}
223
224impl<ChildType> Default for ContainerParentData<ChildType> {
225    fn default() -> ContainerParentData<ChildType> {
226        ContainerParentData::new()
227    }
228}
229
230/// Parent data to support a doubly-linked list of children.
231///
232/// The children can be traversed using [`next_sibling`](Self::next_sibling) or
233/// [`previous_sibling`](Self::previous_sibling), which can be called on the parent data of the
234/// render objects obtained via [`crate::ContainerRenderObjectMixin::first_child`] or
235/// [`crate::ContainerRenderObjectMixin::last_child`].
236///
237/// Flutter's `ContainerParentDataMixin`. The links live in a [`ContainerParentData`] field.
238pub trait ContainerParentDataMixin: ParentData {
239    /// The type-erased handle of a child in the list. `AnyRenderBox` for a box container.
240    type ChildType: Copy + PartialEq;
241
242    /// Mixin field access.
243    fn container_parent_data(&self) -> &ContainerParentData<Self::ChildType>;
244
245    /// See [`container_parent_data`](Self::container_parent_data).
246    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<Self::ChildType>;
247
248    /// The previous sibling in the parent's child list.
249    fn previous_sibling(&self) -> Option<Self::ChildType> {
250        self.container_parent_data().previous_sibling
251    }
252
253    /// Sets [`previous_sibling`](Self::previous_sibling).
254    fn set_previous_sibling(&mut self, value: Option<Self::ChildType>) {
255        self.container_parent_data_mut().previous_sibling = value;
256    }
257
258    /// The next sibling in the parent's child list.
259    fn next_sibling(&self) -> Option<Self::ChildType> {
260        self.container_parent_data().next_sibling
261    }
262
263    /// Sets [`next_sibling`](Self::next_sibling).
264    fn set_next_sibling(&mut self, value: Option<Self::ChildType>) {
265        self.container_parent_data_mut().next_sibling = value;
266    }
267
268    /// Clear the sibling pointers.
269    ///
270    /// The body of Flutter's `detach` override; call it from [`ParentData::detach`].
271    fn detach(&mut self) {
272        debug_assert!(
273            self.previous_sibling().is_none(),
274            "Pointers to siblings must be nulled before detaching ParentData."
275        );
276        debug_assert!(
277            self.next_sibling().is_none(),
278            "Pointers to siblings must be nulled before detaching ParentData."
279        );
280    }
281}
282
283/// Flutter's `ContainerRenderObjectMixin` fields: the head and tail of the child list, and its
284/// length.
285pub struct ContainerRenderObjectData<ChildType> {
286    pub(crate) child_count: usize,
287    pub(crate) first_child: Option<ChildType>,
288    pub(crate) last_child: Option<ChildType>,
289}
290
291impl<ChildType> ContainerRenderObjectData<ChildType> {
292    /// No children.
293    pub const fn new() -> ContainerRenderObjectData<ChildType> {
294        ContainerRenderObjectData {
295            child_count: 0,
296            first_child: None,
297            last_child: None,
298        }
299    }
300}
301
302impl<ChildType> Default for ContainerRenderObjectData<ChildType> {
303    fn default() -> ContainerRenderObjectData<ChildType> {
304        ContainerRenderObjectData::new()
305    }
306}
307
308/// An erased render object a parent can hold as a child: Dart's `ChildType extends RenderObject`
309/// type argument of `RenderObjectWithChildMixin` and `ContainerRenderObjectMixin`.
310///
311/// Implemented by [`crate::AnyRenderBox`] and [`crate::AnyRenderSliver`].
312pub trait ErasedRenderObject: Copy + PartialEq + Debug + 'static {
313    /// The `RenderObject` view of this handle.
314    fn as_object(self) -> AnyRenderObject;
315
316    /// Dart's implicit downcast of a `RenderObject` to `ChildType`.
317    ///
318    /// # Panics
319    ///
320    /// If `object` does not use this protocol.
321    fn from_object(object: AnyRenderObject) -> Self;
322}
323
324/// A render object with a single child.
325///
326/// Flutter's `RenderObjectWithChildMixin`. The child slot lives in a
327/// [`RenderObjectWithChildData`] field.
328pub trait RenderObjectWithChildMixin: RenderObject {
329    /// Flutter's `ChildType`: the protocol of this render object's child.
330    type ChildType: ErasedRenderObject;
331
332    /// Mixin field access.
333    fn child_data(
334        self: RenderHandle<Self>,
335        app: &App,
336    ) -> &RenderObjectWithChildData<Self::ChildType>;
337
338    /// See [`child_data`](Self::child_data).
339    fn child_data_mut(
340        self: RenderHandle<Self>,
341        app: &mut App,
342    ) -> &mut RenderObjectWithChildData<Self::ChildType>;
343
344    /// The render object's unique child.
345    fn child(self: RenderHandle<Self>, app: &App) -> Option<Self::ChildType> {
346        self.child_data(app).child
347    }
348
349    /// Flutter's `RenderObjectWithChildMixin.debugDescribeChildren`: the child, named `child`.
350    /// A class with this mixin answers [`RenderObject::debug_describe_children`] with it.
351    fn debug_describe_children(
352        self: RenderHandle<Self>,
353        app: &App,
354    ) -> Vec<Rc<dyn DiagnosticsNode>> {
355        self.child(app)
356            .map(|child| {
357                Rc::new(child.as_object().to_diagnostics_node(app, "child"))
358                    as Rc<dyn DiagnosticsNode>
359            })
360            .into_iter()
361            .collect()
362    }
363
364    /// Sets the unique child, adopting or dropping as Flutter's setter does.
365    fn set_child(self: RenderHandle<Self>, app: &mut App, value: Option<Self::ChildType>) {
366        if let Some(old) = self.child(app) {
367            self.as_render_object(app).drop_child(app, old.as_object());
368        }
369        self.child_data_mut(app).child = value;
370        if let Some(new) = value {
371            self.as_render_object(app).adopt_child(app, new.as_object());
372        }
373    }
374}
375
376/// Generic mixin for render objects with a list of children.
377///
378/// Provides a child model for a render object that has a doubly-linked list of children.
379///
380/// [`ParentDataType`](ContainerRenderObjectMixin::ParentDataType) stores parent container data
381/// on its child render objects. It must be a [`ContainerParentDataMixin`], which provides the
382/// interface for visiting children. This data is populated by the `setup_parent_data`
383/// implemented by the render object using this mixin.
384///
385/// Flutter's `ContainerRenderObjectMixin`. Its two type arguments are the associated types
386/// [`ChildType`](ContainerRenderObjectMixin::ChildType) and
387/// [`ParentDataType`](ContainerRenderObjectMixin::ParentDataType).
388pub trait ContainerRenderObjectMixin: RenderObject {
389    /// Flutter's `ChildType`: the protocol of this render object's children.
390    type ChildType: ErasedRenderObject;
391
392    /// Flutter's `ParentDataType`: the parent data this render object installs on its children.
393    type ParentDataType: ContainerParentDataMixin<ChildType = Self::ChildType> + 'static;
394
395    /// Mixin field access.
396    fn container_data(
397        self: RenderHandle<Self>,
398        app: &App,
399    ) -> &ContainerRenderObjectData<Self::ChildType>;
400
401    /// See [`container_data`](Self::container_data).
402    fn container_data_mut(
403        self: RenderHandle<Self>,
404        app: &mut App,
405    ) -> &mut ContainerRenderObjectData<Self::ChildType>;
406
407    /// The number of children.
408    fn child_count(self: RenderHandle<Self>, app: &App) -> usize {
409        self.container_data(app).child_count
410    }
411
412    /// Insert child into this render object's child list after the given child.
413    ///
414    /// If `after` is `None`, then this inserts the child at the start of the list, and the child
415    /// becomes the new [`first_child`](Self::first_child).
416    fn insert(
417        self: RenderHandle<Self>,
418        app: &mut App,
419        child: Self::ChildType,
420        after: Option<Self::ChildType>,
421    ) {
422        ContainerRenderObjectBase::insert(self, app, child, after)
423    }
424
425    /// Append child to the end of this render object's child list.
426    fn add(self: RenderHandle<Self>, app: &mut App, child: Self::ChildType) {
427        let last_child = self.last_child(app);
428        self.insert(app, child, last_child);
429    }
430
431    /// Add all the children to the end of this render object's child list.
432    fn add_all(self: RenderHandle<Self>, app: &mut App, children: Option<Vec<Self::ChildType>>) {
433        for child in children.into_iter().flatten() {
434            self.add(app, child);
435        }
436    }
437
438    /// Remove this child from the child list.
439    ///
440    /// Requires the child to be present in the child list.
441    fn remove(self: RenderHandle<Self>, app: &mut App, child: Self::ChildType) {
442        ContainerRenderObjectBase::remove(self, app, child)
443    }
444
445    /// Remove all their children from this render object's child list.
446    ///
447    /// More efficient than removing them individually.
448    fn remove_all(self: RenderHandle<Self>, app: &mut App) {
449        ContainerRenderObjectBase::remove_all(self, app)
450    }
451
452    /// Move the given `child` in the child list to be after another child.
453    ///
454    /// Dart's `move`. More efficient than removing and re-adding the child. Requires the child
455    /// to already be in the child list at some position. Pass `None` for `after` to move the
456    /// child to the start of the child list.
457    fn move_child(
458        self: RenderHandle<Self>,
459        app: &mut App,
460        child: Self::ChildType,
461        after: Option<Self::ChildType>,
462    ) {
463        ContainerRenderObjectBase::move_child(self, app, child, after)
464    }
465
466    /// The body of Flutter's `attach` override: attaches every child in the list.
467    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
468        let mut child = self.first_child(app);
469        while let Some(current) = child {
470            current.as_object().attach(app, owner);
471            child = current
472                .as_object()
473                .parent_data_of::<Self::ParentDataType>(app)
474                .next_sibling();
475        }
476    }
477
478    /// The body of Flutter's `detach` override: detaches every child in the list.
479    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
480        let mut child = self.first_child(app);
481        while let Some(current) = child {
482            current.as_object().detach(app);
483            child = current
484                .as_object()
485                .parent_data_of::<Self::ParentDataType>(app)
486                .next_sibling();
487        }
488    }
489
490    /// Flutter's `redepthChildren`: walks the child list.
491    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
492        let mut child = self.first_child(app);
493        while let Some(current) = child {
494            self.as_render_object(app)
495                .redepth_child(app, current.as_object());
496            child = current
497                .as_object()
498                .parent_data_of::<Self::ParentDataType>(app)
499                .next_sibling();
500        }
501    }
502
503    /// Flutter's `visitChildren`: walks the child list.
504    fn visit_children(
505        self: RenderHandle<Self>,
506        app: &App,
507        visitor: &mut dyn FnMut(AnyRenderObject),
508    ) {
509        let mut child = self.first_child(app);
510        while let Some(current) = child {
511            visitor(current.as_object());
512            child = current
513                .as_object()
514                .parent_data_of::<Self::ParentDataType>(app)
515                .next_sibling();
516        }
517    }
518
519    /// The first child in the child list.
520    fn first_child(self: RenderHandle<Self>, app: &App) -> Option<Self::ChildType> {
521        self.container_data(app).first_child
522    }
523
524    /// Flutter's `ContainerRenderObjectMixin.debugDescribeChildren`: the children in order,
525    /// named `child 1`, `child 2`, …. A class with this mixin answers
526    /// [`RenderObject::debug_describe_children`] with it.
527    fn debug_describe_children(
528        self: RenderHandle<Self>,
529        app: &App,
530    ) -> Vec<Rc<dyn DiagnosticsNode>> {
531        let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
532        ContainerRenderObjectMixin::visit_children(self, app, &mut |child| {
533            let name = format!("child {}", children.len() + 1);
534            children.push(Rc::new(child.to_diagnostics_node(app, name)));
535        });
536        children
537    }
538
539    /// The last child in the child list.
540    fn last_child(self: RenderHandle<Self>, app: &App) -> Option<Self::ChildType> {
541        self.container_data(app).last_child
542    }
543
544    /// The previous child before the given child in the child list.
545    fn child_before(
546        self: RenderHandle<Self>,
547        app: &App,
548        child: Self::ChildType,
549    ) -> Option<Self::ChildType> {
550        debug_assert_eq!(
551            child.as_object().parent(app),
552            Some(self.as_render_object(app))
553        );
554        child
555            .as_object()
556            .parent_data_of::<Self::ParentDataType>(app)
557            .previous_sibling()
558    }
559
560    /// The next child after the given child in the child list.
561    fn child_after(
562        self: RenderHandle<Self>,
563        app: &App,
564        child: Self::ChildType,
565    ) -> Option<Self::ChildType> {
566        debug_assert_eq!(
567            child.as_object().parent(app),
568            Some(self.as_render_object(app))
569        );
570        child
571            .as_object()
572            .parent_data_of::<Self::ParentDataType>(app)
573            .next_sibling()
574    }
575
576    /// Returns a list containing the children of this render object.
577    ///
578    /// Dart's `RenderBoxContainerDefaultsMixin.getChildrenAsList`, useful for any container.
579    fn children_as_list(self: RenderHandle<Self>, app: &App) -> Vec<Self::ChildType> {
580        let mut result = Vec::new();
581        let mut child = self.first_child(app);
582        while let Some(current) = child {
583            result.push(current);
584            child = current
585                .as_object()
586                .parent_data_of::<Self::ParentDataType>(app)
587                .next_sibling();
588        }
589        result
590    }
591}
592
593/// Flutter's `ContainerRenderObjectMixin` bodies that an override calls through `super`.
594///
595/// Blanket-implemented for every container, and repeats the default bodies of the four child-list
596/// mutators: a leaf's own override shadows the default it would otherwise call.
597pub trait ContainerRenderObjectBase: ContainerRenderObjectMixin {
598    /// Flutter's `ContainerRenderObjectMixin.insert`.
599    fn insert(
600        self: RenderHandle<Self>,
601        app: &mut App,
602        child: Self::ChildType,
603        after: Option<Self::ChildType>,
604    ) {
605        debug_assert!(
606            child.as_object() != self.as_render_object(app),
607            "A RenderObject cannot be inserted into itself."
608        );
609        debug_assert!(
610            after.is_none_or(|after| after.as_object() != self.as_render_object(app)),
611            "A RenderObject cannot simultaneously be both the parent and the sibling of another \
612             RenderObject."
613        );
614        debug_assert!(
615            after != Some(child),
616            "A RenderObject cannot be inserted after itself."
617        );
618        debug_assert!(Some(child) != self.first_child(app));
619        debug_assert!(Some(child) != self.last_child(app));
620        self.as_render_object(app)
621            .adopt_child(app, child.as_object());
622        debug_assert!(
623            child
624                .as_object()
625                .parent_data_is::<Self::ParentDataType>(app),
626            "A child has parent data that does not conform to this render object's \
627             ParentDataType. Override setup_parent_data to install it."
628        );
629        insert_into_child_list(self, app, child, after);
630    }
631
632    /// Flutter's `ContainerRenderObjectMixin.remove`.
633    fn remove(self: RenderHandle<Self>, app: &mut App, child: Self::ChildType) {
634        remove_from_child_list(self, app, child);
635        self.as_render_object(app)
636            .drop_child(app, child.as_object());
637    }
638
639    /// Flutter's `ContainerRenderObjectMixin.removeAll`.
640    fn remove_all(self: RenderHandle<Self>, app: &mut App) {
641        let mut child = self.first_child(app);
642        while let Some(current) = child {
643            let child_parent_data = current
644                .as_object()
645                .parent_data_of_mut::<Self::ParentDataType>(app);
646            let next = child_parent_data.next_sibling();
647            child_parent_data.set_previous_sibling(None);
648            child_parent_data.set_next_sibling(None);
649            self.as_render_object(app)
650                .drop_child(app, current.as_object());
651            child = next;
652        }
653        let container = self.container_data_mut(app);
654        container.first_child = None;
655        container.last_child = None;
656        container.child_count = 0;
657    }
658
659    /// Flutter's `ContainerRenderObjectMixin.move`.
660    fn move_child(
661        self: RenderHandle<Self>,
662        app: &mut App,
663        child: Self::ChildType,
664        after: Option<Self::ChildType>,
665    ) {
666        debug_assert!(child.as_object() != self.as_render_object(app));
667        debug_assert!(after.is_none_or(|after| after.as_object() != self.as_render_object(app)));
668        debug_assert!(after != Some(child));
669        debug_assert_eq!(
670            child.as_object().parent(app),
671            Some(self.as_render_object(app)),
672            "the child must already be a child of this render object"
673        );
674        if child
675            .as_object()
676            .parent_data_of::<Self::ParentDataType>(app)
677            .previous_sibling()
678            == after
679        {
680            return;
681        }
682        remove_from_child_list(self, app, child);
683        insert_into_child_list(self, app, child, after);
684        self.as_render_object(app).mark_needs_layout(app);
685    }
686}
687
688impl<T: ContainerRenderObjectMixin> ContainerRenderObjectBase for T {}
689
690/// Flutter's `_debugUltimatePreviousSiblingOf`.
691fn debug_ultimate_previous_sibling_of<P>(
692    app: &App,
693    child: P::ChildType,
694    equals: Option<P::ChildType>,
695) -> bool
696where
697    P: ContainerParentDataMixin + 'static,
698    P::ChildType: ErasedRenderObject,
699{
700    let mut child = child;
701    while let Some(previous) = child
702        .as_object()
703        .parent_data_of::<P>(app)
704        .previous_sibling()
705    {
706        debug_assert!(previous != child);
707        child = previous;
708    }
709    Some(child) == equals
710}
711
712/// Flutter's `_debugUltimateNextSiblingOf`.
713fn debug_ultimate_next_sibling_of<P>(
714    app: &App,
715    child: P::ChildType,
716    equals: Option<P::ChildType>,
717) -> bool
718where
719    P: ContainerParentDataMixin + 'static,
720    P::ChildType: ErasedRenderObject,
721{
722    let mut child = child;
723    while let Some(next) = child.as_object().parent_data_of::<P>(app).next_sibling() {
724        debug_assert!(next != child);
725        child = next;
726    }
727    Some(child) == equals
728}
729
730/// Flutter's `_insertIntoChildList`.
731fn insert_into_child_list<T: ContainerRenderObjectMixin>(
732    this: RenderHandle<T>,
733    app: &mut App,
734    child: T::ChildType,
735    after: Option<T::ChildType>,
736) {
737    type ParentDataOf<T> = <T as ContainerRenderObjectMixin>::ParentDataType;
738
739    debug_assert!(
740        child
741            .as_object()
742            .parent_data_of::<ParentDataOf<T>>(app)
743            .next_sibling()
744            .is_none()
745    );
746    debug_assert!(
747        child
748            .as_object()
749            .parent_data_of::<ParentDataOf<T>>(app)
750            .previous_sibling()
751            .is_none()
752    );
753    this.container_data_mut(app).child_count += 1;
754    let Some(after) = after else {
755        // insert at the start (first_child)
756        let first_child = this.first_child(app);
757        child
758            .as_object()
759            .parent_data_of_mut::<ParentDataOf<T>>(app)
760            .set_next_sibling(first_child);
761        if let Some(first_child) = first_child {
762            first_child
763                .as_object()
764                .parent_data_of_mut::<ParentDataOf<T>>(app)
765                .set_previous_sibling(Some(child));
766        }
767        let container = this.container_data_mut(app);
768        container.first_child = Some(child);
769        container.last_child.get_or_insert(child);
770        return;
771    };
772    debug_assert!(this.first_child(app).is_some());
773    debug_assert!(this.last_child(app).is_some());
774    debug_assert!(debug_ultimate_previous_sibling_of::<ParentDataOf<T>>(
775        app,
776        after,
777        this.first_child(app)
778    ));
779    debug_assert!(debug_ultimate_next_sibling_of::<ParentDataOf<T>>(
780        app,
781        after,
782        this.last_child(app)
783    ));
784    let after_next_sibling = after
785        .as_object()
786        .parent_data_of::<ParentDataOf<T>>(app)
787        .next_sibling();
788    let Some(after_next_sibling) = after_next_sibling else {
789        // insert at the end (last_child); we'll end up with two or more children
790        debug_assert_eq!(Some(after), this.last_child(app));
791        child
792            .as_object()
793            .parent_data_of_mut::<ParentDataOf<T>>(app)
794            .set_previous_sibling(Some(after));
795        after
796            .as_object()
797            .parent_data_of_mut::<ParentDataOf<T>>(app)
798            .set_next_sibling(Some(child));
799        this.container_data_mut(app).last_child = Some(child);
800        return;
801    };
802    // insert in the middle; we'll end up with three or more children
803    // set up links from child to siblings
804    let child_parent_data = child.as_object().parent_data_of_mut::<ParentDataOf<T>>(app);
805    child_parent_data.set_next_sibling(Some(after_next_sibling));
806    child_parent_data.set_previous_sibling(Some(after));
807    // set up links from siblings to child
808    after
809        .as_object()
810        .parent_data_of_mut::<ParentDataOf<T>>(app)
811        .set_next_sibling(Some(child));
812    after_next_sibling
813        .as_object()
814        .parent_data_of_mut::<ParentDataOf<T>>(app)
815        .set_previous_sibling(Some(child));
816}
817
818/// Flutter's `_removeFromChildList`.
819fn remove_from_child_list<T: ContainerRenderObjectMixin>(
820    this: RenderHandle<T>,
821    app: &mut App,
822    child: T::ChildType,
823) {
824    type ParentDataOf<T> = <T as ContainerRenderObjectMixin>::ParentDataType;
825
826    debug_assert!(debug_ultimate_previous_sibling_of::<ParentDataOf<T>>(
827        app,
828        child,
829        this.first_child(app)
830    ));
831    debug_assert!(debug_ultimate_next_sibling_of::<ParentDataOf<T>>(
832        app,
833        child,
834        this.last_child(app)
835    ));
836    let child_parent_data = child.as_object().parent_data_of::<ParentDataOf<T>>(app);
837    let (previous_sibling, next_sibling) = (
838        child_parent_data.previous_sibling(),
839        child_parent_data.next_sibling(),
840    );
841    match previous_sibling {
842        None => {
843            debug_assert_eq!(this.first_child(app), Some(child));
844            this.container_data_mut(app).first_child = next_sibling;
845        }
846        Some(previous_sibling) => previous_sibling
847            .as_object()
848            .parent_data_of_mut::<ParentDataOf<T>>(app)
849            .set_next_sibling(next_sibling),
850    }
851    match next_sibling {
852        None => {
853            debug_assert_eq!(this.last_child(app), Some(child));
854            this.container_data_mut(app).last_child = previous_sibling;
855        }
856        Some(next_sibling) => next_sibling
857            .as_object()
858            .parent_data_of_mut::<ParentDataOf<T>>(app)
859            .set_previous_sibling(previous_sibling),
860    }
861    let child_parent_data = child.as_object().parent_data_of_mut::<ParentDataOf<T>>(app);
862    child_parent_data.set_previous_sibling(None);
863    child_parent_data.set_next_sibling(None);
864    this.container_data_mut(app).child_count -= 1;
865}
866
867/// Class-specific render object: the data accessors and the virtuals, nothing else. Methods
868/// take [`RenderHandle<Self>`] so they can re-enter the same slot through [`App`].
869///
870/// Tree operations (`mark_needs_layout`, `adopt_child`, `parent`, …) live on the erased
871/// [`AnyRenderObject`]; a typed handle reaches them through its protocol trait,
872/// [`crate::RenderBox`] or [`crate::RenderSliver`].
873pub trait RenderObject: 'static + Sized {
874    /// Mixin field access.
875    fn render_object_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectData;
876
877    /// See [`render_object_data`](Self::render_object_data).
878    fn render_object_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderObjectData;
879
880    /// Dart's implicit upcast of a concrete render object to `RenderObject`: this object's
881    /// type-erased handle, through the vtable the protocol recorded when it created it.
882    fn as_render_object(self: RenderHandle<Self>, app: &App) -> AnyRenderObject {
883        let vtable = self
884            .render_object_data(app)
885            .object_vtable
886            .expect("a render object records its vtable when the protocol creates it");
887        AnyRenderObject::from_vtable(self.id(), vtable)
888    }
889
890    /// Do the work of computing the layout for this render object.
891    ///
892    /// Do not call this function directly: call `layout` on the protocol handle instead.
893    /// Read the constraints with `constraints` on the protocol trait.
894    fn perform_layout(self: RenderHandle<Self>, app: &mut App);
895
896    /// Updates the render object's size using only the constraints.
897    ///
898    /// Called by `layout` only when [`sized_by_parent`](Self::sized_by_parent) is true.
899    ///
900    /// A box overrides [`crate::RenderBox::compute_dry_layout`] instead: the box protocol's
901    /// [`crate::RenderBox::perform_resize`] sizes itself from it.
902    fn perform_resize(self: RenderHandle<Self>, _app: &mut App) {
903        let _ = self;
904        panic!("RenderObject::perform_resize was called; override it when sized_by_parent is true")
905    }
906
907    /// Calls `visitor` for each immediate child.
908    fn visit_children(
909        self: RenderHandle<Self>,
910        app: &App,
911        visitor: &mut dyn FnMut(AnyRenderObject),
912    ) {
913        let _ = (self, app, visitor);
914    }
915
916    /// Sets up parent data for `child` if it has none.
917    ///
918    /// For a box, override [`crate::RenderBox::setup_parent_data`] instead; an implementation
919    /// here is not called for boxes.
920    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
921        if child.parent_data(app).is_none() {
922            child.set_parent_data(app, EmptyParentData);
923        }
924    }
925
926    /// The body of Flutter's `attach` override after `super.attach(owner)`; the base body has
927    /// already run. The default attaches the children reported by
928    /// [`visit_children`](Self::visit_children).
929    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
930        for child in collect_children(app, self) {
931            child.attach(app, owner);
932        }
933    }
934
935    /// The body of Flutter's `detach` override after `super.detach()`. The default detaches
936    /// the children reported by [`visit_children`](Self::visit_children).
937    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
938        for child in collect_children(app, self) {
939            child.detach(app);
940        }
941    }
942
943    /// Adjusts the depth of each child reported by [`visit_children`](Self::visit_children).
944    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
945        let depth = self.render_object_data(app).depth;
946        let owner = self.render_object_data(app).owner;
947        for child in collect_children(app, self) {
948            debug_assert_eq!(child.owner(app), owner);
949            child.redepth_below(app, depth);
950        }
951    }
952
953    /// Whether the constraints are the only input to the sizing algorithm.
954    fn sized_by_parent(self: RenderHandle<Self>, _app: &App) -> bool {
955        let _ = self;
956        false
957    }
958
959    /// Applies the transform that would be applied when painting the given child to the
960    /// given matrix.
961    ///
962    /// Used by coordinate conversion functions ([`AnyRenderObject::get_transform_to`]) to
963    /// translate coordinates local to one render object into coordinates local to another
964    /// render object.
965    ///
966    /// Some RenderObjects will provide a zeroed out matrix in this method, indicating that
967    /// the child should not paint anything or respond to hit tests currently. A parent may
968    /// supply a non-zero matrix even if it does not paint its child currently, for example
969    /// if the parent is a `RenderOffstage` with `offstage` set to true. In both of these
970    /// cases, the parent must return `false` from `paintsChild`.
971    ///
972    /// The box protocol's default translates by the child's `BoxParentData` offset; this
973    /// object-level default only asserts, as Dart's `RenderObject.applyPaintTransform`.
974    fn apply_paint_transform(
975        self: RenderHandle<Self>,
976        app: &App,
977        child: AnyRenderObject,
978        transform: &mut Matrix4,
979    ) {
980        let _ = transform;
981        debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
982    }
983
984    /// Dart's `describeApproximatePaintClip`: the rectangle, in this object's coordinates, that
985    /// it clips `child`'s painting to, or `None` where it does not clip it. An estimate, for the
986    /// inspector's screenshot bounds: a clip it may apply is enough.
987    fn describe_approximate_paint_clip(
988        self: RenderHandle<Self>,
989        app: &App,
990        child: AnyRenderObject,
991    ) -> Option<Rect> {
992        let _ = (self, app, child);
993        None
994    }
995
996    /// Whether the given child would be painted if [`paint`](Self::paint) were called.
997    ///
998    /// Some RenderObjects skip painting their children if they are configured to
999    /// not produce any visible effects. For example, a `RenderOffstage` with
1000    /// its `offstage` property set to true, or a `RenderOpacity` with its opacity
1001    /// value set to zero.
1002    ///
1003    /// In these cases, the parent may still supply a non-zero matrix in
1004    /// [`apply_paint_transform`](Self::apply_paint_transform) to inform callers about where it
1005    /// would paint the child if the child were painted at all. Alternatively, the parent may
1006    /// supply a zeroed out matrix if it would not otherwise be able to determine
1007    /// a valid matrix for the child and thus cannot meaningfully determine where
1008    /// the child would paint.
1009    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
1010        debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
1011        true
1012    }
1013
1014    /// Whether this render object repaints separately from its parent.
1015    ///
1016    /// Override this in subclasses to indicate that instances of your class ought
1017    /// to repaint independently. For example, render objects that repaint
1018    /// frequently might want to repaint themselves without requiring their parent
1019    /// to repaint.
1020    ///
1021    /// If this getter returns true, the [`paint_bounds`](Self::paint_bounds) are applied to this
1022    /// object and all descendants. The framework invokes
1023    /// [`update_composited_layer`](Self::update_composited_layer) to create an [`OffsetLayer`]
1024    /// and assigns it to the [`layer`](AnyRenderObject::layer) field.
1025    /// Render objects that declare themselves as repaint boundaries must not replace
1026    /// the layer created by the framework.
1027    ///
1028    /// If the value of this getter changes, [`AnyRenderObject::mark_needs_compositing_bits_update`]
1029    /// must be called.
1030    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
1031        let _ = self;
1032        false
1033    }
1034
1035    /// Whether this render object always needs compositing.
1036    ///
1037    /// Override this in subclasses to indicate that your paint function always
1038    /// creates at least one composited layer. For example, videos should return
1039    /// true if they use hardware decoders.
1040    ///
1041    /// You must call [`AnyRenderObject::mark_needs_compositing_bits_update`] if the value of this
1042    /// getter changes. (This is implied when [`AnyRenderObject::adopt_child`] or
1043    /// [`AnyRenderObject::drop_child`] are called.)
1044    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
1045        let _ = self;
1046        false
1047    }
1048
1049    /// Dart's `super.debugFillProperties` as a class's override calls it: `RenderObject`'s
1050    /// properties, then `RenderBox`'s or `RenderSliver`'s, which the framework adds before
1051    /// [`debug_fill_properties`](Self::debug_fill_properties). A class whose Dart override leaves
1052    /// the super call out, as `RenderView`'s does, overrides this to add nothing.
1053    fn debug_fill_base_properties(
1054        self: RenderHandle<Self>,
1055        app: &App,
1056        properties: &mut DiagnosticPropertiesBuilder,
1057    ) {
1058        self.as_render_object(app)
1059            .fill_base_properties(app, properties);
1060    }
1061
1062    /// Dart's `debugFillProperties`: the properties this class shows in a dump, after its base
1063    /// classes'. A trait default cannot call `super`, so the framework adds `RenderObject`'s and
1064    /// `RenderBox`'s or `RenderSliver`'s properties first and an override adds only its own,
1065    /// in Dart's order.
1066    fn debug_fill_properties(
1067        self: RenderHandle<Self>,
1068        _app: &App,
1069        _properties: &mut DiagnosticPropertiesBuilder,
1070    ) {
1071        let _ = self;
1072    }
1073
1074    /// Dart's `debugDescribeChildren`: the children a dump shows under this object. Dart's
1075    /// default shows none and its child mixins name theirs (`child`; `child 1`, `child 2`, …);
1076    /// this default shows the children [`visit_children`](Self::visit_children) visits, named
1077    /// `child` when there is one and `child 1`, `child 2`, … when there are more, so a dump never
1078    /// drops a child of a class that has not described its own.
1079    fn debug_describe_children(
1080        self: RenderHandle<Self>,
1081        app: &App,
1082    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1083        let mut children = Vec::new();
1084        Self::visit_children(self, app, &mut |child| children.push(child));
1085        let numbered = children.len() > 1;
1086        children
1087            .into_iter()
1088            .enumerate()
1089            .map(|(index, child)| {
1090                let name = if numbered {
1091                    format!("child {}", index + 1)
1092                } else {
1093                    "child".to_owned()
1094                };
1095                Rc::new(child.to_diagnostics_node(app, name)) as Rc<dyn DiagnosticsNode>
1096            })
1097            .collect()
1098    }
1099
1100    /// Dart's `this is MouseTrackerAnnotation`: the annotation this render object implements,
1101    /// read live each time the mouse tracker consults it. `None` for a render object that is
1102    /// not an annotation, which is the default.
1103    fn mouse_tracker_annotation(
1104        self: RenderHandle<Self>,
1105        _app: &App,
1106    ) -> Option<MouseTrackerAnnotation> {
1107        let _ = self;
1108        None
1109    }
1110
1111    /// Update the composited layer owned by this render object.
1112    ///
1113    /// This method is called by the framework when [`is_repaint_boundary`](Self::is_repaint_boundary)
1114    /// is true.
1115    ///
1116    /// If `old_layer` is `None`, this method must return a new [`OffsetLayer`]
1117    /// (or subtype thereof). If `old_layer` is not `None`, then this method must
1118    /// reuse the layer instance that is provided — it is an error to create a new
1119    /// layer in this instance. The layer will be disposed by the framework when
1120    /// either the render object is disposed or if it is no longer a repaint
1121    /// boundary.
1122    ///
1123    /// The [`OffsetLayerMixin::offset`](crate::OffsetLayerMixin::offset) property will be managed
1124    /// by the framework and must not be updated by this method.
1125    ///
1126    /// If a property of the composited layer needs to be updated, the render object
1127    /// must call [`AnyRenderObject::mark_needs_composited_layer_update`] which will schedule this
1128    /// method to be called without repainting children. If this widget was marked as
1129    /// needing to paint and needing a composited layer update, this method is only
1130    /// called once.
1131    fn update_composited_layer(
1132        self: RenderHandle<Self>,
1133        app: &mut App,
1134        old_layer: Option<AnyOffsetLayer>,
1135    ) -> AnyOffsetLayer {
1136        debug_assert!(self.is_repaint_boundary(app));
1137        old_layer.unwrap_or_else(|| OffsetLayer::new(app, Offset::ZERO).as_offset_layer())
1138    }
1139
1140    /// Attempt to make (a portion of) this or a descendant [`RenderObject`] visible on screen.
1141    ///
1142    /// If `descendant` is provided, that render object is made visible. If `descendant` is
1143    /// omitted, this render object is made visible.
1144    ///
1145    /// The optional `rect` parameter describes which area of that render object should be
1146    /// shown on screen. If `rect` is `None`, the entire render object (as defined by its
1147    /// paint bounds) will be revealed. The `rect` parameter is interpreted relative to the
1148    /// coordinate system of `descendant` if that argument is provided and relative to this
1149    /// render object otherwise.
1150    ///
1151    /// The `duration` parameter can be set to a non-zero value to bring the target object on
1152    /// screen in an animation defined by `curve`.
1153    ///
1154    /// See also:
1155    ///
1156    /// * [`crate::show_in_viewport`], which `RenderViewportBase` delegates
1157    ///   this method to.
1158    fn show_on_screen(
1159        self: RenderHandle<Self>,
1160        app: &mut App,
1161        descendant: Option<AnyRenderObject>,
1162        rect: Option<Rect>,
1163        duration: Duration,
1164        curve: Rc<dyn Curve>,
1165    ) {
1166        RenderObjectBase::show_on_screen(self, app, descendant, rect, duration, curve)
1167    }
1168
1169    /// Dart's `object is RenderAbstractViewport` for any interface: the erased handle of the
1170    /// interface `id` names, if this type implements it.
1171    ///
1172    /// An implementor answers each interface it implements with that interface's type-erased
1173    /// handle, boxed; [`AnyRenderObject::interface`] unboxes it. The default implements none.
1174    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
1175        let _ = (self, id);
1176        None
1177    }
1178
1179    /// Release any resources held by this render object.
1180    ///
1181    /// The object that creates a [`RenderObject`] is in charge of disposing it. If this render
1182    /// object has created any children directly, it must dispose of those children in this method
1183    /// as well. It must not dispose of any children that were created by some other object, such
1184    /// as a `RenderObjectElement`. Those children will be disposed when that element unmounts,
1185    /// which may be delayed if the element is moved to another part of the tree.
1186    ///
1187    /// Implementations of this method must end with a call to the inherited method,
1188    /// `RenderObjectBase::dispose(self, app)`, as in Dart's `super.dispose()`.
1189    ///
1190    /// The object is no longer usable after calling dispose. [`AnyRenderObject::dispose`] gives
1191    /// up the tree's hold on it after this hook returns, and the arena frees it at the next
1192    /// checkpoint unless a `Ref` still keeps it.
1193    fn dispose(self: RenderHandle<Self>, app: &mut App) {
1194        RenderObjectBase::dispose(self, app);
1195    }
1196
1197    /// Paint this render object into the given context at the given offset.
1198    ///
1199    /// Do not call this function directly: [`PaintingContext::paint_child`] does. Paint children
1200    /// with `context.paint_child(app, child, offset + child_offset)`; do not use the canvas to
1201    /// translate, and do not use it after painting a child.
1202    fn paint(
1203        self: RenderHandle<Self>,
1204        app: &mut App,
1205        context: &mut PaintingContext,
1206        offset: Offset,
1207    ) {
1208        let _ = (self, app, context, offset);
1209    }
1210}
1211
1212fn collect_children<T: RenderObject>(app: &App, this: RenderHandle<T>) -> Vec<AnyRenderObject> {
1213    let mut children = Vec::new();
1214    this.visit_children(app, &mut |child| children.push(child));
1215    children
1216}
1217
1218/// Implements the [`RenderObject`] field accessors for a `render_object` field.
1219#[macro_export]
1220macro_rules! render_object_accessors {
1221    () => {
1222        fn render_object_data(
1223            self: $crate::RenderHandle<Self>,
1224            app: &::waft_foundation::App,
1225        ) -> &$crate::RenderObjectData {
1226            &self.get(app).render_object
1227        }
1228        fn render_object_data_mut(
1229            self: $crate::RenderHandle<Self>,
1230            app: &mut ::waft_foundation::App,
1231        ) -> &mut $crate::RenderObjectData {
1232            &mut self.get_mut(app).render_object
1233        }
1234    };
1235}
1236
1237/// Typed access to a concrete render object's class-specific state.
1238///
1239/// [`get`](Self::get) / [`get_mut`](Self::get_mut) are point access: drop the
1240/// borrow before any call that can re-enter this slot.
1241pub struct RenderHandle<T>(Handle<T>);
1242
1243impl<T> Clone for RenderHandle<T> {
1244    fn clone(&self) -> RenderHandle<T> {
1245        *self
1246    }
1247}
1248
1249impl<T> Copy for RenderHandle<T> {}
1250
1251impl<T> Receiver for RenderHandle<T> {
1252    type Target = T;
1253}
1254
1255impl<T> PartialEq for RenderHandle<T> {
1256    fn eq(&self, other: &RenderHandle<T>) -> bool {
1257        self.0 == other.0
1258    }
1259}
1260
1261impl<T> Eq for RenderHandle<T> {}
1262
1263impl<T> Hash for RenderHandle<T> {
1264    fn hash<H: Hasher>(&self, state: &mut H) {
1265        self.0.hash(state);
1266    }
1267}
1268
1269impl<T> Debug for RenderHandle<T> {
1270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271        write!(
1272            f,
1273            "RenderHandle<{}>({:?})",
1274            std::any::type_name::<T>(),
1275            self.0.id()
1276        )
1277    }
1278}
1279
1280impl<T: 'static> RenderHandle<T> {
1281    /// The concrete state. Drop the borrow before a virtual call.
1282    pub fn get(self, app: &App) -> &T {
1283        app.get(self.0)
1284    }
1285
1286    /// See [`get`](Self::get).
1287    pub fn get_mut(self, app: &mut App) -> &mut T {
1288        app.get_mut(self.0)
1289    }
1290
1291    pub(crate) fn id(self) -> HandleId {
1292        self.0.id()
1293    }
1294
1295    /// The foundation handle, for a [`waft_foundation::Listener::handle_method`] tear-off.
1296    pub fn handle(self) -> Handle<T> {
1297        self.0
1298    }
1299
1300    /// The render handle for a foundation handle, which is what such a tear-off is called with.
1301    pub fn from_handle(handle: Handle<T>) -> RenderHandle<T> {
1302        RenderHandle(handle)
1303    }
1304}
1305
1306/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
1307pub(crate) fn resolve<T: 'static>(id: HandleId) -> RenderHandle<T> {
1308    RenderHandle(Handle::from_id(id))
1309}
1310
1311/// A render object is a tree node: the tree code keeps it until [`AnyRenderObject::dispose`].
1312#[track_caller]
1313pub(crate) fn create<T: 'static>(app: &mut App, object: T) -> RenderHandle<T> {
1314    RenderHandle(app.create(object).into_tree_node(app))
1315}
1316
1317/// The dispatch signature of [`RenderObject::show_on_screen`].
1318pub(crate) type ShowOnScreenFn =
1319    fn(&mut App, HandleId, Option<AnyRenderObject>, Option<Rect>, Duration, Rc<dyn Curve>);
1320
1321/// The vtable of an erased [`AnyRenderObject`]: one `&'static` table per type, built from the
1322/// trait impl by the protocol. Copied out of the handle before a virtual call, so the slot is not
1323/// borrowed across it.
1324pub(crate) struct RenderObjectVTable {
1325    pub object_data: fn(&App, HandleId) -> &RenderObjectData,
1326    pub object_data_mut: fn(&mut App, HandleId) -> &mut RenderObjectData,
1327    pub visit_children: fn(&App, HandleId, &mut dyn FnMut(AnyRenderObject)),
1328    pub did_attach: fn(&mut App, HandleId, Handle<PipelineOwner>),
1329    pub did_detach: fn(&mut App, HandleId),
1330    pub redepth_children: fn(&mut App, HandleId),
1331    pub setup_parent_data: fn(&mut App, HandleId, AnyRenderObject),
1332    pub sized_by_parent: fn(&App, HandleId) -> bool,
1333    pub perform_layout: fn(&mut App, HandleId),
1334    pub perform_resize: fn(&mut App, HandleId),
1335    pub mark_needs_layout: fn(&mut App, HandleId),
1336    pub paint_bounds: fn(&App, HandleId) -> Rect,
1337    pub apply_paint_transform: fn(&App, HandleId, AnyRenderObject, &mut Matrix4),
1338    pub describe_approximate_paint_clip: fn(&App, HandleId, AnyRenderObject) -> Option<Rect>,
1339    pub paints_child: fn(&App, HandleId, AnyRenderObject) -> bool,
1340    pub is_repaint_boundary: fn(&App, HandleId) -> bool,
1341    pub always_needs_compositing: fn(&App, HandleId) -> bool,
1342    pub mouse_tracker_annotation: fn(&App, HandleId) -> Option<MouseTrackerAnnotation>,
1343    pub update_composited_layer: fn(&mut App, HandleId, Option<AnyOffsetLayer>) -> AnyOffsetLayer,
1344    pub show_on_screen: ShowOnScreenFn,
1345    pub interface: fn(HandleId, TypeId) -> Option<Box<dyn Any>>,
1346    pub paint: fn(&mut App, HandleId, &mut PaintingContext, Offset),
1347    pub dispose: fn(&mut App, HandleId),
1348    pub debug_fill_base_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
1349    pub debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
1350    pub debug_describe_children: fn(&App, HandleId) -> Vec<Rc<dyn DiagnosticsNode>>,
1351    /// The Rust type's path, which a dump names the object by, as Dart's `runtimeType`.
1352    pub type_name: fn() -> &'static str,
1353    /// The protocol table this object table is nested in. Exactly one is `Some`.
1354    pub as_box: Option<fn() -> &'static crate::box_::RenderBoxVTable>,
1355    pub as_sliver: Option<fn() -> &'static crate::sliver::RenderSliverVTable>,
1356}
1357
1358impl RenderObjectVTable {
1359    /// `setup_parent_data`, `apply_paint_transform`, `perform_resize` and `mark_needs_layout`
1360    /// are passed in because the box protocol has its own defaults; `paint_bounds` because each
1361    /// protocol defines it.
1362    pub(crate) const fn of<T: RenderObject>(
1363        setup_parent_data: fn(&mut App, HandleId, AnyRenderObject),
1364        paint_bounds: fn(&App, HandleId) -> Rect,
1365        apply_paint_transform: fn(&App, HandleId, AnyRenderObject, &mut Matrix4),
1366        perform_resize: fn(&mut App, HandleId),
1367        mark_needs_layout: fn(&mut App, HandleId),
1368        as_box: Option<fn() -> &'static crate::box_::RenderBoxVTable>,
1369        as_sliver: Option<fn() -> &'static crate::sliver::RenderSliverVTable>,
1370    ) -> RenderObjectVTable {
1371        RenderObjectVTable {
1372            object_data: |app, id| T::render_object_data(resolve(id), app),
1373            object_data_mut: |app, id| T::render_object_data_mut(resolve(id), app),
1374            visit_children: |app, id, visitor| T::visit_children(resolve(id), app, visitor),
1375            did_attach: |app, id, owner| T::did_attach(resolve(id), app, owner),
1376            did_detach: |app, id| T::did_detach(resolve(id), app),
1377            redepth_children: |app, id| T::redepth_children(resolve(id), app),
1378            setup_parent_data,
1379            sized_by_parent: |app, id| T::sized_by_parent(resolve(id), app),
1380            perform_layout: |app, id| T::perform_layout(resolve(id), app),
1381            perform_resize,
1382            mark_needs_layout,
1383            paint_bounds,
1384            apply_paint_transform,
1385            paints_child: |app, id, child| T::paints_child(resolve(id), app, child),
1386            describe_approximate_paint_clip: |app, id, child| {
1387                T::describe_approximate_paint_clip(resolve(id), app, child)
1388            },
1389            is_repaint_boundary: |app, id| T::is_repaint_boundary(resolve(id), app),
1390            always_needs_compositing: |app, id| T::always_needs_compositing(resolve(id), app),
1391            mouse_tracker_annotation: |app, id| T::mouse_tracker_annotation(resolve(id), app),
1392            update_composited_layer: |app, id, old_layer| {
1393                T::update_composited_layer(resolve(id), app, old_layer)
1394            },
1395            show_on_screen: |app, id, descendant, rect, duration, curve| {
1396                T::show_on_screen(resolve(id), app, descendant, rect, duration, curve)
1397            },
1398            interface: |id, interface| T::interface(resolve(id), interface),
1399            paint: |app, id, context, offset| T::paint(resolve(id), app, context, offset),
1400            dispose: |app, id| T::dispose(resolve(id), app),
1401            debug_fill_base_properties: |app, id, properties| {
1402                T::debug_fill_base_properties(resolve(id), app, properties)
1403            },
1404            debug_fill_properties: |app, id, properties| {
1405                T::debug_fill_properties(resolve(id), app, properties)
1406            },
1407            debug_describe_children: |app, id| T::debug_describe_children(resolve(id), app),
1408            type_name: std::any::type_name::<T>,
1409            as_box,
1410            as_sliver,
1411        }
1412    }
1413}
1414
1415/// Erased `RenderObject`: one identity and a static vtable, the fat pointer rustc cannot build
1416/// for an arena id. No lease.
1417///
1418/// Equality is Dart's `==` on an object reference.
1419#[derive(Clone, Copy)]
1420pub struct AnyRenderObject {
1421    id: HandleId,
1422    vtable: &'static RenderObjectVTable,
1423}
1424
1425impl PartialEq for AnyRenderObject {
1426    fn eq(&self, other: &AnyRenderObject) -> bool {
1427        self.id == other.id
1428    }
1429}
1430
1431impl Eq for AnyRenderObject {}
1432
1433impl Hash for AnyRenderObject {
1434    fn hash<H: Hasher>(&self, state: &mut H) {
1435        self.id.hash(state);
1436    }
1437}
1438
1439impl From<AnyRenderObject> for HandleId {
1440    fn from(object: AnyRenderObject) -> HandleId {
1441        object.id
1442    }
1443}
1444
1445impl Debug for AnyRenderObject {
1446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1447        write!(f, "AnyRenderObject({:?})", self.id)
1448    }
1449}
1450
1451impl AnyRenderObject {
1452    /// Dart's `toStringShort`: the type and identity, then what is pending: how far up the
1453    /// relayout boundary is, and the layout, paint and compositing updates it awaits.
1454    pub fn to_string_short(self, app: &App) -> String {
1455        let mut header = describe_identity(
1456            bare_type_name((self.vtable.type_name)()),
1457            self.id.identity_hash(),
1458        );
1459        let mut count = 0;
1460        let mut node = Some(self);
1461        while let Some(current) = node {
1462            match current.data(app).is_relayout_boundary {
1463                Some(true) => break,
1464                None => {
1465                    count = -1;
1466                    break;
1467                }
1468                Some(false) => {}
1469            }
1470            count += 1;
1471            node = current.parent(app);
1472        }
1473        if count > 0 {
1474            header.push_str(&format!(" relayoutBoundary=up{count}"));
1475        }
1476        let data = self.data(app);
1477        if data.needs_layout {
1478            header.push_str(" NEEDS-LAYOUT");
1479        }
1480        if data.needs_paint {
1481            header.push_str(" NEEDS-PAINT");
1482        }
1483        if data.needs_compositing_bits_update {
1484            header.push_str(" NEEDS-COMPOSITING-BITS-UPDATE");
1485        }
1486        if !self.attached(app) {
1487            header.push_str(" DETACHED");
1488        }
1489        header
1490    }
1491
1492    /// Dart's `toDiagnosticsNode(name:)`: a snapshot of this object as a dump shows it, read now,
1493    /// with its children's.
1494    pub fn to_diagnostics_node(
1495        self,
1496        app: &App,
1497        name: impl IntoPropertyName,
1498    ) -> DiagnosticableTreeNode {
1499        let mut properties = DiagnosticPropertiesBuilder::new();
1500        (self.vtable.debug_fill_base_properties)(app, self.id, &mut properties);
1501        (self.vtable.debug_fill_properties)(app, self.id, &mut properties);
1502        let children = (self.vtable.debug_describe_children)(app, self.id);
1503        DiagnosticableTreeNode::from_parts(name, self.to_string_short(app), properties, children)
1504            .with_value_id(self.id())
1505    }
1506
1507    /// Dart's `RenderObject.toStringDeep`: this object and its descendants, one property per
1508    /// line, at Dart's default level for render objects (debug) and width.
1509    pub fn to_string_deep(self, app: &App) -> String {
1510        self.to_string_deep_with(app, DiagnosticLevel::Debug)
1511    }
1512
1513    /// [`to_string_deep`](Self::to_string_deep) showing only properties at `min_level` or above.
1514    pub fn to_string_deep_with(self, app: &App, min_level: DiagnosticLevel) -> String {
1515        self.to_diagnostics_node(app, None)
1516            .to_string_deep_with("", Some(""), None, min_level, 65)
1517    }
1518
1519    /// The properties `RenderObject`'s `debugFillProperties` adds, then `RenderBox`'s or
1520    /// `RenderSliver`'s: [`RenderObject::debug_fill_base_properties`]'s default.
1521    pub(crate) fn fill_base_properties(
1522        self,
1523        app: &App,
1524        properties: &mut DiagnosticPropertiesBuilder,
1525    ) {
1526        let data = self.data(app);
1527        properties.add(
1528            FlagProperty::new("needsCompositing", data.needs_compositing)
1529                .if_true("needs compositing"),
1530        );
1531        let mut parent_data = DiagnosticsProperty::<String>::new(
1532            "parentData",
1533            data.parent_data.as_ref().map(ToString::to_string),
1534        )
1535        .missing_if_null(true);
1536        if data.debug_can_parent_use_size == Some(true) {
1537            parent_data = parent_data.tooltip("can use size");
1538        }
1539        properties.add(parent_data);
1540        if let Some(render_box) = self.as_box() {
1541            properties.add(
1542                DiagnosticsProperty::<String>::new(
1543                    "constraints",
1544                    render_box
1545                        .box_data(app)
1546                        .constraints()
1547                        .map(|c| c.to_string()),
1548                )
1549                .missing_if_null(true),
1550            );
1551        } else if let Some(sliver) = self.as_sliver() {
1552            properties.add(
1553                DiagnosticsProperty::<String>::new(
1554                    "constraints",
1555                    sliver.sliver_data(app).constraints.map(|c| c.to_string()),
1556                )
1557                .missing_if_null(true),
1558            );
1559        }
1560        properties.add(
1561            DiagnosticsProperty::<String>::new(
1562                "layer",
1563                data.layer
1564                    .layer()
1565                    .map(|layer| layer.as_layer().to_string_short(app)),
1566            )
1567            .default_value(None),
1568        );
1569        if let Some(render_box) = self.as_box() {
1570            properties.add(
1571                DiagnosticsProperty::<Size>::new("size", render_box.box_data(app).size)
1572                    .missing_if_null(true),
1573            );
1574        } else if let Some(sliver) = self.as_sliver() {
1575            properties.add(DiagnosticsProperty::<String>::new(
1576                "geometry",
1577                sliver.sliver_data(app).geometry.map(|g| g.to_string()),
1578            ));
1579        }
1580    }
1581
1582    pub(crate) fn from_vtable(
1583        id: HandleId,
1584        vtable: &'static RenderObjectVTable,
1585    ) -> AnyRenderObject {
1586        AnyRenderObject { id, vtable }
1587    }
1588
1589    /// Dart's `object as RenderBox`, as an `Option`.
1590    pub fn as_box(self) -> Option<crate::box_::AnyRenderBox> {
1591        self.vtable
1592            .as_box
1593            .map(|vtable| crate::box_::AnyRenderBox::from_vtable(self.id, vtable()))
1594    }
1595
1596    /// Dart's `object as RenderSliver`, as an `Option`.
1597    pub fn as_sliver(self) -> Option<crate::sliver::AnyRenderSliver> {
1598        self.vtable
1599            .as_sliver
1600            .map(|vtable| crate::sliver::AnyRenderSliver::from_vtable(self.id, vtable()))
1601    }
1602
1603    /// The render object that is actively computing layout.
1604    ///
1605    /// Only meaningful when asserts are enabled.
1606    pub fn debug_active_layout() -> Option<AnyRenderObject> {
1607        DEBUG_ACTIVE_LAYOUT.get()
1608    }
1609
1610    pub(crate) fn set_debug_active_layout(node: Option<AnyRenderObject>) {
1611        DEBUG_ACTIVE_LAYOUT.set(node);
1612    }
1613
1614    /// The render object that is actively painting.
1615    ///
1616    /// Only meaningful when asserts are enabled.
1617    pub fn debug_active_paint() -> Option<AnyRenderObject> {
1618        DEBUG_ACTIVE_PAINT.get()
1619    }
1620
1621    fn data(self, app: &App) -> &RenderObjectData {
1622        (self.vtable.object_data)(app, self.id)
1623    }
1624
1625    pub(crate) fn data_mut(self, app: &mut App) -> &mut RenderObjectData {
1626        (self.vtable.object_data_mut)(app, self.id)
1627    }
1628
1629    /// Data for use by the parent render object.
1630    pub fn parent_data(self, app: &App) -> Option<&dyn ParentData> {
1631        self.data(app).parent_data.as_deref()
1632    }
1633
1634    /// Mutable parent data.
1635    pub fn parent_data_mut(self, app: &mut App) -> Option<&mut dyn ParentData> {
1636        self.data_mut(app).parent_data.as_deref_mut()
1637    }
1638
1639    /// Dart's `parentData is P`: whether parent data is a `P`, or a subclass embedding the `P`
1640    /// half ([`ParentData::provide`]).
1641    pub fn parent_data_is<P: ParentData + 'static>(self, app: &App) -> bool {
1642        self.parent_data(app)
1643            .is_some_and(|data| data.part::<P>().is_some())
1644    }
1645
1646    /// Dart's `parentData! as P`: the parent data when it is a `P`, or the `P` half a subclass
1647    /// embeds ([`ParentData::provide`]), as `SliverGridParentData` embeds
1648    /// `SliverMultiBoxAdaptorParentData`.
1649    ///
1650    /// # Panics
1651    ///
1652    /// If parent data is missing, or neither `P` nor a subclass of it.
1653    pub fn parent_data_of<P: ParentData + 'static>(self, app: &App) -> &P {
1654        self.parent_data(app)
1655            .and_then(|data| data.part::<P>())
1656            .unwrap_or_else(|| panic!("parent data is not {}", std::any::type_name::<P>()))
1657    }
1658
1659    /// See [`parent_data_of`](Self::parent_data_of).
1660    pub fn parent_data_of_mut<P: ParentData + 'static>(self, app: &mut App) -> &mut P {
1661        self.parent_data_mut(app)
1662            .and_then(|data| data.part_mut::<P>())
1663            .unwrap_or_else(|| panic!("parent data is not {}", std::any::type_name::<P>()))
1664    }
1665
1666    /// Installs parent data. Dart's `child.parentData = …`.
1667    pub fn set_parent_data(self, app: &mut App, parent_data: impl ParentData + 'static) {
1668        self.data_mut(app).parent_data = Some(Box::new(parent_data));
1669    }
1670
1671    fn clear_parent_data(self, app: &mut App) {
1672        self.data_mut(app).parent_data = None;
1673    }
1674
1675    /// The parent of this render object in the render tree.
1676    pub fn parent(self, app: &App) -> Option<AnyRenderObject> {
1677        self.data(app).parent
1678    }
1679
1680    fn set_parent(self, app: &mut App, parent: Option<AnyRenderObject>) {
1681        self.data_mut(app).parent = parent;
1682    }
1683
1684    /// The owner for this render object (`None` if unattached).
1685    pub fn owner(self, app: &App) -> Option<Handle<PipelineOwner>> {
1686        self.data(app).owner
1687    }
1688
1689    /// Whether this render object belongs to a [`PipelineOwner`].
1690    pub fn attached(self, app: &App) -> bool {
1691        self.owner(app).is_some()
1692    }
1693
1694    /// The depth of this render object in the render tree.
1695    pub fn depth(self, app: &App) -> i32 {
1696        self.data(app).depth
1697    }
1698
1699    fn set_depth(self, app: &mut App, depth: i32) {
1700        self.data_mut(app).depth = depth;
1701    }
1702
1703    pub(crate) fn needs_layout(self, app: &App) -> bool {
1704        self.data(app).needs_layout
1705    }
1706
1707    fn set_needs_layout(self, app: &mut App, value: bool) {
1708        self.data_mut(app).needs_layout = value;
1709    }
1710
1711    /// Whether this render object's layout information is dirty.
1712    ///
1713    /// Always `false` when debug assertions are disabled.
1714    pub fn debug_needs_layout(self, app: &App) -> bool {
1715        if !cfg!(debug_assertions) {
1716            return false;
1717        }
1718        self.needs_layout(app)
1719    }
1720
1721    pub(crate) fn is_relayout_boundary(self, app: &App) -> Option<bool> {
1722        self.data(app).is_relayout_boundary
1723    }
1724
1725    fn set_is_relayout_boundary(self, app: &mut App, value: Option<bool>) {
1726        self.data_mut(app).is_relayout_boundary = value;
1727    }
1728
1729    fn doing_this_layout_with_callback(self, app: &App) -> bool {
1730        self.data(app).doing_this_layout_with_callback
1731    }
1732
1733    pub(crate) fn debug_doing_this_layout(self, app: &App) -> bool {
1734        self.data(app).debug_doing_this_layout
1735    }
1736
1737    fn set_debug_doing_this_layout(self, app: &mut App, value: bool) {
1738        self.data_mut(app).debug_doing_this_layout = value;
1739    }
1740
1741    pub(crate) fn debug_doing_this_resize(self, app: &App) -> bool {
1742        self.data(app).debug_doing_this_resize
1743    }
1744
1745    fn set_debug_doing_this_resize(self, app: &mut App, value: bool) {
1746        self.data_mut(app).debug_doing_this_resize = value;
1747    }
1748
1749    fn set_debug_can_parent_use_size(self, app: &mut App, value: Option<bool>) {
1750        self.data_mut(app).debug_can_parent_use_size = value;
1751    }
1752
1753    fn debug_mutations_locked(self, app: &App) -> bool {
1754        self.data(app).debug_mutations_locked
1755    }
1756
1757    fn set_debug_mutations_locked(self, app: &mut App, value: bool) {
1758        self.data_mut(app).debug_mutations_locked = value;
1759    }
1760
1761    fn sized_by_parent(self, app: &App) -> bool {
1762        (self.vtable.sized_by_parent)(app, self.id)
1763    }
1764
1765    /// Calls `visitor` for each immediate child.
1766    pub fn visit_children(self, app: &App, visitor: &mut dyn FnMut(AnyRenderObject)) {
1767        (self.vtable.visit_children)(app, self.id, visitor)
1768    }
1769
1770    /// Override point used by [`adopt_child`](Self::adopt_child).
1771    pub fn setup_parent_data(self, app: &mut App, child: AnyRenderObject) {
1772        (self.vtable.setup_parent_data)(app, self.id, child)
1773    }
1774
1775    /// Adjust the depth of `child` to be greater than this node's own depth.
1776    pub fn redepth_child(self, app: &mut App, child: AnyRenderObject) {
1777        debug_assert_eq!(child.owner(app), self.owner(app));
1778        child.redepth_below(app, self.depth(app));
1779    }
1780
1781    /// Flutter's `redepthChild` from the child's side: `parent_depth` is the parent's depth.
1782    pub(crate) fn redepth_below(self, app: &mut App, parent_depth: i32) {
1783        if self.depth(app) <= parent_depth {
1784            self.set_depth(app, parent_depth + 1);
1785            (self.vtable.redepth_children)(app, self.id);
1786        }
1787    }
1788
1789    /// Called by subclasses when they decide a render object is a child.
1790    pub fn adopt_child(self, app: &mut App, child: AnyRenderObject) {
1791        debug_assert!(child.parent(app).is_none());
1792        if cfg!(debug_assertions) {
1793            let mut node = Some(self);
1794            while let Some(current) = node {
1795                debug_assert_ne!(current, child, "adopt_child would create a cycle");
1796                node = current.parent(app);
1797            }
1798        }
1799        self.setup_parent_data(app, child);
1800        self.mark_needs_layout(app);
1801        self.mark_needs_compositing_bits_update(app);
1802        child.set_parent(app, Some(self));
1803        if self.attached(app) {
1804            child.attach(app, self.owner(app).expect("attached parent has an owner"));
1805        }
1806        self.redepth_child(app, child);
1807    }
1808
1809    /// Called by subclasses when they decide a render object is no longer a child.
1810    pub fn drop_child(self, app: &mut App, child: AnyRenderObject) {
1811        debug_assert_eq!(child.parent(app), Some(self));
1812        debug_assert_eq!(child.attached(app), self.attached(app));
1813        debug_assert!(child.parent_data(app).is_some());
1814        if !child.is_relayout_boundary(app).unwrap_or(true) {
1815            child.set_is_relayout_boundary(app, None);
1816        }
1817        if let Some(parent_data) = child.parent_data_mut(app) {
1818            parent_data.detach();
1819        }
1820        child.clear_parent_data(app);
1821        child.set_parent(app, None);
1822        if self.attached(app) {
1823            child.detach(app);
1824        }
1825        self.mark_needs_layout(app);
1826        self.mark_needs_compositing_bits_update(app);
1827    }
1828
1829    /// Mark this render object as attached to `owner`.
1830    ///
1831    /// Flutter's `RenderObject.attach` body, then the [`RenderObject::did_attach`] hook, which
1832    /// by default attaches the children.
1833    pub fn attach(self, app: &mut App, owner: Handle<PipelineOwner>) {
1834        debug_assert!(
1835            !app.is_disposed(self.id),
1836            "attach on a disposed render object"
1837        );
1838        debug_assert!(self.owner(app).is_none());
1839        self.data_mut(app).owner = Some(owner);
1840        if self.needs_layout(app) && self.is_relayout_boundary(app).is_some() {
1841            self.set_needs_layout(app, false);
1842            self.mark_needs_layout(app);
1843        }
1844        if self.needs_compositing_bits_update(app) {
1845            self.set_needs_compositing_bits_update(app, false);
1846            self.mark_needs_compositing_bits_update(app);
1847        }
1848        if self.needs_paint(app) && self.layer(app).is_some() {
1849            self.set_needs_paint(app, false);
1850            self.mark_needs_paint(app);
1851        }
1852        (self.vtable.did_attach)(app, self.id, owner)
1853    }
1854
1855    /// Mark this render object as detached from its [`PipelineOwner`].
1856    ///
1857    /// Flutter's `RenderObject.detach` body, then the [`RenderObject::did_detach`] hook, which
1858    /// by default detaches the children.
1859    pub fn detach(self, app: &mut App) {
1860        debug_assert!(self.owner(app).is_some());
1861        self.data_mut(app).owner = None;
1862        debug_assert!(
1863            self.parent(app).is_none()
1864                || self.attached(app)
1865                    == self.parent(app).is_some_and(|parent| parent.attached(app))
1866        );
1867        (self.vtable.did_detach)(app, self.id)
1868    }
1869
1870    /// Mark this render object's layout information as dirty.
1871    ///
1872    /// The box protocol overrides this with [`crate::RenderBox::mark_needs_layout`], which
1873    /// clears the intrinsics and dry-layout caches first.
1874    pub fn mark_needs_layout(self, app: &mut App) {
1875        debug_assert!(
1876            !app.is_disposed(self.id),
1877            "mark_needs_layout on a disposed render object"
1878        );
1879        (self.vtable.mark_needs_layout)(app, self.id)
1880    }
1881
1882    /// Mark this render object's layout information as dirty, and then defer to
1883    /// the parent.
1884    pub fn mark_parent_needs_layout(self, app: &mut App) {
1885        self.set_needs_layout(app, true);
1886        let parent = self
1887            .parent(app)
1888            .expect("mark_parent_needs_layout requires a parent");
1889        if !self.doing_this_layout_with_callback(app) {
1890            parent.mark_needs_layout(app);
1891        } else {
1892            debug_assert!(parent.debug_doing_this_layout(app));
1893        }
1894        debug_assert_eq!(Some(parent), self.parent(app));
1895    }
1896
1897    /// Mark layout dirty and also mark the parent, for a `sized_by_parent` change.
1898    /// Allows mutations to be made to this object's child list (and any descendants) as
1899    /// well as to any other dirty nodes in the render tree owned by the same `PipelineOwner`
1900    /// as this object. The `callback` argument is invoked synchronously, and the mutations
1901    /// are allowed only during that callback's execution.
1902    ///
1903    /// This exists to allow child lists to be built on-demand during layout (e.g. based on
1904    /// the object's size), and to enable nodes to be moved around the tree as this happens
1905    /// (e.g. to handle `GlobalKey` reparenting), while still ensuring that any particular
1906    /// node is only laid out once per frame.
1907    ///
1908    /// Calling this function disables a number of asserts that are intended to catch likely
1909    /// bugs. As such, using this function is generally discouraged.
1910    ///
1911    /// This function can only be called during layout.
1912    pub fn invoke_layout_callback(self, app: &mut App, callback: impl FnOnce(&mut App)) {
1913        debug_assert!(self.debug_mutations_locked(app));
1914        debug_assert!(self.debug_doing_this_layout(app));
1915        debug_assert!(!self.doing_this_layout_with_callback(app));
1916        self.data_mut(app).doing_this_layout_with_callback = true;
1917        let owner = self.owner(app).expect("a laying-out object is attached");
1918        owner.enable_mutations_to_dirty_subtrees(app, callback);
1919        self.data_mut(app).doing_this_layout_with_callback = false;
1920    }
1921
1922    pub fn mark_needs_layout_for_sized_by_parent_change(self, app: &mut App) {
1923        self.mark_needs_layout(app);
1924        self.mark_parent_needs_layout(app);
1925    }
1926
1927    /// Bootstrap the rendering pipeline by scheduling the very first layout.
1928    pub fn schedule_initial_layout(self, app: &mut App) {
1929        debug_assert!(self.attached(app));
1930        debug_assert!(self.parent(app).is_none());
1931        debug_assert!(!self.owner(app).expect("attached").debug_doing_layout(app));
1932        debug_assert!(self.is_relayout_boundary(app).is_none());
1933        self.set_is_relayout_boundary(app, Some(true));
1934        if cfg!(debug_assertions) {
1935            self.set_debug_can_parent_use_size(app, Some(false));
1936        }
1937        let owner = self.owner(app).expect("attached");
1938        owner.add_node_needing_layout(app, self);
1939    }
1940
1941    pub(crate) fn layout_without_resize(self, app: &mut App) {
1942        debug_assert!(self.needs_layout(app));
1943        debug_assert!(self.is_relayout_boundary(app).unwrap_or(false));
1944        let perform_layout = self.vtable.perform_layout;
1945        let previous = if cfg!(debug_assertions) {
1946            debug_assert!(!self.doing_this_layout_with_callback(app));
1947            self.set_debug_mutations_locked(app, true);
1948            self.set_debug_doing_this_layout(app, true);
1949            let previous = AnyRenderObject::debug_active_layout();
1950            AnyRenderObject::set_debug_active_layout(Some(self));
1951            if crate::debug::debug_print_layouts(app) {
1952                eprintln!("Laying out (without resize) {self:?}");
1953            }
1954            previous
1955        } else {
1956            None
1957        };
1958        perform_layout(app, self.id);
1959        if cfg!(debug_assertions) {
1960            AnyRenderObject::set_debug_active_layout(previous);
1961            self.set_debug_doing_this_layout(app, false);
1962            self.set_debug_mutations_locked(app, false);
1963        }
1964        self.set_needs_layout(app, false);
1965        self.mark_needs_paint(app);
1966    }
1967
1968    /// Shared `layout` body. Protocol types store their own constraints.
1969    pub(crate) fn run_layout(
1970        self,
1971        app: &mut App,
1972        parent_uses_size: bool,
1973        constraints_tight: bool,
1974        same_constraints: bool,
1975        store_constraints: impl FnOnce(&mut App),
1976    ) {
1977        debug_assert!(!self.debug_doing_this_resize(app));
1978        debug_assert!(!self.debug_doing_this_layout(app));
1979        if cfg!(debug_assertions) {
1980            self.set_debug_can_parent_use_size(app, Some(parent_uses_size));
1981        }
1982
1983        let sized_by_parent = self.sized_by_parent(app);
1984        self.set_is_relayout_boundary(
1985            app,
1986            Some(
1987                !parent_uses_size
1988                    || sized_by_parent
1989                    || constraints_tight
1990                    || self.parent(app).is_none(),
1991            ),
1992        );
1993        if !self.needs_layout(app) && same_constraints {
1994            return;
1995        }
1996        store_constraints(app);
1997
1998        if sized_by_parent {
1999            if cfg!(debug_assertions) {
2000                self.set_debug_doing_this_resize(app, true);
2001            }
2002            (self.vtable.perform_resize)(app, self.id);
2003            if cfg!(debug_assertions) {
2004                self.set_debug_doing_this_resize(app, false);
2005            }
2006        }
2007
2008        let previous = if cfg!(debug_assertions) {
2009            debug_assert!(!self.doing_this_layout_with_callback(app));
2010            self.set_debug_mutations_locked(app, true);
2011            self.set_debug_doing_this_layout(app, true);
2012            let previous = AnyRenderObject::debug_active_layout();
2013            AnyRenderObject::set_debug_active_layout(Some(self));
2014            if crate::debug::debug_print_layouts(app) {
2015                eprintln!(
2016                    "Laying out ({}) {self:?}",
2017                    if sized_by_parent {
2018                        "with separate resize"
2019                    } else {
2020                        "with resize allowed"
2021                    }
2022                );
2023            }
2024            previous
2025        } else {
2026            None
2027        };
2028        (self.vtable.perform_layout)(app, self.id);
2029        if cfg!(debug_assertions) {
2030            AnyRenderObject::set_debug_active_layout(previous);
2031            self.set_debug_doing_this_layout(app, false);
2032            self.set_debug_mutations_locked(app, false);
2033        }
2034        self.set_needs_layout(app, false);
2035        self.mark_needs_paint(app);
2036    }
2037
2038    // ---- paint ------------------------------------------------------------------------------
2039
2040    pub(crate) fn needs_paint(self, app: &App) -> bool {
2041        self.data(app).needs_paint
2042    }
2043
2044    fn set_needs_paint(self, app: &mut App, value: bool) {
2045        self.data_mut(app).needs_paint = value;
2046    }
2047
2048    /// Whether this render object's paint information is dirty.
2049    ///
2050    /// Always `false` when debug assertions are disabled.
2051    pub fn debug_needs_paint(self, app: &App) -> bool {
2052        if !cfg!(debug_assertions) {
2053            return false;
2054        }
2055        self.needs_paint(app)
2056    }
2057
2058    pub(crate) fn needs_composited_layer_update(self, app: &App) -> bool {
2059        self.data(app).needs_composited_layer_update
2060    }
2061
2062    pub(crate) fn set_needs_composited_layer_update(self, app: &mut App, value: bool) {
2063        self.data_mut(app).needs_composited_layer_update = value;
2064    }
2065
2066    /// Whether this render object's layer information is dirty.
2067    ///
2068    /// Always `false` when debug assertions are disabled.
2069    pub fn debug_needs_composited_layer_update(self, app: &App) -> bool {
2070        if !cfg!(debug_assertions) {
2071            return false;
2072        }
2073        self.needs_composited_layer_update(app)
2074    }
2075
2076    pub(crate) fn was_repaint_boundary(self, app: &App) -> bool {
2077        self.data(app).was_repaint_boundary
2078    }
2079
2080    /// The arena id behind this handle.
2081    pub fn id(self) -> HandleId {
2082        self.id
2083    }
2084
2085    /// Dart's `renderObject as T`: the typed handle when this object is a `T`, else `None`.
2086    pub fn downcast<T: RenderObject>(self, app: &App) -> Option<RenderHandle<T>> {
2087        app.handle::<T>(self.id).map(RenderHandle::from_handle)
2088    }
2089
2090    /// Release any resources held by this render object, and the tree's part of its arena entry,
2091    /// after the virtual [`RenderObject::dispose`]. The entry is freed at the next checkpoint,
2092    /// unless something else keeps it (a cached hit-test path, the mouse tracker).
2093    ///
2094    /// The object must be detached. Its parent may still hold a handle to it: the widget layer
2095    /// unmounts bottom-up and disposes the parent next, as Dart does.
2096    pub fn dispose(self, app: &mut App) {
2097        debug_assert!(!self.attached(app));
2098        (self.vtable.dispose)(app, self.id);
2099        app.release_tree_node(self.id);
2100    }
2101
2102    /// Whether this render object repaints separately from its parent.
2103    pub fn is_repaint_boundary(self, app: &App) -> bool {
2104        (self.vtable.is_repaint_boundary)(app, self.id)
2105    }
2106
2107    /// An estimate of the bounds within which this render object will paint.
2108    pub fn paint_bounds(self, app: &App) -> Rect {
2109        (self.vtable.paint_bounds)(app, self.id)
2110    }
2111
2112    /// See [`RenderObject::apply_paint_transform`].
2113    pub fn apply_paint_transform(self, app: &App, child: AnyRenderObject, transform: &mut Matrix4) {
2114        (self.vtable.apply_paint_transform)(app, self.id, child, transform)
2115    }
2116
2117    /// See [`RenderObject::describe_approximate_paint_clip`].
2118    pub fn describe_approximate_paint_clip(
2119        self,
2120        app: &App,
2121        child: AnyRenderObject,
2122    ) -> Option<Rect> {
2123        (self.vtable.describe_approximate_paint_clip)(app, self.id, child)
2124    }
2125
2126    /// See [`RenderObject::paints_child`].
2127    pub fn paints_child(self, app: &App, child: AnyRenderObject) -> bool {
2128        (self.vtable.paints_child)(app, self.id, child)
2129    }
2130
2131    /// Applies the paint transform from this [`AnyRenderObject`] to the `target`
2132    /// [`AnyRenderObject`].
2133    ///
2134    /// Returns a matrix that maps the local paint coordinate system to the coordinate system
2135    /// of `target`, or a `Matrix4::zero()` if the paint transform can not be computed.
2136    ///
2137    /// This method throws an exception when the `target` is not in the same render tree as
2138    /// this render object.
2139    ///
2140    /// The `target` argument defaults to the root of the render tree (`None`).
2141    pub fn get_transform_to(self, app: &App, target: Option<AnyRenderObject>) -> Matrix4 {
2142        debug_assert!(self.attached(app));
2143        // The paths from to fromRenderObject and toRenderObject's common ancestor.
2144        // Each list's length is greater than 1 if not null.
2145        //
2146        // [this, ...., commonAncestorRenderObject], or null if `this` is the common
2147        // ancestor.
2148        let mut from_path: Option<Vec<AnyRenderObject>> = None;
2149        // [target, ...., commonAncestorRenderObject], or null if `target` is the
2150        // common ancestor.
2151        let mut to_path: Option<Vec<AnyRenderObject>> = None;
2152
2153        let mut from = self;
2154        let mut to = target.unwrap_or_else(|| {
2155            self.owner(app)
2156                .and_then(|owner| owner.root_node(app))
2157                .expect("an attached render object has a root")
2158        });
2159
2160        while from != to {
2161            let from_depth = from.depth(app);
2162            let to_depth = to.depth(app);
2163
2164            if from_depth >= to_depth {
2165                let from_parent = from.parent(app).unwrap_or_else(|| {
2166                    panic!("{target:?} and {self:?} are not in the same render tree.")
2167                });
2168                from_path
2169                    .get_or_insert_with(|| vec![self])
2170                    .push(from_parent);
2171                from = from_parent;
2172            }
2173            if from_depth <= to_depth {
2174                let to_parent = to.parent(app).unwrap_or_else(|| {
2175                    panic!("{target:?} and {self:?} are not in the same render tree.")
2176                });
2177                debug_assert!(
2178                    target.is_some(),
2179                    "{self:?} has a depth that is less than or equal to the root node"
2180                );
2181                to_path
2182                    .get_or_insert_with(|| vec![target.expect("checked above")])
2183                    .push(to_parent);
2184                to = to_parent;
2185            }
2186        }
2187
2188        let mut from_transform: Option<Matrix4> = None;
2189        if let Some(from_path) = &from_path {
2190            debug_assert!(from_path.len() > 1);
2191            let mut transform = Matrix4::IDENTITY;
2192            let last_index = if target.is_none() {
2193                from_path.len() - 2
2194            } else {
2195                from_path.len() - 1
2196            };
2197            for index in (1..=last_index).rev() {
2198                from_path[index].apply_paint_transform(app, from_path[index - 1], &mut transform);
2199            }
2200            from_transform = Some(transform);
2201        }
2202        let Some(to_path) = to_path else {
2203            return from_transform.unwrap_or(Matrix4::IDENTITY);
2204        };
2205
2206        debug_assert!(to_path.len() > 1);
2207        let mut to_transform = Matrix4::IDENTITY;
2208        for index in (1..to_path.len()).rev() {
2209            to_path[index].apply_paint_transform(app, to_path[index - 1], &mut to_transform);
2210        }
2211        let Some(to_transform) = to_transform.invert() else {
2212            // If the matrix is singular then `invert()` doesn't do anything.
2213            return zero_matrix();
2214        };
2215        match from_transform {
2216            Some(mut from_transform) => {
2217                multiply(&mut from_transform, &to_transform);
2218                from_transform
2219            }
2220            None => to_transform,
2221        }
2222    }
2223
2224    /// See [`RenderObject::mouse_tracker_annotation`]. Also `None` once the object has left
2225    /// the arena, which the tracker's `Ref`s on what it remembers keep from happening.
2226    pub fn mouse_tracker_annotation(self, app: &App) -> Option<MouseTrackerAnnotation> {
2227        if !app.contains(self.id) {
2228            return None;
2229        }
2230        (self.vtable.mouse_tracker_annotation)(app, self.id)
2231    }
2232
2233    /// See [`RenderObject::interface`]: Dart's `object is RenderAbstractViewport`, as
2234    /// `interface::<AnyRenderAbstractViewport>()`.
2235    pub fn interface<I: 'static>(self) -> Option<I> {
2236        (self.vtable.interface)(self.id, TypeId::of::<I>())?
2237            .downcast()
2238            .ok()
2239            .map(|handle| *handle)
2240    }
2241
2242    /// See [`RenderObject::show_on_screen`].
2243    pub fn show_on_screen(
2244        self,
2245        app: &mut App,
2246        descendant: Option<AnyRenderObject>,
2247        rect: Option<Rect>,
2248        duration: Duration,
2249        curve: Rc<dyn Curve>,
2250    ) {
2251        (self.vtable.show_on_screen)(app, self.id, descendant, rect, duration, curve)
2252    }
2253
2254    /// See [`RenderObject::update_composited_layer`].
2255    pub fn update_composited_layer(
2256        self,
2257        app: &mut App,
2258        old_layer: Option<AnyOffsetLayer>,
2259    ) -> AnyOffsetLayer {
2260        (self.vtable.update_composited_layer)(app, self.id, old_layer)
2261    }
2262
2263    /// Whether this render object always needs compositing.
2264    pub fn always_needs_compositing(self, app: &App) -> bool {
2265        (self.vtable.always_needs_compositing)(app, self.id)
2266    }
2267
2268    /// The compositing layer that this render object uses to repaint.
2269    ///
2270    /// If this render object is not a repaint boundary, it is the responsibility
2271    /// of the [`RenderObject::paint`] method to populate this field. If
2272    /// [`needs_compositing`](Self::needs_compositing) is true, this field may be populated with
2273    /// the root-most layer used by the render object implementation. When repainting, instead of
2274    /// creating a new layer the render object may update the layer stored in this field for
2275    /// better performance. It is also OK to leave this field as `None` and create a new layer
2276    /// on every repaint, but without the performance benefit. If [`needs_compositing`](Self::needs_compositing)
2277    /// is false, this field must be set to `None` either by never populating this field, or by
2278    /// setting it to `None` when the value of [`needs_compositing`](Self::needs_compositing)
2279    /// changes from true to false.
2280    ///
2281    /// If this render object is a repaint boundary, the framework automatically
2282    /// creates an [`OffsetLayer`] and populates this field prior to calling the
2283    /// [`RenderObject::paint`] method. The paint method must not replace the value of this
2284    /// field.
2285    pub fn layer(self, app: &App) -> Option<AnyContainerLayer> {
2286        debug_assert!(
2287            !self.is_repaint_boundary(app)
2288                || self.data(app).layer.layer().is_none()
2289                || self
2290                    .data(app)
2291                    .layer
2292                    .layer()
2293                    .is_some_and(|layer| layer.as_offset_layer().is_some())
2294        );
2295        self.data(app).layer.layer()
2296    }
2297
2298    /// Dart's `layer = newLayer`. The setter asserts this is not a repaint boundary: the
2299    /// framework creates and assigns an [`OffsetLayer`] to a repaint boundary automatically.
2300    pub fn set_layer(self, app: &mut App, new_layer: Option<AnyContainerLayer>) {
2301        debug_assert!(
2302            !self.is_repaint_boundary(app),
2303            "Attempted to set a layer to a repaint boundary render object.\n\
2304             The framework creates and assigns an OffsetLayer to a repaint \
2305             boundary automatically."
2306        );
2307        LayerHandle::set_layer(app, |app| &mut self.data_mut(app).layer, new_layer);
2308    }
2309
2310    /// Dart's `layer as T?`.
2311    pub fn layer_as<T: 'static>(self, app: &App) -> Option<Handle<T>> {
2312        self.layer(app)
2313            .and_then(|layer| app.handle::<T>(layer.id()))
2314    }
2315
2316    /// In debug mode, the compositing layer that this render object uses to repaint.
2317    ///
2318    /// This getter is intended for debugging purposes only. In release builds, it
2319    /// always returns `None`. In debug builds, it returns the layer even if the layer
2320    /// is dirty.
2321    ///
2322    /// For production code, consider [`layer`](Self::layer).
2323    pub fn debug_layer(self, app: &App) -> Option<AnyContainerLayer> {
2324        if !cfg!(debug_assertions) {
2325            return None;
2326        }
2327        self.data(app).layer.layer()
2328    }
2329
2330    pub(crate) fn needs_compositing_bits_update(self, app: &App) -> bool {
2331        self.data(app).needs_compositing_bits_update
2332    }
2333
2334    fn set_needs_compositing_bits_update(self, app: &mut App, value: bool) {
2335        self.data_mut(app).needs_compositing_bits_update = value;
2336    }
2337
2338    /// Mark the compositing state for this render object as dirty.
2339    ///
2340    /// This is called to indicate that the value for [`needs_compositing`](Self::needs_compositing)
2341    /// needs to be recomputed during the next [`PipelineOwner::flush_compositing_bits`] engine
2342    /// phase.
2343    ///
2344    /// When the subtree is mutated, we need to recompute our
2345    /// [`needs_compositing`](Self::needs_compositing) bit, and some of our ancestors need to do
2346    /// the same (in case ours changed in a way that will change theirs). To this end,
2347    /// [`adopt_child`](Self::adopt_child) and [`drop_child`](Self::drop_child) call this method,
2348    /// and, as necessary, this method calls the parent's, etc, walking up the tree to mark all
2349    /// the nodes that need updating.
2350    ///
2351    /// This method does not schedule a rendering frame, because since it cannot be the case
2352    /// that _only_ the compositing bits changed, something else will have scheduled a frame for
2353    /// us.
2354    pub fn mark_needs_compositing_bits_update(self, app: &mut App) {
2355        debug_assert!(
2356            !app.is_disposed(self.id),
2357            "mark_needs_compositing_bits_update on a disposed render object"
2358        );
2359        if self.needs_compositing_bits_update(app) {
2360            return;
2361        }
2362        self.set_needs_compositing_bits_update(app, true);
2363        if let Some(parent) = self.parent(app) {
2364            if parent.needs_compositing_bits_update(app) {
2365                return;
2366            }
2367            // The parent last counted this node by its own compositing bit, which goes stale
2368            // in `was_repaint_boundary` when a node stops being a boundary while it is not
2369            // painted.
2370            if (!self.data(app).needs_compositing || !self.is_repaint_boundary(app))
2371                && !parent.is_repaint_boundary(app)
2372            {
2373                parent.mark_needs_compositing_bits_update(app);
2374                return;
2375            }
2376        }
2377        // parent is fine (or there isn't one), but we are dirty
2378        if let Some(owner) = self.owner(app) {
2379            owner.add_node_needing_compositing_bits_update(app, self);
2380        }
2381    }
2382
2383    /// Whether we or one of our descendants has a compositing layer.
2384    ///
2385    /// If this node needs compositing as indicated by this bit, then all ancestor
2386    /// nodes will also need compositing.
2387    ///
2388    /// Only legal to call after [`PipelineOwner::flush_layout`] and
2389    /// [`PipelineOwner::flush_compositing_bits`] have been called.
2390    pub fn needs_compositing(self, app: &App) -> bool {
2391        debug_assert!(
2392            !self.needs_compositing_bits_update(app),
2393            "make sure we don't use this bit when it is dirty"
2394        );
2395        self.data(app).needs_compositing
2396    }
2397
2398    /// Flutter's `_updateCompositingBits`.
2399    pub(crate) fn update_compositing_bits(self, app: &mut App) {
2400        if !self.needs_compositing_bits_update(app) {
2401            return;
2402        }
2403        let old_needs_compositing = self.data(app).needs_compositing;
2404        self.data_mut(app).needs_compositing = false;
2405        let mut children = Vec::new();
2406        self.visit_children(app, &mut |child| children.push(child));
2407        for child in children {
2408            child.update_compositing_bits(app);
2409            if child.needs_compositing(app) {
2410                self.data_mut(app).needs_compositing = true;
2411            }
2412        }
2413        if self.is_repaint_boundary(app) || self.always_needs_compositing(app) {
2414            self.data_mut(app).needs_compositing = true;
2415        }
2416        // If a node was previously a repaint boundary, but no longer is one, then
2417        // regardless of its compositing state we need to find a new parent to
2418        // paint from. To do this, we mark it clean again so that the traversal
2419        // in markNeedsPaint is not short-circuited. It is removed from _nodesNeedingPaint
2420        // so that we do not attempt to paint from it after locating a parent.
2421        if !self.is_repaint_boundary(app) && self.was_repaint_boundary(app) {
2422            self.set_needs_paint(app, false);
2423            self.set_needs_composited_layer_update(app, false);
2424            if let Some(owner) = self.owner(app) {
2425                owner.remove_node_needing_paint(app, self);
2426            }
2427            self.set_needs_compositing_bits_update(app, false);
2428            self.mark_needs_paint(app);
2429        } else if old_needs_compositing != self.data(app).needs_compositing {
2430            self.set_needs_compositing_bits_update(app, false);
2431            self.mark_needs_paint(app);
2432        } else {
2433            self.set_needs_compositing_bits_update(app, false);
2434        }
2435    }
2436
2437    /// Mark this render object as having changed its visual appearance.
2438    ///
2439    /// Rather than eagerly updating this render object's display list in response to writes,
2440    /// we instead mark the render object as needing to paint, which schedules a visual update.
2441    /// As part of the visual update, the rendering pipeline will give this render object an
2442    /// opportunity to update its display list.
2443    pub fn mark_needs_paint(self, app: &mut App) {
2444        debug_assert!(
2445            !app.is_disposed(self.id),
2446            "mark_needs_paint on a disposed render object"
2447        );
2448        debug_assert!(
2449            self.owner(app)
2450                .is_none_or(|owner| !owner.debug_doing_paint(app))
2451        );
2452        if self.needs_paint(app) {
2453            return;
2454        }
2455        self.set_needs_paint(app, true);
2456        if self.is_repaint_boundary(app) && self.was_repaint_boundary(app) {
2457            if crate::debug::debug_print_mark_needs_paint_stacks(app) {
2458                eprintln!("markNeedsPaint() called for {self:?}");
2459            }
2460            debug_assert!(
2461                self.layer(app)
2462                    .is_some_and(|layer| layer.as_offset_layer().is_some())
2463            );
2464            if let Some(owner) = self.owner(app) {
2465                owner.add_node_needing_paint(app, self);
2466                owner.request_visual_update(app);
2467            }
2468        } else if let Some(parent) = self.parent(app) {
2469            parent.mark_needs_paint(app);
2470        } else {
2471            if crate::debug::debug_print_mark_needs_paint_stacks(app) {
2472                eprintln!("markNeedsPaint() called for {self:?} (root of render tree)");
2473            }
2474            if let Some(owner) = self.owner(app) {
2475                owner.request_visual_update(app);
2476            }
2477        }
2478    }
2479
2480    /// Mark this render object as having changed a property on its composited
2481    /// layer.
2482    ///
2483    /// Render objects that have a composited layer have [`is_repaint_boundary`](Self::is_repaint_boundary)
2484    /// equal to true may update the properties of that composited layer without repainting
2485    /// their children. If this render object is a repaint boundary but does
2486    /// not yet have a composited layer created for it, this method will instead
2487    /// mark the nearest repaint boundary parent as needing to be painted.
2488    ///
2489    /// If this method is called on a render object that is not a repaint boundary
2490    /// or is a repaint boundary but hasn't been composited yet, it is equivalent
2491    /// to calling [`mark_needs_paint`](Self::mark_needs_paint).
2492    pub fn mark_needs_composited_layer_update(self, app: &mut App) {
2493        debug_assert!(
2494            !app.is_disposed(self.id),
2495            "mark_needs_composited_layer_update on a disposed render object"
2496        );
2497        debug_assert!(
2498            self.owner(app)
2499                .is_none_or(|owner| !owner.debug_doing_paint(app))
2500        );
2501        if self.needs_composited_layer_update(app) || self.needs_paint(app) {
2502            return;
2503        }
2504        self.set_needs_composited_layer_update(app, true);
2505        if self.is_repaint_boundary(app) && self.was_repaint_boundary(app) {
2506            debug_assert!(self.layer(app).is_some());
2507            if let Some(owner) = self.owner(app) {
2508                owner.add_node_needing_paint(app, self);
2509                owner.request_visual_update(app);
2510            }
2511        } else {
2512            self.mark_needs_paint(app);
2513        }
2514    }
2515
2516    /// Flutter's `_skippedPaintingOnLayer`: this boundary's layer is detached, so the first
2517    /// attached ancestor boundary will repaint it when it repaints.
2518    pub(crate) fn skipped_painting_on_layer(self, app: &mut App) {
2519        debug_assert!(self.attached(app));
2520        debug_assert!(self.is_repaint_boundary(app));
2521        debug_assert!(self.needs_paint(app) || self.needs_composited_layer_update(app));
2522        debug_assert!(self.layer(app).is_some());
2523        debug_assert!(
2524            self.layer(app)
2525                .is_some_and(|layer| !layer.as_layer().attached(app))
2526        );
2527        let mut node = self.parent(app);
2528        while let Some(current) = node {
2529            if current.is_repaint_boundary(app) {
2530                match current.layer(app) {
2531                    None => break,
2532                    Some(layer) if layer.as_layer().attached(app) => break,
2533                    Some(_) => current.set_needs_paint(app, true),
2534                }
2535            }
2536            node = current.parent(app);
2537        }
2538    }
2539
2540    /// Bootstrap the rendering pipeline by scheduling the very first paint.
2541    ///
2542    /// Requires that this render object is attached, is the root of the render
2543    /// tree, and has a composited layer.
2544    pub fn schedule_initial_paint(self, app: &mut App, root_layer: AnyContainerLayer) {
2545        debug_assert!(root_layer.as_layer().attached(app));
2546        debug_assert!(self.attached(app));
2547        debug_assert!(self.parent(app).is_none());
2548        debug_assert!(!self.owner(app).expect("attached").debug_doing_paint(app));
2549        debug_assert!(self.is_repaint_boundary(app));
2550        debug_assert!(self.layer(app).is_none());
2551        LayerHandle::set_layer(app, |app| &mut self.data_mut(app).layer, Some(root_layer));
2552        debug_assert!(self.needs_paint(app));
2553        let owner = self.owner(app).expect("attached");
2554        owner.add_node_needing_paint(app, self);
2555    }
2556
2557    /// Replace the layer. This is only valid for the root of a render
2558    /// object subtree (whatever object [`schedule_initial_paint`](Self::schedule_initial_paint)
2559    /// was called on).
2560    ///
2561    /// This might be called if, e.g., the device pixel ratio changed.
2562    pub fn replace_root_layer(self, app: &mut App, root_layer: AnyOffsetLayer) {
2563        debug_assert!(
2564            !app.is_disposed(self.id),
2565            "replace_root_layer on a disposed render object"
2566        );
2567        debug_assert!(root_layer.as_layer().attached(app));
2568        debug_assert!(self.attached(app));
2569        debug_assert!(self.parent(app).is_none());
2570        debug_assert!(!self.owner(app).expect("attached").debug_doing_paint(app));
2571        debug_assert!(self.is_repaint_boundary(app));
2572        debug_assert!(
2573            self.layer(app).is_some(),
2574            "use schedule_initial_paint the first time"
2575        );
2576        self.layer(app).expect("checked").as_layer().detach(app);
2577        LayerHandle::set_layer(
2578            app,
2579            |app| &mut self.data_mut(app).layer,
2580            Some(root_layer.as_container_layer()),
2581        );
2582        self.mark_needs_paint(app);
2583    }
2584
2585    /// Dart's `paint(context, offset)` called directly, as flutter_test's `paints` matcher calls
2586    /// it on the object it reads: none of `_paintWithContext`'s bookkeeping, so what the object
2587    /// records for its own frames is left as it was.
2588    #[cfg(any(test, feature = "test-support"))]
2589    pub fn paint(self, app: &mut App, context: &mut PaintingContext, offset: Offset) {
2590        (self.vtable.paint)(app, self.id, context, offset);
2591    }
2592
2593    /// Flutter's `_paintWithContext`: the framework wrapper around the `paint` virtual.
2594    pub(crate) fn paint_with_context(
2595        self,
2596        app: &mut App,
2597        context: &mut PaintingContext,
2598        offset: Offset,
2599    ) {
2600        debug_assert!(
2601            !self.data(app).debug_doing_this_paint,
2602            "Tried to paint a RenderObject reentrantly: {self:?}"
2603        );
2604        if self.needs_layout(app) {
2605            return;
2606        }
2607        debug_assert!(
2608            !self.needs_compositing_bits_update(app),
2609            "Tried to paint a RenderObject before its compositing bits were updated.\n\
2610             The following RenderObject was marked as having dirty compositing bits \
2611             at the time that it was painted: {self:?}\n\
2612             A RenderObject that still has dirty compositing bits cannot be painted \
2613             because this indicates that the tree has not yet been properly configured \
2614             for creating the layer tree.\n\
2615             This usually indicates an error in the Flutter framework itself."
2616        );
2617        let debug_last_active_paint = if cfg!(debug_assertions) {
2618            self.data_mut(app).debug_doing_this_paint = true;
2619            let previous = DEBUG_ACTIVE_PAINT.replace(Some(self));
2620            debug_assert!(!self.is_repaint_boundary(app) || self.layer(app).is_some());
2621            previous
2622        } else {
2623            None
2624        };
2625        self.set_needs_paint(app, false);
2626        self.set_needs_composited_layer_update(app, false);
2627        let is_repaint_boundary = self.is_repaint_boundary(app);
2628        self.data_mut(app).was_repaint_boundary = is_repaint_boundary;
2629        (self.vtable.paint)(app, self.id, context, offset);
2630        debug_assert!(!self.needs_layout(app));
2631        debug_assert!(!self.needs_paint(app));
2632        if cfg!(debug_assertions) {
2633            DEBUG_ACTIVE_PAINT.set(debug_last_active_paint);
2634            self.data_mut(app).debug_doing_this_paint = false;
2635        }
2636    }
2637}
2638
2639/// Flutter's `RenderObject` bodies that an override calls through `super`.
2640///
2641/// Blanket-implemented for every [`RenderObject`], and repeats the default bodies of the
2642/// virtuals above: a leaf's own override shadows the default it would otherwise call.
2643pub trait RenderObjectBase: RenderObject {
2644    /// Flutter's `RenderObject.dispose` body: releases the layer handle. An override calls it
2645    /// last, where Dart writes `super.dispose()`.
2646    fn dispose(self: RenderHandle<Self>, app: &mut App) {
2647        LayerHandle::set_layer(app, |app| &mut self.render_object_data_mut(app).layer, None);
2648    }
2649
2650    /// Flutter's `RenderObject.markNeedsLayout` body; an override calls it where Dart writes
2651    /// `super.markNeedsLayout()`.
2652    fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
2653        let this = self.as_render_object(app);
2654        if this.needs_layout(app) {
2655            return;
2656        }
2657        this.set_needs_layout(app, true);
2658        if let Some(owner) = this.owner(app)
2659            && this.is_relayout_boundary(app).unwrap_or(false)
2660        {
2661            if crate::debug::debug_print_mark_needs_layout_stacks(app) {
2662                eprintln!("markNeedsLayout() called for {this:?}");
2663            }
2664            owner.add_node_needing_layout(app, this);
2665            owner.request_visual_update(app);
2666        } else if this.parent(app).is_some() {
2667            this.mark_parent_needs_layout(app);
2668        }
2669    }
2670
2671    /// Flutter's `RenderObject.showOnScreen`.
2672    fn show_on_screen(
2673        self: RenderHandle<Self>,
2674        app: &mut App,
2675        descendant: Option<AnyRenderObject>,
2676        rect: Option<Rect>,
2677        duration: Duration,
2678        curve: Rc<dyn Curve>,
2679    ) {
2680        let this = self.as_render_object(app);
2681        if let Some(parent) = this.parent(app) {
2682            parent.show_on_screen(app, Some(descendant.unwrap_or(this)), rect, duration, curve);
2683        }
2684    }
2685}
2686
2687impl<T: RenderObject> RenderObjectBase for T {}
2688
2689/// vector_math's `Matrix4.zero()`.
2690pub(crate) fn zero_matrix() -> Matrix4 {
2691    Matrix4::from_flutter_array(&[0.0; 16])
2692}
2693
2694/// vector_math's `transform.multiply(other)`: `transform = transform * other`, so `other`
2695/// applies first to a point.
2696pub(crate) fn multiply(transform: &mut Matrix4, other: &Matrix4) {
2697    *transform = transform.then(other);
2698}
2699
2700/// vector_math's `transform.translate(dx, dy)`.
2701pub(crate) fn translate(transform: &mut Matrix4, dx: f64, dy: f64) {
2702    multiply(transform, &Matrix4::translation(dx as f32, dy as f32));
2703}
2704
2705/// vector_math's `Matrix4.perspectiveTransform(Vector3)`: transforms the point and divides by
2706/// the resulting `w`.
2707pub(crate) fn perspective_transform(transform: &Matrix4, point: [f64; 3]) -> [f64; 3] {
2708    let m = transform.to_flutter_array().map(f64::from);
2709    let [x, y, z] = point;
2710    let out = |row: usize| m[row] * x + m[4 + row] * y + m[8 + row] * z + m[12 + row];
2711    let w = out(3);
2712    [out(0) / w, out(1) / w, out(2) / w]
2713}
2714
2715/// The bag of [`RenderObjectWithLayoutCallbackMixin`].
2716#[derive(Debug)]
2717pub struct RenderObjectWithLayoutCallbackData {
2718    // The initial value of this flag must be set to true to prevent the layout
2719    // callback from being scheduled when the subtree has never been laid out (in
2720    // which case the `constraints` or any other layout information is unknown).
2721    needs_rebuild: bool,
2722}
2723
2724impl Default for RenderObjectWithLayoutCallbackData {
2725    fn default() -> RenderObjectWithLayoutCallbackData {
2726        RenderObjectWithLayoutCallbackData {
2727            needs_rebuild: true,
2728        }
2729    }
2730}
2731
2732/// A mixin for `RenderObject`s that run a layout callback (typically one that builds a
2733/// widget subtree) during `perform_layout`, as `LayoutBuilder`'s render object does.
2734///
2735/// Implementers keep the bag under a field named `layout_callback`, implement
2736/// [`layout_callback`](Self::layout_callback), and call
2737/// [`run_layout_callback`](Self::run_layout_callback) in their `perform_layout`. The mixin
2738/// is on the box protocol here because scheduling needs the tree methods.
2739pub trait RenderObjectWithLayoutCallbackMixin: crate::box_::RenderBox {
2740    /// The mixin's bag.
2741    fn layout_callback_data(
2742        self: RenderHandle<Self>,
2743        app: &App,
2744    ) -> &RenderObjectWithLayoutCallbackData;
2745
2746    /// See [`layout_callback_data`](Self::layout_callback_data).
2747    fn layout_callback_data_mut(
2748        self: RenderHandle<Self>,
2749        app: &mut App,
2750    ) -> &mut RenderObjectWithLayoutCallbackData;
2751
2752    /// The layout callback to run in `perform_layout`, through
2753    /// [`run_layout_callback`](Self::run_layout_callback), which invokes it with
2754    /// [`AnyRenderObject::invoke_layout_callback`].
2755    fn layout_callback(self: RenderHandle<Self>, app: &mut App);
2756
2757    /// Invokes [`layout_callback`](Self::layout_callback) with
2758    /// [`AnyRenderObject::invoke_layout_callback`].
2759    ///
2760    /// Must be called in `perform_layout`, and only after the callback was scheduled.
2761    fn run_layout_callback(self: RenderHandle<Self>, app: &mut App) {
2762        debug_assert!(self.as_object().debug_doing_this_layout(app));
2763        self.as_object()
2764            .invoke_layout_callback(app, |app| Self::layout_callback(self, app));
2765        self.layout_callback_data_mut(app).needs_rebuild = false;
2766    }
2767
2768    /// Schedules the layout callback to be run in the next layout pass, marking this object
2769    /// for layout.
2770    fn schedule_layout_callback(self: RenderHandle<Self>, app: &mut App) {
2771        if self.layout_callback_data(app).needs_rebuild {
2772            debug_assert!(self.as_object().needs_layout(app));
2773            return;
2774        }
2775        self.layout_callback_data_mut(app).needs_rebuild = true;
2776        // This ensures that the layout callback will be run even if an ancestor
2777        // chooses to not lay out this subtree (for example, obstructed OverlayEntries
2778        // with `maintainState` set to true), to maintain the widget tree integrity
2779        // (making sure global keys are unique, for example).
2780        if let Some(owner) = self.as_object().owner(app) {
2781            owner.add_node_needing_layout(app, self.as_object());
2782        }
2783        // In an active tree, markNeedsLayout is needed to inform the layout boundary
2784        // that its child size may change.
2785        self.as_object().mark_needs_layout(app);
2786    }
2787}
2788
2789#[cfg(test)]
2790mod tests {
2791    use std::cell::Cell;
2792    use std::rc::Rc;
2793
2794    use waft_foundation::{App, AppCell, Listener};
2795
2796    use super::*;
2797    use crate::box_::{BoxConstraints, RenderBox, RenderBoxData};
2798    use crate::pipeline_owner::PipelineOwner;
2799
2800    struct TestLeaf {
2801        render_object: RenderObjectData,
2802        render_box: RenderBoxData,
2803        layouts: Rc<Cell<u32>>,
2804    }
2805
2806    impl RenderObject for TestLeaf {
2807        render_object_accessors!();
2808
2809        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2810            let layouts = self.get(app).layouts.clone();
2811            layouts.set(layouts.get() + 1);
2812            let size = self.constraints(app).smallest();
2813            self.set_size(app, size);
2814        }
2815    }
2816
2817    impl RenderBox for TestLeaf {
2818        crate::render_box_accessors!();
2819    }
2820
2821    struct TestParent {
2822        render_object: RenderObjectData,
2823        render_box: RenderBoxData,
2824        child: Option<crate::AnyRenderBox>,
2825        layouts: Rc<Cell<u32>>,
2826        parent_uses_size: bool,
2827        lay_out_child: bool,
2828    }
2829
2830    impl RenderObject for TestParent {
2831        render_object_accessors!();
2832
2833        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2834            let layouts = self.get(app).layouts.clone();
2835            layouts.set(layouts.get() + 1);
2836            let child = self.get(app).child;
2837            let parent_uses_size = self.get(app).parent_uses_size;
2838            let lay_out_child = self.get(app).lay_out_child;
2839            let constraints = self.constraints(app);
2840            if let Some(child) = child
2841                && lay_out_child
2842            {
2843                child.layout(app, constraints, parent_uses_size);
2844                let _again = self.get(app).layouts.get();
2845                if parent_uses_size {
2846                    self.set_size(app, child.size(app));
2847                    return;
2848                }
2849            }
2850            self.set_size(app, constraints.smallest());
2851        }
2852
2853        fn visit_children(
2854            self: RenderHandle<Self>,
2855            app: &App,
2856            visitor: &mut dyn FnMut(AnyRenderObject),
2857        ) {
2858            if let Some(child) = self.get(app).child {
2859                visitor(child.as_object());
2860            }
2861        }
2862    }
2863
2864    impl RenderBox for TestParent {
2865        crate::render_box_accessors!();
2866    }
2867
2868    fn tight() -> BoxConstraints {
2869        BoxConstraints::tight_for_finite(100.0, 100.0)
2870    }
2871
2872    fn loose() -> BoxConstraints {
2873        BoxConstraints::new()
2874    }
2875
2876    fn leaf(layouts: Rc<Cell<u32>>) -> TestLeaf {
2877        TestLeaf {
2878            render_object: RenderObjectData::new(),
2879            render_box: RenderBoxData::new(),
2880            layouts,
2881        }
2882    }
2883
2884    fn parent(
2885        child: Option<crate::AnyRenderBox>,
2886        layouts: Rc<Cell<u32>>,
2887        parent_uses_size: bool,
2888        lay_out_child: bool,
2889    ) -> TestParent {
2890        TestParent {
2891            render_object: RenderObjectData::new(),
2892            render_box: RenderBoxData::new(),
2893            child,
2894            layouts,
2895            parent_uses_size,
2896            lay_out_child,
2897        }
2898    }
2899
2900    /// `object_test.dart`: `nodesNeedingLayout updated with layout changes`.
2901    #[test]
2902    fn nodes_needing_layout_updated_with_layout_changes() {
2903        let cell = AppCell::new();
2904        let mut app = cell.borrow_mut();
2905        let owner = PipelineOwner::new(&mut app, None, None);
2906        let node = RenderHandle::new_box(&mut app, leaf(Rc::new(Cell::new(0))));
2907        node.as_object().attach(&mut app, owner.handle());
2908        assert!(owner.nodes_needing_layout(&app).is_empty());
2909
2910        node.layout(&mut app, tight(), false);
2911        node.as_object().mark_needs_layout(&mut app);
2912        assert!(owner.nodes_needing_layout(&app).contains(&node.as_object()));
2913
2914        owner.flush_layout(&mut app);
2915        assert!(owner.nodes_needing_layout(&app).is_empty());
2916    }
2917
2918    #[test]
2919    fn clean_layout_skips_perform_layout() {
2920        let cell = AppCell::new();
2921        let mut app = cell.borrow_mut();
2922        let layouts = Rc::new(Cell::new(0));
2923        let node = RenderHandle::new_box(&mut app, leaf(Rc::clone(&layouts)));
2924        node.layout(&mut app, tight(), false);
2925        assert_eq!(layouts.get(), 1);
2926        node.layout(&mut app, tight(), false);
2927        assert_eq!(layouts.get(), 1);
2928        node.as_object().mark_needs_layout(&mut app);
2929        node.layout(&mut app, tight(), false);
2930        assert_eq!(layouts.get(), 2);
2931    }
2932
2933    #[test]
2934    fn parent_uses_size_marks_parent() {
2935        let cell = AppCell::new();
2936        let mut app = cell.borrow_mut();
2937        let owner = PipelineOwner::new(&mut app, None, None);
2938        let child = RenderHandle::new_box(&mut app, leaf(Rc::new(Cell::new(0))));
2939        let parent = RenderHandle::new_box(
2940            &mut app,
2941            parent(Some(child.as_box()), Rc::new(Cell::new(0)), true, true),
2942        );
2943        parent.adopt_child(&mut app, child.as_object());
2944        parent.as_object().attach(&mut app, owner.handle());
2945        parent.layout(&mut app, loose(), false);
2946        assert!(!parent.debug_needs_layout(&app));
2947        assert!(!child.debug_needs_layout(&app));
2948
2949        child.as_object().mark_needs_layout(&mut app);
2950        assert!(parent.debug_needs_layout(&app));
2951        assert!(
2952            owner
2953                .nodes_needing_layout(&app)
2954                .contains(&parent.as_object())
2955        );
2956    }
2957
2958    #[test]
2959    fn adopt_drop_attach_detach() {
2960        let cell = AppCell::new();
2961        let mut app = cell.borrow_mut();
2962        let owner = PipelineOwner::new(&mut app, None, None);
2963        let child = RenderHandle::new_box(&mut app, leaf(Rc::new(Cell::new(0))));
2964        let parent = RenderHandle::new_box(
2965            &mut app,
2966            parent(Some(child.as_box()), Rc::new(Cell::new(0)), false, true),
2967        );
2968        parent.adopt_child(&mut app, child.as_object());
2969        assert_eq!(child.parent(&app), Some(parent.as_object()));
2970        assert_eq!(
2971            child.as_object().depth(&app),
2972            parent.as_object().depth(&app) + 1
2973        );
2974        assert!(!child.attached(&app));
2975
2976        parent.as_object().attach(&mut app, owner.handle());
2977        assert!(parent.attached(&app));
2978        assert!(child.attached(&app));
2979        assert_eq!(child.owner(&app), Some(owner.handle()));
2980
2981        parent.drop_child(&mut app, child.as_object());
2982        assert!(child.parent(&app).is_none());
2983        assert!(!child.attached(&app));
2984        assert!(parent.attached(&app));
2985    }
2986
2987    #[test]
2988    fn parent_reenters_itself_after_child_layout() {
2989        let cell = AppCell::new();
2990        let mut app = cell.borrow_mut();
2991        let layouts = Rc::new(Cell::new(0));
2992        let child = RenderHandle::new_box(&mut app, leaf(Rc::new(Cell::new(0))));
2993        let parent = RenderHandle::new_box(
2994            &mut app,
2995            parent(Some(child.as_box()), Rc::clone(&layouts), true, true),
2996        );
2997        parent.adopt_child(&mut app, child.as_object());
2998        parent.layout(&mut app, loose(), false);
2999        assert_eq!(layouts.get(), 1);
3000        assert_eq!(parent.size(&app), child.size(&app));
3001    }
3002
3003    #[test]
3004    fn flush_layout_orders_by_depth() {
3005        let cell = AppCell::new();
3006        let mut app = cell.borrow_mut();
3007        let owner = PipelineOwner::new(&mut app, None, None);
3008        let order = Rc::new(std::cell::RefCell::new(Vec::new()));
3009        let child_order = Rc::clone(&order);
3010        let parent_order = Rc::clone(&order);
3011
3012        struct OrderLeaf {
3013            render_object: RenderObjectData,
3014            render_box: RenderBoxData,
3015            name: &'static str,
3016            order: Rc<std::cell::RefCell<Vec<&'static str>>>,
3017        }
3018        impl RenderObject for OrderLeaf {
3019            render_object_accessors!();
3020
3021            fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3022                let name = self.get(app).name;
3023                self.get(app).order.borrow_mut().push(name);
3024                let size = self.constraints(app).smallest();
3025                self.set_size(app, size);
3026            }
3027        }
3028        impl RenderBox for OrderLeaf {
3029            crate::render_box_accessors!();
3030        }
3031
3032        struct OrderParent {
3033            render_object: RenderObjectData,
3034            render_box: RenderBoxData,
3035            name: &'static str,
3036            child: Option<crate::AnyRenderBox>,
3037            order: Rc<std::cell::RefCell<Vec<&'static str>>>,
3038        }
3039        impl RenderObject for OrderParent {
3040            render_object_accessors!();
3041
3042            fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3043                let name = self.get(app).name;
3044                self.get(app).order.borrow_mut().push(name);
3045                let size = self.constraints(app).smallest();
3046                self.set_size(app, size);
3047            }
3048            fn visit_children(
3049                self: RenderHandle<Self>,
3050                app: &App,
3051                visitor: &mut dyn FnMut(AnyRenderObject),
3052            ) {
3053                if let Some(child) = self.get(app).child {
3054                    visitor(child.as_object());
3055                }
3056            }
3057        }
3058        impl RenderBox for OrderParent {
3059            crate::render_box_accessors!();
3060        }
3061
3062        let child = RenderHandle::new_box(
3063            &mut app,
3064            OrderLeaf {
3065                render_object: RenderObjectData::new(),
3066                render_box: RenderBoxData::new(),
3067                name: "child",
3068                order: child_order,
3069            },
3070        );
3071        let parent = RenderHandle::new_box(
3072            &mut app,
3073            OrderParent {
3074                render_object: RenderObjectData::new(),
3075                render_box: RenderBoxData::new(),
3076                name: "parent",
3077                child: Some(child.as_box()),
3078                order: parent_order,
3079            },
3080        );
3081        parent.adopt_child(&mut app, child.as_object());
3082        parent.as_object().attach(&mut app, owner.handle());
3083        parent.layout(&mut app, tight(), false);
3084        child.layout(&mut app, tight(), false);
3085        parent.as_object().mark_needs_layout(&mut app);
3086        child.as_object().mark_needs_layout(&mut app);
3087        order.borrow_mut().clear();
3088        owner.flush_layout(&mut app);
3089        assert_eq!(*order.borrow(), ["parent", "child"]);
3090    }
3091
3092    #[test]
3093    fn mark_needs_layout_requests_visual_update() {
3094        let cell = AppCell::new();
3095        let mut app = cell.borrow_mut();
3096        let updates = Rc::new(Cell::new(0));
3097        let updates_cb = Rc::clone(&updates);
3098        let owner = PipelineOwner::new(
3099            &mut app,
3100            Some(Listener::new(move |_| {
3101                updates_cb.set(updates_cb.get() + 1);
3102            })),
3103            None,
3104        );
3105        let node = RenderHandle::new_box(&mut app, leaf(Rc::new(Cell::new(0))));
3106        owner.set_root_node(&mut app, Some(node.as_object()));
3107        node.layout(&mut app, tight(), false);
3108        assert_eq!(updates.get(), 0);
3109        node.as_object().mark_needs_layout(&mut app);
3110        assert_eq!(updates.get(), 1);
3111    }
3112}