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