entity_map.rs

  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<T> From<WeakModel<T>> for AnyWeakModel {
540    fn from(model: WeakModel<T>) -> Self {
541        model.any_model
542    }
543}
544
545impl Hash for AnyWeakModel {
546    fn hash<H: Hasher>(&self, state: &mut H) {
547        self.entity_id.hash(state);
548    }
549}
550
551impl PartialEq for AnyWeakModel {
552    fn eq(&self, other: &Self) -> bool {
553        self.entity_id == other.entity_id
554    }
555}
556
557impl Eq for AnyWeakModel {}
558
559/// A weak reference to a model of the given type.
560#[derive(Deref, DerefMut)]
561pub struct WeakModel<T> {
562    #[deref]
563    #[deref_mut]
564    any_model: AnyWeakModel,
565    entity_type: PhantomData<T>,
566}
567
568impl<T> std::fmt::Debug for WeakModel<T> {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        f.debug_struct(&type_name::<Self>())
571            .field("entity_id", &self.any_model.entity_id)
572            .field("entity_type", &type_name::<T>())
573            .finish()
574    }
575}
576
577unsafe impl<T> Send for WeakModel<T> {}
578unsafe impl<T> Sync for WeakModel<T> {}
579
580impl<T> Clone for WeakModel<T> {
581    fn clone(&self) -> Self {
582        Self {
583            any_model: self.any_model.clone(),
584            entity_type: self.entity_type,
585        }
586    }
587}
588
589impl<T: 'static> WeakModel<T> {
590    /// Upgrade this weak model reference into a strong model reference
591    pub fn upgrade(&self) -> Option<Model<T>> {
592        // Delegate to the trait implementation to keep behavior in one place.
593        Model::upgrade_from(self)
594    }
595
596    /// Updates the entity referenced by this model with the given function if
597    /// the referenced entity still exists. Returns an error if the entity has
598    /// been released.
599    pub fn update<C, R>(
600        &self,
601        cx: &mut C,
602        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
603    ) -> 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.update_model(&this, update)),
612        )
613    }
614
615    /// Reads the entity referenced by this model with the given function if
616    /// the referenced entity still exists. Returns an error if the entity has
617    /// been released.
618    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &AppContext) -> R) -> Result<R>
619    where
620        C: Context,
621        Result<C::Result<R>>: crate::Flatten<R>,
622    {
623        crate::Flatten::flatten(
624            self.upgrade()
625                .ok_or_else(|| anyhow!("entity release"))
626                .map(|this| cx.read_model(&this, read)),
627        )
628    }
629}
630
631impl<T> Hash for WeakModel<T> {
632    fn hash<H: Hasher>(&self, state: &mut H) {
633        self.any_model.hash(state);
634    }
635}
636
637impl<T> PartialEq for WeakModel<T> {
638    fn eq(&self, other: &Self) -> bool {
639        self.any_model == other.any_model
640    }
641}
642
643impl<T> Eq for WeakModel<T> {}
644
645impl<T> PartialEq<Model<T>> for WeakModel<T> {
646    fn eq(&self, other: &Model<T>) -> bool {
647        self.entity_id() == other.any_model.entity_id()
648    }
649}
650
651#[cfg(any(test, feature = "test-support"))]
652static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
653    std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty()));
654
655#[cfg(any(test, feature = "test-support"))]
656#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
657pub(crate) struct HandleId {
658    id: u64, // id of the handle itself, not the pointed at object
659}
660
661#[cfg(any(test, feature = "test-support"))]
662pub(crate) struct LeakDetector {
663    next_handle_id: u64,
664    entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
665}
666
667#[cfg(any(test, feature = "test-support"))]
668impl LeakDetector {
669    #[track_caller]
670    pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
671        let id = util::post_inc(&mut self.next_handle_id);
672        let handle_id = HandleId { id };
673        let handles = self.entity_handles.entry(entity_id).or_default();
674        handles.insert(
675            handle_id,
676            LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
677        );
678        handle_id
679    }
680
681    pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
682        let handles = self.entity_handles.entry(entity_id).or_default();
683        handles.remove(&handle_id);
684    }
685
686    pub fn assert_released(&mut self, entity_id: EntityId) {
687        let handles = self.entity_handles.entry(entity_id).or_default();
688        if !handles.is_empty() {
689            for backtrace in handles.values_mut() {
690                if let Some(mut backtrace) = backtrace.take() {
691                    backtrace.resolve();
692                    eprintln!("Leaked handle: {:#?}", backtrace);
693                } else {
694                    eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
695                }
696            }
697            panic!();
698        }
699    }
700}
701
702#[cfg(test)]
703mod test {
704    use crate::EntityMap;
705
706    struct TestEntity {
707        pub i: i32,
708    }
709
710    #[test]
711    fn test_entity_map_slot_assignment_before_cleanup() {
712        // Tests that slots are not re-used before take_dropped.
713        let mut entity_map = EntityMap::new();
714
715        let slot = entity_map.reserve::<TestEntity>();
716        entity_map.insert(slot, TestEntity { i: 1 });
717
718        let slot = entity_map.reserve::<TestEntity>();
719        entity_map.insert(slot, TestEntity { i: 2 });
720
721        let dropped = entity_map.take_dropped();
722        assert_eq!(dropped.len(), 2);
723
724        assert_eq!(
725            dropped
726                .into_iter()
727                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
728                .collect::<Vec<i32>>(),
729            vec![1, 2],
730        );
731    }
732
733    #[test]
734    fn test_entity_map_weak_upgrade_before_cleanup() {
735        // Tests that weak handles are not upgraded before take_dropped
736        let mut entity_map = EntityMap::new();
737
738        let slot = entity_map.reserve::<TestEntity>();
739        let handle = entity_map.insert(slot, TestEntity { i: 1 });
740        let weak = handle.downgrade();
741        drop(handle);
742
743        let strong = weak.upgrade();
744        assert_eq!(strong, None);
745
746        let dropped = entity_map.take_dropped();
747        assert_eq!(dropped.len(), 1);
748
749        assert_eq!(
750            dropped
751                .into_iter()
752                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
753                .collect::<Vec<i32>>(),
754            vec![1],
755        );
756    }
757}