1use crate::{AnyBox, AppContext, Context};
2use anyhow::{anyhow, Result};
3use derive_more::{Deref, DerefMut};
4use parking_lot::{RwLock, RwLockUpgradableReadGuard};
5use slotmap::{SecondaryMap, SlotMap};
6use std::{
7 any::{type_name, Any, TypeId},
8 fmt::{self, Display},
9 hash::{Hash, Hasher},
10 marker::PhantomData,
11 mem,
12 sync::{
13 atomic::{AtomicUsize, Ordering::SeqCst},
14 Arc, Weak,
15 },
16};
17
18slotmap::new_key_type! { pub struct EntityId; }
19
20impl EntityId {
21 pub fn as_u64(self) -> u64 {
22 self.0.as_ffi()
23 }
24}
25
26impl Display for EntityId {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 write!(f, "{}", self)
29 }
30}
31
32pub(crate) struct EntityMap {
33 entities: SecondaryMap<EntityId, AnyBox>,
34 ref_counts: Arc<RwLock<EntityRefCounts>>,
35}
36
37struct EntityRefCounts {
38 counts: SlotMap<EntityId, AtomicUsize>,
39 dropped_entity_ids: Vec<EntityId>,
40}
41
42impl EntityMap {
43 pub fn new() -> Self {
44 Self {
45 entities: SecondaryMap::new(),
46 ref_counts: Arc::new(RwLock::new(EntityRefCounts {
47 counts: SlotMap::with_key(),
48 dropped_entity_ids: Vec::new(),
49 })),
50 }
51 }
52
53 /// Reserve a slot for an entity, which you can subsequently use with `insert`.
54 pub fn reserve<T: 'static>(&self) -> Slot<T> {
55 let id = self.ref_counts.write().counts.insert(1.into());
56 Slot(Handle::new(id, Arc::downgrade(&self.ref_counts)))
57 }
58
59 /// Insert an entity into a slot obtained by calling `reserve`.
60 pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Handle<T>
61 where
62 T: Any + Send + Sync,
63 {
64 let handle = slot.0;
65 self.entities.insert(handle.entity_id, Box::new(entity));
66 handle
67 }
68
69 /// Move an entity to the stack.
70 pub fn lease<'a, T>(&mut self, handle: &'a Handle<T>) -> Lease<'a, T> {
71 let entity = Some(
72 self.entities
73 .remove(handle.entity_id)
74 .expect("Circular entity lease. Is the entity already being updated?"),
75 );
76 Lease {
77 handle,
78 entity,
79 entity_type: PhantomData,
80 }
81 }
82
83 /// Return an entity after moving it to the stack.
84 pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
85 self.entities
86 .insert(lease.handle.entity_id, lease.entity.take().unwrap());
87 }
88
89 pub fn read<T>(&self, handle: &Handle<T>) -> &T {
90 (handle.downcast_entity)(&self.entities[handle.entity_id])
91 }
92
93 pub fn take_dropped(&mut self) -> Vec<(EntityId, AnyBox)> {
94 let dropped_entity_ids = mem::take(&mut self.ref_counts.write().dropped_entity_ids);
95 dropped_entity_ids
96 .into_iter()
97 .map(|entity_id| (entity_id, self.entities.remove(entity_id).unwrap()))
98 .collect()
99 }
100}
101
102pub struct Lease<'a, T> {
103 entity: Option<AnyBox>,
104 pub handle: &'a Handle<T>,
105 entity_type: PhantomData<T>,
106}
107
108impl<'a, T> core::ops::Deref for Lease<'a, T> {
109 type Target = T;
110
111 fn deref(&self) -> &Self::Target {
112 (self.handle.downcast_entity)(self.entity.as_ref().unwrap())
113 }
114}
115
116impl<'a, T> core::ops::DerefMut for Lease<'a, T> {
117 fn deref_mut(&mut self) -> &mut Self::Target {
118 (self.handle.downcast_entity_mut)(self.entity.as_mut().unwrap())
119 }
120}
121
122impl<'a, T> Drop for Lease<'a, T> {
123 fn drop(&mut self) {
124 if self.entity.is_some() {
125 // We don't panic here, because other panics can cause us to drop the lease without ending it cleanly.
126 log::error!("Leases must be ended with EntityMap::end_lease")
127 }
128 }
129}
130
131#[derive(Deref, DerefMut)]
132pub struct Slot<T>(Handle<T>);
133
134pub struct AnyHandle {
135 pub(crate) entity_id: EntityId,
136 entity_type: TypeId,
137 entity_map: Weak<RwLock<EntityRefCounts>>,
138}
139
140impl AnyHandle {
141 fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
142 Self {
143 entity_id: id,
144 entity_type,
145 entity_map,
146 }
147 }
148
149 pub fn entity_id(&self) -> EntityId {
150 self.entity_id
151 }
152
153 pub fn downgrade(&self) -> AnyWeakHandle {
154 AnyWeakHandle {
155 entity_id: self.entity_id,
156 entity_type: self.entity_type,
157 entity_ref_counts: self.entity_map.clone(),
158 }
159 }
160
161 pub fn downcast<T: 'static>(&self) -> Option<Handle<T>> {
162 if TypeId::of::<T>() == self.entity_type {
163 Some(Handle {
164 any_handle: self.clone(),
165 entity_type: PhantomData,
166 downcast_entity: |any| any.downcast_ref().unwrap(),
167 downcast_entity_mut: |any| any.downcast_mut().unwrap(),
168 })
169 } else {
170 None
171 }
172 }
173}
174
175impl Clone for AnyHandle {
176 fn clone(&self) -> Self {
177 if let Some(entity_map) = self.entity_map.upgrade() {
178 let entity_map = entity_map.read();
179 let count = entity_map
180 .counts
181 .get(self.entity_id)
182 .expect("detected over-release of a handle");
183 let prev_count = count.fetch_add(1, SeqCst);
184 assert_ne!(prev_count, 0, "Detected over-release of a handle.");
185 }
186
187 Self {
188 entity_id: self.entity_id,
189 entity_type: self.entity_type,
190 entity_map: self.entity_map.clone(),
191 }
192 }
193}
194
195impl Drop for AnyHandle {
196 fn drop(&mut self) {
197 if let Some(entity_map) = self.entity_map.upgrade() {
198 let entity_map = entity_map.upgradable_read();
199 let count = entity_map
200 .counts
201 .get(self.entity_id)
202 .expect("Detected over-release of a handle.");
203 let prev_count = count.fetch_sub(1, SeqCst);
204 assert_ne!(prev_count, 0, "Detected over-release of a handle.");
205 if prev_count == 1 {
206 // We were the last reference to this entity, so we can remove it.
207 let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
208 entity_map.counts.remove(self.entity_id);
209 entity_map.dropped_entity_ids.push(self.entity_id);
210 }
211 }
212 }
213}
214
215impl<T> From<Handle<T>> for AnyHandle {
216 fn from(handle: Handle<T>) -> Self {
217 handle.any_handle
218 }
219}
220
221impl Hash for AnyHandle {
222 fn hash<H: Hasher>(&self, state: &mut H) {
223 self.entity_id.hash(state);
224 }
225}
226
227impl PartialEq for AnyHandle {
228 fn eq(&self, other: &Self) -> bool {
229 self.entity_id == other.entity_id
230 }
231}
232
233impl Eq for AnyHandle {}
234
235#[derive(Deref, DerefMut)]
236pub struct Handle<T> {
237 #[deref]
238 #[deref_mut]
239 any_handle: AnyHandle,
240 entity_type: PhantomData<T>,
241 downcast_entity: fn(&dyn Any) -> &T,
242 downcast_entity_mut: fn(&mut dyn Any) -> &mut T,
243}
244
245unsafe impl<T> Send for Handle<T> {}
246unsafe impl<T> Sync for Handle<T> {}
247
248impl<T: 'static> Handle<T> {
249 fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
250 where
251 T: 'static,
252 {
253 Self {
254 any_handle: AnyHandle::new(id, TypeId::of::<T>(), entity_map),
255 entity_type: PhantomData,
256 downcast_entity: |any| any.downcast_ref().unwrap(),
257 downcast_entity_mut: |any| any.downcast_mut().unwrap(),
258 }
259 }
260
261 pub fn downgrade(&self) -> WeakHandle<T> {
262 WeakHandle {
263 any_handle: self.any_handle.downgrade(),
264 entity_type: self.entity_type,
265 downcast_entity: self.downcast_entity,
266 downcast_entity_mut: self.downcast_entity_mut,
267 }
268 }
269
270 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
271 cx.entities.read(self)
272 }
273
274 /// Update the entity referenced by this handle with the given function.
275 ///
276 /// The update function receives a context appropriate for its environment.
277 /// When updating in an `AppContext`, it receives a `ModelContext`.
278 /// When updating an a `WindowContext`, it receives a `ViewContext`.
279 pub fn update<C, R>(
280 &self,
281 cx: &mut C,
282 update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
283 ) -> C::Result<R>
284 where
285 C: Context,
286 {
287 cx.update_entity(self, update)
288 }
289}
290
291impl<T> Clone for Handle<T> {
292 fn clone(&self) -> Self {
293 Self {
294 any_handle: self.any_handle.clone(),
295 entity_type: self.entity_type,
296 downcast_entity: self.downcast_entity,
297 downcast_entity_mut: self.downcast_entity_mut,
298 }
299 }
300}
301
302impl<T> std::fmt::Debug for Handle<T> {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 write!(
305 f,
306 "Handle {{ entity_id: {:?}, entity_type: {:?} }}",
307 self.any_handle.entity_id,
308 type_name::<T>()
309 )
310 }
311}
312
313impl<T> Hash for Handle<T> {
314 fn hash<H: Hasher>(&self, state: &mut H) {
315 self.any_handle.hash(state);
316 }
317}
318
319impl<T> PartialEq for Handle<T> {
320 fn eq(&self, other: &Self) -> bool {
321 self.any_handle == other.any_handle
322 }
323}
324
325impl<T> Eq for Handle<T> {}
326
327#[derive(Clone)]
328pub struct AnyWeakHandle {
329 pub(crate) entity_id: EntityId,
330 entity_type: TypeId,
331 entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
332}
333
334impl AnyWeakHandle {
335 pub fn entity_id(&self) -> EntityId {
336 self.entity_id
337 }
338
339 pub fn is_upgradable(&self) -> bool {
340 let ref_count = self
341 .entity_ref_counts
342 .upgrade()
343 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
344 .unwrap_or(0);
345 ref_count > 0
346 }
347
348 pub fn upgrade(&self) -> Option<AnyHandle> {
349 let entity_map = self.entity_ref_counts.upgrade()?;
350 entity_map
351 .read()
352 .counts
353 .get(self.entity_id)?
354 .fetch_add(1, SeqCst);
355 Some(AnyHandle {
356 entity_id: self.entity_id,
357 entity_type: self.entity_type,
358 entity_map: self.entity_ref_counts.clone(),
359 })
360 }
361}
362
363impl<T> From<WeakHandle<T>> for AnyWeakHandle {
364 fn from(handle: WeakHandle<T>) -> Self {
365 handle.any_handle
366 }
367}
368
369impl Hash for AnyWeakHandle {
370 fn hash<H: Hasher>(&self, state: &mut H) {
371 self.entity_id.hash(state);
372 }
373}
374
375impl PartialEq for AnyWeakHandle {
376 fn eq(&self, other: &Self) -> bool {
377 self.entity_id == other.entity_id
378 }
379}
380
381impl Eq for AnyWeakHandle {}
382
383#[derive(Deref, DerefMut)]
384pub struct WeakHandle<T> {
385 #[deref]
386 #[deref_mut]
387 any_handle: AnyWeakHandle,
388 entity_type: PhantomData<T>,
389 downcast_entity: fn(&dyn Any) -> &T,
390 pub(crate) downcast_entity_mut: fn(&mut dyn Any) -> &mut T,
391}
392
393unsafe impl<T> Send for WeakHandle<T> {}
394unsafe impl<T> Sync for WeakHandle<T> {}
395
396impl<T> Clone for WeakHandle<T> {
397 fn clone(&self) -> Self {
398 Self {
399 any_handle: self.any_handle.clone(),
400 entity_type: self.entity_type,
401 downcast_entity: self.downcast_entity,
402 downcast_entity_mut: self.downcast_entity_mut,
403 }
404 }
405}
406
407impl<T: 'static> WeakHandle<T> {
408 pub fn upgrade(&self) -> Option<Handle<T>> {
409 Some(Handle {
410 any_handle: self.any_handle.upgrade()?,
411 entity_type: self.entity_type,
412 downcast_entity: self.downcast_entity,
413 downcast_entity_mut: self.downcast_entity_mut,
414 })
415 }
416
417 /// Update the entity referenced by this handle with the given function if
418 /// the referenced entity still exists. Returns an error if the entity has
419 /// been released.
420 ///
421 /// The update function receives a context appropriate for its environment.
422 /// When updating in an `AppContext`, it receives a `ModelContext`.
423 /// When updating an a `WindowContext`, it receives a `ViewContext`.
424 pub fn update<C, R>(
425 &self,
426 cx: &mut C,
427 update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
428 ) -> Result<R>
429 where
430 C: Context,
431 Result<C::Result<R>>: crate::Flatten<R>,
432 {
433 crate::Flatten::flatten(
434 self.upgrade()
435 .ok_or_else(|| anyhow!("entity release"))
436 .map(|this| cx.update_entity(&this, update)),
437 )
438 }
439}
440
441impl<T> Hash for WeakHandle<T> {
442 fn hash<H: Hasher>(&self, state: &mut H) {
443 self.any_handle.hash(state);
444 }
445}
446
447impl<T> PartialEq for WeakHandle<T> {
448 fn eq(&self, other: &Self) -> bool {
449 self.any_handle == other.any_handle
450 }
451}
452
453impl<T> Eq for WeakHandle<T> {}