Skip to main content

waft_widgets/framework/
widget.rs

1//! `Widget` and its kinds. A widget is an immutable value; the tree holds it as a shared
2//! [`WidgetRef`]. Dart's `class Foo extends StatelessWidget` is `impl StatelessWidget for
3//! Foo`, and a value becomes a tree node with [`IntoWidget::into_widget`].
4
5use std::any::{Any, TypeId};
6use std::fmt::{self, Debug};
7use std::hash::{Hash, Hasher};
8use std::panic::Location;
9use std::rc::Rc;
10
11use waft_foundation::{
12    App, DiagnosticPropertiesBuilder, DiagnosticableNode, DiagnosticsTreeStyle, HandleId,
13    IntoPropertyName, Key,
14};
15use waft_rendering::{
16    AnyRenderObject, ContainerRenderObjectMixin, ErasedRenderObject, ParentData, RenderHandle,
17    RenderObject, RenderObjectWithChildMixin,
18};
19
20use super::element::{AnyElement, BuildContext, Element};
21use super::elements::{
22    InheritedElement, LeafRenderObjectElement, MultiChildRenderObjectElement, ParentDataElement,
23    SingleChildRenderObjectElement, StatefulElement, StatelessElement,
24};
25use super::state::{AnyState, State};
26use crate::widgets::inherited_theme::InheritedTheme;
27use crate::widgets::preferred_size::PreferredSizeWidget;
28
29/// A widget's key (Dart's `Key?` on a widget): a local key, or a [`GlobalKey`], which is a
30/// key the element tree registers.
31///
32/// Every key type converts into it with `.into()`: a [`GlobalKey`] into
33/// [`Global`](Self::Global), any other [`Key`] (including an app's own) into
34/// [`Local`](Self::Local).
35#[derive(Clone)]
36pub enum KeyRef {
37    /// A key the element tree does not register (Dart's `LocalKey`).
38    Local(Rc<dyn Key>),
39    /// A key the element tree registers (Dart's `GlobalKey`).
40    Global(GlobalKey),
41}
42
43impl KeyRef {
44    /// The key that decides how this key compares.
45    pub fn key(&self) -> &dyn Key {
46        match self {
47            KeyRef::Local(key) => &**key,
48            KeyRef::Global(global) => global.key(),
49        }
50    }
51}
52
53impl PartialEq for KeyRef {
54    fn eq(&self, other: &KeyRef) -> bool {
55        match (self, other) {
56            (KeyRef::Local(a), KeyRef::Local(b)) => **a == **b,
57            (KeyRef::Global(a), KeyRef::Global(b)) => a == b,
58            _ => false,
59        }
60    }
61}
62
63impl Eq for KeyRef {}
64
65impl Hash for KeyRef {
66    fn hash<H: Hasher>(&self, state: &mut H) {
67        std::mem::discriminant(self).hash(state);
68        self.key().hash(state);
69    }
70}
71
72impl Debug for KeyRef {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match self {
75            KeyRef::Local(key) => key.fmt(f),
76            KeyRef::Global(global) => global.fmt(f),
77        }
78    }
79}
80
81impl<K: Key> From<K> for KeyRef {
82    fn from(key: K) -> KeyRef {
83        KeyRef::Local(Rc::new(key))
84    }
85}
86
87impl From<GlobalKey> for KeyRef {
88    fn from(key: GlobalKey) -> KeyRef {
89        KeyRef::Global(key)
90    }
91}
92
93/// A shared, immutable widget (Dart's `Widget` reference).
94pub type WidgetRef = Rc<dyn Widget>;
95
96/// Dart's `Widget.==`, which no widget can override: identity.
97impl PartialEq for dyn Widget {
98    fn eq(&self, other: &dyn Widget) -> bool {
99        std::ptr::addr_eq(self as *const dyn Widget, other as *const dyn Widget)
100    }
101}
102
103/// Describes the configuration for an `Element`.
104///
105/// Widgets are the central class hierarchy in the Flutter framework. A widget is an immutable
106/// description of part of a user interface. Widgets can be inflated into elements, which
107/// manage the underlying render tree.
108///
109/// This is the erased object every kind of widget becomes ([`IntoWidget`]); user code
110/// implements a kind ([`StatelessWidget`], [`StatefulWidget`], …) rather than this trait.
111pub trait Widget: Any + Debug {
112    /// Controls how one widget replaces another widget in the tree.
113    ///
114    /// If the [`key`](Self::key) of the widget is the same as the key of the widget it is
115    /// replacing (and the types are the same), the framework updates the existing element
116    /// instead of creating a new one.
117    fn key(&self) -> Option<&KeyRef>;
118
119    /// Where the widget was made, in a debug build: Dart's creation location, which the widget
120    /// inspector shows and its summary tree keeps the app's own widgets by.
121    fn creation_location(&self) -> Option<&'static Location<'static>> {
122        None
123    }
124
125    /// Keeps where the widget was made, for [`creation_location`](Self::creation_location) to
126    /// answer: what `into_widget` calls on a widget that is its own tree node, which has no
127    /// wrapper to keep it in. Such a widget keeps it in a field
128    /// (`created: Option<CreationLocation>`); the default keeps nothing.
129    fn record_creation_location(&mut self, location: CreationLocation) {
130        let _ = location;
131    }
132
133    /// Dart's `toStringShort`: the type, then the key when there is one, as
134    /// `Text-[<'title'>]`.
135    fn to_string_short(&self) -> String {
136        describe_widget(self.type_name(), self.key())
137    }
138
139    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
140    /// order. Dart's `Widget` base only sets the dense tree style, which
141    /// [`to_diagnostics_node`](<dyn Widget>::to_diagnostics_node) does before calling this.
142    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
143        let _ = properties;
144    }
145
146    /// Inflates this configuration to a concrete instance. `this` is this widget's shared
147    /// reference, which the element keeps.
148    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement;
149
150    /// The concrete widget, for Dart's `widget as Foo`.
151    fn as_any(&self) -> &dyn Any;
152
153    /// The concrete widget's type, Dart's `runtimeType`.
154    fn widget_type(&self) -> TypeId;
155
156    /// The concrete widget's type name, as Dart's `runtimeType` prints in a message: the
157    /// type's own name without its module path.
158    ///
159    /// The default names `Self`, so an erased form overrides it with
160    /// [`short_type_name`]`::<W>()` of the widget it wraps.
161    fn type_name(&self) -> &'static str {
162        short_type_name::<Self>()
163    }
164
165    /// The kind of element this widget inflates to, for `Element.updateChild`'s superclass
166    /// check.
167    fn kind(&self) -> WidgetKind;
168
169    /// Dart's `widget is InheritedTheme`: this widget as an [`InheritedTheme`], when it is one.
170    ///
171    /// Only the erased form of an inherited widget forwards it, from
172    /// [`InheritedWidget::as_inherited_theme`]; `InheritedTheme::capture` also checks that the
173    /// ancestor is an inherited element, as Dart's pattern does.
174    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
175        None
176    }
177
178    /// This widget as a [`RenderObjectWidget`], when it is one of the three kinds the framework
179    /// makes elements for (leaf, single-child, multi-child): what those elements create and
180    /// update their render object through, so they are not copied per widget type.
181    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
182        None
183    }
184
185    /// This widget as a [`SingleChildRenderObjectWidget`], when it is one.
186    fn as_single_child_render_object(&self) -> Option<&dyn AnySingleChildRenderObjectWidget> {
187        None
188    }
189
190    /// This widget as a [`MultiChildRenderObjectWidget`], when it is one.
191    fn as_multi_child_render_object(&self) -> Option<&dyn AnyMultiChildRenderObjectWidget> {
192        None
193    }
194
195    /// This widget as a [`ParentDataWidget`], when it is one: what the one
196    /// [`ParentDataElement`] reads, so that element is not copied per widget type.
197    fn as_parent_data(&self) -> Option<&dyn AnyParentDataWidget> {
198        None
199    }
200
201    /// This widget as a [`StatefulWidget`], when it is one: what the one [`StatefulElement`]
202    /// creates its state through, so that element is not copied per widget type.
203    fn as_stateful(&self) -> Option<&dyn AnyStatefulWidget> {
204        None
205    }
206
207    /// This widget as an [`InheritedWidget`], when it is one: what the one
208    /// [`InheritedElement`] reads, so that element is not copied per widget type.
209    fn as_inherited(&self) -> Option<&dyn AnyInheritedWidget> {
210        None
211    }
212
213    /// This widget as a [`StatelessWidget`], when it is one: what the one
214    /// [`StatelessElement`] builds from, so that element is not copied per widget type.
215    fn as_stateless(&self) -> Option<&dyn StatelessWidget> {
216        None
217    }
218
219    /// Dart's `widget is PreferredSizeWidget`: this widget as a [`PreferredSizeWidget`], when
220    /// it is one.
221    ///
222    /// The erased forms of a stateless and a stateful widget forward it, from
223    /// [`StatelessWidget::as_preferred_size_widget`] and
224    /// [`StatefulWidget::as_preferred_size_widget`].
225    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
226        None
227    }
228}
229
230impl dyn Widget {
231    /// Dart's `Widget.toDiagnosticsNode(name:, style:)`: a snapshot of this widget's properties,
232    /// in the dense style unless `style` says otherwise.
233    pub fn to_diagnostics_node(
234        &self,
235        app: &App,
236        name: impl IntoPropertyName,
237        style: Option<DiagnosticsTreeStyle>,
238    ) -> DiagnosticableNode {
239        let mut properties = DiagnosticPropertiesBuilder::new();
240        properties.default_diagnostics_tree_style = DiagnosticsTreeStyle::Dense;
241        self.debug_fill_properties(app, &mut properties);
242        let node = DiagnosticableNode::from_parts(name, self.to_string_short(), properties);
243        match style {
244            Some(style) => node.with_style(style),
245            None => node,
246        }
247    }
248}
249
250/// Dart's `Widget.toStringShort`: `type_name`, then `-` and the key when there is one.
251pub fn describe_widget(type_name: &str, key: Option<&KeyRef>) -> String {
252    match key {
253        Some(key) => format!("{type_name}-{key:?}"),
254        None => type_name.to_string(),
255    }
256}
257
258/// Dart's `Widget._debugConcreteSubtype` classes.
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260pub enum WidgetKind {
261    Stateful,
262    Stateless,
263    Other,
264}
265
266/// Whether the `new_widget` can be used to update an `Element` that currently has the
267/// `old_widget` as its configuration.
268///
269/// An element that uses a given widget as its configuration can be updated to use another
270/// widget as its configuration if, and only if, the two widgets have `runtimeType` and
271/// [`Widget::key`] properties that are equal.
272///
273/// If the widgets have no key (their key is null), then they are considered a match if they
274/// have the same type, even if their children are completely different.
275pub fn can_update(old_widget: &dyn Widget, new_widget: &dyn Widget) -> bool {
276    old_widget.widget_type() == new_widget.widget_type()
277        && keys_equal(old_widget.key(), new_widget.key())
278}
279
280/// Dart's `oldWidget.key == newWidget.key`.
281pub fn keys_equal(a: Option<&KeyRef>, b: Option<&KeyRef>) -> bool {
282    match (a, b) {
283        (None, None) => true,
284        (Some(a), Some(b)) => a == b,
285        _ => false,
286    }
287}
288
289/// Dart's `identical(a, b)` on two widget references: `Widget.==` is identity.
290pub fn same_widget(a: &WidgetRef, b: &WidgetRef) -> bool {
291    Rc::ptr_eq(a, b)
292}
293
294/// Dart's `widget as W`: the concrete widget behind a [`WidgetRef`], when it is a `W`.
295pub fn downcast_widget<W: 'static>(widget: &dyn Widget) -> Option<&W> {
296    widget.as_any().downcast_ref::<W>()
297}
298
299/// `W`'s name as Dart's `runtimeType` prints it, for [`Widget::type_name`]: the module path
300/// before the type's own name is cut, and the type arguments are kept as Rust writes them.
301pub fn short_type_name<W: ?Sized>() -> &'static str {
302    without_module_path(std::any::type_name::<W>())
303}
304
305/// [`short_type_name`]'s cut, one body for every type.
306fn without_module_path(name: &'static str) -> &'static str {
307    let type_arguments = name.find('<').unwrap_or(name.len());
308    let own_name = name[..type_arguments]
309        .rfind("::")
310        .map_or(0, |path_end| path_end + 2);
311    &name[own_name..]
312}
313
314/// Where a widget was made, in a debug build: the line of the call that turned it into a
315/// [`WidgetRef`], which a setter taking a child passes on from its own caller. Dart's
316/// `--track-widget-creation` location, which is also kept in a debug build alone; a release build
317/// keeps nothing.
318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub struct CreationLocation {
320    #[cfg(debug_assertions)]
321    location: &'static Location<'static>,
322}
323
324impl CreationLocation {
325    /// The location of the call this one's caller was called from, as `#[track_caller]` carries
326    /// it.
327    #[cfg_attr(debug_assertions, track_caller)]
328    pub fn of_caller() -> CreationLocation {
329        CreationLocation {
330            #[cfg(debug_assertions)]
331            location: Location::caller(),
332        }
333    }
334
335    /// The location, in a debug build.
336    pub fn location(self) -> Option<&'static Location<'static>> {
337        #[cfg(debug_assertions)]
338        return Some(self.location);
339        #[cfg(not(debug_assertions))]
340        return None;
341    }
342}
343
344/// The conversion of a widget value into a tree node.
345///
346/// Every widget kind gets a blanket implementation, told apart by the phantom `Kind` so the
347/// implementations do not overlap; a call site infers it. A [`WidgetRef`] converts to itself, and
348/// a widget that is its own tree node converts as itself ([`TreeNodeKind`]).
349pub trait IntoWidget<Kind> {
350    /// The widget as a tree node, made where this is called: its
351    /// [`creation_location`](Widget::creation_location).
352    #[cfg_attr(debug_assertions, track_caller)]
353    fn into_widget(self) -> WidgetRef;
354}
355
356/// The kind tag of [`IntoWidget`] for a [`WidgetRef`].
357pub struct WidgetRefKind;
358
359impl IntoWidget<WidgetRefKind> for WidgetRef {
360    fn into_widget(self) -> WidgetRef {
361        self
362    }
363}
364
365/// The kind tag of [`IntoWidget`] for a widget that is its own tree node: one implementing
366/// [`Widget`] directly, whose element is its own rather than a wrapper's — a render object
367/// widget that builds a child during layout (`LayoutBuilder`), a table (`Table`), a proxy widget
368/// (`NotificationListener`), a collection of views (`ViewCollection`). It converts to itself,
369/// which is what its inherent `into_widget` answers.
370pub struct TreeNodeKind;
371
372impl<W: Widget> IntoWidget<TreeNodeKind> for W {
373    #[cfg_attr(debug_assertions, track_caller)]
374    fn into_widget(mut self) -> WidgetRef {
375        self.record_creation_location(CreationLocation::of_caller());
376        Rc::new(self)
377    }
378}
379
380// ---------------------------------------------------------------------------------------------
381// StatelessWidget
382
383/// A widget that does not require mutable state.
384///
385/// A stateless widget is a widget that describes part of the user interface by building a
386/// constellation of other widgets that describe the user interface more concretely. The
387/// building process continues recursively until the description of the user interface is
388/// fully concrete (e.g., consists entirely of `RenderObjectWidget`s, which describe concrete
389/// `RenderObject`s).
390pub trait StatelessWidget: Debug + 'static {
391    /// See [`Widget::key`].
392    fn key(&self) -> Option<&KeyRef> {
393        None
394    }
395
396    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
397    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
398    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
399        let _ = properties;
400    }
401
402    /// Dart's constructor asserts that relate two or more arguments.
403    ///
404    /// A fluent chain of setters has seen every argument only once it ends, so the framework
405    /// calls this in a debug build when the widget is turned into a [`WidgetRef`]
406    /// (`into_widget`), and a bad combination panics where the widget is handed to the tree.
407    /// An assert on one argument stays in that argument's setter.
408    fn debug_check_constructor(&self) {}
409
410    /// Dart's `this is PreferredSizeWidget`: a widget that implements [`PreferredSizeWidget`]
411    /// answers with itself, which is what a parent asking an erased child for its preferred
412    /// size reads.
413    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
414        None
415    }
416
417    /// Describes the part of the user interface represented by this widget.
418    ///
419    /// The framework calls this method when this widget is inserted into the tree in a given
420    /// [`BuildContext`] and when the dependencies of this widget change (e.g., an
421    /// `InheritedWidget` referenced by this widget changes). This method can potentially be
422    /// called in every frame and should not have any side effects beyond building a widget.
423    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
424}
425
426/// The kind tag of [`IntoWidget`] for a [`StatelessWidget`].
427pub struct StatelessKind;
428
429/// The erased form of a [`StatelessWidget`].
430pub struct Stateless<W: StatelessWidget>(pub W, pub(crate) CreationLocation);
431
432impl<W: StatelessWidget> IntoWidget<StatelessKind> for W {
433    #[cfg_attr(debug_assertions, track_caller)]
434    fn into_widget(self) -> WidgetRef {
435        if cfg!(debug_assertions) {
436            self.debug_check_constructor();
437        }
438        Rc::new(Stateless(self, CreationLocation::of_caller()))
439    }
440}
441
442impl<W: StatelessWidget> Widget for Stateless<W> {
443    fn key(&self) -> Option<&KeyRef> {
444        self.0.key()
445    }
446
447    fn creation_location(&self) -> Option<&'static Location<'static>> {
448        self.1.location()
449    }
450
451    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
452        self.0.debug_fill_properties(app, properties);
453    }
454
455    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
456        StatelessElement::new(app, this).as_element()
457    }
458
459    fn as_any(&self) -> &dyn Any {
460        &self.0
461    }
462
463    fn widget_type(&self) -> TypeId {
464        TypeId::of::<W>()
465    }
466
467    fn type_name(&self) -> &'static str {
468        short_type_name::<W>()
469    }
470
471    fn kind(&self) -> WidgetKind {
472        WidgetKind::Stateless
473    }
474
475    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
476        self.0.as_preferred_size_widget()
477    }
478
479    fn as_stateless(&self) -> Option<&dyn StatelessWidget> {
480        Some(&self.0)
481    }
482}
483
484impl<W: StatelessWidget> Debug for Stateless<W> {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        self.0.fmt(f)
487    }
488}
489
490// ---------------------------------------------------------------------------------------------
491// StatefulWidget
492
493/// A widget that has mutable state.
494///
495/// State is information that (1) can be read synchronously when the widget is built and (2)
496/// might change during the lifetime of the widget. It is the responsibility of the widget
497/// implementer to ensure that the [`State`] is promptly notified when such state changes,
498/// using `State::set_state`.
499///
500/// A stateful widget is a widget that describes part of the user interface by building a
501/// constellation of other widgets that describe the user interface more concretely.
502///
503/// Dart's `createState` returns any `State<Foo>`; here the state class is the associated
504/// type [`State`](Self::State), which is what `State<T>`'s type argument already fixed.
505///
506/// Make one when the widget owns a Flutter object between builds — a
507/// [`TextEditingController`](crate::TextEditingController), a [`FocusNode`](crate::FocusNode),
508/// an [`AnimationController`](crate::AnimationController). The app's data lives in an
509/// [`Entity`](waft_foundation::Entity), which a [`StatelessWidget`] reads in `build` and is
510/// rebuilt by when it notifies; see [`State`].
511pub trait StatefulWidget: Debug + 'static {
512    /// The state this widget creates.
513    type State: State<Widget = Self>;
514
515    /// See [`Widget::key`].
516    fn key(&self) -> Option<&KeyRef> {
517        None
518    }
519
520    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
521    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
522    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
523        let _ = properties;
524    }
525
526    /// See [`StatelessWidget::debug_check_constructor`].
527    fn debug_check_constructor(&self) {}
528
529    /// See [`StatelessWidget::as_preferred_size_widget`].
530    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
531        None
532    }
533
534    /// See [`Widget::type_name`]. A stateful form another widget kind becomes (an animated or
535    /// status transition widget) names the widget it wraps.
536    fn type_name(&self) -> &'static str {
537        short_type_name::<Self>()
538    }
539
540    /// Creates the mutable state for this widget at a given location in the tree.
541    ///
542    /// The framework can call this method multiple times over the lifetime of a
543    /// [`StatefulWidget`]. For example, if the widget is inserted into the tree in multiple
544    /// locations, the framework will create a separate [`State`] object for each location.
545    /// Similarly, if the widget is removed from the tree and later inserted in to the tree
546    /// again, the framework will call [`create_state`](Self::create_state) again to create a
547    /// fresh [`State`] object, simplifying the lifecycle of [`State`] objects.
548    fn create_state(&self) -> Self::State;
549}
550
551/// The kind tag of [`IntoWidget`] for a [`StatefulWidget`].
552pub struct StatefulKind;
553
554/// The erased form of a [`StatefulWidget`].
555pub struct Stateful<W: StatefulWidget>(pub W, pub(crate) CreationLocation);
556
557impl<W: StatefulWidget> IntoWidget<StatefulKind> for W {
558    #[cfg_attr(debug_assertions, track_caller)]
559    fn into_widget(self) -> WidgetRef {
560        if cfg!(debug_assertions) {
561            self.debug_check_constructor();
562        }
563        Rc::new(Stateful(self, CreationLocation::of_caller()))
564    }
565}
566
567impl<W: StatefulWidget> Widget for Stateful<W> {
568    fn key(&self) -> Option<&KeyRef> {
569        self.0.key()
570    }
571
572    fn creation_location(&self) -> Option<&'static Location<'static>> {
573        self.1.location()
574    }
575
576    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
577        self.0.debug_fill_properties(app, properties);
578    }
579
580    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
581        StatefulElement::new(app, this).as_element()
582    }
583
584    fn as_any(&self) -> &dyn Any {
585        &self.0
586    }
587
588    fn widget_type(&self) -> TypeId {
589        TypeId::of::<W>()
590    }
591
592    fn type_name(&self) -> &'static str {
593        StatefulWidget::type_name(&self.0)
594    }
595
596    fn kind(&self) -> WidgetKind {
597        WidgetKind::Stateful
598    }
599
600    fn as_stateful(&self) -> Option<&dyn AnyStatefulWidget> {
601        Some(self)
602    }
603
604    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
605        self.0.as_preferred_size_widget()
606    }
607}
608
609impl<W: StatefulWidget> AnyStatefulWidget for Stateful<W> {
610    fn create_state(&self, app: &mut App) -> AnyState {
611        let state = app.create(self.0.create_state()).into_tree_node(app);
612        AnyState::of(state)
613    }
614}
615
616/// A [`StatefulWidget`] of any type, as the one [`StatefulElement`] reaches it.
617pub trait AnyStatefulWidget {
618    /// [`StatefulWidget::create_state`], with the state put in the arena for its element.
619    fn create_state(&self, app: &mut App) -> AnyState;
620}
621
622impl<W: StatefulWidget> Debug for Stateful<W> {
623    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624        self.0.fmt(f)
625    }
626}
627
628// ---------------------------------------------------------------------------------------------
629// ProxyWidget: ParentDataWidget, InheritedWidget
630
631/// Base class for widgets that efficiently propagate information down the tree.
632///
633/// To obtain the nearest instance of a particular type of inherited widget from a build
634/// context, use `BuildContext::depend_on_inherited_widget_of_exact_type`.
635///
636/// Inherited widgets, when referenced in this way, will cause the consumer to rebuild when
637/// the inherited widget itself changes state.
638pub trait InheritedWidget: Debug + 'static {
639    /// See [`Widget::key`].
640    fn key(&self) -> Option<&KeyRef> {
641        None
642    }
643
644    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
645    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
646    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
647        let _ = properties;
648    }
649
650    /// See [`StatelessWidget::debug_check_constructor`].
651    fn debug_check_constructor(&self) {}
652
653    /// The widget below this widget in the tree.
654    fn child(&self) -> &WidgetRef;
655
656    /// Whether the framework should notify widgets that inherit from this widget.
657    ///
658    /// When this widget is rebuilt, sometimes we need to rebuild the widgets that inherit
659    /// from this widget but sometimes we do not. For example, if the data held by this widget
660    /// is the same as the data held by `old_widget`, then we do not need to rebuild the
661    /// widgets that inherited the data held by `old_widget`.
662    ///
663    /// The framework distinguishes these cases by calling this function with the widget that
664    /// previously occupied this location in the tree as an argument. The given widget is
665    /// guaranteed to have the same `runtimeType` as this object.
666    fn update_should_notify(&self, old_widget: &Self) -> bool;
667
668    /// Dart's `this is InheritedTheme`: an inherited widget that is an [`InheritedTheme`]
669    /// answers with itself, which is what `InheritedTheme::capture` collects.
670    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
671        None
672    }
673}
674
675/// The kind tag of [`IntoWidget`] for an [`InheritedWidget`].
676pub struct InheritedKind;
677
678/// The erased form of an [`InheritedWidget`].
679pub struct Inherited<W: InheritedWidget>(pub W, pub(crate) CreationLocation);
680
681impl<W: InheritedWidget> IntoWidget<InheritedKind> for W {
682    #[cfg_attr(debug_assertions, track_caller)]
683    fn into_widget(self) -> WidgetRef {
684        if cfg!(debug_assertions) {
685            self.debug_check_constructor();
686        }
687        Rc::new(Inherited(self, CreationLocation::of_caller()))
688    }
689}
690
691impl<W: InheritedWidget> Widget for Inherited<W> {
692    fn key(&self) -> Option<&KeyRef> {
693        self.0.key()
694    }
695
696    fn creation_location(&self) -> Option<&'static Location<'static>> {
697        self.1.location()
698    }
699
700    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
701        self.0.debug_fill_properties(app, properties);
702    }
703
704    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
705        InheritedElement::new(app, this).as_element()
706    }
707
708    fn as_any(&self) -> &dyn Any {
709        &self.0
710    }
711
712    fn widget_type(&self) -> TypeId {
713        TypeId::of::<W>()
714    }
715
716    fn type_name(&self) -> &'static str {
717        short_type_name::<W>()
718    }
719
720    fn kind(&self) -> WidgetKind {
721        WidgetKind::Other
722    }
723
724    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
725        self.0.as_inherited_theme()
726    }
727
728    fn as_inherited(&self) -> Option<&dyn AnyInheritedWidget> {
729        Some(self)
730    }
731}
732
733impl<W: InheritedWidget> AnyInheritedWidget for Inherited<W> {
734    fn child(&self) -> &WidgetRef {
735        self.0.child()
736    }
737
738    fn update_should_notify(&self, old_widget: &dyn Widget) -> bool {
739        let old_widget =
740            downcast_widget::<W>(old_widget).expect("the old widget has the same type");
741        self.0.update_should_notify(old_widget)
742    }
743}
744
745/// An [`InheritedWidget`] of any type, as the one [`InheritedElement`] reads it.
746pub trait AnyInheritedWidget {
747    /// See [`InheritedWidget::child`].
748    fn child(&self) -> &WidgetRef;
749
750    /// [`InheritedWidget::update_should_notify`] against an `old_widget` of the same type.
751    fn update_should_notify(&self, old_widget: &dyn Widget) -> bool;
752}
753
754impl<W: InheritedWidget> Debug for Inherited<W> {
755    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756        self.0.fmt(f)
757    }
758}
759
760/// Base class for widgets that hook `ParentData` information for children of
761/// `RenderObjectWidget`s.
762///
763/// This can be used to provide per-child configuration for `RenderObjectWidget`s with more
764/// than one child. For example, `Stack` uses the `Positioned` parent data widget to position
765/// each child.
766pub trait ParentDataWidget: Debug + 'static {
767    /// The parent data this widget writes; Dart's `T extends ParentData`.
768    type ParentData: ParentData + 'static;
769
770    /// See [`Widget::key`].
771    fn key(&self) -> Option<&KeyRef> {
772        None
773    }
774
775    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
776    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
777    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
778        let _ = properties;
779    }
780
781    /// See [`StatelessWidget::debug_check_constructor`].
782    fn debug_check_constructor(&self) {}
783
784    /// The widget below this widget in the tree.
785    fn child(&self) -> &WidgetRef;
786
787    /// Write the data from this widget into the given render object's parent data.
788    ///
789    /// The framework calls this function whenever it detects that the `RenderObject`
790    /// associated with the [`child`](Self::child) has outdated `parent_data`. The parent data
791    /// is the data that the parent of the render object uses when laying out and painting the
792    /// render object.
793    ///
794    /// This function is responsible for calling `mark_needs_layout` on the render object as
795    /// appropriate.
796    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject);
797
798    /// Dart's `debugIsValidRenderObject`: whether `render_object`'s parent data is the one
799    /// this widget writes.
800    ///
801    /// The default answers `render_object.parent_data_is::<Self::ParentData>(app)`. A widget
802    /// whose Dart counterpart also accepts a subclass of its `ParentData` — `Positioned` on a
803    /// `_TheaterParentData` — overrides this to accept that type too.
804    fn debug_is_valid_render_object(
805        &self,
806        app: &App,
807        render_object: ::waft_rendering::AnyRenderObject,
808    ) -> bool {
809        render_object.parent_data_is::<Self::ParentData>(app)
810    }
811
812    /// Whether the `ParentDataElement::apply_widget_out_of_turn` method will be allowed
813    /// with this widget.
814    ///
815    /// This should only return true if this widget represents a `ParentData` configuration
816    /// that will have no impact on the layout or paint phase.
817    fn debug_can_apply_out_of_turn(&self) -> bool {
818        false
819    }
820}
821
822/// The kind tag of [`IntoWidget`] for a [`ParentDataWidget`].
823pub struct ParentDataKind;
824
825/// The erased form of a [`ParentDataWidget`].
826pub struct ParentDataWrapper<W: ParentDataWidget>(pub W, pub(crate) CreationLocation);
827
828impl<W: ParentDataWidget> IntoWidget<ParentDataKind> for W {
829    #[cfg_attr(debug_assertions, track_caller)]
830    fn into_widget(self) -> WidgetRef {
831        if cfg!(debug_assertions) {
832            self.debug_check_constructor();
833        }
834        Rc::new(ParentDataWrapper(self, CreationLocation::of_caller()))
835    }
836}
837
838impl<W: ParentDataWidget> Widget for ParentDataWrapper<W> {
839    fn key(&self) -> Option<&KeyRef> {
840        self.0.key()
841    }
842
843    fn creation_location(&self) -> Option<&'static Location<'static>> {
844        self.1.location()
845    }
846
847    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
848        self.0.debug_fill_properties(app, properties);
849    }
850
851    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
852        ParentDataElement::new(app, this).as_element()
853    }
854
855    fn as_any(&self) -> &dyn Any {
856        &self.0
857    }
858
859    fn widget_type(&self) -> TypeId {
860        TypeId::of::<W>()
861    }
862
863    fn type_name(&self) -> &'static str {
864        short_type_name::<W>()
865    }
866
867    fn kind(&self) -> WidgetKind {
868        WidgetKind::Other
869    }
870
871    fn as_parent_data(&self) -> Option<&dyn AnyParentDataWidget> {
872        Some(self)
873    }
874}
875
876impl<W: ParentDataWidget> AnyParentDataWidget for ParentDataWrapper<W> {
877    fn child(&self) -> &WidgetRef {
878        self.0.child()
879    }
880
881    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
882        self.0.apply_parent_data(app, render_object);
883    }
884
885    fn debug_is_valid_render_object(&self, app: &App, render_object: AnyRenderObject) -> bool {
886        self.0.debug_is_valid_render_object(app, render_object)
887    }
888
889    fn parent_data_type_name(&self) -> &'static str {
890        std::any::type_name::<W::ParentData>()
891    }
892}
893
894/// A [`ParentDataWidget`] of any type, as the one [`ParentDataElement`] reads it.
895pub trait AnyParentDataWidget: Debug {
896    /// See [`ParentDataWidget::child`].
897    fn child(&self) -> &WidgetRef;
898
899    /// See [`ParentDataWidget::apply_parent_data`].
900    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject);
901
902    /// See [`ParentDataWidget::debug_is_valid_render_object`].
903    fn debug_is_valid_render_object(&self, app: &App, render_object: AnyRenderObject) -> bool;
904
905    /// The name of [`ParentDataWidget::ParentData`], for the message of an invalid use.
906    fn parent_data_type_name(&self) -> &'static str;
907}
908
909impl<W: ParentDataWidget> Debug for ParentDataWrapper<W> {
910    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
911        self.0.fmt(f)
912    }
913}
914
915// ---------------------------------------------------------------------------------------------
916// RenderObjectWidget
917
918/// The parts of a `RenderObjectWidget` every kind shares: the render object it creates and
919/// updates. Dart's `covariant RenderObject renderObject` parameters are typed through
920/// [`RenderObject`](Self::RenderObject).
921pub trait RenderObjectWidget: Debug + 'static {
922    /// The render object this widget creates; Dart's `covariant RenderObject` parameter type.
923    type RenderObject: RenderObject;
924
925    /// See [`Widget::key`].
926    fn key(&self) -> Option<&KeyRef> {
927        None
928    }
929
930    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
931    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
932    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
933        let _ = properties;
934    }
935
936    /// Dart's `toStringShort`, for a widget that names itself apart from its type, as
937    /// `SizedBox.expand` does; see [`Widget::to_string_short`].
938    fn to_string_short(&self) -> String {
939        describe_widget(short_type_name::<Self>(), self.key())
940    }
941
942    /// See [`StatelessWidget::debug_check_constructor`].
943    fn debug_check_constructor(&self) {}
944
945    /// Dart's `debugVisitOnstageChildren` of the element this widget makes, for a widget whose
946    /// Dart element subclass overrides it only to hide children (`_OffstageElement`,
947    /// `_IndexedStackElement`): calls `visitor` for each of `children`, in order, that is
948    /// onstage. Waft's generic single- and multi-child elements stand in for those subclasses
949    /// and ask their widget here; an element of a widget's own overrides
950    /// [`Element::debug_visit_onstage_children`] instead.
951    fn debug_visit_onstage_children(
952        &self,
953        app: &App,
954        children: &[AnyElement],
955        visitor: &mut dyn FnMut(AnyElement),
956    ) {
957        let _ = app;
958        children.iter().for_each(|child| visitor(*child));
959    }
960
961    /// Creates an instance of the `RenderObject` class that this widget represents, using the
962    /// configuration described by this widget.
963    ///
964    /// This method should not do anything with the children of the render object. That
965    /// should instead be handled by the method that overrides `RenderObjectElement.mount`
966    /// in the object rendered by this object's `create_element` method.
967    ///
968    /// Returns the type-erased handle (`handle.as_object()`), which is what the element tree holds;
969    /// [`update_render_object`](Self::update_render_object) gets the typed handle back.
970    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject;
971
972    /// Copies the configuration described by this widget to the given render object, which
973    /// will be of the same type as returned by this object's
974    /// [`create_render_object`](Self::create_render_object).
975    ///
976    /// This method should not do anything to update the children of the render object. That
977    /// should instead be handled by the method that overrides `RenderObjectElement.update`
978    /// in the object rendered by this object's `create_element` method.
979    fn update_render_object(
980        &self,
981        app: &mut App,
982        context: BuildContext,
983        render_object: RenderHandle<Self::RenderObject>,
984    ) {
985        let _ = (app, context, render_object);
986    }
987
988    /// A render object previously associated with this widget has been removed from the tree.
989    /// The given `RenderObject` will be of the same type as returned by this object's
990    /// [`create_render_object`](Self::create_render_object).
991    fn did_unmount_render_object(
992        &self,
993        app: &mut App,
994        render_object: RenderHandle<Self::RenderObject>,
995    ) {
996        let _ = (app, render_object);
997    }
998}
999
1000/// A superclass for `RenderObjectWidget`s that configure `RenderObject` subclasses that have
1001/// no children.
1002pub trait LeafRenderObjectWidget: RenderObjectWidget {}
1003
1004/// The kind tag of [`IntoWidget`] for a [`LeafRenderObjectWidget`].
1005pub struct LeafRenderObjectKind;
1006
1007/// The erased form of a [`LeafRenderObjectWidget`].
1008pub struct LeafRenderObject<W: LeafRenderObjectWidget>(pub W, pub(crate) CreationLocation);
1009
1010impl<W: LeafRenderObjectWidget> IntoWidget<LeafRenderObjectKind> for W {
1011    #[cfg_attr(debug_assertions, track_caller)]
1012    fn into_widget(self) -> WidgetRef {
1013        if cfg!(debug_assertions) {
1014            RenderObjectWidget::debug_check_constructor(&self);
1015        }
1016        Rc::new(LeafRenderObject(self, CreationLocation::of_caller()))
1017    }
1018}
1019
1020impl<W: LeafRenderObjectWidget> Widget for LeafRenderObject<W> {
1021    fn key(&self) -> Option<&KeyRef> {
1022        self.0.key()
1023    }
1024
1025    fn creation_location(&self) -> Option<&'static Location<'static>> {
1026        self.1.location()
1027    }
1028
1029    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1030        self.0.debug_fill_properties(app, properties);
1031    }
1032
1033    fn to_string_short(&self) -> String {
1034        self.0.to_string_short()
1035    }
1036
1037    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
1038        LeafRenderObjectElement::new(app, this).as_element()
1039    }
1040
1041    fn as_any(&self) -> &dyn Any {
1042        &self.0
1043    }
1044
1045    fn widget_type(&self) -> TypeId {
1046        TypeId::of::<W>()
1047    }
1048
1049    fn type_name(&self) -> &'static str {
1050        short_type_name::<W>()
1051    }
1052
1053    fn kind(&self) -> WidgetKind {
1054        WidgetKind::Other
1055    }
1056
1057    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
1058        Some(self)
1059    }
1060}
1061
1062impl<W: LeafRenderObjectWidget> Debug for LeafRenderObject<W> {
1063    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1064        self.0.fmt(f)
1065    }
1066}
1067
1068/// A superclass for `RenderObjectWidget`s that configure `RenderObject` subclasses that have
1069/// a single child slot.
1070///
1071/// The render object assigned to this widget should make use of
1072/// `RenderObjectWithChildMixin` to implement a single child model.
1073pub trait SingleChildRenderObjectWidget: RenderObjectWidget
1074where
1075    Self::RenderObject: RenderObjectWithChildMixin,
1076{
1077    /// The widget below this widget in the tree.
1078    fn child(&self) -> Option<&WidgetRef>;
1079
1080    /// Creates the element that manages this widget's child.
1081    ///
1082    /// Dart's `createElement`; a widget whose element has bodies of its own
1083    /// (`SingleChildScrollView`'s viewport) overrides it with an element that implements
1084    /// `SingleChildRenderObjectElementBase`.
1085    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
1086    where
1087        Self: Sized,
1088    {
1089        SingleChildRenderObjectElement::new(app, this).as_element()
1090    }
1091}
1092
1093/// The kind tag of [`IntoWidget`] for a [`SingleChildRenderObjectWidget`].
1094pub struct SingleChildRenderObjectKind;
1095
1096/// The erased form of a [`SingleChildRenderObjectWidget`].
1097pub struct SingleChildRenderObject<W: SingleChildRenderObjectWidget>(
1098    pub W,
1099    pub(crate) CreationLocation,
1100)
1101where
1102    W::RenderObject: RenderObjectWithChildMixin;
1103
1104impl<W: SingleChildRenderObjectWidget> IntoWidget<SingleChildRenderObjectKind> for W
1105where
1106    W::RenderObject: RenderObjectWithChildMixin,
1107{
1108    #[cfg_attr(debug_assertions, track_caller)]
1109    fn into_widget(self) -> WidgetRef {
1110        if cfg!(debug_assertions) {
1111            RenderObjectWidget::debug_check_constructor(&self);
1112        }
1113        Rc::new(SingleChildRenderObject(self, CreationLocation::of_caller()))
1114    }
1115}
1116
1117impl<W: SingleChildRenderObjectWidget> Widget for SingleChildRenderObject<W>
1118where
1119    W::RenderObject: RenderObjectWithChildMixin,
1120{
1121    fn key(&self) -> Option<&KeyRef> {
1122        self.0.key()
1123    }
1124
1125    fn creation_location(&self) -> Option<&'static Location<'static>> {
1126        self.1.location()
1127    }
1128
1129    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1130        self.0.debug_fill_properties(app, properties);
1131    }
1132
1133    fn to_string_short(&self) -> String {
1134        self.0.to_string_short()
1135    }
1136
1137    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
1138        SingleChildRenderObjectWidget::create_element(&self.0, app, this)
1139    }
1140
1141    fn as_any(&self) -> &dyn Any {
1142        &self.0
1143    }
1144
1145    fn widget_type(&self) -> TypeId {
1146        TypeId::of::<W>()
1147    }
1148
1149    fn type_name(&self) -> &'static str {
1150        short_type_name::<W>()
1151    }
1152
1153    fn kind(&self) -> WidgetKind {
1154        WidgetKind::Other
1155    }
1156
1157    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
1158        Some(self)
1159    }
1160
1161    fn as_single_child_render_object(&self) -> Option<&dyn AnySingleChildRenderObjectWidget> {
1162        Some(self)
1163    }
1164}
1165
1166impl<W: SingleChildRenderObjectWidget> Debug for SingleChildRenderObject<W>
1167where
1168    W::RenderObject: RenderObjectWithChildMixin,
1169{
1170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1171        self.0.fmt(f)
1172    }
1173}
1174
1175/// A superclass for `RenderObjectWidget`s that configure `RenderObject` subclasses that have a
1176/// single list of children. (This superclass only provides the storage for that child list, it
1177/// doesn't actually provide the updating logic.)
1178///
1179/// The render object assigned to this widget must use `ContainerRenderObjectMixin`, which
1180/// provides the necessary functionality to visit the children of the container render object
1181/// (the render object belonging to the [`children`](Self::children) widgets).
1182///
1183/// See also:
1184///
1185///  * `Stack`, which uses [`MultiChildRenderObjectWidget`].
1186///  * `RenderStack`, for an example implementation of the associated render object.
1187pub trait MultiChildRenderObjectWidget: RenderObjectWidget
1188where
1189    Self::RenderObject: ContainerRenderObjectMixin,
1190{
1191    /// The widgets below this widget in the tree.
1192    ///
1193    /// If this list is going to be mutated, it is usually wise to put a [`Key`] on each of the
1194    /// child widgets, so that the framework can match old configurations to new configurations
1195    /// and maintain the underlying render objects.
1196    ///
1197    /// Also, a widget is immutable, so directly modifying the [`children`](Self::children) of a
1198    /// widget already in the tree results in incorrect behaviour. Whenever the children list is
1199    /// modified, a new list should be provided.
1200    fn children(&self) -> &[WidgetRef];
1201
1202    /// Creates the element that manages this widget's children.
1203    ///
1204    /// Dart's `createElement`; a widget whose element has bodies of its own (`Viewport`)
1205    /// overrides it with an element that implements `MultiChildRenderObjectElementBase`.
1206    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
1207    where
1208        Self: Sized,
1209    {
1210        MultiChildRenderObjectElement::new(app, this).as_element()
1211    }
1212}
1213
1214/// The kind tag of [`IntoWidget`] for a [`MultiChildRenderObjectWidget`].
1215pub struct MultiChildRenderObjectKind;
1216
1217/// The erased form of a [`MultiChildRenderObjectWidget`].
1218pub struct MultiChildRenderObject<W: MultiChildRenderObjectWidget>(
1219    pub W,
1220    pub(crate) CreationLocation,
1221)
1222where
1223    W::RenderObject: ContainerRenderObjectMixin;
1224
1225impl<W: MultiChildRenderObjectWidget> IntoWidget<MultiChildRenderObjectKind> for W
1226where
1227    W::RenderObject: ContainerRenderObjectMixin,
1228{
1229    #[cfg_attr(debug_assertions, track_caller)]
1230    fn into_widget(self) -> WidgetRef {
1231        if cfg!(debug_assertions) {
1232            RenderObjectWidget::debug_check_constructor(&self);
1233        }
1234        Rc::new(MultiChildRenderObject(self, CreationLocation::of_caller()))
1235    }
1236}
1237
1238impl<W: MultiChildRenderObjectWidget> Widget for MultiChildRenderObject<W>
1239where
1240    W::RenderObject: ContainerRenderObjectMixin,
1241{
1242    fn key(&self) -> Option<&KeyRef> {
1243        self.0.key()
1244    }
1245
1246    fn creation_location(&self) -> Option<&'static Location<'static>> {
1247        self.1.location()
1248    }
1249
1250    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1251        self.0.debug_fill_properties(app, properties);
1252    }
1253
1254    fn to_string_short(&self) -> String {
1255        self.0.to_string_short()
1256    }
1257
1258    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
1259        MultiChildRenderObjectWidget::create_element(&self.0, app, this)
1260    }
1261
1262    fn as_any(&self) -> &dyn Any {
1263        &self.0
1264    }
1265
1266    fn widget_type(&self) -> TypeId {
1267        TypeId::of::<W>()
1268    }
1269
1270    fn type_name(&self) -> &'static str {
1271        short_type_name::<W>()
1272    }
1273
1274    fn kind(&self) -> WidgetKind {
1275        WidgetKind::Other
1276    }
1277
1278    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
1279        Some(self)
1280    }
1281
1282    fn as_multi_child_render_object(&self) -> Option<&dyn AnyMultiChildRenderObjectWidget> {
1283        Some(self)
1284    }
1285}
1286
1287impl<W: MultiChildRenderObjectWidget> Debug for MultiChildRenderObject<W>
1288where
1289    W::RenderObject: ContainerRenderObjectMixin,
1290{
1291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1292        self.0.fmt(f)
1293    }
1294}
1295
1296/// A [`RenderObjectWidget`] of any type, as the framework's render object elements reach it:
1297/// its render object calls with the render object erased, so those elements are not copied per
1298/// widget type.
1299pub trait AnyRenderObjectWidget {
1300    /// See [`RenderObjectWidget::create_render_object`].
1301    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject;
1302
1303    /// [`RenderObjectWidget::update_render_object`] on the render object this widget's type
1304    /// creates.
1305    fn update_render_object(
1306        &self,
1307        app: &mut App,
1308        context: BuildContext,
1309        render_object: AnyRenderObject,
1310    );
1311
1312    /// [`RenderObjectWidget::did_unmount_render_object`] on the render object this widget's type
1313    /// creates.
1314    fn did_unmount_render_object(&self, app: &mut App, render_object: AnyRenderObject);
1315
1316    /// See [`RenderObjectWidget::debug_visit_onstage_children`].
1317    fn debug_visit_onstage_children(
1318        &self,
1319        app: &App,
1320        children: &[AnyElement],
1321        visitor: &mut dyn FnMut(AnyElement),
1322    );
1323}
1324
1325/// A [`SingleChildRenderObjectWidget`] of any type: its child, and its render object's child
1326/// slot (`RenderObjectWithChildMixin`) with the render objects erased.
1327pub trait AnySingleChildRenderObjectWidget: AnyRenderObjectWidget {
1328    /// See [`SingleChildRenderObjectWidget::child`].
1329    fn child(&self) -> Option<&WidgetRef>;
1330
1331    /// The child of `render_object`, which this widget's type created.
1332    fn render_object_child(
1333        &self,
1334        app: &App,
1335        render_object: AnyRenderObject,
1336    ) -> Option<AnyRenderObject>;
1337
1338    /// Sets the child of `render_object`, which this widget's type created.
1339    fn set_render_object_child(
1340        &self,
1341        app: &mut App,
1342        render_object: AnyRenderObject,
1343        child: Option<AnyRenderObject>,
1344    );
1345}
1346
1347/// A [`MultiChildRenderObjectWidget`] of any type: its children, and its render object's child
1348/// list (`ContainerRenderObjectMixin`) with the render objects erased.
1349pub trait AnyMultiChildRenderObjectWidget: AnyRenderObjectWidget {
1350    /// See [`MultiChildRenderObjectWidget::children`].
1351    fn children(&self) -> &[WidgetRef];
1352
1353    /// Inserts `child` into `render_object`'s child list after `after`, or first.
1354    fn insert_render_object_child(
1355        &self,
1356        app: &mut App,
1357        render_object: AnyRenderObject,
1358        child: AnyRenderObject,
1359        after: Option<AnyRenderObject>,
1360    );
1361
1362    /// Moves `child` in `render_object`'s child list to after `after`, or first.
1363    fn move_render_object_child(
1364        &self,
1365        app: &mut App,
1366        render_object: AnyRenderObject,
1367        child: AnyRenderObject,
1368        after: Option<AnyRenderObject>,
1369    );
1370
1371    /// Removes `child` from `render_object`'s child list.
1372    fn remove_render_object_child(
1373        &self,
1374        app: &mut App,
1375        render_object: AnyRenderObject,
1376        child: AnyRenderObject,
1377    );
1378}
1379
1380/// The [`AnyRenderObjectWidget`] calls of an erased render object widget `$wrapper<W>`.
1381macro_rules! any_render_object_widget_calls {
1382    () => {
1383        fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1384            self.0.create_render_object(app, context)
1385        }
1386
1387        fn update_render_object(
1388            &self,
1389            app: &mut App,
1390            context: BuildContext,
1391            render_object: AnyRenderObject,
1392        ) {
1393            let render_object = typed_render_object::<W>(app, render_object);
1394            self.0.update_render_object(app, context, render_object);
1395        }
1396
1397        fn did_unmount_render_object(&self, app: &mut App, render_object: AnyRenderObject) {
1398            let render_object = typed_render_object::<W>(app, render_object);
1399            self.0.did_unmount_render_object(app, render_object);
1400        }
1401
1402        fn debug_visit_onstage_children(
1403            &self,
1404            app: &App,
1405            children: &[AnyElement],
1406            visitor: &mut dyn FnMut(AnyElement),
1407        ) {
1408            self.0.debug_visit_onstage_children(app, children, visitor);
1409        }
1410    };
1411}
1412
1413/// `render_object` as the render object `W` creates.
1414fn typed_render_object<W: RenderObjectWidget>(
1415    app: &App,
1416    render_object: AnyRenderObject,
1417) -> RenderHandle<W::RenderObject> {
1418    render_object
1419        .downcast(app)
1420        .expect("the render object this widget created")
1421}
1422
1423impl<W: LeafRenderObjectWidget> AnyRenderObjectWidget for LeafRenderObject<W> {
1424    any_render_object_widget_calls!();
1425}
1426
1427impl<W: SingleChildRenderObjectWidget> AnyRenderObjectWidget for SingleChildRenderObject<W>
1428where
1429    W::RenderObject: RenderObjectWithChildMixin,
1430{
1431    any_render_object_widget_calls!();
1432}
1433
1434impl<W: SingleChildRenderObjectWidget> AnySingleChildRenderObjectWidget
1435    for SingleChildRenderObject<W>
1436where
1437    W::RenderObject: RenderObjectWithChildMixin,
1438{
1439    fn child(&self) -> Option<&WidgetRef> {
1440        self.0.child()
1441    }
1442
1443    fn render_object_child(
1444        &self,
1445        app: &App,
1446        render_object: AnyRenderObject,
1447    ) -> Option<AnyRenderObject> {
1448        typed_render_object::<W>(app, render_object)
1449            .child(app)
1450            .map(ErasedRenderObject::as_object)
1451    }
1452
1453    fn set_render_object_child(
1454        &self,
1455        app: &mut App,
1456        render_object: AnyRenderObject,
1457        child: Option<AnyRenderObject>,
1458    ) {
1459        typed_render_object::<W>(app, render_object)
1460            .set_child(app, child.map(ErasedRenderObject::from_object));
1461    }
1462}
1463
1464impl<W: MultiChildRenderObjectWidget> AnyRenderObjectWidget for MultiChildRenderObject<W>
1465where
1466    W::RenderObject: ContainerRenderObjectMixin,
1467{
1468    any_render_object_widget_calls!();
1469}
1470
1471impl<W: MultiChildRenderObjectWidget> AnyMultiChildRenderObjectWidget for MultiChildRenderObject<W>
1472where
1473    W::RenderObject: ContainerRenderObjectMixin,
1474{
1475    fn children(&self) -> &[WidgetRef] {
1476        self.0.children()
1477    }
1478
1479    fn insert_render_object_child(
1480        &self,
1481        app: &mut App,
1482        render_object: AnyRenderObject,
1483        child: AnyRenderObject,
1484        after: Option<AnyRenderObject>,
1485    ) {
1486        typed_render_object::<W>(app, render_object).insert(
1487            app,
1488            ErasedRenderObject::from_object(child),
1489            after.map(ErasedRenderObject::from_object),
1490        );
1491    }
1492
1493    fn move_render_object_child(
1494        &self,
1495        app: &mut App,
1496        render_object: AnyRenderObject,
1497        child: AnyRenderObject,
1498        after: Option<AnyRenderObject>,
1499    ) {
1500        typed_render_object::<W>(app, render_object).move_child(
1501            app,
1502            ErasedRenderObject::from_object(child),
1503            after.map(ErasedRenderObject::from_object),
1504        );
1505    }
1506
1507    fn remove_render_object_child(
1508        &self,
1509        app: &mut App,
1510        render_object: AnyRenderObject,
1511        child: AnyRenderObject,
1512    ) {
1513        typed_render_object::<W>(app, render_object)
1514            .remove(app, ErasedRenderObject::from_object(child));
1515    }
1516}
1517
1518// ---------------------------------------------------------------------------------------------
1519// GlobalKey
1520
1521/// A key that is unique across the entire app.
1522///
1523/// Global keys uniquely identify elements. Global keys provide access to other objects that
1524/// are associated with those elements, such as `BuildContext`. For [`StatefulWidget`]s,
1525/// global keys also provide access to [`State`].
1526///
1527/// Widgets that have global keys reparent their subtrees when they are moved from one
1528/// location in the tree to another location in the tree. In order to reparent its subtree, a
1529/// widget must arrive at its new location in the tree in the same animation frame in which
1530/// it was removed from its old location in the tree.
1531///
1532/// Reparenting an `Element` using a global key is relatively expensive, as this operation
1533/// will trigger a call to `State::deactivate` on the associated [`State`] and all of its
1534/// descendants; then force all widgets that depends on an `InheritedWidget` to rebuild.
1535///
1536/// A global key is a key the element tree registers: it compares and hashes as the [`Key`] it
1537/// wraps, and the registry maps it to its element as Dart's `Map<GlobalKey, Element>` does.
1538/// [`new`](Self::new) and [`labeled`](Self::labeled) compare by themselves (Dart's
1539/// `LabeledGlobalKey`), [`object`](Self::object) by an object (Dart's `GlobalObjectKey`), and
1540/// [`wrapping`](Self::wrapping) as the key it is given (Dart's subclasses that override `==`).
1541/// Cloning shares the key. Dart's type argument names the state; here
1542/// [`current_state`](Self::current_state) does.
1543#[derive(Clone)]
1544pub struct GlobalKey {
1545    key: Rc<dyn Key>,
1546}
1547
1548impl GlobalKey {
1549    /// Creates a global key that is equal only to itself and its clones; Dart's factory
1550    /// `GlobalKey()`, a `LabeledGlobalKey` without a label.
1551    #[expect(
1552        clippy::new_without_default,
1553        reason = "each call creates a distinct key; Default would suggest a neutral value"
1554    )]
1555    pub fn new() -> GlobalKey {
1556        GlobalKey::wrapping(Rc::new(LabeledGlobalKeyValue::new(None)))
1557    }
1558
1559    /// Creates a global key with a debugging label (Dart's `LabeledGlobalKey`).
1560    ///
1561    /// The label does not affect the key's identity.
1562    pub fn labeled(debug_label: impl Into<String>) -> GlobalKey {
1563        GlobalKey::wrapping(Rc::new(LabeledGlobalKeyValue::new(Some(
1564            debug_label.into(),
1565        ))))
1566    }
1567
1568    /// Creates a global key that uses the identity of `value` for its `==` (Dart's
1569    /// `GlobalObjectKey`).
1570    ///
1571    /// An object's identity is its [`Handle`](waft_foundation::Handle): Dart's
1572    /// `GlobalObjectKey(this)` in a `State` is `GlobalKey::object(self.id())`.
1573    pub fn object(value: impl Into<HandleId>) -> GlobalKey {
1574        GlobalKey::wrapping(Rc::new(GlobalObjectKeyValue {
1575            value: value.into(),
1576        }))
1577    }
1578
1579    /// Creates a global key that compares and hashes as `key`: Dart's `GlobalKey` subclasses
1580    /// that override `==` and `hashCode`, such as `_ReorderableItemGlobalKey`.
1581    ///
1582    /// Two global keys wrapping equal keys name the same element.
1583    pub fn wrapping(key: Rc<dyn Key>) -> GlobalKey {
1584        GlobalKey { key }
1585    }
1586
1587    /// The key this global key compares and hashes as.
1588    pub fn key(&self) -> &dyn Key {
1589        &*self.key
1590    }
1591
1592    /// The build context in which the widget with this key builds.
1593    ///
1594    /// The current context is `None` if there is no widget in the tree that matches this
1595    /// global key.
1596    pub fn current_context(&self, app: &App) -> Option<BuildContext> {
1597        self.current_element(app)
1598    }
1599
1600    /// The widget in the tree that currently has this global key.
1601    ///
1602    /// The current widget is `None` if there is no widget in the tree that matches this
1603    /// global key.
1604    pub fn current_widget(&self, app: &App) -> Option<WidgetRef> {
1605        let element = self.current_element(app)?;
1606        Some(element.widget(app).clone())
1607    }
1608
1609    /// The [`State`] for the widget in the tree that currently has this global key.
1610    ///
1611    /// The current state is `None` if (1) there is no widget in the tree that matches this
1612    /// global key, (2) that widget is not a [`StatefulWidget`], or the associated [`State`]
1613    /// object is not an `S`.
1614    pub fn current_state<S: State>(&self, app: &App) -> Option<waft_foundation::Handle<S>> {
1615        let element = self.current_element(app)?;
1616        element.state_handle::<S>(app)
1617    }
1618
1619    fn current_element(&self, app: &App) -> Option<AnyElement> {
1620        let owner = crate::binding::current_build_owner(app)?;
1621        owner.global_key_element(app, self)
1622    }
1623}
1624
1625impl PartialEq for GlobalKey {
1626    fn eq(&self, other: &GlobalKey) -> bool {
1627        *self.key == *other.key
1628    }
1629}
1630
1631impl Eq for GlobalKey {}
1632
1633impl Hash for GlobalKey {
1634    fn hash<H: Hasher>(&self, state: &mut H) {
1635        self.key.hash(state);
1636    }
1637}
1638
1639impl Debug for GlobalKey {
1640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1641        self.key.fmt(f)
1642    }
1643}
1644
1645/// What a [`GlobalKey::new`] or [`GlobalKey::labeled`] key compares by: itself (Dart's
1646/// `LabeledGlobalKey`).
1647struct LabeledGlobalKeyValue {
1648    unique: waft_foundation::UniqueKey,
1649    debug_label: Option<String>,
1650}
1651
1652impl LabeledGlobalKeyValue {
1653    fn new(debug_label: Option<String>) -> LabeledGlobalKeyValue {
1654        LabeledGlobalKeyValue {
1655            unique: waft_foundation::UniqueKey::new(),
1656            debug_label,
1657        }
1658    }
1659}
1660
1661impl Key for LabeledGlobalKeyValue {
1662    fn eq_key(&self, other: &dyn Key) -> bool {
1663        (other as &dyn Any)
1664            .downcast_ref::<LabeledGlobalKeyValue>()
1665            .is_some_and(|other| other.unique == self.unique)
1666    }
1667
1668    fn hash_key(&self, mut state: &mut dyn Hasher) {
1669        TypeId::of::<LabeledGlobalKeyValue>().hash(&mut state);
1670        self.unique.hash(&mut state);
1671    }
1672}
1673
1674impl Debug for LabeledGlobalKeyValue {
1675    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1676        let id = std::ptr::from_ref(self) as usize & 0xF_FFFF;
1677        match &self.debug_label {
1678            Some(label) => write!(f, "[GlobalKey#{id:05x} {label}]"),
1679            None => write!(f, "[GlobalKey#{id:05x}]"),
1680        }
1681    }
1682}
1683
1684/// What a [`GlobalKey::object`] key compares by: an object's identity (Dart's
1685/// `GlobalObjectKey`).
1686struct GlobalObjectKeyValue {
1687    value: HandleId,
1688}
1689
1690impl Key for GlobalObjectKeyValue {
1691    fn eq_key(&self, other: &dyn Key) -> bool {
1692        (other as &dyn Any)
1693            .downcast_ref::<GlobalObjectKeyValue>()
1694            .is_some_and(|other| other.value == self.value)
1695    }
1696
1697    fn hash_key(&self, mut state: &mut dyn Hasher) {
1698        TypeId::of::<GlobalObjectKeyValue>().hash(&mut state);
1699        self.value.hash(&mut state);
1700    }
1701}
1702
1703impl Debug for GlobalObjectKeyValue {
1704    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705        write!(f, "[GlobalObjectKey {:?}]", self.value)
1706    }
1707}
1708
1709/// A key that uses the identity of an object as its value (Dart's `ObjectKey`).
1710///
1711/// Used to tie the identity of a widget to the identity of an object used to generate that
1712/// widget. An object's identity is its [`Handle`](waft_foundation::Handle): pass
1713/// `Some(handle.id())`.
1714///
1715/// See also:
1716///
1717///  * [`waft_foundation::Key`], the base trait for all keys.
1718///  * The discussion at `Widget.key` for more information about how widgets use keys.
1719#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1720pub struct ObjectKey {
1721    /// The object whose identity is used by this key's `==`. The key names it without keeping
1722    /// it.
1723    pub value: Option<HandleId>,
1724}
1725
1726impl ObjectKey {
1727    /// Creates a key that uses the identity of `value` for its `==`.
1728    pub const fn new(value: Option<HandleId>) -> ObjectKey {
1729        ObjectKey { value }
1730    }
1731}
1732
1733impl Key for ObjectKey {
1734    fn eq_key(&self, other: &dyn Key) -> bool {
1735        (other as &dyn Any)
1736            .downcast_ref::<ObjectKey>()
1737            .is_some_and(|other| other.value == self.value)
1738    }
1739
1740    fn hash_key(&self, mut state: &mut dyn Hasher) {
1741        TypeId::of::<ObjectKey>().hash(&mut state);
1742        self.value.hash(&mut state);
1743    }
1744}
1745
1746impl waft_foundation::LocalKey for ObjectKey {}
1747
1748impl Debug for ObjectKey {
1749    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1750        match self.value {
1751            Some(value) => write!(f, "[{value:?}]"),
1752            None => f.write_str("[null]"),
1753        }
1754    }
1755}