Skip to main content

waft_widgets/framework/
state.rs

1//! `State`: the logic and internal state for a [`StatefulWidget`].
2//!
3//! A state object is one struct in the arena, reached through `Handle<Self>`; the framework
4//! bookkeeping (Dart's `_element`, `_widget`, and the debug lifecycle) is the [`StateData`]
5//! bag the struct holds under the field `state`.
6
7use std::any::TypeId;
8use std::marker::PhantomData;
9
10use waft_foundation::{
11    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticableNode, DiagnosticsNode,
12    DiagnosticsTreeStyle, EnumProperty, Handle, HandleId, ObjectFlagProperty, bare_type_name,
13    describe_identity,
14};
15
16use super::element::{BuildContext, Element};
17use super::elements::StatefulElement;
18use super::widget::{StatefulWidget, WidgetRef, downcast_widget};
19
20/// Tracks the lifecycle of [`State`] objects when asserts are enabled.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum StateLifecycle {
23    /// The [`State`] object has been created. [`State::init_state`] is called at this time.
24    Created,
25    /// The [`State::init_state`] method has been called but the [`State`] object is not yet
26    /// ready to build. [`State::did_change_dependencies`] is called at this time.
27    Initialized,
28    /// The [`State`] object is ready to build and [`State::dispose`] has not yet been called.
29    Ready,
30    /// The [`State::dispose`] method has been called and the [`State`] object is no longer
31    /// able to build.
32    Defunct,
33}
34
35/// The framework's part of a [`State`]: the element it belongs to and its lifecycle.
36pub struct StateData<W: StatefulWidget> {
37    widget: Option<WidgetRef>,
38    element: Option<Handle<StatefulElement>>,
39    debug_lifecycle_state: StateLifecycle,
40    /// The state's widget type. The bag holds nothing of it since its element stopped being
41    /// generic; it stays so a state's `state: StateData<MyWidget>` field and
42    /// [`State::state_data`] keep their shape.
43    widget_type: PhantomData<fn() -> W>,
44}
45
46impl<W: StatefulWidget> StateData<W> {
47    /// A state that is not yet attached to an element.
48    pub fn new() -> StateData<W> {
49        StateData {
50            widget: None,
51            element: None,
52            debug_lifecycle_state: StateLifecycle::Created,
53            widget_type: PhantomData,
54        }
55    }
56
57    /// Dart's `State._widget`, set by the element before `init_state` and on every update.
58    pub(crate) fn set_widget(&mut self, widget: WidgetRef) {
59        self.widget = Some(widget);
60    }
61
62    pub(crate) fn element(&self) -> Option<Handle<StatefulElement>> {
63        self.element
64    }
65
66    pub(crate) fn set_element(&mut self, element: Option<Handle<StatefulElement>>) {
67        self.element = element;
68    }
69
70    pub(crate) fn debug_lifecycle_state(&self) -> StateLifecycle {
71        self.debug_lifecycle_state
72    }
73
74    pub(crate) fn set_debug_lifecycle_state(&mut self, state: StateLifecycle) {
75        self.debug_lifecycle_state = state;
76    }
77}
78
79impl<W: StatefulWidget> Default for StateData<W> {
80    fn default() -> StateData<W> {
81        StateData::new()
82    }
83}
84
85/// A [`State`] of any type, as the one [`StatefulElement`] holds it: its handle and the hooks
86/// the element calls, so the element is not copied per state type. Opaque outside the framework.
87#[derive(Clone, Copy)]
88pub struct AnyState {
89    id: HandleId,
90    vtable: &'static StateVTable,
91}
92
93/// The hooks of one [`State`] type that its element calls.
94struct StateVTable {
95    type_id: TypeId,
96    type_name: fn() -> &'static str,
97    debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
98    build: fn(&mut App, HandleId, BuildContext) -> WidgetRef,
99    init_state: fn(&mut App, HandleId),
100    did_change_dependencies: fn(&mut App, HandleId),
101    did_update_widget: fn(&mut App, HandleId, &WidgetRef),
102    activate: fn(&mut App, HandleId),
103    deactivate: fn(&mut App, HandleId),
104    dispose: fn(&mut App, HandleId),
105    set_widget: fn(&mut App, HandleId, WidgetRef),
106    element: fn(&App, HandleId) -> Option<Handle<StatefulElement>>,
107    set_element: fn(&mut App, HandleId, Option<Handle<StatefulElement>>),
108    debug_lifecycle_state: fn(&App, HandleId) -> StateLifecycle,
109    set_debug_lifecycle_state: fn(&mut App, HandleId, StateLifecycle),
110}
111
112impl StateVTable {
113    const fn of<S: State>() -> StateVTable {
114        fn typed<S: State>(id: HandleId) -> Handle<S> {
115            Handle::from_id(id)
116        }
117        StateVTable {
118            type_id: TypeId::of::<S>(),
119            type_name: std::any::type_name::<S>,
120            debug_fill_properties: |app, id, properties| {
121                typed::<S>(id).debug_fill_properties(app, properties)
122            },
123            build: |app, id, context| typed::<S>(id).build(app, context),
124            init_state: |app, id| typed::<S>(id).init_state(app),
125            did_change_dependencies: |app, id| typed::<S>(id).did_change_dependencies(app),
126            did_update_widget: |app, id, old_widget| {
127                let old_widget = downcast_widget::<S::Widget>(&**old_widget)
128                    .expect("a StatefulElement holds its StatefulWidget");
129                typed::<S>(id).did_update_widget(app, old_widget);
130            },
131            activate: |app, id| typed::<S>(id).activate(app),
132            deactivate: |app, id| typed::<S>(id).deactivate(app),
133            dispose: |app, id| typed::<S>(id).dispose(app),
134            set_widget: |app, id, widget| typed::<S>(id).state_data_mut(app).set_widget(widget),
135            element: |app, id| typed::<S>(id).state_data(app).element(),
136            set_element: |app, id, element| typed::<S>(id).state_data_mut(app).set_element(element),
137            debug_lifecycle_state: |app, id| typed::<S>(id).state_data(app).debug_lifecycle_state(),
138            set_debug_lifecycle_state: |app, id, lifecycle| {
139                typed::<S>(id)
140                    .state_data_mut(app)
141                    .set_debug_lifecycle_state(lifecycle);
142            },
143        }
144    }
145}
146
147impl AnyState {
148    pub(crate) fn of<S: State>(state: Handle<S>) -> AnyState {
149        AnyState {
150            id: state.id(),
151            vtable: const { &StateVTable::of::<S>() },
152        }
153    }
154
155    pub(crate) fn id(self) -> HandleId {
156        self.id
157    }
158
159    pub(crate) fn type_id(self) -> TypeId {
160        self.vtable.type_id
161    }
162
163    pub(crate) fn build(self, app: &mut App, context: BuildContext) -> WidgetRef {
164        (self.vtable.build)(app, self.id, context)
165    }
166
167    pub(crate) fn init_state(self, app: &mut App) {
168        (self.vtable.init_state)(app, self.id);
169    }
170
171    pub(crate) fn did_change_dependencies(self, app: &mut App) {
172        (self.vtable.did_change_dependencies)(app, self.id);
173    }
174
175    pub(crate) fn did_update_widget(self, app: &mut App, old_widget: &WidgetRef) {
176        (self.vtable.did_update_widget)(app, self.id, old_widget);
177    }
178
179    pub(crate) fn activate(self, app: &mut App) {
180        (self.vtable.activate)(app, self.id);
181    }
182
183    pub(crate) fn deactivate(self, app: &mut App) {
184        (self.vtable.deactivate)(app, self.id);
185    }
186
187    pub(crate) fn dispose(self, app: &mut App) {
188        (self.vtable.dispose)(app, self.id);
189    }
190
191    pub(crate) fn set_widget(self, app: &mut App, widget: WidgetRef) {
192        (self.vtable.set_widget)(app, self.id, widget);
193    }
194
195    pub(crate) fn element(self, app: &App) -> Option<Handle<StatefulElement>> {
196        (self.vtable.element)(app, self.id)
197    }
198
199    pub(crate) fn set_element(self, app: &mut App, element: Option<Handle<StatefulElement>>) {
200        (self.vtable.set_element)(app, self.id, element);
201    }
202
203    /// Dart's `State.toStringShort`, from `Diagnosticable`: the state's type and identity.
204    pub fn to_string_short(self) -> String {
205        describe_identity(
206            bare_type_name((self.vtable.type_name)()),
207            self.id.identity_hash(),
208        )
209    }
210
211    /// Dart's `State.toString`: the short description, then the properties at the info level
212    /// or above on the same line, as `ScrollableState#1a2b3(position: …)`.
213    pub fn to_string(self, app: &App) -> String {
214        let mut properties = DiagnosticPropertiesBuilder::new();
215        self.fill_base_properties(app, &mut properties);
216        (self.vtable.debug_fill_properties)(app, self.id, &mut properties);
217        DiagnosticableNode::from_parts(None, self.to_string_short(), properties)
218            .with_style(DiagnosticsTreeStyle::SingleLine)
219            .to_string_with(None, DiagnosticLevel::Info)
220    }
221
222    /// The properties `State.debugFillProperties` adds before a state's own: the lifecycle
223    /// unless it is ready, and whether the state has its widget and element.
224    fn fill_base_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
225        properties.add(
226            EnumProperty::new("lifecycle state", self.debug_lifecycle_state(app))
227                .default_value(Some(StateLifecycle::Ready)),
228        );
229        properties.add(
230            ObjectFlagProperty::<String>::new("_widget", self.widget_description(app))
231                .if_null("no widget"),
232        );
233        properties.add(
234            ObjectFlagProperty::<String>::new(
235                "_element",
236                self.element(app)
237                    .map(|element| element.as_element().to_string_short(app)),
238            )
239            .if_null("not mounted"),
240        );
241    }
242
243    /// The state's widget as its element names it, while the state is attached to one.
244    fn widget_description(self, app: &App) -> Option<String> {
245        let element = self.element(app)?.as_element();
246        element
247            .mounted(app)
248            .then(|| element.widget(app).to_string_short())
249    }
250
251    pub(crate) fn debug_lifecycle_state(self, app: &App) -> StateLifecycle {
252        (self.vtable.debug_lifecycle_state)(app, self.id)
253    }
254
255    pub(crate) fn set_debug_lifecycle_state(self, app: &mut App, lifecycle: StateLifecycle) {
256        (self.vtable.set_debug_lifecycle_state)(app, self.id, lifecycle);
257    }
258}
259
260/// The accessors [`State`] asks for, for a struct whose bag is the field `state`.
261#[macro_export]
262macro_rules! state_accessors {
263    () => {
264        fn state_data(
265            self: $crate::__private::foundation::Handle<Self>,
266            app: &$crate::__private::foundation::App,
267        ) -> &$crate::StateData<Self::Widget> {
268            &app.get(self).state
269        }
270
271        fn state_data_mut(
272            self: $crate::__private::foundation::Handle<Self>,
273            app: &mut $crate::__private::foundation::App,
274        ) -> &mut $crate::StateData<Self::Widget> {
275            &mut app.get_mut(self).state
276        }
277    };
278}
279
280/// The logic and internal state for a [`StatefulWidget`].
281///
282/// State is information that (1) can be read synchronously when the widget is built and (2)
283/// might change during the lifetime of the widget. It is the responsibility of the widget
284/// implementer to ensure that the [`State`] is promptly notified when such state changes,
285/// using [`set_state`](Self::set_state).
286///
287/// [`State`] objects are created by the framework by calling the
288/// [`StatefulWidget::create_state`] method when inflating a [`StatefulWidget`] to insert it
289/// into the tree. Because a given [`StatefulWidget`] instance can be inflated multiple times
290/// (e.g., the widget is incorporated into the tree in multiple places at once), there might
291/// be more than one [`State`] object associated with a given [`StatefulWidget`] instance.
292/// Similarly, if a [`StatefulWidget`] is removed from the tree and later inserted in to the
293/// tree again, the framework will call [`StatefulWidget::create_state`] again to create a
294/// fresh [`State`] object, simplifying the lifecycle of [`State`] objects.
295///
296/// Methods take `self: Handle<Self>`: the state lives in the arena, and [`widget`](Self::widget)
297/// / [`context`](Self::context) read the element it is attached to.
298///
299/// # When a widget needs one
300///
301/// A [`State`] is for what a widget *owns* as a Flutter object across its builds: a
302/// [`TextEditingController`](crate::TextEditingController), a [`FocusNode`](crate::FocusNode), an
303/// [`AnimationController`](crate::AnimationController) it drives. The app's own data is not
304/// state: it lives in an [`Entity`](waft_foundation::Entity), which a
305/// [`StatelessWidget`](crate::StatelessWidget) reads in `build` and is rebuilt by when it
306/// notifies. A stateful widget whose only job is to hold a counter or a fetched list is app data
307/// in the wrong place.
308pub trait State: Sized + 'static {
309    /// The widget this state belongs to; Dart's `State<T>` type argument.
310    type Widget: StatefulWidget<State = Self>;
311
312    /// The framework's bookkeeping, held under the field `state`
313    /// ([`state_accessors!`](crate::state_accessors)).
314    fn state_data(self: Handle<Self>, app: &App) -> &StateData<Self::Widget>;
315
316    /// See [`state_data`](Self::state_data).
317    fn state_data_mut(self: Handle<Self>, app: &mut App) -> &mut StateData<Self::Widget>;
318
319    /// The current configuration.
320    ///
321    /// A [`State`] object's configuration is the corresponding [`StatefulWidget`] instance.
322    /// This property is initialized by the framework before calling
323    /// [`init_state`](Self::init_state). If the parent updates this location in the tree to a
324    /// new widget with the same `runtimeType` and [`Widget::key`](super::Widget::key) as the
325    /// current configuration, the framework will update this property to refer to the new
326    /// widget and then call [`did_update_widget`](Self::did_update_widget), passing the old
327    /// configuration as an argument.
328    fn widget(self: Handle<Self>, app: &App) -> &Self::Widget {
329        let widget = self
330            .state_data(app)
331            .widget
332            .as_ref()
333            .expect("the framework sets the widget before init_state");
334        downcast_widget::<Self::Widget>(&**widget)
335            .expect("a StatefulElement holds its StatefulWidget")
336    }
337
338    /// The location in the tree where this widget builds.
339    ///
340    /// The framework associates [`State`] objects with a [`BuildContext`] after creating them
341    /// with [`StatefulWidget::create_state`] and before calling
342    /// [`init_state`](Self::init_state). The association is permanent: the [`State`] object
343    /// will never change its [`BuildContext`]. However, the [`BuildContext`] itself can be
344    /// moved around the tree.
345    ///
346    /// After calling [`dispose`](Self::dispose), the framework severs the [`State`] object's
347    /// connection with the [`BuildContext`].
348    fn context(self: Handle<Self>, app: &App) -> BuildContext {
349        use super::element::Element;
350        self.state_data(app)
351            .element()
352            .expect(
353                "This widget has been unmounted, so the State no longer has a context (and \
354                 should be considered defunct). Consider canceling any active work during \
355                 \"dispose\" or using the \"mounted\" getter to determine if the State is still \
356                 active.",
357            )
358            .as_element()
359    }
360
361    /// Whether this [`State`] object is currently in a tree.
362    ///
363    /// After creating a [`State`] object and before calling [`init_state`](Self::init_state),
364    /// the framework "mounts" the [`State`] object by associating it with a [`BuildContext`].
365    /// The [`State`] object remains mounted until the framework calls
366    /// [`dispose`](Self::dispose), after which time the framework will never ask the
367    /// [`State`] object to [`build`](Self::build) again.
368    ///
369    /// It is an error to call [`set_state`](Self::set_state) unless
370    /// [`mounted`](Self::mounted) is true.
371    fn mounted(self: Handle<Self>, app: &App) -> bool {
372        app.contains(self) && self.state_data(app).element().is_some()
373    }
374
375    /// Called when this object is inserted into the tree.
376    ///
377    /// The framework will call this method exactly once for each [`State`] object it creates.
378    ///
379    /// Override this method to perform initialization that depends on the location at which
380    /// this object was inserted into the tree (i.e., [`context`](Self::context)) or on the
381    /// widget used to configure this object (i.e., [`widget`](Self::widget)).
382    ///
383    /// You should not use `BuildContext::depend_on_inherited_widget_of_exact_type` from this
384    /// method. However, [`did_change_dependencies`](Self::did_change_dependencies) will be
385    /// called immediately following this method, and
386    /// `BuildContext::depend_on_inherited_widget_of_exact_type` can be used there.
387    fn init_state(self: Handle<Self>, app: &mut App) {
388        let _ = (self, app);
389    }
390
391    /// Called whenever the widget configuration changes.
392    ///
393    /// If the parent widget rebuilds and requests that this location in the tree update to
394    /// display a new widget with the same `runtimeType` and [`Widget::key`](super::Widget::key),
395    /// the framework will update the [`widget`](Self::widget) property of this [`State`]
396    /// object to refer to the new widget and then call this method with the previous widget
397    /// as an argument.
398    ///
399    /// Override this method to respond when the [`widget`](Self::widget) changes (e.g., to
400    /// start implicit animations).
401    ///
402    /// The framework always calls [`build`](Self::build) after calling
403    /// [`did_update_widget`](Self::did_update_widget), which means any calls to
404    /// [`set_state`](Self::set_state) in [`did_update_widget`](Self::did_update_widget) are
405    /// redundant.
406    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Self::Widget) {
407        let _ = (self, app, old_widget);
408    }
409
410    /// Notify the framework that the internal state of this object has changed.
411    ///
412    /// Whenever you change the internal state of a [`State`] object, make the change in a
413    /// function that you pass to [`set_state`](Self::set_state):
414    ///
415    /// ```text
416    /// self.set_state(app, |state| { state.my_state = new_value; });
417    /// ```
418    ///
419    /// The provided callback is immediately called synchronously. It must not return a
420    /// future (the callback cannot be `async`), since then it would be unclear when the
421    /// state was actually being set.
422    ///
423    /// Calling [`set_state`](Self::set_state) notifies the framework that the internal state
424    /// of this object has changed in a way that might impact the user interface in this
425    /// subtree, which causes the framework to schedule a [`build`](Self::build) for this
426    /// [`State`] object.
427    ///
428    /// If you just change the state directly without calling
429    /// [`set_state`](Self::set_state), the framework might not schedule a
430    /// [`build`](Self::build) and the user interface for this subtree might not be updated
431    /// to reflect the new state.
432    fn set_state(self: Handle<Self>, app: &mut App, f: impl FnOnce(&mut Self)) {
433        use super::element::Element;
434        if cfg!(debug_assertions) {
435            let lifecycle = self.state_data(app).debug_lifecycle_state();
436            assert!(
437                lifecycle != StateLifecycle::Defunct,
438                "setState() called after dispose(): this error happens if you call setState() \
439                 on a State object for a widget that no longer appears in the widget tree \
440                 (e.g., whose parent widget no longer includes the widget in its build)."
441            );
442            assert!(
443                !(lifecycle == StateLifecycle::Created && !self.mounted(app)),
444                "setState() called in constructor: this happens when you call setState() on a \
445                 State object for a widget that hasn't been inserted into the widget tree yet."
446            );
447        }
448        f(app.get_mut(self));
449        let element = self
450            .state_data(app)
451            .element()
452            .expect("set_state needs a mounted state");
453        element.as_element().mark_needs_build(app);
454    }
455
456    /// Called when this object is removed from the tree.
457    ///
458    /// The framework calls this method whenever it removes this [`State`] object from the
459    /// tree. In some cases, the framework will reinsert the [`State`] object into another
460    /// part of the tree (e.g., if the subtree containing this [`State`] object is grafted
461    /// from one location in the tree to another due to the use of a `GlobalKey`). If that
462    /// happens, the framework will call [`activate`](Self::activate) to give the [`State`]
463    /// object a chance to reacquire any resources that it released in
464    /// [`deactivate`](Self::deactivate). It will then also call [`build`](Self::build) to give
465    /// the [`State`] object a chance to adapt to its new location in the tree. If the
466    /// framework does reinsert this subtree, it will do so before the end of the animation
467    /// frame in which the subtree was removed from the tree. For this reason, [`State`]
468    /// objects can defer releasing most resources until the framework calls their
469    /// [`dispose`](Self::dispose) method.
470    fn deactivate(self: Handle<Self>, app: &mut App) {
471        let _ = (self, app);
472    }
473
474    /// Called when this object is reinserted into the tree after having been removed via
475    /// [`deactivate`](Self::deactivate).
476    ///
477    /// In most cases, after a [`State`] object has been deactivated, it is _not_ reinserted
478    /// into the tree, and its [`dispose`](Self::dispose) method will be called to signal that
479    /// it is ready to be garbage collected.
480    ///
481    /// In some cases, however, after a [`State`] object has been deactivated, the framework
482    /// will reinsert it into another part of the tree (e.g., if the subtree containing this
483    /// [`State`] object is grafted from one location in the tree to another due to the use
484    /// of a `GlobalKey`). If that happens, the framework will call
485    /// [`activate`](Self::activate) to give the [`State`] object a chance to reacquire any
486    /// resources that it released in [`deactivate`](Self::deactivate). It will then also call
487    /// [`build`](Self::build) to give the object a chance to adapt to its new location in the
488    /// tree.
489    fn activate(self: Handle<Self>, app: &mut App) {
490        let _ = (self, app);
491    }
492
493    /// Called when this object is removed from the tree permanently.
494    ///
495    /// The framework calls this method when this [`State`] object will never build again.
496    /// After the framework calls [`dispose`](Self::dispose), the [`State`] object is
497    /// considered unmounted and the [`mounted`](Self::mounted) property is false. It is an
498    /// error to call [`set_state`](Self::set_state) at this point.
499    ///
500    /// Subclasses should override this method to release any resources retained by this
501    /// object (e.g., stop any active animations).
502    fn dispose(self: Handle<Self>, app: &mut App) {
503        let _ = (self, app);
504    }
505
506    /// Describes the part of the user interface represented by this widget.
507    ///
508    /// The framework calls this method in a number of different situations. For example:
509    ///
510    ///  * After calling [`init_state`](Self::init_state).
511    ///  * After calling [`did_update_widget`](Self::did_update_widget).
512    ///  * After receiving a call to [`set_state`](Self::set_state).
513    ///  * After a dependency of this [`State`] object changes (e.g., an `InheritedWidget`
514    ///    referenced by the previous [`build`](Self::build) changes).
515    ///  * After calling [`deactivate`](Self::deactivate) and then reinserting the [`State`]
516    ///    object into the tree at another location.
517    ///
518    /// This method can potentially be called in every frame and should not have any side
519    /// effects beyond building a widget.
520    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef;
521
522    /// Called when a dependency of this [`State`] object changes.
523    ///
524    /// For example, if the previous call to [`build`](Self::build) referenced an
525    /// `InheritedWidget` that later changed, the framework would call this method to notify
526    /// this object about the change.
527    ///
528    /// This method is also called immediately after [`init_state`](Self::init_state). It is
529    /// safe to call `BuildContext::depend_on_inherited_widget_of_exact_type` from this method.
530    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
531        let _ = (self, app);
532    }
533
534    /// Dart's `debugFillProperties`: the properties this state shows where its element's dump
535    /// names it (`state: ScrollableState#1a2b3(offset: 0.0)`), after the lifecycle and mounting
536    /// properties `State`'s base adds, which the framework adds first.
537    fn debug_fill_properties(
538        self: Handle<Self>,
539        app: &App,
540        properties: &mut DiagnosticPropertiesBuilder,
541    ) {
542        let _ = (self, app, properties);
543    }
544}