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 f.debug_struct("Model")
438 .field("entity_id", &self.any_model.entity_id)
439 .field("entity_type", &type_name::<T>())
440 .finish()
441 }
442}
443
444impl<T> Hash for Model<T> {
445 fn hash<H: Hasher>(&self, state: &mut H) {
446 self.any_model.hash(state);
447 }
448}
449
450impl<T> PartialEq for Model<T> {
451 fn eq(&self, other: &Self) -> bool {
452 self.any_model == other.any_model
453 }
454}
455
456impl<T> Eq for Model<T> {}
457
458impl<T> PartialEq<WeakModel<T>> for Model<T> {
459 fn eq(&self, other: &WeakModel<T>) -> bool {
460 self.any_model.entity_id() == other.entity_id()
461 }
462}
463
464/// A type erased, weak reference to a model.
465#[derive(Clone)]
466pub struct AnyWeakModel {
467 pub(crate) entity_id: EntityId,
468 entity_type: TypeId,
469 entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
470}
471
472impl AnyWeakModel {
473 /// Get the entity ID associated with this weak reference.
474 pub fn entity_id(&self) -> EntityId {
475 self.entity_id
476 }
477
478 /// Check if this weak handle can be upgraded, or if the model has already been dropped
479 pub fn is_upgradable(&self) -> bool {
480 let ref_count = self
481 .entity_ref_counts
482 .upgrade()
483 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
484 .unwrap_or(0);
485 ref_count > 0
486 }
487
488 /// Upgrade this weak model reference to a strong reference.
489 pub fn upgrade(&self) -> Option<AnyModel> {
490 let ref_counts = &self.entity_ref_counts.upgrade()?;
491 let ref_counts = ref_counts.read();
492 let ref_count = ref_counts.counts.get(self.entity_id)?;
493
494 // entity_id is in dropped_entity_ids
495 if ref_count.load(SeqCst) == 0 {
496 return None;
497 }
498 ref_count.fetch_add(1, SeqCst);
499 drop(ref_counts);
500
501 Some(AnyModel {
502 entity_id: self.entity_id,
503 entity_type: self.entity_type,
504 entity_map: self.entity_ref_counts.clone(),
505 #[cfg(any(test, feature = "test-support"))]
506 handle_id: self
507 .entity_ref_counts
508 .upgrade()
509 .unwrap()
510 .write()
511 .leak_detector
512 .handle_created(self.entity_id),
513 })
514 }
515
516 /// Assert that model referenced by this weak handle has been released.
517 #[cfg(any(test, feature = "test-support"))]
518 pub fn assert_released(&self) {
519 self.entity_ref_counts
520 .upgrade()
521 .unwrap()
522 .write()
523 .leak_detector
524 .assert_released(self.entity_id);
525
526 if self
527 .entity_ref_counts
528 .upgrade()
529 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
530 .is_some()
531 {
532 panic!(
533 "entity was recently dropped but resources are retained until the end of the effect cycle."
534 )
535 }
536 }
537}
538
539impl std::fmt::Debug for AnyWeakModel {
540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541 f.debug_struct(type_name::<Self>())
542 .field("entity_id", &self.entity_id)
543 .field("entity_type", &self.entity_type)
544 .finish()
545 }
546}
547
548impl<T> From<WeakModel<T>> for AnyWeakModel {
549 fn from(model: WeakModel<T>) -> Self {
550 model.any_model
551 }
552}
553
554impl Hash for AnyWeakModel {
555 fn hash<H: Hasher>(&self, state: &mut H) {
556 self.entity_id.hash(state);
557 }
558}
559
560impl PartialEq for AnyWeakModel {
561 fn eq(&self, other: &Self) -> bool {
562 self.entity_id == other.entity_id
563 }
564}
565
566impl Eq for AnyWeakModel {}
567
568/// A weak reference to a model of the given type.
569#[derive(Deref, DerefMut)]
570pub struct WeakModel<T> {
571 #[deref]
572 #[deref_mut]
573 any_model: AnyWeakModel,
574 entity_type: PhantomData<T>,
575}
576
577impl<T> std::fmt::Debug for WeakModel<T> {
578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579 f.debug_struct(&type_name::<Self>())
580 .field("entity_id", &self.any_model.entity_id)
581 .field("entity_type", &type_name::<T>())
582 .finish()
583 }
584}
585
586unsafe impl<T> Send for WeakModel<T> {}
587unsafe impl<T> Sync for WeakModel<T> {}
588
589impl<T> Clone for WeakModel<T> {
590 fn clone(&self) -> Self {
591 Self {
592 any_model: self.any_model.clone(),
593 entity_type: self.entity_type,
594 }
595 }
596}
597
598impl<T: 'static> WeakModel<T> {
599 /// Upgrade this weak model reference into a strong model reference
600 pub fn upgrade(&self) -> Option<Model<T>> {
601 // Delegate to the trait implementation to keep behavior in one place.
602 Model::upgrade_from(self)
603 }
604
605 /// Updates the entity referenced by this model with the given function if
606 /// the referenced entity still exists. Returns an error if the entity has
607 /// been released.
608 pub fn update<C, R>(
609 &self,
610 cx: &mut C,
611 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
612 ) -> Result<R>
613 where
614 C: Context,
615 Result<C::Result<R>>: crate::Flatten<R>,
616 {
617 crate::Flatten::flatten(
618 self.upgrade()
619 .ok_or_else(|| anyhow!("entity release"))
620 .map(|this| cx.update_model(&this, update)),
621 )
622 }
623
624 /// Reads the entity referenced by this model with the given function if
625 /// the referenced entity still exists. Returns an error if the entity has
626 /// been released.
627 pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &AppContext) -> R) -> Result<R>
628 where
629 C: Context,
630 Result<C::Result<R>>: crate::Flatten<R>,
631 {
632 crate::Flatten::flatten(
633 self.upgrade()
634 .ok_or_else(|| anyhow!("entity release"))
635 .map(|this| cx.read_model(&this, read)),
636 )
637 }
638}
639
640impl<T> Hash for WeakModel<T> {
641 fn hash<H: Hasher>(&self, state: &mut H) {
642 self.any_model.hash(state);
643 }
644}
645
646impl<T> PartialEq for WeakModel<T> {
647 fn eq(&self, other: &Self) -> bool {
648 self.any_model == other.any_model
649 }
650}
651
652impl<T> Eq for WeakModel<T> {}
653
654impl<T> PartialEq<Model<T>> for WeakModel<T> {
655 fn eq(&self, other: &Model<T>) -> bool {
656 self.entity_id() == other.any_model.entity_id()
657 }
658}
659
660#[cfg(any(test, feature = "test-support"))]
661static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
662 std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty()));
663
664#[cfg(any(test, feature = "test-support"))]
665#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
666pub(crate) struct HandleId {
667 id: u64, // id of the handle itself, not the pointed at object
668}
669
670#[cfg(any(test, feature = "test-support"))]
671pub(crate) struct LeakDetector {
672 next_handle_id: u64,
673 entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
674}
675
676#[cfg(any(test, feature = "test-support"))]
677impl LeakDetector {
678 #[track_caller]
679 pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
680 let id = util::post_inc(&mut self.next_handle_id);
681 let handle_id = HandleId { id };
682 let handles = self.entity_handles.entry(entity_id).or_default();
683 handles.insert(
684 handle_id,
685 LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
686 );
687 handle_id
688 }
689
690 pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
691 let handles = self.entity_handles.entry(entity_id).or_default();
692 handles.remove(&handle_id);
693 }
694
695 pub fn assert_released(&mut self, entity_id: EntityId) {
696 let handles = self.entity_handles.entry(entity_id).or_default();
697 if !handles.is_empty() {
698 for backtrace in handles.values_mut() {
699 if let Some(mut backtrace) = backtrace.take() {
700 backtrace.resolve();
701 eprintln!("Leaked handle: {:#?}", backtrace);
702 } else {
703 eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
704 }
705 }
706 panic!();
707 }
708 }
709}
710
711#[cfg(test)]
712mod test {
713 use crate::EntityMap;
714
715 struct TestEntity {
716 pub i: i32,
717 }
718
719 #[test]
720 fn test_entity_map_slot_assignment_before_cleanup() {
721 // Tests that slots are not re-used before take_dropped.
722 let mut entity_map = EntityMap::new();
723
724 let slot = entity_map.reserve::<TestEntity>();
725 entity_map.insert(slot, TestEntity { i: 1 });
726
727 let slot = entity_map.reserve::<TestEntity>();
728 entity_map.insert(slot, TestEntity { i: 2 });
729
730 let dropped = entity_map.take_dropped();
731 assert_eq!(dropped.len(), 2);
732
733 assert_eq!(
734 dropped
735 .into_iter()
736 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
737 .collect::<Vec<i32>>(),
738 vec![1, 2],
739 );
740 }
741
742 #[test]
743 fn test_entity_map_weak_upgrade_before_cleanup() {
744 // Tests that weak handles are not upgraded before take_dropped
745 let mut entity_map = EntityMap::new();
746
747 let slot = entity_map.reserve::<TestEntity>();
748 let handle = entity_map.insert(slot, TestEntity { i: 1 });
749 let weak = handle.downgrade();
750 drop(handle);
751
752 let strong = weak.upgrade();
753 assert_eq!(strong, None);
754
755 let dropped = entity_map.take_dropped();
756 assert_eq!(dropped.len(), 1);
757
758 assert_eq!(
759 dropped
760 .into_iter()
761 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
762 .collect::<Vec<i32>>(),
763 vec![1],
764 );
765 }
766}