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