1use 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
53pub type BuildContext = AnyElement;
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum ElementLifecycle {
62 Initial,
63 Active,
64 Inactive,
65 Failed,
66 Defunct,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct IndexedSlot {
77 pub value: Option<AnyElement>,
80 pub index: usize,
82}
83
84#[derive(Clone, Debug)]
86pub enum Slot {
87 Indexed(IndexedSlot),
89 Index(i32),
91 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
106pub type ForgottenChildren<'a> = &'a dyn Fn(&App, AnyElement) -> bool;
109
110pub trait NotificationTarget: 'static {
116 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
126pub trait Notification: Any + Debug {
137 fn as_any(&self) -> &dyn Any;
139
140 fn viewport_depth(&self) -> Option<&Cell<u32>> {
150 None
151 }
152
153 fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
160 None
161 }
162
163 fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
172 None
173 }
174
175 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
190pub struct NotificationNode {
192 parent: Option<Rc<NotificationNode>>,
193 current: AnyElement,
194}
195
196impl NotificationNode {
197 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
212pub 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 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 notification_tree: Option<Rc<NotificationNode>>,
229 dependencies: Option<HashSet<AnyElement>>,
230 had_unsatisfied_dependencies: bool,
231 debug_built_once: bool,
232 entity_watches: HashMap<EntityId, Subscription>,
235}
236
237impl ElementData {
238 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 pub fn widget_ref(&self) -> &WidgetRef {
262 self.widget.as_ref().expect("the element is unmounted")
263 }
264}
265
266#[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
286pub trait Element: Sized + 'static {
298 fn element_data(self: Handle<Self>, app: &App) -> &ElementData;
301
302 fn element_data_mut(self: Handle<Self>, app: &mut App) -> &mut ElementData;
304
305 fn as_element(self: Handle<Self>) -> AnyElement {
307 AnyElement {
308 id: self.id(),
309 vtable: const { &ElementVTable::of::<Self>() },
310 }
311 }
312
313 fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
319 let _ = (self, app, visitor);
320 }
321
322 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 fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
347 ElementBase::render_object_attaching_child(self, app)
348 }
349
350 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 fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
371 ElementBase::update(self, app, new_widget);
372 }
373
374 fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
376 ElementBase::update_slot(self, app, new_slot);
377 }
378
379 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 fn detach_render_object(self: Handle<Self>, app: &mut App) {
397 ElementBase::detach_render_object(self, app);
398 }
399
400 fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
403 let _ = (self, app, child);
404 }
405
406 fn activate(self: Handle<Self>, app: &mut App) {
408 ElementBase::activate(self, app);
409 }
410
411 fn deactivate(self: Handle<Self>, app: &mut App) {
413 ElementBase::deactivate(self, app);
414 }
415
416 fn debug_deactivated(self: Handle<Self>, app: &mut App) {
418 debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
419 }
420
421 fn unmount(self: Handle<Self>, app: &mut App) {
423 ElementBase::unmount(self, app);
424 }
425
426 fn perform_rebuild(self: Handle<Self>, app: &mut App) {
430 ElementBase::perform_rebuild(self, app);
431 }
432
433 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
435 ElementBase::did_change_dependencies(self, app);
436 }
437
438 fn update_inheritance(self: Handle<Self>, app: &mut App) {
440 ElementBase::update_inheritance(self, app);
441 }
442
443 fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
454 ElementBase::attach_notification_tree(self, app);
455 }
456
457 fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
463 ElementBase::build_scope(self, app)
464 }
465
466 fn mark_needs_build(self: Handle<Self>, app: &mut App) {
473 ElementBase::mark_needs_build(self, app);
474 }
475
476 fn on_notification(self: Handle<Self>, app: &mut App, notification: &dyn Notification) -> bool {
483 let _ = (app, notification);
484 false
485 }
486
487 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 fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
501 ElementBase::render_object(self, app)
502 }
503
504 fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
506 let _ = (self, app);
507 false
508 }
509
510 const IS_RENDER_OBJECT_ELEMENT: bool = false;
514
515 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 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 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 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 const IS_PARENT_DATA_ELEMENT: bool = false;
558
559 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 const IS_INHERITED_ELEMENT: bool = false;
571
572 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 fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
585 let _ = (self, app, dependent);
586 unreachable!("not an InheritedElement");
587 }
588
589 fn state_handle_id(self: Handle<Self>, app: &App) -> Option<(TypeId, HandleId)> {
591 let _ = (self, app);
592 None
593 }
594
595 fn debug_fill_properties(
599 self: Handle<Self>,
600 app: &App,
601 properties: &mut DiagnosticPropertiesBuilder,
602 ) {
603 let _ = (self, app, properties);
604 }
605
606 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
617pub(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
661fn 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#[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 pub fn id(self) -> HandleId {
764 self.id
765 }
766
767 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 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(¤t).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 pub fn widget(self, app: &App) -> &WidgetRef {
807 self.data(app).widget_ref()
808 }
809
810 pub fn mounted(self, app: &App) -> bool {
815 app.contains(self.id) && self.data(app).widget.is_some()
816 }
817
818 pub fn parent(self, app: &App) -> Option<AnyElement> {
820 self.data(app).parent
821 }
822
823 pub fn slot(self, app: &App) -> Option<Slot> {
825 self.data(app).slot.clone()
826 }
827
828 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 pub fn owner(self, app: &App) -> Option<Handle<BuildOwner>> {
840 self.data(app).owner
841 }
842
843 pub fn build_scope(self, app: &App) -> Handle<BuildScope> {
845 (self.vtable.build_scope)(app, self.id)
846 }
847
848 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 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 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 pub fn to_string_deep(self, app: &App) -> String {
900 self.to_string_deep_with(app, DiagnosticLevel::Debug, 65)
901 }
902
903 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 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 pub fn debug_is_active(self, app: &App) -> bool {
971 self.lifecycle(app) == ElementLifecycle::Active
972 }
973
974 pub fn debug_is_defunct(self, app: &App) -> bool {
976 self.lifecycle(app) == ElementLifecycle::Defunct
977 }
978
979 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 pub fn debug_doing_build(self, app: &App) -> bool {
994 (self.vtable.debug_doing_build)(app, self.id)
995 }
996
997 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 pub fn visit_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1008 (self.vtable.visit_children)(app, self.id, visitor);
1009 }
1010
1011 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 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 pub fn render_object_attaching_child(self, app: &App) -> Option<AnyElement> {
1040 (self.vtable.render_object_attaching_child)(app, self.id)
1041 }
1042
1043 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 pub fn update(self, app: &mut App, new_widget: WidgetRef) {
1050 (self.vtable.update)(app, self.id, new_widget);
1051 }
1052
1053 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 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 pub fn detach_render_object(self, app: &mut App) {
1065 (self.vtable.detach_render_object)(app, self.id);
1066 }
1067
1068 pub fn forget_child(self, app: &mut App, child: AnyElement) {
1070 (self.vtable.forget_child)(app, self.id, child);
1071 }
1072
1073 pub fn activate(self, app: &mut App) {
1075 (self.vtable.activate)(app, self.id);
1076 }
1077
1078 pub fn deactivate(self, app: &mut App) {
1080 (self.vtable.deactivate)(app, self.id);
1081 }
1082
1083 pub fn debug_deactivated(self, app: &mut App) {
1085 (self.vtable.debug_deactivated)(app, self.id);
1086 }
1087
1088 pub fn unmount(self, app: &mut App) {
1090 (self.vtable.unmount)(app, self.id);
1091 }
1092
1093 pub fn perform_rebuild(self, app: &mut App) {
1095 (self.vtable.perform_rebuild)(app, self.id);
1096 }
1097
1098 pub fn did_change_dependencies(self, app: &mut App) {
1100 (self.vtable.did_change_dependencies)(app, self.id);
1101 }
1102
1103 pub fn update_inheritance(self, app: &mut App) {
1105 (self.vtable.update_inheritance)(app, self.id);
1106 }
1107
1108 pub fn attach_notification_tree(self, app: &mut App) {
1110 (self.vtable.attach_notification_tree)(app, self.id);
1111 }
1112
1113 pub fn on_notification(self, app: &mut App, notification: &dyn Notification) -> bool {
1115 (self.vtable.on_notification)(app, self.id, notification)
1116 }
1117
1118 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 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 pub fn render_object(self, app: &App) -> Option<AnyRenderObject> {
1143 (self.vtable.render_object)(app, self.id)
1144 }
1145
1146 #[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 #[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 pub fn is_render_object_element(self) -> bool {
1195 self.vtable.is_render_object_element
1196 }
1197
1198 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 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 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 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 pub fn is_parent_data_element(self) -> bool {
1236 self.vtable.is_parent_data_element
1237 }
1238
1239 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 pub fn is_inherited_element(self) -> bool {
1246 self.vtable.is_inherited_element
1247 }
1248
1249 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 pub fn remove_dependent(self, app: &mut App, dependent: AnyElement) {
1261 (self.vtable.remove_dependent)(app, self.id, dependent);
1262 }
1263
1264 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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); }
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 let data = self.data_mut(app);
1699 data.inherited_elements = None;
1700 data.lifecycle = ElementLifecycle::Inactive;
1701 }
1702
1703 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn mark_needs_build(self, app: &mut App) {
2048 (self.vtable.mark_needs_build)(app, self.id);
2049 }
2050
2051 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 #[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 #[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 pub fn notification_tree(self, app: &App) -> Option<Rc<NotificationNode>> {
2111 self.data(app).notification_tree.clone()
2112 }
2113
2114 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 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
2152fn 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
2164pub(crate) struct Rebuilding {
2169 owner: Handle<BuildOwner>,
2170 debug_previous_build_target: Option<AnyElement>,
2171}
2172
2173pub trait ElementBase: Element {
2179 #[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 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()); next = Some(child);
2198 });
2199 next
2200 }
2201
2202 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 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 #[inline(always)]
2252 fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
2253 let this = self.as_element();
2254 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 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 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 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 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 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 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 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 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 fn perform_rebuild(self: Handle<Self>, app: &mut App) {
2354 let this = self.as_element();
2355 this.set_dirty(app, false);
2356 }
2357
2358 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2360 let this = self.as_element();
2361 debug_assert!(this.lifecycle(app) == ElementLifecycle::Active); debug_assert!(debug_check_owner_build_target_exists(
2363 this,
2364 app,
2365 "didChangeDependencies"
2366 ));
2367 this.mark_needs_build(app);
2368 }
2369
2370 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 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 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 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 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
2451pub(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
2480pub fn widget_kind(widget: &dyn Widget) -> WidgetKind {
2482 widget.kind()
2483}