1use crate::{
2 AppContext, AsyncAppContext, Context, Effect, EntityId, EventEmitter, Handle, MainThread,
3 Reference, Subscription, Task, WeakHandle,
4};
5use derive_more::{Deref, DerefMut};
6use futures::FutureExt;
7use std::{
8 any::{Any, TypeId},
9 borrow::{Borrow, BorrowMut},
10 future::Future,
11};
12
13#[derive(Deref, DerefMut)]
14pub struct ModelContext<'a, T> {
15 #[deref]
16 #[deref_mut]
17 app: Reference<'a, AppContext>,
18 model_state: WeakHandle<T>,
19}
20
21impl<'a, T: 'static> ModelContext<'a, T> {
22 pub(crate) fn mutable(app: &'a mut AppContext, model_state: WeakHandle<T>) -> Self {
23 Self {
24 app: Reference::Mutable(app),
25 model_state,
26 }
27 }
28
29 pub fn entity_id(&self) -> EntityId {
30 self.model_state.entity_id
31 }
32
33 pub fn handle(&self) -> Handle<T> {
34 self.weak_handle()
35 .upgrade()
36 .expect("The entity must be alive if we have a model context")
37 }
38
39 pub fn weak_handle(&self) -> WeakHandle<T> {
40 self.model_state.clone()
41 }
42
43 pub fn observe<T2: 'static>(
44 &mut self,
45 handle: &Handle<T2>,
46 mut on_notify: impl FnMut(&mut T, Handle<T2>, &mut ModelContext<'_, T>) + Send + 'static,
47 ) -> Subscription
48 where
49 T: 'static + Send,
50 {
51 let this = self.weak_handle();
52 let handle = handle.downgrade();
53 self.app.observers.insert(
54 handle.entity_id,
55 Box::new(move |cx| {
56 if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
57 this.update(cx, |this, cx| on_notify(this, handle, cx));
58 true
59 } else {
60 false
61 }
62 }),
63 )
64 }
65
66 pub fn subscribe<E: 'static + EventEmitter>(
67 &mut self,
68 handle: &Handle<E>,
69 mut on_event: impl FnMut(&mut T, Handle<E>, &E::Event, &mut ModelContext<'_, T>)
70 + Send
71 + 'static,
72 ) -> Subscription
73 where
74 T: 'static + Send,
75 {
76 let this = self.weak_handle();
77 let handle = handle.downgrade();
78 self.app.event_listeners.insert(
79 handle.entity_id,
80 Box::new(move |event, cx| {
81 let event: &E::Event = event.downcast_ref().expect("invalid event type");
82 if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
83 this.update(cx, |this, cx| on_event(this, handle, event, cx));
84 true
85 } else {
86 false
87 }
88 }),
89 )
90 }
91
92 pub fn on_release(
93 &mut self,
94 mut on_release: impl FnMut(&mut T, &mut AppContext) + Send + 'static,
95 ) -> Subscription
96 where
97 T: 'static,
98 {
99 self.app.release_listeners.insert(
100 self.model_state.entity_id,
101 Box::new(move |this, cx| {
102 let this = this.downcast_mut().expect("invalid entity type");
103 on_release(this, cx);
104 }),
105 )
106 }
107
108 pub fn observe_release<E: 'static>(
109 &mut self,
110 handle: &Handle<E>,
111 mut on_release: impl FnMut(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + 'static,
112 ) -> Subscription
113 where
114 T: Any + Send,
115 {
116 let this = self.weak_handle();
117 self.app.release_listeners.insert(
118 handle.entity_id,
119 Box::new(move |entity, cx| {
120 let entity = entity.downcast_mut().expect("invalid entity type");
121 if let Some(this) = this.upgrade() {
122 this.update(cx, |this, cx| on_release(this, entity, cx));
123 }
124 }),
125 )
126 }
127
128 pub fn observe_global<G: 'static>(
129 &mut self,
130 mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + Send + 'static,
131 ) -> Subscription
132 where
133 T: 'static + Send,
134 {
135 let handle = self.weak_handle();
136 self.global_observers.insert(
137 TypeId::of::<G>(),
138 Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),
139 )
140 }
141
142 pub fn on_app_quit<Fut>(
143 &mut self,
144 mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + Send + 'static,
145 ) -> Subscription
146 where
147 Fut: 'static + Future<Output = ()> + Send,
148 T: 'static + Send,
149 {
150 let handle = self.weak_handle();
151 self.app.quit_observers.insert(
152 (),
153 Box::new(move |cx| {
154 let future = handle.update(cx, |entity, cx| on_quit(entity, cx)).ok();
155 async move {
156 if let Some(future) = future {
157 future.await;
158 }
159 }
160 .boxed()
161 }),
162 )
163 }
164
165 pub fn notify(&mut self) {
166 if self
167 .app
168 .pending_notifications
169 .insert(self.model_state.entity_id)
170 {
171 self.app.pending_effects.push_back(Effect::Notify {
172 emitter: self.model_state.entity_id,
173 });
174 }
175 }
176
177 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
178 where
179 G: 'static + Send,
180 {
181 let mut global = self.app.lease_global::<G>();
182 let result = f(&mut global, self);
183 self.app.end_global_lease(global);
184 result
185 }
186
187 pub fn spawn<Fut, R>(
188 &self,
189 f: impl FnOnce(WeakHandle<T>, AsyncAppContext) -> Fut + Send + 'static,
190 ) -> Task<R>
191 where
192 T: 'static,
193 Fut: Future<Output = R> + Send + 'static,
194 R: Send + 'static,
195 {
196 let this = self.weak_handle();
197 self.app.spawn(|cx| f(this, cx))
198 }
199
200 pub fn spawn_on_main<Fut, R>(
201 &self,
202 f: impl FnOnce(WeakHandle<T>, MainThread<AsyncAppContext>) -> Fut + Send + 'static,
203 ) -> Task<R>
204 where
205 Fut: Future<Output = R> + 'static,
206 R: Send + 'static,
207 {
208 let this = self.weak_handle();
209 self.app.spawn_on_main(|cx| f(this, cx))
210 }
211}
212
213impl<'a, T> ModelContext<'a, T>
214where
215 T: EventEmitter,
216 T::Event: Send,
217{
218 pub fn emit(&mut self, event: T::Event) {
219 self.app.pending_effects.push_back(Effect::Emit {
220 emitter: self.model_state.entity_id,
221 event: Box::new(event),
222 });
223 }
224}
225
226impl<'a, T> Context for ModelContext<'a, T> {
227 type EntityContext<'b, U> = ModelContext<'b, U>;
228 type Result<U> = U;
229
230 fn entity<U>(
231 &mut self,
232 build_entity: impl FnOnce(&mut Self::EntityContext<'_, U>) -> U,
233 ) -> Handle<U>
234 where
235 U: 'static + Send,
236 {
237 self.app.entity(build_entity)
238 }
239
240 fn update_entity<U: 'static, R>(
241 &mut self,
242 handle: &Handle<U>,
243 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, U>) -> R,
244 ) -> R {
245 self.app.update_entity(handle, update)
246 }
247}
248
249impl<T> Borrow<AppContext> for ModelContext<'_, T> {
250 fn borrow(&self) -> &AppContext {
251 &self.app
252 }
253}
254
255impl<T> BorrowMut<AppContext> for ModelContext<'_, T> {
256 fn borrow_mut(&mut self) -> &mut AppContext {
257 &mut self.app
258 }
259}