use std::any::{Any, TypeId};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use waft_embedder::Size;
use waft_foundation::{
App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
DiagnosticsProperty, DiagnosticsTreeStyle, EntityId, FlagProperty, Handle, HandleId,
IntoPropertyName, ObjectFlagProperty, Subscription, TrackedSet, bare_type_name,
describe_identity,
};
use waft_rendering::{AnyRenderObject, RenderHandle, RenderObject};
use super::build_owner::{BuildOwner, BuildScope};
use super::element_node::{ElementDiagnosticsNode, ElementFacts};
use super::state::State;
use super::widget::{
GlobalKey, InheritedWidget, KeyRef, Widget, WidgetKind, WidgetRef, can_update, downcast_widget,
same_widget,
};
use crate::widgets::notification_listener::LayoutChangedNotification;
use crate::widgets::scroll_notification::ScrollNotification;
use waft_foundation::Ref;
pub type BuildContext = AnyElement;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ElementLifecycle {
Initial,
Active,
Inactive,
Failed,
Defunct,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IndexedSlot {
pub value: Option<AnyElement>,
pub index: usize,
}
#[derive(Clone, Debug)]
pub enum Slot {
Indexed(IndexedSlot),
Index(i32),
Custom(Rc<dyn Any>),
}
impl PartialEq for Slot {
fn eq(&self, other: &Slot) -> bool {
match (self, other) {
(Slot::Indexed(a), Slot::Indexed(b)) => a == b,
(Slot::Index(a), Slot::Index(b)) => a == b,
(Slot::Custom(a), Slot::Custom(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
}
pub type ForgottenChildren<'a> = &'a dyn Fn(&App, AnyElement) -> bool;
pub trait NotificationTarget: 'static {
fn cast(notification: &dyn Notification) -> Option<&Self>;
}
impl<T: Notification> NotificationTarget for T {
fn cast(notification: &dyn Notification) -> Option<&T> {
notification.as_any().downcast_ref::<T>()
}
}
pub trait Notification: Any + Debug {
fn as_any(&self) -> &dyn Any;
fn viewport_depth(&self) -> Option<&Cell<u32>> {
None
}
fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
None
}
fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
None
}
fn dispatch(&self, app: &mut App, target: Option<BuildContext>)
where
Self: Sized,
{
if let Some(target) = target {
target.dispatch_notification(app, self);
}
}
}
pub struct NotificationNode {
parent: Option<Rc<NotificationNode>>,
current: AnyElement,
}
impl NotificationNode {
pub fn new(parent: Option<Rc<NotificationNode>>, current: AnyElement) -> NotificationNode {
NotificationNode { parent, current }
}
fn dispatch_notification(&self, app: &mut App, notification: &dyn Notification) {
if self.current.on_notification(app, notification) {
return;
}
if let Some(parent) = &self.parent {
parent.dispatch_notification(app, notification);
}
}
}
pub struct ElementData {
parent: Option<AnyElement>,
slot: Option<Slot>,
depth: u32,
widget: Option<WidgetRef>,
owner: Option<Handle<BuildOwner>>,
pub(crate) parent_build_scope: Option<Handle<BuildScope>>,
root_build_scope: Option<Ref<BuildScope>>,
lifecycle: ElementLifecycle,
dirty: bool,
pub(crate) in_dirty_list: bool,
inherited_elements: Option<Rc<HashMap<TypeId, AnyElement>>>,
notification_tree: Option<Rc<NotificationNode>>,
dependencies: Option<HashSet<AnyElement>>,
had_unsatisfied_dependencies: bool,
debug_built_once: bool,
entity_watches: HashMap<EntityId, Subscription>,
}
impl ElementData {
pub fn new(widget: WidgetRef) -> ElementData {
ElementData {
parent: None,
slot: None,
depth: 0,
widget: Some(widget),
owner: None,
parent_build_scope: None,
root_build_scope: None,
lifecycle: ElementLifecycle::Initial,
dirty: true,
in_dirty_list: false,
inherited_elements: None,
notification_tree: None,
dependencies: None,
had_unsatisfied_dependencies: false,
debug_built_once: false,
entity_watches: HashMap::new(),
}
}
pub fn widget_ref(&self) -> &WidgetRef {
self.widget.as_ref().expect("the element is unmounted")
}
}
#[macro_export]
macro_rules! element_accessors {
() => {
fn element_data(
self: $crate::__private::foundation::Handle<Self>,
app: &$crate::__private::foundation::App,
) -> &$crate::ElementData {
&app.get(self).element
}
fn element_data_mut(
self: $crate::__private::foundation::Handle<Self>,
app: &mut $crate::__private::foundation::App,
) -> &mut $crate::ElementData {
&mut app.get_mut(self).element
}
};
}
pub trait Element: Sized + 'static {
fn element_data(self: Handle<Self>, app: &App) -> &ElementData;
fn element_data_mut(self: Handle<Self>, app: &mut App) -> &mut ElementData;
fn as_element(self: Handle<Self>) -> AnyElement {
AnyElement {
id: self.id(),
vtable: const { &ElementVTable::of::<Self>() },
}
}
fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
let _ = (self, app, visitor);
}
fn debug_visit_onstage_children(
self: Handle<Self>,
app: &App,
visitor: &mut dyn FnMut(AnyElement),
) {
self.visit_children(app, visitor);
}
fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
ElementBase::render_object_attaching_child(self, app)
}
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
ElementBase::mount(self, app, parent, new_slot);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
ElementBase::update(self, app, new_widget);
}
fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
ElementBase::update_slot(self, app, new_slot);
}
fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
ElementBase::attach_render_object(self, app, new_slot);
}
fn detach_render_object(self: Handle<Self>, app: &mut App) {
ElementBase::detach_render_object(self, app);
}
fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
let _ = (self, app, child);
}
fn activate(self: Handle<Self>, app: &mut App) {
ElementBase::activate(self, app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
ElementBase::deactivate(self, app);
}
fn debug_deactivated(self: Handle<Self>, app: &mut App) {
debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
}
fn unmount(self: Handle<Self>, app: &mut App) {
ElementBase::unmount(self, app);
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
ElementBase::perform_rebuild(self, app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
ElementBase::did_change_dependencies(self, app);
}
fn update_inheritance(self: Handle<Self>, app: &mut App) {
ElementBase::update_inheritance(self, app);
}
fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
ElementBase::attach_notification_tree(self, app);
}
fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
ElementBase::build_scope(self, app)
}
fn mark_needs_build(self: Handle<Self>, app: &mut App) {
ElementBase::mark_needs_build(self, app);
}
fn on_notification(self: Handle<Self>, app: &mut App, notification: &dyn Notification) -> bool {
let _ = (app, notification);
false
}
fn debug_expects_render_object_for_slot(
self: Handle<Self>,
app: &App,
slot: Option<&Slot>,
) -> bool {
let _ = (self, app, slot);
true
}
fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
ElementBase::render_object(self, app)
}
fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
let _ = (self, app);
false
}
const IS_RENDER_OBJECT_ELEMENT: bool = false;
fn insert_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
let _ = (self, app, child, slot);
unreachable!("not a RenderObjectElement");
}
fn move_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
old_slot: Option<Slot>,
new_slot: Option<Slot>,
) {
let _ = (self, app, child, old_slot, new_slot);
unreachable!("not a RenderObjectElement");
}
fn remove_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
let _ = (self, app, child, slot);
unreachable!("not a RenderObjectElement");
}
fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
let _ = (self, app, parent_data_element);
unreachable!("not a RenderObjectElement");
}
const IS_PARENT_DATA_ELEMENT: bool = false;
fn apply_parent_data(
self: Handle<Self>,
app: &mut App,
render_object: AnyRenderObject,
) -> bool {
let _ = (self, app, render_object);
unreachable!("not a ParentDataElement");
}
const IS_INHERITED_ELEMENT: bool = false;
fn update_dependencies(
self: Handle<Self>,
app: &mut App,
dependent: AnyElement,
aspect: Option<Rc<dyn Any>>,
) {
let _ = (self, app, dependent, aspect);
unreachable!("not an InheritedElement");
}
fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
let _ = (self, app, dependent);
unreachable!("not an InheritedElement");
}
fn state_handle_id(self: Handle<Self>, app: &App) -> Option<(TypeId, HandleId)> {
let _ = (self, app);
None
}
fn debug_fill_properties(
self: Handle<Self>,
app: &App,
properties: &mut DiagnosticPropertiesBuilder,
) {
let _ = (self, app, properties);
}
fn debug_describe_children(self: Handle<Self>, app: &App) -> Vec<Rc<dyn DiagnosticsNode>> {
let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
Self::visit_children(self, app, &mut |child| {
children.push(Rc::new(child.to_diagnostics_node(app, None)));
});
children
}
}
pub(crate) struct ElementVTable {
pub type_name: fn() -> &'static str,
pub debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
pub debug_describe_children: fn(&App, HandleId) -> Vec<Rc<dyn DiagnosticsNode>>,
pub element_data: fn(&App, HandleId) -> &ElementData,
pub element_data_mut: fn(&mut App, HandleId) -> &mut ElementData,
pub visit_children: fn(&App, HandleId, &mut dyn FnMut(AnyElement)),
pub debug_visit_onstage_children: fn(&App, HandleId, &mut dyn FnMut(AnyElement)),
pub render_object_attaching_child: fn(&App, HandleId) -> Option<AnyElement>,
pub mount: fn(&mut App, HandleId, Option<AnyElement>, Option<Slot>),
pub update: fn(&mut App, HandleId, WidgetRef),
pub update_slot: fn(&mut App, HandleId, Option<Slot>),
pub attach_render_object: fn(&mut App, HandleId, Option<Slot>),
pub detach_render_object: fn(&mut App, HandleId),
pub forget_child: fn(&mut App, HandleId, AnyElement),
pub activate: fn(&mut App, HandleId),
pub deactivate: fn(&mut App, HandleId),
pub debug_deactivated: fn(&mut App, HandleId),
pub unmount: fn(&mut App, HandleId),
pub perform_rebuild: fn(&mut App, HandleId),
pub did_change_dependencies: fn(&mut App, HandleId),
pub update_inheritance: fn(&mut App, HandleId),
pub attach_notification_tree: fn(&mut App, HandleId),
pub build_scope: fn(&App, HandleId) -> Handle<BuildScope>,
pub mark_needs_build: fn(&mut App, HandleId),
pub on_notification: fn(&mut App, HandleId, &dyn Notification) -> bool,
pub debug_expects_render_object_for_slot: fn(&App, HandleId, Option<&Slot>) -> bool,
pub render_object: fn(&App, HandleId) -> Option<AnyRenderObject>,
pub debug_doing_build: fn(&App, HandleId) -> bool,
pub is_render_object_element: bool,
pub insert_render_object_child: fn(&mut App, HandleId, AnyRenderObject, Option<Slot>),
pub move_render_object_child:
fn(&mut App, HandleId, AnyRenderObject, Option<Slot>, Option<Slot>),
pub remove_render_object_child: fn(&mut App, HandleId, AnyRenderObject, Option<Slot>),
pub update_parent_data: fn(&mut App, HandleId, AnyElement),
pub is_parent_data_element: bool,
pub apply_parent_data: fn(&mut App, HandleId, AnyRenderObject) -> bool,
pub is_inherited_element: bool,
pub update_dependencies: fn(&mut App, HandleId, AnyElement, Option<Rc<dyn Any>>),
pub remove_dependent: fn(&mut App, HandleId, AnyElement),
pub state_handle_id: fn(&App, HandleId) -> Option<(TypeId, HandleId)>,
}
fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
Handle::from_id(id)
}
impl ElementVTable {
pub(crate) const fn of<T: Element>() -> ElementVTable {
ElementVTable {
type_name: std::any::type_name::<T>,
debug_fill_properties: |app, id, properties| {
T::debug_fill_properties(resolve(id), app, properties)
},
debug_describe_children: |app, id| T::debug_describe_children(resolve(id), app),
element_data: |app, id| T::element_data(resolve(id), app),
element_data_mut: |app, id| T::element_data_mut(resolve(id), app),
visit_children: |app, id, visitor| T::visit_children(resolve(id), app, visitor),
debug_visit_onstage_children: |app, id, visitor| {
T::debug_visit_onstage_children(resolve(id), app, visitor)
},
render_object_attaching_child: |app, id| {
T::render_object_attaching_child(resolve(id), app)
},
mount: |app, id, parent, slot| T::mount(resolve(id), app, parent, slot),
update: |app, id, widget| T::update(resolve(id), app, widget),
update_slot: |app, id, slot| T::update_slot(resolve(id), app, slot),
attach_render_object: |app, id, slot| T::attach_render_object(resolve(id), app, slot),
detach_render_object: |app, id| T::detach_render_object(resolve(id), app),
forget_child: |app, id, child| T::forget_child(resolve(id), app, child),
activate: |app, id| T::activate(resolve(id), app),
deactivate: |app, id| T::deactivate(resolve(id), app),
debug_deactivated: |app, id| T::debug_deactivated(resolve(id), app),
unmount: |app, id| T::unmount(resolve(id), app),
perform_rebuild: |app, id| T::perform_rebuild(resolve(id), app),
did_change_dependencies: |app, id| T::did_change_dependencies(resolve(id), app),
update_inheritance: |app, id| T::update_inheritance(resolve(id), app),
attach_notification_tree: |app, id| T::attach_notification_tree(resolve(id), app),
build_scope: |app, id| T::build_scope(resolve(id), app),
mark_needs_build: |app, id| T::mark_needs_build(resolve(id), app),
on_notification: |app, id, notification| {
T::on_notification(resolve(id), app, notification)
},
debug_expects_render_object_for_slot: |app, id, slot| {
T::debug_expects_render_object_for_slot(resolve(id), app, slot)
},
render_object: |app, id| T::render_object(resolve(id), app),
debug_doing_build: |app, id| T::debug_doing_build(resolve(id), app),
is_render_object_element: T::IS_RENDER_OBJECT_ELEMENT,
insert_render_object_child: |app, id, child, slot| {
T::insert_render_object_child(resolve(id), app, child, slot)
},
move_render_object_child: |app, id, child, old_slot, new_slot| {
T::move_render_object_child(resolve(id), app, child, old_slot, new_slot)
},
remove_render_object_child: |app, id, child, slot| {
T::remove_render_object_child(resolve(id), app, child, slot)
},
update_parent_data: |app, id, element| T::update_parent_data(resolve(id), app, element),
is_parent_data_element: T::IS_PARENT_DATA_ELEMENT,
apply_parent_data: |app, id, render_object| {
T::apply_parent_data(resolve(id), app, render_object)
},
is_inherited_element: T::IS_INHERITED_ELEMENT,
update_dependencies: |app, id, dependent, aspect| {
T::update_dependencies(resolve(id), app, dependent, aspect)
},
remove_dependent: |app, id, dependent| T::remove_dependent(resolve(id), app, dependent),
state_handle_id: |app, id| T::state_handle_id(resolve(id), app),
}
}
}
#[derive(Clone, Copy)]
pub struct AnyElement {
id: HandleId,
vtable: &'static ElementVTable,
}
impl PartialEq for AnyElement {
fn eq(&self, other: &AnyElement) -> bool {
self.id == other.id
}
}
impl Eq for AnyElement {}
impl Hash for AnyElement {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Debug for AnyElement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Element({:?})", self.id)
}
}
impl AnyElement {
pub fn id(self) -> HandleId {
self.id
}
pub fn downcast<T: Element>(self, app: &App) -> Option<Handle<T>> {
app.handle::<T>(self.id)
}
pub(crate) fn data(self, app: &App) -> &ElementData {
(self.vtable.element_data)(app, self.id)
}
pub(crate) fn data_mut(self, app: &mut App) -> &mut ElementData {
(self.vtable.element_data_mut)(app, self.id)
}
pub(crate) fn bind_entity_watches(self, app: &mut App, tracked: TrackedSet) {
let current: HashSet<EntityId> = self.data(app).entity_watches.keys().copied().collect();
let tracked: HashSet<EntityId> = tracked.iter().collect();
for id in current.difference(&tracked) {
self.data_mut(app).entity_watches.remove(id);
}
let added: Vec<EntityId> = tracked.difference(¤t).copied().collect();
for id in added {
let element = self;
let subscription = app.observe_entity_id(id, move |app| {
if element.lifecycle(app) == ElementLifecycle::Active {
element.mark_needs_build(app);
}
true
});
self.data_mut(app).entity_watches.insert(id, subscription);
}
app.flush_entity_effects();
}
pub fn widget(self, app: &App) -> &WidgetRef {
self.data(app).widget_ref()
}
pub fn mounted(self, app: &App) -> bool {
app.contains(self.id) && self.data(app).widget.is_some()
}
pub fn parent(self, app: &App) -> Option<AnyElement> {
self.data(app).parent
}
pub fn slot(self, app: &App) -> Option<Slot> {
self.data(app).slot.clone()
}
pub fn depth(self, app: &App) -> u32 {
debug_assert!(
self.lifecycle(app) != ElementLifecycle::Initial,
"Depth is only available when element has been mounted."
);
self.data(app).depth
}
pub fn owner(self, app: &App) -> Option<Handle<BuildOwner>> {
self.data(app).owner
}
pub fn build_scope(self, app: &App) -> Handle<BuildScope> {
(self.vtable.build_scope)(app, self.id)
}
pub fn lifecycle(self, app: &App) -> ElementLifecycle {
if !app.contains(self.id) {
return ElementLifecycle::Defunct;
}
self.data(app).lifecycle
}
pub fn to_string_short(self, app: &App) -> String {
match &self.data(app).widget {
Some(widget) => widget.to_string_short(),
None => format!(
"{}(DEFUNCT)",
describe_identity(
bare_type_name((self.vtable.type_name)()),
self.id.identity_hash()
)
),
}
}
pub fn to_diagnostics_node(
self,
app: &App,
name: impl IntoPropertyName,
) -> ElementDiagnosticsNode {
let mut properties = DiagnosticPropertiesBuilder::new();
self.fill_base_properties(app, &mut properties);
(self.vtable.debug_fill_properties)(app, self.id, &mut properties);
let children = (self.vtable.debug_describe_children)(app, self.id);
let node = DiagnosticableTreeNode::from_parts(
name,
self.to_string_short(app),
properties,
children,
)
.with_value_id(self.id());
let widget = self.data(app).widget.as_ref();
let facts = ElementFacts {
widget_runtime_type: widget.map(|widget| widget.type_name()),
stateful: widget.is_some_and(|widget| widget.kind() == WidgetKind::Stateful),
creation_location: widget.and_then(|widget| widget.creation_location()),
};
ElementDiagnosticsNode::new(node, facts)
}
pub fn to_string_deep(self, app: &App) -> String {
self.to_string_deep_with(app, DiagnosticLevel::Debug, 65)
}
pub fn to_string_deep_with(
self,
app: &App,
min_level: DiagnosticLevel,
wrap_width: usize,
) -> String {
self.to_diagnostics_node(app, None).to_string_deep_with(
"",
Some(""),
None,
min_level,
wrap_width,
)
}
fn fill_base_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
properties.default_diagnostics_tree_style = DiagnosticsTreeStyle::Dense;
let data = self.data(app);
if data.lifecycle != ElementLifecycle::Initial {
properties.add(ObjectFlagProperty::<u32>::new("depth", data.depth).if_null("no depth"));
}
properties.add(
ObjectFlagProperty::<String>::new(
"widget",
data.widget.as_ref().map(|widget| widget.to_string_short()),
)
.if_null("no widget"),
);
let key = data.widget.as_ref().and_then(|widget| widget.key());
properties.add(
DiagnosticsProperty::<String>::new("key", key.map(|key| format!("{key:?}")))
.with_show_name(false)
.default_value(None)
.with_level(DiagnosticLevel::Hidden),
);
if let Some(widget) = &data.widget {
widget.debug_fill_properties(app, properties);
}
properties.add(FlagProperty::new("dirty", data.dirty).if_true("dirty"));
if let Some(dependencies) = data.dependencies.as_ref().filter(|set| !set.is_empty()) {
let mut names: Vec<String> = dependencies
.iter()
.map(|dependency| dependency.to_string_short(app))
.collect();
names.sort();
properties.add(DiagnosticsProperty::<String>::new(
"dependencies",
format!("[{}]", names.join(", ")),
));
}
if self.is_render_object_element() {
properties.add(
DiagnosticsProperty::<String>::new(
"renderObject",
self.render_object(app)
.map(|render_object| render_object.to_string_short(app)),
)
.default_value(None),
);
}
}
pub fn debug_is_active(self, app: &App) -> bool {
self.lifecycle(app) == ElementLifecycle::Active
}
pub fn debug_is_defunct(self, app: &App) -> bool {
self.lifecycle(app) == ElementLifecycle::Defunct
}
pub fn dirty(self, app: &App) -> bool {
self.data(app).dirty
}
pub(crate) fn in_dirty_list(self, app: &App) -> bool {
self.data(app).in_dirty_list
}
pub fn debug_doing_build(self, app: &App) -> bool {
(self.vtable.debug_doing_build)(app, self.id)
}
pub fn children(self, app: &App) -> Vec<AnyElement> {
let mut children = Vec::new();
self.visit_children(app, &mut |child| children.push(child));
children
}
pub fn visit_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
(self.vtable.visit_children)(app, self.id, visitor);
}
pub fn debug_visit_onstage_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
(self.vtable.debug_visit_onstage_children)(app, self.id, visitor);
}
pub fn render_object_attaching_child(self, app: &App) -> Option<AnyElement> {
(self.vtable.render_object_attaching_child)(app, self.id)
}
pub fn mount(self, app: &mut App, parent: Option<AnyElement>, new_slot: Option<Slot>) {
(self.vtable.mount)(app, self.id, parent, new_slot);
}
pub fn update(self, app: &mut App, new_widget: WidgetRef) {
(self.vtable.update)(app, self.id, new_widget);
}
pub fn update_slot(self, app: &mut App, new_slot: Option<Slot>) {
(self.vtable.update_slot)(app, self.id, new_slot);
}
pub fn attach_render_object(self, app: &mut App, new_slot: Option<Slot>) {
(self.vtable.attach_render_object)(app, self.id, new_slot);
}
pub fn detach_render_object(self, app: &mut App) {
(self.vtable.detach_render_object)(app, self.id);
}
pub fn forget_child(self, app: &mut App, child: AnyElement) {
(self.vtable.forget_child)(app, self.id, child);
}
pub fn activate(self, app: &mut App) {
(self.vtable.activate)(app, self.id);
}
pub fn deactivate(self, app: &mut App) {
(self.vtable.deactivate)(app, self.id);
}
pub fn debug_deactivated(self, app: &mut App) {
(self.vtable.debug_deactivated)(app, self.id);
}
pub fn unmount(self, app: &mut App) {
(self.vtable.unmount)(app, self.id);
}
pub fn perform_rebuild(self, app: &mut App) {
(self.vtable.perform_rebuild)(app, self.id);
}
pub fn did_change_dependencies(self, app: &mut App) {
(self.vtable.did_change_dependencies)(app, self.id);
}
pub fn update_inheritance(self, app: &mut App) {
(self.vtable.update_inheritance)(app, self.id);
}
pub fn attach_notification_tree(self, app: &mut App) {
(self.vtable.attach_notification_tree)(app, self.id);
}
pub fn on_notification(self, app: &mut App, notification: &dyn Notification) -> bool {
(self.vtable.on_notification)(app, self.id, notification)
}
pub fn dispatch_notification(self, app: &mut App, notification: &dyn Notification) {
let tree = self.data(app).notification_tree.clone();
if let Some(tree) = tree {
tree.dispatch_notification(app, notification);
}
}
pub fn debug_expects_render_object_for_slot(self, app: &App, slot: Option<&Slot>) -> bool {
(self.vtable.debug_expects_render_object_for_slot)(app, self.id, slot)
}
pub fn render_object(self, app: &App) -> Option<AnyRenderObject> {
(self.vtable.render_object)(app, self.id)
}
#[inline(always)]
pub fn inflate_widget(
self,
app: &mut App,
new_widget: WidgetRef,
new_slot: Option<Slot>,
) -> AnyElement {
let inactive_child = match new_widget.key() {
Some(KeyRef::Global(key)) => self.retake_inactive_element(app, key, &new_widget),
_ => None,
};
match inactive_child {
Some(inactive_child) => {
self.inflate_inactive_child(app, inactive_child, new_widget, new_slot)
}
None => {
let new_child = new_widget.create_element(app, new_widget.clone());
debug_assert!(debug_check_for_cycles(self, app, new_child));
new_child.mount(app, Some(self), new_slot);
debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
new_child
}
}
}
#[inline(never)]
fn inflate_inactive_child(
self,
app: &mut App,
inactive_child: AnyElement,
new_widget: WidgetRef,
new_slot: Option<Slot>,
) -> AnyElement {
debug_assert!(inactive_child.parent(app).is_none());
inactive_child.activate_with_parent(app, self, new_slot.clone());
let updated_child =
self.update_child(app, Some(inactive_child), Some(new_widget), new_slot);
debug_assert!(updated_child == Some(inactive_child));
updated_child.expect("a retaken child stays")
}
pub fn is_render_object_element(self) -> bool {
self.vtable.is_render_object_element
}
pub fn insert_render_object_child(
self,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
(self.vtable.insert_render_object_child)(app, self.id, child, slot);
}
pub fn move_render_object_child(
self,
app: &mut App,
child: AnyRenderObject,
old_slot: Option<Slot>,
new_slot: Option<Slot>,
) {
(self.vtable.move_render_object_child)(app, self.id, child, old_slot, new_slot);
}
pub fn remove_render_object_child(
self,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
(self.vtable.remove_render_object_child)(app, self.id, child, slot);
}
pub fn update_parent_data(self, app: &mut App, parent_data_element: AnyElement) {
(self.vtable.update_parent_data)(app, self.id, parent_data_element);
}
pub fn is_parent_data_element(self) -> bool {
self.vtable.is_parent_data_element
}
pub fn apply_parent_data(self, app: &mut App, render_object: AnyRenderObject) -> bool {
(self.vtable.apply_parent_data)(app, self.id, render_object)
}
pub fn is_inherited_element(self) -> bool {
self.vtable.is_inherited_element
}
pub fn update_dependencies(
self,
app: &mut App,
dependent: AnyElement,
aspect: Option<Rc<dyn Any>>,
) {
(self.vtable.update_dependencies)(app, self.id, dependent, aspect);
}
pub fn remove_dependent(self, app: &mut App, dependent: AnyElement) {
(self.vtable.remove_dependent)(app, self.id, dependent);
}
pub fn state_handle<S: State>(self, app: &App) -> Option<Handle<S>> {
let (type_id, id) = (self.vtable.state_handle_id)(app, self.id)?;
(type_id == TypeId::of::<S>()).then(|| Handle::from_id(id))
}
#[inline(always)]
pub fn update_child(
self,
app: &mut App,
child: Option<AnyElement>,
new_widget: Option<WidgetRef>,
new_slot: Option<Slot>,
) -> Option<AnyElement> {
let Some(new_widget) = new_widget else {
if let Some(child) = child {
self.deactivate_child(app, child);
}
return None;
};
let new_child = match child {
Some(child) => {
let has_same_superclass = child.widget(app).kind() == new_widget.kind();
if has_same_superclass && same_widget(child.widget(app), &new_widget) {
if child.slot(app) != new_slot {
self.update_slot_for_child(app, child, new_slot);
}
child
} else if has_same_superclass && can_update(&**child.widget(app), &*new_widget) {
if child.slot(app) != new_slot {
self.update_slot_for_child(app, child, new_slot);
}
child.update(app, new_widget.clone());
debug_assert!(same_widget(child.widget(app), &new_widget));
child
} else {
self.deactivate_child(app, child);
debug_assert!(child.parent(app).is_none());
self.inflate_widget(app, new_widget, new_slot)
}
}
None => self.inflate_widget(app, new_widget, new_slot),
};
Some(new_child)
}
pub fn update_children(
self,
app: &mut App,
old_children: &[AnyElement],
new_widgets: &[WidgetRef],
forgotten_children: Option<ForgottenChildren<'_>>,
slots: Option<&[Option<Slot>]>,
) -> Vec<AnyElement> {
debug_assert!(slots.is_none_or(|slots| slots.len() == new_widgets.len()));
let replace_with_null_if_forgotten = |app: &App, child: AnyElement| -> Option<AnyElement> {
let forgotten = forgotten_children.is_some_and(|forgotten| forgotten(app, child));
(!forgotten).then_some(child)
};
let slot_for =
|new_child_index: usize, previous_child: Option<AnyElement>| -> Option<Slot> {
match slots {
Some(slots) => slots[new_child_index].clone(),
None => Some(Slot::Indexed(IndexedSlot {
index: new_child_index,
value: previous_child,
})),
}
};
let mut new_children_top = 0usize;
let mut old_children_top = 0usize;
let mut new_children_bottom = new_widgets.len() as isize - 1;
let mut old_children_bottom = old_children.len() as isize - 1;
let mut new_children: Vec<Option<AnyElement>> = vec![None; new_widgets.len()];
let mut previous_child: Option<AnyElement> = None;
while (old_children_top as isize <= old_children_bottom)
&& (new_children_top as isize <= new_children_bottom)
{
let old_child = replace_with_null_if_forgotten(app, old_children[old_children_top]);
let new_widget = &new_widgets[new_children_top];
debug_assert!(
old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
);
let Some(old_child) = old_child else {
break;
};
if !can_update(&**old_child.widget(app), &**new_widget) {
break;
}
let new_child = self
.update_child(
app,
Some(old_child),
Some(new_widget.clone()),
slot_for(new_children_top, previous_child),
)
.expect("a widget yields a child");
debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
new_children[new_children_top] = Some(new_child);
previous_child = Some(new_child);
new_children_top += 1;
old_children_top += 1;
}
while (old_children_top as isize <= old_children_bottom)
&& (new_children_top as isize <= new_children_bottom)
{
let old_child =
replace_with_null_if_forgotten(app, old_children[old_children_bottom as usize]);
let new_widget = &new_widgets[new_children_bottom as usize];
debug_assert!(
old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
);
let Some(old_child) = old_child else {
break;
};
if !can_update(&**old_child.widget(app), &**new_widget) {
break;
}
old_children_bottom -= 1;
new_children_bottom -= 1;
}
let have_old_children = old_children_top as isize <= old_children_bottom;
let mut old_keyed_children: HashMap<KeyRef, AnyElement> = HashMap::new();
if have_old_children {
while old_children_top as isize <= old_children_bottom {
let old_child = replace_with_null_if_forgotten(app, old_children[old_children_top]);
debug_assert!(
old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
);
if let Some(old_child) = old_child {
match old_child.widget(app).key().cloned() {
Some(key) => {
old_keyed_children.insert(key, old_child);
}
None => self.deactivate_child(app, old_child),
}
}
old_children_top += 1;
}
}
while new_children_top as isize <= new_children_bottom {
let new_widget = &new_widgets[new_children_top];
let mut old_child: Option<AnyElement> = None;
if have_old_children
&& let Some(key) = new_widget.key()
&& let Some(candidate) = old_keyed_children.get(key).copied()
&& can_update(&**candidate.widget(app), &**new_widget)
{
old_keyed_children.remove(key);
old_child = Some(candidate);
}
debug_assert!(
old_child.is_none_or(|old| can_update(&**old.widget(app), &**new_widget))
);
let new_child = self
.update_child(
app,
old_child,
Some(new_widget.clone()),
slot_for(new_children_top, previous_child),
)
.expect("a widget yields a child");
debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
debug_assert!(old_child.is_none_or(
|old| old == new_child || old.lifecycle(app) != ElementLifecycle::Active
));
new_children[new_children_top] = Some(new_child);
previous_child = Some(new_child);
new_children_top += 1;
}
debug_assert!(old_children_top as isize == old_children_bottom + 1);
debug_assert!(new_children_top as isize == new_children_bottom + 1);
debug_assert!(
new_widgets.len() - new_children_top == old_children.len() - old_children_top
);
new_children_bottom = new_widgets.len() as isize - 1;
old_children_bottom = old_children.len() as isize - 1;
while (old_children_top as isize <= old_children_bottom)
&& (new_children_top as isize <= new_children_bottom)
{
let old_child = old_children[old_children_top];
debug_assert!(replace_with_null_if_forgotten(app, old_child).is_some());
debug_assert!(old_child.lifecycle(app) == ElementLifecycle::Active);
let new_widget = &new_widgets[new_children_top];
debug_assert!(can_update(&**old_child.widget(app), &**new_widget));
let new_child = self
.update_child(
app,
Some(old_child),
Some(new_widget.clone()),
slot_for(new_children_top, previous_child),
)
.expect("a widget yields a child");
debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
debug_assert!(
old_child == new_child || old_child.lifecycle(app) != ElementLifecycle::Active
);
new_children[new_children_top] = Some(new_child);
previous_child = Some(new_child);
new_children_top += 1;
old_children_top += 1;
}
if have_old_children {
for old_child in old_keyed_children.into_values() {
if replace_with_null_if_forgotten(app, old_child).is_some() {
self.deactivate_child(app, old_child);
}
}
}
new_children
.into_iter()
.map(|child| child.expect("every slot was filled"))
.collect()
}
pub fn update_slot_for_child(self, app: &mut App, child: AnyElement, new_slot: Option<Slot>) {
debug_assert!(self.lifecycle(app) == ElementLifecycle::Active);
debug_assert!(child.parent(app) == Some(self));
let mut element = Some(child);
while let Some(current) = element {
current.update_slot(app, new_slot.clone());
element = current.render_object_attaching_child(app);
}
}
fn update_depth(self, app: &mut App, parent_depth: u32) {
let expected_depth = parent_depth + 1;
if self.data(app).depth < expected_depth {
self.data_mut(app).depth = expected_depth;
for child in self.children(app) {
child.update_depth(app, expected_depth);
}
}
}
fn update_build_scope_recursively(self, app: &mut App) {
let parent_scope = self.parent(app).map(|parent| parent.build_scope(app));
if self.data(app).parent_build_scope == parent_scope {
return;
}
let data = self.data_mut(app);
data.in_dirty_list = false;
data.parent_build_scope = parent_scope;
for child in self.children(app) {
child.update_build_scope_recursively(app);
}
}
fn retake_inactive_element(
self,
app: &mut App,
key: &GlobalKey,
new_widget: &WidgetRef,
) -> Option<AnyElement> {
let owner = self.owner(app).expect("a mounted element has an owner");
let element = owner.global_key_element(app, key)?;
if !can_update(&**element.widget(app), &**new_widget) {
return None;
}
if let Some(parent) = element.parent(app) {
assert!(
parent != self,
"A GlobalKey was used multiple times inside one widget's child list. A \
GlobalKey can only be specified on one widget at a time in the widget tree."
);
parent.forget_child(app, element);
parent.deactivate_child(app, element);
}
debug_assert!(element.parent(app).is_none());
owner.inactive_remove(app, element);
Some(element)
}
pub fn deactivate_child(self, app: &mut App, child: AnyElement) {
debug_assert!(child.parent(app) == Some(self));
child.data_mut(app).parent = None;
child.detach_render_object(app);
let owner = self.owner(app).expect("a mounted element has an owner");
owner.inactive_add(app, child); }
fn activate_with_parent(self, app: &mut App, parent: AnyElement, new_slot: Option<Slot>) {
debug_assert!(self.lifecycle(app) == ElementLifecycle::Inactive);
let parent_owner = parent.owner(app);
let data = self.data_mut(app);
data.parent = Some(parent);
data.owner = parent_owner;
let parent_depth = parent.depth(app);
self.update_depth(app, parent_depth);
self.update_build_scope_recursively(app);
activate_recursively(app, self);
self.attach_render_object(app, new_slot);
debug_assert!(self.lifecycle(app) == ElementLifecycle::Active);
}
pub(crate) fn ensure_deactivated(self, app: &mut App) {
let dependencies: Vec<AnyElement> = self
.data(app)
.dependencies
.iter()
.flatten()
.copied()
.collect();
for dependency in dependencies {
dependency.remove_dependent(app, self);
}
let data = self.data_mut(app);
data.inherited_elements = None;
data.lifecycle = ElementLifecycle::Inactive;
}
pub fn find_render_object(self, app: &App) -> Option<AnyRenderObject> {
debug_assert!(
self.lifecycle(app) == ElementLifecycle::Active,
"Cannot get renderObject of inactive element. In order for an element to have a \
valid renderObject, it must be active, which means it is part of the tree."
);
self.render_object(app)
}
pub fn size(self, app: &App) -> Option<Size> {
debug_assert!(
self.lifecycle(app) == ElementLifecycle::Active,
"Cannot get size of inactive element."
);
debug_assert!(
!self
.owner(app)
.is_some_and(|owner| owner.debug_building(app)),
"Cannot get size during build."
);
let render_object = self.find_render_object(app)?;
let render_box = render_object.as_box()?;
debug_assert!(
render_box.has_size(app),
"Cannot get size from a render object that has not been through layout."
);
debug_assert!(
!render_object.debug_needs_layout(app),
"Cannot get size from a render object that has been marked dirty for layout."
);
Some(render_box.size(app))
}
pub fn does_depend_on_inherited_element(self, app: &App, ancestor: AnyElement) -> bool {
self.data(app)
.dependencies
.as_ref()
.is_some_and(|dependencies| dependencies.contains(&ancestor))
}
pub fn depend_on_inherited_element(
self,
app: &mut App,
ancestor: AnyElement,
aspect: Option<Rc<dyn Any>>,
) -> WidgetRef {
self.data_mut(app)
.dependencies
.get_or_insert_with(HashSet::new)
.insert(ancestor);
ancestor.update_dependencies(app, self, aspect);
ancestor.widget(app).clone()
}
pub fn depend_on_inherited_widget_of_exact_type<W: InheritedWidget>(
self,
app: &mut App,
) -> Option<&W> {
self.depend_on_inherited_widget_of_exact_type_with_aspect::<W>(app, None)
}
pub fn depend_on_inherited_widget_of_exact_type_with_aspect<W: InheritedWidget>(
self,
app: &mut App,
aspect: Option<Rc<dyn Any>>,
) -> Option<&W> {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
let ancestor = self
.data(app)
.inherited_elements
.as_ref()
.and_then(|elements| elements.get(&TypeId::of::<W>()).copied());
let Some(ancestor) = ancestor else {
self.data_mut(app).had_unsatisfied_dependencies = true;
return None;
};
self.depend_on_inherited_element(app, ancestor, aspect);
let widget: &WidgetRef = ancestor.widget(app);
downcast_widget::<W>(&**widget)
}
pub fn get_inherited_widget_of_exact_type<W: InheritedWidget>(self, app: &App) -> Option<&W> {
let element = self.get_element_for_inherited_widget_of_exact_type::<W>(app)?;
let widget: &WidgetRef = element.widget(app);
downcast_widget::<W>(&**widget)
}
pub fn get_element_for_inherited_widget_of_exact_type<W: InheritedWidget>(
self,
app: &App,
) -> Option<AnyElement> {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
self.data(app)
.inherited_elements
.as_ref()
.and_then(|elements| elements.get(&TypeId::of::<W>()).copied())
}
fn debug_check_state_is_active_for_ancestor_lookup(self, app: &App) -> bool {
assert!(
self.lifecycle(app) == ElementLifecycle::Active,
"Looking up a deactivated widget's ancestor is unsafe. At this point the state of \
the widget's element tree is no longer stable. To safely refer to a widget's \
ancestor in its dispose() method, save a reference to the ancestor by calling \
dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() \
method."
);
true
}
pub fn find_ancestor_widget_of_exact_type<W: 'static>(self, app: &App) -> Option<&W> {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
let mut ancestor = self.parent(app);
while let Some(current) = ancestor {
if current.widget(app).widget_type() == TypeId::of::<W>() {
return downcast_widget::<W>(&**current.widget(app));
}
ancestor = current.parent(app);
}
None
}
pub fn find_ancestor_state_of_type<S: State>(self, app: &App) -> Option<Handle<S>> {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
let mut ancestor = self.parent(app);
while let Some(current) = ancestor {
if let Some(state) = current.state_handle::<S>(app) {
return Some(state);
}
ancestor = current.parent(app);
}
None
}
pub fn find_root_ancestor_state_of_type<S: State>(self, app: &App) -> Option<Handle<S>> {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
let mut ancestor = self.parent(app);
let mut stateful_ancestor = None;
while let Some(current) = ancestor {
if let Some(state) = current.state_handle::<S>(app) {
stateful_ancestor = Some(state);
}
ancestor = current.parent(app);
}
stateful_ancestor
}
pub fn find_ancestor_render_object_of_type<R: RenderObject>(
self,
app: &App,
) -> Option<RenderHandle<R>> {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
let mut ancestor = self.parent(app);
while let Some(current) = ancestor {
if current.is_render_object_element()
&& let Some(render_object) = current.render_object(app)
&& let Some(typed) = render_object.downcast::<R>(app)
{
return Some(typed);
}
ancestor = current.parent(app);
}
None
}
pub fn visit_ancestor_elements(self, app: &App, visitor: &mut dyn FnMut(AnyElement) -> bool) {
debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
let mut ancestor = self.parent(app);
while let Some(current) = ancestor {
if !visitor(current) {
break;
}
ancestor = current.parent(app);
}
}
pub fn visit_child_elements(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
debug_assert!(
!self
.owner(app)
.is_some_and(|owner| owner.debug_state_locked(app)),
"visitChildElements() called during build."
);
self.visit_children(app, visitor);
}
pub fn debug_is_descendant_of(self, app: &App, target: AnyElement) -> bool {
let mut element = Some(self);
while let Some(current) = element
&& current.depth(app) > target.depth(app)
{
element = current.parent(app);
}
element == Some(target)
}
pub fn mark_needs_build(self, app: &mut App) {
(self.vtable.mark_needs_build)(app, self.id);
}
pub fn rebuild(self, app: &mut App, force: bool) {
if let Some(rebuilding) = self.begin_rebuild(app, force) {
self.perform_rebuild(app);
self.end_rebuild(app, rebuilding);
}
}
#[inline(always)]
pub(crate) fn begin_rebuild(self, app: &mut App, force: bool) -> Option<Rebuilding> {
debug_assert!(self.lifecycle(app) != ElementLifecycle::Initial);
if self.lifecycle(app) != ElementLifecycle::Active || (!self.dirty(app) && !force) {
return None;
}
let owner = self.owner(app).expect("an active element has an owner");
debug_assert!(owner.debug_state_locked(app));
let debug_previous_build_target = owner.debug_current_build_target(app);
if cfg!(debug_assertions) {
owner.set_debug_current_build_target(app, Some(self));
self.data_mut(app).debug_built_once = true;
}
Some(Rebuilding {
owner,
debug_previous_build_target,
})
}
#[inline(always)]
pub(crate) fn end_rebuild(self, app: &mut App, rebuilding: Rebuilding) {
if cfg!(debug_assertions) {
let owner = rebuilding.owner;
debug_assert!(owner.debug_current_build_target(app) == Some(self));
owner.set_debug_current_build_target(app, rebuilding.debug_previous_build_target);
}
debug_assert!(!self.dirty(app));
}
pub(crate) fn had_dependencies(self, app: &App) -> bool {
let data = self.data(app);
data.dependencies
.as_ref()
.is_some_and(|dependencies| !dependencies.is_empty())
|| data.had_unsatisfied_dependencies
}
pub fn notification_tree(self, app: &App) -> Option<Rc<NotificationNode>> {
self.data(app).notification_tree.clone()
}
pub fn set_notification_tree(self, app: &mut App, tree: Option<Rc<NotificationNode>>) {
self.data_mut(app).notification_tree = tree;
}
pub(crate) fn inherited_elements(self, app: &App) -> Option<Rc<HashMap<TypeId, AnyElement>>> {
self.data(app).inherited_elements.clone()
}
pub(crate) fn set_inherited_elements(
self,
app: &mut App,
elements: Option<Rc<HashMap<TypeId, AnyElement>>>,
) {
self.data_mut(app).inherited_elements = elements;
}
pub(crate) fn set_slot(self, app: &mut App, slot: Option<Slot>) {
self.data_mut(app).slot = slot;
}
pub(crate) fn set_dirty(self, app: &mut App, dirty: bool) {
self.data_mut(app).dirty = dirty;
}
pub fn assign_owner(self, app: &mut App, owner: Handle<BuildOwner>) {
let scope = BuildScope::new(app, None);
let data = self.data_mut(app);
data.owner = Some(owner);
data.parent_build_scope = Some(scope.handle());
data.root_build_scope = Some(scope);
}
}
fn activate_recursively(app: &mut App, element: AnyElement) {
let mut stack = vec![element];
while let Some(element) = stack.pop() {
debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
element.activate(app);
debug_assert!(element.lifecycle(app) == ElementLifecycle::Active);
stack.extend(element.children(app).into_iter().rev());
}
}
pub(crate) struct Rebuilding {
owner: Handle<BuildOwner>,
debug_previous_build_target: Option<AnyElement>,
}
pub trait ElementBase: Element {
#[inline(always)]
fn rebuild(self: Handle<Self>, app: &mut App, force: bool) {
let this = self.as_element();
if let Some(rebuilding) = this.begin_rebuild(app, force) {
Element::perform_rebuild(self, app);
this.end_rebuild(app, rebuilding);
}
}
fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
let this = self.as_element();
let mut next = None;
this.visit_children(app, &mut |child| {
debug_assert!(next.is_none()); next = Some(child);
});
next
}
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
let this = self.as_element();
debug_assert!(
this.lifecycle(app) == ElementLifecycle::Initial,
"This element is no longer in its initial state ({:?})",
this.lifecycle(app)
);
debug_assert!(
this.parent(app).is_none(),
"This element already has a parent and it shouldn't have one yet."
);
debug_assert!(
parent.is_none_or(|parent| parent.lifecycle(app) == ElementLifecycle::Active),
"Parent should be null or in the active state"
);
debug_assert!(
this.slot(app).is_none(),
"This element already has a slot and it shouldn't"
);
let parent_depth = parent.map_or(0, |parent| parent.depth(app));
let parent_owner = parent.and_then(|parent| parent.owner(app));
let parent_scope = parent.map(|parent| parent.build_scope(app));
let data = this.data_mut(app);
data.parent = parent;
data.slot = new_slot;
data.lifecycle = ElementLifecycle::Active;
data.depth = 1 + parent_depth;
if parent.is_some() {
data.owner = parent_owner;
data.parent_build_scope = parent_scope;
}
let owner = this.owner(app).expect("a mounted element has an owner");
if let Some(KeyRef::Global(key)) = this.widget(app).key().cloned() {
owner.register_global_key(app, &key, this);
}
this.update_inheritance(app);
this.attach_notification_tree(app);
}
#[inline(always)]
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
let this = self.as_element();
debug_assert!(
this.lifecycle(app) == ElementLifecycle::Active
&& !same_widget(this.widget(app), &new_widget)
&& can_update(&**this.widget(app), &*new_widget)
);
this.data_mut(app).widget = Some(new_widget);
}
fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
debug_assert!(this.parent(app).is_some());
debug_assert!(
this.parent(app)
.is_some_and(|parent| parent.lifecycle(app) == ElementLifecycle::Active)
);
this.set_slot(app, new_slot);
}
fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
let this = self.as_element();
debug_assert!(this.slot(app).is_none());
for child in this.children(app) {
child.attach_render_object(app, new_slot.clone());
}
this.set_slot(app, new_slot);
}
fn detach_render_object(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
for child in this.children(app) {
child.detach_render_object(app);
}
this.set_slot(app, None);
}
fn activate(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) == ElementLifecycle::Inactive);
let owner = this
.owner(app)
.expect("an inactive element keeps its owner");
let had_dependencies = this.had_dependencies(app);
let had_entity_watches = !this.data(app).entity_watches.is_empty();
let data = this.data_mut(app);
data.lifecycle = ElementLifecycle::Active;
if let Some(dependencies) = &mut data.dependencies {
dependencies.clear();
}
data.had_unsatisfied_dependencies = false;
this.update_inheritance(app);
this.attach_notification_tree(app);
if this.dirty(app) {
owner.schedule_build_for(app, this);
}
if had_dependencies {
this.did_change_dependencies(app);
} else if had_entity_watches {
this.mark_needs_build(app);
}
}
fn deactivate(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
debug_assert!(this.mounted(app));
this.ensure_deactivated(app);
}
fn unmount(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) == ElementLifecycle::Inactive);
debug_assert!(this.mounted(app));
let owner = this
.owner(app)
.expect("an inactive element keeps its owner");
if let Some(KeyRef::Global(key)) = this.widget(app).key().cloned() {
owner.unregister_global_key(app, &key, this);
}
let data = this.data_mut(app);
data.widget = None;
data.dependencies = None;
data.entity_watches.clear();
data.lifecycle = ElementLifecycle::Defunct;
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
this.set_dirty(app, false);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) == ElementLifecycle::Active); debug_assert!(debug_check_owner_build_target_exists(
this,
app,
"didChangeDependencies"
));
this.mark_needs_build(app);
}
fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
let tree = this
.parent(app)
.and_then(|parent| parent.data(app).notification_tree.clone());
this.data_mut(app).notification_tree = tree;
}
fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
self.as_element()
.data(app)
.parent_build_scope
.expect("an element in a tree has a build scope")
}
fn mark_needs_build(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) != ElementLifecycle::Defunct);
if this.lifecycle(app) != ElementLifecycle::Active {
return;
}
let owner = this.owner(app).expect("an active element has an owner");
if cfg!(debug_assertions) {
if owner.debug_building(app) {
let target = owner
.debug_current_build_target(app)
.expect("building has a target");
debug_assert!(owner.debug_state_locked(app));
assert!(
this.debug_is_descendant_of(app, target),
"setState() or markNeedsBuild() called during build. This widget cannot \
be marked as needing to build because the framework is already in the \
process of building widgets. A widget can be marked as needing to be \
built during the build phase only if one of its ancestors is currently \
building."
);
} else {
assert!(
!owner.debug_state_locked(app),
"setState() or markNeedsBuild() called when widget tree was locked."
);
}
}
if this.dirty(app) {
return;
}
this.data_mut(app).dirty = true;
owner.schedule_build_for(app, this);
}
fn update_inheritance(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
let inherited = this
.parent(app)
.and_then(|parent| parent.inherited_elements(app));
this.set_inherited_elements(app, inherited);
}
fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
let this = self.as_element();
let mut current = Some(this);
while let Some(element) = current {
if element.lifecycle(app) == ElementLifecycle::Defunct {
break;
} else if element.is_render_object_element() {
return element.render_object(app);
} else {
current = element.render_object_attaching_child(app);
}
}
None
}
}
impl<T: Element> ElementBase for T {}
pub(crate) fn debug_check_owner_build_target_exists(
this: AnyElement,
app: &App,
method_name: &str,
) -> bool {
let owner = this.owner(app).expect("an active element has an owner");
assert!(
owner.debug_current_build_target(app).is_some(),
"{method_name} for {:?} was called at an inappropriate time. It may only be called \
while the widgets are being built.",
this.widget(app)
);
true
}
fn debug_check_for_cycles(this: AnyElement, app: &App, new_child: AnyElement) -> bool {
debug_assert!(new_child.parent(app).is_none());
let mut node = this;
while let Some(parent) = node.parent(app) {
node = parent;
}
assert!(
node != new_child,
"about to create a cycle in the element tree"
);
true
}
pub fn widget_kind(widget: &dyn Widget) -> WidgetKind {
widget.kind()
}