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 + Sync + 'static,
47 ) -> Subscription
48 where
49 T: Any + Send + Sync,
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 + Sync
72 + 'static,
73 ) -> Subscription
74 where
75 T: Any + Send + Sync,
76 {
77 let this = self.weak_handle();
78 let handle = handle.downgrade();
79 self.app.event_listeners.insert(
80 handle.entity_id,
81 Box::new(move |event, cx| {
82 let event = event.downcast_ref().expect("invalid event type");
83 if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
84 this.update(cx, |this, cx| on_event(this, handle, event, cx));
85 true
86 } else {
87 false
88 }
89 }),
90 )
91 }
92
93 pub fn on_release(
94 &mut self,
95 mut on_release: impl FnMut(&mut T, &mut AppContext) + Send + Sync + 'static,
96 ) -> Subscription
97 where
98 T: 'static,
99 {
100 self.app.release_listeners.insert(
101 self.model_state.entity_id,
102 Box::new(move |this, cx| {
103 let this = this.downcast_mut().expect("invalid entity type");
104 on_release(this, cx);
105 }),
106 )
107 }
108
109 pub fn observe_release<E: 'static>(
110 &mut self,
111 handle: &Handle<E>,
112 mut on_release: impl FnMut(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + Sync + 'static,
113 ) -> Subscription
114 where
115 T: Any + Send + Sync,
116 {
117 let this = self.weak_handle();
118 self.app.observe_release(handle, move |entity, cx| {
119 if let Some(this) = this.upgrade() {
120 this.update(cx, |this, cx| on_release(this, entity, cx));
121 }
122 })
123 }
124
125 pub fn observe_global<G: 'static>(
126 &mut self,
127 mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + Send + Sync + 'static,
128 ) -> Subscription
129 where
130 T: Any + Send + Sync,
131 {
132 let handle = self.weak_handle();
133 self.global_observers.insert(
134 TypeId::of::<G>(),
135 Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),
136 )
137 }
138
139 pub fn on_app_quit<Fut>(
140 &mut self,
141 mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + Send + Sync + 'static,
142 ) -> Subscription
143 where
144 Fut: 'static + Future<Output = ()> + Send,
145 T: Any + Send + Sync,
146 {
147 let handle = self.weak_handle();
148 self.app.quit_observers.insert(
149 (),
150 Box::new(move |cx| {
151 let future = handle.update(cx, |entity, cx| on_quit(entity, cx)).ok();
152 async move {
153 if let Some(future) = future {
154 future.await;
155 }
156 }
157 .boxed()
158 }),
159 )
160 }
161
162 pub fn notify(&mut self) {
163 if self
164 .app
165 .pending_notifications
166 .insert(self.model_state.entity_id)
167 {
168 self.app.pending_effects.push_back(Effect::Notify {
169 emitter: self.model_state.entity_id,
170 });
171 }
172 }
173
174 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
175 where
176 G: 'static + Send + Sync,
177 {
178 let mut global = self.app.lease_global::<G>();
179 let result = f(&mut global, self);
180 self.app.end_global_lease(global);
181 result
182 }
183
184 pub fn spawn<Fut, R>(
185 &self,
186 f: impl FnOnce(WeakHandle<T>, AsyncAppContext) -> Fut + Send + 'static,
187 ) -> Task<R>
188 where
189 T: 'static,
190 Fut: Future<Output = R> + Send + 'static,
191 R: Send + 'static,
192 {
193 let this = self.weak_handle();
194 self.app.spawn(|cx| f(this, cx))
195 }
196
197 pub fn spawn_on_main<Fut, R>(
198 &self,
199 f: impl FnOnce(WeakHandle<T>, MainThread<AsyncAppContext>) -> Fut + Send + 'static,
200 ) -> Task<R>
201 where
202 Fut: Future<Output = R> + 'static,
203 R: Send + 'static,
204 {
205 let this = self.weak_handle();
206 self.app.spawn_on_main(|cx| f(this, cx))
207 }
208}
209
210impl<'a, T> ModelContext<'a, T>
211where
212 T: EventEmitter,
213 T::Event: Send + Sync,
214{
215 pub fn emit(&mut self, event: T::Event) {
216 self.app.pending_effects.push_back(Effect::Emit {
217 emitter: self.model_state.entity_id,
218 event: Box::new(event),
219 });
220 }
221}
222
223impl<'a, T> Context for ModelContext<'a, T> {
224 type EntityContext<'b, 'c, U> = ModelContext<'b, U>;
225 type Result<U> = U;
226
227 fn entity<U>(
228 &mut self,
229 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, U>) -> U,
230 ) -> Handle<U>
231 where
232 U: 'static + Send + Sync,
233 {
234 self.app.entity(build_entity)
235 }
236
237 fn update_entity<U: 'static, R>(
238 &mut self,
239 handle: &Handle<U>,
240 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
241 ) -> R {
242 self.app.update_entity(handle, update)
243 }
244}
245
246impl<T> Borrow<AppContext> for ModelContext<'_, T> {
247 fn borrow(&self) -> &AppContext {
248 &self.app
249 }
250}
251
252impl<T> BorrowMut<AppContext> for ModelContext<'_, T> {
253 fn borrow_mut(&mut self) -> &mut AppContext {
254 &mut self.app
255 }
256}