Skip to main content

gpui/app/
entity_map.rs

1// Modified by Longbridge for gpui-fast.
2use crate::{App, AppContext, GpuiBorrow, VisualContext, Window, seal::Sealed};
3use anyhow::{Context as _, Result};
4use collections::FxHashSet;
5use derive_more::{Deref, DerefMut};
6use parking_lot::{RwLock, RwLockUpgradableReadGuard};
7use slotmap::{KeyData, SecondaryMap, SlotMap};
8use std::{
9    any::{Any, TypeId, type_name},
10    cell::RefCell,
11    cmp::Ordering,
12    fmt::{self, Display},
13    hash::{Hash, Hasher},
14    marker::PhantomData,
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, gpui_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    pub(crate) access_log: crate::fast::dependencies::EntityAccessLog,
61    ref_counts: Arc<RwLock<EntityRefCounts>>,
62}
63
64#[doc(hidden)]
65pub(crate) struct EntityRefCounts {
66    counts: SlotMap<EntityId, AtomicUsize>,
67    dropped_entity_ids: Vec<EntityId>,
68    #[cfg(any(test, gpui_leak_detection))]
69    leak_detector: LeakDetector,
70}
71
72pub(super) struct LeaseInner {
73    pub(super) entity: Option<Box<dyn Any>>,
74}
75
76impl EntityMap {
77    pub fn new() -> Self {
78        Self {
79            entities: SecondaryMap::new(),
80            accessed_entities: RefCell::new(FxHashSet::default()),
81            access_log: crate::fast::dependencies::EntityAccessLog::default(),
82            ref_counts: Arc::new(RwLock::new(EntityRefCounts {
83                counts: SlotMap::with_key(),
84                dropped_entity_ids: Vec::new(),
85                #[cfg(any(test, gpui_leak_detection))]
86                leak_detector: LeakDetector {
87                    next_handle_id: 0,
88                    entity_handles: HashMap::default(),
89                },
90            })),
91        }
92    }
93
94    #[doc(hidden)]
95    pub fn ref_counts_drop_handle(&self) -> Arc<RwLock<EntityRefCounts>> {
96        self.ref_counts.clone()
97    }
98
99    /// Captures a snapshot of all entities that currently have alive handles.
100    ///
101    /// The returned [`LeakDetectorSnapshot`] can later be passed to
102    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
103    /// entities created after the snapshot are still alive.
104    #[cfg(any(test, gpui_leak_detection))]
105    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
106        self.ref_counts.read().leak_detector.snapshot()
107    }
108
109    /// Asserts that no entities created after `snapshot` still have alive handles.
110    ///
111    /// See [`LeakDetector::assert_no_new_leaks`] for details.
112    #[cfg(any(test, gpui_leak_detection))]
113    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
114        self.ref_counts
115            .read()
116            .leak_detector
117            .assert_no_new_leaks(snapshot)
118    }
119
120    /// Reserve a slot for an entity, which you can subsequently use with `insert`.
121    pub fn reserve<T: 'static>(&self) -> Slot<T> {
122        let id = self.ref_counts.write().counts.insert(1.into());
123        Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
124    }
125
126    /// Insert an entity into a slot obtained by calling `reserve`.
127    pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
128    where
129        T: 'static,
130    {
131        let mut accessed_entities = self.accessed_entities.get_mut();
132        accessed_entities.insert(slot.entity_id);
133        crate::fast::dependencies::note_access(self, slot.entity_id);
134
135        let handle = slot.0;
136        self.entities.insert(handle.entity_id, Box::new(entity));
137        handle
138    }
139
140    /// Move an entity to the stack.
141    #[track_caller]
142    pub fn lease<T>(&mut self, pointer: &Entity<T>) -> Lease<T> {
143        Lease {
144            inner: self.lease_erased(pointer, type_name::<T>()),
145            id: pointer.entity_id,
146            entity_type: PhantomData,
147        }
148    }
149
150    /// Returns an entity after moving it to the stack.
151    pub fn end_lease<T>(&mut self, lease: Lease<T>) {
152        self.end_lease_erased(lease.id, lease.inner);
153    }
154
155    #[inline(always)]
156    pub fn read<T: 'static>(&self, entity: &Entity<T>) -> &T {
157        self.assert_valid_context(entity);
158        self.read_inner(entity.entity_id)
159            .and_then(|entity| entity.downcast_ref())
160            .unwrap_or_else(|| double_lease_panic("read", type_name::<T>()))
161    }
162
163    #[track_caller]
164    pub(super) fn lease_erased(&mut self, pointer: &AnyEntity, entity_type: &str) -> LeaseInner {
165        self.assert_valid_context(pointer);
166        crate::fast::dependencies::note_update(self, pointer.entity_id);
167        let entity = Some(
168            self.lease_inner(pointer.entity_id)
169                .unwrap_or_else(|| double_lease_panic("update", entity_type)),
170        );
171        LeaseInner { entity }
172    }
173
174    pub(super) fn end_lease_erased(&mut self, entity_id: EntityId, mut lease: LeaseInner) {
175        self.end_lease_inner(entity_id, lease.entity.take().unwrap());
176    }
177
178    fn assert_valid_context(&self, entity: &AnyEntity) {
179        debug_assert!(
180            Weak::ptr_eq(&entity.entity_map, &Arc::downgrade(&self.ref_counts)),
181            "used a entity with the wrong context"
182        );
183    }
184
185    pub fn clear_accessed(&mut self) {
186        self.accessed_entities.get_mut().clear();
187    }
188
189    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
190        let mut ref_counts = &mut *self.ref_counts.write();
191        let dropped_entity_ids = ref_counts.dropped_entity_ids.drain(..);
192        let mut accessed_entities = self.accessed_entities.get_mut();
193
194        dropped_entity_ids
195            .filter_map(|entity_id| {
196                let count = ref_counts.counts.remove(entity_id).unwrap();
197                debug_assert_eq!(
198                    count.load(SeqCst),
199                    0,
200                    "dropped an entity that was referenced"
201                );
202                accessed_entities.remove(&entity_id);
203                crate::fast::dependencies::EntityAccessLog::forget(&mut self.access_log, entity_id);
204                // If the EntityId was allocated with `Context::reserve`,
205                // the entity may not have been inserted.
206                Some((entity_id, self.entities.remove(entity_id)?))
207            })
208            .collect()
209    }
210
211    #[inline(never)]
212    fn read_inner(&self, entity_id: EntityId) -> Option<&dyn Any> {
213        let mut accessed_entities = self.accessed_entities.borrow_mut();
214        accessed_entities.insert(entity_id);
215        crate::fast::dependencies::note_access(self, entity_id);
216        self.entities.get(entity_id).map(Box::as_ref)
217    }
218
219    #[inline(never)]
220    fn lease_inner(&mut self, entity_id: EntityId) -> Option<Box<dyn Any>> {
221        self.accessed_entities.get_mut().insert(entity_id);
222        self.entities.remove(entity_id)
223    }
224
225    #[inline(never)]
226    fn end_lease_inner(&mut self, entity_id: EntityId, entity: Box<dyn Any>) {
227        self.entities.insert(entity_id, entity);
228    }
229}
230
231#[track_caller]
232fn double_lease_panic(operation: &str, entity_type: &str) -> ! {
233    panic!("cannot {operation} {entity_type} while it is already being updated")
234}
235
236pub(crate) struct Lease<T> {
237    pub id: EntityId,
238    inner: LeaseInner,
239    entity_type: PhantomData<T>,
240}
241
242impl<T: 'static> core::ops::Deref for Lease<T> {
243    type Target = T;
244
245    fn deref(&self) -> &Self::Target {
246        self.inner.entity.as_ref().unwrap().downcast_ref().unwrap()
247    }
248}
249
250impl<T: 'static> core::ops::DerefMut for Lease<T> {
251    fn deref_mut(&mut self) -> &mut Self::Target {
252        self.inner.entity.as_mut().unwrap().downcast_mut().unwrap()
253    }
254}
255
256impl Drop for LeaseInner {
257    fn drop(&mut self) {
258        if self.entity.is_some() && !panicking() {
259            panic!("Leases must be ended with EntityMap::end_lease")
260        }
261    }
262}
263
264#[derive(Deref, DerefMut)]
265pub(crate) struct Slot<T>(Entity<T>);
266
267/// A dynamically typed reference to a entity, which can be downcast into a `Entity<T>`.
268pub struct AnyEntity {
269    pub(crate) entity_id: EntityId,
270    pub(crate) entity_type: TypeId,
271    entity_map: Weak<RwLock<EntityRefCounts>>,
272    #[cfg(any(test, gpui_leak_detection))]
273    handle_id: HandleId,
274}
275
276impl AnyEntity {
277    fn new(
278        id: EntityId,
279        entity_type: TypeId,
280        entity_map: Weak<RwLock<EntityRefCounts>>,
281        #[cfg(any(test, gpui_leak_detection))] type_name: &'static str,
282    ) -> Self {
283        Self {
284            entity_id: id,
285            entity_type,
286            #[cfg(any(test, gpui_leak_detection))]
287            handle_id: entity_map
288                .clone()
289                .upgrade()
290                .unwrap()
291                .write()
292                .leak_detector
293                .handle_created(id, Some(type_name)),
294            entity_map,
295        }
296    }
297
298    /// Returns the id associated with this entity.
299    #[inline]
300    pub fn entity_id(&self) -> EntityId {
301        self.entity_id
302    }
303
304    /// Returns the [TypeId] associated with this entity.
305    #[inline]
306    pub fn entity_type(&self) -> TypeId {
307        self.entity_type
308    }
309
310    /// Converts this entity handle into a weak variant, which does not prevent it from being released.
311    pub fn downgrade(&self) -> AnyWeakEntity {
312        AnyWeakEntity {
313            entity_id: self.entity_id,
314            entity_type: self.entity_type,
315            entity_ref_counts: self.entity_map.clone(),
316        }
317    }
318
319    /// Converts this entity handle into a strongly-typed entity handle of the given type.
320    /// If this entity handle is not of the specified type, returns itself as an error variant.
321    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
322        if TypeId::of::<T>() == self.entity_type {
323            Ok(Entity {
324                any_entity: self,
325                entity_type: PhantomData,
326            })
327        } else {
328            Err(self)
329        }
330    }
331}
332
333impl Clone for AnyEntity {
334    fn clone(&self) -> Self {
335        if let Some(entity_map) = self.entity_map.upgrade() {
336            let entity_map = entity_map.read();
337            let count = entity_map
338                .counts
339                .get(self.entity_id)
340                .expect("detected over-release of a entity");
341            let prev_count = count.fetch_add(1, SeqCst);
342            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
343        }
344
345        Self {
346            entity_id: self.entity_id,
347            entity_type: self.entity_type,
348            entity_map: self.entity_map.clone(),
349            #[cfg(any(test, gpui_leak_detection))]
350            handle_id: self
351                .entity_map
352                .upgrade()
353                .unwrap()
354                .write()
355                .leak_detector
356                .handle_created(self.entity_id, None),
357        }
358    }
359}
360
361impl Drop for AnyEntity {
362    fn drop(&mut self) {
363        if let Some(entity_map) = self.entity_map.upgrade() {
364            let entity_map = entity_map.upgradable_read();
365            let count = entity_map
366                .counts
367                .get(self.entity_id)
368                .expect("detected over-release of a handle.");
369            let prev_count = count.fetch_sub(1, SeqCst);
370            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
371            if prev_count == 1 {
372                // We were the last reference to this entity, so we can remove it.
373                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
374                entity_map.dropped_entity_ids.push(self.entity_id);
375            }
376        }
377
378        #[cfg(any(test, gpui_leak_detection))]
379        if let Some(entity_map) = self.entity_map.upgrade() {
380            entity_map
381                .write()
382                .leak_detector
383                .handle_released(self.entity_id, self.handle_id)
384        }
385    }
386}
387
388impl<T> From<Entity<T>> for AnyEntity {
389    #[inline]
390    fn from(entity: Entity<T>) -> Self {
391        entity.any_entity
392    }
393}
394
395impl Hash for AnyEntity {
396    #[inline]
397    fn hash<H: Hasher>(&self, state: &mut H) {
398        self.entity_id.hash(state);
399    }
400}
401
402impl PartialEq for AnyEntity {
403    #[inline]
404    fn eq(&self, other: &Self) -> bool {
405        self.entity_id == other.entity_id
406    }
407}
408
409impl Eq for AnyEntity {}
410
411impl Ord for AnyEntity {
412    #[inline]
413    fn cmp(&self, other: &Self) -> Ordering {
414        self.entity_id.cmp(&other.entity_id)
415    }
416}
417
418impl PartialOrd for AnyEntity {
419    #[inline]
420    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
421        Some(self.cmp(other))
422    }
423}
424
425impl std::fmt::Debug for AnyEntity {
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        f.debug_struct("AnyEntity")
428            .field("entity_id", &self.entity_id.as_u64())
429            .finish()
430    }
431}
432
433/// A strong, well-typed reference to a struct which is managed
434/// by GPUI
435#[derive(Deref, DerefMut)]
436pub struct Entity<T> {
437    #[deref]
438    #[deref_mut]
439    pub(crate) any_entity: AnyEntity,
440    pub(crate) entity_type: PhantomData<fn(T) -> T>,
441}
442
443impl<T> Sealed for Entity<T> {}
444
445impl<T: 'static> Entity<T> {
446    #[inline]
447    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
448    where
449        T: 'static,
450    {
451        Self {
452            any_entity: AnyEntity::new(
453                id,
454                TypeId::of::<T>(),
455                entity_map,
456                #[cfg(any(test, gpui_leak_detection))]
457                std::any::type_name::<T>(),
458            ),
459            entity_type: PhantomData,
460        }
461    }
462
463    /// Get the entity ID associated with this entity
464    #[inline]
465    pub fn entity_id(&self) -> EntityId {
466        self.any_entity.entity_id
467    }
468
469    /// Downgrade this entity pointer to a non-retaining weak pointer
470    #[inline]
471    pub fn downgrade(&self) -> WeakEntity<T> {
472        WeakEntity {
473            any_entity: self.any_entity.downgrade(),
474            entity_type: self.entity_type,
475        }
476    }
477
478    /// Convert this into a dynamically typed entity.
479    #[inline]
480    pub fn into_any(self) -> AnyEntity {
481        self.any_entity
482    }
483
484    /// Grab a reference to this entity from the context.
485    #[inline]
486    pub fn read<'a>(&self, cx: &'a App) -> &'a T {
487        cx.entities.read(self)
488    }
489
490    /// Read the entity referenced by this handle with the given function.
491    #[inline]
492    pub fn read_with<R, C: AppContext>(&self, cx: &C, f: impl FnOnce(&T, &App) -> R) -> R {
493        cx.read_entity(self, f)
494    }
495
496    /// Updates the entity referenced by this handle with the given function.
497    #[inline]
498    pub fn update<R, C: AppContext>(
499        &self,
500        cx: &mut C,
501        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
502    ) -> R {
503        cx.update_entity(self, update)
504    }
505
506    /// Updates the entity referenced by this handle with the given function.
507    #[inline]
508    pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> GpuiBorrow<'a, T> {
509        cx.as_mut(self)
510    }
511
512    /// Updates the entity referenced by this handle with the given function.
513    pub fn write<C: AppContext>(&self, cx: &mut C, value: T) {
514        self.update(cx, |entity, cx| {
515            *entity = value;
516            cx.notify();
517        })
518    }
519
520    /// Updates the entity referenced by this handle with the given function if
521    /// the referenced entity still exists, within a visual context that has a window.
522    /// Returns an error if the window has been closed.
523    #[inline]
524    pub fn update_in<R, C: VisualContext>(
525        &self,
526        cx: &mut C,
527        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
528    ) -> C::Result<R> {
529        cx.update_window_entity(self, update)
530    }
531}
532
533impl<T> Clone for Entity<T> {
534    #[inline]
535    fn clone(&self) -> Self {
536        Self {
537            any_entity: self.any_entity.clone(),
538            entity_type: self.entity_type,
539        }
540    }
541}
542
543impl<T> std::fmt::Debug for Entity<T> {
544    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545        f.debug_struct("Entity")
546            .field("entity_id", &self.any_entity.entity_id)
547            .field("entity_type", &type_name::<T>())
548            .finish()
549    }
550}
551
552impl<T> Hash for Entity<T> {
553    #[inline]
554    fn hash<H: Hasher>(&self, state: &mut H) {
555        self.any_entity.hash(state);
556    }
557}
558
559impl<T> PartialEq for Entity<T> {
560    #[inline]
561    fn eq(&self, other: &Self) -> bool {
562        self.any_entity == other.any_entity
563    }
564}
565
566impl<T> Eq for Entity<T> {}
567
568impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
569    #[inline]
570    fn eq(&self, other: &WeakEntity<T>) -> bool {
571        self.any_entity.entity_id() == other.entity_id()
572    }
573}
574
575impl<T: 'static> Ord for Entity<T> {
576    #[inline]
577    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
578        self.entity_id().cmp(&other.entity_id())
579    }
580}
581
582impl<T: 'static> PartialOrd for Entity<T> {
583    #[inline]
584    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
585        Some(self.cmp(other))
586    }
587}
588
589/// A type erased, weak reference to a entity.
590#[derive(Clone)]
591pub struct AnyWeakEntity {
592    pub(crate) entity_id: EntityId,
593    entity_type: TypeId,
594    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
595}
596
597impl AnyWeakEntity {
598    /// Get the entity ID associated with this weak reference.
599    #[inline]
600    pub fn entity_id(&self) -> EntityId {
601        self.entity_id
602    }
603
604    /// Check if this weak handle can be upgraded, or if the entity has already been dropped
605    pub fn is_upgradable(&self) -> bool {
606        let ref_count = self
607            .entity_ref_counts
608            .upgrade()
609            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
610            .unwrap_or(0);
611        ref_count > 0
612    }
613
614    /// Upgrade this weak entity reference to a strong reference.
615    pub fn upgrade(&self) -> Option<AnyEntity> {
616        let ref_counts = &self.entity_ref_counts.upgrade()?;
617        let ref_counts = ref_counts.read();
618        let ref_count = ref_counts.counts.get(self.entity_id)?;
619
620        if atomic_incr_if_not_zero(ref_count) == 0 {
621            // entity_id is in dropped_entity_ids
622            return None;
623        }
624        drop(ref_counts);
625
626        Some(AnyEntity {
627            entity_id: self.entity_id,
628            entity_type: self.entity_type,
629            entity_map: self.entity_ref_counts.clone(),
630            #[cfg(any(test, gpui_leak_detection))]
631            handle_id: self
632                .entity_ref_counts
633                .upgrade()
634                .unwrap()
635                .write()
636                .leak_detector
637                .handle_created(self.entity_id, None),
638        })
639    }
640
641    /// Asserts that the entity referenced by this weak handle has been fully released.
642    ///
643    /// # Example
644    ///
645    /// ```ignore
646    /// let entity = cx.new(|_| MyEntity::new());
647    /// let weak = entity.downgrade();
648    /// drop(entity);
649    ///
650    /// // Verify the entity was released
651    /// weak.assert_released();
652    /// ```
653    ///
654    /// # Debugging Leaks
655    ///
656    /// With leak detection enabled (build with `GPUI_LEAK_DETECTION=1`), a failure
657    /// lists each leaked handle. Also set the `LEAK_BACKTRACE` environment variable
658    /// to see where they were allocated:
659    ///
660    /// ```bash
661    /// GPUI_LEAK_DETECTION=1 LEAK_BACKTRACE=1 cargo test my_test
662    /// ```
663    ///
664    /// # Panics
665    ///
666    /// - Panics if any strong handles to the entity are still alive.
667    /// - Panics if the entity was recently dropped but cleanup hasn't completed yet
668    ///   (resources are retained until the end of the effect cycle).
669    #[cfg(any(test, feature = "test-support", gpui_leak_detection))]
670    pub fn assert_released(&self) {
671        #[cfg(any(test, gpui_leak_detection))]
672        self.entity_ref_counts
673            .upgrade()
674            .unwrap()
675            .write()
676            .leak_detector
677            .assert_released(self.entity_id);
678
679        if self
680            .entity_ref_counts
681            .upgrade()
682            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
683            .is_some()
684        {
685            panic!(
686                "entity is still alive, or was recently dropped and its resources are retained \
687                 until the end of the effect cycle. Build with GPUI_LEAK_DETECTION=1 to list \
688                 its live handles."
689            )
690        }
691    }
692
693    /// Creates a weak entity that can never be upgraded.
694    pub fn new_invalid() -> Self {
695        /// To hold the invariant that all ids are unique, and considering that slotmap
696        /// increases their IDs from `0`, we can decrease ours from `u64::MAX` so these
697        /// two will never conflict (u64 is way too large).
698        static UNIQUE_NON_CONFLICTING_ID_GENERATOR: AtomicU64 = AtomicU64::new(u64::MAX);
699        let entity_id = UNIQUE_NON_CONFLICTING_ID_GENERATOR.fetch_sub(1, SeqCst);
700
701        Self {
702            // Safety:
703            //   Docs say this is safe but can be unspecified if slotmap changes the representation
704            //   after `1.0.7`, that said, providing a valid entity_id here is not necessary as long
705            //   as we guarantee that `entity_id` is never used if `entity_ref_counts` equals
706            //   to `Weak::new()` (that is, it's unable to upgrade), that is the invariant that
707            //   actually needs to be hold true.
708            //
709            //   And there is no sane reason to read an entity slot if `entity_ref_counts` can't be
710            //   read in the first place, so we're good!
711            entity_id: entity_id.into(),
712            entity_type: TypeId::of::<()>(),
713            entity_ref_counts: Weak::new(),
714        }
715    }
716}
717
718impl std::fmt::Debug for AnyWeakEntity {
719    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720        f.debug_struct(type_name::<Self>())
721            .field("entity_id", &self.entity_id)
722            .field("entity_type", &self.entity_type)
723            .finish()
724    }
725}
726
727impl<T> From<WeakEntity<T>> for AnyWeakEntity {
728    #[inline]
729    fn from(entity: WeakEntity<T>) -> Self {
730        entity.any_entity
731    }
732}
733
734impl Hash for AnyWeakEntity {
735    #[inline]
736    fn hash<H: Hasher>(&self, state: &mut H) {
737        self.entity_id.hash(state);
738    }
739}
740
741impl PartialEq for AnyWeakEntity {
742    #[inline]
743    fn eq(&self, other: &Self) -> bool {
744        self.entity_id == other.entity_id
745    }
746}
747
748impl Eq for AnyWeakEntity {}
749
750impl Ord for AnyWeakEntity {
751    #[inline]
752    fn cmp(&self, other: &Self) -> Ordering {
753        self.entity_id.cmp(&other.entity_id)
754    }
755}
756
757impl PartialOrd for AnyWeakEntity {
758    #[inline]
759    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
760        Some(self.cmp(other))
761    }
762}
763
764/// A weak reference to a entity of the given type.
765#[derive(Deref, DerefMut)]
766pub struct WeakEntity<T> {
767    #[deref]
768    #[deref_mut]
769    any_entity: AnyWeakEntity,
770    entity_type: PhantomData<fn(T) -> T>,
771}
772
773impl<T> std::fmt::Debug for WeakEntity<T> {
774    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775        f.debug_struct(type_name::<Self>())
776            .field("entity_id", &self.any_entity.entity_id)
777            .field("entity_type", &type_name::<T>())
778            .finish()
779    }
780}
781
782impl<T> Clone for WeakEntity<T> {
783    fn clone(&self) -> Self {
784        Self {
785            any_entity: self.any_entity.clone(),
786            entity_type: self.entity_type,
787        }
788    }
789}
790
791impl<T: 'static> WeakEntity<T> {
792    /// Upgrade this weak entity reference into a strong entity reference
793    pub fn upgrade(&self) -> Option<Entity<T>> {
794        Some(Entity {
795            any_entity: self.any_entity.upgrade()?,
796            entity_type: self.entity_type,
797        })
798    }
799
800    /// Updates the entity referenced by this handle with the given function if
801    /// the referenced entity still exists. Returns an error if the entity has
802    /// been released.
803    #[inline(always)]
804    pub fn update<C, R>(
805        &self,
806        cx: &mut C,
807        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
808    ) -> Result<R>
809    where
810        C: AppContext,
811    {
812        let entity = self.upgrade().context("entity released")?;
813        Ok(cx.update_entity(&entity, update))
814    }
815
816    /// Updates the entity referenced by this handle with the given function if
817    /// the referenced entity still exists, within a visual context that has a window.
818    /// Returns an error if the entity has been released.
819    #[inline(always)]
820    pub fn update_in<C, R>(
821        &self,
822        cx: &mut C,
823        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
824    ) -> Result<R>
825    where
826        C: AppContext,
827    {
828        let entity = self.upgrade().context("entity released")?;
829        cx.with_window(entity.entity_id(), |window, app| {
830            entity.update(app, |entity, cx| update(entity, window, cx))
831        })
832        .context("entity has no current window")
833    }
834
835    /// Reads the entity referenced by this handle with the given function if
836    /// the referenced entity still exists. Returns an error if the entity has
837    /// been released.
838    #[inline(always)]
839    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
840    where
841        C: AppContext,
842    {
843        let entity = self.upgrade().context("entity released")?;
844        Ok(cx.read_entity(&entity, read))
845    }
846
847    /// Create a new weak entity that can never be upgraded.
848    #[inline]
849    pub fn new_invalid() -> Self {
850        Self {
851            any_entity: AnyWeakEntity::new_invalid(),
852            entity_type: PhantomData,
853        }
854    }
855}
856
857impl<T> Hash for WeakEntity<T> {
858    #[inline]
859    fn hash<H: Hasher>(&self, state: &mut H) {
860        self.any_entity.hash(state);
861    }
862}
863
864impl<T> PartialEq for WeakEntity<T> {
865    #[inline]
866    fn eq(&self, other: &Self) -> bool {
867        self.any_entity == other.any_entity
868    }
869}
870
871impl<T> Eq for WeakEntity<T> {}
872
873impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
874    #[inline]
875    fn eq(&self, other: &Entity<T>) -> bool {
876        self.entity_id() == other.any_entity.entity_id()
877    }
878}
879
880impl<T: 'static> Ord for WeakEntity<T> {
881    #[inline]
882    fn cmp(&self, other: &Self) -> Ordering {
883        self.entity_id().cmp(&other.entity_id())
884    }
885}
886
887impl<T: 'static> PartialOrd for WeakEntity<T> {
888    #[inline]
889    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
890        Some(self.cmp(other))
891    }
892}
893
894/// Controls whether backtraces are captured when entity handles are created.
895///
896/// Set the `LEAK_BACKTRACE` environment variable to any non-empty value to enable
897/// backtrace capture. This helps identify where leaked handles were allocated.
898#[cfg(any(test, gpui_leak_detection))]
899static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
900    std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
901
902/// Unique identifier for a specific entity handle instance.
903///
904/// This is distinct from `EntityId` - while multiple handles can point to the same
905/// entity (same `EntityId`), each handle has its own unique `HandleId`.
906#[cfg(any(test, gpui_leak_detection))]
907#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
908pub(crate) struct HandleId {
909    id: u64,
910}
911
912/// Tracks entity handle allocations to detect leaks.
913///
914/// The leak detector is enabled in tests and when the `leak-detection` feature is active.
915/// It tracks every `Entity<T>` and `AnyEntity` handle that is created and released,
916/// allowing you to verify that all handles to an entity have been properly dropped.
917///
918/// # How do leaks happen?
919///
920/// Entities are reference-counted structures that can own other entities
921/// allowing to form cycles. If such a strong-reference counted cycle is
922/// created, all participating strong entities in this cycle will effectively
923/// leak as they cannot be released anymore.
924///
925/// Cycles can also happen if an entity owns a task or subscription that it
926/// itself owns a strong reference to the entity again.
927///
928/// # Usage
929///
930/// You can use `WeakEntity::assert_released` or `AnyWeakEntity::assert_released`
931/// to verify that an entity has been fully released:
932///
933/// ```ignore
934/// let entity = cx.new(|_| MyEntity::new());
935/// let weak = entity.downgrade();
936/// drop(entity);
937///
938/// // This will panic if any handles to the entity are still alive
939/// weak.assert_released();
940/// ```
941///
942/// # Debugging Leaks
943///
944/// When a leak is detected, the detector will panic with information about the leaked
945/// handles. To see where the leaked handles were allocated, set the `LEAK_BACKTRACE`
946/// environment variable:
947///
948/// ```bash
949/// LEAK_BACKTRACE=1 cargo test my_test
950/// ```
951///
952/// This will capture and display backtraces for each leaked handle, helping you
953/// identify where leaked handles were created.
954///
955/// # How It Works
956///
957/// - When an entity handle is created (via `Entity::new`, `Entity::clone`, or
958///   `WeakEntity::upgrade`), `handle_created` is called to register the handle.
959/// - When a handle is dropped, `handle_released` removes it from tracking.
960/// - `assert_released` verifies that no handles remain for a given entity.
961#[cfg(any(test, gpui_leak_detection))]
962pub(crate) struct LeakDetector {
963    next_handle_id: u64,
964    entity_handles: HashMap<EntityId, EntityLeakData>,
965}
966
967/// A snapshot of the set of alive entities at a point in time.
968///
969/// Created by [`LeakDetector::snapshot`]. Can later be passed to
970/// [`LeakDetector::assert_no_new_leaks`] to verify that no new entity
971/// handles remain between the snapshot and the current state.
972#[cfg(any(test, feature = "test-support", gpui_leak_detection))]
973#[derive(Default)]
974pub struct LeakDetectorSnapshot {
975    #[cfg(any(test, gpui_leak_detection))]
976    entity_ids: collections::HashSet<EntityId>,
977}
978
979#[cfg(any(test, gpui_leak_detection))]
980struct EntityLeakData {
981    handles: HashMap<HandleId, Option<backtrace::Backtrace>>,
982    type_name: &'static str,
983}
984
985#[cfg(any(test, gpui_leak_detection))]
986impl LeakDetector {
987    /// Records that a new handle has been created for the given entity.
988    ///
989    /// Returns a unique `HandleId` that must be passed to `handle_released` when
990    /// the handle is dropped. If `LEAK_BACKTRACE` is set, captures a backtrace
991    /// at the allocation site.
992    #[track_caller]
993    pub fn handle_created(
994        &mut self,
995        entity_id: EntityId,
996        type_name: Option<&'static str>,
997    ) -> HandleId {
998        let id = gpui_util::post_inc(&mut self.next_handle_id);
999        let handle_id = HandleId { id };
1000        let handles = self
1001            .entity_handles
1002            .entry(entity_id)
1003            .or_insert_with(|| EntityLeakData {
1004                handles: HashMap::default(),
1005                type_name: type_name.unwrap_or("<unknown>"),
1006            });
1007        handles.handles.insert(
1008            handle_id,
1009            LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
1010        );
1011        handle_id
1012    }
1013
1014    /// Records that a handle has been released (dropped).
1015    ///
1016    /// This removes the handle from tracking. The `handle_id` should be the same
1017    /// one returned by `handle_created` when the handle was allocated.
1018    pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
1019        if let std::collections::hash_map::Entry::Occupied(mut data) =
1020            self.entity_handles.entry(entity_id)
1021        {
1022            data.get_mut().handles.remove(&handle_id);
1023            if data.get().handles.is_empty() {
1024                data.remove();
1025            }
1026        }
1027    }
1028
1029    /// Asserts that all handles to the given entity have been released.
1030    ///
1031    /// # Panics
1032    ///
1033    /// Panics if any handles to the entity are still alive. The panic message
1034    /// includes backtraces for each leaked handle if `LEAK_BACKTRACE` is set,
1035    /// otherwise it suggests setting the environment variable to get more info.
1036    pub fn assert_released(&mut self, entity_id: EntityId) {
1037        use std::fmt::Write as _;
1038
1039        if let Some(data) = self.entity_handles.remove(&entity_id) {
1040            let mut out = String::new();
1041            for (_, backtrace) in data.handles {
1042                if let Some(mut backtrace) = backtrace {
1043                    backtrace.resolve();
1044                    let backtrace = BacktraceFormatter(backtrace);
1045                    writeln!(out, "Leaked handle:\n{:?}", backtrace).unwrap();
1046                } else {
1047                    writeln!(
1048                        out,
1049                        "Leaked handle: (export LEAK_BACKTRACE to find allocation site)"
1050                    )
1051                    .unwrap();
1052                }
1053            }
1054            panic!("Handles for {} leaked:\n{out}", data.type_name);
1055        }
1056    }
1057
1058    /// Captures a snapshot of all entity IDs that currently have alive handles.
1059    ///
1060    /// The returned [`LeakDetectorSnapshot`] can later be passed to
1061    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
1062    /// entities created after the snapshot are still alive.
1063    pub fn snapshot(&self) -> LeakDetectorSnapshot {
1064        LeakDetectorSnapshot {
1065            entity_ids: self.entity_handles.keys().copied().collect(),
1066        }
1067    }
1068
1069    /// Asserts that no entities created after `snapshot` still have alive handles.
1070    ///
1071    /// Entities that were already tracked at the time of the snapshot are ignored,
1072    /// even if they still have handles. Only *new* entities (those whose
1073    /// `EntityId` was not present in the snapshot) are considered leaks.
1074    ///
1075    /// # Panics
1076    ///
1077    /// Panics if any new entity handles exist. The panic message lists every
1078    /// leaked entity with its type name, and includes allocation-site backtraces
1079    /// when `LEAK_BACKTRACE` is set.
1080    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1081        use std::fmt::Write as _;
1082
1083        let mut out = String::new();
1084        for (entity_id, data) in &self.entity_handles {
1085            if snapshot.entity_ids.contains(entity_id) {
1086                continue;
1087            }
1088            for (_, backtrace) in &data.handles {
1089                if let Some(backtrace) = backtrace {
1090                    let mut backtrace = backtrace.clone();
1091                    backtrace.resolve();
1092                    let backtrace = BacktraceFormatter(backtrace);
1093                    writeln!(
1094                        out,
1095                        "Leaked handle for entity {} ({entity_id:?}):\n{:?}",
1096                        data.type_name, backtrace
1097                    )
1098                    .unwrap();
1099                } else {
1100                    writeln!(
1101                        out,
1102                        "Leaked handle for entity {} ({entity_id:?}): (export LEAK_BACKTRACE to find allocation site)",
1103                        data.type_name
1104                    )
1105                    .unwrap();
1106                }
1107            }
1108        }
1109
1110        if !out.is_empty() {
1111            panic!("New entity leaks detected since snapshot:\n{out}");
1112        }
1113    }
1114}
1115
1116#[cfg(any(test, gpui_leak_detection))]
1117impl Drop for LeakDetector {
1118    fn drop(&mut self) {
1119        use std::fmt::Write;
1120
1121        if self.entity_handles.is_empty() || std::thread::panicking() {
1122            return;
1123        }
1124
1125        let mut out = String::new();
1126        for (entity_id, data) in self.entity_handles.drain() {
1127            for (_handle, backtrace) in data.handles {
1128                if let Some(mut backtrace) = backtrace {
1129                    backtrace.resolve();
1130                    let backtrace = BacktraceFormatter(backtrace);
1131                    writeln!(
1132                        out,
1133                        "Leaked handle for entity {} ({entity_id:?}):\n{:?}",
1134                        data.type_name, backtrace
1135                    )
1136                    .unwrap();
1137                } else {
1138                    writeln!(
1139                        out,
1140                        "Leaked handle for entity {} ({entity_id:?}): (export LEAK_BACKTRACE to find allocation site)",
1141                        data.type_name
1142                    )
1143                    .unwrap();
1144                }
1145            }
1146        }
1147        panic!("Exited with leaked handles:\n{out}");
1148    }
1149}
1150
1151#[cfg(any(test, gpui_leak_detection))]
1152struct BacktraceFormatter(backtrace::Backtrace);
1153
1154#[cfg(any(test, gpui_leak_detection))]
1155impl fmt::Debug for BacktraceFormatter {
1156    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1157        use backtrace::{BacktraceFmt, BytesOrWideString, PrintFmt};
1158
1159        let style = if fmt.alternate() {
1160            PrintFmt::Full
1161        } else {
1162            PrintFmt::Short
1163        };
1164
1165        // When printing paths we try to strip the cwd if it exists, otherwise
1166        // we just print the path as-is. Note that we also only do this for the
1167        // short format, because if it's full we presumably want to print
1168        // everything.
1169        let cwd = std::env::current_dir();
1170        let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
1171            let path = path.into_path_buf();
1172            if style != PrintFmt::Full {
1173                if let Ok(cwd) = &cwd {
1174                    if let Ok(suffix) = path.strip_prefix(cwd) {
1175                        return fmt::Display::fmt(&suffix.display(), fmt);
1176                    }
1177                }
1178            }
1179            fmt::Display::fmt(&path.display(), fmt)
1180        };
1181
1182        let mut f = BacktraceFmt::new(fmt, style, &mut print_path);
1183        f.add_context()?;
1184        let mut strip = true;
1185        for frame in self.0.frames() {
1186            if let [symbol, ..] = frame.symbols()
1187                && let Some(name) = symbol.name()
1188                && let Some(filename) = name.as_str()
1189            {
1190                match filename {
1191                    "test::run_test_in_process"
1192                    | "scheduler::executor::spawn_local_with_source_location::impl$1::poll<core::pin::Pin<alloc::boxed::Box<dyn$<core::future::future::Future<assoc$<Output,enum2$<core::result::Result<workspace::OpenResult,anyhow::Error> > > > >,alloc::alloc::Global> > >" => {
1193                        strip = true
1194                    }
1195                    "gpui::app::entity_map::LeakDetector::handle_created" => {
1196                        strip = false;
1197                        continue;
1198                    }
1199                    "zed::main" => {
1200                        strip = true;
1201                        f.frame().backtrace_frame(frame)?;
1202                    }
1203                    _ => {}
1204                }
1205            }
1206            if strip {
1207                continue;
1208            }
1209            f.frame().backtrace_frame(frame)?;
1210        }
1211        f.finish()?;
1212        Ok(())
1213    }
1214}
1215
1216#[cfg(test)]
1217mod test {
1218    use crate::EntityMap;
1219
1220    struct TestEntity {
1221        pub i: i32,
1222    }
1223
1224    #[test]
1225    fn test_entity_map_slot_assignment_before_cleanup() {
1226        // Tests that slots are not re-used before take_dropped.
1227        let mut entity_map = EntityMap::new();
1228
1229        let slot = entity_map.reserve::<TestEntity>();
1230        entity_map.insert(slot, TestEntity { i: 1 });
1231
1232        let slot = entity_map.reserve::<TestEntity>();
1233        entity_map.insert(slot, TestEntity { i: 2 });
1234
1235        let dropped = entity_map.take_dropped();
1236        assert_eq!(dropped.len(), 2);
1237
1238        assert_eq!(
1239            dropped
1240                .into_iter()
1241                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1242                .collect::<Vec<i32>>(),
1243            vec![1, 2],
1244        );
1245    }
1246
1247    #[test]
1248    fn test_entity_map_weak_upgrade_before_cleanup() {
1249        // Tests that weak handles are not upgraded before take_dropped
1250        let mut entity_map = EntityMap::new();
1251
1252        let slot = entity_map.reserve::<TestEntity>();
1253        let handle = entity_map.insert(slot, TestEntity { i: 1 });
1254        let weak = handle.downgrade();
1255        drop(handle);
1256
1257        let strong = weak.upgrade();
1258        assert_eq!(strong, None);
1259
1260        let dropped = entity_map.take_dropped();
1261        assert_eq!(dropped.len(), 1);
1262
1263        assert_eq!(
1264            dropped
1265                .into_iter()
1266                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1267                .collect::<Vec<i32>>(),
1268            vec![1],
1269        );
1270    }
1271
1272    #[test]
1273    fn test_leak_detector_snapshot_no_leaks() {
1274        let mut entity_map = EntityMap::new();
1275
1276        let slot = entity_map.reserve::<TestEntity>();
1277        let pre_existing = entity_map.insert(slot, TestEntity { i: 1 });
1278
1279        let snapshot = entity_map.leak_detector_snapshot();
1280
1281        let slot = entity_map.reserve::<TestEntity>();
1282        let temporary = entity_map.insert(slot, TestEntity { i: 2 });
1283        drop(temporary);
1284
1285        entity_map.assert_no_new_leaks(&snapshot);
1286
1287        drop(pre_existing);
1288    }
1289
1290    #[test]
1291    #[should_panic(expected = "New entity leaks detected since snapshot")]
1292    fn test_leak_detector_snapshot_detects_new_leak() {
1293        let mut entity_map = EntityMap::new();
1294
1295        let slot = entity_map.reserve::<TestEntity>();
1296        let pre_existing = entity_map.insert(slot, TestEntity { i: 1 });
1297
1298        let snapshot = entity_map.leak_detector_snapshot();
1299
1300        let slot = entity_map.reserve::<TestEntity>();
1301        let leaked = entity_map.insert(slot, TestEntity { i: 2 });
1302
1303        // `leaked` is still alive, so this should panic.
1304        entity_map.assert_no_new_leaks(&snapshot);
1305
1306        drop(pre_existing);
1307        drop(leaked);
1308    }
1309}