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