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