1use crate::util::impl_deref;
2use crate::{App, AppContext, GpuiBorrow, VisualContext, Window, seal::Sealed};
3use anyhow::{Context as _, Result};
4use collections::FxHashSet;
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, gpui_leak_detection))]
26use collections::HashMap;
27
28slotmap::new_key_type! {
29 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 pub fn as_non_zero_u64(self) -> NonZeroU64 {
42 NonZeroU64::new(self.0.as_ffi()).unwrap()
43 }
44
45 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 accessed_entities: RefCell<AccessedEntities>,
60 ref_counts: Arc<RwLock<EntityRefCounts>>,
61}
62
63struct AccessedEntities {
69 frame: FxHashSet<EntityId>,
75 scopes: Vec<FxHashSet<EntityId>>,
77}
78
79impl AccessedEntities {
80 fn innermost(&mut self) -> &mut FxHashSet<EntityId> {
81 self.scopes.last_mut().unwrap_or(&mut self.frame)
82 }
83}
84
85#[doc(hidden)]
86pub(crate) struct EntityRefCounts {
87 counts: SlotMap<EntityId, AtomicUsize>,
88 dropped_entity_ids: Vec<EntityId>,
89 #[cfg(any(test, gpui_leak_detection))]
90 leak_detector: LeakDetector,
91}
92
93pub(super) struct LeaseInner {
94 pub(super) entity: Option<Box<dyn Any>>,
95}
96
97impl EntityMap {
98 pub fn new() -> Self {
99 Self {
100 entities: SecondaryMap::new(),
101 accessed_entities: RefCell::new(AccessedEntities {
102 frame: FxHashSet::default(),
103 scopes: Vec::new(),
104 }),
105 ref_counts: Arc::new(RwLock::new(EntityRefCounts {
106 counts: SlotMap::with_key(),
107 dropped_entity_ids: Vec::new(),
108 #[cfg(any(test, gpui_leak_detection))]
109 leak_detector: LeakDetector {
110 next_handle_id: 0,
111 entity_handles: HashMap::default(),
112 },
113 })),
114 }
115 }
116
117 #[doc(hidden)]
118 pub fn ref_counts_drop_handle(&self) -> Arc<RwLock<EntityRefCounts>> {
119 self.ref_counts.clone()
120 }
121
122 #[cfg(any(test, gpui_leak_detection))]
128 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
129 self.ref_counts.read().leak_detector.snapshot()
130 }
131
132 #[cfg(any(test, gpui_leak_detection))]
136 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
137 self.ref_counts
138 .read()
139 .leak_detector
140 .assert_no_new_leaks(snapshot)
141 }
142
143 pub fn reserve<T: 'static>(&self) -> Slot<T> {
145 let id = self.ref_counts.write().counts.insert(1.into());
146 Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
147 }
148
149 pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
151 where
152 T: 'static,
153 {
154 self.accessed_entities
155 .get_mut()
156 .innermost()
157 .insert(slot.entity_id);
158
159 let handle = slot.0;
160 self.entities.insert(handle.entity_id, Box::new(entity));
161 handle
162 }
163
164 #[track_caller]
166 pub fn lease<T>(&mut self, pointer: &Entity<T>) -> Lease<T> {
167 Lease {
168 inner: self.lease_erased(pointer, type_name::<T>()),
169 id: pointer.entity_id,
170 entity_type: PhantomData,
171 }
172 }
173
174 pub fn end_lease<T>(&mut self, lease: Lease<T>) {
176 self.end_lease_erased(lease.id, lease.inner);
177 }
178
179 #[inline(always)]
180 pub fn read<T: 'static>(&self, entity: &Entity<T>) -> &T {
181 self.assert_valid_context(entity);
182 self.read_inner(entity.entity_id)
183 .and_then(|entity| entity.downcast_ref())
184 .unwrap_or_else(|| double_lease_panic("read", type_name::<T>()))
185 }
186
187 #[track_caller]
188 pub(super) fn lease_erased(&mut self, pointer: &AnyEntity, entity_type: &str) -> LeaseInner {
189 self.assert_valid_context(pointer);
190 let entity = Some(
191 self.lease_inner(pointer.entity_id)
192 .unwrap_or_else(|| double_lease_panic("update", entity_type)),
193 );
194 LeaseInner { entity }
195 }
196
197 pub(super) fn end_lease_erased(&mut self, entity_id: EntityId, mut lease: LeaseInner) {
198 self.end_lease_inner(entity_id, lease.entity.take().unwrap());
199 }
200
201 fn assert_valid_context(&self, entity: &AnyEntity) {
202 debug_assert!(
203 Weak::ptr_eq(&entity.entity_map, &Arc::downgrade(&self.ref_counts)),
204 "used a entity with the wrong context"
205 );
206 }
207
208 pub fn extend_accessed(&mut self, entities: impl IntoIterator<Item = EntityId>) {
213 let ref_counts = self.ref_counts.read();
214 self.accessed_entities.get_mut().innermost().extend(
215 entities
216 .into_iter()
217 .filter(|entity_id| ref_counts.counts.contains_key(*entity_id)),
218 );
219 }
220
221 pub fn clear_accessed(&mut self) {
223 let accessed_entities = self.accessed_entities.get_mut();
224 accessed_entities.scopes.clear();
225 accessed_entities.frame.clear();
226 }
227
228 pub fn push_access_scope(&mut self) {
229 self.accessed_entities
230 .get_mut()
231 .scopes
232 .push(FxHashSet::default());
233 }
234
235 pub fn pop_access_scope(&mut self) -> FxHashSet<EntityId> {
238 let accessed_entities = self.accessed_entities.get_mut();
239 let Some(scope) = accessed_entities.scopes.pop() else {
240 debug_assert!(false, "popped an access scope that wasn't pushed");
241 return FxHashSet::default();
242 };
243 accessed_entities.innermost().extend(scope.iter().copied());
244 scope
245 }
246
247 pub fn take_accessed(&mut self) -> FxHashSet<EntityId> {
250 let accessed_entities = self.accessed_entities.get_mut();
251 debug_assert!(
252 accessed_entities.scopes.is_empty(),
253 "access scope left open"
254 );
255 mem::take(&mut accessed_entities.frame)
256 }
257
258 pub fn restore_accessed(&mut self, entities: FxHashSet<EntityId>) {
259 self.accessed_entities.get_mut().frame = entities;
260 }
261
262 pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
263 let ref_counts = &mut *self.ref_counts.write();
264 let dropped_entity_ids = ref_counts.dropped_entity_ids.drain(..);
265 let accessed_entities = self.accessed_entities.get_mut();
266
267 dropped_entity_ids
268 .filter_map(|entity_id| {
269 let count = ref_counts.counts.remove(entity_id).unwrap();
270 debug_assert_eq!(
271 count.load(SeqCst),
272 0,
273 "dropped an entity that was referenced"
274 );
275 accessed_entities.frame.remove(&entity_id);
276 for scope in &mut accessed_entities.scopes {
277 scope.remove(&entity_id);
278 }
279 Some((entity_id, self.entities.remove(entity_id)?))
282 })
283 .collect()
284 }
285
286 #[inline(never)]
287 fn read_inner(&self, entity_id: EntityId) -> Option<&dyn Any> {
288 self.accessed_entities
289 .borrow_mut()
290 .innermost()
291 .insert(entity_id);
292 self.entities.get(entity_id).map(Box::as_ref)
293 }
294
295 #[inline(never)]
296 fn lease_inner(&mut self, entity_id: EntityId) -> Option<Box<dyn Any>> {
297 self.accessed_entities
298 .get_mut()
299 .innermost()
300 .insert(entity_id);
301 self.entities.remove(entity_id)
302 }
303
304 #[inline(never)]
305 fn end_lease_inner(&mut self, entity_id: EntityId, entity: Box<dyn Any>) {
306 self.entities.insert(entity_id, entity);
307 }
308}
309
310#[track_caller]
311fn double_lease_panic(operation: &str, entity_type: &str) -> ! {
312 panic!("cannot {operation} {entity_type} while it is already being updated")
313}
314
315pub(crate) struct Lease<T> {
316 pub id: EntityId,
317 inner: LeaseInner,
318 entity_type: PhantomData<T>,
319}
320
321impl<T: 'static> core::ops::Deref for Lease<T> {
322 type Target = T;
323
324 fn deref(&self) -> &Self::Target {
325 self.inner.entity.as_ref().unwrap().downcast_ref().unwrap()
326 }
327}
328
329impl<T: 'static> core::ops::DerefMut for Lease<T> {
330 fn deref_mut(&mut self) -> &mut Self::Target {
331 self.inner.entity.as_mut().unwrap().downcast_mut().unwrap()
332 }
333}
334
335impl Drop for LeaseInner {
336 fn drop(&mut self) {
337 if self.entity.is_some() && !panicking() {
338 panic!("Leases must be ended with EntityMap::end_lease")
339 }
340 }
341}
342
343pub(crate) struct Slot<T>(Entity<T>);
344
345impl_deref!([T] Slot<T> => mut 0: Entity<T>);
346
347pub struct AnyEntity {
349 pub(crate) entity_id: EntityId,
350 pub(crate) entity_type: TypeId,
351 entity_map: Weak<RwLock<EntityRefCounts>>,
352 #[cfg(any(test, gpui_leak_detection))]
353 handle_id: HandleId,
354}
355
356impl AnyEntity {
357 fn new(
358 id: EntityId,
359 entity_type: TypeId,
360 entity_map: Weak<RwLock<EntityRefCounts>>,
361 #[cfg(any(test, gpui_leak_detection))] type_name: &'static str,
362 ) -> Self {
363 Self {
364 entity_id: id,
365 entity_type,
366 #[cfg(any(test, gpui_leak_detection))]
367 handle_id: entity_map
368 .clone()
369 .upgrade()
370 .unwrap()
371 .write()
372 .leak_detector
373 .handle_created(id, Some(type_name)),
374 entity_map,
375 }
376 }
377
378 #[inline]
380 pub fn entity_id(&self) -> EntityId {
381 self.entity_id
382 }
383
384 #[inline]
386 pub fn entity_type(&self) -> TypeId {
387 self.entity_type
388 }
389
390 pub fn downgrade(&self) -> AnyWeakEntity {
392 AnyWeakEntity {
393 entity_id: self.entity_id,
394 entity_type: self.entity_type,
395 entity_ref_counts: self.entity_map.clone(),
396 }
397 }
398
399 pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
402 if TypeId::of::<T>() == self.entity_type {
403 Ok(Entity {
404 any_entity: self,
405 entity_type: PhantomData,
406 })
407 } else {
408 Err(self)
409 }
410 }
411}
412
413impl Clone for AnyEntity {
414 fn clone(&self) -> Self {
415 if let Some(entity_map) = self.entity_map.upgrade() {
416 let entity_map = entity_map.read();
417 let count = entity_map
418 .counts
419 .get(self.entity_id)
420 .expect("detected over-release of a entity");
421 let prev_count = count.fetch_add(1, SeqCst);
422 assert_ne!(prev_count, 0, "Detected over-release of a entity.");
423 }
424
425 Self {
426 entity_id: self.entity_id,
427 entity_type: self.entity_type,
428 entity_map: self.entity_map.clone(),
429 #[cfg(any(test, gpui_leak_detection))]
430 handle_id: self
431 .entity_map
432 .upgrade()
433 .unwrap()
434 .write()
435 .leak_detector
436 .handle_created(self.entity_id, None),
437 }
438 }
439}
440
441impl Drop for AnyEntity {
442 fn drop(&mut self) {
443 if let Some(entity_map) = self.entity_map.upgrade() {
444 let entity_map = entity_map.upgradable_read();
445 let count = entity_map
446 .counts
447 .get(self.entity_id)
448 .expect("detected over-release of a handle.");
449 let prev_count = count.fetch_sub(1, SeqCst);
450 assert_ne!(prev_count, 0, "Detected over-release of a entity.");
451 if prev_count == 1 {
452 let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
454 entity_map.dropped_entity_ids.push(self.entity_id);
455 }
456 }
457
458 #[cfg(any(test, gpui_leak_detection))]
459 if let Some(entity_map) = self.entity_map.upgrade() {
460 entity_map
461 .write()
462 .leak_detector
463 .handle_released(self.entity_id, self.handle_id)
464 }
465 }
466}
467
468impl<T> From<Entity<T>> for AnyEntity {
469 #[inline]
470 fn from(entity: Entity<T>) -> Self {
471 entity.any_entity
472 }
473}
474
475impl Hash for AnyEntity {
476 #[inline]
477 fn hash<H: Hasher>(&self, state: &mut H) {
478 self.entity_id.hash(state);
479 }
480}
481
482impl PartialEq for AnyEntity {
483 #[inline]
484 fn eq(&self, other: &Self) -> bool {
485 self.entity_id == other.entity_id
486 }
487}
488
489impl Eq for AnyEntity {}
490
491impl Ord for AnyEntity {
492 #[inline]
493 fn cmp(&self, other: &Self) -> Ordering {
494 self.entity_id.cmp(&other.entity_id)
495 }
496}
497
498impl PartialOrd for AnyEntity {
499 #[inline]
500 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
501 Some(self.cmp(other))
502 }
503}
504
505impl std::fmt::Debug for AnyEntity {
506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507 f.debug_struct("AnyEntity")
508 .field("entity_id", &self.entity_id.as_u64())
509 .finish()
510 }
511}
512
513pub struct Entity<T> {
516 pub(crate) any_entity: AnyEntity,
517 pub(crate) entity_type: PhantomData<fn(T) -> T>,
518}
519
520impl_deref!([T] Entity<T> => mut any_entity: AnyEntity);
521
522impl<T> Sealed for Entity<T> {}
523
524impl<T: 'static> Entity<T> {
525 #[inline]
526 fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
527 where
528 T: 'static,
529 {
530 Self {
531 any_entity: AnyEntity::new(
532 id,
533 TypeId::of::<T>(),
534 entity_map,
535 #[cfg(any(test, gpui_leak_detection))]
536 std::any::type_name::<T>(),
537 ),
538 entity_type: PhantomData,
539 }
540 }
541
542 #[inline]
544 pub fn entity_id(&self) -> EntityId {
545 self.any_entity.entity_id
546 }
547
548 #[inline]
550 pub fn downgrade(&self) -> WeakEntity<T> {
551 WeakEntity {
552 any_entity: self.any_entity.downgrade(),
553 entity_type: self.entity_type,
554 }
555 }
556
557 #[inline]
559 pub fn into_any(self) -> AnyEntity {
560 self.any_entity
561 }
562
563 #[inline]
565 pub fn read<'a>(&self, cx: &'a App) -> &'a T {
566 cx.entities.read(self)
567 }
568
569 #[inline]
571 pub fn read_with<R, C: AppContext>(&self, cx: &C, f: impl FnOnce(&T, &App) -> R) -> R {
572 cx.read_entity(self, f)
573 }
574
575 #[inline]
577 pub fn update<R, C: AppContext>(
578 &self,
579 cx: &mut C,
580 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
581 ) -> R {
582 cx.update_entity(self, update)
583 }
584
585 #[inline]
587 pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> GpuiBorrow<'a, T> {
588 cx.as_mut(self)
589 }
590
591 pub fn write<C: AppContext>(&self, cx: &mut C, value: T) {
593 self.update(cx, |entity, cx| {
594 *entity = value;
595 cx.notify();
596 })
597 }
598
599 #[inline]
603 pub fn update_in<R, C: VisualContext>(
604 &self,
605 cx: &mut C,
606 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
607 ) -> C::Result<R> {
608 cx.update_window_entity(self, update)
609 }
610}
611
612impl<T> Clone for Entity<T> {
613 #[inline]
614 fn clone(&self) -> Self {
615 Self {
616 any_entity: self.any_entity.clone(),
617 entity_type: self.entity_type,
618 }
619 }
620}
621
622impl<T> std::fmt::Debug for Entity<T> {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 f.debug_struct("Entity")
625 .field("entity_id", &self.any_entity.entity_id)
626 .field("entity_type", &type_name::<T>())
627 .finish()
628 }
629}
630
631impl<T> Hash for Entity<T> {
632 #[inline]
633 fn hash<H: Hasher>(&self, state: &mut H) {
634 self.any_entity.hash(state);
635 }
636}
637
638impl<T> PartialEq for Entity<T> {
639 #[inline]
640 fn eq(&self, other: &Self) -> bool {
641 self.any_entity == other.any_entity
642 }
643}
644
645impl<T> Eq for Entity<T> {}
646
647impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
648 #[inline]
649 fn eq(&self, other: &WeakEntity<T>) -> bool {
650 self.any_entity.entity_id() == other.entity_id()
651 }
652}
653
654impl<T: 'static> Ord for Entity<T> {
655 #[inline]
656 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
657 self.entity_id().cmp(&other.entity_id())
658 }
659}
660
661impl<T: 'static> PartialOrd for Entity<T> {
662 #[inline]
663 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
664 Some(self.cmp(other))
665 }
666}
667
668#[derive(Clone)]
670pub struct AnyWeakEntity {
671 pub(crate) entity_id: EntityId,
672 entity_type: TypeId,
673 entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
674}
675
676impl AnyWeakEntity {
677 #[inline]
679 pub fn entity_id(&self) -> EntityId {
680 self.entity_id
681 }
682
683 pub fn is_upgradable(&self) -> bool {
685 let ref_count = self
686 .entity_ref_counts
687 .upgrade()
688 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
689 .unwrap_or(0);
690 ref_count > 0
691 }
692
693 pub fn upgrade(&self) -> Option<AnyEntity> {
695 let ref_counts = &self.entity_ref_counts.upgrade()?;
696 let ref_counts = ref_counts.read();
697 let ref_count = ref_counts.counts.get(self.entity_id)?;
698
699 if atomic_incr_if_not_zero(ref_count) == 0 {
700 return None;
702 }
703 drop(ref_counts);
704
705 Some(AnyEntity {
706 entity_id: self.entity_id,
707 entity_type: self.entity_type,
708 entity_map: self.entity_ref_counts.clone(),
709 #[cfg(any(test, gpui_leak_detection))]
710 handle_id: self
711 .entity_ref_counts
712 .upgrade()
713 .unwrap()
714 .write()
715 .leak_detector
716 .handle_created(self.entity_id, None),
717 })
718 }
719
720 #[cfg(any(test, feature = "test-support", gpui_leak_detection))]
749 pub fn assert_released(&self) {
750 #[cfg(any(test, gpui_leak_detection))]
751 self.entity_ref_counts
752 .upgrade()
753 .unwrap()
754 .write()
755 .leak_detector
756 .assert_released(self.entity_id);
757
758 if self
759 .entity_ref_counts
760 .upgrade()
761 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
762 .is_some()
763 {
764 panic!(
765 "entity is still alive, or was recently dropped and its resources are retained \
766 until the end of the effect cycle. Build with GPUI_LEAK_DETECTION=1 to list \
767 its live handles."
768 )
769 }
770 }
771
772 pub fn new_invalid() -> Self {
774 static UNIQUE_NON_CONFLICTING_ID_GENERATOR: AtomicU64 = AtomicU64::new(u64::MAX);
778 let entity_id = UNIQUE_NON_CONFLICTING_ID_GENERATOR.fetch_sub(1, SeqCst);
779
780 Self {
781 entity_id: entity_id.into(),
791 entity_type: TypeId::of::<()>(),
792 entity_ref_counts: Weak::new(),
793 }
794 }
795}
796
797impl std::fmt::Debug for AnyWeakEntity {
798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799 f.debug_struct(type_name::<Self>())
800 .field("entity_id", &self.entity_id)
801 .field("entity_type", &self.entity_type)
802 .finish()
803 }
804}
805
806impl<T> From<WeakEntity<T>> for AnyWeakEntity {
807 #[inline]
808 fn from(entity: WeakEntity<T>) -> Self {
809 entity.any_entity
810 }
811}
812
813impl Hash for AnyWeakEntity {
814 #[inline]
815 fn hash<H: Hasher>(&self, state: &mut H) {
816 self.entity_id.hash(state);
817 }
818}
819
820impl PartialEq for AnyWeakEntity {
821 #[inline]
822 fn eq(&self, other: &Self) -> bool {
823 self.entity_id == other.entity_id
824 }
825}
826
827impl Eq for AnyWeakEntity {}
828
829impl Ord for AnyWeakEntity {
830 #[inline]
831 fn cmp(&self, other: &Self) -> Ordering {
832 self.entity_id.cmp(&other.entity_id)
833 }
834}
835
836impl PartialOrd for AnyWeakEntity {
837 #[inline]
838 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
839 Some(self.cmp(other))
840 }
841}
842
843pub struct WeakEntity<T> {
845 any_entity: AnyWeakEntity,
846 entity_type: PhantomData<fn(T) -> T>,
847}
848
849impl_deref!([T] WeakEntity<T> => mut any_entity: AnyWeakEntity);
850
851impl<T> std::fmt::Debug for WeakEntity<T> {
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 f.debug_struct(type_name::<Self>())
854 .field("entity_id", &self.any_entity.entity_id)
855 .field("entity_type", &type_name::<T>())
856 .finish()
857 }
858}
859
860impl<T> Clone for WeakEntity<T> {
861 fn clone(&self) -> Self {
862 Self {
863 any_entity: self.any_entity.clone(),
864 entity_type: self.entity_type,
865 }
866 }
867}
868
869impl<T: 'static> WeakEntity<T> {
870 pub fn upgrade(&self) -> Option<Entity<T>> {
872 Some(Entity {
873 any_entity: self.any_entity.upgrade()?,
874 entity_type: self.entity_type,
875 })
876 }
877
878 #[inline(always)]
882 pub fn update<C, R>(
883 &self,
884 cx: &mut C,
885 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
886 ) -> Result<R>
887 where
888 C: AppContext,
889 {
890 let entity = self.upgrade().context("entity released")?;
891 Ok(cx.update_entity(&entity, update))
892 }
893
894 #[inline(always)]
898 pub fn update_in<C, R>(
899 &self,
900 cx: &mut C,
901 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
902 ) -> Result<R>
903 where
904 C: AppContext,
905 {
906 let entity = self.upgrade().context("entity released")?;
907 cx.with_window(entity.entity_id(), |window, app| {
908 entity.update(app, |entity, cx| update(entity, window, cx))
909 })
910 .context("entity has no current window")
911 }
912
913 #[inline(always)]
917 pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
918 where
919 C: AppContext,
920 {
921 let entity = self.upgrade().context("entity released")?;
922 Ok(cx.read_entity(&entity, read))
923 }
924
925 #[inline]
927 pub fn new_invalid() -> Self {
928 Self {
929 any_entity: AnyWeakEntity::new_invalid(),
930 entity_type: PhantomData,
931 }
932 }
933}
934
935impl<T> Hash for WeakEntity<T> {
936 #[inline]
937 fn hash<H: Hasher>(&self, state: &mut H) {
938 self.any_entity.hash(state);
939 }
940}
941
942impl<T> PartialEq for WeakEntity<T> {
943 #[inline]
944 fn eq(&self, other: &Self) -> bool {
945 self.any_entity == other.any_entity
946 }
947}
948
949impl<T> Eq for WeakEntity<T> {}
950
951impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
952 #[inline]
953 fn eq(&self, other: &Entity<T>) -> bool {
954 self.entity_id() == other.any_entity.entity_id()
955 }
956}
957
958impl<T: 'static> Ord for WeakEntity<T> {
959 #[inline]
960 fn cmp(&self, other: &Self) -> Ordering {
961 self.entity_id().cmp(&other.entity_id())
962 }
963}
964
965impl<T: 'static> PartialOrd for WeakEntity<T> {
966 #[inline]
967 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
968 Some(self.cmp(other))
969 }
970}
971
972#[cfg(any(test, gpui_leak_detection))]
977static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
978 std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
979
980#[cfg(any(test, gpui_leak_detection))]
985#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
986pub(crate) struct HandleId {
987 id: u64,
988}
989
990#[cfg(any(test, gpui_leak_detection))]
1040pub(crate) struct LeakDetector {
1041 next_handle_id: u64,
1042 entity_handles: HashMap<EntityId, EntityLeakData>,
1043}
1044
1045#[cfg(any(test, feature = "test-support", gpui_leak_detection))]
1051#[derive(Default)]
1052pub struct LeakDetectorSnapshot {
1053 #[cfg(any(test, gpui_leak_detection))]
1054 entity_ids: collections::HashSet<EntityId>,
1055}
1056
1057#[cfg(any(test, gpui_leak_detection))]
1058struct EntityLeakData {
1059 handles: HashMap<HandleId, Option<backtrace::Backtrace>>,
1060 type_name: &'static str,
1061}
1062
1063#[cfg(any(test, gpui_leak_detection))]
1064impl LeakDetector {
1065 #[track_caller]
1071 pub fn handle_created(
1072 &mut self,
1073 entity_id: EntityId,
1074 type_name: Option<&'static str>,
1075 ) -> HandleId {
1076 let id = gpui_util::post_inc(&mut self.next_handle_id);
1077 let handle_id = HandleId { id };
1078 let handles = self
1079 .entity_handles
1080 .entry(entity_id)
1081 .or_insert_with(|| EntityLeakData {
1082 handles: HashMap::default(),
1083 type_name: type_name.unwrap_or("<unknown>"),
1084 });
1085 handles.handles.insert(
1086 handle_id,
1087 LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
1088 );
1089 handle_id
1090 }
1091
1092 pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
1097 if let std::collections::hash_map::Entry::Occupied(mut data) =
1098 self.entity_handles.entry(entity_id)
1099 {
1100 data.get_mut().handles.remove(&handle_id);
1101 if data.get().handles.is_empty() {
1102 data.remove();
1103 }
1104 }
1105 }
1106
1107 pub fn assert_released(&mut self, entity_id: EntityId) {
1115 use std::fmt::Write as _;
1116
1117 if let Some(data) = self.entity_handles.remove(&entity_id) {
1118 let mut out = String::new();
1119 for (_, backtrace) in data.handles {
1120 if let Some(mut backtrace) = backtrace {
1121 backtrace.resolve();
1122 let backtrace = BacktraceFormatter(backtrace);
1123 writeln!(out, "Leaked handle:\n{:?}", backtrace).unwrap();
1124 } else {
1125 writeln!(
1126 out,
1127 "Leaked handle: (export LEAK_BACKTRACE to find allocation site)"
1128 )
1129 .unwrap();
1130 }
1131 }
1132 panic!("Handles for {} leaked:\n{out}", data.type_name);
1133 }
1134 }
1135
1136 pub fn snapshot(&self) -> LeakDetectorSnapshot {
1142 LeakDetectorSnapshot {
1143 entity_ids: self.entity_handles.keys().copied().collect(),
1144 }
1145 }
1146
1147 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1159 use std::fmt::Write as _;
1160
1161 let mut out = String::new();
1162 for (entity_id, data) in &self.entity_handles {
1163 if snapshot.entity_ids.contains(entity_id) {
1164 continue;
1165 }
1166 for (_, backtrace) in &data.handles {
1167 if let Some(backtrace) = backtrace {
1168 let mut backtrace = backtrace.clone();
1169 backtrace.resolve();
1170 let backtrace = BacktraceFormatter(backtrace);
1171 writeln!(
1172 out,
1173 "Leaked handle for entity {} ({entity_id:?}):\n{:?}",
1174 data.type_name, backtrace
1175 )
1176 .unwrap();
1177 } else {
1178 writeln!(
1179 out,
1180 "Leaked handle for entity {} ({entity_id:?}): (export LEAK_BACKTRACE to find allocation site)",
1181 data.type_name
1182 )
1183 .unwrap();
1184 }
1185 }
1186 }
1187
1188 if !out.is_empty() {
1189 panic!("New entity leaks detected since snapshot:\n{out}");
1190 }
1191 }
1192}
1193
1194#[cfg(any(test, gpui_leak_detection))]
1195impl Drop for LeakDetector {
1196 fn drop(&mut self) {
1197 use std::fmt::Write;
1198
1199 if self.entity_handles.is_empty() || std::thread::panicking() {
1200 return;
1201 }
1202
1203 let mut out = String::new();
1204 for (entity_id, data) in self.entity_handles.drain() {
1205 for (_handle, backtrace) in data.handles {
1206 if let Some(mut backtrace) = backtrace {
1207 backtrace.resolve();
1208 let backtrace = BacktraceFormatter(backtrace);
1209 writeln!(
1210 out,
1211 "Leaked handle for entity {} ({entity_id:?}):\n{:?}",
1212 data.type_name, backtrace
1213 )
1214 .unwrap();
1215 } else {
1216 writeln!(
1217 out,
1218 "Leaked handle for entity {} ({entity_id:?}): (export LEAK_BACKTRACE to find allocation site)",
1219 data.type_name
1220 )
1221 .unwrap();
1222 }
1223 }
1224 }
1225 panic!("Exited with leaked handles:\n{out}");
1226 }
1227}
1228
1229#[cfg(any(test, gpui_leak_detection))]
1230struct BacktraceFormatter(backtrace::Backtrace);
1231
1232#[cfg(any(test, gpui_leak_detection))]
1233impl fmt::Debug for BacktraceFormatter {
1234 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1235 use backtrace::{BacktraceFmt, BytesOrWideString, PrintFmt};
1236
1237 let style = if fmt.alternate() {
1238 PrintFmt::Full
1239 } else {
1240 PrintFmt::Short
1241 };
1242
1243 let cwd = std::env::current_dir();
1248 let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
1249 let path = path.into_path_buf();
1250 if style != PrintFmt::Full {
1251 if let Ok(cwd) = &cwd {
1252 if let Ok(suffix) = path.strip_prefix(cwd) {
1253 return fmt::Display::fmt(&suffix.display(), fmt);
1254 }
1255 }
1256 }
1257 fmt::Display::fmt(&path.display(), fmt)
1258 };
1259
1260 let mut f = BacktraceFmt::new(fmt, style, &mut print_path);
1261 f.add_context()?;
1262 let mut strip = true;
1263 for frame in self.0.frames() {
1264 if let [symbol, ..] = frame.symbols()
1265 && let Some(name) = symbol.name()
1266 && let Some(filename) = name.as_str()
1267 {
1268 match filename {
1269 "test::run_test_in_process"
1270 | "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> > >" => {
1271 strip = true
1272 }
1273 "gpui::app::entity_map::LeakDetector::handle_created" => {
1274 strip = false;
1275 continue;
1276 }
1277 "zed::main" => {
1278 strip = true;
1279 f.frame().backtrace_frame(frame)?;
1280 }
1281 _ => {}
1282 }
1283 }
1284 if strip {
1285 continue;
1286 }
1287 f.frame().backtrace_frame(frame)?;
1288 }
1289 f.finish()?;
1290 Ok(())
1291 }
1292}
1293
1294#[cfg(test)]
1295mod test {
1296 use crate::EntityMap;
1297 use collections::FxHashSet;
1298
1299 struct TestEntity {
1300 pub i: i32,
1301 }
1302
1303 #[test]
1304 fn test_accessed_entity_scopes() {
1305 let mut entity_map = EntityMap::new();
1306 let slot = entity_map.reserve::<TestEntity>();
1307 let first = entity_map.insert(slot, TestEntity { i: 1 });
1308 let slot = entity_map.reserve::<TestEntity>();
1309 let second = entity_map.insert(slot, TestEntity { i: 2 });
1310 entity_map.clear_accessed();
1311
1312 entity_map.read(&first);
1313 entity_map.push_access_scope();
1314 entity_map.read(&first);
1315 entity_map.push_access_scope();
1316 entity_map.read(&second);
1317 let inner = entity_map.pop_access_scope();
1318 let outer = entity_map.pop_access_scope();
1319
1320 assert_eq!(inner, FxHashSet::from_iter([second.entity_id()]));
1321 let both = FxHashSet::from_iter([first.entity_id(), second.entity_id()]);
1322 assert_eq!(outer, both);
1323 assert_eq!(entity_map.take_accessed(), both);
1324
1325 drop(second);
1326 entity_map.take_dropped();
1327 entity_map.extend_accessed(both);
1328 assert_eq!(
1329 entity_map.take_accessed(),
1330 FxHashSet::from_iter([first.entity_id()]),
1331 "a released entity shouldn't be recorded again"
1332 );
1333 }
1334
1335 #[test]
1336 fn test_entity_map_slot_assignment_before_cleanup() {
1337 let mut entity_map = EntityMap::new();
1339
1340 let slot = entity_map.reserve::<TestEntity>();
1341 entity_map.insert(slot, TestEntity { i: 1 });
1342
1343 let slot = entity_map.reserve::<TestEntity>();
1344 entity_map.insert(slot, TestEntity { i: 2 });
1345
1346 let dropped = entity_map.take_dropped();
1347 assert_eq!(dropped.len(), 2);
1348
1349 assert_eq!(
1350 dropped
1351 .into_iter()
1352 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1353 .collect::<Vec<i32>>(),
1354 vec![1, 2],
1355 );
1356 }
1357
1358 #[test]
1359 fn test_entity_map_weak_upgrade_before_cleanup() {
1360 let mut entity_map = EntityMap::new();
1362
1363 let slot = entity_map.reserve::<TestEntity>();
1364 let handle = entity_map.insert(slot, TestEntity { i: 1 });
1365 let weak = handle.downgrade();
1366 drop(handle);
1367
1368 let strong = weak.upgrade();
1369 assert_eq!(strong, None);
1370
1371 let dropped = entity_map.take_dropped();
1372 assert_eq!(dropped.len(), 1);
1373
1374 assert_eq!(
1375 dropped
1376 .into_iter()
1377 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1378 .collect::<Vec<i32>>(),
1379 vec![1],
1380 );
1381 }
1382
1383 #[test]
1384 fn test_leak_detector_snapshot_no_leaks() {
1385 let mut entity_map = EntityMap::new();
1386
1387 let slot = entity_map.reserve::<TestEntity>();
1388 let pre_existing = entity_map.insert(slot, TestEntity { i: 1 });
1389
1390 let snapshot = entity_map.leak_detector_snapshot();
1391
1392 let slot = entity_map.reserve::<TestEntity>();
1393 let temporary = entity_map.insert(slot, TestEntity { i: 2 });
1394 drop(temporary);
1395
1396 entity_map.assert_no_new_leaks(&snapshot);
1397
1398 drop(pre_existing);
1399 }
1400
1401 #[test]
1402 #[should_panic(expected = "New entity leaks detected since snapshot")]
1403 fn test_leak_detector_snapshot_detects_new_leak() {
1404 let mut entity_map = EntityMap::new();
1405
1406 let slot = entity_map.reserve::<TestEntity>();
1407 let pre_existing = entity_map.insert(slot, TestEntity { i: 1 });
1408
1409 let snapshot = entity_map.leak_detector_snapshot();
1410
1411 let slot = entity_map.reserve::<TestEntity>();
1412 let leaked = entity_map.insert(slot, TestEntity { i: 2 });
1413
1414 entity_map.assert_no_new_leaks(&snapshot);
1416
1417 drop(pre_existing);
1418 drop(leaked);
1419 }
1420}