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