This commit is contained in:
Antonio Scandurra
2023-10-23 14:59:57 +02:00
parent a72434f67b
commit 4e6fb9034d
7 changed files with 289 additions and 198 deletions
+12 -11
View File
@@ -56,7 +56,7 @@ impl App {
);
let text_system = Arc::new(TextSystem::new(platform.text_system()));
let entities = EntityMap::new();
let mut entities = EntityMap::new();
let unit_entity = entities.insert(entities.reserve(), ());
let app_metadata = AppMetadata {
os_name: platform.os_name(),
@@ -190,7 +190,7 @@ pub struct AppContext {
pub(crate) observers: SubscriberSet<EntityId, Handler>,
pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
pub(crate) global_observers: SubscriberSet<TypeId, Listener>,
pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
pub(crate) propagate_event: bool,
@@ -427,12 +427,10 @@ impl AppContext {
}
fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
self.pending_global_notifications.insert(type_id);
let global = self.globals_by_type.remove(&type_id).unwrap();
self.pending_global_notifications.remove(&type_id);
self.global_observers
.clone()
.retain(&type_id, |observer| observer(global.as_ref(), self));
self.globals_by_type.insert(type_id, global);
.retain(&type_id, |observer| observer(self));
}
pub fn to_async(&self) -> AsyncAppContext {
@@ -563,12 +561,12 @@ impl AppContext {
pub fn observe_global<G: 'static>(
&mut self,
f: impl Fn(&G, &mut Self) + Send + Sync + 'static,
f: impl Fn(&mut Self) + Send + Sync + 'static,
) -> Subscription {
self.global_observers.insert(
TypeId::of::<G>(),
Box::new(move |global, cx| {
f(global.downcast_ref::<G>().unwrap(), cx);
Box::new(move |cx| {
f(cx);
true
}),
)
@@ -648,7 +646,7 @@ impl Context for AppContext {
) -> Handle<T> {
self.update(|cx| {
let slot = cx.entities.reserve();
let entity = build_entity(&mut ModelContext::mutable(cx, slot.id));
let entity = build_entity(&mut ModelContext::mutable(cx, slot.entity_id));
cx.entities.insert(slot, entity)
})
}
@@ -660,7 +658,10 @@ impl Context for AppContext {
) -> R {
self.update(|cx| {
let mut entity = cx.entities.lease(handle);
let result = update(&mut entity, &mut ModelContext::mutable(cx, handle.id));
let result = update(
&mut entity,
&mut ModelContext::mutable(cx, handle.entity_id),
);
cx.entities.end_lease(entity);
result
})
+131 -58
View File
@@ -1,10 +1,12 @@
use crate::Context;
use crate::{AppContext, Context};
use anyhow::{anyhow, Result};
use derive_more::{Deref, DerefMut};
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use slotmap::{SecondaryMap, SlotMap};
use std::{
any::{Any, TypeId},
fmt::{self, Display},
hash::{Hash, Hasher},
marker::PhantomData,
mem,
sync::{
@@ -15,81 +17,101 @@ use std::{
slotmap::new_key_type! { pub struct EntityId; }
pub(crate) struct EntityMap(Arc<RwLock<EntityMapState>>);
impl Display for EntityId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
struct EntityMapState {
ref_counts: SlotMap<EntityId, AtomicUsize>,
pub(crate) struct EntityMap {
entities: SecondaryMap<EntityId, Box<dyn Any + Send + Sync>>,
dropped_entities: Vec<(EntityId, Box<dyn Any + Send + Sync>)>,
ref_counts: Arc<RwLock<EntityRefCounts>>,
}
struct EntityRefCounts {
counts: SlotMap<EntityId, AtomicUsize>,
dropped_entity_ids: Vec<EntityId>,
}
impl EntityMap {
pub fn new() -> Self {
Self(Arc::new(RwLock::new(EntityMapState {
ref_counts: SlotMap::with_key(),
Self {
entities: SecondaryMap::new(),
dropped_entities: Vec::new(),
})))
ref_counts: Arc::new(RwLock::new(EntityRefCounts {
counts: SlotMap::with_key(),
dropped_entity_ids: Vec::new(),
})),
}
}
/// Reserve a slot for an entity, which you can subsequently use with `insert`.
pub fn reserve<T: 'static + Send + Sync>(&self) -> Slot<T> {
let id = self.0.write().ref_counts.insert(1.into());
Slot(Handle::new(id, Arc::downgrade(&self.0)))
let id = self.ref_counts.write().counts.insert(1.into());
Slot(Handle::new(id, Arc::downgrade(&self.ref_counts)))
}
/// Insert an entity into a slot obtained by calling `reserve`.
pub fn insert<T: 'static + Any + Send + Sync>(&self, slot: Slot<T>, entity: T) -> Handle<T> {
pub fn insert<T: 'static + Any + Send + Sync>(
&mut self,
slot: Slot<T>,
entity: T,
) -> Handle<T> {
let handle = slot.0;
self.0.write().entities.insert(handle.id, Box::new(entity));
self.entities.insert(handle.entity_id, Box::new(entity));
handle
}
/// Move an entity to the stack.
pub fn lease<T: 'static + Send + Sync>(&self, handle: &Handle<T>) -> Lease<T> {
let id = handle.id;
pub fn lease<'a, T: 'static + Send + Sync>(&mut self, handle: &'a Handle<T>) -> Lease<'a, T> {
let entity = Some(
self.0
.write()
.entities
.remove(id)
self.entities
.remove(handle.entity_id)
.expect("Circular entity lease. Is the entity already being updated?")
.downcast::<T>()
.unwrap(),
);
Lease { id, entity }
Lease { handle, entity }
}
/// Return an entity after moving it to the stack.
pub fn end_lease<T: 'static + Send + Sync>(&mut self, mut lease: Lease<T>) {
self.0
.write()
.entities
.insert(lease.id, lease.entity.take().unwrap());
self.entities
.insert(lease.handle.entity_id, lease.entity.take().unwrap());
}
pub fn read<T: 'static + Send + Sync>(&self, handle: &Handle<T>) -> &T {
self.entities[handle.entity_id].downcast_ref().unwrap()
}
pub fn weak_handle<T: 'static + Send + Sync>(&self, id: EntityId) -> WeakHandle<T> {
WeakHandle {
any_handle: AnyWeakHandle {
id,
entity_id: id,
entity_type: TypeId::of::<T>(),
entity_map: Arc::downgrade(&self.0),
entity_ref_counts: Arc::downgrade(&self.ref_counts),
},
entity_type: PhantomData,
}
}
pub fn take_dropped(&self) -> Vec<(EntityId, Box<dyn Any + Send + Sync>)> {
mem::take(&mut self.0.write().dropped_entities)
pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any + Send + Sync>)> {
let dropped_entity_ids = mem::take(&mut self.ref_counts.write().dropped_entity_ids);
dropped_entity_ids
.into_iter()
.map(|entity_id| (entity_id, self.entities.remove(entity_id).unwrap()))
.collect()
}
}
pub struct Lease<T> {
pub struct Lease<'a, T: Send + Sync> {
entity: Option<Box<T>>,
pub id: EntityId,
pub handle: &'a Handle<T>,
}
impl<T> core::ops::Deref for Lease<T> {
impl<'a, T> core::ops::Deref for Lease<'a, T>
where
T: Send + Sync,
{
type Target = T;
fn deref(&self) -> &Self::Target {
@@ -97,13 +119,19 @@ impl<T> core::ops::Deref for Lease<T> {
}
}
impl<T> core::ops::DerefMut for Lease<T> {
impl<'a, T> core::ops::DerefMut for Lease<'a, T>
where
T: Send + Sync,
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.entity.as_mut().unwrap()
}
}
impl<T> Drop for Lease<T> {
impl<'a, T> Drop for Lease<'a, T>
where
T: Send + Sync,
{
fn drop(&mut self) {
if self.entity.is_some() {
// We don't panic here, because other panics can cause us to drop the lease without ending it cleanly.
@@ -116,25 +144,29 @@ impl<T> Drop for Lease<T> {
pub struct Slot<T: Send + Sync + 'static>(Handle<T>);
pub struct AnyHandle {
pub(crate) id: EntityId,
pub(crate) entity_id: EntityId,
entity_type: TypeId,
entity_map: Weak<RwLock<EntityMapState>>,
entity_map: Weak<RwLock<EntityRefCounts>>,
}
impl AnyHandle {
fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityMapState>>) -> Self {
fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
Self {
id,
entity_id: id,
entity_type,
entity_map,
}
}
pub fn entity_id(&self) -> EntityId {
self.entity_id
}
pub fn downgrade(&self) -> AnyWeakHandle {
AnyWeakHandle {
id: self.id,
entity_id: self.entity_id,
entity_type: self.entity_type,
entity_map: self.entity_map.clone(),
entity_ref_counts: self.entity_map.clone(),
}
}
@@ -158,15 +190,15 @@ impl Clone for AnyHandle {
if let Some(entity_map) = self.entity_map.upgrade() {
let entity_map = entity_map.read();
let count = entity_map
.ref_counts
.get(self.id)
.counts
.get(self.entity_id)
.expect("detected over-release of a handle");
let prev_count = count.fetch_add(1, SeqCst);
assert_ne!(prev_count, 0, "Detected over-release of a handle.");
}
Self {
id: self.id,
entity_id: self.entity_id,
entity_type: self.entity_type,
entity_map: self.entity_map.clone(),
}
@@ -178,20 +210,16 @@ impl Drop for AnyHandle {
if let Some(entity_map) = self.entity_map.upgrade() {
let entity_map = entity_map.upgradable_read();
let count = entity_map
.ref_counts
.get(self.id)
.counts
.get(self.entity_id)
.expect("Detected over-release of a handle.");
let prev_count = count.fetch_sub(1, SeqCst);
assert_ne!(prev_count, 0, "Detected over-release of a handle.");
if prev_count == 1 {
// We were the last reference to this entity, so we can remove it.
let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
let entity = entity_map
.entities
.remove(self.id)
.expect("entity was removed twice");
entity_map.ref_counts.remove(self.id);
entity_map.dropped_entities.push((self.id, entity));
entity_map.counts.remove(self.entity_id);
entity_map.dropped_entity_ids.push(self.entity_id);
}
}
}
@@ -215,7 +243,7 @@ pub struct Handle<T: Send + Sync> {
}
impl<T: 'static + Send + Sync> Handle<T> {
fn new(id: EntityId, entity_map: Weak<RwLock<EntityMapState>>) -> Self {
fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
Self {
any_handle: AnyHandle::new(id, TypeId::of::<T>(), entity_map),
entity_type: PhantomData,
@@ -229,6 +257,10 @@ impl<T: 'static + Send + Sync> Handle<T> {
}
}
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
cx.entities.read(self)
}
/// Update the entity referenced by this handle with the given function.
///
/// The update function receives a context appropriate for its environment.
@@ -254,23 +286,36 @@ impl<T: Send + Sync> Clone for Handle<T> {
#[derive(Clone)]
pub struct AnyWeakHandle {
pub(crate) id: EntityId,
pub(crate) entity_id: EntityId,
entity_type: TypeId,
entity_map: Weak<RwLock<EntityMapState>>,
entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
}
impl AnyWeakHandle {
pub fn entity_id(&self) -> EntityId {
self.entity_id
}
pub fn is_upgradable(&self) -> bool {
let ref_count = self
.entity_ref_counts
.upgrade()
.and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
.unwrap_or(0);
ref_count > 0
}
pub fn upgrade(&self) -> Option<AnyHandle> {
let entity_map = &self.entity_map.upgrade()?;
let entity_map = self.entity_ref_counts.upgrade()?;
entity_map
.read()
.ref_counts
.get(self.id)?
.counts
.get(self.entity_id)?
.fetch_add(1, SeqCst);
Some(AnyHandle {
id: self.id,
entity_id: self.entity_id,
entity_type: self.entity_type,
entity_map: self.entity_map.clone(),
entity_map: self.entity_ref_counts.clone(),
})
}
}
@@ -284,6 +329,20 @@ where
}
}
impl Hash for AnyWeakHandle {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entity_id.hash(state);
}
}
impl PartialEq for AnyWeakHandle {
fn eq(&self, other: &Self) -> bool {
self.entity_id == other.entity_id
}
}
impl Eq for AnyWeakHandle {}
#[derive(Deref, DerefMut)]
pub struct WeakHandle<T> {
#[deref]
@@ -331,3 +390,17 @@ impl<T: Send + Sync + 'static> WeakHandle<T> {
)
}
}
impl<T: Send + Sync + 'static> Hash for WeakHandle<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.any_handle.hash(state);
}
}
impl<T: Send + Sync + 'static> PartialEq for WeakHandle<T> {
fn eq(&self, other: &Self) -> bool {
self.any_handle == other.any_handle
}
}
impl<T: Send + Sync + 'static> Eq for WeakHandle<T> {}
+31 -20
View File
@@ -4,7 +4,7 @@ use crate::{
};
use derive_more::{Deref, DerefMut};
use futures::FutureExt;
use std::{future::Future, marker::PhantomData};
use std::{any::TypeId, future::Future, marker::PhantomData};
#[derive(Deref, DerefMut)]
pub struct ModelContext<'a, T> {
@@ -36,7 +36,7 @@ impl<'a, T: Send + Sync + 'static> ModelContext<'a, T> {
let this = self.handle();
let handle = handle.downgrade();
self.app.observers.insert(
handle.id,
handle.entity_id,
Box::new(move |cx| {
if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
this.update(cx, |this, cx| on_notify(this, handle, cx));
@@ -59,7 +59,7 @@ impl<'a, T: Send + Sync + 'static> ModelContext<'a, T> {
let this = self.handle();
let handle = handle.downgrade();
self.app.event_listeners.insert(
handle.id,
handle.entity_id,
Box::new(move |event, cx| {
let event = event.downcast_ref().expect("invalid event type");
if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
@@ -85,6 +85,34 @@ impl<'a, T: Send + Sync + 'static> ModelContext<'a, T> {
)
}
pub fn observe_release<E: Send + Sync + 'static>(
&mut self,
handle: &Handle<E>,
on_release: impl Fn(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + Sync + 'static,
) -> Subscription {
let this = self.handle();
self.app.release_listeners.insert(
handle.entity_id,
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
if let Some(this) = this.upgrade() {
this.update(cx, |this, cx| on_release(this, entity, cx));
}
}),
)
}
pub fn observe_global<G: 'static>(
&mut self,
f: impl Fn(&mut T, &mut ModelContext<'_, T>) + Send + Sync + 'static,
) -> Subscription {
let handle = self.handle();
self.global_observers.insert(
TypeId::of::<G>(),
Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),
)
}
pub fn on_app_quit<Fut>(
&mut self,
on_quit: impl Fn(&mut T, &mut ModelContext<T>) -> Fut + Send + Sync + 'static,
@@ -107,23 +135,6 @@ impl<'a, T: Send + Sync + 'static> ModelContext<'a, T> {
)
}
pub fn observe_release<E: Send + Sync + 'static>(
&mut self,
handle: &Handle<E>,
on_release: impl Fn(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + Sync + 'static,
) -> Subscription {
let this = self.handle();
self.app.release_listeners.insert(
handle.id,
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
if let Some(this) = this.upgrade() {
this.update(cx, |this, cx| on_release(this, entity, cx));
}
}),
)
}
pub fn notify(&mut self) {
if self.app.pending_notifications.insert(self.entity_id) {
self.app.pending_effects.push_back(Effect::Notify {
+2 -2
View File
@@ -58,7 +58,7 @@ impl<V: 'static + Send + Sync> Element for View<V> {
type ElementState = AnyElement<V>;
fn id(&self) -> Option<crate::ElementId> {
Some(ElementId::View(self.state.id))
Some(ElementId::View(self.state.entity_id))
}
fn initialize(
@@ -159,7 +159,7 @@ trait ViewObject: 'static + Send + Sync {
impl<V: Send + Sync + 'static> ViewObject for View<V> {
fn entity_id(&self) -> EntityId {
self.state.id
self.state.entity_id
}
fn initialize(&mut self, cx: &mut WindowContext) -> AnyBox {
+10 -14
View File
@@ -1019,15 +1019,12 @@ impl<'a, 'w> WindowContext<'a, 'w> {
pub fn observe_global<G: 'static>(
&mut self,
f: impl Fn(&G, &mut WindowContext<'_, '_>) + Send + Sync + 'static,
f: impl Fn(&mut WindowContext<'_, '_>) + Send + Sync + 'static,
) -> Subscription {
let window_id = self.window.handle.id;
self.global_observers.insert(
TypeId::of::<G>(),
Box::new(move |global, cx| {
let global = global.downcast_ref::<G>().unwrap();
cx.update_window(window_id, |cx| f(global, cx)).is_ok()
}),
Box::new(move |cx| cx.update_window(window_id, |cx| f(cx)).is_ok()),
)
}
@@ -1128,7 +1125,7 @@ impl Context for WindowContext<'_, '_> {
let entity = build_entity(&mut ViewContext::mutable(
&mut *self.app,
&mut self.window,
slot.id,
slot.entity_id,
));
self.entities.insert(slot, entity)
}
@@ -1141,7 +1138,7 @@ impl Context for WindowContext<'_, '_> {
let mut entity = self.entities.lease(handle);
let result = update(
&mut *entity,
&mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.id),
&mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.entity_id),
);
self.entities.end_lease(entity);
result
@@ -1352,7 +1349,7 @@ impl<'a, 'w, V: Send + Sync + 'static> ViewContext<'a, 'w, V> {
let handle = handle.downgrade();
let window_handle = self.window.handle;
self.app.observers.insert(
handle.id,
handle.entity_id,
Box::new(move |cx| {
cx.update_window(window_handle.id, |cx| {
if let Some(handle) = handle.upgrade() {
@@ -1379,7 +1376,7 @@ impl<'a, 'w, V: Send + Sync + 'static> ViewContext<'a, 'w, V> {
let handle = handle.downgrade();
let window_handle = self.window.handle;
self.app.event_listeners.insert(
handle.id,
handle.entity_id,
Box::new(move |event, cx| {
cx.update_window(window_handle.id, |cx| {
if let Some(handle) = handle.upgrade() {
@@ -1418,7 +1415,7 @@ impl<'a, 'w, V: Send + Sync + 'static> ViewContext<'a, 'w, V> {
let this = self.handle();
let window_handle = self.window.handle;
self.app.release_listeners.insert(
handle.id,
handle.entity_id,
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
// todo!("are we okay with silently swallowing the error?")
@@ -1578,16 +1575,15 @@ impl<'a, 'w, V: Send + Sync + 'static> ViewContext<'a, 'w, V> {
pub fn observe_global<G: 'static>(
&mut self,
f: impl Fn(&mut V, &G, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
) -> Subscription {
let window_id = self.window.handle.id;
let handle = self.handle();
self.global_observers.insert(
TypeId::of::<G>(),
Box::new(move |global, cx| {
let global = global.downcast_ref::<G>().unwrap();
Box::new(move |cx| {
cx.update_window(window_id, |cx| {
handle.update(cx, |view, cx| f(view, global, cx)).is_ok()
handle.update(cx, |view, cx| f(view, cx)).is_ok()
})
.unwrap_or(false)
}),