Skip to main content

wgpui/app/
entity_map.rs

1use crate::{App, AppContext, GpuiBorrow, VisualContext, Window, seal::Sealed};
2use anyhow::{Context as _, Result};
3use collections::FxHashSet;
4use derive_more::{Deref, DerefMut};
5use parking_lot::{RwLock, RwLockUpgradableReadGuard};
6use slotmap::{KeyData, SecondaryMap, SlotMap};
7use std::{
8    any::{Any, TypeId, type_name},
9    cell::RefCell,
10    cmp::Ordering,
11    fmt::{self, Display},
12    hash::{Hash, Hasher},
13    marker::PhantomData,
14    mem,
15    num::NonZeroU64,
16    sync::{
17        Arc, Weak,
18        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
19    },
20    thread::panicking,
21};
22
23use super::Context;
24use crate::util::atomic_incr_if_not_zero;
25#[cfg(any(test, feature = "leak-detection"))]
26use collections::HashMap;
27
28slotmap::new_key_type! {
29    /// A unique identifier for a entity across the application.
30    pub struct EntityId;
31}
32
33impl From<u64> for EntityId {
34    fn from(value: u64) -> Self {
35        Self(KeyData::from_ffi(value))
36    }
37}
38
39impl EntityId {
40    /// Converts this entity id to a [NonZeroU64]
41    pub fn as_non_zero_u64(self) -> NonZeroU64 {
42        NonZeroU64::new(self.0.as_ffi()).unwrap()
43    }
44
45    /// Converts this entity id to a [u64]
46    pub fn as_u64(self) -> u64 {
47        self.0.as_ffi()
48    }
49}
50
51impl Display for EntityId {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "{}", self.as_u64())
54    }
55}
56
57/// The entity identities alive when a leak-detection checkpoint was captured.
58#[cfg(any(test, feature = "leak-detection"))]
59pub struct LeakDetectorSnapshot {
60    entity_ids: FxHashSet<EntityId>,
61}
62
63pub(crate) struct EntityMap {
64    entities: SecondaryMap<EntityId, Box<dyn Any>>,
65    pub accessed_entities: RefCell<FxHashSet<EntityId>>,
66    ref_counts: Arc<RwLock<EntityRefCounts>>,
67}
68
69pub(crate) struct EntityRefCounts {
70    counts: SlotMap<EntityId, AtomicUsize>,
71    dropped_entity_ids: Vec<EntityId>,
72    #[cfg(any(test, feature = "leak-detection"))]
73    leak_detector: LeakDetector,
74}
75
76impl EntityMap {
77    pub fn new() -> Self {
78        Self {
79            entities: SecondaryMap::new(),
80            accessed_entities: RefCell::new(FxHashSet::default()),
81            ref_counts: Arc::new(RwLock::new(EntityRefCounts {
82                counts: SlotMap::with_key(),
83                dropped_entity_ids: Vec::new(),
84                #[cfg(any(test, feature = "leak-detection"))]
85                leak_detector: LeakDetector {
86                    next_handle_id: 0,
87                    entity_handles: HashMap::default(),
88                },
89            })),
90        }
91    }
92
93    /// Returns a handle to the ref counts for test cleanup.
94    pub fn ref_counts_drop_handle(&self) -> Arc<RwLock<EntityRefCounts>> {
95        self.ref_counts.clone()
96    }
97
98    #[cfg(any(test, feature = "leak-detection"))]
99    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
100        let counts = self.ref_counts.read();
101        LeakDetectorSnapshot {
102            entity_ids: counts
103                .leak_detector
104                .entity_handles
105                .iter()
106                .filter(|(_, handles)| !handles.is_empty())
107                .map(|(id, _)| *id)
108                .collect(),
109        }
110    }
111
112    #[cfg(any(test, feature = "leak-detection"))]
113    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
114        let counts = self.ref_counts.read();
115        let leaked: Vec<_> = counts
116            .leak_detector
117            .entity_handles
118            .iter()
119            .filter(|(id, handles)| !snapshot.entity_ids.contains(id) && !handles.is_empty())
120            .map(|(id, handles)| format!("{id:?}: {} live handles", handles.len()))
121            .collect();
122        assert!(
123            leaked.is_empty(),
124            "new entity leaks since checkpoint: {}",
125            leaked.join(", ")
126        );
127    }
128
129    /// Reserve a slot for an entity, which you can subsequently use with `insert`.
130    pub fn reserve<T: 'static>(&self) -> Slot<T> {
131        let id = self.ref_counts.write().counts.insert(1.into());
132        Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
133    }
134
135    /// Insert an entity into a slot obtained by calling `reserve`.
136    pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
137    where
138        T: 'static,
139    {
140        let mut accessed_entities = self.accessed_entities.borrow_mut();
141        accessed_entities.insert(slot.entity_id);
142
143        let handle = slot.0;
144        self.entities.insert(handle.entity_id, Box::new(entity));
145        handle
146    }
147
148    /// Move an entity to the stack.
149    #[track_caller]
150    pub fn lease<T>(&mut self, pointer: &Entity<T>) -> Lease<T> {
151        self.assert_valid_context(pointer);
152        let mut accessed_entities = self.accessed_entities.borrow_mut();
153        accessed_entities.insert(pointer.entity_id);
154
155        let entity = Some(
156            self.entities
157                .remove(pointer.entity_id)
158                .unwrap_or_else(|| double_lease_panic::<T>("update")),
159        );
160        Lease {
161            entity,
162            id: pointer.entity_id,
163            entity_type: PhantomData,
164        }
165    }
166
167    /// Returns an entity after moving it to the stack.
168    pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
169        self.entities.insert(lease.id, lease.entity.take().unwrap());
170    }
171
172    pub fn read<T: 'static>(&self, entity: &Entity<T>) -> &T {
173        self.assert_valid_context(entity);
174        let mut accessed_entities = self.accessed_entities.borrow_mut();
175        accessed_entities.insert(entity.entity_id);
176
177        self.entities
178            .get(entity.entity_id)
179            .and_then(|entity| entity.downcast_ref())
180            .unwrap_or_else(|| double_lease_panic::<T>("read"))
181    }
182
183    fn assert_valid_context(&self, entity: &AnyEntity) {
184        debug_assert!(
185            Weak::ptr_eq(&entity.entity_map, &Arc::downgrade(&self.ref_counts)),
186            "used a entity with the wrong context"
187        );
188    }
189
190    pub fn extend_accessed(&mut self, entities: &FxHashSet<EntityId>) {
191        self.accessed_entities
192            .borrow_mut()
193            .extend(entities.iter().copied());
194    }
195
196    pub fn clear_accessed(&mut self) {
197        self.accessed_entities.borrow_mut().clear();
198    }
199
200    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
201        let mut ref_counts = self.ref_counts.write();
202        let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
203        let mut accessed_entities = self.accessed_entities.borrow_mut();
204
205        dropped_entity_ids
206            .into_iter()
207            .filter_map(|entity_id| {
208                let count = ref_counts.counts.remove(entity_id).unwrap();
209                debug_assert_eq!(
210                    count.load(SeqCst),
211                    0,
212                    "dropped an entity that was referenced"
213                );
214                accessed_entities.remove(&entity_id);
215                // If the EntityId was allocated with `Context::reserve`,
216                // the entity may not have been inserted.
217                Some((entity_id, self.entities.remove(entity_id)?))
218            })
219            .collect()
220    }
221}
222
223#[track_caller]
224fn double_lease_panic<T>(operation: &str) -> ! {
225    panic!(
226        "cannot {operation} {} while it is already being updated",
227        std::any::type_name::<T>()
228    )
229}
230
231pub(crate) struct Lease<T> {
232    entity: Option<Box<dyn Any>>,
233    pub id: EntityId,
234    entity_type: PhantomData<T>,
235}
236
237impl<T: 'static> core::ops::Deref for Lease<T> {
238    type Target = T;
239
240    fn deref(&self) -> &Self::Target {
241        self.entity.as_ref().unwrap().downcast_ref().unwrap()
242    }
243}
244
245impl<T: 'static> core::ops::DerefMut for Lease<T> {
246    fn deref_mut(&mut self) -> &mut Self::Target {
247        self.entity.as_mut().unwrap().downcast_mut().unwrap()
248    }
249}
250
251impl<T> Drop for Lease<T> {
252    fn drop(&mut self) {
253        if self.entity.is_some() && !panicking() {
254            panic!("Leases must be ended with EntityMap::end_lease")
255        }
256    }
257}
258
259#[derive(Deref, DerefMut)]
260pub(crate) struct Slot<T>(Entity<T>);
261
262/// A dynamically typed reference to a entity, which can be downcast into a `Entity<T>`.
263pub struct AnyEntity {
264    pub(crate) entity_id: EntityId,
265    pub(crate) entity_type: TypeId,
266    entity_map: Weak<RwLock<EntityRefCounts>>,
267    #[cfg(any(test, feature = "leak-detection"))]
268    handle_id: HandleId,
269}
270
271impl AnyEntity {
272    fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
273        Self {
274            entity_id: id,
275            entity_type,
276            #[cfg(any(test, feature = "leak-detection"))]
277            handle_id: entity_map
278                .clone()
279                .upgrade()
280                .unwrap()
281                .write()
282                .leak_detector
283                .handle_created(id),
284            entity_map,
285        }
286    }
287
288    /// Returns the id associated with this entity.
289    #[inline]
290    pub fn entity_id(&self) -> EntityId {
291        self.entity_id
292    }
293
294    /// Returns the [TypeId] associated with this entity.
295    #[inline]
296    pub fn entity_type(&self) -> TypeId {
297        self.entity_type
298    }
299
300    /// Converts this entity handle into a weak variant, which does not prevent it from being released.
301    pub fn downgrade(&self) -> AnyWeakEntity {
302        AnyWeakEntity {
303            entity_id: self.entity_id,
304            entity_type: self.entity_type,
305            entity_ref_counts: self.entity_map.clone(),
306        }
307    }
308
309    /// Converts this entity handle into a strongly-typed entity handle of the given type.
310    /// If this entity handle is not of the specified type, returns itself as an error variant.
311    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
312        if TypeId::of::<T>() == self.entity_type {
313            Ok(Entity {
314                any_entity: self,
315                entity_type: PhantomData,
316            })
317        } else {
318            Err(self)
319        }
320    }
321}
322
323impl Clone for AnyEntity {
324    fn clone(&self) -> Self {
325        if let Some(entity_map) = self.entity_map.upgrade() {
326            let entity_map = entity_map.read();
327            let count = entity_map
328                .counts
329                .get(self.entity_id)
330                .expect("detected over-release of a entity");
331            let prev_count = count.fetch_add(1, SeqCst);
332            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
333        }
334
335        Self {
336            entity_id: self.entity_id,
337            entity_type: self.entity_type,
338            entity_map: self.entity_map.clone(),
339            #[cfg(any(test, feature = "leak-detection"))]
340            handle_id: self
341                .entity_map
342                .upgrade()
343                .unwrap()
344                .write()
345                .leak_detector
346                .handle_created(self.entity_id),
347        }
348    }
349}
350
351impl Drop for AnyEntity {
352    fn drop(&mut self) {
353        if let Some(entity_map) = self.entity_map.upgrade() {
354            let entity_map = entity_map.upgradable_read();
355            let count = entity_map
356                .counts
357                .get(self.entity_id)
358                .expect("detected over-release of a handle.");
359            let prev_count = count.fetch_sub(1, SeqCst);
360            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
361            if prev_count == 1 {
362                // We were the last reference to this entity, so we can remove it.
363                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
364                entity_map.dropped_entity_ids.push(self.entity_id);
365            }
366        }
367
368        #[cfg(any(test, feature = "leak-detection"))]
369        if let Some(entity_map) = self.entity_map.upgrade() {
370            entity_map
371                .write()
372                .leak_detector
373                .handle_released(self.entity_id, self.handle_id)
374        }
375    }
376}
377
378impl<T> From<Entity<T>> for AnyEntity {
379    #[inline]
380    fn from(entity: Entity<T>) -> Self {
381        entity.any_entity
382    }
383}
384
385impl Hash for AnyEntity {
386    #[inline]
387    fn hash<H: Hasher>(&self, state: &mut H) {
388        self.entity_id.hash(state);
389    }
390}
391
392impl PartialEq for AnyEntity {
393    #[inline]
394    fn eq(&self, other: &Self) -> bool {
395        self.entity_id == other.entity_id
396    }
397}
398
399impl Eq for AnyEntity {}
400
401impl Ord for AnyEntity {
402    #[inline]
403    fn cmp(&self, other: &Self) -> Ordering {
404        self.entity_id.cmp(&other.entity_id)
405    }
406}
407
408impl PartialOrd for AnyEntity {
409    #[inline]
410    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
411        Some(self.cmp(other))
412    }
413}
414
415impl std::fmt::Debug for AnyEntity {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        f.debug_struct("AnyEntity")
418            .field("entity_id", &self.entity_id.as_u64())
419            .finish()
420    }
421}
422
423/// A strong, well-typed reference to a struct which is managed
424/// by WGPUI
425#[derive(Deref, DerefMut)]
426pub struct Entity<T> {
427    #[deref]
428    #[deref_mut]
429    pub(crate) any_entity: AnyEntity,
430    pub(crate) entity_type: PhantomData<fn(T) -> T>,
431}
432
433impl<T> Sealed for Entity<T> {}
434
435impl<T: 'static> Entity<T> {
436    #[inline]
437    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
438    where
439        T: 'static,
440    {
441        Self {
442            any_entity: AnyEntity::new(id, TypeId::of::<T>(), entity_map),
443            entity_type: PhantomData,
444        }
445    }
446
447    /// Get the entity ID associated with this entity
448    #[inline]
449    pub fn entity_id(&self) -> EntityId {
450        self.any_entity.entity_id
451    }
452
453    /// Downgrade this entity pointer to a non-retaining weak pointer
454    #[inline]
455    pub fn downgrade(&self) -> WeakEntity<T> {
456        WeakEntity {
457            any_entity: self.any_entity.downgrade(),
458            entity_type: self.entity_type,
459        }
460    }
461
462    /// Convert this into a dynamically typed entity.
463    #[inline]
464    pub fn into_any(self) -> AnyEntity {
465        self.any_entity
466    }
467
468    /// Grab a reference to this entity from the context.
469    #[inline]
470    pub fn read<'a>(&self, cx: &'a App) -> &'a T {
471        cx.entities.read(self)
472    }
473
474    /// Read the entity referenced by this handle with the given function.
475    #[inline]
476    pub fn read_with<R, C: AppContext>(
477        &self,
478        cx: &C,
479        f: impl FnOnce(&T, &App) -> R,
480    ) -> C::Result<R> {
481        cx.read_entity(self, f)
482    }
483
484    /// Updates the entity referenced by this handle with the given function.
485    #[inline]
486    pub fn update<R, C: AppContext>(
487        &self,
488        cx: &mut C,
489        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
490    ) -> C::Result<R> {
491        cx.update_entity(self, update)
492    }
493
494    /// Updates the entity referenced by this handle with the given function.
495    #[inline]
496    pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> C::Result<GpuiBorrow<'a, T>> {
497        cx.as_mut(self)
498    }
499
500    /// Updates the entity referenced by this handle with the given function.
501    pub fn write<C: AppContext>(&self, cx: &mut C, value: T) -> C::Result<()> {
502        self.update(cx, |entity, cx| {
503            *entity = value;
504            cx.notify();
505        })
506    }
507
508    /// Updates the entity referenced by this handle with the given function if
509    /// the referenced entity still exists, within a visual context that has a window.
510    /// Returns an error if the entity has been released.
511    #[inline]
512    pub fn update_in<R, C: VisualContext>(
513        &self,
514        cx: &mut C,
515        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
516    ) -> C::Result<R> {
517        cx.update_window_entity(self, update)
518    }
519}
520
521impl<T> Clone for Entity<T> {
522    #[inline]
523    fn clone(&self) -> Self {
524        Self {
525            any_entity: self.any_entity.clone(),
526            entity_type: self.entity_type,
527        }
528    }
529}
530
531impl<T> std::fmt::Debug for Entity<T> {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        f.debug_struct("Entity")
534            .field("entity_id", &self.any_entity.entity_id)
535            .field("entity_type", &type_name::<T>())
536            .finish()
537    }
538}
539
540impl<T> Hash for Entity<T> {
541    #[inline]
542    fn hash<H: Hasher>(&self, state: &mut H) {
543        self.any_entity.hash(state);
544    }
545}
546
547impl<T> PartialEq for Entity<T> {
548    #[inline]
549    fn eq(&self, other: &Self) -> bool {
550        self.any_entity == other.any_entity
551    }
552}
553
554impl<T> Eq for Entity<T> {}
555
556impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
557    #[inline]
558    fn eq(&self, other: &WeakEntity<T>) -> bool {
559        self.any_entity.entity_id() == other.entity_id()
560    }
561}
562
563impl<T: 'static> Ord for Entity<T> {
564    #[inline]
565    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
566        self.entity_id().cmp(&other.entity_id())
567    }
568}
569
570impl<T: 'static> PartialOrd for Entity<T> {
571    #[inline]
572    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
573        Some(self.cmp(other))
574    }
575}
576
577/// A type erased, weak reference to a entity.
578#[derive(Clone)]
579pub struct AnyWeakEntity {
580    pub(crate) entity_id: EntityId,
581    entity_type: TypeId,
582    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
583}
584
585impl AnyWeakEntity {
586    /// Get the entity ID associated with this weak reference.
587    #[inline]
588    pub fn entity_id(&self) -> EntityId {
589        self.entity_id
590    }
591
592    /// Check if this weak handle can be upgraded, or if the entity has already been dropped
593    pub fn is_upgradable(&self) -> bool {
594        let ref_count = self
595            .entity_ref_counts
596            .upgrade()
597            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
598            .unwrap_or(0);
599        ref_count > 0
600    }
601
602    /// Upgrade this weak entity reference to a strong reference.
603    pub fn upgrade(&self) -> Option<AnyEntity> {
604        let ref_counts = &self.entity_ref_counts.upgrade()?;
605        let ref_counts = ref_counts.read();
606        let ref_count = ref_counts.counts.get(self.entity_id)?;
607
608        if atomic_incr_if_not_zero(ref_count) == 0 {
609            // entity_id is in dropped_entity_ids
610            return None;
611        }
612        drop(ref_counts);
613
614        Some(AnyEntity {
615            entity_id: self.entity_id,
616            entity_type: self.entity_type,
617            entity_map: self.entity_ref_counts.clone(),
618            #[cfg(any(test, feature = "leak-detection"))]
619            handle_id: self
620                .entity_ref_counts
621                .upgrade()
622                .unwrap()
623                .write()
624                .leak_detector
625                .handle_created(self.entity_id),
626        })
627    }
628
629    /// Asserts that the entity referenced by this weak handle has been fully released.
630    ///
631    /// # Example
632    ///
633    /// ```ignore
634    /// let entity = cx.new(|_| MyEntity::new());
635    /// let weak = entity.downgrade();
636    /// drop(entity);
637    ///
638    /// // Verify the entity was released
639    /// weak.assert_released();
640    /// ```
641    ///
642    /// # Debugging Leaks
643    ///
644    /// If this method panics due to leaked handles, set the `LEAK_BACKTRACE` environment
645    /// variable to see where the leaked handles were allocated:
646    ///
647    /// ```bash
648    /// LEAK_BACKTRACE=1 cargo test my_test
649    /// ```
650    ///
651    /// # Panics
652    ///
653    /// - Panics if any strong handles to the entity are still alive.
654    /// - Panics if the entity was recently dropped but cleanup hasn't completed yet
655    ///   (resources are retained until the end of the effect cycle).
656    #[cfg(any(test, feature = "leak-detection"))]
657    pub fn assert_released(&self) {
658        self.entity_ref_counts
659            .upgrade()
660            .unwrap()
661            .write()
662            .leak_detector
663            .assert_released(self.entity_id);
664
665        if self
666            .entity_ref_counts
667            .upgrade()
668            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
669            .is_some()
670        {
671            panic!(
672                "entity was recently dropped but resources are retained until the end of the effect cycle."
673            )
674        }
675    }
676
677    /// Creates a weak entity that can never be upgraded.
678    pub fn new_invalid() -> Self {
679        /// To hold the invariant that all ids are unique, and considering that slotmap
680        /// increases their IDs from `0`, we can decrease ours from `u64::MAX` so these
681        /// two will never conflict (u64 is way too large).
682        static UNIQUE_NON_CONFLICTING_ID_GENERATOR: AtomicU64 = AtomicU64::new(u64::MAX);
683        let entity_id = UNIQUE_NON_CONFLICTING_ID_GENERATOR.fetch_sub(1, SeqCst);
684
685        Self {
686            // Safety:
687            //   Docs say this is safe but can be unspecified if slotmap changes the representation
688            //   after `1.0.7`, that said, providing a valid entity_id here is not necessary as long
689            //   as we guarantee that `entity_id` is never used if `entity_ref_counts` equals
690            //   to `Weak::new()` (that is, it's unable to upgrade), that is the invariant that
691            //   actually needs to be hold true.
692            //
693            //   And there is no sane reason to read an entity slot if `entity_ref_counts` can't be
694            //   read in the first place, so we're good!
695            entity_id: entity_id.into(),
696            entity_type: TypeId::of::<()>(),
697            entity_ref_counts: Weak::new(),
698        }
699    }
700}
701
702impl std::fmt::Debug for AnyWeakEntity {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        f.debug_struct(type_name::<Self>())
705            .field("entity_id", &self.entity_id)
706            .field("entity_type", &self.entity_type)
707            .finish()
708    }
709}
710
711impl<T> From<WeakEntity<T>> for AnyWeakEntity {
712    #[inline]
713    fn from(entity: WeakEntity<T>) -> Self {
714        entity.any_entity
715    }
716}
717
718impl Hash for AnyWeakEntity {
719    #[inline]
720    fn hash<H: Hasher>(&self, state: &mut H) {
721        self.entity_id.hash(state);
722    }
723}
724
725impl PartialEq for AnyWeakEntity {
726    #[inline]
727    fn eq(&self, other: &Self) -> bool {
728        self.entity_id == other.entity_id
729    }
730}
731
732impl Eq for AnyWeakEntity {}
733
734impl Ord for AnyWeakEntity {
735    #[inline]
736    fn cmp(&self, other: &Self) -> Ordering {
737        self.entity_id.cmp(&other.entity_id)
738    }
739}
740
741impl PartialOrd for AnyWeakEntity {
742    #[inline]
743    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
744        Some(self.cmp(other))
745    }
746}
747
748/// A weak reference to a entity of the given type.
749#[derive(Deref, DerefMut)]
750pub struct WeakEntity<T> {
751    #[deref]
752    #[deref_mut]
753    any_entity: AnyWeakEntity,
754    entity_type: PhantomData<fn(T) -> T>,
755}
756
757impl<T> std::fmt::Debug for WeakEntity<T> {
758    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759        f.debug_struct(type_name::<Self>())
760            .field("entity_id", &self.any_entity.entity_id)
761            .field("entity_type", &type_name::<T>())
762            .finish()
763    }
764}
765
766impl<T> Clone for WeakEntity<T> {
767    fn clone(&self) -> Self {
768        Self {
769            any_entity: self.any_entity.clone(),
770            entity_type: self.entity_type,
771        }
772    }
773}
774
775impl<T: 'static> WeakEntity<T> {
776    /// Upgrade this weak entity reference into a strong entity reference
777    pub fn upgrade(&self) -> Option<Entity<T>> {
778        Some(Entity {
779            any_entity: self.any_entity.upgrade()?,
780            entity_type: self.entity_type,
781        })
782    }
783
784    /// Updates the entity referenced by this handle with the given function if
785    /// the referenced entity still exists. Returns an error if the entity has
786    /// been released.
787    pub fn update<C, R>(
788        &self,
789        cx: &mut C,
790        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
791    ) -> Result<R>
792    where
793        C: AppContext,
794        Result<C::Result<R>>: crate::Flatten<R>,
795    {
796        crate::Flatten::flatten(
797            self.upgrade()
798                .context("entity released")
799                .map(|this| cx.update_entity(&this, update)),
800        )
801    }
802
803    /// Updates the entity referenced by this handle with the given function if
804    /// the referenced entity still exists, within a visual context that has a window.
805    /// Returns an error if the entity has been released.
806    pub fn update_in<C, R>(
807        &self,
808        cx: &mut C,
809        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
810    ) -> Result<R>
811    where
812        C: VisualContext,
813        Result<C::Result<R>>: crate::Flatten<R>,
814    {
815        let window = cx.window_handle();
816        let this = self.upgrade().context("entity released")?;
817
818        crate::Flatten::flatten(window.update(cx, |_, window, cx| {
819            this.update(cx, |entity, cx| update(entity, window, cx))
820        }))
821    }
822
823    /// Reads the entity referenced by this handle with the given function if
824    /// the referenced entity still exists. Returns an error if the entity has
825    /// been released.
826    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
827    where
828        C: AppContext,
829        Result<C::Result<R>>: crate::Flatten<R>,
830    {
831        crate::Flatten::flatten(
832            self.upgrade()
833                .context("entity released")
834                .map(|this| cx.read_entity(&this, read)),
835        )
836    }
837
838    /// Create a new weak entity that can never be upgraded.
839    #[inline]
840    pub fn new_invalid() -> Self {
841        Self {
842            any_entity: AnyWeakEntity::new_invalid(),
843            entity_type: PhantomData,
844        }
845    }
846}
847
848impl<T> Hash for WeakEntity<T> {
849    #[inline]
850    fn hash<H: Hasher>(&self, state: &mut H) {
851        self.any_entity.hash(state);
852    }
853}
854
855impl<T> PartialEq for WeakEntity<T> {
856    #[inline]
857    fn eq(&self, other: &Self) -> bool {
858        self.any_entity == other.any_entity
859    }
860}
861
862impl<T> Eq for WeakEntity<T> {}
863
864impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
865    #[inline]
866    fn eq(&self, other: &Entity<T>) -> bool {
867        self.entity_id() == other.any_entity.entity_id()
868    }
869}
870
871impl<T: 'static> Ord for WeakEntity<T> {
872    #[inline]
873    fn cmp(&self, other: &Self) -> Ordering {
874        self.entity_id().cmp(&other.entity_id())
875    }
876}
877
878impl<T: 'static> PartialOrd for WeakEntity<T> {
879    #[inline]
880    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
881        Some(self.cmp(other))
882    }
883}
884
885/// Controls whether backtraces are captured when entity handles are created.
886///
887/// Set the `LEAK_BACKTRACE` environment variable to any non-empty value to enable
888/// backtrace capture. This helps identify where leaked handles were allocated.
889#[cfg(any(test, feature = "leak-detection"))]
890static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
891    std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
892
893/// Unique identifier for a specific entity handle instance.
894///
895/// This is distinct from `EntityId` - while multiple handles can point to the same
896/// entity (same `EntityId`), each handle has its own unique `HandleId`.
897#[cfg(any(test, feature = "leak-detection"))]
898#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
899pub(crate) struct HandleId {
900    id: u64,
901}
902
903/// Tracks entity handle allocations to detect leaks.
904///
905/// The leak detector is enabled in tests and when the `leak-detection` feature is active.
906/// It tracks every `Entity<T>` and `AnyEntity` handle that is created and released,
907/// allowing you to verify that all handles to an entity have been properly dropped.
908///
909/// # How do leaks happen?
910///
911/// Entities are reference-counted structures that can own other entities
912/// allowing to form cycles. If such a strong-reference counted cycle is
913/// created, all participating strong entities in this cycle will effectively
914/// leak as they cannot be released anymore.
915///
916/// # Usage
917///
918/// You can use `WeakEntity::assert_released` or `AnyWeakEntity::assert_released`
919/// to verify that an entity has been fully released:
920///
921/// ```ignore
922/// let entity = cx.new(|_| MyEntity::new());
923/// let weak = entity.downgrade();
924/// drop(entity);
925///
926/// // This will panic if any handles to the entity are still alive
927/// weak.assert_released();
928/// ```
929///
930/// # Debugging Leaks
931///
932/// When a leak is detected, the detector will panic with information about the leaked
933/// handles. To see where the leaked handles were allocated, set the `LEAK_BACKTRACE`
934/// environment variable:
935///
936/// ```bash
937/// LEAK_BACKTRACE=1 cargo test my_test
938/// ```
939///
940/// This will capture and display backtraces for each leaked handle, helping you
941/// identify where handles were created but not released.
942///
943/// # How It Works
944///
945/// - When an entity handle is created (via `Entity::new`, `Entity::clone`, or
946///   `WeakEntity::upgrade`), `handle_created` is called to register the handle.
947/// - When a handle is dropped, `handle_released` removes it from tracking.
948/// - `assert_released` verifies that no handles remain for a given entity.
949#[cfg(any(test, feature = "leak-detection"))]
950pub(crate) struct LeakDetector {
951    next_handle_id: u64,
952    entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
953}
954
955#[cfg(any(test, feature = "leak-detection"))]
956impl LeakDetector {
957    /// Records that a new handle has been created for the given entity.
958    ///
959    /// Returns a unique `HandleId` that must be passed to `handle_released` when
960    /// the handle is dropped. If `LEAK_BACKTRACE` is set, captures a backtrace
961    /// at the allocation site.
962    #[track_caller]
963    pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
964        let id = util::post_inc(&mut self.next_handle_id);
965        let handle_id = HandleId { id };
966        let handles = self.entity_handles.entry(entity_id).or_default();
967        handles.insert(
968            handle_id,
969            LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
970        );
971        handle_id
972    }
973
974    /// Records that a handle has been released (dropped).
975    ///
976    /// This removes the handle from tracking. The `handle_id` should be the same
977    /// one returned by `handle_created` when the handle was allocated.
978    pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
979        let handles = self.entity_handles.entry(entity_id).or_default();
980        handles.remove(&handle_id);
981    }
982
983    /// Asserts that all handles to the given entity have been released.
984    ///
985    /// # Panics
986    ///
987    /// Panics if any handles to the entity are still alive. The panic message
988    /// includes backtraces for each leaked handle if `LEAK_BACKTRACE` is set,
989    /// otherwise it suggests setting the environment variable to get more info.
990    pub fn assert_released(&mut self, entity_id: EntityId) {
991        use std::fmt::Write as _;
992        let handles = self.entity_handles.entry(entity_id).or_default();
993        if !handles.is_empty() {
994            let mut out = String::new();
995            for backtrace in handles.values_mut() {
996                if let Some(mut backtrace) = backtrace.take() {
997                    backtrace.resolve();
998                    writeln!(out, "Leaked handle:\n{:?}", backtrace).unwrap();
999                } else {
1000                    writeln!(
1001                        out,
1002                        "Leaked handle: (export LEAK_BACKTRACE to find allocation site)"
1003                    )
1004                    .unwrap();
1005                }
1006            }
1007            panic!("{out}");
1008        }
1009    }
1010}
1011
1012#[cfg(test)]
1013mod test {
1014    use crate::EntityMap;
1015
1016    struct TestEntity {
1017        pub i: i32,
1018    }
1019
1020    #[test]
1021    fn test_entity_map_slot_assignment_before_cleanup() {
1022        // Tests that slots are not re-used before take_dropped.
1023        let mut entity_map = EntityMap::new();
1024
1025        let slot = entity_map.reserve::<TestEntity>();
1026        entity_map.insert(slot, TestEntity { i: 1 });
1027
1028        let slot = entity_map.reserve::<TestEntity>();
1029        entity_map.insert(slot, TestEntity { i: 2 });
1030
1031        let dropped = entity_map.take_dropped();
1032        assert_eq!(dropped.len(), 2);
1033
1034        assert_eq!(
1035            dropped
1036                .into_iter()
1037                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1038                .collect::<Vec<i32>>(),
1039            vec![1, 2],
1040        );
1041    }
1042
1043    #[test]
1044    fn test_entity_map_weak_upgrade_before_cleanup() {
1045        // Tests that weak handles are not upgraded before take_dropped
1046        let mut entity_map = EntityMap::new();
1047
1048        let slot = entity_map.reserve::<TestEntity>();
1049        let handle = entity_map.insert(slot, TestEntity { i: 1 });
1050        let weak = handle.downgrade();
1051        drop(handle);
1052
1053        let strong = weak.upgrade();
1054        assert_eq!(strong, None);
1055
1056        let dropped = entity_map.take_dropped();
1057        assert_eq!(dropped.len(), 1);
1058
1059        assert_eq!(
1060            dropped
1061                .into_iter()
1062                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1063                .collect::<Vec<i32>>(),
1064            vec![1],
1065        );
1066    }
1067}