Implement {ModelHandle,ViewHandle}::become_delegate

This commit is contained in:
Antonio Scandurra 2022-03-08 09:30:32 +01:00
parent f2848a092b
commit b49951ac57

View file

@ -60,10 +60,6 @@ pub trait View: Entity + Sized {
} }
} }
pub trait Delegator: Entity {
type Delegation;
}
pub trait ReadModel { pub trait ReadModel {
fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T; fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
} }
@ -1156,34 +1152,32 @@ impl MutableAppContext {
} }
} }
pub fn become_delegate_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription fn become_delegate_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
where where
E: Entity, E: Entity,
E::Event: 'static,
H: Handle<E>, H: Handle<E>,
F: 'static + FnMut(H, &E::Event, &mut Self) -> bool, F: 'static + FnMut(H, E::Event, &mut Self) -> bool,
{ {
let id = post_inc(&mut self.next_subscription_id); let id = post_inc(&mut self.next_subscription_id);
let emitter = handle.downgrade(); let emitter = handle.downgrade();
self.subscriptions self.delegations.lock().insert(
.lock() handle.id(),
.entry(handle.id()) (
.or_default()
.insert(
id, id,
Box::new(move |payload, cx| { Box::new(move |payload, cx| {
if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) { if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
let payload = payload.downcast_ref().expect("downcast is type safe"); let payload = *payload.downcast().expect("downcast is type safe");
callback(emitter, payload, cx) callback(emitter, payload, cx)
} else { } else {
false false
} }
}), }),
); ),
Subscription::Subscription { );
Subscription::Delegation {
id, id,
entity_id: handle.id(), entity_id: handle.id(),
subscriptions: Some(Arc::downgrade(&self.subscriptions)), delegations: Some(Arc::downgrade(&self.delegations)),
} }
} }
@ -1726,6 +1720,17 @@ impl MutableAppContext {
} }
} }
} }
let delegate = self.delegations.lock().remove(&entity_id);
if let Some((id, mut callback)) = delegate {
let alive = callback(payload, self);
if alive {
self.delegations
.lock()
.entry(entity_id)
.or_insert_with(|| (id, callback));
}
}
} }
fn notify_model_observers(&mut self, observed_id: usize) { fn notify_model_observers(&mut self, observed_id: usize) {
@ -2363,6 +2368,26 @@ impl<'a, T: Entity> ModelContext<'a, T> {
}) })
} }
pub fn become_delegate<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
where
E: Entity,
H: Handle<E>,
F: 'static + FnMut(&mut T, H, E::Event, &mut ModelContext<T>),
{
let delegate = self.weak_handle();
self.app
.become_delegate_internal(handle, move |emitter, event, cx| {
if let Some(delegate) = delegate.upgrade(cx) {
delegate.update(cx, |subscriber, cx| {
callback(subscriber, emitter, event, cx);
});
true
} else {
false
}
})
}
pub fn observe_release<S, F>( pub fn observe_release<S, F>(
&mut self, &mut self,
handle: &ModelHandle<S>, handle: &ModelHandle<S>,
@ -2630,23 +2655,22 @@ impl<'a, T: View> ViewContext<'a, T> {
pub fn become_delegate<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription pub fn become_delegate<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
where where
E: Delegator, E: Entity,
E::Event: 'static,
H: Handle<E>, H: Handle<E>,
F: 'static + FnMut(&mut T, H, E::Event, &mut ViewContext<T>), F: 'static + FnMut(&mut T, H, E::Event, &mut ViewContext<T>),
{ {
// let subscriber = self.weak_handle(); let delegate = self.weak_handle();
// self.app self.app
// .subscribe_internal(handle, move |emitter, event, cx| { .become_delegate_internal(handle, move |emitter, event, cx| {
// if let Some(subscriber) = subscriber.upgrade(cx) { if let Some(delegate) = delegate.upgrade(cx) {
// subscriber.update(cx, |subscriber, cx| { delegate.update(cx, |subscriber, cx| {
// callback(subscriber, emitter, event, cx); callback(subscriber, emitter, event, cx);
// }); });
// true true
// } else { } else {
// false false
// } }
// }) })
} }
pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
@ -3802,6 +3826,11 @@ pub enum Subscription {
entity_id: usize, entity_id: usize,
subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>, subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
}, },
Delegation {
id: usize,
entity_id: usize,
delegations: Option<Weak<Mutex<HashMap<usize, (usize, DelegationCallback)>>>>,
},
Observation { Observation {
id: usize, id: usize,
entity_id: usize, entity_id: usize,
@ -3821,6 +3850,9 @@ impl Subscription {
Subscription::Subscription { subscriptions, .. } => { Subscription::Subscription { subscriptions, .. } => {
subscriptions.take(); subscriptions.take();
} }
Subscription::Delegation { delegations, .. } => {
delegations.take();
}
Subscription::Observation { observations, .. } => { Subscription::Observation { observations, .. } => {
observations.take(); observations.take();
} }
@ -3867,6 +3899,19 @@ impl Drop for Subscription {
} }
} }
} }
Subscription::Delegation {
id,
entity_id,
delegations,
} => {
if let Some(delegations) = delegations.as_ref().and_then(Weak::upgrade) {
if let Entry::Occupied(entry) = delegations.lock().entry(*entity_id) {
if *id == entry.get().0 {
let _ = entry.remove();
}
}
}
}
} }
} }
} }
@ -4120,7 +4165,7 @@ mod tests {
} }
#[crate::test(self)] #[crate::test(self)]
fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) { fn test_model_events(cx: &mut MutableAppContext) {
#[derive(Default)] #[derive(Default)]
struct Model { struct Model {
events: Vec<usize>, events: Vec<usize>,
@ -4132,11 +4177,16 @@ mod tests {
let handle_1 = cx.add_model(|_| Model::default()); let handle_1 = cx.add_model(|_| Model::default());
let handle_2 = cx.add_model(|_| Model::default()); let handle_2 = cx.add_model(|_| Model::default());
handle_1.update(cx, |_, c| { handle_1.update(cx, |_, cx| {
c.subscribe(&handle_2, move |model: &mut Model, emitter, event, c| { cx.become_delegate(&handle_2, |model, _, event, _| {
model.events.push(event * 3);
})
.detach();
cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
model.events.push(*event); model.events.push(*event);
c.subscribe(&emitter, |model, _, event, _| { cx.subscribe(&emitter, |model, _, event, _| {
model.events.push(*event * 2); model.events.push(*event * 2);
}) })
.detach(); .detach();
@ -4145,10 +4195,10 @@ mod tests {
}); });
handle_2.update(cx, |_, c| c.emit(7)); handle_2.update(cx, |_, c| c.emit(7));
assert_eq!(handle_1.read(cx).events, vec![7]); assert_eq!(handle_1.read(cx).events, vec![7, 21]);
handle_2.update(cx, |_, c| c.emit(5)); handle_2.update(cx, |_, c| c.emit(5));
assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]); assert_eq!(handle_1.read(cx).events, vec![7, 21, 5, 10, 15]);
} }
#[crate::test(self)] #[crate::test(self)]
@ -4375,7 +4425,7 @@ mod tests {
} }
#[crate::test(self)] #[crate::test(self)]
fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) { fn test_view_events(cx: &mut MutableAppContext) {
#[derive(Default)] #[derive(Default)]
struct View { struct View {
events: Vec<usize>, events: Vec<usize>,
@ -4405,31 +4455,36 @@ mod tests {
let handle_2 = cx.add_view(window_id, |_| View::default()); let handle_2 = cx.add_view(window_id, |_| View::default());
let handle_3 = cx.add_model(|_| Model); let handle_3 = cx.add_model(|_| Model);
handle_1.update(cx, |_, c| { handle_1.update(cx, |_, cx| {
c.subscribe(&handle_2, move |me, emitter, event, c| { cx.become_delegate(&handle_2, |me, _, event, _| {
me.events.push(event * 3);
})
.detach();
cx.subscribe(&handle_2, move |me, emitter, event, cx| {
me.events.push(*event); me.events.push(*event);
c.subscribe(&emitter, |me, _, event, _| { cx.subscribe(&emitter, |me, _, event, _| {
me.events.push(*event * 2); me.events.push(*event * 2);
}) })
.detach(); .detach();
}) })
.detach(); .detach();
c.subscribe(&handle_3, |me, _, event, _| { cx.subscribe(&handle_3, |me, _, event, _| {
me.events.push(*event); me.events.push(*event);
}) })
.detach(); .detach();
}); });
handle_2.update(cx, |_, c| c.emit(7)); handle_2.update(cx, |_, c| c.emit(7));
assert_eq!(handle_1.read(cx).events, vec![7]); assert_eq!(handle_1.read(cx).events, vec![7, 21]);
handle_2.update(cx, |_, c| c.emit(5)); handle_2.update(cx, |_, c| c.emit(5));
assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]); assert_eq!(handle_1.read(cx).events, vec![7, 21, 5, 10, 15]);
handle_3.update(cx, |_, c| c.emit(9)); handle_3.update(cx, |_, c| c.emit(9));
assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]); assert_eq!(handle_1.read(cx).events, vec![7, 21, 5, 10, 15, 9]);
} }
#[crate::test(self)] #[crate::test(self)]