Skip to main content

waft_widgets/framework/
element.rs

1//! `Element`: an instantiation of a `Widget` at a particular location in the tree.
2//!
3//! An element is one struct in the arena, reached through `Handle<Self>`; Dart's base-class
4//! fields are the [`ElementData`] bag the struct holds under the field `element`. A reference
5//! to "some element" is the type-erased handle [`AnyElement`], which is also the [`BuildContext`]
6//! (Dart's `Element implements BuildContext`).
7//!
8//! Dart's base bodies are the free functions `base_*`; an override calls the one it would
9//! call as `super`.
10//!
11//! Mounting and rebuilding recurse once per level of the tree, and on the web each wasm call
12//! costs Safari's first tier close to a kilobyte of stack however small it is, so a deep tree
13//! (the Material gallery's phone layout is about 300 levels) overflows an iPhone's stack when a
14//! level costs many calls. A level costs one: the child's vtable entry. Everything between one
15//! entry and the next is folded into it with `#[inline(always)]`: each element's `mount`,
16//! `update`, `first_build` and `perform_rebuild` and the base bodies they forward to,
17//! [`AnyElement::update_child`] and [`AnyElement::inflate_widget`] (which is why it is not an
18//! override point). An element of a known type rebuilds through
19//! [`ElementBase::rebuild`], which calls its `perform_rebuild` directly rather than through the
20//! vtable. Folding `update_child` into every entry is cheap only because the framework's
21//! elements are not generic over their widget, so there are a few dozen entries rather than one
22//! per widget type. A forwarding method on that path without the attribute, or a call back
23//! into `update_child` from what it folds in (see `inflate_inactive_child`), adds a call to
24//! every level. The walks over a whole subtree (activate, deactivate, unmount) are loops.
25
26use std::any::{Any, TypeId};
27use std::cell::Cell;
28use std::collections::{HashMap, HashSet};
29use std::fmt::{self, Debug};
30use std::hash::{Hash, Hasher};
31use std::rc::Rc;
32
33use waft_embedder::Size;
34use waft_foundation::{
35    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
36    DiagnosticsProperty, DiagnosticsTreeStyle, EntityId, FlagProperty, Handle, HandleId,
37    IntoPropertyName, ObjectFlagProperty, Subscription, TrackedSet, bare_type_name,
38    describe_identity,
39};
40use waft_rendering::{AnyRenderObject, RenderHandle, RenderObject};
41
42use super::build_owner::{BuildOwner, BuildScope};
43use super::element_node::{ElementDiagnosticsNode, ElementFacts};
44use super::state::State;
45use super::widget::{
46    GlobalKey, InheritedWidget, KeyRef, Widget, WidgetKind, WidgetRef, can_update, downcast_widget,
47    same_widget,
48};
49use crate::widgets::notification_listener::LayoutChangedNotification;
50use crate::widgets::scroll_notification::ScrollNotification;
51use waft_foundation::Ref;
52
53/// A handle to the location of a widget in the widget tree.
54///
55/// This is Dart's `BuildContext` interface, which `Element` implements: here the type-erased
56/// element handle plays both parts.
57pub type BuildContext = AnyElement;
58
59/// Dart's `_ElementLifecycle`.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum ElementLifecycle {
62    Initial,
63    Active,
64    Inactive,
65    Failed,
66    Defunct,
67}
68
69/// A value for `Element.slot` used for children of `MultiChildRenderObjectElement`s.
70///
71/// A slot for a `MultiChildRenderObjectElement` consists of an [`index`](Self::index)
72/// identifying where the child occurring at this slot is located in the
73/// `MultiChildRenderObjectElement`'s child list and an arbitrary [`value`](Self::value) that
74/// can further define where the child occurring at this slot fits in its parent's child list.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct IndexedSlot {
77    /// Information to define where the child occurring at this slot fits in its parent's
78    /// child list.
79    pub value: Option<AnyElement>,
80    /// The index of this slot in the parent's child list.
81    pub index: usize,
82}
83
84/// Dart's `Object? slot` on an element: how the parent tells its children apart.
85#[derive(Clone, Debug)]
86pub enum Slot {
87    /// A child of a multi-child render object element.
88    Indexed(IndexedSlot),
89    /// The index of a child of a lazily built sliver (`SliverMultiBoxAdaptorElement`).
90    Index(i32),
91    /// A parent-defined value, compared by identity as an arbitrary Dart object would be.
92    Custom(Rc<dyn Any>),
93}
94
95impl PartialEq for Slot {
96    fn eq(&self, other: &Slot) -> bool {
97        match (self, other) {
98            (Slot::Indexed(a), Slot::Indexed(b)) => a == b,
99            (Slot::Index(a), Slot::Index(b)) => a == b,
100            (Slot::Custom(a), Slot::Custom(b)) => Rc::ptr_eq(a, b),
101            _ => false,
102        }
103    }
104}
105
106/// The live "is this child forgotten?" check [`AnyElement::update_children`] takes (Dart's
107/// `Set<Element> forgottenChildren`).
108pub type ForgottenChildren<'a> = &'a dyn Fn(&App, AnyElement) -> bool;
109
110/// A type a `NotificationListener<T>` can listen for: a concrete [`Notification`], or a
111/// family of them named by a trait object (`dyn ScrollNotification`).
112///
113/// Dart's `notification is T`; a family answers it through a vtable slot on
114/// [`Notification`], a concrete type through [`Notification::as_any`].
115pub trait NotificationTarget: 'static {
116    /// The notification as a `T`, when it is one.
117    fn cast(notification: &dyn Notification) -> Option<&Self>;
118}
119
120impl<T: Notification> NotificationTarget for T {
121    fn cast(notification: &dyn Notification) -> Option<&T> {
122        notification.as_any().downcast_ref::<T>()
123    }
124}
125
126/// To send a notification, call [`dispatch`](Self::dispatch) on the notification you wish to
127/// send. The notification will be delivered to any `NotificationListener` widgets with the
128/// appropriate type parameters that are ancestors of the given [`BuildContext`].
129/// A notification that can bubble up the widget tree.
130///
131/// You can determine the type of a notification using the `is` operator to check the
132/// `runtimeType` of the notification; here [`as_any`](Self::as_any) and a downcast.
133///
134/// To listen for notifications in a subtree, use a `NotificationListener`.
135///
136pub trait Notification: Any + Debug {
137    /// The notification as `Any`, for Dart's `notification is T` check.
138    fn as_any(&self) -> &dyn Any;
139
140    /// The depth counter of a notification that mixes in `ViewportNotificationMixin`
141    /// (`widgets/scroll_notification.rs`), for the viewport elements that increment it as
142    /// the notification bubbles past them; `None` — the default — for every other
143    /// notification.
144    ///
145    /// This is Dart's `notification is ViewportNotificationMixin`: a mixin is an interface,
146    /// not a type, so an erased notification answers the check from its own vtable rather
147    /// than through [`as_any`](Self::as_any). The counter is a [`Cell`] because a
148    /// notification bubbles as `&dyn Notification`.
149    fn viewport_depth(&self) -> Option<&Cell<u32>> {
150        None
151    }
152
153    /// The notification as a `ScrollNotification` (`widgets/scroll_notification.rs`), for a
154    /// `NotificationListener<dyn ScrollNotification>`; `None` — the default — for every
155    /// other notification.
156    ///
157    /// This is Dart's `notification is ScrollNotification`, answered from the vtable as
158    /// [`viewport_depth`](Self::viewport_depth) is, because the family is a trait.
159    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
160        None
161    }
162
163    /// The notification as a `LayoutChangedNotification`
164    /// (`widgets/notification_listener.rs`), for a
165    /// `NotificationListener<dyn LayoutChangedNotification>`; `None` — the default — for every
166    /// other notification.
167    ///
168    /// This is Dart's `notification is LayoutChangedNotification`, answered from the vtable as
169    /// [`as_scroll_notification`](Self::as_scroll_notification) is: every notification Dart
170    /// derives from `LayoutChangedNotification` answers it, scroll notifications included.
171    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
172        None
173    }
174
175    /// Start bubbling this notification at the given build context.
176    ///
177    /// The notification will be delivered to any `NotificationListener` widgets with the
178    /// appropriate type parameters that are ancestors of the given [`BuildContext`]. If the
179    /// [`BuildContext`] is null, the notification is not dispatched.
180    fn dispatch(&self, app: &mut App, target: Option<BuildContext>)
181    where
182        Self: Sized,
183    {
184        if let Some(target) = target {
185            target.dispatch_notification(app, self);
186        }
187    }
188}
189
190/// Dart's `_NotificationNode`: one notifiable element and the chain above it.
191pub struct NotificationNode {
192    parent: Option<Rc<NotificationNode>>,
193    current: AnyElement,
194}
195
196impl NotificationNode {
197    /// A node for `current`, chained under its nearest notifiable ancestor.
198    pub fn new(parent: Option<Rc<NotificationNode>>, current: AnyElement) -> NotificationNode {
199        NotificationNode { parent, current }
200    }
201
202    fn dispatch_notification(&self, app: &mut App, notification: &dyn Notification) {
203        if self.current.on_notification(app, notification) {
204            return;
205        }
206        if let Some(parent) = &self.parent {
207            parent.dispatch_notification(app, notification);
208        }
209    }
210}
211
212/// The fields of Dart's `Element` base class.
213pub struct ElementData {
214    parent: Option<AnyElement>,
215    slot: Option<Slot>,
216    depth: u32,
217    widget: Option<WidgetRef>,
218    owner: Option<Handle<BuildOwner>>,
219    pub(crate) parent_build_scope: Option<Handle<BuildScope>>,
220    /// The scope [`assign_owner`](AnyElement::assign_owner) made for a root element, which the
221    /// root holds; every other element's `parent_build_scope` names one an ancestor holds.
222    root_build_scope: Option<Ref<BuildScope>>,
223    lifecycle: ElementLifecycle,
224    dirty: bool,
225    pub(crate) in_dirty_list: bool,
226    inherited_elements: Option<Rc<HashMap<TypeId, AnyElement>>>,
227    /// Dart's `_notificationTree`: the nearest notifiable ancestor chain.
228    notification_tree: Option<Rc<NotificationNode>>,
229    dependencies: Option<HashSet<AnyElement>>,
230    had_unsatisfied_dependencies: bool,
231    debug_built_once: bool,
232    /// Entities this element's last `build` read. Kept across deactivate; dropped on unmount.
233    /// Activate rebuilds if this is non-empty, the way `hadDependencies` rebuilds for inherited widgets.
234    entity_watches: HashMap<EntityId, Subscription>,
235}
236
237impl ElementData {
238    /// Creates an element's bookkeeping for the given widget.
239    pub fn new(widget: WidgetRef) -> ElementData {
240        ElementData {
241            parent: None,
242            slot: None,
243            depth: 0,
244            widget: Some(widget),
245            owner: None,
246            parent_build_scope: None,
247            root_build_scope: None,
248            lifecycle: ElementLifecycle::Initial,
249            dirty: true,
250            in_dirty_list: false,
251            inherited_elements: None,
252            notification_tree: None,
253            dependencies: None,
254            had_unsatisfied_dependencies: false,
255            debug_built_once: false,
256            entity_watches: HashMap::new(),
257        }
258    }
259
260    /// The configuration for this element, as a shared reference.
261    pub fn widget_ref(&self) -> &WidgetRef {
262        self.widget.as_ref().expect("the element is unmounted")
263    }
264}
265
266/// The accessors [`Element`] asks for, for a struct whose bag is the field `element`.
267#[macro_export]
268macro_rules! element_accessors {
269    () => {
270        fn element_data(
271            self: $crate::__private::foundation::Handle<Self>,
272            app: &$crate::__private::foundation::App,
273        ) -> &$crate::ElementData {
274            &app.get(self).element
275        }
276
277        fn element_data_mut(
278            self: $crate::__private::foundation::Handle<Self>,
279            app: &mut $crate::__private::foundation::App,
280        ) -> &mut $crate::ElementData {
281            &mut app.get_mut(self).element
282        }
283    };
284}
285
286/// An instantiation of a `Widget` at a particular location in the tree.
287///
288/// Widgets describe how to configure a subtree but the same widget can be used to configure
289/// multiple subtrees simultaneously because widgets are immutable. An [`Element`] represents
290/// the use of a widget to configure a specific location in the tree. Over time, the widget
291/// associated with a given element can change, for example, if the parent widget rebuilds
292/// and creates a new widget for this location.
293///
294/// The overridable methods default to Dart's base bodies; an override that must run the
295/// base as well calls it through [`ElementBase`] (`ElementBase::mount(self, ..)`), where
296/// Dart calls `super`.
297pub trait Element: Sized + 'static {
298    /// Dart's base-class fields, held under the field `element`
299    /// ([`element_accessors!`](crate::element_accessors)).
300    fn element_data(self: Handle<Self>, app: &App) -> &ElementData;
301
302    /// See [`element_data`](Self::element_data).
303    fn element_data_mut(self: Handle<Self>, app: &mut App) -> &mut ElementData;
304
305    /// The type-erased handle to this element.
306    fn as_element(self: Handle<Self>) -> AnyElement {
307        AnyElement {
308            id: self.id(),
309            vtable: const { &ElementVTable::of::<Self>() },
310        }
311    }
312
313    /// Calls the argument for each child. Must be overridden by subclasses that support
314    /// having children.
315    ///
316    /// There is no guaranteed order in which the children will be visited, though it should
317    /// be consistent over time.
318    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
319        let _ = (self, app, visitor);
320    }
321
322    /// Calls the argument for each child considered onstage.
323    ///
324    /// Classes like `Offstage` and `Overlay` override this method to hide their children.
325    ///
326    /// Being onstage affects the element's discoverability during testing when you use
327    /// flutter_test's `Finder`. Offstage elements are ignored by finders by default.
328    ///
329    /// Most widgets are not visible when offstage, but that is not always the case: an element
330    /// that is offstage here may still paint.
331    fn debug_visit_onstage_children(
332        self: Handle<Self>,
333        app: &App,
334        visitor: &mut dyn FnMut(AnyElement),
335    ) {
336        self.visit_children(app, visitor);
337    }
338
339    /// Returns the child of this [`Element`] that will insert a `RenderObject` into an
340    /// ancestor of this Element to construct the render tree.
341    ///
342    /// Returns `None` if this Element doesn't have any children who need to attach a
343    /// `RenderObject` to an ancestor of this [`Element`]. A `RenderObjectElement` will
344    /// therefore return `None` because its children insert their `RenderObject`s into the
345    /// `RenderObjectElement` itself and not into an ancestor of the `RenderObjectElement`.
346    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
347        ElementBase::render_object_attaching_child(self, app)
348    }
349
350    /// Add this element to the tree in the given slot of the given parent.
351    ///
352    /// The framework calls this function when a newly created element is added to the tree
353    /// for the first time. Use this method to initialize state that depends on having a
354    /// parent. State that is independent of the parent can more easily be initialized in the
355    /// constructor.
356    fn mount(
357        self: Handle<Self>,
358        app: &mut App,
359        parent: Option<AnyElement>,
360        new_slot: Option<Slot>,
361    ) {
362        ElementBase::mount(self, app, parent, new_slot);
363    }
364
365    /// Change the widget used to configure this element.
366    ///
367    /// The framework calls this function when the parent wishes to use a different widget to
368    /// configure this element. The new widget is guaranteed to have the same `runtimeType` as
369    /// the old widget.
370    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
371        ElementBase::update(self, app, new_widget);
372    }
373
374    /// Called by [`AnyElement::update_slot_for_child`] when the slot for a child has changed.
375    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
376        ElementBase::update_slot(self, app, new_slot);
377    }
378
379    /// Add [`AnyElement::render_object`] to the render tree at the location specified by
380    /// `new_slot`.
381    ///
382    /// The default implementation of this function calls
383    /// [`attach_render_object`](Self::attach_render_object) recursively on each child. The
384    /// `RenderObjectElement::attach_render_object` override does the actual work of adding
385    /// [`AnyElement::render_object`] to the render tree.
386    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
387        ElementBase::attach_render_object(self, app, new_slot);
388    }
389
390    /// Remove [`AnyElement::render_object`] from the render tree.
391    ///
392    /// The default implementation of this function calls
393    /// [`detach_render_object`](Self::detach_render_object) recursively on each child. The
394    /// `RenderObjectElement::detach_render_object` override does the actual work of removing
395    /// [`AnyElement::render_object`] from the render tree.
396    fn detach_render_object(self: Handle<Self>, app: &mut App) {
397        ElementBase::detach_render_object(self, app);
398    }
399
400    /// Remove the given child from the element's child list, in preparation for the child
401    /// being reused elsewhere in the element tree.
402    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
403        let _ = (self, app, child);
404    }
405
406    /// Transition from the "inactive" to the "active" lifecycle state.
407    fn activate(self: Handle<Self>, app: &mut App) {
408        ElementBase::activate(self, app);
409    }
410
411    /// Transition from the "active" to the "inactive" lifecycle state.
412    fn deactivate(self: Handle<Self>, app: &mut App) {
413        ElementBase::deactivate(self, app);
414    }
415
416    /// Called, in debug mode, after children have been deactivated.
417    fn debug_deactivated(self: Handle<Self>, app: &mut App) {
418        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
419    }
420
421    /// Transition from the "inactive" to the "defunct" lifecycle state.
422    fn unmount(self: Handle<Self>, app: &mut App) {
423        ElementBase::unmount(self, app);
424    }
425
426    /// Cause the widget to update itself.
427    ///
428    /// Called by [`AnyElement::rebuild`] after the appropriate checks have been made.
429    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
430        ElementBase::perform_rebuild(self, app);
431    }
432
433    /// Called when a dependency of this element changes.
434    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
435        ElementBase::did_change_dependencies(self, app);
436    }
437
438    /// Dart's `_updateInheritance`: inherit the parent's inherited-element map.
439    fn update_inheritance(self: Handle<Self>, app: &mut App) {
440        ElementBase::update_inheritance(self, app);
441    }
442
443    /// Called in [`mount`](Self::mount) and [`activate`](Self::activate) to register this
444    /// element in the notification tree.
445    ///
446    /// This method is only exposed so that notifiable elements can be implemented (Dart's
447    /// `NotifiableElementMixin`): an element that wishes to respond to notifications
448    /// overrides it to insert a node for itself, and [`on_notification`](Self::on_notification)
449    /// to handle them.
450    ///
451    /// See also:
452    ///   * `NotificationListener`, a widget that allows listening to notifications.
453    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
454        ElementBase::attach_notification_tree(self, app);
455    }
456
457    /// The [`BuildScope`] whose dirty list this element is in.
458    ///
459    /// The [`BuildOwner`] builds the dirty elements of one scope per `build_scope` call;
460    /// an element that wants its own (a `LayoutBuilder`, whose subtree is built during
461    /// layout) overrides this.
462    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
463        ElementBase::build_scope(self, app)
464    }
465
466    /// Marks the element as dirty and adds it to the global list of widgets to rebuild in
467    /// the next frame.
468    ///
469    /// Since it is inefficient to build an element twice in one frame, applications and
470    /// widgets should be structured so as to only mark widgets dirty during event handlers
471    /// before the frame begins, not during the build itself.
472    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
473        ElementBase::mark_needs_build(self, app);
474    }
475
476    /// Called when a notification of the appropriate type arrives at this location in the
477    /// tree (Dart's `NotifiableElementMixin.onNotification`).
478    ///
479    /// Return true to cancel the notification bubbling. Return false to allow the
480    /// notification to continue to be dispatched to further ancestors. Only elements that
481    /// override [`attach_notification_tree`](Self::attach_notification_tree) are asked.
482    fn on_notification(self: Handle<Self>, app: &mut App, notification: &dyn Notification) -> bool {
483        let _ = (app, notification);
484        false
485    }
486
487    /// Whether the child in the provided `slot` (or one of its descendants) must insert a
488    /// `RenderObject` into its ancestor `RenderObjectElement` by calling
489    /// `RenderObjectElement::insert_render_object_child` on it.
490    fn debug_expects_render_object_for_slot(
491        self: Handle<Self>,
492        app: &App,
493        slot: Option<&Slot>,
494    ) -> bool {
495        let _ = (self, app, slot);
496        true
497    }
498
499    /// The render object at (or below) this location in the tree.
500    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
501        ElementBase::render_object(self, app)
502    }
503
504    /// Whether this element is in the middle of building.
505    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
506        let _ = (self, app);
507        false
508    }
509
510    // ---- Dart's `is` checks and the members behind them ----
511
512    /// Dart's `this is RenderObjectElement`.
513    const IS_RENDER_OBJECT_ELEMENT: bool = false;
514
515    /// `RenderObjectElement.insertRenderObjectChild`.
516    fn insert_render_object_child(
517        self: Handle<Self>,
518        app: &mut App,
519        child: AnyRenderObject,
520        slot: Option<Slot>,
521    ) {
522        let _ = (self, app, child, slot);
523        unreachable!("not a RenderObjectElement");
524    }
525
526    /// `RenderObjectElement.moveRenderObjectChild`.
527    fn move_render_object_child(
528        self: Handle<Self>,
529        app: &mut App,
530        child: AnyRenderObject,
531        old_slot: Option<Slot>,
532        new_slot: Option<Slot>,
533    ) {
534        let _ = (self, app, child, old_slot, new_slot);
535        unreachable!("not a RenderObjectElement");
536    }
537
538    /// `RenderObjectElement.removeRenderObjectChild`.
539    fn remove_render_object_child(
540        self: Handle<Self>,
541        app: &mut App,
542        child: AnyRenderObject,
543        slot: Option<Slot>,
544    ) {
545        let _ = (self, app, child, slot);
546        unreachable!("not a RenderObjectElement");
547    }
548
549    /// `RenderObjectElement._updateParentData`: apply a parent-data widget to this element's
550    /// render object.
551    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
552        let _ = (self, app, parent_data_element);
553        unreachable!("not a RenderObjectElement");
554    }
555
556    /// Dart's `this is ParentDataElement`.
557    const IS_PARENT_DATA_ELEMENT: bool = false;
558
559    /// `ParentDataWidget.applyParentData` through the element that holds the widget.
560    fn apply_parent_data(
561        self: Handle<Self>,
562        app: &mut App,
563        render_object: AnyRenderObject,
564    ) -> bool {
565        let _ = (self, app, render_object);
566        unreachable!("not a ParentDataElement");
567    }
568
569    /// Dart's `this is InheritedElement`.
570    const IS_INHERITED_ELEMENT: bool = false;
571
572    /// `InheritedElement.updateDependencies`.
573    fn update_dependencies(
574        self: Handle<Self>,
575        app: &mut App,
576        dependent: AnyElement,
577        aspect: Option<Rc<dyn Any>>,
578    ) {
579        let _ = (self, app, dependent, aspect);
580        unreachable!("not an InheritedElement");
581    }
582
583    /// `InheritedElement.removeDependent`.
584    fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
585        let _ = (self, app, dependent);
586        unreachable!("not an InheritedElement");
587    }
588
589    /// Dart's `this is StatefulElement && state is T`: the state's type and arena id.
590    fn state_handle_id(self: Handle<Self>, app: &App) -> Option<(TypeId, HandleId)> {
591        let _ = (self, app);
592        None
593    }
594
595    /// Dart's `debugFillProperties` as an element class overrides it: the properties it adds
596    /// after `Element`'s, and `RenderObjectElement`'s for a render object element, which the
597    /// framework adds first since a trait default cannot call `super`.
598    fn debug_fill_properties(
599        self: Handle<Self>,
600        app: &App,
601        properties: &mut DiagnosticPropertiesBuilder,
602    ) {
603        let _ = (self, app, properties);
604    }
605
606    /// Dart's `debugDescribeChildren`: the children a dump shows under this element, by
607    /// default every child [`visit_children`](Self::visit_children) visits.
608    fn debug_describe_children(self: Handle<Self>, app: &App) -> Vec<Rc<dyn DiagnosticsNode>> {
609        let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
610        Self::visit_children(self, app, &mut |child| {
611            children.push(Rc::new(child.to_diagnostics_node(app, None)));
612        });
613        children
614    }
615}
616
617/// The vtable of an erased [`AnyElement`]: one `&'static` table per element type.
618pub(crate) struct ElementVTable {
619    pub type_name: fn() -> &'static str,
620    pub debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
621    pub debug_describe_children: fn(&App, HandleId) -> Vec<Rc<dyn DiagnosticsNode>>,
622    pub element_data: fn(&App, HandleId) -> &ElementData,
623    pub element_data_mut: fn(&mut App, HandleId) -> &mut ElementData,
624    pub visit_children: fn(&App, HandleId, &mut dyn FnMut(AnyElement)),
625    pub debug_visit_onstage_children: fn(&App, HandleId, &mut dyn FnMut(AnyElement)),
626    pub render_object_attaching_child: fn(&App, HandleId) -> Option<AnyElement>,
627    pub mount: fn(&mut App, HandleId, Option<AnyElement>, Option<Slot>),
628    pub update: fn(&mut App, HandleId, WidgetRef),
629    pub update_slot: fn(&mut App, HandleId, Option<Slot>),
630    pub attach_render_object: fn(&mut App, HandleId, Option<Slot>),
631    pub detach_render_object: fn(&mut App, HandleId),
632    pub forget_child: fn(&mut App, HandleId, AnyElement),
633    pub activate: fn(&mut App, HandleId),
634    pub deactivate: fn(&mut App, HandleId),
635    pub debug_deactivated: fn(&mut App, HandleId),
636    pub unmount: fn(&mut App, HandleId),
637    pub perform_rebuild: fn(&mut App, HandleId),
638    pub did_change_dependencies: fn(&mut App, HandleId),
639    pub update_inheritance: fn(&mut App, HandleId),
640    pub attach_notification_tree: fn(&mut App, HandleId),
641    pub build_scope: fn(&App, HandleId) -> Handle<BuildScope>,
642    pub mark_needs_build: fn(&mut App, HandleId),
643    pub on_notification: fn(&mut App, HandleId, &dyn Notification) -> bool,
644    pub debug_expects_render_object_for_slot: fn(&App, HandleId, Option<&Slot>) -> bool,
645    pub render_object: fn(&App, HandleId) -> Option<AnyRenderObject>,
646    pub debug_doing_build: fn(&App, HandleId) -> bool,
647    pub is_render_object_element: bool,
648    pub insert_render_object_child: fn(&mut App, HandleId, AnyRenderObject, Option<Slot>),
649    pub move_render_object_child:
650        fn(&mut App, HandleId, AnyRenderObject, Option<Slot>, Option<Slot>),
651    pub remove_render_object_child: fn(&mut App, HandleId, AnyRenderObject, Option<Slot>),
652    pub update_parent_data: fn(&mut App, HandleId, AnyElement),
653    pub is_parent_data_element: bool,
654    pub apply_parent_data: fn(&mut App, HandleId, AnyRenderObject) -> bool,
655    pub is_inherited_element: bool,
656    pub update_dependencies: fn(&mut App, HandleId, AnyElement, Option<Rc<dyn Any>>),
657    pub remove_dependent: fn(&mut App, HandleId, AnyElement),
658    pub state_handle_id: fn(&App, HandleId) -> Option<(TypeId, HandleId)>,
659}
660
661/// The typed handle for an erased id. Free: nothing is looked up; `App::get` checks the slot.
662fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
663    Handle::from_id(id)
664}
665
666impl ElementVTable {
667    pub(crate) const fn of<T: Element>() -> ElementVTable {
668        ElementVTable {
669            type_name: std::any::type_name::<T>,
670            debug_fill_properties: |app, id, properties| {
671                T::debug_fill_properties(resolve(id), app, properties)
672            },
673            debug_describe_children: |app, id| T::debug_describe_children(resolve(id), app),
674            element_data: |app, id| T::element_data(resolve(id), app),
675            element_data_mut: |app, id| T::element_data_mut(resolve(id), app),
676            visit_children: |app, id, visitor| T::visit_children(resolve(id), app, visitor),
677            debug_visit_onstage_children: |app, id, visitor| {
678                T::debug_visit_onstage_children(resolve(id), app, visitor)
679            },
680            render_object_attaching_child: |app, id| {
681                T::render_object_attaching_child(resolve(id), app)
682            },
683            mount: |app, id, parent, slot| T::mount(resolve(id), app, parent, slot),
684            update: |app, id, widget| T::update(resolve(id), app, widget),
685            update_slot: |app, id, slot| T::update_slot(resolve(id), app, slot),
686            attach_render_object: |app, id, slot| T::attach_render_object(resolve(id), app, slot),
687            detach_render_object: |app, id| T::detach_render_object(resolve(id), app),
688            forget_child: |app, id, child| T::forget_child(resolve(id), app, child),
689            activate: |app, id| T::activate(resolve(id), app),
690            deactivate: |app, id| T::deactivate(resolve(id), app),
691            debug_deactivated: |app, id| T::debug_deactivated(resolve(id), app),
692            unmount: |app, id| T::unmount(resolve(id), app),
693            perform_rebuild: |app, id| T::perform_rebuild(resolve(id), app),
694            did_change_dependencies: |app, id| T::did_change_dependencies(resolve(id), app),
695            update_inheritance: |app, id| T::update_inheritance(resolve(id), app),
696            attach_notification_tree: |app, id| T::attach_notification_tree(resolve(id), app),
697            build_scope: |app, id| T::build_scope(resolve(id), app),
698            mark_needs_build: |app, id| T::mark_needs_build(resolve(id), app),
699            on_notification: |app, id, notification| {
700                T::on_notification(resolve(id), app, notification)
701            },
702            debug_expects_render_object_for_slot: |app, id, slot| {
703                T::debug_expects_render_object_for_slot(resolve(id), app, slot)
704            },
705            render_object: |app, id| T::render_object(resolve(id), app),
706            debug_doing_build: |app, id| T::debug_doing_build(resolve(id), app),
707            is_render_object_element: T::IS_RENDER_OBJECT_ELEMENT,
708            insert_render_object_child: |app, id, child, slot| {
709                T::insert_render_object_child(resolve(id), app, child, slot)
710            },
711            move_render_object_child: |app, id, child, old_slot, new_slot| {
712                T::move_render_object_child(resolve(id), app, child, old_slot, new_slot)
713            },
714            remove_render_object_child: |app, id, child, slot| {
715                T::remove_render_object_child(resolve(id), app, child, slot)
716            },
717            update_parent_data: |app, id, element| T::update_parent_data(resolve(id), app, element),
718            is_parent_data_element: T::IS_PARENT_DATA_ELEMENT,
719            apply_parent_data: |app, id, render_object| {
720                T::apply_parent_data(resolve(id), app, render_object)
721            },
722            is_inherited_element: T::IS_INHERITED_ELEMENT,
723            update_dependencies: |app, id, dependent, aspect| {
724                T::update_dependencies(resolve(id), app, dependent, aspect)
725            },
726            remove_dependent: |app, id, dependent| T::remove_dependent(resolve(id), app, dependent),
727            state_handle_id: |app, id| T::state_handle_id(resolve(id), app),
728        }
729    }
730}
731
732/// Erased `Element`: one identity and a static vtable, like `AnyRenderObject`.
733///
734/// Equality is Dart's `==` on an element, which is identity.
735#[derive(Clone, Copy)]
736pub struct AnyElement {
737    id: HandleId,
738    vtable: &'static ElementVTable,
739}
740
741impl PartialEq for AnyElement {
742    fn eq(&self, other: &AnyElement) -> bool {
743        self.id == other.id
744    }
745}
746
747impl Eq for AnyElement {}
748
749impl Hash for AnyElement {
750    fn hash<H: Hasher>(&self, state: &mut H) {
751        self.id.hash(state);
752    }
753}
754
755impl Debug for AnyElement {
756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757        write!(f, "Element({:?})", self.id)
758    }
759}
760
761impl AnyElement {
762    /// The arena id behind this handle.
763    pub fn id(self) -> HandleId {
764        self.id
765    }
766
767    /// Dart's `element as T`: the typed handle when this element is a `T`, else `None`.
768    pub fn downcast<T: Element>(self, app: &App) -> Option<Handle<T>> {
769        app.handle::<T>(self.id)
770    }
771
772    pub(crate) fn data(self, app: &App) -> &ElementData {
773        (self.vtable.element_data)(app, self.id)
774    }
775
776    pub(crate) fn data_mut(self, app: &mut App) -> &mut ElementData {
777        (self.vtable.element_data_mut)(app, self.id)
778    }
779
780    /// Diffs the entities `build` read and binds [`observe`](App::observe_entity_id) watches.
781    pub(crate) fn bind_entity_watches(self, app: &mut App, tracked: TrackedSet) {
782        let current: HashSet<EntityId> = self.data(app).entity_watches.keys().copied().collect();
783        let tracked: HashSet<EntityId> = tracked.iter().collect();
784        for id in current.difference(&tracked) {
785            self.data_mut(app).entity_watches.remove(id);
786        }
787        let added: Vec<EntityId> = tracked.difference(&current).copied().collect();
788        for id in added {
789            let element = self;
790            let subscription = app.observe_entity_id(id, move |app| {
791                if element.lifecycle(app) == ElementLifecycle::Active {
792                    element.mark_needs_build(app);
793                }
794                true
795            });
796            self.data_mut(app).entity_watches.insert(id, subscription);
797        }
798        app.flush_entity_effects();
799    }
800
801    // ---- fields ----
802
803    /// The configuration for this element.
804    ///
805    /// Avoid overriding this field on `Element` subtypes.
806    pub fn widget(self, app: &App) -> &WidgetRef {
807        self.data(app).widget_ref()
808    }
809
810    /// Returns true if the Element is active.
811    ///
812    /// A defunct element is freed after its unmount; a handle kept past that, as a callback
813    /// keeps its `BuildContext`, answers false.
814    pub fn mounted(self, app: &App) -> bool {
815        app.contains(self.id) && self.data(app).widget.is_some()
816    }
817
818    /// The parent of this element, or `None` at the root.
819    pub fn parent(self, app: &App) -> Option<AnyElement> {
820        self.data(app).parent
821    }
822
823    /// Information set by parent to define where this child fits in its parent's child list.
824    pub fn slot(self, app: &App) -> Option<Slot> {
825        self.data(app).slot.clone()
826    }
827
828    /// An integer that is guaranteed to be greater than the parent's, if any. The element at
829    /// the root of the tree must have a depth greater than 0.
830    pub fn depth(self, app: &App) -> u32 {
831        debug_assert!(
832            self.lifecycle(app) != ElementLifecycle::Initial,
833            "Depth is only available when element has been mounted."
834        );
835        self.data(app).depth
836    }
837
838    /// The object that manages the lifecycle of this element.
839    pub fn owner(self, app: &App) -> Option<Handle<BuildOwner>> {
840        self.data(app).owner
841    }
842
843    /// The [`BuildScope`] whose dirty list this element is in.
844    pub fn build_scope(self, app: &App) -> Handle<BuildScope> {
845        (self.vtable.build_scope)(app, self.id)
846    }
847
848    /// Where this element is in its lifecycle; a freed element is defunct.
849    pub fn lifecycle(self, app: &App) -> ElementLifecycle {
850        if !app.contains(self.id) {
851            return ElementLifecycle::Defunct;
852        }
853        self.data(app).lifecycle
854    }
855
856    /// Dart's `toStringShort`: the widget's, or the element's identity once it has none.
857    pub fn to_string_short(self, app: &App) -> String {
858        match &self.data(app).widget {
859            Some(widget) => widget.to_string_short(),
860            None => format!(
861                "{}(DEFUNCT)",
862                describe_identity(
863                    bare_type_name((self.vtable.type_name)()),
864                    self.id.identity_hash()
865                )
866            ),
867        }
868    }
869
870    /// Dart's `toDiagnosticsNode(name:)`: a snapshot of this element and its descendants as a
871    /// dump shows them, one line each in the dense style.
872    pub fn to_diagnostics_node(
873        self,
874        app: &App,
875        name: impl IntoPropertyName,
876    ) -> ElementDiagnosticsNode {
877        let mut properties = DiagnosticPropertiesBuilder::new();
878        self.fill_base_properties(app, &mut properties);
879        (self.vtable.debug_fill_properties)(app, self.id, &mut properties);
880        let children = (self.vtable.debug_describe_children)(app, self.id);
881        let node = DiagnosticableTreeNode::from_parts(
882            name,
883            self.to_string_short(app),
884            properties,
885            children,
886        )
887        .with_value_id(self.id());
888        let widget = self.data(app).widget.as_ref();
889        let facts = ElementFacts {
890            widget_runtime_type: widget.map(|widget| widget.type_name()),
891            stateful: widget.is_some_and(|widget| widget.kind() == WidgetKind::Stateful),
892            creation_location: widget.and_then(|widget| widget.creation_location()),
893        };
894        ElementDiagnosticsNode::new(node, facts)
895    }
896
897    /// Dart's `Element.toStringDeep`: this element and its descendants, at Dart's default level
898    /// (debug) and width.
899    pub fn to_string_deep(self, app: &App) -> String {
900        self.to_string_deep_with(app, DiagnosticLevel::Debug, 65)
901    }
902
903    /// [`to_string_deep`](Self::to_string_deep) showing only properties at `min_level` or
904    /// above, wrapping a line at `wrap_width` characters.
905    pub fn to_string_deep_with(
906        self,
907        app: &App,
908        min_level: DiagnosticLevel,
909        wrap_width: usize,
910    ) -> String {
911        self.to_diagnostics_node(app, None).to_string_deep_with(
912            "",
913            Some(""),
914            None,
915            min_level,
916            wrap_width,
917        )
918    }
919
920    /// The properties `Element.debugFillProperties` adds, with its widget's among them, then
921    /// `RenderObjectElement`'s render object.
922    fn fill_base_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
923        properties.default_diagnostics_tree_style = DiagnosticsTreeStyle::Dense;
924        let data = self.data(app);
925        if data.lifecycle != ElementLifecycle::Initial {
926            properties.add(ObjectFlagProperty::<u32>::new("depth", data.depth).if_null("no depth"));
927        }
928        properties.add(
929            ObjectFlagProperty::<String>::new(
930                "widget",
931                data.widget.as_ref().map(|widget| widget.to_string_short()),
932            )
933            .if_null("no widget"),
934        );
935        let key = data.widget.as_ref().and_then(|widget| widget.key());
936        properties.add(
937            DiagnosticsProperty::<String>::new("key", key.map(|key| format!("{key:?}")))
938                .with_show_name(false)
939                .default_value(None)
940                .with_level(DiagnosticLevel::Hidden),
941        );
942        if let Some(widget) = &data.widget {
943            widget.debug_fill_properties(app, properties);
944        }
945        properties.add(FlagProperty::new("dirty", data.dirty).if_true("dirty"));
946        if let Some(dependencies) = data.dependencies.as_ref().filter(|set| !set.is_empty()) {
947            let mut names: Vec<String> = dependencies
948                .iter()
949                .map(|dependency| dependency.to_string_short(app))
950                .collect();
951            names.sort();
952            properties.add(DiagnosticsProperty::<String>::new(
953                "dependencies",
954                format!("[{}]", names.join(", ")),
955            ));
956        }
957        if self.is_render_object_element() {
958            properties.add(
959                DiagnosticsProperty::<String>::new(
960                    "renderObject",
961                    self.render_object(app)
962                        .map(|render_object| render_object.to_string_short(app)),
963                )
964                .default_value(None),
965            );
966        }
967    }
968
969    /// Whether the element is active (in the tree).
970    pub fn debug_is_active(self, app: &App) -> bool {
971        self.lifecycle(app) == ElementLifecycle::Active
972    }
973
974    /// Whether the element is defunct (unmounted).
975    pub fn debug_is_defunct(self, app: &App) -> bool {
976        self.lifecycle(app) == ElementLifecycle::Defunct
977    }
978
979    /// Returns true if the element has been marked as needing rebuilding.
980    ///
981    /// The flag is true when the element is first created and after
982    /// [`mark_needs_build`](Self::mark_needs_build) has been called. The flag is reset to
983    /// false in the [`perform_rebuild`](Self::perform_rebuild) implementation.
984    pub fn dirty(self, app: &App) -> bool {
985        self.data(app).dirty
986    }
987
988    pub(crate) fn in_dirty_list(self, app: &App) -> bool {
989        self.data(app).in_dirty_list
990    }
991
992    /// Whether this element is in the middle of building.
993    pub fn debug_doing_build(self, app: &App) -> bool {
994        (self.vtable.debug_doing_build)(app, self.id)
995    }
996
997    /// The children, in visit order.
998    pub fn children(self, app: &App) -> Vec<AnyElement> {
999        let mut children = Vec::new();
1000        self.visit_children(app, &mut |child| children.push(child));
1001        children
1002    }
1003
1004    // ---- virtual dispatch ----
1005
1006    /// See [`Element::visit_children`].
1007    pub fn visit_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1008        (self.vtable.visit_children)(app, self.id, visitor);
1009    }
1010
1011    /// See [`Element::debug_visit_onstage_children`].
1012    pub fn debug_visit_onstage_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1013        (self.vtable.debug_visit_onstage_children)(app, self.id, visitor);
1014    }
1015
1016    /// Every element under this one, depth first with a parent before its children and siblings
1017    /// in order, without this one, and with `skip_offstage` only those onstage: Dart's
1018    /// `collectAllElementsFrom`.
1019    pub fn descendants(self, app: &App, skip_offstage: bool) -> Vec<AnyElement> {
1020        let children_of = |element: AnyElement| {
1021            let mut children = Vec::new();
1022            if skip_offstage {
1023                element.debug_visit_onstage_children(app, &mut |child| children.push(child));
1024            } else {
1025                element.visit_children(app, &mut |child| children.push(child));
1026            }
1027            children
1028        };
1029        let mut found = Vec::new();
1030        let mut pending: Vec<AnyElement> = children_of(self).into_iter().rev().collect();
1031        while let Some(element) = pending.pop() {
1032            found.push(element);
1033            pending.extend(children_of(element).into_iter().rev());
1034        }
1035        found
1036    }
1037
1038    /// See [`Element::render_object_attaching_child`].
1039    pub fn render_object_attaching_child(self, app: &App) -> Option<AnyElement> {
1040        (self.vtable.render_object_attaching_child)(app, self.id)
1041    }
1042
1043    /// See [`Element::mount`].
1044    pub fn mount(self, app: &mut App, parent: Option<AnyElement>, new_slot: Option<Slot>) {
1045        (self.vtable.mount)(app, self.id, parent, new_slot);
1046    }
1047
1048    /// See [`Element::update`].
1049    pub fn update(self, app: &mut App, new_widget: WidgetRef) {
1050        (self.vtable.update)(app, self.id, new_widget);
1051    }
1052
1053    /// See [`Element::update_slot`].
1054    pub fn update_slot(self, app: &mut App, new_slot: Option<Slot>) {
1055        (self.vtable.update_slot)(app, self.id, new_slot);
1056    }
1057
1058    /// See [`Element::attach_render_object`].
1059    pub fn attach_render_object(self, app: &mut App, new_slot: Option<Slot>) {
1060        (self.vtable.attach_render_object)(app, self.id, new_slot);
1061    }
1062
1063    /// See [`Element::detach_render_object`].
1064    pub fn detach_render_object(self, app: &mut App) {
1065        (self.vtable.detach_render_object)(app, self.id);
1066    }
1067
1068    /// See [`Element::forget_child`].
1069    pub fn forget_child(self, app: &mut App, child: AnyElement) {
1070        (self.vtable.forget_child)(app, self.id, child);
1071    }
1072
1073    /// See [`Element::activate`].
1074    pub fn activate(self, app: &mut App) {
1075        (self.vtable.activate)(app, self.id);
1076    }
1077
1078    /// See [`Element::deactivate`].
1079    pub fn deactivate(self, app: &mut App) {
1080        (self.vtable.deactivate)(app, self.id);
1081    }
1082
1083    /// See [`Element::debug_deactivated`].
1084    pub fn debug_deactivated(self, app: &mut App) {
1085        (self.vtable.debug_deactivated)(app, self.id);
1086    }
1087
1088    /// See [`Element::unmount`].
1089    pub fn unmount(self, app: &mut App) {
1090        (self.vtable.unmount)(app, self.id);
1091    }
1092
1093    /// See [`Element::perform_rebuild`].
1094    pub fn perform_rebuild(self, app: &mut App) {
1095        (self.vtable.perform_rebuild)(app, self.id);
1096    }
1097
1098    /// See [`Element::did_change_dependencies`].
1099    pub fn did_change_dependencies(self, app: &mut App) {
1100        (self.vtable.did_change_dependencies)(app, self.id);
1101    }
1102
1103    /// See [`Element::update_inheritance`].
1104    pub fn update_inheritance(self, app: &mut App) {
1105        (self.vtable.update_inheritance)(app, self.id);
1106    }
1107
1108    /// See [`Element::attach_notification_tree`].
1109    pub fn attach_notification_tree(self, app: &mut App) {
1110        (self.vtable.attach_notification_tree)(app, self.id);
1111    }
1112
1113    /// See [`Element::on_notification`].
1114    pub fn on_notification(self, app: &mut App, notification: &dyn Notification) -> bool {
1115        (self.vtable.on_notification)(app, self.id, notification)
1116    }
1117
1118    /// Start bubbling this notification at the given build context.
1119    ///
1120    /// The notification will be delivered to any `NotificationListener` widgets with the
1121    /// appropriate type parameters that are ancestors of the given [`BuildContext`].
1122    pub fn dispatch_notification(self, app: &mut App, notification: &dyn Notification) {
1123        let tree = self.data(app).notification_tree.clone();
1124        if let Some(tree) = tree {
1125            tree.dispatch_notification(app, notification);
1126        }
1127    }
1128
1129    /// See [`Element::debug_expects_render_object_for_slot`].
1130    pub fn debug_expects_render_object_for_slot(self, app: &App, slot: Option<&Slot>) -> bool {
1131        (self.vtable.debug_expects_render_object_for_slot)(app, self.id, slot)
1132    }
1133
1134    /// The render object at (or below) this location in the tree.
1135    ///
1136    /// If this object is a `RenderObjectElement`, the render object is the one at this
1137    /// location in the tree. Otherwise, this getter will walk down the tree until it finds a
1138    /// `RenderObjectElement`.
1139    ///
1140    /// Some locations in the tree are not backed by a render object. In those cases, this
1141    /// getter returns `None`.
1142    pub fn render_object(self, app: &App) -> Option<AnyRenderObject> {
1143        (self.vtable.render_object)(app, self.id)
1144    }
1145
1146    /// `Element.inflateWidget`: create an element for the given widget and add it as a child of
1147    /// this element in the given slot.
1148    #[inline(always)]
1149    pub fn inflate_widget(
1150        self,
1151        app: &mut App,
1152        new_widget: WidgetRef,
1153        new_slot: Option<Slot>,
1154    ) -> AnyElement {
1155        let inactive_child = match new_widget.key() {
1156            Some(KeyRef::Global(key)) => self.retake_inactive_element(app, key, &new_widget),
1157            _ => None,
1158        };
1159        match inactive_child {
1160            Some(inactive_child) => {
1161                self.inflate_inactive_child(app, inactive_child, new_widget, new_slot)
1162            }
1163            None => {
1164                let new_child = new_widget.create_element(app, new_widget.clone());
1165                debug_assert!(debug_check_for_cycles(self, app, new_child));
1166                new_child.mount(app, Some(self), new_slot);
1167                debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
1168                new_child
1169            }
1170        }
1171    }
1172
1173    /// [`inflate_widget`](Self::inflate_widget) for a child taken back from the inactive
1174    /// elements by its global key. Out of line so that `inflate_widget` and
1175    /// [`update_child`](Self::update_child), which this calls, can both fold into the element
1176    /// that runs them.
1177    #[inline(never)]
1178    fn inflate_inactive_child(
1179        self,
1180        app: &mut App,
1181        inactive_child: AnyElement,
1182        new_widget: WidgetRef,
1183        new_slot: Option<Slot>,
1184    ) -> AnyElement {
1185        debug_assert!(inactive_child.parent(app).is_none());
1186        inactive_child.activate_with_parent(app, self, new_slot.clone());
1187        let updated_child =
1188            self.update_child(app, Some(inactive_child), Some(new_widget), new_slot);
1189        debug_assert!(updated_child == Some(inactive_child));
1190        updated_child.expect("a retaken child stays")
1191    }
1192
1193    /// Dart's `this is RenderObjectElement`.
1194    pub fn is_render_object_element(self) -> bool {
1195        self.vtable.is_render_object_element
1196    }
1197
1198    /// See [`Element::insert_render_object_child`].
1199    pub fn insert_render_object_child(
1200        self,
1201        app: &mut App,
1202        child: AnyRenderObject,
1203        slot: Option<Slot>,
1204    ) {
1205        (self.vtable.insert_render_object_child)(app, self.id, child, slot);
1206    }
1207
1208    /// See [`Element::move_render_object_child`].
1209    pub fn move_render_object_child(
1210        self,
1211        app: &mut App,
1212        child: AnyRenderObject,
1213        old_slot: Option<Slot>,
1214        new_slot: Option<Slot>,
1215    ) {
1216        (self.vtable.move_render_object_child)(app, self.id, child, old_slot, new_slot);
1217    }
1218
1219    /// See [`Element::remove_render_object_child`].
1220    pub fn remove_render_object_child(
1221        self,
1222        app: &mut App,
1223        child: AnyRenderObject,
1224        slot: Option<Slot>,
1225    ) {
1226        (self.vtable.remove_render_object_child)(app, self.id, child, slot);
1227    }
1228
1229    /// See [`Element::update_parent_data`].
1230    pub fn update_parent_data(self, app: &mut App, parent_data_element: AnyElement) {
1231        (self.vtable.update_parent_data)(app, self.id, parent_data_element);
1232    }
1233
1234    /// Dart's `this is ParentDataElement`.
1235    pub fn is_parent_data_element(self) -> bool {
1236        self.vtable.is_parent_data_element
1237    }
1238
1239    /// See [`Element::apply_parent_data`].
1240    pub fn apply_parent_data(self, app: &mut App, render_object: AnyRenderObject) -> bool {
1241        (self.vtable.apply_parent_data)(app, self.id, render_object)
1242    }
1243
1244    /// Dart's `this is InheritedElement`.
1245    pub fn is_inherited_element(self) -> bool {
1246        self.vtable.is_inherited_element
1247    }
1248
1249    /// See [`Element::update_dependencies`].
1250    pub fn update_dependencies(
1251        self,
1252        app: &mut App,
1253        dependent: AnyElement,
1254        aspect: Option<Rc<dyn Any>>,
1255    ) {
1256        (self.vtable.update_dependencies)(app, self.id, dependent, aspect);
1257    }
1258
1259    /// See [`Element::remove_dependent`].
1260    pub fn remove_dependent(self, app: &mut App, dependent: AnyElement) {
1261        (self.vtable.remove_dependent)(app, self.id, dependent);
1262    }
1263
1264    /// The typed state handle when this is a `StatefulElement` whose state is an `S`.
1265    pub fn state_handle<S: State>(self, app: &App) -> Option<Handle<S>> {
1266        let (type_id, id) = (self.vtable.state_handle_id)(app, self.id)?;
1267        (type_id == TypeId::of::<S>()).then(|| Handle::from_id(id))
1268    }
1269
1270    // ---- Dart's `Element` concrete members ----
1271
1272    /// Update the given child with the given new configuration.
1273    ///
1274    /// This method is the core of the widgets system. It is called each time we are to add,
1275    /// update, or remove a child based on an updated configuration.
1276    ///
1277    /// The `new_slot` argument specifies the new value for this element's
1278    /// [`slot`](Self::slot).
1279    ///
1280    /// If the `child` is `None`, and the `new_widget` is not `None`, then we have a new child
1281    /// for which we need to create an [`Element`], configured with `new_widget`.
1282    ///
1283    /// If the `new_widget` is `None`, and the `child` is not `None`, then we need to remove
1284    /// it because it no longer has a configuration.
1285    ///
1286    /// If neither are `None`, then we need to update the `child`'s configuration to be the
1287    /// new configuration given by `new_widget`. If `new_widget` can be given to the existing
1288    /// child (as determined by `can_update`), then it is so given. Otherwise, the old child
1289    /// needs to be disposed and a new child created for the new configuration.
1290    ///
1291    /// If both are `None`, then we don't have a child and won't have a child, so we do
1292    /// nothing.
1293    ///
1294    /// The [`update_child`](Self::update_child) method returns the new child, if it had to
1295    /// create one, or the child that was passed in, if it just had to update the child, or
1296    /// `None`, if it removed the child and did not replace it.
1297    #[inline(always)]
1298    pub fn update_child(
1299        self,
1300        app: &mut App,
1301        child: Option<AnyElement>,
1302        new_widget: Option<WidgetRef>,
1303        new_slot: Option<Slot>,
1304    ) -> Option<AnyElement> {
1305        let Some(new_widget) = new_widget else {
1306            if let Some(child) = child {
1307                self.deactivate_child(app, child);
1308            }
1309            return None;
1310        };
1311        let new_child = match child {
1312            Some(child) => {
1313                let has_same_superclass = child.widget(app).kind() == new_widget.kind();
1314                if has_same_superclass && same_widget(child.widget(app), &new_widget) {
1315                    if child.slot(app) != new_slot {
1316                        self.update_slot_for_child(app, child, new_slot);
1317                    }
1318                    child
1319                } else if has_same_superclass && can_update(&**child.widget(app), &*new_widget) {
1320                    if child.slot(app) != new_slot {
1321                        self.update_slot_for_child(app, child, new_slot);
1322                    }
1323                    child.update(app, new_widget.clone());
1324                    debug_assert!(same_widget(child.widget(app), &new_widget));
1325                    child
1326                } else {
1327                    self.deactivate_child(app, child);
1328                    debug_assert!(child.parent(app).is_none());
1329                    self.inflate_widget(app, new_widget, new_slot)
1330                }
1331            }
1332            None => self.inflate_widget(app, new_widget, new_slot),
1333        };
1334        Some(new_child)
1335    }
1336
1337    /// Updates the children of this element to use new widgets.
1338    ///
1339    /// Attempts to update the given old children list using the given new widgets, removing
1340    /// obsolete elements and introducing new ones as necessary, and then returns the new
1341    /// child list.
1342    ///
1343    /// During this function the `old_children` list must not be modified. If the caller
1344    /// wishes to remove elements from `old_children` reentrantly while this function is on
1345    /// the stack, the caller can supply a `forgotten_children` argument, which can be
1346    /// modified while this function is on the stack. Whenever this function reads from
1347    /// `old_children`, this function first checks whether the child is in
1348    /// `forgotten_children`. If it is, the function acts as if the child was not in
1349    /// `old_children`.
1350    ///
1351    /// `forgotten_children` is a predicate so that it reads the caller's set live (in the
1352    /// arena, where a reentrant `forget_child` writes it) rather than a snapshot.
1353    ///
1354    /// This function is a convenience wrapper around [`update_child`](Self::update_child),
1355    /// which updates each individual child. If `slots` is non-`None`, the value for the
1356    /// `new_slot` argument of [`update_child`](Self::update_child) is retrieved from that
1357    /// list using the index that the currently processed `child` corresponds to in the
1358    /// `new_widgets` list (`new_widgets` and `slots` must have the same length). If `slots`
1359    /// is `None`, an [`IndexedSlot`] is used as the value for the `new_slot` argument. In
1360    /// that case, [`IndexedSlot::index`] is set to the index that the currently processed
1361    /// `child` corresponds to in the `new_widgets` list and [`IndexedSlot::value`] is set to
1362    /// the [`Element`] of the previous widget in that list (or `None` if it is the first
1363    /// child).
1364    pub fn update_children(
1365        self,
1366        app: &mut App,
1367        old_children: &[AnyElement],
1368        new_widgets: &[WidgetRef],
1369        forgotten_children: Option<ForgottenChildren<'_>>,
1370        slots: Option<&[Option<Slot>]>,
1371    ) -> Vec<AnyElement> {
1372        debug_assert!(slots.is_none_or(|slots| slots.len() == new_widgets.len()));
1373        let replace_with_null_if_forgotten = |app: &App, child: AnyElement| -> Option<AnyElement> {
1374            let forgotten = forgotten_children.is_some_and(|forgotten| forgotten(app, child));
1375            (!forgotten).then_some(child)
1376        };
1377        let slot_for =
1378            |new_child_index: usize, previous_child: Option<AnyElement>| -> Option<Slot> {
1379                match slots {
1380                    Some(slots) => slots[new_child_index].clone(),
1381                    None => Some(Slot::Indexed(IndexedSlot {
1382                        index: new_child_index,
1383                        value: previous_child,
1384                    })),
1385                }
1386            };
1387
1388        // This attempts to diff the new child list (newWidgets) with
1389        // the old child list (oldChildren), and produce a new list of elements to
1390        // be the new list of child elements of this element. The called of this
1391        // method is expected to update this render object accordingly.
1392
1393        // The cases it tries to optimize for are:
1394        //  - the old list is empty
1395        //  - the lists are identical
1396        //  - there is an insertion or removal of one or more widgets in
1397        //    only one place in the list
1398        // If a widget with a key is in both lists, it will be synced.
1399        // Widgets without keys might be synced but there is no guarantee.
1400
1401        // The general approach is to sync the entire new list backwards, as follows:
1402        // 1. Walk the lists from the top, invoking updateChild on each element.
1403        // 2. Walk the lists from the bottom, without syncing, and simply track the
1404        //    number of matching elements at the end.
1405        // 3. Walk the middle of the old list, and collect the keyed children in a map.
1406        // 4. Walk the middle of the new list, syncing with the keyed old children when
1407        //    keys match, otherwise inflating new elements.
1408        // 5. Walk the bottom of the lists, syncing the elements that matched at the end.
1409        // 6. Deactivate any old children that were not synced.
1410        let mut new_children_top = 0usize;
1411        let mut old_children_top = 0usize;
1412        let mut new_children_bottom = new_widgets.len() as isize - 1;
1413        let mut old_children_bottom = old_children.len() as isize - 1;
1414
1415        let mut new_children: Vec<Option<AnyElement>> = vec![None; new_widgets.len()];
1416        let mut previous_child: Option<AnyElement> = None;
1417
1418        // Update the top of the list.
1419        while (old_children_top as isize <= old_children_bottom)
1420            && (new_children_top as isize <= new_children_bottom)
1421        {
1422            let old_child = replace_with_null_if_forgotten(app, old_children[old_children_top]);
1423            let new_widget = &new_widgets[new_children_top];
1424            debug_assert!(
1425                old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
1426            );
1427            let Some(old_child) = old_child else {
1428                break;
1429            };
1430            if !can_update(&**old_child.widget(app), &**new_widget) {
1431                break;
1432            }
1433            let new_child = self
1434                .update_child(
1435                    app,
1436                    Some(old_child),
1437                    Some(new_widget.clone()),
1438                    slot_for(new_children_top, previous_child),
1439                )
1440                .expect("a widget yields a child");
1441            debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
1442            new_children[new_children_top] = Some(new_child);
1443            previous_child = Some(new_child);
1444            new_children_top += 1;
1445            old_children_top += 1;
1446        }
1447
1448        // Scan the bottom of the list.
1449        while (old_children_top as isize <= old_children_bottom)
1450            && (new_children_top as isize <= new_children_bottom)
1451        {
1452            let old_child =
1453                replace_with_null_if_forgotten(app, old_children[old_children_bottom as usize]);
1454            let new_widget = &new_widgets[new_children_bottom as usize];
1455            debug_assert!(
1456                old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
1457            );
1458            let Some(old_child) = old_child else {
1459                break;
1460            };
1461            if !can_update(&**old_child.widget(app), &**new_widget) {
1462                break;
1463            }
1464            old_children_bottom -= 1;
1465            new_children_bottom -= 1;
1466        }
1467
1468        // Scan the old children in the middle of the list.
1469        let have_old_children = old_children_top as isize <= old_children_bottom;
1470        let mut old_keyed_children: HashMap<KeyRef, AnyElement> = HashMap::new();
1471        if have_old_children {
1472            while old_children_top as isize <= old_children_bottom {
1473                let old_child = replace_with_null_if_forgotten(app, old_children[old_children_top]);
1474                debug_assert!(
1475                    old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
1476                );
1477                if let Some(old_child) = old_child {
1478                    match old_child.widget(app).key().cloned() {
1479                        Some(key) => {
1480                            old_keyed_children.insert(key, old_child);
1481                        }
1482                        None => self.deactivate_child(app, old_child),
1483                    }
1484                }
1485                old_children_top += 1;
1486            }
1487        }
1488
1489        // Update the middle of the list.
1490        while new_children_top as isize <= new_children_bottom {
1491            let new_widget = &new_widgets[new_children_top];
1492            let mut old_child: Option<AnyElement> = None;
1493            if have_old_children
1494                && let Some(key) = new_widget.key()
1495                && let Some(candidate) = old_keyed_children.get(key).copied()
1496                && can_update(&**candidate.widget(app), &**new_widget)
1497            {
1498                // we found a match!
1499                // remove it from oldKeyedChildren so we don't unsync it later
1500                old_keyed_children.remove(key);
1501                old_child = Some(candidate);
1502            }
1503            debug_assert!(
1504                old_child.is_none_or(|old| can_update(&**old.widget(app), &**new_widget))
1505            );
1506            let new_child = self
1507                .update_child(
1508                    app,
1509                    old_child,
1510                    Some(new_widget.clone()),
1511                    slot_for(new_children_top, previous_child),
1512                )
1513                .expect("a widget yields a child");
1514            debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
1515            debug_assert!(old_child.is_none_or(
1516                |old| old == new_child || old.lifecycle(app) != ElementLifecycle::Active
1517            ));
1518            new_children[new_children_top] = Some(new_child);
1519            previous_child = Some(new_child);
1520            new_children_top += 1;
1521        }
1522
1523        // We've scanned the whole list.
1524        debug_assert!(old_children_top as isize == old_children_bottom + 1);
1525        debug_assert!(new_children_top as isize == new_children_bottom + 1);
1526        debug_assert!(
1527            new_widgets.len() - new_children_top == old_children.len() - old_children_top
1528        );
1529        new_children_bottom = new_widgets.len() as isize - 1;
1530        old_children_bottom = old_children.len() as isize - 1;
1531
1532        // Update the bottom of the list.
1533        while (old_children_top as isize <= old_children_bottom)
1534            && (new_children_top as isize <= new_children_bottom)
1535        {
1536            let old_child = old_children[old_children_top];
1537            debug_assert!(replace_with_null_if_forgotten(app, old_child).is_some());
1538            debug_assert!(old_child.lifecycle(app) == ElementLifecycle::Active);
1539            let new_widget = &new_widgets[new_children_top];
1540            debug_assert!(can_update(&**old_child.widget(app), &**new_widget));
1541            let new_child = self
1542                .update_child(
1543                    app,
1544                    Some(old_child),
1545                    Some(new_widget.clone()),
1546                    slot_for(new_children_top, previous_child),
1547                )
1548                .expect("a widget yields a child");
1549            debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
1550            debug_assert!(
1551                old_child == new_child || old_child.lifecycle(app) != ElementLifecycle::Active
1552            );
1553            new_children[new_children_top] = Some(new_child);
1554            previous_child = Some(new_child);
1555            new_children_top += 1;
1556            old_children_top += 1;
1557        }
1558
1559        // Clean up any of the remaining middle nodes from the old list.
1560        if have_old_children {
1561            for old_child in old_keyed_children.into_values() {
1562                if replace_with_null_if_forgotten(app, old_child).is_some() {
1563                    self.deactivate_child(app, old_child);
1564                }
1565            }
1566        }
1567        new_children
1568            .into_iter()
1569            .map(|child| child.expect("every slot was filled"))
1570            .collect()
1571    }
1572
1573    /// Change the slot that the given child occupies in its parent.
1574    ///
1575    /// Called by `MultiChildRenderObjectElement`, and other `RenderObjectElement` subclasses
1576    /// that have multiple children, when child moves from one position to another in this
1577    /// element's child list.
1578    pub fn update_slot_for_child(self, app: &mut App, child: AnyElement, new_slot: Option<Slot>) {
1579        debug_assert!(self.lifecycle(app) == ElementLifecycle::Active);
1580        debug_assert!(child.parent(app) == Some(self));
1581        let mut element = Some(child);
1582        while let Some(current) = element {
1583            current.update_slot(app, new_slot.clone());
1584            element = current.render_object_attaching_child(app);
1585        }
1586    }
1587
1588    fn update_depth(self, app: &mut App, parent_depth: u32) {
1589        let expected_depth = parent_depth + 1;
1590        if self.data(app).depth < expected_depth {
1591            self.data_mut(app).depth = expected_depth;
1592            for child in self.children(app) {
1593                child.update_depth(app, expected_depth);
1594            }
1595        }
1596    }
1597
1598    fn update_build_scope_recursively(self, app: &mut App) {
1599        let parent_scope = self.parent(app).map(|parent| parent.build_scope(app));
1600        if self.data(app).parent_build_scope == parent_scope {
1601            return;
1602        }
1603        // Unset the _inDirtyList flag so this Element can be added to the dirty list
1604        // of the new build scope.
1605        let data = self.data_mut(app);
1606        data.in_dirty_list = false;
1607        data.parent_build_scope = parent_scope;
1608        for child in self.children(app) {
1609            child.update_build_scope_recursively(app);
1610        }
1611    }
1612
1613    fn retake_inactive_element(
1614        self,
1615        app: &mut App,
1616        key: &GlobalKey,
1617        new_widget: &WidgetRef,
1618    ) -> Option<AnyElement> {
1619        // The "inactivity" of the element being retaken here may be forward-looking: if
1620        // we are taking an element with a GlobalKey from an element that currently has
1621        // it as a child, then we know that element will soon no longer have that
1622        // element as a child. The only way that assumption could be false is if the
1623        // global key is being duplicated, and we'll try to track that using the
1624        // _debugTrackElementThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans call below.
1625        let owner = self.owner(app).expect("a mounted element has an owner");
1626        let element = owner.global_key_element(app, key)?;
1627        if !can_update(&**element.widget(app), &**new_widget) {
1628            return None;
1629        }
1630        if let Some(parent) = element.parent(app) {
1631            assert!(
1632                parent != self,
1633                "A GlobalKey was used multiple times inside one widget's child list. A \
1634                 GlobalKey can only be specified on one widget at a time in the widget tree."
1635            );
1636            parent.forget_child(app, element);
1637            parent.deactivate_child(app, element);
1638        }
1639        debug_assert!(element.parent(app).is_none());
1640        owner.inactive_remove(app, element);
1641        Some(element)
1642    }
1643
1644    /// Move the given element to the list of inactive elements and detach its render object
1645    /// from the render tree.
1646    ///
1647    /// This method stops the given element from being a child of this element by detaching
1648    /// its render object from the render tree and moving the element to the list of inactive
1649    /// elements.
1650    ///
1651    /// This method (indirectly) calls [`deactivate`](Self::deactivate) on the child.
1652    ///
1653    /// The caller is responsible for removing the child from its child model. Typically
1654    /// [`deactivate_child`](Self::deactivate_child) is called by the element itself while it
1655    /// is updating its child model; however, during
1656    /// `GlobalKey` reparenting, the new parent proactively calls the old parent's
1657    /// [`deactivate_child`](Self::deactivate_child), first using [`forget_child`](Self::forget_child)
1658    /// to cause the old parent to update its child model.
1659    pub fn deactivate_child(self, app: &mut App, child: AnyElement) {
1660        debug_assert!(child.parent(app) == Some(self));
1661        child.data_mut(app).parent = None;
1662        child.detach_render_object(app);
1663        let owner = self.owner(app).expect("a mounted element has an owner");
1664        owner.inactive_add(app, child); // this eventually calls child.deactivate()
1665    }
1666
1667    fn activate_with_parent(self, app: &mut App, parent: AnyElement, new_slot: Option<Slot>) {
1668        debug_assert!(self.lifecycle(app) == ElementLifecycle::Inactive);
1669        let parent_owner = parent.owner(app);
1670        let data = self.data_mut(app);
1671        data.parent = Some(parent);
1672        data.owner = parent_owner;
1673        let parent_depth = parent.depth(app);
1674        self.update_depth(app, parent_depth);
1675        self.update_build_scope_recursively(app);
1676        activate_recursively(app, self);
1677        self.attach_render_object(app, new_slot);
1678        debug_assert!(self.lifecycle(app) == ElementLifecycle::Active);
1679    }
1680
1681    pub(crate) fn ensure_deactivated(self, app: &mut App) {
1682        let dependencies: Vec<AnyElement> = self
1683            .data(app)
1684            .dependencies
1685            .iter()
1686            .flatten()
1687            .copied()
1688            .collect();
1689        for dependency in dependencies {
1690            dependency.remove_dependent(app, self);
1691        }
1692        // For expediency, we don't actually clear the list here, even though it's
1693        // no longer representative of what we are registered with. If we never
1694        // get re-used, it doesn't matter. If we do, then we'll clear the list in
1695        // activate(). The benefit of this is that it allows Element's activate()
1696        // implementation to decide whether to rebuild based on whether we had
1697        // dependencies here.
1698        let data = self.data_mut(app);
1699        data.inherited_elements = None;
1700        data.lifecycle = ElementLifecycle::Inactive;
1701    }
1702
1703    /// The current `RenderObject` for the widget. If the widget is a `RenderObjectWidget`,
1704    /// this is the render object that the widget created for itself. Otherwise, it is the
1705    /// render object of the first descendant `RenderObjectWidget`.
1706    ///
1707    /// This method will only return a valid result after the build phase is complete. It is
1708    /// therefore not valid to call this from a build method. It should only be called from
1709    /// interaction event handlers (e.g. gesture callbacks) or layout or paint callbacks. It
1710    /// is also not valid to call if [`mounted`](Self::mounted) is false.
1711    pub fn find_render_object(self, app: &App) -> Option<AnyRenderObject> {
1712        debug_assert!(
1713            self.lifecycle(app) == ElementLifecycle::Active,
1714            "Cannot get renderObject of inactive element. In order for an element to have a \
1715             valid renderObject, it must be active, which means it is part of the tree."
1716        );
1717        self.render_object(app)
1718    }
1719
1720    /// The size of the `RenderBox` returned by [`find_render_object`](Self::find_render_object).
1721    ///
1722    /// This getter will only return a valid result after the layout phase is complete. It is
1723    /// therefore not valid to call this from a build method. It should only be called from
1724    /// paint callbacks or interaction event handlers (e.g. gesture callbacks).
1725    ///
1726    /// This getter will only return a valid result if [`find_render_object`](Self::find_render_object)
1727    /// actually returns a `RenderBox`. If [`find_render_object`](Self::find_render_object)
1728    /// returns a render object that is not a subtype of `RenderBox` (e.g., `RenderView`),
1729    /// this getter will return `None`.
1730    pub fn size(self, app: &App) -> Option<Size> {
1731        debug_assert!(
1732            self.lifecycle(app) == ElementLifecycle::Active,
1733            "Cannot get size of inactive element."
1734        );
1735        debug_assert!(
1736            !self
1737                .owner(app)
1738                .is_some_and(|owner| owner.debug_building(app)),
1739            "Cannot get size during build."
1740        );
1741        let render_object = self.find_render_object(app)?;
1742        let render_box = render_object.as_box()?;
1743        debug_assert!(
1744            render_box.has_size(app),
1745            "Cannot get size from a render object that has not been through layout."
1746        );
1747        debug_assert!(
1748            !render_object.debug_needs_layout(app),
1749            "Cannot get size from a render object that has been marked dirty for layout."
1750        );
1751        Some(render_box.size(app))
1752    }
1753
1754    /// Returns `true` if `ancestor` is a dependency of this element.
1755    pub fn does_depend_on_inherited_element(self, app: &App, ancestor: AnyElement) -> bool {
1756        self.data(app)
1757            .dependencies
1758            .as_ref()
1759            .is_some_and(|dependencies| dependencies.contains(&ancestor))
1760    }
1761
1762    /// Registers this build context with `ancestor` such that when `ancestor`'s widget
1763    /// changes this build context is rebuilt.
1764    ///
1765    /// Returns `ancestor.widget`.
1766    ///
1767    /// This method is rarely called directly. Most applications should use
1768    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type),
1769    /// which calls this method after finding the appropriate `InheritedElement` ancestor.
1770    pub fn depend_on_inherited_element(
1771        self,
1772        app: &mut App,
1773        ancestor: AnyElement,
1774        aspect: Option<Rc<dyn Any>>,
1775    ) -> WidgetRef {
1776        self.data_mut(app)
1777            .dependencies
1778            .get_or_insert_with(HashSet::new)
1779            .insert(ancestor);
1780        ancestor.update_dependencies(app, self, aspect);
1781        ancestor.widget(app).clone()
1782    }
1783
1784    /// Returns the nearest widget of the given type `W` and creates a dependency on it, or
1785    /// `None` if no appropriate widget is found.
1786    ///
1787    /// The widget found will be a concrete [`InheritedWidget`] subclass, and calling this
1788    /// method registers this build context with the returned widget. When that widget
1789    /// changes (or a new widget of that type is introduced, or the widget goes away), this
1790    /// build context is rebuilt so that it can obtain new values from that widget.
1791    ///
1792    /// This is typically called implicitly from `of()` static methods, e.g. `Theme.of`.
1793    ///
1794    /// This method should not be called from widget constructors or from
1795    /// `State::init_state` methods, because those methods would not get called again if the
1796    /// inherited value were to change. To ensure that the widget correctly updates itself
1797    /// when the inherited value changes, only call this (directly or indirectly) from build
1798    /// methods, layout and paint callbacks, or from `State::did_change_dependencies`.
1799    pub fn depend_on_inherited_widget_of_exact_type<W: InheritedWidget>(
1800        self,
1801        app: &mut App,
1802    ) -> Option<&W> {
1803        self.depend_on_inherited_widget_of_exact_type_with_aspect::<W>(app, None)
1804    }
1805
1806    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
1807    /// with Dart's `aspect` argument, for `InheritedModel`.
1808    pub fn depend_on_inherited_widget_of_exact_type_with_aspect<W: InheritedWidget>(
1809        self,
1810        app: &mut App,
1811        aspect: Option<Rc<dyn Any>>,
1812    ) -> Option<&W> {
1813        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1814        let ancestor = self
1815            .data(app)
1816            .inherited_elements
1817            .as_ref()
1818            .and_then(|elements| elements.get(&TypeId::of::<W>()).copied());
1819        let Some(ancestor) = ancestor else {
1820            self.data_mut(app).had_unsatisfied_dependencies = true;
1821            return None;
1822        };
1823        self.depend_on_inherited_element(app, ancestor, aspect);
1824        let widget: &WidgetRef = ancestor.widget(app);
1825        downcast_widget::<W>(&**widget)
1826    }
1827
1828    /// Returns the nearest widget of the given [`InheritedWidget`] subclass `W` or `None` if
1829    /// an appropriate ancestor is not found.
1830    ///
1831    /// This method does not introduce a dependency the way that the more typical
1832    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
1833    /// does, so this context will not be rebuilt if the [`InheritedWidget`] changes. This
1834    /// function is meant for those uncommon use cases where a dependency is undesirable.
1835    pub fn get_inherited_widget_of_exact_type<W: InheritedWidget>(self, app: &App) -> Option<&W> {
1836        let element = self.get_element_for_inherited_widget_of_exact_type::<W>(app)?;
1837        let widget: &WidgetRef = element.widget(app);
1838        downcast_widget::<W>(&**widget)
1839    }
1840
1841    /// Obtains the element corresponding to the nearest widget of the given type `W`, which
1842    /// must be the type of a concrete [`InheritedWidget`] subclass.
1843    ///
1844    /// Returns `None` if no such element is found.
1845    ///
1846    /// Calling this method is O(1) with a small constant factor.
1847    ///
1848    /// This method does not establish a relationship with the target in the way that
1849    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
1850    /// does.
1851    pub fn get_element_for_inherited_widget_of_exact_type<W: InheritedWidget>(
1852        self,
1853        app: &App,
1854    ) -> Option<AnyElement> {
1855        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1856        self.data(app)
1857            .inherited_elements
1858            .as_ref()
1859            .and_then(|elements| elements.get(&TypeId::of::<W>()).copied())
1860    }
1861
1862    fn debug_check_state_is_active_for_ancestor_lookup(self, app: &App) -> bool {
1863        assert!(
1864            self.lifecycle(app) == ElementLifecycle::Active,
1865            "Looking up a deactivated widget's ancestor is unsafe. At this point the state of \
1866             the widget's element tree is no longer stable. To safely refer to a widget's \
1867             ancestor in its dispose() method, save a reference to the ancestor by calling \
1868             dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() \
1869             method."
1870        );
1871        true
1872    }
1873
1874    /// Returns the nearest ancestor widget of the given type `W`, which must be the type of
1875    /// a concrete `Widget` subclass.
1876    ///
1877    /// In general, [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
1878    /// is more useful, since inherited widgets will trigger consumers to rebuild when they
1879    /// change. This method is appropriate when used in interaction event handlers (e.g.
1880    /// gesture callbacks) or for performing one-off tasks such as asserting that you have or
1881    /// don't have a widget of a specific type as an ancestor. The return value of a Widget's
1882    /// build method should not depend on the value returned by this method, because the
1883    /// build context will not rebuild if the return value of this method changes. This could
1884    /// lead to a situation where data used in the build method changes, but the widget is
1885    /// not rebuilt.
1886    ///
1887    /// Calling this method is relatively expensive (O(N) in the depth of the tree). Only
1888    /// call this method if the distance from this widget to the desired ancestor is known to
1889    /// be small and bounded.
1890    pub fn find_ancestor_widget_of_exact_type<W: 'static>(self, app: &App) -> Option<&W> {
1891        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1892        let mut ancestor = self.parent(app);
1893        while let Some(current) = ancestor {
1894            if current.widget(app).widget_type() == TypeId::of::<W>() {
1895                return downcast_widget::<W>(&**current.widget(app));
1896            }
1897            ancestor = current.parent(app);
1898        }
1899        None
1900    }
1901
1902    /// Returns the [`State`] object of the nearest ancestor `StatefulWidget` widget that is
1903    /// an instance of the given type `S`.
1904    ///
1905    /// This should not be used from build methods, because the build context will not be
1906    /// rebuilt if the value that would be returned by this method changes. In general,
1907    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
1908    /// is more appropriate for such cases. This method is useful for changing the state of an
1909    /// ancestor widget in a one-off manner, for example, to cause an ancestor scrolling list
1910    /// to scroll this build context's widget into view, or to move the focus in response to
1911    /// user interaction.
1912    ///
1913    /// Calling this method is relatively expensive (O(N) in the depth of the tree). Only
1914    /// call this method if the distance from this widget to the desired ancestor is known to
1915    /// be small and bounded.
1916    pub fn find_ancestor_state_of_type<S: State>(self, app: &App) -> Option<Handle<S>> {
1917        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1918        let mut ancestor = self.parent(app);
1919        while let Some(current) = ancestor {
1920            if let Some(state) = current.state_handle::<S>(app) {
1921                return Some(state);
1922            }
1923            ancestor = current.parent(app);
1924        }
1925        None
1926    }
1927
1928    /// Returns the [`State`] object of the furthest ancestor `StatefulWidget` widget that is
1929    /// an instance of the given type `S`.
1930    ///
1931    /// Functions the same way as [`find_ancestor_state_of_type`](Self::find_ancestor_state_of_type)
1932    /// but keeps visiting subsequent ancestors until there are none of the type instance of
1933    /// `S` remaining. Then returns the last one found.
1934    ///
1935    /// This operation is O(N) as well though N is the entire widget tree rather than a
1936    /// subtree.
1937    pub fn find_root_ancestor_state_of_type<S: State>(self, app: &App) -> Option<Handle<S>> {
1938        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1939        let mut ancestor = self.parent(app);
1940        let mut stateful_ancestor = None;
1941        while let Some(current) = ancestor {
1942            if let Some(state) = current.state_handle::<S>(app) {
1943                stateful_ancestor = Some(state);
1944            }
1945            ancestor = current.parent(app);
1946        }
1947        stateful_ancestor
1948    }
1949
1950    /// Returns the `RenderObject` object of the nearest ancestor `RenderObjectWidget` widget
1951    /// that is an instance of the given type `R`.
1952    ///
1953    /// This should not be used from build methods, because the build context will not be
1954    /// rebuilt if the value that would be returned by this method changes. In general,
1955    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
1956    /// is more appropriate for such cases. This method is useful only in esoteric cases where
1957    /// a widget needs to cause an ancestor to change its layout or paint behavior. For
1958    /// example, it is used by `Material` so that `InkWell` widgets can trigger the ink splash
1959    /// on the `Material`'s actual render object.
1960    ///
1961    /// Calling this method is relatively expensive (O(N) in the depth of the tree). Only
1962    /// call this method if the distance from this widget to the desired ancestor is known to
1963    /// be small and bounded.
1964    pub fn find_ancestor_render_object_of_type<R: RenderObject>(
1965        self,
1966        app: &App,
1967    ) -> Option<RenderHandle<R>> {
1968        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1969        let mut ancestor = self.parent(app);
1970        while let Some(current) = ancestor {
1971            if current.is_render_object_element()
1972                && let Some(render_object) = current.render_object(app)
1973                && let Some(typed) = render_object.downcast::<R>(app)
1974            {
1975                return Some(typed);
1976            }
1977            ancestor = current.parent(app);
1978        }
1979        None
1980    }
1981
1982    /// Walks the ancestor chain, starting with the parent of this build context's widget,
1983    /// invoking the argument for each ancestor.
1984    ///
1985    /// The callback is given a reference to the ancestor widget's corresponding [`Element`]
1986    /// object. The walk stops when it reaches the root widget or when the callback returns
1987    /// false. The callback must not return `None`.
1988    ///
1989    /// This is useful for inspecting the widget tree.
1990    ///
1991    /// Calling this method is relatively expensive (O(N) in the depth of the tree).
1992    pub fn visit_ancestor_elements(self, app: &App, visitor: &mut dyn FnMut(AnyElement) -> bool) {
1993        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
1994        let mut ancestor = self.parent(app);
1995        while let Some(current) = ancestor {
1996            if !visitor(current) {
1997                break;
1998            }
1999            ancestor = current.parent(app);
2000        }
2001    }
2002
2003    /// Walks the children of this widget.
2004    ///
2005    /// This is useful for applying changes to children after they are built without waiting
2006    /// for the next frame, especially if the children are known, and especially if there is
2007    /// exactly one child (as is always the case for `StatefulWidget`s or `StatelessWidget`s).
2008    ///
2009    /// Calling this method is very cheap for build contexts that correspond to
2010    /// `StatefulWidget`s or `StatelessWidget`s (O(1), since there's only one child).
2011    ///
2012    /// Calling this method is potentially expensive for build contexts that correspond to
2013    /// `RenderObjectWidget`s (O(N) in the number of children).
2014    ///
2015    /// Calling this method recursively is extremely expensive (O(N) in the number of
2016    /// descendants), and should be avoided if possible. Generally it is significantly cheaper
2017    /// to use an `InheritedWidget` and have the descendants pull data down than it is to use
2018    /// [`visit_child_elements`](Self::visit_child_elements) recursively to push data down to
2019    /// them.
2020    pub fn visit_child_elements(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
2021        debug_assert!(
2022            !self
2023                .owner(app)
2024                .is_some_and(|owner| owner.debug_state_locked(app)),
2025            "visitChildElements() called during build."
2026        );
2027        self.visit_children(app, visitor);
2028    }
2029
2030    /// Dart's `_debugIsDescendantOf`.
2031    pub fn debug_is_descendant_of(self, app: &App, target: AnyElement) -> bool {
2032        let mut element = Some(self);
2033        while let Some(current) = element
2034            && current.depth(app) > target.depth(app)
2035        {
2036            element = current.parent(app);
2037        }
2038        element == Some(target)
2039    }
2040
2041    /// Marks the element as dirty and adds it to the global list of widgets to rebuild in the
2042    /// next frame.
2043    ///
2044    /// Since it is inefficient to build an element twice in one frame, applications and
2045    /// widgets should be structured so as to only mark widgets dirty during event handlers
2046    /// before the frame begins, not during the build itself.
2047    pub fn mark_needs_build(self, app: &mut App) {
2048        (self.vtable.mark_needs_build)(app, self.id);
2049    }
2050
2051    /// Cause the widget to update itself. In debug builds, also verify various invariants.
2052    ///
2053    /// Called by the [`BuildOwner`] when `BuildOwner::schedule_build_for` has been called to
2054    /// mark this element dirty, by [`mount`](Self::mount) when the element is first built,
2055    /// and by [`update`](Self::update) when the widget has changed.
2056    ///
2057    /// The method will only rebuild if [`dirty`](Self::dirty) is true. To rebuild
2058    /// irrespective of the [`dirty`](Self::dirty) flag, set `force` to true. Forcing a
2059    /// rebuild is convenient when [`update`](Self::update) is called, during which
2060    /// [`dirty`](Self::dirty) is false.
2061    pub fn rebuild(self, app: &mut App, force: bool) {
2062        if let Some(rebuilding) = self.begin_rebuild(app, force) {
2063            self.perform_rebuild(app);
2064            self.end_rebuild(app, rebuilding);
2065        }
2066    }
2067
2068    /// What [`rebuild`](Self::rebuild) checks and records before `perform_rebuild`, or `None`
2069    /// when the element needs no rebuild. Apart from `rebuild` itself so that an element of a
2070    /// known type can call its own `perform_rebuild` in between (see [`ElementBase::rebuild`]).
2071    #[inline(always)]
2072    pub(crate) fn begin_rebuild(self, app: &mut App, force: bool) -> Option<Rebuilding> {
2073        debug_assert!(self.lifecycle(app) != ElementLifecycle::Initial);
2074        if self.lifecycle(app) != ElementLifecycle::Active || (!self.dirty(app) && !force) {
2075            return None;
2076        }
2077        let owner = self.owner(app).expect("an active element has an owner");
2078        debug_assert!(owner.debug_state_locked(app));
2079        let debug_previous_build_target = owner.debug_current_build_target(app);
2080        if cfg!(debug_assertions) {
2081            owner.set_debug_current_build_target(app, Some(self));
2082            self.data_mut(app).debug_built_once = true;
2083        }
2084        Some(Rebuilding {
2085            owner,
2086            debug_previous_build_target,
2087        })
2088    }
2089
2090    /// What [`rebuild`](Self::rebuild) restores and checks after `perform_rebuild`.
2091    #[inline(always)]
2092    pub(crate) fn end_rebuild(self, app: &mut App, rebuilding: Rebuilding) {
2093        if cfg!(debug_assertions) {
2094            let owner = rebuilding.owner;
2095            debug_assert!(owner.debug_current_build_target(app) == Some(self));
2096            owner.set_debug_current_build_target(app, rebuilding.debug_previous_build_target);
2097        }
2098        debug_assert!(!self.dirty(app));
2099    }
2100
2101    pub(crate) fn had_dependencies(self, app: &App) -> bool {
2102        let data = self.data(app);
2103        data.dependencies
2104            .as_ref()
2105            .is_some_and(|dependencies| !dependencies.is_empty())
2106            || data.had_unsatisfied_dependencies
2107    }
2108
2109    /// The notification chain this element dispatches into.
2110    pub fn notification_tree(self, app: &App) -> Option<Rc<NotificationNode>> {
2111        self.data(app).notification_tree.clone()
2112    }
2113
2114    /// Sets the notification chain: a notifiable element chains a node for itself here.
2115    pub fn set_notification_tree(self, app: &mut App, tree: Option<Rc<NotificationNode>>) {
2116        self.data_mut(app).notification_tree = tree;
2117    }
2118
2119    pub(crate) fn inherited_elements(self, app: &App) -> Option<Rc<HashMap<TypeId, AnyElement>>> {
2120        self.data(app).inherited_elements.clone()
2121    }
2122
2123    pub(crate) fn set_inherited_elements(
2124        self,
2125        app: &mut App,
2126        elements: Option<Rc<HashMap<TypeId, AnyElement>>>,
2127    ) {
2128        self.data_mut(app).inherited_elements = elements;
2129    }
2130
2131    pub(crate) fn set_slot(self, app: &mut App, slot: Option<Slot>) {
2132        self.data_mut(app).slot = slot;
2133    }
2134
2135    pub(crate) fn set_dirty(self, app: &mut App, dirty: bool) {
2136        self.data_mut(app).dirty = dirty;
2137    }
2138
2139    /// `RootElementMixin.assignOwner`: set the owner of the element and its build scope.
2140    ///
2141    /// The owner of an element is determined at mount, so this should only be called on a
2142    /// root element that is about to be mounted without a parent.
2143    pub fn assign_owner(self, app: &mut App, owner: Handle<BuildOwner>) {
2144        let scope = BuildScope::new(app, None);
2145        let data = self.data_mut(app);
2146        data.owner = Some(owner);
2147        data.parent_build_scope = Some(scope.handle());
2148        data.root_build_scope = Some(scope);
2149    }
2150}
2151
2152/// Dart's `_activateRecursively`: activates `element`, then its children, in a loop rather than
2153/// recursion so a deep subtree costs no stack per level.
2154fn activate_recursively(app: &mut App, element: AnyElement) {
2155    let mut stack = vec![element];
2156    while let Some(element) = stack.pop() {
2157        debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
2158        element.activate(app);
2159        debug_assert!(element.lifecycle(app) == ElementLifecycle::Active);
2160        stack.extend(element.children(app).into_iter().rev());
2161    }
2162}
2163
2164// ---------------------------------------------------------------------------------------------
2165// Dart's `Element` base bodies. An override calls the one it would call as `super`.
2166
2167/// The build owner and earlier build target an element's rebuild restores once it is done.
2168pub(crate) struct Rebuilding {
2169    owner: Handle<BuildOwner>,
2170    debug_previous_build_target: Option<AnyElement>,
2171}
2172
2173/// Dart's `Element` bodies, reachable from an override the way `super.mount(..)` is.
2174///
2175/// Every [`Element`] implements it. An override that must run the inherited body calls it
2176/// trait-qualified, `ElementBase::mount(self, app, parent, new_slot)`, at the position Dart
2177/// calls `super`; the [`Element`] defaults run the same bodies.
2178pub trait ElementBase: Element {
2179    /// `Element.rebuild` for an element whose type is known: calls its
2180    /// [`perform_rebuild`](Element::perform_rebuild) directly rather than through the vtable,
2181    /// so a first build adds no frame on the way down the tree.
2182    #[inline(always)]
2183    fn rebuild(self: Handle<Self>, app: &mut App, force: bool) {
2184        let this = self.as_element();
2185        if let Some(rebuilding) = this.begin_rebuild(app, force) {
2186            Element::perform_rebuild(self, app);
2187            this.end_rebuild(app, rebuilding);
2188        }
2189    }
2190
2191    /// `Element.renderObjectAttachingChild`: the single child, if any.
2192    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
2193        let this = self.as_element();
2194        let mut next = None;
2195        this.visit_children(app, &mut |child| {
2196            debug_assert!(next.is_none()); // This verifies that there's only one child.
2197            next = Some(child);
2198        });
2199        next
2200    }
2201
2202    /// `Element.mount`.
2203    fn mount(
2204        self: Handle<Self>,
2205        app: &mut App,
2206        parent: Option<AnyElement>,
2207        new_slot: Option<Slot>,
2208    ) {
2209        let this = self.as_element();
2210        debug_assert!(
2211            this.lifecycle(app) == ElementLifecycle::Initial,
2212            "This element is no longer in its initial state ({:?})",
2213            this.lifecycle(app)
2214        );
2215        debug_assert!(
2216            this.parent(app).is_none(),
2217            "This element already has a parent and it shouldn't have one yet."
2218        );
2219        debug_assert!(
2220            parent.is_none_or(|parent| parent.lifecycle(app) == ElementLifecycle::Active),
2221            "Parent should be null or in the active state"
2222        );
2223        debug_assert!(
2224            this.slot(app).is_none(),
2225            "This element already has a slot and it shouldn't"
2226        );
2227        let parent_depth = parent.map_or(0, |parent| parent.depth(app));
2228        let parent_owner = parent.and_then(|parent| parent.owner(app));
2229        let parent_scope = parent.map(|parent| parent.build_scope(app));
2230        let data = this.data_mut(app);
2231        data.parent = parent;
2232        data.slot = new_slot;
2233        data.lifecycle = ElementLifecycle::Active;
2234        data.depth = 1 + parent_depth;
2235        if parent.is_some() {
2236            // Only assign ownership if the parent is non-null. If parent is null
2237            // (the root node), the owner should have already been assigned.
2238            // See RootRenderObjectElement.assignOwner().
2239            data.owner = parent_owner;
2240            data.parent_build_scope = parent_scope;
2241        }
2242        let owner = this.owner(app).expect("a mounted element has an owner");
2243        if let Some(KeyRef::Global(key)) = this.widget(app).key().cloned() {
2244            owner.register_global_key(app, &key, this);
2245        }
2246        this.update_inheritance(app);
2247        this.attach_notification_tree(app);
2248    }
2249
2250    /// `Element.update`.
2251    #[inline(always)]
2252    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
2253        let this = self.as_element();
2254        // This code is hot when hot reloading, so we try to
2255        // only call _AssertionError._evaluateAssertion once.
2256        debug_assert!(
2257            this.lifecycle(app) == ElementLifecycle::Active
2258                && !same_widget(this.widget(app), &new_widget)
2259                && can_update(&**this.widget(app), &*new_widget)
2260        );
2261        this.data_mut(app).widget = Some(new_widget);
2262    }
2263
2264    /// `Element.updateSlot`.
2265    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
2266        let this = self.as_element();
2267        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
2268        debug_assert!(this.parent(app).is_some());
2269        debug_assert!(
2270            this.parent(app)
2271                .is_some_and(|parent| parent.lifecycle(app) == ElementLifecycle::Active)
2272        );
2273        this.set_slot(app, new_slot);
2274    }
2275
2276    /// `Element.attachRenderObject`.
2277    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
2278        let this = self.as_element();
2279        debug_assert!(this.slot(app).is_none());
2280        for child in this.children(app) {
2281            child.attach_render_object(app, new_slot.clone());
2282        }
2283        this.set_slot(app, new_slot);
2284    }
2285
2286    /// `Element.detachRenderObject`.
2287    fn detach_render_object(self: Handle<Self>, app: &mut App) {
2288        let this = self.as_element();
2289        for child in this.children(app) {
2290            child.detach_render_object(app);
2291        }
2292        this.set_slot(app, None);
2293    }
2294
2295    /// `Element.activate`.
2296    fn activate(self: Handle<Self>, app: &mut App) {
2297        let this = self.as_element();
2298        debug_assert!(this.lifecycle(app) == ElementLifecycle::Inactive);
2299        let owner = this
2300            .owner(app)
2301            .expect("an inactive element keeps its owner");
2302        let had_dependencies = this.had_dependencies(app);
2303        let had_entity_watches = !this.data(app).entity_watches.is_empty();
2304        let data = this.data_mut(app);
2305        data.lifecycle = ElementLifecycle::Active;
2306        // We unregistered our dependencies in deactivate, but never cleared the list.
2307        // Since we're going to be reused, let's clear our list now.
2308        if let Some(dependencies) = &mut data.dependencies {
2309            dependencies.clear();
2310        }
2311        data.had_unsatisfied_dependencies = false;
2312        this.update_inheritance(app);
2313        this.attach_notification_tree(app);
2314        if this.dirty(app) {
2315            owner.schedule_build_for(app, this);
2316        }
2317        if had_dependencies {
2318            this.did_change_dependencies(app);
2319        } else if had_entity_watches {
2320            this.mark_needs_build(app);
2321        }
2322    }
2323
2324    /// `Element.deactivate`.
2325    fn deactivate(self: Handle<Self>, app: &mut App) {
2326        let this = self.as_element();
2327        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
2328        debug_assert!(this.mounted(app));
2329        this.ensure_deactivated(app);
2330    }
2331
2332    /// `Element.unmount`.
2333    fn unmount(self: Handle<Self>, app: &mut App) {
2334        let this = self.as_element();
2335        debug_assert!(this.lifecycle(app) == ElementLifecycle::Inactive);
2336        debug_assert!(this.mounted(app));
2337        let owner = this
2338            .owner(app)
2339            .expect("an inactive element keeps its owner");
2340        if let Some(KeyRef::Global(key)) = this.widget(app).key().cloned() {
2341            owner.unregister_global_key(app, &key, this);
2342        }
2343        // Release resources to reduce the severity of memory leaks caused by
2344        // defunct, but accidentally retained Elements.
2345        let data = this.data_mut(app);
2346        data.widget = None;
2347        data.dependencies = None;
2348        data.entity_watches.clear();
2349        data.lifecycle = ElementLifecycle::Defunct;
2350    }
2351
2352    /// `Element.performRebuild`: clears the dirty flag.
2353    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
2354        let this = self.as_element();
2355        this.set_dirty(app, false);
2356    }
2357
2358    /// `Element.didChangeDependencies`.
2359    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2360        let this = self.as_element();
2361        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active); // otherwise markNeedsBuild is a no-op
2362        debug_assert!(debug_check_owner_build_target_exists(
2363            this,
2364            app,
2365            "didChangeDependencies"
2366        ));
2367        this.mark_needs_build(app);
2368    }
2369
2370    /// `Element.attachNotificationTree`: inherit the parent's notification chain.
2371    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
2372        let this = self.as_element();
2373        let tree = this
2374            .parent(app)
2375            .and_then(|parent| parent.data(app).notification_tree.clone());
2376        this.data_mut(app).notification_tree = tree;
2377    }
2378
2379    /// `Element.buildScope`: the scope inherited from the parent at mount.
2380    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
2381        self.as_element()
2382            .data(app)
2383            .parent_build_scope
2384            .expect("an element in a tree has a build scope")
2385    }
2386
2387    /// `Element.markNeedsBuild`.
2388    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
2389        let this = self.as_element();
2390        debug_assert!(this.lifecycle(app) != ElementLifecycle::Defunct);
2391        if this.lifecycle(app) != ElementLifecycle::Active {
2392            return;
2393        }
2394        let owner = this.owner(app).expect("an active element has an owner");
2395        if cfg!(debug_assertions) {
2396            if owner.debug_building(app) {
2397                let target = owner
2398                    .debug_current_build_target(app)
2399                    .expect("building has a target");
2400                debug_assert!(owner.debug_state_locked(app));
2401                assert!(
2402                    this.debug_is_descendant_of(app, target),
2403                    "setState() or markNeedsBuild() called during build. This widget cannot \
2404                     be marked as needing to build because the framework is already in the \
2405                     process of building widgets. A widget can be marked as needing to be \
2406                     built during the build phase only if one of its ancestors is currently \
2407                     building."
2408                );
2409            } else {
2410                assert!(
2411                    !owner.debug_state_locked(app),
2412                    "setState() or markNeedsBuild() called when widget tree was locked."
2413                );
2414            }
2415        }
2416        if this.dirty(app) {
2417            return;
2418        }
2419        this.data_mut(app).dirty = true;
2420        owner.schedule_build_for(app, this);
2421    }
2422
2423    /// `Element._updateInheritance`.
2424    fn update_inheritance(self: Handle<Self>, app: &mut App) {
2425        let this = self.as_element();
2426        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
2427        let inherited = this
2428            .parent(app)
2429            .and_then(|parent| parent.inherited_elements(app));
2430        this.set_inherited_elements(app, inherited);
2431    }
2432
2433    /// `Element.renderObject`: walk down through the attaching children.
2434    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
2435        let this = self.as_element();
2436        let mut current = Some(this);
2437        while let Some(element) = current {
2438            if element.lifecycle(app) == ElementLifecycle::Defunct {
2439                break;
2440            } else if element.is_render_object_element() {
2441                return element.render_object(app);
2442            } else {
2443                current = element.render_object_attaching_child(app);
2444            }
2445        }
2446        None
2447    }
2448}
2449impl<T: Element> ElementBase for T {}
2450
2451/// Dart's `_debugCheckOwnerBuildTargetExists`.
2452pub(crate) fn debug_check_owner_build_target_exists(
2453    this: AnyElement,
2454    app: &App,
2455    method_name: &str,
2456) -> bool {
2457    let owner = this.owner(app).expect("an active element has an owner");
2458    assert!(
2459        owner.debug_current_build_target(app).is_some(),
2460        "{method_name} for {:?} was called at an inappropriate time. It may only be called \
2461         while the widgets are being built.",
2462        this.widget(app)
2463    );
2464    true
2465}
2466
2467fn debug_check_for_cycles(this: AnyElement, app: &App, new_child: AnyElement) -> bool {
2468    debug_assert!(new_child.parent(app).is_none());
2469    let mut node = this;
2470    while let Some(parent) = node.parent(app) {
2471        node = parent;
2472    }
2473    assert!(
2474        node != new_child,
2475        "about to create a cycle in the element tree"
2476    );
2477    true
2478}
2479
2480/// The widget kinds the superclass check compares.
2481pub fn widget_kind(widget: &dyn Widget) -> WidgetKind {
2482    widget.kind()
2483}