1use crate::{
2 AppContext, AsyncAppContext, Context, Effect, EntityId, EventEmitter, Handle, Reference,
3 Subscription, Task, WeakHandle,
4};
5use derive_more::{Deref, DerefMut};
6use futures::FutureExt;
7use std::{future::Future, marker::PhantomData};
8
9#[derive(Deref, DerefMut)]
10pub struct ModelContext<'a, T> {
11 #[deref]
12 #[deref_mut]
13 app: Reference<'a, AppContext>,
14 entity_type: PhantomData<T>,
15 entity_id: EntityId,
16}
17
18impl<'a, T: Send + Sync + 'static> ModelContext<'a, T> {
19 pub(crate) fn mutable(app: &'a mut AppContext, entity_id: EntityId) -> Self {
20 Self {
21 app: Reference::Mutable(app),
22 entity_type: PhantomData,
23 entity_id,
24 }
25 }
26
27 pub fn handle(&self) -> WeakHandle<T> {
28 self.app.entities.weak_handle(self.entity_id)
29 }
30
31 pub fn observe<E: Send + Sync + 'static>(
32 &mut self,
33 handle: &Handle<E>,
34 on_notify: impl Fn(&mut T, Handle<E>, &mut ModelContext<'_, T>) + Send + Sync + 'static,
35 ) -> Subscription {
36 let this = self.handle();
37 let handle = handle.downgrade();
38 self.app.observers.insert(
39 handle.id,
40 Box::new(move |cx| {
41 if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
42 this.update(cx, |this, cx| on_notify(this, handle, cx));
43 true
44 } else {
45 false
46 }
47 }),
48 )
49 }
50
51 pub fn subscribe<E: EventEmitter + Send + Sync + 'static>(
52 &mut self,
53 handle: &Handle<E>,
54 on_event: impl Fn(&mut T, Handle<E>, &E::Event, &mut ModelContext<'_, T>)
55 + Send
56 + Sync
57 + 'static,
58 ) -> Subscription {
59 let this = self.handle();
60 let handle = handle.downgrade();
61 self.app.event_listeners.insert(
62 handle.id,
63 Box::new(move |event, cx| {
64 let event = event.downcast_ref().expect("invalid event type");
65 if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
66 this.update(cx, |this, cx| on_event(this, handle, event, cx));
67 true
68 } else {
69 false
70 }
71 }),
72 )
73 }
74
75 pub fn on_release(
76 &mut self,
77 on_release: impl Fn(&mut T, &mut AppContext) + Send + Sync + 'static,
78 ) -> Subscription {
79 self.app.release_listeners.insert(
80 self.entity_id,
81 Box::new(move |this, cx| {
82 let this = this.downcast_mut().expect("invalid entity type");
83 on_release(this, cx);
84 }),
85 )
86 }
87
88 pub fn on_app_quit<Fut>(
89 &mut self,
90 on_quit: impl Fn(&mut T, &mut AppContext) -> Fut + Send + Sync + 'static,
91 ) -> Subscription
92 where
93 Fut: 'static + Future<Output = ()> + Send,
94 {
95 let handle = self.handle();
96 self.app.quit_observers.insert(
97 (),
98 Box::new(move |cx| {
99 let future = handle.update(cx, |entity, cx| on_quit(entity, cx)).ok();
100 async move {
101 if let Some(future) = future {
102 future.await;
103 }
104 }
105 .boxed()
106 }),
107 )
108 }
109
110 pub fn observe_release<E: Send + Sync + 'static>(
111 &mut self,
112 handle: &Handle<E>,
113 on_release: impl Fn(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + Sync + 'static,
114 ) -> Subscription {
115 let this = self.handle();
116 self.app.release_listeners.insert(
117 handle.id,
118 Box::new(move |entity, cx| {
119 let entity = entity.downcast_mut().expect("invalid entity type");
120 if let Some(this) = this.upgrade() {
121 this.update(cx, |this, cx| on_release(this, entity, cx));
122 }
123 }),
124 )
125 }
126
127 pub fn notify(&mut self) {
128 if self.app.pending_notifications.insert(self.entity_id) {
129 self.app.pending_effects.push_back(Effect::Notify {
130 emitter: self.entity_id,
131 });
132 }
133 }
134
135 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
136 where
137 G: 'static + Send + Sync,
138 {
139 let mut global = self.app.lease_global::<G>();
140 let result = f(global.as_mut(), self);
141 self.app.restore_global(global);
142 result
143 }
144
145 pub fn spawn<Fut, R>(
146 &self,
147 f: impl FnOnce(WeakHandle<T>, AsyncAppContext) -> Fut + Send + 'static,
148 ) -> Task<R>
149 where
150 Fut: Future<Output = R> + Send + 'static,
151 R: Send + 'static,
152 {
153 let this = self.handle();
154 self.app.spawn(|cx| f(this, cx))
155 }
156}
157
158impl<'a, T: EventEmitter + Send + Sync + 'static> ModelContext<'a, T> {
159 pub fn emit(&mut self, event: T::Event) {
160 self.app.pending_effects.push_back(Effect::Emit {
161 emitter: self.entity_id,
162 event: Box::new(event),
163 });
164 }
165}
166
167impl<'a, T: 'static> Context for ModelContext<'a, T> {
168 type EntityContext<'b, 'c, U: Send + Sync + 'static> = ModelContext<'b, U>;
169 type Result<U> = U;
170
171 fn entity<U: Send + Sync + 'static>(
172 &mut self,
173 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, U>) -> U,
174 ) -> Handle<U> {
175 self.app.entity(build_entity)
176 }
177
178 fn update_entity<U: Send + Sync + 'static, R>(
179 &mut self,
180 handle: &Handle<U>,
181 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
182 ) -> R {
183 self.app.update_entity(handle, update)
184 }
185}