1use crate::{
2 AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
3 Entity, Focusable, ForegroundExecutor, Global, PromptLevel, Render, Reservation, Result, Task,
4 VisualContext, Window, WindowHandle,
5};
6use anyhow::{Context as _, anyhow};
7use derive_more::{Deref, DerefMut};
8use futures::channel::oneshot;
9use std::{future::Future, rc::Weak};
10
11use super::{Context, WeakEntity};
12
13/// An async-friendly version of [App] with a static lifetime so it can be held across `await` points in async code.
14/// You're provided with an instance when calling [App::spawn], and you can also create one with [App::to_async].
15/// Internally, this holds a weak reference to an `App`, so its methods are fallible to protect against cases where the [App] is dropped.
16#[derive(Clone)]
17pub struct AsyncApp {
18 pub(crate) app: Weak<AppCell>,
19 pub(crate) background_executor: BackgroundExecutor,
20 pub(crate) foreground_executor: ForegroundExecutor,
21}
22
23impl AppContext for AsyncApp {
24 type Result<T> = Result<T>;
25
26 fn new<T: 'static>(
27 &mut self,
28 build_entity: impl FnOnce(&mut Context<T>) -> T,
29 ) -> Self::Result<Entity<T>> {
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(build_entity))
36 }
37
38 fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
39 let app = self
40 .app
41 .upgrade()
42 .ok_or_else(|| anyhow!("app was released"))?;
43 let mut app = app.borrow_mut();
44 Ok(app.reserve_entity())
45 }
46
47 fn insert_entity<T: 'static>(
48 &mut self,
49 reservation: Reservation<T>,
50 build_entity: impl FnOnce(&mut Context<T>) -> T,
51 ) -> Result<Entity<T>> {
52 let app = self
53 .app
54 .upgrade()
55 .ok_or_else(|| anyhow!("app was released"))?;
56 let mut app = app.borrow_mut();
57 Ok(app.insert_entity(reservation, build_entity))
58 }
59
60 fn update_entity<T: 'static, R>(
61 &mut self,
62 handle: &Entity<T>,
63 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
64 ) -> Self::Result<R> {
65 let app = self
66 .app
67 .upgrade()
68 .ok_or_else(|| anyhow!("app was released"))?;
69 let mut app = app.borrow_mut();
70 Ok(app.update_entity(handle, update))
71 }
72
73 fn read_entity<T, R>(
74 &self,
75 handle: &Entity<T>,
76 callback: impl FnOnce(&T, &App) -> R,
77 ) -> Self::Result<R>
78 where
79 T: 'static,
80 {
81 let app = self.app.upgrade().context("app was released")?;
82 let lock = app.borrow();
83 Ok(lock.read_entity(handle, callback))
84 }
85
86 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
87 where
88 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
89 {
90 let app = self.app.upgrade().context("app was released")?;
91 let mut lock = app.borrow_mut();
92 lock.update_window(window, f)
93 }
94
95 fn read_window<T, R>(
96 &self,
97 window: &WindowHandle<T>,
98 read: impl FnOnce(Entity<T>, &App) -> R,
99 ) -> Result<R>
100 where
101 T: 'static,
102 {
103 let app = self.app.upgrade().context("app was released")?;
104 let lock = app.borrow();
105 lock.read_window(window, read)
106 }
107
108 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
109 where
110 R: Send + 'static,
111 {
112 self.background_executor.spawn(future)
113 }
114
115 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
116 where
117 G: Global,
118 {
119 let app = self.app.upgrade().context("app was released")?;
120 let mut lock = app.borrow_mut();
121 Ok(lock.update(|this| this.read_global(callback)))
122 }
123}
124
125impl AsyncApp {
126 /// Schedules all windows in the application to be redrawn.
127 pub fn refresh(&self) -> Result<()> {
128 let app = self
129 .app
130 .upgrade()
131 .ok_or_else(|| anyhow!("app was released"))?;
132 let mut lock = app.borrow_mut();
133 lock.refresh_windows();
134 Ok(())
135 }
136
137 /// Get an executor which can be used to spawn futures in the background.
138 pub fn background_executor(&self) -> &BackgroundExecutor {
139 &self.background_executor
140 }
141
142 /// Get an executor which can be used to spawn futures in the foreground.
143 pub fn foreground_executor(&self) -> &ForegroundExecutor {
144 &self.foreground_executor
145 }
146
147 /// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
148 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R> {
149 let app = self
150 .app
151 .upgrade()
152 .ok_or_else(|| anyhow!("app was released"))?;
153 let mut lock = app.borrow_mut();
154 Ok(lock.update(f))
155 }
156
157 /// Open a window with the given options based on the root view returned by the given function.
158 pub fn open_window<V>(
159 &self,
160 options: crate::WindowOptions,
161 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
162 ) -> Result<WindowHandle<V>>
163 where
164 V: 'static + Render,
165 {
166 let app = self
167 .app
168 .upgrade()
169 .ok_or_else(|| anyhow!("app was released"))?;
170 let mut lock = app.borrow_mut();
171 lock.open_window(options, build_root_view)
172 }
173
174 /// Schedule a future to be polled in the background.
175 #[track_caller]
176 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
177 where
178 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
179 R: 'static,
180 {
181 let mut cx = self.clone();
182 self.foreground_executor
183 .spawn(async move { f(&mut cx).await })
184 }
185
186 /// Determine whether global state of the specified type has been assigned.
187 /// Returns an error if the `App` has been dropped.
188 pub fn has_global<G: Global>(&self) -> Result<bool> {
189 let app = self
190 .app
191 .upgrade()
192 .ok_or_else(|| anyhow!("app was released"))?;
193 let app = app.borrow_mut();
194 Ok(app.has_global::<G>())
195 }
196
197 /// Reads the global state of the specified type, passing it to the given callback.
198 ///
199 /// Panics if no global state of the specified type has been assigned.
200 /// Returns an error if the `App` has been dropped.
201 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
202 let app = self
203 .app
204 .upgrade()
205 .ok_or_else(|| anyhow!("app was released"))?;
206 let app = app.borrow_mut();
207 Ok(read(app.global(), &app))
208 }
209
210 /// Reads the global state of the specified type, passing it to the given callback.
211 ///
212 /// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
213 /// if no state of the specified type has been assigned.
214 ///
215 /// Returns an error if no state of the specified type has been assigned the `App` has been dropped.
216 pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
217 let app = self.app.upgrade()?;
218 let app = app.borrow_mut();
219 Some(read(app.try_global()?, &app))
220 }
221
222 /// A convenience method for [App::update_global]
223 /// for updating the global state of the specified type.
224 pub fn update_global<G: Global, R>(
225 &self,
226 update: impl FnOnce(&mut G, &mut App) -> R,
227 ) -> Result<R> {
228 let app = self
229 .app
230 .upgrade()
231 .ok_or_else(|| anyhow!("app was released"))?;
232 let mut app = app.borrow_mut();
233 Ok(app.update(|cx| cx.update_global(update)))
234 }
235
236 /// Run something using this entity and cx, when the returned struct is dropped
237 pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
238 &self,
239 entity: &WeakEntity<T>,
240 f: Callback,
241 ) -> util::Deferred<impl FnOnce() + use<T, Callback>> {
242 let entity = entity.clone();
243 let mut cx = self.clone();
244 util::defer(move || {
245 entity.update(&mut cx, f).ok();
246 })
247 }
248}
249
250/// A cloneable, owned handle to the application context,
251/// composed with the window associated with the current task.
252#[derive(Clone, Deref, DerefMut)]
253pub struct AsyncWindowContext {
254 #[deref]
255 #[deref_mut]
256 app: AsyncApp,
257 window: AnyWindowHandle,
258}
259
260impl AsyncWindowContext {
261 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
262 Self { app, window }
263 }
264
265 /// Get the handle of the window this context is associated with.
266 pub fn window_handle(&self) -> AnyWindowHandle {
267 self.window
268 }
269
270 /// A convenience method for [`App::update_window`].
271 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
272 self.app
273 .update_window(self.window, |_, window, cx| update(window, cx))
274 }
275
276 /// A convenience method for [`App::update_window`].
277 pub fn update_root<R>(
278 &mut self,
279 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
280 ) -> Result<R> {
281 self.app.update_window(self.window, update)
282 }
283
284 /// A convenience method for [`Window::on_next_frame`].
285 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
286 self.window
287 .update(self, |_, window, _| window.on_next_frame(f))
288 .ok();
289 }
290
291 /// A convenience method for [`App::global`].
292 pub fn read_global<G: Global, R>(
293 &mut self,
294 read: impl FnOnce(&G, &Window, &App) -> R,
295 ) -> Result<R> {
296 self.window
297 .update(self, |_, window, cx| read(cx.global(), window, cx))
298 }
299
300 /// A convenience method for [`App::update_global`].
301 /// for updating the global state of the specified type.
302 pub fn update_global<G, R>(
303 &mut self,
304 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
305 ) -> Result<R>
306 where
307 G: Global,
308 {
309 self.window.update(self, |_, window, cx| {
310 cx.update_global(|global, cx| update(global, window, cx))
311 })
312 }
313
314 /// Schedule a future to be executed on the main thread. This is used for collecting
315 /// the results of background tasks and updating the UI.
316 #[track_caller]
317 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
318 where
319 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
320 R: 'static,
321 {
322 let mut cx = self.clone();
323 self.foreground_executor
324 .spawn(async move { f(&mut cx).await })
325 }
326
327 /// Present a platform dialog.
328 /// The provided message will be presented, along with buttons for each answer.
329 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
330 pub fn prompt(
331 &mut self,
332 level: PromptLevel,
333 message: &str,
334 detail: Option<&str>,
335 answers: &[&str],
336 ) -> oneshot::Receiver<usize> {
337 self.window
338 .update(self, |_, window, cx| {
339 window.prompt(level, message, detail, answers, cx)
340 })
341 .unwrap_or_else(|_| oneshot::channel().1)
342 }
343}
344
345impl AppContext for AsyncWindowContext {
346 type Result<T> = Result<T>;
347
348 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Result<Entity<T>>
349 where
350 T: 'static,
351 {
352 self.window.update(self, |_, _, cx| cx.new(build_entity))
353 }
354
355 fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
356 self.window.update(self, |_, _, cx| cx.reserve_entity())
357 }
358
359 fn insert_entity<T: 'static>(
360 &mut self,
361 reservation: Reservation<T>,
362 build_entity: impl FnOnce(&mut Context<T>) -> T,
363 ) -> Self::Result<Entity<T>> {
364 self.window
365 .update(self, |_, _, cx| cx.insert_entity(reservation, build_entity))
366 }
367
368 fn update_entity<T: 'static, R>(
369 &mut self,
370 handle: &Entity<T>,
371 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
372 ) -> Result<R> {
373 self.window
374 .update(self, |_, _, cx| cx.update_entity(handle, update))
375 }
376
377 fn read_entity<T, R>(
378 &self,
379 handle: &Entity<T>,
380 read: impl FnOnce(&T, &App) -> R,
381 ) -> Self::Result<R>
382 where
383 T: 'static,
384 {
385 self.app.read_entity(handle, read)
386 }
387
388 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
389 where
390 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
391 {
392 self.app.update_window(window, update)
393 }
394
395 fn read_window<T, R>(
396 &self,
397 window: &WindowHandle<T>,
398 read: impl FnOnce(Entity<T>, &App) -> R,
399 ) -> Result<R>
400 where
401 T: 'static,
402 {
403 self.app.read_window(window, read)
404 }
405
406 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
407 where
408 R: Send + 'static,
409 {
410 self.app.background_executor.spawn(future)
411 }
412
413 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
414 where
415 G: Global,
416 {
417 self.app.read_global(callback)
418 }
419}
420
421impl VisualContext for AsyncWindowContext {
422 fn window_handle(&self) -> AnyWindowHandle {
423 self.window
424 }
425
426 fn new_window_entity<T: 'static>(
427 &mut self,
428 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
429 ) -> Self::Result<Entity<T>> {
430 self.window
431 .update(self, |_, window, cx| cx.new(|cx| build_entity(window, cx)))
432 }
433
434 fn update_window_entity<T: 'static, R>(
435 &mut self,
436 view: &Entity<T>,
437 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
438 ) -> Self::Result<R> {
439 self.window.update(self, |_, window, cx| {
440 view.update(cx, |entity, cx| update(entity, window, cx))
441 })
442 }
443
444 fn replace_root_view<V>(
445 &mut self,
446 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
447 ) -> Self::Result<Entity<V>>
448 where
449 V: 'static + Render,
450 {
451 self.window
452 .update(self, |_, window, cx| window.replace_root(cx, build_view))
453 }
454
455 fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
456 where
457 V: Focusable,
458 {
459 self.window.update(self, |_, window, cx| {
460 view.read(cx).focus_handle(cx).clone().focus(window);
461 })
462 }
463}