1use crate::{seal::Sealed, AppContext, Context, Entity, ModelContext};
2use anyhow::{anyhow, Result};
3use derive_more::{Deref, DerefMut};
4use parking_lot::{RwLock, RwLockUpgradableReadGuard};
5use slotmap::{KeyData, SecondaryMap, SlotMap};
6use std::{
7 any::{type_name, Any, TypeId},
8 fmt::{self, Display},
9 hash::{Hash, Hasher},
10 marker::PhantomData,
11 mem,
12 num::NonZeroU64,
13 sync::{
14 atomic::{AtomicUsize, Ordering::SeqCst},
15 Arc, Weak,
16 },
17 thread::panicking,
18};
19
20#[cfg(any(test, feature = "test-support"))]
21use collections::HashMap;
22
23slotmap::new_key_type! {
24 /// A unique identifier for a model or view across the application.
25 pub struct EntityId;
26}
27
28impl From<u64> for EntityId {
29 fn from(value: u64) -> Self {
30 Self(KeyData::from_ffi(value))
31 }
32}
33
34impl EntityId {
35 /// Converts this entity id to a [NonZeroU64]
36 pub fn as_non_zero_u64(self) -> NonZeroU64 {
37 NonZeroU64::new(self.0.as_ffi()).unwrap()
38 }
39
40 /// Converts this entity id to a [u64]
41 pub fn as_u64(self) -> u64 {
42 self.0.as_ffi()
43 }
44}
45
46impl Display for EntityId {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 write!(f, "{}", self.as_u64())
49 }
50}
51
52pub(crate) struct EntityMap {
53 entities: SecondaryMap<EntityId, Box<dyn Any>>,
54 ref_counts: Arc<RwLock<EntityRefCounts>>,
55}
56
57struct EntityRefCounts {
58 counts: SlotMap<EntityId, AtomicUsize>,
59 dropped_entity_ids: Vec<EntityId>,
60 #[cfg(any(test, feature = "test-support"))]
61 leak_detector: LeakDetector,
62}
63
64impl EntityMap {
65 pub fn new() -> Self {
66 Self {
67 entities: SecondaryMap::new(),
68 ref_counts: Arc::new(RwLock::new(EntityRefCounts {
69 counts: SlotMap::with_key(),
70 dropped_entity_ids: Vec::new(),
71 #[cfg(any(test, feature = "test-support"))]
72 leak_detector: LeakDetector {
73 next_handle_id: 0,
74 entity_handles: HashMap::default(),
75 },
76 })),
77 }
78 }
79
80 /// Reserve a slot for an entity, which you can subsequently use with `insert`.
81 pub fn reserve<T: 'static>(&self) -> Slot<T> {
82 let id = self.ref_counts.write().counts.insert(1.into());
83 Slot(Model::new(id, Arc::downgrade(&self.ref_counts)))
84 }
85
86 /// Insert an entity into a slot obtained by calling `reserve`.
87 pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Model<T>
88 where
89 T: 'static,
90 {
91 let model = slot.0;
92 self.entities.insert(model.entity_id, Box::new(entity));
93 model
94 }
95
96 /// Move an entity to the stack.
97 #[track_caller]
98 pub fn lease<'a, T>(&mut self, model: &'a Model<T>) -> Lease<'a, T> {
99 self.assert_valid_context(model);
100 let entity = Some(self.entities.remove(model.entity_id).unwrap_or_else(|| {
101 panic!(
102 "Circular entity lease of {}. Is it already being updated?",
103 std::any::type_name::<T>()
104 )
105 }));
106 Lease {
107 model,
108 entity,
109 entity_type: PhantomData,
110 }
111 }
112
113 /// Returns an entity after moving it to the stack.
114 pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
115 self.entities
116 .insert(lease.model.entity_id, lease.entity.take().unwrap());
117 }
118
119 pub fn read<T: 'static>(&self, model: &Model<T>) -> &T {
120 self.assert_valid_context(model);
121 self.entities[model.entity_id].downcast_ref().unwrap()
122 }
123
124 fn assert_valid_context(&self, model: &AnyModel) {
125 debug_assert!(
126 Weak::ptr_eq(&model.entity_map, &Arc::downgrade(&self.ref_counts)),
127 "used a model with the wrong context"
128 );
129 }
130
131 pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
132 let mut ref_counts = self.ref_counts.write();
133 let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
134
135 dropped_entity_ids
136 .into_iter()
137 .filter_map(|entity_id| {
138 let count = ref_counts.counts.remove(entity_id).unwrap();
139 debug_assert_eq!(
140 count.load(SeqCst),
141 0,
142 "dropped an entity that was referenced"
143 );
144 // If the EntityId was allocated with `Context::reserve`,
145 // the entity may not have been inserted.
146 Some((entity_id, self.entities.remove(entity_id)?))
147 })
148 .collect()
149 }
150}
151
152pub(crate) struct Lease<'a, T> {
153 entity: Option<Box<dyn Any>>,
154 pub model: &'a Model<T>,
155 entity_type: PhantomData<T>,
156}
157
158impl<'a, T: 'static> core::ops::Deref for Lease<'a, T> {
159 type Target = T;
160
161 fn deref(&self) -> &Self::Target {
162 self.entity.as_ref().unwrap().downcast_ref().unwrap()
163 }
164}
165
166impl<'a, T: 'static> core::ops::DerefMut for Lease<'a, T> {
167 fn deref_mut(&mut self) -> &mut Self::Target {
168 self.entity.as_mut().unwrap().downcast_mut().unwrap()
169 }
170}
171
172impl<'a, T> Drop for Lease<'a, T> {
173 fn drop(&mut self) {
174 if self.entity.is_some() && !panicking() {
175 panic!("Leases must be ended with EntityMap::end_lease")
176 }
177 }
178}
179
180#[derive(Deref, DerefMut)]
181pub(crate) struct Slot<T>(Model<T>);
182
183/// A dynamically typed reference to a model, which can be downcast into a `Model<T>`.
184pub struct AnyModel {
185 pub(crate) entity_id: EntityId,
186 pub(crate) entity_type: TypeId,
187 entity_map: Weak<RwLock<EntityRefCounts>>,
188 #[cfg(any(test, feature = "test-support"))]
189 handle_id: HandleId,
190}
191
192impl AnyModel {
193 fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
194 Self {
195 entity_id: id,
196 entity_type,
197 entity_map: entity_map.clone(),
198 #[cfg(any(test, feature = "test-support"))]
199 handle_id: entity_map
200 .upgrade()
201 .unwrap()
202 .write()
203 .leak_detector
204 .handle_created(id),
205 }
206 }
207
208 /// Returns the id associated with this model.
209 pub fn entity_id(&self) -> EntityId {
210 self.entity_id
211 }
212
213 /// Returns the [TypeId] associated with this model.
214 pub fn entity_type(&self) -> TypeId {
215 self.entity_type
216 }
217
218 /// Converts this model handle into a weak variant, which does not prevent it from being released.
219 pub fn downgrade(&self) -> AnyWeakModel {
220 AnyWeakModel {
221 entity_id: self.entity_id,
222 entity_type: self.entity_type,
223 entity_ref_counts: self.entity_map.clone(),
224 }
225 }
226
227 /// Converts this model handle into a strongly-typed model handle of the given type.
228 /// If this model handle is not of the specified type, returns itself as an error variant.
229 pub fn downcast<T: 'static>(self) -> Result<Model<T>, AnyModel> {
230 if TypeId::of::<T>() == self.entity_type {
231 Ok(Model {
232 any_model: self,
233 entity_type: PhantomData,
234 })
235 } else {
236 Err(self)
237 }
238 }
239}
240
241impl Clone for AnyModel {
242 fn clone(&self) -> Self {
243 if let Some(entity_map) = self.entity_map.upgrade() {
244 let entity_map = entity_map.read();
245 let count = entity_map
246 .counts
247 .get(self.entity_id)
248 .expect("detected over-release of a model");
249 let prev_count = count.fetch_add(1, SeqCst);
250 assert_ne!(prev_count, 0, "Detected over-release of a model.");
251 }
252
253 Self {
254 entity_id: self.entity_id,
255 entity_type: self.entity_type,
256 entity_map: self.entity_map.clone(),
257 #[cfg(any(test, feature = "test-support"))]
258 handle_id: self
259 .entity_map
260 .upgrade()
261 .unwrap()
262 .write()
263 .leak_detector
264 .handle_created(self.entity_id),
265 }
266 }
267}
268
269impl Drop for AnyModel {
270 fn drop(&mut self) {
271 if let Some(entity_map) = self.entity_map.upgrade() {
272 let entity_map = entity_map.upgradable_read();
273 let count = entity_map
274 .counts
275 .get(self.entity_id)
276 .expect("detected over-release of a handle.");
277 let prev_count = count.fetch_sub(1, SeqCst);
278 assert_ne!(prev_count, 0, "Detected over-release of a model.");
279 if prev_count == 1 {
280 // We were the last reference to this entity, so we can remove it.
281 let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
282 entity_map.dropped_entity_ids.push(self.entity_id);
283 }
284 }
285
286 #[cfg(any(test, feature = "test-support"))]
287 if let Some(entity_map) = self.entity_map.upgrade() {
288 entity_map
289 .write()
290 .leak_detector
291 .handle_released(self.entity_id, self.handle_id)
292 }
293 }
294}
295
296impl<T> From<Model<T>> for AnyModel {
297 fn from(model: Model<T>) -> Self {
298 model.any_model
299 }
300}
301
302impl Hash for AnyModel {
303 fn hash<H: Hasher>(&self, state: &mut H) {
304 self.entity_id.hash(state);
305 }
306}
307
308impl PartialEq for AnyModel {
309 fn eq(&self, other: &Self) -> bool {
310 self.entity_id == other.entity_id
311 }
312}
313
314impl Eq for AnyModel {}
315
316impl std::fmt::Debug for AnyModel {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 f.debug_struct("AnyModel")
319 .field("entity_id", &self.entity_id.as_u64())
320 .finish()
321 }
322}
323
324/// A strong, well typed reference to a struct which is managed
325/// by GPUI
326#[derive(Deref, DerefMut)]
327pub struct Model<T> {
328 #[deref]
329 #[deref_mut]
330 pub(crate) any_model: AnyModel,
331 pub(crate) entity_type: PhantomData<T>,
332}
333
334unsafe impl<T> Send for Model<T> {}
335unsafe impl<T> Sync for Model<T> {}
336impl<T> Sealed for Model<T> {}
337
338impl<T: 'static> Entity<T> for Model<T> {
339 type Weak = WeakModel<T>;
340
341 fn entity_id(&self) -> EntityId {
342 self.any_model.entity_id
343 }
344
345 fn downgrade(&self) -> Self::Weak {
346 WeakModel {
347 any_model: self.any_model.downgrade(),
348 entity_type: self.entity_type,
349 }
350 }
351
352 fn upgrade_from(weak: &Self::Weak) -> Option<Self>
353 where
354 Self: Sized,
355 {
356 Some(Model {
357 any_model: weak.any_model.upgrade()?,
358 entity_type: weak.entity_type,
359 })
360 }
361}
362
363impl<T: 'static> Model<T> {
364 fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
365 where
366 T: 'static,
367 {
368 Self {
369 any_model: AnyModel::new(id, TypeId::of::<T>(), entity_map),
370 entity_type: PhantomData,
371 }
372 }
373
374 /// Downgrade the this to a weak model reference
375 pub fn downgrade(&self) -> WeakModel<T> {
376 // Delegate to the trait implementation to keep behavior in one place.
377 // This method was included to improve method resolution in the presence of
378 // the Model's deref
379 Entity::downgrade(self)
380 }
381
382 /// Convert this into a dynamically typed model.
383 pub fn into_any(self) -> AnyModel {
384 self.any_model
385 }
386
387 /// Grab a reference to this entity from the context.
388 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
389 cx.entities.read(self)
390 }
391
392 /// Read the entity referenced by this model with the given function.
393 pub fn read_with<R, C: Context>(
394 &self,
395 cx: &C,
396 f: impl FnOnce(&T, &AppContext) -> R,
397 ) -> C::Result<R> {
398 cx.read_model(self, f)
399 }
400
401 /// Updates the entity referenced by this model with the given function.
402 ///
403 /// The update function receives a context appropriate for its environment.
404 /// When updating in an `AppContext`, it receives a `ModelContext`.
405 /// When updating in a `WindowContext`, it receives a `ViewContext`.
406 pub fn update<C, R>(
407 &self,
408 cx: &mut C,
409 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
410 ) -> C::Result<R>
411 where
412 C: Context,
413 {
414 cx.update_model(self, update)
415 }
416}
417
418impl<T> Clone for Model<T> {
419 fn clone(&self) -> Self {
420 Self {
421 any_model: self.any_model.clone(),
422 entity_type: self.entity_type,
423 }
424 }
425}
426
427impl<T> std::fmt::Debug for Model<T> {
428 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429 write!(
430 f,
431 "Model {{ entity_id: {:?}, entity_type: {:?} }}",
432 self.any_model.entity_id,
433 type_name::<T>()
434 )
435 }
436}
437
438impl<T> Hash for Model<T> {
439 fn hash<H: Hasher>(&self, state: &mut H) {
440 self.any_model.hash(state);
441 }
442}
443
444impl<T> PartialEq for Model<T> {
445 fn eq(&self, other: &Self) -> bool {
446 self.any_model == other.any_model
447 }
448}
449
450impl<T> Eq for Model<T> {}
451
452impl<T> PartialEq<WeakModel<T>> for Model<T> {
453 fn eq(&self, other: &WeakModel<T>) -> bool {
454 self.any_model.entity_id() == other.entity_id()
455 }
456}
457
458/// A type erased, weak reference to a model.
459#[derive(Clone)]
460pub struct AnyWeakModel {
461 pub(crate) entity_id: EntityId,
462 entity_type: TypeId,
463 entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
464}
465
466impl AnyWeakModel {
467 /// Get the entity ID associated with this weak reference.
468 pub fn entity_id(&self) -> EntityId {
469 self.entity_id
470 }
471
472 /// Check if this weak handle can be upgraded, or if the model has already been dropped
473 pub fn is_upgradable(&self) -> bool {
474 let ref_count = self
475 .entity_ref_counts
476 .upgrade()
477 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
478 .unwrap_or(0);
479 ref_count > 0
480 }
481
482 /// Upgrade this weak model reference to a strong reference.
483 pub fn upgrade(&self) -> Option<AnyModel> {
484 let ref_counts = &self.entity_ref_counts.upgrade()?;
485 let ref_counts = ref_counts.read();
486 let ref_count = ref_counts.counts.get(self.entity_id)?;
487
488 // entity_id is in dropped_entity_ids
489 if ref_count.load(SeqCst) == 0 {
490 return None;
491 }
492 ref_count.fetch_add(1, SeqCst);
493 drop(ref_counts);
494
495 Some(AnyModel {
496 entity_id: self.entity_id,
497 entity_type: self.entity_type,
498 entity_map: self.entity_ref_counts.clone(),
499 #[cfg(any(test, feature = "test-support"))]
500 handle_id: self
501 .entity_ref_counts
502 .upgrade()
503 .unwrap()
504 .write()
505 .leak_detector
506 .handle_created(self.entity_id),
507 })
508 }
509
510 /// Assert that model referenced by this weak handle has been released.
511 #[cfg(any(test, feature = "test-support"))]
512 pub fn assert_released(&self) {
513 self.entity_ref_counts
514 .upgrade()
515 .unwrap()
516 .write()
517 .leak_detector
518 .assert_released(self.entity_id);
519
520 if self
521 .entity_ref_counts
522 .upgrade()
523 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
524 .is_some()
525 {
526 panic!(
527 "entity was recently dropped but resources are retained until the end of the effect cycle."
528 )
529 }
530 }
531}
532
533impl<T> From<WeakModel<T>> for AnyWeakModel {
534 fn from(model: WeakModel<T>) -> Self {
535 model.any_model
536 }
537}
538
539impl Hash for AnyWeakModel {
540 fn hash<H: Hasher>(&self, state: &mut H) {
541 self.entity_id.hash(state);
542 }
543}
544
545impl PartialEq for AnyWeakModel {
546 fn eq(&self, other: &Self) -> bool {
547 self.entity_id == other.entity_id
548 }
549}
550
551impl Eq for AnyWeakModel {}
552
553/// A weak reference to a model of the given type.
554#[derive(Deref, DerefMut)]
555pub struct WeakModel<T> {
556 #[deref]
557 #[deref_mut]
558 any_model: AnyWeakModel,
559 entity_type: PhantomData<T>,
560}
561
562unsafe impl<T> Send for WeakModel<T> {}
563unsafe impl<T> Sync for WeakModel<T> {}
564
565impl<T> Clone for WeakModel<T> {
566 fn clone(&self) -> Self {
567 Self {
568 any_model: self.any_model.clone(),
569 entity_type: self.entity_type,
570 }
571 }
572}
573
574impl<T: 'static> WeakModel<T> {
575 /// Upgrade this weak model reference into a strong model reference
576 pub fn upgrade(&self) -> Option<Model<T>> {
577 // Delegate to the trait implementation to keep behavior in one place.
578 Model::upgrade_from(self)
579 }
580
581 /// Updates the entity referenced by this model with the given function if
582 /// the referenced entity still exists. Returns an error if the entity has
583 /// been released.
584 pub fn update<C, R>(
585 &self,
586 cx: &mut C,
587 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
588 ) -> Result<R>
589 where
590 C: Context,
591 Result<C::Result<R>>: crate::Flatten<R>,
592 {
593 crate::Flatten::flatten(
594 self.upgrade()
595 .ok_or_else(|| anyhow!("entity release"))
596 .map(|this| cx.update_model(&this, update)),
597 )
598 }
599
600 /// Reads the entity referenced by this model with the given function if
601 /// the referenced entity still exists. Returns an error if the entity has
602 /// been released.
603 pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &AppContext) -> R) -> Result<R>
604 where
605 C: Context,
606 Result<C::Result<R>>: crate::Flatten<R>,
607 {
608 crate::Flatten::flatten(
609 self.upgrade()
610 .ok_or_else(|| anyhow!("entity release"))
611 .map(|this| cx.read_model(&this, read)),
612 )
613 }
614}
615
616impl<T> Hash for WeakModel<T> {
617 fn hash<H: Hasher>(&self, state: &mut H) {
618 self.any_model.hash(state);
619 }
620}
621
622impl<T> PartialEq for WeakModel<T> {
623 fn eq(&self, other: &Self) -> bool {
624 self.any_model == other.any_model
625 }
626}
627
628impl<T> Eq for WeakModel<T> {}
629
630impl<T> PartialEq<Model<T>> for WeakModel<T> {
631 fn eq(&self, other: &Model<T>) -> bool {
632 self.entity_id() == other.any_model.entity_id()
633 }
634}
635
636#[cfg(any(test, feature = "test-support"))]
637lazy_static::lazy_static! {
638 static ref LEAK_BACKTRACE: bool =
639 std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
640}
641
642#[cfg(any(test, feature = "test-support"))]
643#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
644pub(crate) struct HandleId {
645 id: u64, // id of the handle itself, not the pointed at object
646}
647
648#[cfg(any(test, feature = "test-support"))]
649pub(crate) struct LeakDetector {
650 next_handle_id: u64,
651 entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
652}
653
654#[cfg(any(test, feature = "test-support"))]
655impl LeakDetector {
656 #[track_caller]
657 pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
658 let id = util::post_inc(&mut self.next_handle_id);
659 let handle_id = HandleId { id };
660 let handles = self.entity_handles.entry(entity_id).or_default();
661 handles.insert(
662 handle_id,
663 LEAK_BACKTRACE.then(|| backtrace::Backtrace::new_unresolved()),
664 );
665 handle_id
666 }
667
668 pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
669 let handles = self.entity_handles.entry(entity_id).or_default();
670 handles.remove(&handle_id);
671 }
672
673 pub fn assert_released(&mut self, entity_id: EntityId) {
674 let handles = self.entity_handles.entry(entity_id).or_default();
675 if !handles.is_empty() {
676 for (_, backtrace) in handles {
677 if let Some(mut backtrace) = backtrace.take() {
678 backtrace.resolve();
679 eprintln!("Leaked handle: {:#?}", backtrace);
680 } else {
681 eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
682 }
683 }
684 panic!();
685 }
686 }
687}
688
689#[cfg(test)]
690mod test {
691 use crate::EntityMap;
692
693 struct TestEntity {
694 pub i: i32,
695 }
696
697 #[test]
698 fn test_entity_map_slot_assignment_before_cleanup() {
699 // Tests that slots are not re-used before take_dropped.
700 let mut entity_map = EntityMap::new();
701
702 let slot = entity_map.reserve::<TestEntity>();
703 entity_map.insert(slot, TestEntity { i: 1 });
704
705 let slot = entity_map.reserve::<TestEntity>();
706 entity_map.insert(slot, TestEntity { i: 2 });
707
708 let dropped = entity_map.take_dropped();
709 assert_eq!(dropped.len(), 2);
710
711 assert_eq!(
712 dropped
713 .into_iter()
714 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
715 .collect::<Vec<i32>>(),
716 vec![1, 2],
717 );
718 }
719
720 #[test]
721 fn test_entity_map_weak_upgrade_before_cleanup() {
722 // Tests that weak handles are not upgraded before take_dropped
723 let mut entity_map = EntityMap::new();
724
725 let slot = entity_map.reserve::<TestEntity>();
726 let handle = entity_map.insert(slot, TestEntity { i: 1 });
727 let weak = handle.downgrade();
728 drop(handle);
729
730 let strong = weak.upgrade();
731 assert_eq!(strong, None);
732
733 let dropped = entity_map.take_dropped();
734 assert_eq!(dropped.len(), 1);
735
736 assert_eq!(
737 dropped
738 .into_iter()
739 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
740 .collect::<Vec<i32>>(),
741 vec![1],
742 );
743 }
744}