Skip to main content

waft_foundation/
entity.rs

1//! App-level stores the user writes. Not a Flutter type and not how the framework is implemented.
2//!
3//! [`Handle`](crate::Handle) is the Flutter object: Copy, point access, no lease. [`Entity`] is
4//! Clone and refcounted; [`App::update`] leases `T` out of the map so the store can
5//! [`notify`](Context::notify) and [`emit`](Context::emit) without naming itself. Re-entering the
6//! same entity panics. Other entities and every Handle stay visible.
7//!
8//! An observer or listener lives in the list of the entity it watches, so it never holds that
9//! entity strongly: the entity would keep itself alive. Releasing an entity drops its observers
10//! and listeners.
11
12use std::any::{Any, TypeId, type_name};
13use std::cell::{Cell, RefCell};
14use std::collections::{HashMap, HashSet, VecDeque};
15use std::fmt::{self, Debug};
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::ops::{Deref, DerefMut};
19use std::rc::{Rc, Weak};
20
21use slotmap::{SlotMap, new_key_type};
22
23use crate::app::App;
24
25new_key_type! {
26    /// Identity of an [`Entity`]. Stale after the last strong handle drops and effects flush.
27    pub struct EntityId;
28}
29
30/// Entities a tracking frame read or updated. [`App::entity_track`] returns this.
31#[derive(Clone, Debug, Default)]
32pub struct TrackedSet {
33    ids: HashSet<EntityId>,
34}
35
36impl TrackedSet {
37    pub fn contains(&self, id: EntityId) -> bool {
38        self.ids.contains(&id)
39    }
40
41    pub fn is_empty(&self) -> bool {
42        self.ids.is_empty()
43    }
44
45    pub fn iter(&self) -> impl Iterator<Item = EntityId> + '_ {
46        self.ids.iter().copied()
47    }
48
49    pub fn len(&self) -> usize {
50        self.ids.len()
51    }
52}
53
54/// Marker: `T` can [`Context::emit`] events of type `E`.
55pub trait EventEmitter<E: 'static>: 'static {}
56
57/// A handle to an [`observe`](App::observe) or [`subscribe`](App::subscribe). Drop cancels it.
58/// [`detach`](Self::detach) keeps the callback until the emitter is gone, or, for one made through
59/// a [`Context`], the subscriber.
60#[must_use]
61pub struct Subscription {
62    cancel: Option<Rc<Cell<bool>>>,
63}
64
65impl Subscription {
66    /// Keep the callback after this handle is dropped.
67    pub fn detach(mut self) {
68        self.cancel.take();
69    }
70}
71
72impl Drop for Subscription {
73    fn drop(&mut self) {
74        if let Some(cancel) = self.cancel.take() {
75            cancel.set(true);
76        }
77    }
78}
79
80impl Debug for Subscription {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str("Subscription")
83    }
84}
85
86/// Strong, refcounted handle to a user store owned by [`App`].
87///
88/// An `Entity` is for the app's own data and the logic that changes it: the lines a note holds,
89/// the list a page shows, the ranking a client fetches. [`App::new_entity`] makes it,
90/// [`App::read`] and [`App::update`] read and change it, and [`Context::notify`] rebuilds the
91/// widgets that read it. It is not a Flutter object: a controller, an animation or a scroll
92/// position is a [`Ref`](crate::Ref), which [`App::create`] makes and which models Dart's
93/// reference to an object the framework keeps.
94pub struct Entity<T> {
95    id: EntityId,
96    keep: Rc<EntityKeep>,
97    entity_type: PhantomData<fn(T) -> T>,
98}
99
100/// Weak handle. [`upgrade`](Self::upgrade) fails as soon as the last [`Entity`] drops.
101pub struct WeakEntity<T> {
102    id: EntityId,
103    keep: Weak<EntityKeep>,
104    entity_type: PhantomData<fn(T) -> T>,
105}
106
107struct EntityKeep {
108    id: EntityId,
109    dropped: DroppedEntities,
110}
111
112impl Drop for EntityKeep {
113    fn drop(&mut self) {
114        self.dropped.push(self.id);
115    }
116}
117
118#[derive(Clone, Default)]
119struct DroppedEntities(Rc<RefCell<Vec<EntityId>>>);
120
121impl DroppedEntities {
122    fn push(&self, id: EntityId) {
123        self.0.borrow_mut().push(id);
124    }
125
126    fn take(&self) -> Vec<EntityId> {
127        std::mem::take(&mut *self.0.borrow_mut())
128    }
129}
130
131struct Slot {
132    type_name: &'static str,
133    type_id: TypeId,
134    value: Option<Box<dyn Any>>,
135    keep: Weak<EntityKeep>,
136}
137
138enum Effect {
139    Notify {
140        emitter: EntityId,
141    },
142    Emit {
143        emitter: EntityId,
144        event_type: TypeId,
145        event: Box<dyn Any>,
146    },
147}
148
149struct Observer {
150    active: bool,
151    cancelled: Rc<Cell<bool>>,
152    handler: Box<dyn FnMut(&mut App) -> bool>,
153}
154
155type EventHandler = Box<dyn FnMut(&mut App, &dyn Any) -> bool>;
156
157struct EventListener {
158    active: bool,
159    cancelled: Rc<Cell<bool>>,
160    event_type: TypeId,
161    handler: EventHandler,
162}
163
164pub(crate) struct EntityMap {
165    slots: SlotMap<EntityId, Slot>,
166    dropped: DroppedEntities,
167    tracking: Rc<RefCell<Vec<HashSet<EntityId>>>>,
168    update_depth: u32,
169    flushing: bool,
170    pending: VecDeque<Effect>,
171    pending_notifications: HashSet<EntityId>,
172    observers: HashMap<EntityId, Vec<Observer>>,
173    event_listeners: HashMap<EntityId, Vec<EventListener>>,
174}
175
176impl EntityMap {
177    pub(crate) fn new() -> EntityMap {
178        EntityMap {
179            slots: SlotMap::with_key(),
180            dropped: DroppedEntities::default(),
181            tracking: Rc::new(RefCell::new(Vec::new())),
182            update_depth: 0,
183            flushing: false,
184            pending: VecDeque::new(),
185            pending_notifications: HashSet::new(),
186            observers: HashMap::new(),
187            event_listeners: HashMap::new(),
188        }
189    }
190}
191
192impl<T> Entity<T> {
193    pub fn entity_id(&self) -> EntityId {
194        self.id
195    }
196
197    pub fn downgrade(&self) -> WeakEntity<T> {
198        WeakEntity {
199            id: self.id,
200            keep: Rc::downgrade(&self.keep),
201            entity_type: PhantomData,
202        }
203    }
204
205    /// Same as [`App::read`].
206    pub fn read<'a>(&self, app: &'a App) -> &'a T
207    where
208        T: 'static,
209    {
210        app.read(self)
211    }
212
213    /// Same as [`App::update`].
214    pub fn update<R>(&self, app: &mut App, f: impl FnOnce(&mut T, &mut Context<T>) -> R) -> R
215    where
216        T: 'static,
217    {
218        app.update(self, f)
219    }
220}
221
222impl<T> Clone for Entity<T> {
223    fn clone(&self) -> Entity<T> {
224        Entity {
225            id: self.id,
226            keep: Rc::clone(&self.keep),
227            entity_type: PhantomData,
228        }
229    }
230}
231
232impl<T> PartialEq for Entity<T> {
233    fn eq(&self, other: &Entity<T>) -> bool {
234        self.id == other.id
235    }
236}
237
238impl<T> Eq for Entity<T> {}
239
240impl<T> Hash for Entity<T> {
241    fn hash<H: Hasher>(&self, state: &mut H) {
242        self.id.hash(state);
243    }
244}
245
246impl<T> Debug for Entity<T> {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        write!(f, "Entity<{}>({:?})", type_name::<T>(), self.id)
249    }
250}
251
252impl<T> WeakEntity<T> {
253    pub fn entity_id(&self) -> EntityId {
254        self.id
255    }
256
257    pub fn upgrade(&self) -> Option<Entity<T>> {
258        self.keep.upgrade().map(|keep| Entity {
259            id: self.id,
260            keep,
261            entity_type: PhantomData,
262        })
263    }
264}
265
266impl<T> Clone for WeakEntity<T> {
267    fn clone(&self) -> WeakEntity<T> {
268        WeakEntity {
269            id: self.id,
270            keep: Weak::clone(&self.keep),
271            entity_type: PhantomData,
272        }
273    }
274}
275
276impl<T> Debug for WeakEntity<T> {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        write!(f, "WeakEntity<{}>({:?})", type_name::<T>(), self.id)
279    }
280}
281
282/// `&mut App` scoped to one entity so the store can notify and emit while `T` is leased.
283pub struct Context<'a, T> {
284    app: &'a mut App,
285    entity: WeakEntity<T>,
286}
287
288impl<T> Context<'_, T> {
289    fn new<'a>(app: &'a mut App, entity: WeakEntity<T>) -> Context<'a, T> {
290        Context { app, entity }
291    }
292
293    pub fn entity(&self) -> Entity<T> {
294        self.entity
295            .upgrade()
296            .expect("the entity is leased, so a strong handle exists")
297    }
298
299    pub fn weak_entity(&self) -> WeakEntity<T> {
300        self.entity.clone()
301    }
302
303    /// Untyped dirty: observers run, and elements that read this entity last build rebuild.
304    pub fn notify(&mut self) {
305        let id = self.entity.id;
306        self.app.queue_entity_notify(id);
307    }
308
309    pub fn emit<E>(&mut self, event: E)
310    where
311        T: EventEmitter<E>,
312        E: 'static,
313    {
314        let id = self.entity.id;
315        self.app.queue_entity_emit(id, event);
316    }
317
318    /// Holds neither entity: the callback ends when either goes.
319    pub fn observe<W: 'static>(
320        &mut self,
321        entity: &Entity<W>,
322        mut on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<T>) + 'static,
323    ) -> Subscription
324    where
325        T: 'static,
326    {
327        let this = self.weak_entity();
328        let watched = entity.downgrade();
329        self.app.observe_entity_id(entity.entity_id(), move |app| {
330            let (Some(this), Some(watched)) = (this.upgrade(), watched.upgrade()) else {
331                return false;
332            };
333            this.update(app, |this, cx| on_notify(this, watched, cx));
334            true
335        })
336    }
337
338    /// Holds neither entity: the callback ends when either goes.
339    pub fn subscribe<W, E>(
340        &mut self,
341        entity: &Entity<W>,
342        mut on_event: impl FnMut(&mut T, Entity<W>, &E, &mut Context<T>) + 'static,
343    ) -> Subscription
344    where
345        T: 'static,
346        W: EventEmitter<E> + 'static,
347        E: 'static,
348    {
349        let this = self.weak_entity();
350        let watched = entity.downgrade();
351        self.app
352            .subscribe_entity_id(entity.entity_id(), TypeId::of::<E>(), move |app, event| {
353                let (Some(this), Some(watched)) = (this.upgrade(), watched.upgrade()) else {
354                    return false;
355                };
356                let event = event
357                    .downcast_ref::<E>()
358                    .expect("subscriber event type matches the emitter");
359                this.update(app, |this, cx| on_event(this, watched, event, cx));
360                true
361            })
362    }
363}
364
365impl<T> Deref for Context<'_, T> {
366    type Target = App;
367
368    fn deref(&self) -> &App {
369        self.app
370    }
371}
372
373impl<T> DerefMut for Context<'_, T> {
374    fn deref_mut(&mut self) -> &mut App {
375        self.app
376    }
377}
378
379struct TrackFrame {
380    tracking: Rc<RefCell<Vec<HashSet<EntityId>>>>,
381    taken: bool,
382}
383
384impl TrackFrame {
385    fn finish(mut self) -> HashSet<EntityId> {
386        self.taken = true;
387        self.tracking
388            .borrow_mut()
389            .pop()
390            .expect("entity_track frame")
391    }
392}
393
394impl Drop for TrackFrame {
395    fn drop(&mut self) {
396        if !self.taken {
397            self.tracking.borrow_mut().pop();
398        }
399    }
400}
401
402impl App {
403    /// Opens a tracking frame. [`App::read`] and [`App::update`] record into it.
404    pub fn entity_track<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> (R, TrackedSet) {
405        self.entities.tracking.borrow_mut().push(HashSet::new());
406        let frame = TrackFrame {
407            tracking: Rc::clone(&self.entities.tracking),
408            taken: false,
409        };
410        let result = f(self);
411        (
412            result,
413            TrackedSet {
414                ids: frame.finish(),
415            },
416        )
417    }
418
419    /// Records a build dependency when a tracking frame is open.
420    pub fn read<'a, T: 'static>(&'a self, entity: &Entity<T>) -> &'a T {
421        self.record_entity_access(entity.id);
422        self.entity_ref(entity.id)
423    }
424
425    /// Leases `T` for the closure. Re-entering this entity panics.
426    pub fn update<T: 'static, R>(
427        &mut self,
428        entity: &Entity<T>,
429        f: impl FnOnce(&mut T, &mut Context<T>) -> R,
430    ) -> R {
431        self.record_entity_access(entity.id);
432        self.update_entity(entity, f)
433    }
434
435    pub fn new_entity<T: 'static>(
436        &mut self,
437        build: impl FnOnce(&mut Context<T>) -> T,
438    ) -> Entity<T> {
439        self.begin_entity_update();
440        let entity = self.reserve_entity::<T>();
441        let value = {
442            let mut cx = Context::new(self, entity.downgrade());
443            build(&mut cx)
444        };
445        self.insert_entity(&entity, value);
446        self.record_entity_access(entity.id);
447        self.end_entity_update();
448        entity
449    }
450
451    pub fn observe<T: 'static>(
452        &mut self,
453        entity: &Entity<T>,
454        mut on_notify: impl FnMut(&mut App) + 'static,
455    ) -> Subscription {
456        self.observe_entity_id(entity.id, move |app| {
457            on_notify(app);
458            true
459        })
460    }
461
462    pub fn subscribe<T, E>(
463        &mut self,
464        entity: &Entity<T>,
465        mut on_event: impl FnMut(&mut App, &E) + 'static,
466    ) -> Subscription
467    where
468        T: EventEmitter<E> + 'static,
469        E: 'static,
470    {
471        self.subscribe_entity_id(entity.id, TypeId::of::<E>(), move |app, event| {
472            let event = event
473                .downcast_ref::<E>()
474                .expect("subscriber event type matches the emitter");
475            on_event(app, event);
476            true
477        })
478    }
479
480    /// Runs queued notify/emit and activates subscribers registered since the last flush.
481    pub fn flush_entity_effects(&mut self) {
482        if self.entities.flushing {
483            return;
484        }
485        self.entities.flushing = true;
486        loop {
487            self.release_dropped_entities();
488            if let Some(effect) = self.entities.pending.pop_front() {
489                match effect {
490                    Effect::Notify { emitter } => self.apply_entity_notify(emitter),
491                    Effect::Emit {
492                        emitter,
493                        event_type,
494                        event,
495                    } => self.apply_entity_emit(emitter, event_type, &*event),
496                }
497                continue;
498            }
499            self.activate_entity_subscribers();
500            if self.entities.pending.is_empty() {
501                break;
502            }
503        }
504        self.entities.flushing = false;
505    }
506
507    pub(crate) fn record_entity_access(&self, id: EntityId) {
508        if let Some(frame) = self.entities.tracking.borrow_mut().last_mut() {
509            frame.insert(id);
510        }
511    }
512
513    pub fn observe_entity_id(
514        &mut self,
515        id: EntityId,
516        handler: impl FnMut(&mut App) -> bool + 'static,
517    ) -> Subscription {
518        let cancelled = Rc::new(Cell::new(false));
519        self.entities
520            .observers
521            .entry(id)
522            .or_default()
523            .push(Observer {
524                active: false,
525                cancelled: Rc::clone(&cancelled),
526                handler: Box::new(handler),
527            });
528        if self.entities.update_depth == 0 && !self.entities.flushing {
529            self.flush_entity_effects();
530        }
531        Subscription {
532            cancel: Some(cancelled),
533        }
534    }
535
536    fn subscribe_entity_id(
537        &mut self,
538        id: EntityId,
539        event_type: TypeId,
540        handler: impl FnMut(&mut App, &dyn Any) -> bool + 'static,
541    ) -> Subscription {
542        let cancelled = Rc::new(Cell::new(false));
543        self.entities
544            .event_listeners
545            .entry(id)
546            .or_default()
547            .push(EventListener {
548                active: false,
549                cancelled: Rc::clone(&cancelled),
550                event_type,
551                handler: Box::new(handler),
552            });
553        if self.entities.update_depth == 0 && !self.entities.flushing {
554            self.flush_entity_effects();
555        }
556        Subscription {
557            cancel: Some(cancelled),
558        }
559    }
560
561    fn begin_entity_update(&mut self) {
562        self.entities.update_depth += 1;
563    }
564
565    fn end_entity_update(&mut self) {
566        self.entities.update_depth = self.entities.update_depth.saturating_sub(1);
567        if self.entities.update_depth == 0 {
568            self.flush_entity_effects();
569        }
570    }
571
572    fn queue_entity_notify(&mut self, id: EntityId) {
573        if self.entities.pending_notifications.insert(id) {
574            self.entities
575                .pending
576                .push_back(Effect::Notify { emitter: id });
577        }
578        if self.entities.update_depth == 0 {
579            self.flush_entity_effects();
580        }
581    }
582
583    fn queue_entity_emit<E: 'static>(&mut self, id: EntityId, event: E) {
584        self.entities.pending.push_back(Effect::Emit {
585            emitter: id,
586            event_type: TypeId::of::<E>(),
587            event: Box::new(event),
588        });
589        if self.entities.update_depth == 0 {
590            self.flush_entity_effects();
591        }
592    }
593
594    fn activate_entity_subscribers(&mut self) {
595        for observers in self.entities.observers.values_mut() {
596            for observer in observers.iter_mut() {
597                if !observer.cancelled.get() {
598                    observer.active = true;
599                }
600            }
601        }
602        for listeners in self.entities.event_listeners.values_mut() {
603            for listener in listeners.iter_mut() {
604                if !listener.cancelled.get() {
605                    listener.active = true;
606                }
607            }
608        }
609    }
610
611    fn apply_entity_notify(&mut self, emitter: EntityId) {
612        self.entities.pending_notifications.remove(&emitter);
613        let mut observers = self.entities.observers.remove(&emitter).unwrap_or_default();
614        let mut i = 0;
615        while i < observers.len() {
616            let run = !observers[i].cancelled.get() && observers[i].active;
617            if run && !(observers[i].handler)(self) {
618                observers[i].cancelled.set(true);
619            }
620            if let Some(mut extra) = self.entities.observers.remove(&emitter) {
621                observers.append(&mut extra);
622            }
623            i += 1;
624        }
625        observers.retain(|observer| !observer.cancelled.get());
626        if !observers.is_empty() {
627            self.entities.observers.insert(emitter, observers);
628        }
629    }
630
631    fn apply_entity_emit(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
632        let mut listeners = self
633            .entities
634            .event_listeners
635            .remove(&emitter)
636            .unwrap_or_default();
637        let mut i = 0;
638        while i < listeners.len() {
639            let run = !listeners[i].cancelled.get()
640                && listeners[i].active
641                && listeners[i].event_type == event_type;
642            if run && !(listeners[i].handler)(self, event) {
643                listeners[i].cancelled.set(true);
644            }
645            if let Some(mut extra) = self.entities.event_listeners.remove(&emitter) {
646                listeners.append(&mut extra);
647            }
648            i += 1;
649        }
650        listeners.retain(|listener| !listener.cancelled.get());
651        if !listeners.is_empty() {
652            self.entities.event_listeners.insert(emitter, listeners);
653        }
654    }
655
656    /// Releases every entity whose last handle dropped, again until none is left: a released
657    /// value or callback can hold the last handle of another.
658    fn release_dropped_entities(&mut self) {
659        loop {
660            let dropped = self.entities.dropped.take();
661            if dropped.is_empty() {
662                break;
663            }
664            for id in dropped {
665                self.release_entity(id);
666            }
667        }
668    }
669
670    /// Drops the entity with every observer and listener registered on it.
671    fn release_entity(&mut self, id: EntityId) {
672        if self
673            .entities
674            .slots
675            .get(id)
676            .is_some_and(|slot| slot.keep.upgrade().is_some())
677        {
678            return;
679        }
680        self.entities.slots.remove(id);
681        self.entities.observers.remove(&id);
682        self.entities.event_listeners.remove(&id);
683        self.entities.pending_notifications.remove(&id);
684    }
685
686    fn reserve_entity<T: 'static>(&mut self) -> Entity<T> {
687        let dropped = self.entities.dropped.clone();
688        let id = self.entities.slots.insert(Slot {
689            type_name: type_name::<T>(),
690            type_id: TypeId::of::<T>(),
691            value: None,
692            keep: Weak::new(),
693        });
694        let keep = Rc::new(EntityKeep { id, dropped });
695        self.entities.slots[id].keep = Rc::downgrade(&keep);
696        Entity {
697            id,
698            keep,
699            entity_type: PhantomData,
700        }
701    }
702
703    fn insert_entity<T: 'static>(&mut self, entity: &Entity<T>, value: T) {
704        let slot = self
705            .entities
706            .slots
707            .get_mut(entity.id)
708            .expect("reserved entity");
709        assert!(slot.value.is_none(), "insert into an occupied entity slot");
710        slot.value = Some(Box::new(value));
711    }
712
713    fn entity_ref<T: 'static>(&self, id: EntityId) -> &T {
714        let slot = self
715            .entities
716            .slots
717            .get(id)
718            .unwrap_or_else(|| panic!("stale entity {}", type_name::<T>()));
719        assert_eq!(
720            slot.type_id,
721            TypeId::of::<T>(),
722            "entity type mismatch: stored {}, asked {}",
723            slot.type_name,
724            type_name::<T>()
725        );
726        let value = slot.value.as_ref().unwrap_or_else(|| {
727            panic!(
728                "cannot read {} while it is already being updated",
729                slot.type_name
730            )
731        });
732        value.downcast_ref::<T>().expect("entity type matches slot")
733    }
734
735    fn update_entity<T: 'static, R>(
736        &mut self,
737        entity: &Entity<T>,
738        f: impl FnOnce(&mut T, &mut Context<T>) -> R,
739    ) -> R {
740        self.begin_entity_update();
741        let mut value = self.take_entity::<T>(entity.id);
742        let result = {
743            let mut cx = Context::new(self, entity.downgrade());
744            f(&mut value, &mut cx)
745        };
746        self.put_entity(entity.id, value);
747        self.end_entity_update();
748        result
749    }
750
751    fn take_entity<T: 'static>(&mut self, id: EntityId) -> T {
752        let slot = self
753            .entities
754            .slots
755            .get_mut(id)
756            .unwrap_or_else(|| panic!("stale entity {}", type_name::<T>()));
757        assert_eq!(slot.type_id, TypeId::of::<T>());
758        let boxed = slot.value.take().unwrap_or_else(|| {
759            panic!(
760                "cannot update {} while it is already being updated",
761                slot.type_name
762            )
763        });
764        *boxed
765            .downcast::<T>()
766            .unwrap_or_else(|_| panic!("entity type matches slot"))
767    }
768
769    fn put_entity<T: 'static>(&mut self, id: EntityId, value: T) {
770        let slot = self
771            .entities
772            .slots
773            .get_mut(id)
774            .expect("entity slot exists for a live lease");
775        slot.value = Some(Box::new(value));
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use crate::AppCell;
783    use std::rc::Rc;
784
785    struct Counter {
786        count: i32,
787    }
788
789    struct Doubler {
790        count: i32,
791    }
792
793    struct Changed {
794        by: i32,
795    }
796
797    impl EventEmitter<Changed> for Counter {}
798
799    #[test]
800    fn read_and_update_round_trip() {
801        let cell = AppCell::new();
802        let mut app = cell.borrow_mut();
803        let counter = app.new_entity(|_cx| Counter { count: 1 });
804        assert_eq!(counter.read(&app).count, 1);
805        counter.update(&mut app, |counter, cx| {
806            counter.count += 1;
807            cx.notify();
808        });
809        assert_eq!(counter.read(&app).count, 2);
810    }
811
812    #[test]
813    #[should_panic(expected = "already being updated")]
814    fn reentering_the_same_entity_panics() {
815        let cell = AppCell::new();
816        let mut app = cell.borrow_mut();
817        let counter = app.new_entity(|_cx| Counter { count: 0 });
818        counter.update(&mut app, |_counter, cx| {
819            let this = cx.entity();
820            this.read(cx);
821        });
822    }
823
824    #[test]
825    fn entity_track_records_reads() {
826        let cell = AppCell::new();
827        let mut app = cell.borrow_mut();
828        let counter = app.new_entity(|_cx| Counter { count: 3 });
829        let other = app.new_entity(|_cx| Counter { count: 0 });
830        let (n, tracked) = app.entity_track(|app| counter.read(app).count);
831        assert_eq!(n, 3);
832        assert!(tracked.contains(counter.entity_id()));
833        assert!(!tracked.contains(other.entity_id()));
834    }
835
836    #[test]
837    fn observe_runs_after_notify() {
838        let cell = AppCell::new();
839        let mut app = cell.borrow_mut();
840        let first = app.new_entity(|_cx| Counter { count: 1 });
841        let second = app.new_entity(|cx| {
842            cx.observe(&first, |second: &mut Doubler, first, cx| {
843                second.count = first.read(cx).count * 2;
844            })
845            .detach();
846            Doubler { count: 0 }
847        });
848        first.update(&mut app, |counter, cx| {
849            counter.count = 4;
850            cx.notify();
851        });
852        assert_eq!(second.read(&app).count, 8);
853    }
854
855    #[test]
856    fn a_subscriber_registered_during_notify_does_not_see_that_notify() {
857        let cell = AppCell::new();
858        let mut app = cell.borrow_mut();
859        let seen = Rc::new(Cell::new(0));
860        let first = app.new_entity(|_cx| Counter { count: 0 });
861        let seen_for_late = Rc::clone(&seen);
862        first.update(&mut app, |counter, cx| {
863            counter.count = 1;
864            let late = cx.entity();
865            cx.observe(&late, {
866                let seen = Rc::clone(&seen_for_late);
867                move |_, _, _| seen.set(seen.get() + 1)
868            })
869            .detach();
870            cx.notify();
871        });
872        assert_eq!(seen.get(), 0);
873        first.update(&mut app, |_counter, cx| cx.notify());
874        assert_eq!(seen.get(), 1);
875    }
876
877    #[test]
878    fn emit_reaches_a_typed_subscriber() {
879        let cell = AppCell::new();
880        let mut app = cell.borrow_mut();
881        let first = app.new_entity(|_cx| Counter { count: 0 });
882        let second = app.new_entity(|cx| {
883            cx.subscribe(
884                &first,
885                |second: &mut Doubler, _first, event: &Changed, _cx| {
886                    second.count += event.by;
887                },
888            )
889            .detach();
890            Doubler { count: 0 }
891        });
892        first.update(&mut app, |_counter, cx| {
893            cx.emit(Changed { by: 5 });
894        });
895        assert_eq!(second.read(&app).count, 5);
896    }
897
898    #[test]
899    fn dropping_the_last_handle_reaps_the_entity() {
900        let cell = AppCell::new();
901        let mut app = cell.borrow_mut();
902        let counter = app.new_entity(|_cx| Counter { count: 1 });
903        let weak = counter.downgrade();
904        drop(counter);
905        app.flush_entity_effects();
906        assert!(weak.upgrade().is_none());
907    }
908
909    #[test]
910    fn dropping_a_subscription_stops_callbacks() {
911        let cell = AppCell::new();
912        let mut app = cell.borrow_mut();
913        let seen = Rc::new(Cell::new(0));
914        let counter = app.new_entity(|_cx| Counter { count: 0 });
915        let sub = {
916            let seen = Rc::clone(&seen);
917            app.observe(&counter, move |_app| seen.set(seen.get() + 1))
918        };
919        counter.update(&mut app, |_c, cx| cx.notify());
920        assert_eq!(seen.get(), 1);
921        drop(sub);
922        counter.update(&mut app, |_c, cx| cx.notify());
923        assert_eq!(seen.get(), 1);
924    }
925
926    #[test]
927    fn an_observed_entity_goes_with_its_last_handle() {
928        assert_a_watched_counter_goes_with_its_last_handle(observe_counter, Subscription::detach);
929        assert_a_watched_counter_goes_with_its_last_handle(observe_counter, drop);
930    }
931
932    #[test]
933    fn a_subscribed_entity_goes_with_its_last_handle() {
934        assert_a_watched_counter_goes_with_its_last_handle(
935            subscribe_to_counter,
936            Subscription::detach,
937        );
938        assert_a_watched_counter_goes_with_its_last_handle(subscribe_to_counter, drop);
939    }
940
941    #[test]
942    fn an_entity_only_a_released_one_held_goes_in_the_same_flush() {
943        struct Holder {
944            _counter: Entity<Counter>,
945        }
946        let cell = AppCell::new();
947        let mut app = cell.borrow_mut();
948        let counter = app.new_entity(|_cx| Counter { count: 0 });
949        let _doubler = app.new_entity(|cx| {
950            observe_counter(cx, &counter).detach();
951            Doubler { count: 0 }
952        });
953        let counter_id = counter.entity_id();
954        assert!(registered_on(&app, counter_id));
955        let holder = app.new_entity(|_cx| Holder { _counter: counter });
956        drop(holder);
957        app.flush_entity_effects();
958        assert!(is_released(&app, counter_id));
959    }
960
961    fn observe_counter(cx: &mut Context<Doubler>, counter: &Entity<Counter>) -> Subscription {
962        cx.observe(counter, |_doubler, _counter, _cx| {})
963    }
964
965    fn subscribe_to_counter(cx: &mut Context<Doubler>, counter: &Entity<Counter>) -> Subscription {
966        cx.subscribe(counter, |_doubler, _counter, _event: &Changed, _cx| {})
967    }
968
969    /// A doubler watches a counter through `watch` and ends the subscription with `end`; letting
970    /// go of the counter releases it with what was registered on it, while the doubler lives.
971    fn assert_a_watched_counter_goes_with_its_last_handle(
972        watch: fn(&mut Context<Doubler>, &Entity<Counter>) -> Subscription,
973        end: fn(Subscription),
974    ) {
975        let cell = AppCell::new();
976        let mut app = cell.borrow_mut();
977        let counter = app.new_entity(|_cx| Counter { count: 0 });
978        let _doubler = app.new_entity(|cx| {
979            end(watch(cx, &counter));
980            Doubler { count: 0 }
981        });
982        let counter_id = counter.entity_id();
983        assert!(registered_on(&app, counter_id));
984        let weak_counter = counter.downgrade();
985        drop(counter);
986        app.flush_entity_effects();
987        assert!(weak_counter.upgrade().is_none());
988        assert!(is_released(&app, counter_id));
989    }
990
991    /// Whether nothing of the entity is left: neither its slot nor what was registered on it.
992    fn is_released(app: &App, id: EntityId) -> bool {
993        !app.entities.slots.contains_key(id) && !registered_on(app, id)
994    }
995
996    fn registered_on(app: &App, id: EntityId) -> bool {
997        app.entities.observers.contains_key(&id) || app.entities.event_listeners.contains_key(&id)
998    }
999}