1use crate::{
2 AnyView, AnyWindowHandle, AppCell, AppContext, BackgroundExecutor, Context, DismissEvent,
3 FocusableView, ForegroundExecutor, Model, ModelContext, Render, Result, Task, View,
4 ViewContext, VisualContext, WindowContext, WindowHandle,
5};
6use anyhow::{anyhow, Context as _};
7use derive_more::{Deref, DerefMut};
8use std::{future::Future, rc::Weak};
9
10/// An async-friendly version of [AppContext] with a static lifetime so it can be held across `await` points in async code.
11/// You're provided with an instance when calling [AppContext::spawn], and you can also create one with [AppContext::to_async].
12/// Internally, this holds a weak reference to an `AppContext`, so its methods are fallible to protect against cases where the [AppContext] is dropped.
13#[derive(Clone)]
14pub struct AsyncAppContext {
15 pub(crate) app: Weak<AppCell>,
16 pub(crate) background_executor: BackgroundExecutor,
17 pub(crate) foreground_executor: ForegroundExecutor,
18}
19
20impl Context for AsyncAppContext {
21 type Result<T> = Result<T>;
22
23 fn new_model<T: 'static>(
24 &mut self,
25 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
26 ) -> Self::Result<Model<T>>
27 where
28 T: 'static,
29 {
30 let app = self
31 .app
32 .upgrade()
33 .ok_or_else(|| anyhow!("app was released"))?;
34 let mut app = app.borrow_mut();
35 Ok(app.new_model(build_model))
36 }
37
38 fn update_model<T: 'static, R>(
39 &mut self,
40 handle: &Model<T>,
41 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
42 ) -> Self::Result<R> {
43 let app = self
44 .app
45 .upgrade()
46 .ok_or_else(|| anyhow!("app was released"))?;
47 let mut app = app.borrow_mut();
48 Ok(app.update_model(handle, update))
49 }
50
51 fn read_model<T, R>(
52 &self,
53 handle: &Model<T>,
54 callback: impl FnOnce(&T, &AppContext) -> R,
55 ) -> Self::Result<R>
56 where
57 T: 'static,
58 {
59 let app = self.app.upgrade().context("app was released")?;
60 let lock = app.borrow();
61 Ok(lock.read_model(handle, callback))
62 }
63
64 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
65 where
66 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
67 {
68 let app = self.app.upgrade().context("app was released")?;
69 let mut lock = app.borrow_mut();
70 lock.update_window(window, f)
71 }
72
73 fn read_window<T, R>(
74 &self,
75 window: &WindowHandle<T>,
76 read: impl FnOnce(View<T>, &AppContext) -> R,
77 ) -> Result<R>
78 where
79 T: 'static,
80 {
81 let app = self.app.upgrade().context("app was released")?;
82 let lock = app.borrow();
83 lock.read_window(window, read)
84 }
85}
86
87impl AsyncAppContext {
88 /// Schedules all windows in the application to be redrawn.
89 pub fn refresh(&mut self) -> Result<()> {
90 let app = self
91 .app
92 .upgrade()
93 .ok_or_else(|| anyhow!("app was released"))?;
94 let mut lock = app.borrow_mut();
95 lock.refresh();
96 Ok(())
97 }
98
99 /// Get an executor which can be used to spawn futures in the background.
100 pub fn background_executor(&self) -> &BackgroundExecutor {
101 &self.background_executor
102 }
103
104 /// Get an executor which can be used to spawn futures in the foreground.
105 pub fn foreground_executor(&self) -> &ForegroundExecutor {
106 &self.foreground_executor
107 }
108
109 /// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
110 pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> Result<R> {
111 let app = self
112 .app
113 .upgrade()
114 .ok_or_else(|| anyhow!("app was released"))?;
115 let mut lock = app.borrow_mut();
116 Ok(f(&mut lock))
117 }
118
119 /// Open a window with the given options based on the root view returned by the given function.
120 pub fn open_window<V>(
121 &self,
122 options: crate::WindowOptions,
123 build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
124 ) -> Result<WindowHandle<V>>
125 where
126 V: 'static + Render,
127 {
128 let app = self
129 .app
130 .upgrade()
131 .ok_or_else(|| anyhow!("app was released"))?;
132 let mut lock = app.borrow_mut();
133 Ok(lock.open_window(options, build_root_view))
134 }
135
136 /// Schedule a future to be polled in the background.
137 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
138 where
139 Fut: Future<Output = R> + 'static,
140 R: 'static,
141 {
142 self.foreground_executor.spawn(f(self.clone()))
143 }
144
145 /// Determine whether global state of the specified type has been assigned.
146 /// Returns an error if the `AppContext` has been dropped.
147 pub fn has_global<G: 'static>(&self) -> Result<bool> {
148 let app = self
149 .app
150 .upgrade()
151 .ok_or_else(|| anyhow!("app was released"))?;
152 let app = app.borrow_mut();
153 Ok(app.has_global::<G>())
154 }
155
156 /// Reads the global state of the specified type, passing it to the given callback.
157 /// Panics if no global state of the specified type has been assigned.
158 /// Returns an error if the `AppContext` has been dropped.
159 pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> {
160 let app = self
161 .app
162 .upgrade()
163 .ok_or_else(|| anyhow!("app was released"))?;
164 let app = app.borrow_mut();
165 Ok(read(app.global(), &app))
166 }
167
168 /// Reads the global state of the specified type, passing it to the given callback.
169 /// Similar to [read_global], but returns an error instead of panicking if no state of the specified type has been assigned.
170 /// Returns an error if no state of the specified type has been assigned the `AppContext` has been dropped.
171 pub fn try_read_global<G: 'static, R>(
172 &self,
173 read: impl FnOnce(&G, &AppContext) -> R,
174 ) -> Option<R> {
175 let app = self.app.upgrade()?;
176 let app = app.borrow_mut();
177 Some(read(app.try_global()?, &app))
178 }
179
180 /// A convenience method for [AppContext::update_global]
181 /// for updating the global state of the specified type.
182 pub fn update_global<G: 'static, R>(
183 &mut self,
184 update: impl FnOnce(&mut G, &mut AppContext) -> R,
185 ) -> Result<R> {
186 let app = self
187 .app
188 .upgrade()
189 .ok_or_else(|| anyhow!("app was released"))?;
190 let mut app = app.borrow_mut();
191 Ok(app.update_global(update))
192 }
193}
194
195/// A cloneable, owned handle to the application context,
196/// composed with the window associated with the current task.
197#[derive(Clone, Deref, DerefMut)]
198pub struct AsyncWindowContext {
199 #[deref]
200 #[deref_mut]
201 app: AsyncAppContext,
202 window: AnyWindowHandle,
203}
204
205impl AsyncWindowContext {
206 pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
207 Self { app, window }
208 }
209
210 /// Get the handle of the window this context is associated with.
211 pub fn window_handle(&self) -> AnyWindowHandle {
212 self.window
213 }
214
215 /// A convenience method for [WindowContext::update()]
216 pub fn update<R>(&mut self, update: impl FnOnce(&mut WindowContext) -> R) -> Result<R> {
217 self.app.update_window(self.window, |_, cx| update(cx))
218 }
219
220 /// A convenience method for [WindowContext::update()]
221 pub fn update_root<R>(
222 &mut self,
223 update: impl FnOnce(AnyView, &mut WindowContext) -> R,
224 ) -> Result<R> {
225 self.app.update_window(self.window, update)
226 }
227
228 /// A convenience method for [WindowContext::on_next_frame()]
229 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
230 self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
231 }
232
233 /// A convenience method for [AppContext::global()]
234 pub fn read_global<G: 'static, R>(
235 &mut self,
236 read: impl FnOnce(&G, &WindowContext) -> R,
237 ) -> Result<R> {
238 self.window.update(self, |_, cx| read(cx.global(), cx))
239 }
240
241 /// A convenience method for [AppContext::update_global()]
242 /// for updating the global state of the specified type.
243 pub fn update_global<G, R>(
244 &mut self,
245 update: impl FnOnce(&mut G, &mut WindowContext) -> R,
246 ) -> Result<R>
247 where
248 G: 'static,
249 {
250 self.window.update(self, |_, cx| cx.update_global(update))
251 }
252
253 /// Schedule a future to be executed on the main thread. This is used for collecting
254 /// the results of background tasks and updating the UI.
255 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
256 where
257 Fut: Future<Output = R> + 'static,
258 R: 'static,
259 {
260 self.foreground_executor.spawn(f(self.clone()))
261 }
262}
263
264impl Context for AsyncWindowContext {
265 type Result<T> = Result<T>;
266
267 fn new_model<T>(
268 &mut self,
269 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
270 ) -> Result<Model<T>>
271 where
272 T: 'static,
273 {
274 self.window.update(self, |_, cx| cx.new_model(build_model))
275 }
276
277 fn update_model<T: 'static, R>(
278 &mut self,
279 handle: &Model<T>,
280 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
281 ) -> Result<R> {
282 self.window
283 .update(self, |_, cx| cx.update_model(handle, update))
284 }
285
286 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
287 where
288 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
289 {
290 self.app.update_window(window, update)
291 }
292
293 fn read_model<T, R>(
294 &self,
295 handle: &Model<T>,
296 read: impl FnOnce(&T, &AppContext) -> R,
297 ) -> Self::Result<R>
298 where
299 T: 'static,
300 {
301 self.app.read_model(handle, read)
302 }
303
304 fn read_window<T, R>(
305 &self,
306 window: &WindowHandle<T>,
307 read: impl FnOnce(View<T>, &AppContext) -> R,
308 ) -> Result<R>
309 where
310 T: 'static,
311 {
312 self.app.read_window(window, read)
313 }
314}
315
316impl VisualContext for AsyncWindowContext {
317 fn new_view<V>(
318 &mut self,
319 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
320 ) -> Self::Result<View<V>>
321 where
322 V: 'static + Render,
323 {
324 self.window
325 .update(self, |_, cx| cx.new_view(build_view_state))
326 }
327
328 fn update_view<V: 'static, R>(
329 &mut self,
330 view: &View<V>,
331 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
332 ) -> Self::Result<R> {
333 self.window
334 .update(self, |_, cx| cx.update_view(view, update))
335 }
336
337 fn replace_root_view<V>(
338 &mut self,
339 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
340 ) -> Self::Result<View<V>>
341 where
342 V: 'static + Render,
343 {
344 self.window
345 .update(self, |_, cx| cx.replace_root_view(build_view))
346 }
347
348 fn focus_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
349 where
350 V: FocusableView,
351 {
352 self.window.update(self, |_, cx| {
353 view.read(cx).focus_handle(cx).clone().focus(cx);
354 })
355 }
356
357 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
358 where
359 V: crate::ManagedView,
360 {
361 self.window
362 .update(self, |_, cx| view.update(cx, |_, cx| cx.emit(DismissEvent)))
363 }
364}