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