Skip to main content

waft_foundation/
change_notifier.rs

1//! Flutter counterpart: `foundation/change_notifier.dart`.
2
3use std::any::TypeId;
4use std::cell::Cell;
5use std::fmt::{self, Debug};
6use std::hash::{Hash, Hasher};
7use std::rc::{Rc, Weak};
8
9use crate::app::{App, Handle, HandleId, Retained, ToHandle};
10
11/// A closure registered with a [`Listenable`].
12///
13/// Flutter's counterpart is `VoidCallback`. Receives [`App`] because a Rust
14/// listener cannot own what it mutates.
15///
16/// [`Listenable::remove_listener`] matches identity: [`Listener::new`] equals
17/// only its clones; [`Listener::handle_method`] equals any other built from the
18/// same handle and function.
19///
20/// A closure owns what it captures, as a Dart closure does: one that captures a [`Ref`] to the
21/// object it is registered on keeps that object until it is removed. A tear-off
22/// ([`handle_method`](Listener::handle_method)) does not keep its receiver.
23#[derive(Clone)]
24pub struct Listener {
25    callback: Rc<dyn Fn(&mut App)>,
26    identity: ListenerIdentity,
27}
28
29/// Equality key. Closures compare by allocation; handle-methods by
30/// `(handle, TypeId of F)`. TypeId, not address: release codegen can merge
31/// identical bodies.
32#[derive(Clone, Copy)]
33enum ListenerIdentity {
34    Closure,
35    HandleMethod(HandleId, TypeId),
36}
37
38impl Listener {
39    /// Wraps a closure as a listener.
40    pub fn new(callback: impl Fn(&mut App) + 'static) -> Listener {
41        Listener {
42            callback: Rc::new(callback),
43            identity: ListenerIdentity::Closure,
44        }
45    }
46
47    /// A handle's associated function, comparable like a Dart method tear-off.
48    ///
49    /// Pass the function by name. Rebuild at the removal site with the same
50    /// handle and function. A fn pointer or capturing closure is rejected: it
51    /// has no canonical identity. Two captureless closure literals also never
52    /// match — each has a unique type, as in Dart where only tear-offs
53    /// canonicalize.
54    ///
55    /// The listener names its receiver without keeping it, so the most common ring in Flutter
56    /// (a parent's listener list holding a tear-off of the child that keeps the parent) holds
57    /// nothing. Once the receiver is freed the listener is skipped
58    /// ([`App::tear_off_receiver_is_live`]).
59    pub fn handle_method<T: 'static, F>(this: Handle<T>, f: F) -> Listener
60    where
61        F: Fn(Handle<T>, &mut App) + 'static,
62    {
63        const {
64            assert!(
65                std::mem::size_of::<F>() == 0,
66                "pass the function by name: a fn pointer or capturing closure \
67                 has no canonical identity to match on removal"
68            )
69        };
70        Listener {
71            callback: Rc::new(move |app: &mut App| {
72                if app.tear_off_receiver_is_live(this) {
73                    f(this, app);
74                }
75            }),
76            identity: ListenerIdentity::HandleMethod(this.id(), TypeId::of::<F>()),
77        }
78    }
79
80    /// Calls the closure.
81    pub fn call(&self, app: &mut App) {
82        (self.callback)(app);
83    }
84
85    /// A reference to this listener that does not keep its closure alive, for a closure that
86    /// removes itself: Dart's `late VoidCallback l; l = () { ...; notifier.removeListener(l); };`
87    /// names itself, and a closure holding its own listener strongly would keep itself alive
88    /// after the notifier lets it go.
89    pub fn downgrade(&self) -> WeakListener {
90        WeakListener {
91            callback: Rc::downgrade(&self.callback),
92            identity: self.identity,
93        }
94    }
95}
96
97/// A [`Listener`] that does not keep its closure alive; see [`Listener::downgrade`].
98#[derive(Clone)]
99pub struct WeakListener {
100    callback: Weak<dyn Fn(&mut App)>,
101    identity: ListenerIdentity,
102}
103
104impl WeakListener {
105    /// The listener, equal to the one it was made from, while something still holds that one.
106    pub fn upgrade(&self) -> Option<Listener> {
107        Some(Listener {
108            callback: self.callback.upgrade()?,
109            identity: self.identity,
110        })
111    }
112}
113
114impl PartialEq for Listener {
115    fn eq(&self, other: &Listener) -> bool {
116        match (self.identity, other.identity) {
117            (ListenerIdentity::Closure, ListenerIdentity::Closure) => {
118                Rc::ptr_eq(&self.callback, &other.callback)
119            }
120            (
121                ListenerIdentity::HandleMethod(handle, function),
122                ListenerIdentity::HandleMethod(other_handle, other_function),
123            ) => handle == other_handle && function == other_function,
124            _ => false,
125        }
126    }
127}
128
129impl Eq for Listener {}
130
131impl Hash for Listener {
132    fn hash<H: Hasher>(&self, state: &mut H) {
133        match self.identity {
134            ListenerIdentity::Closure => (Rc::as_ptr(&self.callback) as *const ()).hash(state),
135            ListenerIdentity::HandleMethod(handle, function) => {
136                handle.hash(state);
137                function.hash(state);
138            }
139        }
140    }
141}
142
143impl Debug for Listener {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.write_str("Listener")
146    }
147}
148
149/// An object that maintains a list of listeners.
150///
151/// The listeners are typically used to notify clients that the object has been
152/// updated.
153///
154/// There are two variants of this interface:
155///
156///  * [`ValueListenable`], an interface that augments the [`Listenable`]
157///    interface with the concept of a _current value_.
158///
159///  * `Animation`, an interface that augments the [`ValueListenable`] interface
160///    to add the concept of direction (forward or reverse).
161///
162/// Many classes in the Flutter API use or implement these interfaces. The
163/// following subclasses are especially relevant:
164///
165///  * [`ChangeNotifier`], which can be mixed in to create objects that
166///    implement the [`Listenable`] interface.
167///
168///  * [`ValueNotifier`], which implements the [`ValueListenable`] interface
169///    with a mutable value that triggers the notifications when modified.
170///
171/// The terms "notify clients", "send notifications", "trigger notifications",
172/// and "fire notifications" are used interchangeably.
173pub trait Listenable {
174    /// Register a closure to be called when the object notifies its listeners.
175    fn add_listener(&self, app: &mut App, listener: Listener);
176
177    /// Remove a previously registered closure from the list of closures that the
178    /// object notifies.
179    fn remove_listener(&self, app: &mut App, listener: &Listener);
180}
181
182/// A [`Listenable`] that triggers when any of the given [`Listenable`]s
183/// themselves trigger.
184///
185/// Once it is created, items must not be added to or removed from the list.
186/// Doing so will lead to memory leaks or exceptions.
187///
188/// The list may contain `None`s; they are ignored.
189///
190/// Dart's `Listenable.merge` factory.
191pub struct MergingListenable {
192    children: Vec<Option<Rc<dyn Listenable>>>,
193}
194
195impl MergingListenable {
196    /// Dart `Listenable.merge(listenables)`.
197    pub fn new(children: Vec<Option<Rc<dyn Listenable>>>) -> MergingListenable {
198        MergingListenable { children }
199    }
200}
201
202impl Listenable for MergingListenable {
203    fn add_listener(&self, app: &mut App, listener: Listener) {
204        for child in self.children.iter().flatten() {
205            child.add_listener(app, listener.clone());
206        }
207    }
208
209    fn remove_listener(&self, app: &mut App, listener: &Listener) {
210        for child in self.children.iter().flatten() {
211            child.remove_listener(app, listener);
212        }
213    }
214}
215
216impl Debug for MergingListenable {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        write!(f, "Listenable::merge([{} children])", self.children.len())
219    }
220}
221
222/// An interface for implementors of [`Listenable`] that expose a [`value`].
223///
224/// This interface is implemented by [`ValueNotifier<T>`] and `Animation<T>`, and
225/// allows other APIs to accept either of those implementations interchangeably.
226///
227/// [`value`]: ValueListenable::value
228pub trait ValueListenable<T>: Listenable {
229    /// The current value of the object.
230    ///
231    /// When the value changes, the callbacks registered with
232    /// [`Listenable::add_listener`] will be invoked.
233    fn value<'a>(&'a self, app: &'a App) -> &'a T;
234}
235
236/// The fields of Dart's `ChangeNotifier` mixin.
237#[derive(Debug, Default)]
238pub struct ChangeNotifierData {
239    count: usize,
240    // Dart keeps `_listeners` as a fixed-length list. `count` is the live
241    // length; slots from `count` onward, and slots vacated during a dispatch,
242    // are `None`.
243    listeners: Vec<Option<Listener>>,
244    /// Shared with [`Notification`] so a panic still decrements.
245    notification_call_stack_depth: Rc<Cell<usize>>,
246    reentrantly_removed_listeners: usize,
247    #[cfg(debug_assertions)]
248    debug_disposed: bool,
249}
250
251impl ChangeNotifierData {
252    /// Creates a notifier with no listeners.
253    pub fn new() -> ChangeNotifierData {
254        ChangeNotifierData::default()
255    }
256
257    /// Used by owners to assert that the [`ChangeNotifier`] has not yet been
258    /// disposed.
259    ///
260    /// Call it inside a `debug_assert!`, as Dart calls it inside an `assert`,
261    /// so that it is stripped in release:
262    ///
263    /// ```
264    /// # use waft_foundation::ChangeNotifierData;
265    /// # struct MyNotifier { change_notifier: ChangeNotifierData }
266    /// impl MyNotifier {
267    ///     fn do_update(&mut self) {
268    ///         debug_assert!(ChangeNotifierData::debug_assert_not_disposed(&self.change_notifier));
269    ///         // ...
270    ///     }
271    /// }
272    /// ```
273    pub fn debug_assert_not_disposed(notifier: &ChangeNotifierData) -> bool {
274        #[cfg(debug_assertions)]
275        assert!(
276            !notifier.debug_disposed,
277            "A ChangeNotifier was used after being disposed.\n\
278             Once you have called dispose() on a ChangeNotifier, it can no longer be used."
279        );
280        let _ = notifier;
281        true
282    }
283
284    /// Whether any listeners are currently registered.
285    ///
286    /// Clients should not depend on this value for their behavior, because having
287    /// one listener's logic change when another listener happens to start or stop
288    /// listening will lead to extremely hard-to-track bugs. Owners might use
289    /// this information to determine whether to do any work when there are no
290    /// listeners, however; for example, resuming a stream when a listener is
291    /// added and pausing it when a listener is removed.
292    ///
293    /// Typically this is used by overriding [`Listenable::add_listener`], checking
294    /// if [`has_listeners`] is false before calling `self.change_notifier.add_listener()`,
295    /// and if so, starting whatever work is needed to determine when to call
296    /// [`notify_listeners`]; and similarly, by overriding
297    /// [`Listenable::remove_listener`], checking if [`has_listeners`] is false
298    /// after calling `self.change_notifier.remove_listener()`, and if so, stopping that
299    /// same work.
300    ///
301    /// This method returns false if [`dispose`] has been called.
302    ///
303    /// [`has_listeners`]: ChangeNotifierData::has_listeners
304    /// [`notify_listeners`]: Handle::notify_listeners
305    /// [`dispose`]: ChangeNotifierData::dispose
306    pub fn has_listeners(&self) -> bool {
307        self.count > 0
308    }
309
310    /// Register a closure to be called when the object changes.
311    ///
312    /// If the given closure is already registered, an additional instance is
313    /// added, and must be removed the same number of times it is added before it
314    /// will stop being called.
315    ///
316    /// This method must not be called after [`dispose`] has been called.
317    ///
318    /// If a listener is added twice, and is removed once during an iteration
319    /// (e.g. in response to a notification), it will still be called again. If,
320    /// on the other hand, it is removed as many times as it was registered, then
321    /// it will no longer be called. This odd behavior is the result of the
322    /// [`ChangeNotifier`] not being able to determine which listener is being
323    /// removed, since they are identical, therefore it will conservatively still
324    /// call all the listeners when it knows that any are still registered.
325    ///
326    /// This surprising behavior can be unexpectedly observed when registering a
327    /// listener on two separate objects which are both forwarding all
328    /// registrations to a common upstream object.
329    ///
330    /// See also:
331    ///
332    ///  * [`remove_listener`], which removes a previously registered closure from
333    ///    the list of closures that are notified when the object changes.
334    ///
335    /// [`dispose`]: ChangeNotifierData::dispose
336    /// [`remove_listener`]: ChangeNotifierData::remove_listener
337    pub fn add_listener(&mut self, listener: Listener) {
338        debug_assert!(ChangeNotifierData::debug_assert_not_disposed(self));
339
340        if self.count == self.listeners.len() {
341            if self.count == 0 {
342                self.listeners = vec![None; 1];
343            } else {
344                let mut new_listeners = vec![None; self.listeners.len() * 2];
345                new_listeners[..self.count].clone_from_slice(&self.listeners[..self.count]);
346                self.listeners = new_listeners;
347            }
348        }
349        self.listeners[self.count] = Some(listener);
350        self.count += 1;
351    }
352
353    fn remove_at(&mut self, index: usize) {
354        // The list holding the listeners is not growable for performances reasons.
355        // We still want to shrink this list if a lot of listeners have been added
356        // and then removed outside a notify_listeners iteration.
357        // We do this only when the real number of listeners is half the length
358        // of our list.
359        self.count -= 1;
360        if self.count * 2 <= self.listeners.len() {
361            let mut new_listeners = vec![None; self.count];
362
363            // Listeners before the index are at the same place.
364            new_listeners[..index].clone_from_slice(&self.listeners[..index]);
365
366            // Listeners after the index move towards the start of the list.
367            new_listeners[index..self.count]
368                .clone_from_slice(&self.listeners[index + 1..self.count + 1]);
369
370            self.listeners = new_listeners;
371        } else {
372            // When there are more listeners than half the length of the list, we only
373            // shift our listeners, so that we avoid to reallocate memory for the
374            // whole list.
375            for i in index..self.count {
376                let moved = self.listeners[i + 1].clone();
377                self.listeners[i] = moved;
378            }
379            self.listeners[self.count] = None;
380        }
381    }
382
383    /// Remove a previously registered closure from the list of closures that are
384    /// notified when the object changes.
385    ///
386    /// If the given listener is not registered, the call is ignored.
387    ///
388    /// This method returns immediately if [`dispose`] has been called.
389    ///
390    /// If a listener is added twice, and is removed once during an iteration
391    /// (e.g. in response to a notification), it will still be called again. If,
392    /// on the other hand, it is removed as many times as it was registered, then
393    /// it will no longer be called. This odd behavior is the result of the
394    /// [`ChangeNotifier`] not being able to determine which listener is being
395    /// removed, since they are identical, therefore it will conservatively still
396    /// call all the listeners when it knows that any are still registered.
397    ///
398    /// See also:
399    ///
400    ///  * [`add_listener`], which registers a closure to be called when the object
401    ///    changes.
402    ///
403    /// [`dispose`]: ChangeNotifierData::dispose
404    /// [`add_listener`]: ChangeNotifierData::add_listener
405    pub fn remove_listener(&mut self, listener: &Listener) {
406        // This method is allowed to be called on disposed instances for usability
407        // reasons. Due to how our frame scheduling logic between render objects and
408        // overlays, it is common that the owner of this instance would be disposed a
409        // frame earlier than the listeners. Allowing calls to this method after it
410        // is disposed makes it easier for listeners to properly clean up.
411        for i in 0..self.count {
412            if self.listeners[i].as_ref() == Some(listener) {
413                if self.notification_call_stack_depth.get() > 0 {
414                    // We don't resize the list during notify_listeners iterations
415                    // but we set to null, the listeners we want to remove. We will
416                    // effectively resize the list at the end of all notify_listeners
417                    // iterations.
418                    self.listeners[i] = None;
419                    self.reentrantly_removed_listeners += 1;
420                } else {
421                    // When we are outside the notify_listeners iterations we can
422                    // effectively shrink the list.
423                    self.remove_at(i);
424                }
425                break;
426            }
427        }
428    }
429
430    /// Discards any resources used by the object.
431    ///
432    /// After this is called, the object is not in a usable state and should be
433    /// discarded (calls to [`add_listener`] will panic in debug builds after the
434    /// object is disposed).
435    ///
436    /// This method should only be called by the object's owner.
437    ///
438    /// This method does not notify listeners, and clears the listener list once
439    /// it is called. Owners of this type must decide on whether to notify
440    /// listeners or not immediately before disposal.
441    ///
442    /// The owner is a handle, as for [`Handle::notify_listeners`], so the arena can record the
443    /// disposal ([`App::mark_disposed`]).
444    ///
445    /// [`add_listener`]: ChangeNotifierData::add_listener
446    pub fn dispose<T: ChangeNotifier>(app: &mut App, owner: impl ToHandle<T>) {
447        let owner = owner.to_handle();
448        app.get_mut(owner)
449            .change_notifier_data_mut()
450            .clear_for_dispose();
451        app.mark_disposed(owner);
452    }
453
454    fn clear_for_dispose(&mut self) {
455        debug_assert!(ChangeNotifierData::debug_assert_not_disposed(self));
456        debug_assert!(
457            self.notification_call_stack_depth.get() == 0,
458            "The \"dispose()\" method on {self:?} was called during the call to \
459             \"notify_listeners()\". This is likely to cause errors since it modifies \
460             the list of listeners while the list is being used."
461        );
462        #[cfg(debug_assertions)]
463        {
464            self.debug_disposed = true;
465        }
466        self.listeners = Vec::new();
467        self.count = 0;
468        // A panicking listener skips Dart's per-listener `catch`, which is
469        // what zeros this. Leaving it set underflows
470        // `count - reentrantly_removed_listeners` on the next dispatch.
471        //
472        // The depth is not reset: it is shared with any live Notification,
473        // which decrements on drop.
474        self.reentrantly_removed_listeners = 0;
475    }
476
477    /// Dispatch through [`Handle::notify_listeners`]. The owner is a handle, not
478    /// `&mut self`, so a listener can re-enter it.
479    pub(crate) fn notify_listeners<T: 'static>(
480        app: &mut App,
481        owner: Handle<T>,
482        field: fn(&mut T) -> &mut ChangeNotifierData,
483    ) {
484        let (notification, end) = {
485            let notifier = field(app.get_mut(owner));
486            debug_assert!(ChangeNotifierData::debug_assert_not_disposed(notifier));
487            if notifier.count == 0 {
488                return;
489            }
490
491            // To make sure that listeners removed during this iteration are not called,
492            // we set them to null, but we don't shrink the list right away.
493            // By doing this, we can continue to iterate on our list until it reaches
494            // the last listener added before the call to this method.
495
496            // To allow potential listeners to recursively call notify_listeners, we track
497            // the number of times this method is called in notification_call_stack_depth.
498            // Once every recursive iteration is finished (i.e. when
499            // notification_call_stack_depth == 0), we can safely shrink our list so that
500            // it will only contain not null listeners.
501            let notification =
502                Notification::begin(Rc::clone(&notifier.notification_call_stack_depth));
503            (notification, notifier.count)
504        };
505
506        for i in 0..end {
507            let listener = field(app.get_mut(owner)).listeners[i].clone();
508            if let Some(listener) = listener {
509                listener.call(app);
510            }
511        }
512
513        drop(notification);
514
515        let notifier = field(app.get_mut(owner));
516        if notifier.notification_call_stack_depth.get() == 0
517            && notifier.reentrantly_removed_listeners > 0
518        {
519            notifier.compact_reentrantly_removed_listeners();
520        }
521    }
522
523    fn compact_reentrantly_removed_listeners(&mut self) {
524        // We really remove the listeners when all notifications are done.
525        let new_length = self.count - self.reentrantly_removed_listeners;
526        if new_length * 2 <= self.listeners.len() {
527            // As in remove_at, we only shrink the list when the real number of
528            // listeners is half the length of our list.
529            let mut new_listeners = vec![None; new_length];
530
531            let mut new_index = 0;
532            for listener in &self.listeners[..self.count] {
533                if listener.is_some() {
534                    new_listeners[new_index] = listener.clone();
535                    new_index += 1;
536                }
537            }
538
539            self.listeners = new_listeners;
540        } else {
541            // Otherwise we put all the null references at the end.
542            for i in 0..new_length {
543                if self.listeners[i].is_none() {
544                    // We swap this item with the next not null item.
545                    let mut swap_index = i + 1;
546                    while self.listeners[swap_index].is_none() {
547                        swap_index += 1;
548                    }
549                    self.listeners.swap(i, swap_index);
550                }
551            }
552        }
553
554        self.reentrantly_removed_listeners = 0;
555        self.count = new_length;
556    }
557}
558
559/// Dart's `try`/`finally` around each listener. Holds the depth by `Rc`, never
560/// a borrow of the notifier, so a panic still decrements.
561struct Notification {
562    depth: Rc<Cell<usize>>,
563}
564
565impl Notification {
566    fn begin(depth: Rc<Cell<usize>>) -> Notification {
567        depth.set(depth.get() + 1);
568        Notification { depth }
569    }
570}
571
572impl Drop for Notification {
573    fn drop(&mut self) {
574        self.depth.set(self.depth.get() - 1);
575    }
576}
577
578/// The object side of [`Listenable`]: an arena object that keeps listeners. Implementing it
579/// makes `Handle<Self>` a [`Listenable`]. Every [`ChangeNotifier`] is one; an object with its
580/// own listener bookkeeping (Flutter's `AnimationLocalListenersMixin`) implements it directly.
581///
582/// [`Listenable`] itself takes `&self` so that an erased handle type can implement it; a crate
583/// cannot implement that foreign trait for `Handle<ItsType>`, so it implements this one on
584/// the type instead.
585pub trait ListenableObject: Sized + 'static {
586    /// Register a closure to be called when the object notifies its listeners.
587    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener);
588
589    /// Remove a previously registered closure from the list of closures that the
590    /// object notifies.
591    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener);
592}
593
594impl<T: ChangeNotifier> ListenableObject for T {
595    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
596        // Dart's `addListener` dispatches the object's creation to the leak tracking here, since
597        // a mixin has no constructor of its own.
598        app.expect_dispose(self);
599        ChangeNotifier::will_add_listener(self, app);
600        app.get_mut(self)
601            .change_notifier_data_mut()
602            .add_listener(listener);
603    }
604
605    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
606        // Allowed on a disposed instance (see `ChangeNotifierData::remove_listener`); here a
607        // disposed notifier may already have left the arena, so a stale handle is a no-op.
608        if !app.contains(self) {
609            return;
610        }
611        app.get_mut(self)
612            .change_notifier_data_mut()
613            .remove_listener(listener);
614        ChangeNotifier::did_remove_listener(self, app);
615    }
616}
617
618/// A Copy handle to an object that keeps listeners: what a [`Retained`] of it is a
619/// [`Listenable`] through. [`Handle<T>`] is one for a [`ListenableObject`]; an erased handle (an
620/// animation's) implements it for its type.
621///
622/// The [`Listenable`] is the [`Retained`], not the bare handle, so an `Rc<dyn Listenable>` keeps
623/// the object it listens to. The methods are named apart from [`ListenableObject`]'s so a
624/// `handle.add_listener(..)` call is never ambiguous.
625pub trait ListenableHandle: Copy + 'static {
626    /// See [`Listenable::add_listener`].
627    fn add_listener_to(self, app: &mut App, listener: Listener);
628
629    /// See [`Listenable::remove_listener`].
630    fn remove_listener_from(self, app: &mut App, listener: &Listener);
631}
632
633impl<T: ListenableObject> ListenableHandle for Handle<T> {
634    fn add_listener_to(self, app: &mut App, listener: Listener) {
635        T::add_listener(self, app, listener);
636    }
637
638    fn remove_listener_from(self, app: &mut App, listener: &Listener) {
639        T::remove_listener(self, app, listener);
640    }
641}
642
643impl<H: ListenableHandle> Listenable for Retained<H> {
644    fn add_listener(&self, app: &mut App, listener: Listener) {
645        self.handle().add_listener_to(app, listener);
646    }
647
648    fn remove_listener(&self, app: &mut App, listener: &Listener) {
649        self.handle().remove_listener_from(app, listener);
650    }
651}
652
653/// A class that can be mixed in that provides a change notification API using
654/// [`Listener`] for notifications.
655///
656/// It is O(1) for adding listeners and O(N) for removing listeners and
657/// dispatching notifications (where N is the number of listeners).
658///
659/// Hold [`ChangeNotifierData`] as a field and implement this trait. Then
660/// [`Handle::notify_listeners`] is inherent — no extra import at the call site.
661///
662/// See also:
663///
664///  * [`ValueNotifier`], which is a [`ChangeNotifier`] that wraps a single
665///    value.
666pub trait ChangeNotifier: Sized + 'static {
667    fn change_notifier_data(&self) -> &ChangeNotifierData;
668
669    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData;
670
671    /// Runs before the listener is stored. Dart overrides of `addListener` that
672    /// work before `super.addListener` go here.
673    fn will_add_listener(self: Handle<Self>, app: &mut App) {
674        let _ = app;
675    }
676
677    /// Runs after the listener is removed. Dart overrides of `removeListener` that
678    /// work after `super.removeListener` go here.
679    fn did_remove_listener(self: Handle<Self>, app: &mut App) {
680        let _ = app;
681    }
682}
683
684impl ChangeNotifier for ChangeNotifierData {
685    fn change_notifier_data(&self) -> &ChangeNotifierData {
686        self
687    }
688
689    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
690        self
691    }
692}
693
694impl<T: ChangeNotifier> Handle<T> {
695    /// Call all the registered listeners.
696    ///
697    /// Call this method whenever the object changes, to notify any clients the
698    /// object may have changed. Listeners that are added during this iteration
699    /// will not be visited. Listeners that are removed during this iteration will
700    /// not be visited after they are removed.
701    ///
702    /// This method must not be called after [`ChangeNotifierData::dispose`] has been
703    /// called.
704    ///
705    /// Surprising behavior can result when reentrantly removing a listener (e.g.
706    /// in response to a notification) that has been registered multiple times.
707    /// See the discussion at [`ChangeNotifierData::remove_listener`].
708    pub fn notify_listeners(self, app: &mut App) {
709        ChangeNotifierData::notify_listeners(app, self, T::change_notifier_data_mut);
710    }
711}
712
713/// A [`ChangeNotifier`] that holds a single value.
714///
715/// When [`value`] is replaced with a new value that is **not equal** to the old
716/// value as evaluated by `PartialEq`, this type notifies its listeners.
717///
718/// ## Limitations
719///
720/// Notifications are triggered based on **equality**, not on mutations within
721/// the value itself. As a result, changes to mutable values that do not affect
722/// their equality will not cause listeners to be notified.
723///
724/// Because of this behavior, [`ValueNotifier`] is best used with immutable data
725/// types. For mutable data types, consider holding a [`ChangeNotifierData`]
726/// directly and calling [`Handle::notify_listeners`] when changes occur.
727///
728/// [`value`]: ValueListenable::value
729#[derive(Debug, Default)]
730pub struct ValueNotifier<T> {
731    change_notifier: ChangeNotifierData,
732    value: T,
733}
734
735impl<T> ValueNotifier<T> {
736    /// Creates a [`ChangeNotifier`] that wraps this value.
737    pub fn new(value: T) -> ValueNotifier<T> {
738        ValueNotifier {
739            change_notifier: ChangeNotifierData::new(),
740            value,
741        }
742    }
743
744    /// The wrapped value. Prefer [`ValueListenable::value`] on the [`Ref`] when
745    /// you do not already have a borrow of the slot.
746    pub fn value(&self) -> &T {
747        &self.value
748    }
749}
750
751impl<T: 'static> ValueNotifier<T> {
752    /// Discards any resources used by the object; see [`ChangeNotifierData::dispose`].
753    pub fn dispose(self: Handle<Self>, app: &mut App) {
754        ChangeNotifierData::dispose(app, self);
755    }
756}
757
758impl<T: 'static> ChangeNotifier for ValueNotifier<T> {
759    fn change_notifier_data(&self) -> &ChangeNotifierData {
760        &self.change_notifier
761    }
762
763    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
764        &mut self.change_notifier
765    }
766}
767
768impl<T: 'static> Handle<ValueNotifier<T>> {
769    /// The current value, read through the bare handle.
770    pub fn value(self, app: &App) -> &T {
771        app.get(self).value()
772    }
773}
774
775impl<T: PartialEq + 'static> Handle<ValueNotifier<T>> {
776    /// Replaces the current value, notifying listeners when it differs.
777    ///
778    /// Dart's setter takes only the value. This takes [`App`] because notifying
779    /// does: a listener may assign back through this setter.
780    pub fn set_value(self, app: &mut App, new_value: T) {
781        if app.get(self).value == new_value {
782            return;
783        }
784        app.get_mut(self).value = new_value;
785        self.notify_listeners(app);
786    }
787}
788
789/// A Copy handle to an object with a current value: what a [`Retained`] of it is a
790/// [`ValueListenable`] through, as [`ListenableHandle`] is for [`Listenable`].
791pub trait ValueListenableHandle<T>: ListenableHandle {
792    /// See [`ValueListenable::value`].
793    fn value_of(self, app: &App) -> &T;
794}
795
796impl<T: 'static> ValueListenableHandle<T> for Handle<ValueNotifier<T>> {
797    fn value_of(self, app: &App) -> &T {
798        app.get(self).value()
799    }
800}
801
802impl<T, H: ValueListenableHandle<T>> ValueListenable<T> for Retained<H> {
803    fn value<'a>(&'a self, app: &'a App) -> &'a T {
804        self.handle().value_of(app)
805    }
806}
807
808#[cfg(test)]
809mod tests {
810    use std::cell::RefCell;
811    use std::panic::{AssertUnwindSafe, catch_unwind};
812
813    use super::*;
814    use crate::app_cell::AppCell;
815
816    type Log = Rc<RefCell<Vec<String>>>;
817
818    fn fired(log: &Log) -> Vec<String> {
819        log.borrow().clone()
820    }
821
822    #[derive(Default)]
823    struct TestNotifier {
824        change_notifier: ChangeNotifierData,
825    }
826
827    impl ChangeNotifier for TestNotifier {
828        fn change_notifier_data(&self) -> &ChangeNotifierData {
829            &self.change_notifier
830        }
831
832        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
833            &mut self.change_notifier
834        }
835    }
836
837    fn recording(log: &Log, name: &'static str) -> Listener {
838        let log = Rc::clone(log);
839        Listener::new(move |_app| log.borrow_mut().push(name.to_string()))
840    }
841
842    /// The helpers take a `&Ref`, or a bare handle from inside a listener of the host.
843    fn add(app: &mut App, host: impl ToHandle<TestNotifier>, listener: Listener) {
844        host.to_handle().add_listener(app, listener);
845    }
846
847    fn remove(app: &mut App, host: impl ToHandle<TestNotifier>, listener: &Listener) {
848        host.to_handle().remove_listener(app, listener);
849    }
850
851    fn notify(app: &mut App, host: impl ToHandle<TestNotifier>) {
852        host.to_handle().notify_listeners(app);
853    }
854
855    fn silence_panic_hook() -> Box<dyn Fn(&std::panic::PanicHookInfo<'_>) + Send + Sync + 'static> {
856        let hook = std::panic::take_hook();
857        std::panic::set_hook(Box::new(|_| {}));
858        hook
859    }
860
861    /// `change_notifier_test.dart`: "ChangeNotifier" — order, duplicates, extra remove.
862    #[test]
863    fn listeners_are_called_in_the_order_they_were_added() {
864        let cell = AppCell::new();
865        let mut app = cell.borrow_mut();
866        let log = Log::default();
867        let host = app.create(TestNotifier::default());
868
869        let listener = recording(&log, "listener");
870        add(&mut app, &host, listener.clone());
871        add(&mut app, &host, listener.clone());
872        notify(&mut app, &host);
873        assert_eq!(fired(&log), ["listener", "listener"]);
874        log.borrow_mut().clear();
875
876        remove(&mut app, &host, &listener);
877        notify(&mut app, &host);
878        assert_eq!(fired(&log), ["listener"]);
879        log.borrow_mut().clear();
880
881        remove(&mut app, &host, &listener);
882        notify(&mut app, &host);
883        assert_eq!(fired(&log), Vec::<String>::new());
884        log.borrow_mut().clear();
885
886        remove(&mut app, &host, &listener);
887        notify(&mut app, &host);
888        assert_eq!(fired(&log), Vec::<String>::new());
889        log.borrow_mut().clear();
890
891        add(&mut app, &host, listener.clone());
892        notify(&mut app, &host);
893        assert_eq!(fired(&log), ["listener"]);
894        log.borrow_mut().clear();
895
896        let listener1 = recording(&log, "listener1");
897        add(&mut app, &host, listener1.clone());
898        notify(&mut app, &host);
899        assert_eq!(fired(&log), ["listener", "listener1"]);
900        log.borrow_mut().clear();
901
902        let listener2 = recording(&log, "listener2");
903        add(&mut app, &host, listener2.clone());
904        notify(&mut app, &host);
905        assert_eq!(fired(&log), ["listener", "listener1", "listener2"]);
906        log.borrow_mut().clear();
907
908        remove(&mut app, &host, &listener1);
909        notify(&mut app, &host);
910        assert_eq!(fired(&log), ["listener", "listener2"]);
911        log.borrow_mut().clear();
912
913        add(&mut app, &host, listener1.clone());
914        notify(&mut app, &host);
915        assert_eq!(fired(&log), ["listener", "listener2", "listener1"]);
916    }
917
918    /// `change_notifier_test.dart`: "ChangeNotifier with mutating listener".
919    #[test]
920    fn a_listener_mutates_the_notifier_dispatching_to_it() {
921        let cell = AppCell::new();
922        let mut app = cell.borrow_mut();
923        let log = Log::default();
924        let host = app.create(TestNotifier::default());
925
926        let listener1 = recording(&log, "listener1");
927        let listener3 = recording(&log, "listener3");
928        let listener4 = recording(&log, "listener4");
929        let listener2 = {
930            let log = Rc::clone(&log);
931            let (one, three, four) = (listener1.clone(), listener3.clone(), listener4.clone());
932            let host = host.handle();
933            Listener::new(move |app: &mut App| {
934                log.borrow_mut().push("listener2".to_string());
935                let notifier = &mut app.get_mut(host).change_notifier;
936                notifier.remove_listener(&one);
937                notifier.remove_listener(&three);
938                notifier.add_listener(four.clone());
939            })
940        };
941
942        add(&mut app, &host, listener1);
943        add(&mut app, &host, listener2);
944        add(&mut app, &host, listener3);
945
946        notify(&mut app, &host);
947        assert_eq!(fired(&log), ["listener1", "listener2"]);
948
949        log.borrow_mut().clear();
950        notify(&mut app, &host);
951        assert_eq!(fired(&log), ["listener2", "listener4"]);
952
953        log.borrow_mut().clear();
954        notify(&mut app, &host);
955        assert_eq!(fired(&log), ["listener2", "listener4", "listener4"]);
956    }
957
958    /// `change_notifier_test.dart`: "During notifyListeners, a listener was added and removed immediately".
959    #[test]
960    fn a_listener_added_and_removed_immediately_during_notify_is_not_called() {
961        let cell = AppCell::new();
962        let mut app = cell.borrow_mut();
963        let log = Log::default();
964        let host = app.create(TestNotifier::default());
965
966        let listener2 = recording(&log, "listener2");
967        let listener3 = recording(&log, "listener3");
968        let listener1 = {
969            let log = Rc::clone(&log);
970            let two = listener2.clone();
971            let three = listener3.clone();
972            let host = host.handle();
973            Listener::new(move |app: &mut App| {
974                log.borrow_mut().push("listener1".to_string());
975                let notifier = &mut app.get_mut(host).change_notifier;
976                notifier.add_listener(two.clone());
977                notifier.remove_listener(&two);
978                notifier.add_listener(three.clone());
979            })
980        };
981
982        add(&mut app, &host, listener1);
983        notify(&mut app, &host);
984        assert_eq!(fired(&log), ["listener1"]);
985    }
986
987    /// `change_notifier_test.dart`: self-removing listener in the middle still notifies all.
988    #[test]
989    fn a_self_removing_listener_in_the_middle_still_notifies_all() {
990        let cell = AppCell::new();
991        let mut app = cell.borrow_mut();
992        let log = Log::default();
993        let host = app.create(TestNotifier::default());
994
995        let listener1 = recording(&log, "listener1");
996        let self_removing_slot: Rc<RefCell<Option<Listener>>> = Rc::new(RefCell::new(None));
997        let self_removing = {
998            let log = Rc::clone(&log);
999            let slot = Rc::clone(&self_removing_slot);
1000            let host = host.handle();
1001            Listener::new(move |app: &mut App| {
1002                log.borrow_mut().push("selfRemovingListener".to_string());
1003                let me = slot.borrow().clone().unwrap();
1004                app.get_mut(host).change_notifier.remove_listener(&me);
1005            })
1006        };
1007        *self_removing_slot.borrow_mut() = Some(self_removing.clone());
1008
1009        add(&mut app, &host, listener1.clone());
1010        add(&mut app, &host, self_removing);
1011        add(&mut app, &host, listener1);
1012
1013        notify(&mut app, &host);
1014        assert_eq!(
1015            fired(&log),
1016            ["listener1", "selfRemovingListener", "listener1"]
1017        );
1018    }
1019
1020    /// `change_notifier_test.dart`: first listener removes itself, still notifies the rest.
1021    #[test]
1022    fn the_first_listener_removing_itself_still_notifies_the_rest() {
1023        let cell = AppCell::new();
1024        let mut app = cell.borrow_mut();
1025        let log = Log::default();
1026        let host = app.create(TestNotifier::default());
1027
1028        let self_removing_slot: Rc<RefCell<Option<Listener>>> = Rc::new(RefCell::new(None));
1029        let self_removing = {
1030            let log = Rc::clone(&log);
1031            let slot = Rc::clone(&self_removing_slot);
1032            let host = host.handle();
1033            Listener::new(move |app: &mut App| {
1034                log.borrow_mut().push("selfRemovingListener".to_string());
1035                let me = slot.borrow().clone().unwrap();
1036                app.get_mut(host).change_notifier.remove_listener(&me);
1037            })
1038        };
1039        *self_removing_slot.borrow_mut() = Some(self_removing.clone());
1040        let listener1 = recording(&log, "listener1");
1041
1042        add(&mut app, &host, self_removing);
1043        add(&mut app, &host, listener1);
1044
1045        notify(&mut app, &host);
1046        assert_eq!(fired(&log), ["selfRemovingListener", "listener1"]);
1047    }
1048
1049    #[test]
1050    fn only_a_handle_to_the_same_closure_compares_equal() {
1051        let log = Log::default();
1052        let listener = recording(&log, "a");
1053
1054        assert_eq!(listener, listener.clone());
1055        assert_ne!(listener, recording(&log, "a"));
1056    }
1057
1058    #[test]
1059    fn a_rebuilt_handle_method_listener_matches_like_a_dart_tear_off() {
1060        struct Host;
1061        fn hook(_this: Handle<Host>, _app: &mut App) {}
1062        fn other_hook(_this: Handle<Host>, _app: &mut App) {}
1063
1064        let cell = AppCell::new();
1065        let mut app = cell.borrow_mut();
1066        let a = app.create(Host);
1067        let b = app.create(Host);
1068
1069        assert_eq!(
1070            Listener::handle_method(a.handle(), hook),
1071            Listener::handle_method(a.handle(), hook)
1072        );
1073        assert_ne!(
1074            Listener::handle_method(a.handle(), hook),
1075            Listener::handle_method(b.handle(), hook)
1076        );
1077        assert_ne!(
1078            Listener::handle_method(a.handle(), hook),
1079            Listener::handle_method(a.handle(), other_hook)
1080        );
1081        assert_ne!(
1082            Listener::handle_method(a.handle(), hook),
1083            Listener::new(|_app| {})
1084        );
1085    }
1086
1087    #[test]
1088    fn a_handle_method_listener_calls_the_function_with_its_handle() {
1089        struct Host;
1090        thread_local! {
1091            static CALLED_WITH: Cell<Option<HandleId>> = const { Cell::new(None) };
1092        }
1093        fn hook(this: Handle<Host>, _app: &mut App) {
1094            CALLED_WITH.with(|called| called.set(Some(this.id())));
1095        }
1096
1097        let cell = AppCell::new();
1098        let mut app = cell.borrow_mut();
1099        let host = app.create(Host);
1100        Listener::handle_method(host.handle(), hook).call(&mut app);
1101        assert_eq!(CALLED_WITH.with(Cell::get), Some(host.id()));
1102    }
1103
1104    /// A listener dropped with its receiver, never removed, is what Dart would leak: here the
1105    /// receiver is freed and the notifier skips the tear-off, reporting it once.
1106    #[test]
1107    #[cfg(debug_assertions)]
1108    fn a_tear_off_whose_receiver_was_freed_is_skipped_and_reported_once() {
1109        struct Host;
1110        fn hook(_this: Handle<Host>, _app: &mut App) {
1111            panic!("a freed receiver's tear-off ran");
1112        }
1113
1114        let cell = AppCell::new();
1115        let notifier = cell.borrow_mut().create(ChangeNotifierData::new());
1116        let host = cell.borrow_mut().create(Host).handle();
1117        notifier.add_listener(&mut cell.borrow_mut(), Listener::handle_method(host, hook));
1118        cell.checkpoint();
1119        assert!(!cell.borrow().contains(host), "nothing kept the receiver");
1120
1121        notifier.notify_listeners(&mut cell.borrow_mut());
1122        notifier.notify_listeners(&mut cell.borrow_mut());
1123        let skipped = cell.borrow_mut().debug_take_skipped_tear_offs();
1124        assert_eq!(skipped.len(), 1, "{skipped:?}");
1125        assert!(skipped[0].contains("Host"), "{skipped:?}");
1126    }
1127
1128    /// `remove_at` shifts in place while survivors fill more than half the
1129    /// buffer, and reallocates once they fit in half of it.
1130    #[test]
1131    fn removing_keeps_order_across_both_shrink_branches() {
1132        for first in 0..8 {
1133            let cell = AppCell::new();
1134            let mut app = cell.borrow_mut();
1135            let log = Log::default();
1136            let host = app.create(TestNotifier::default());
1137
1138            let names = ["0", "1", "2", "3", "4", "5", "6", "7"];
1139            let listeners: Vec<Listener> = names.iter().map(|name| recording(&log, name)).collect();
1140            for listener in &listeners {
1141                add(&mut app, &host, listener.clone());
1142            }
1143
1144            let mut survivors: Vec<String> = names.iter().map(|n| n.to_string()).collect();
1145            let mut saw_realloc = false;
1146
1147            for step in 0..8 {
1148                let index = (first + step) % 8;
1149                remove(&mut app, &host, &listeners[index]);
1150                survivors.retain(|s| s != names[index]);
1151                saw_realloc |= app.get(&host).change_notifier.listeners.len() < 8;
1152
1153                log.borrow_mut().clear();
1154                notify(&mut app, &host);
1155                assert_eq!(fired(&log), survivors, "after removing {index}");
1156                assert_eq!(app.get(&host).change_notifier.count, survivors.len());
1157            }
1158
1159            assert!(saw_realloc, "the shrink branch never ran");
1160        }
1161    }
1162
1163    /// `change_notifier_test.dart`: "Cannot use a disposed ChangeNotifier except for remove listener".
1164    #[test]
1165    fn dispose_drops_every_listener_but_leaves_removal_callable() {
1166        let cell = AppCell::new();
1167        let mut app = cell.borrow_mut();
1168        let log = Log::default();
1169        let host = app.create(TestNotifier::default());
1170
1171        let listener = recording(&log, "a");
1172        add(&mut app, &host, listener.clone());
1173        ChangeNotifierData::dispose(&mut app, &host);
1174
1175        assert!(!app.get(&host).change_notifier.has_listeners());
1176        app.get_mut(&host)
1177            .change_notifier
1178            .remove_listener(&listener);
1179        assert_eq!(fired(&log), Vec::<String>::new());
1180    }
1181
1182    #[test]
1183    #[cfg(debug_assertions)]
1184    #[should_panic(expected = "was used after being disposed")]
1185    fn adding_a_listener_after_dispose_panics_in_debug() {
1186        let mut notifier = ChangeNotifierData::new();
1187        notifier.clear_for_dispose();
1188        notifier.add_listener(recording(&Log::default(), "a"));
1189    }
1190
1191    #[test]
1192    #[cfg(debug_assertions)]
1193    #[should_panic(expected = "was used after being disposed")]
1194    fn notifying_after_dispose_panics_in_debug() {
1195        let cell = AppCell::new();
1196        let mut app = cell.borrow_mut();
1197        let host = app.create(TestNotifier::default());
1198        ChangeNotifierData::dispose(&mut app, &host);
1199        notify(&mut app, &host);
1200    }
1201
1202    #[test]
1203    #[cfg(debug_assertions)]
1204    #[should_panic(expected = "was used after being disposed")]
1205    fn disposing_twice_panics_in_debug() {
1206        let mut notifier = ChangeNotifierData::new();
1207        notifier.clear_for_dispose();
1208        notifier.clear_for_dispose();
1209    }
1210
1211    /// Dart's `late VoidCallback l; l = () { notifier.removeListener(l); };`: the closure names
1212    /// itself weakly, so once the notifier lets it go nothing keeps it.
1213    #[test]
1214    fn a_listener_that_removes_itself_through_a_weak_listener_is_dropped() {
1215        let cell = AppCell::new();
1216        let mut app = cell.borrow_mut();
1217        let notifier = app.create(ValueNotifier::new(0i32));
1218        let host = notifier.handle();
1219        let itself: Rc<std::cell::OnceCell<WeakListener>> = Rc::default();
1220        let listener = {
1221            let itself = Rc::clone(&itself);
1222            Listener::new(move |app: &mut App| {
1223                if let Some(listener) = itself.get().and_then(WeakListener::upgrade) {
1224                    host.remove_listener(app, &listener);
1225                }
1226            })
1227        };
1228        let weak = listener.downgrade();
1229        let _ = itself.set(listener.downgrade());
1230        host.add_listener(&mut app, listener);
1231        assert!(weak.upgrade().is_some(), "the notifier keeps it");
1232        host.notify_listeners(&mut app);
1233        assert!(!app.get(host).change_notifier.has_listeners());
1234        assert!(
1235            weak.upgrade().is_none(),
1236            "nothing keeps it once it removed itself"
1237        );
1238    }
1239
1240    /// `change_notifier_test.dart`: "Can check hasListener on a disposed ChangeNotifier".
1241    #[test]
1242    fn has_listeners_is_false_after_dispose() {
1243        let cell = AppCell::new();
1244        let mut app = cell.borrow_mut();
1245        let counter = app.create(ValueNotifier::new(0i32));
1246        counter.add_listener(&mut app, recording(&Log::default(), "a"));
1247        assert!(app.get(&counter).change_notifier.has_listeners());
1248        counter.dispose(&mut app);
1249        assert!(!app.get(&counter).change_notifier.has_listeners());
1250    }
1251
1252    /// `change_notifier_test.dart`: "Value notifier".
1253    #[test]
1254    fn value_notifier_notifies_only_when_the_value_differs() {
1255        let cell = AppCell::new();
1256        let mut app = cell.borrow_mut();
1257        let log = Log::default();
1258        let notifier = app.create(ValueNotifier::new(2.0));
1259
1260        notifier.add_listener(&mut app, {
1261            let log = Rc::clone(&log);
1262            let notifier = notifier.handle();
1263            Listener::new(move |app: &mut App| {
1264                log.borrow_mut().push(app.get(notifier).value().to_string());
1265            })
1266        });
1267
1268        notifier.set_value(&mut app, 3.0);
1269        assert_eq!(fired(&log), ["3"]);
1270        log.borrow_mut().clear();
1271
1272        notifier.set_value(&mut app, 3.0);
1273        assert_eq!(fired(&log), Vec::<String>::new());
1274    }
1275
1276    /// `change_notifier_test.dart`: "hasListeners".
1277    #[test]
1278    fn has_listeners() {
1279        let cell = AppCell::new();
1280        let mut app = cell.borrow_mut();
1281        let notifier = app.create(ValueNotifier::new(true));
1282        assert!(!app.get(&notifier).change_notifier.has_listeners());
1283
1284        let test1 = recording(&Log::default(), "test1");
1285        let test2 = recording(&Log::default(), "test2");
1286
1287        notifier.add_listener(&mut app, test1.clone());
1288        assert!(app.get(&notifier).change_notifier.has_listeners());
1289        notifier.add_listener(&mut app, test1.clone());
1290        assert!(app.get(&notifier).change_notifier.has_listeners());
1291        notifier.remove_listener(&mut app, &test1);
1292        assert!(app.get(&notifier).change_notifier.has_listeners());
1293        notifier.remove_listener(&mut app, &test1);
1294        assert!(!app.get(&notifier).change_notifier.has_listeners());
1295        notifier.add_listener(&mut app, test1.clone());
1296        assert!(app.get(&notifier).change_notifier.has_listeners());
1297        notifier.add_listener(&mut app, test2.clone());
1298        assert!(app.get(&notifier).change_notifier.has_listeners());
1299        notifier.remove_listener(&mut app, &test1);
1300        assert!(app.get(&notifier).change_notifier.has_listeners());
1301        notifier.remove_listener(&mut app, &test2);
1302        assert!(!app.get(&notifier).change_notifier.has_listeners());
1303    }
1304
1305    /// `change_notifier_test.dart`: "Calling debugAssertNotDisposed works as intended".
1306    #[test]
1307    fn debug_assert_not_disposed_returns_true_while_live() {
1308        let notifier = ChangeNotifierData::new();
1309        assert!(ChangeNotifierData::debug_assert_not_disposed(&notifier));
1310    }
1311
1312    #[test]
1313    #[cfg(debug_assertions)]
1314    #[should_panic(expected = "was used after being disposed")]
1315    fn debug_assert_not_disposed_panics_after_dispose() {
1316        let mut notifier = ChangeNotifierData::new();
1317        notifier.clear_for_dispose();
1318        ChangeNotifierData::debug_assert_not_disposed(&notifier);
1319    }
1320
1321    /// `change_notifier_test.dart`: "notifyListener can be called recursively".
1322    #[test]
1323    fn a_listener_assigns_through_its_owners_setter_and_the_dispatch_recurses() {
1324        let cell = AppCell::new();
1325        let mut app = cell.borrow_mut();
1326        let log = Log::default();
1327        let counter = app.create(ValueNotifier::new(0i32));
1328
1329        let listener1 = {
1330            let log = Rc::clone(&log);
1331            let counter = counter.handle();
1332            Listener::new(move |app: &mut App| {
1333                log.borrow_mut().push("listener1".to_string());
1334                if *app.get(counter).value() < 0 {
1335                    counter.set_value(app, 0);
1336                }
1337            })
1338        };
1339        counter.add_listener(&mut app, listener1);
1340
1341        counter.notify_listeners(&mut app);
1342        assert_eq!(fired(&log), ["listener1"]);
1343
1344        log.borrow_mut().clear();
1345        counter.set_value(&mut app, 3);
1346        assert_eq!(fired(&log), ["listener1"]);
1347
1348        log.borrow_mut().clear();
1349        counter.set_value(&mut app, -2);
1350        assert_eq!(fired(&log), ["listener1", "listener1"]);
1351        assert_eq!(*app.get(&counter).value(), 0);
1352    }
1353
1354    /// `change_notifier_test.dart`: "Remove Listeners while notifying on a list which will not resize".
1355    #[test]
1356    fn removing_listeners_while_notifying_on_a_list_which_will_not_resize() {
1357        let cell = AppCell::new();
1358        let mut app = cell.borrow_mut();
1359        let log = Log::default();
1360        let host = app.create(TestNotifier::default());
1361
1362        let names = [
1363            "listener0",
1364            "listener1",
1365            "listener2",
1366            "listener3",
1367            "listener4",
1368            "listener5",
1369            "listener6",
1370            "listener7",
1371            "listener8",
1372            "listener9",
1373            "listener10",
1374            "listener11",
1375        ];
1376        let listeners: Vec<Listener> = names.iter().map(|name| recording(&log, name)).collect();
1377
1378        let auto_remove = {
1379            let to_remove = [
1380                listeners[1].clone(),
1381                listeners[3].clone(),
1382                listeners[4].clone(),
1383            ];
1384            let auto_remove_slot: Rc<RefCell<Option<Listener>>> = Rc::new(RefCell::new(None));
1385            let slot = Rc::clone(&auto_remove_slot);
1386            let host = host.handle();
1387            let listener = Listener::new(move |app: &mut App| {
1388                let notifier = &mut app.get_mut(host).change_notifier;
1389                notifier.remove_listener(&to_remove[0]);
1390                notifier.remove_listener(&to_remove[1]);
1391                notifier.remove_listener(&to_remove[2]);
1392                let me = slot.borrow().clone().unwrap();
1393                notifier.remove_listener(&me);
1394            });
1395            *auto_remove_slot.borrow_mut() = Some(listener.clone());
1396            listener
1397        };
1398
1399        add(&mut app, &host, auto_remove);
1400        for listener in &listeners {
1401            add(&mut app, &host, listener.clone());
1402        }
1403
1404        let remaining = [
1405            "listener0",
1406            "listener2",
1407            "listener5",
1408            "listener6",
1409            "listener7",
1410            "listener8",
1411            "listener9",
1412            "listener10",
1413            "listener11",
1414        ];
1415
1416        notify(&mut app, &host);
1417        assert_eq!(fired(&log), remaining);
1418
1419        log.borrow_mut().clear();
1420        notify(&mut app, &host);
1421        assert_eq!(fired(&log), remaining);
1422
1423        for i in [0, 2, 5, 6, 7, 8, 9, 10, 11] {
1424            remove(&mut app, &host, &listeners[i]);
1425        }
1426        log.borrow_mut().clear();
1427        notify(&mut app, &host);
1428        assert_eq!(fired(&log), Vec::<String>::new());
1429    }
1430
1431    /// `change_notifier_test.dart`: "ChangeNotifier can not dispose in callback".
1432    #[test]
1433    #[cfg(debug_assertions)]
1434    fn dispose_during_notify_panics_and_does_not_finish_the_callback() {
1435        let cell = AppCell::new();
1436        let mut app = cell.borrow_mut();
1437        let host = app.create(TestNotifier::default());
1438        let finished = Rc::new(Cell::new(false));
1439        let finished_flag = Rc::clone(&finished);
1440        let listener = {
1441            let host = host.handle();
1442            Listener::new(move |app: &mut App| {
1443                ChangeNotifierData::dispose(app, host);
1444                finished_flag.set(true);
1445            })
1446        };
1447        add(&mut app, &host, listener);
1448
1449        let hook = silence_panic_hook();
1450        let panicked = catch_unwind(AssertUnwindSafe(|| {
1451            notify(&mut app, &host);
1452        }))
1453        .is_err();
1454        std::panic::set_hook(hook);
1455
1456        assert!(panicked);
1457        assert!(!finished.get());
1458        ChangeNotifierData::dispose(&mut app, &host);
1459    }
1460
1461    #[test]
1462    fn a_bare_change_notifier_handle_can_notify() {
1463        let cell = AppCell::new();
1464        let mut app = cell.borrow_mut();
1465        let log = Log::default();
1466        let on_undo = app.create(ChangeNotifierData::new());
1467
1468        on_undo.add_listener(&mut app, recording(&log, "undo"));
1469        on_undo.notify_listeners(&mut app);
1470
1471        assert_eq!(fired(&log), ["undo"]);
1472    }
1473
1474    #[test]
1475    fn a_panicking_listener_leaves_the_notifier_usable() {
1476        let cell = AppCell::new();
1477        let mut app = cell.borrow_mut();
1478        let log = Log::default();
1479        let host = app.create(TestNotifier::default());
1480
1481        let l0 = recording(&log, "l0");
1482        let l2 = recording(&log, "l2");
1483        let l3 = Listener::new(|_app: &mut App| panic!("bad listener"));
1484        let l1 = {
1485            let log = Rc::clone(&log);
1486            let (zero, two) = (l0.clone(), l2.clone());
1487            let host = host.handle();
1488            Listener::new(move |app: &mut App| {
1489                log.borrow_mut().push("l1".to_string());
1490                let notifier = &mut app.get_mut(host).change_notifier;
1491                notifier.remove_listener(&zero);
1492                notifier.remove_listener(&two);
1493            })
1494        };
1495
1496        add(&mut app, &host, l0);
1497        add(&mut app, &host, l1);
1498        add(&mut app, &host, l2);
1499        add(&mut app, &host, l3.clone());
1500
1501        let hook = silence_panic_hook();
1502        let panicked = catch_unwind(AssertUnwindSafe(|| {
1503            notify(&mut app, &host);
1504        }))
1505        .is_err();
1506        std::panic::set_hook(hook);
1507
1508        assert!(panicked);
1509        assert_eq!(fired(&log), ["l0", "l1"]);
1510        assert_eq!(
1511            app.get(&host)
1512                .change_notifier
1513                .notification_call_stack_depth
1514                .get(),
1515            0
1516        );
1517        assert_eq!(app.get(&host).change_notifier.count, 4);
1518
1519        app.get_mut(&host).change_notifier.remove_listener(&l3);
1520        assert_eq!(app.get(&host).change_notifier.count, 3);
1521        assert_eq!(
1522            app.get(&host).change_notifier.reentrantly_removed_listeners,
1523            2
1524        );
1525
1526        log.borrow_mut().clear();
1527        notify(&mut app, &host);
1528        assert_eq!(fired(&log), ["l1"]);
1529        assert_eq!(app.get(&host).change_notifier.count, 1);
1530        assert_eq!(
1531            app.get(&host).change_notifier.reentrantly_removed_listeners,
1532            0
1533        );
1534
1535        log.borrow_mut().clear();
1536        notify(&mut app, &host);
1537        assert_eq!(fired(&log), ["l1"]);
1538    }
1539
1540    #[test]
1541    fn a_panic_inside_a_nested_dispatch_still_pairs_the_depth_guards() {
1542        let cell = AppCell::new();
1543        let mut app = cell.borrow_mut();
1544        let log = Log::default();
1545        let host = app.create(TestNotifier::default());
1546        let inner_host = app.create(TestNotifier::default());
1547
1548        let doomed = recording(&log, "doomed");
1549        add(
1550            &mut app,
1551            inner_host.handle(),
1552            Listener::new(|_app: &mut App| panic!("inner listener")),
1553        );
1554
1555        let outer = {
1556            let log = Rc::clone(&log);
1557            let doomed = doomed.clone();
1558            let host = host.handle();
1559            let inner_host = inner_host.handle();
1560            Listener::new(move |app: &mut App| {
1561                log.borrow_mut().push("outer".to_string());
1562                app.get_mut(host).change_notifier.remove_listener(&doomed);
1563                notify(app, inner_host);
1564            })
1565        };
1566
1567        add(&mut app, &host, outer);
1568        add(&mut app, &host, doomed);
1569
1570        let hook = silence_panic_hook();
1571        let panicked = catch_unwind(AssertUnwindSafe(|| {
1572            notify(&mut app, &host);
1573        }))
1574        .is_err();
1575        std::panic::set_hook(hook);
1576
1577        assert!(panicked);
1578        assert_eq!(
1579            app.get(&host)
1580                .change_notifier
1581                .notification_call_stack_depth
1582                .get(),
1583            0
1584        );
1585        assert_eq!(
1586            app.get(&inner_host)
1587                .change_notifier
1588                .notification_call_stack_depth
1589                .get(),
1590            0
1591        );
1592
1593        let survivor = app.get(&host).change_notifier.listeners[0].clone().unwrap();
1594        remove(&mut app, &host, &survivor);
1595        log.borrow_mut().clear();
1596        notify(&mut app, &host);
1597        assert_eq!(
1598            app.get(&host).change_notifier.reentrantly_removed_listeners,
1599            0
1600        );
1601        assert!(!app.get(&host).change_notifier.has_listeners());
1602    }
1603
1604    #[test]
1605    fn dispose_clears_the_compaction_owed_by_a_panicked_dispatch() {
1606        let cell = AppCell::new();
1607        let mut app = cell.borrow_mut();
1608        let log = Log::default();
1609        let host = app.create(TestNotifier::default());
1610
1611        let doomed = recording(&log, "doomed");
1612        let saboteur = {
1613            let doomed = doomed.clone();
1614            let host = host.handle();
1615            Listener::new(move |app: &mut App| {
1616                app.get_mut(host).change_notifier.remove_listener(&doomed);
1617                panic!("bad listener");
1618            })
1619        };
1620        add(&mut app, &host, saboteur);
1621        add(&mut app, &host, doomed);
1622
1623        let hook = silence_panic_hook();
1624        let _ = catch_unwind(AssertUnwindSafe(|| {
1625            notify(&mut app, &host);
1626        }));
1627        std::panic::set_hook(hook);
1628
1629        assert_eq!(
1630            app.get(&host).change_notifier.reentrantly_removed_listeners,
1631            1
1632        );
1633
1634        ChangeNotifierData::dispose(&mut app, &host);
1635        assert_eq!(
1636            app.get(&host).change_notifier.reentrantly_removed_listeners,
1637            0
1638        );
1639        assert_eq!(app.get(&host).change_notifier.count, 0);
1640    }
1641
1642    #[test]
1643    #[cfg(not(debug_assertions))]
1644    fn a_disposed_notifier_reused_in_release_does_not_underflow() {
1645        let cell = AppCell::new();
1646        let mut app = cell.borrow_mut();
1647        let log = Log::default();
1648        let host = app.create(TestNotifier::default());
1649
1650        let doomed = recording(&log, "doomed");
1651        let saboteur = {
1652            let doomed = doomed.clone();
1653            let host = host.handle();
1654            Listener::new(move |app: &mut App| {
1655                app.get_mut(host).change_notifier.remove_listener(&doomed);
1656                panic!("bad listener");
1657            })
1658        };
1659        add(&mut app, &host, saboteur);
1660        add(&mut app, &host, doomed);
1661
1662        let hook = silence_panic_hook();
1663        let _ = catch_unwind(AssertUnwindSafe(|| {
1664            notify(&mut app, &host);
1665        }));
1666        std::panic::set_hook(hook);
1667
1668        ChangeNotifierData::dispose(&mut app, &host);
1669        add(&mut app, &host, recording(&log, "after"));
1670
1671        log.borrow_mut().clear();
1672        notify(&mut app, &host);
1673        assert_eq!(fired(&log), ["after"]);
1674        assert_eq!(app.get(&host).change_notifier.count, 1);
1675    }
1676}