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
326#[derive(Clone)]
327pub struct AnyWeakHandle {
328 pub(crate) entity_id: EntityId,
329 entity_type: TypeId,
330 entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
331}
332
333impl AnyWeakHandle {
334 pub fn entity_id(&self) -> EntityId {
335 self.entity_id
336 }
337
338 pub fn is_upgradable(&self) -> bool {
339 let ref_count = self
340 .entity_ref_counts
341 .upgrade()
342 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
343 .unwrap_or(0);
344 ref_count > 0
345 }
346
347 pub fn upgrade(&self) -> Option<AnyHandle> {
348 let entity_map = self.entity_ref_counts.upgrade()?;
349 entity_map
350 .read()
351 .counts
352 .get(self.entity_id)?
353 .fetch_add(1, SeqCst);
354 Some(AnyHandle {
355 entity_id: self.entity_id,
356 entity_type: self.entity_type,
357 entity_map: self.entity_ref_counts.clone(),
358 })
359 }
360}
361
362impl<T> From<WeakHandle<T>> for AnyWeakHandle {
363 fn from(handle: WeakHandle<T>) -> Self {
364 handle.any_handle
365 }
366}
367
368impl Hash for AnyWeakHandle {
369 fn hash<H: Hasher>(&self, state: &mut H) {
370 self.entity_id.hash(state);
371 }
372}
373
374impl PartialEq for AnyWeakHandle {
375 fn eq(&self, other: &Self) -> bool {
376 self.entity_id == other.entity_id
377 }
378}
379
380impl Eq for AnyWeakHandle {}
381
382#[derive(Deref, DerefMut)]
383pub struct WeakHandle<T> {
384 #[deref]
385 #[deref_mut]
386 any_handle: AnyWeakHandle,
387 entity_type: PhantomData<T>,
388}
389
390unsafe impl<T> Send for WeakHandle<T> {}
391unsafe impl<T> Sync for WeakHandle<T> {}
392
393impl<T> Clone for WeakHandle<T> {
394 fn clone(&self) -> Self {
395 Self {
396 any_handle: self.any_handle.clone(),
397 entity_type: self.entity_type,
398 }
399 }
400}
401
402impl<T: 'static> WeakHandle<T> {
403 pub fn upgrade(&self) -> Option<Handle<T>> {
404 Some(Handle {
405 any_handle: self.any_handle.upgrade()?,
406 entity_type: self.entity_type,
407 })
408 }
409
410 /// Update the entity referenced by this handle with the given function if
411 /// the referenced entity still exists. Returns an error if the entity has
412 /// been released.
413 ///
414 /// The update function receives a context appropriate for its environment.
415 /// When updating in an `AppContext`, it receives a `ModelContext`.
416 /// When updating an a `WindowContext`, it receives a `ViewContext`.
417 pub fn update<C, R>(
418 &self,
419 cx: &mut C,
420 update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
421 ) -> Result<R>
422 where
423 C: Context,
424 Result<C::Result<R>>: crate::Flatten<R>,
425 {
426 crate::Flatten::flatten(
427 self.upgrade()
428 .ok_or_else(|| anyhow!("entity release"))
429 .map(|this| cx.update_entity(&this, update)),
430 )
431 }
432}
433
434impl<T> Hash for WeakHandle<T> {
435 fn hash<H: Hasher>(&self, state: &mut H) {
436 self.any_handle.hash(state);
437 }
438}
439
440impl<T> PartialEq for WeakHandle<T> {
441 fn eq(&self, other: &Self) -> bool {
442 self.any_handle == other.any_handle
443 }
444}
445
446impl<T> Eq for WeakHandle<T> {}