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