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::{anyhow, Context as _};
7use derive_more::{Deref, DerefMut};
8use futures::channel::oneshot;
9use std::{future::Future, rc::Weak};
10
11use super::Context;
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<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R>
177 where
178 Fut: Future<Output = R> + 'static,
179 R: 'static,
180 {
181 self.foreground_executor.spawn(f(self.clone()))
182 }
183
184 /// Determine whether global state of the specified type has been assigned.
185 /// Returns an error if the `App` has been dropped.
186 pub fn has_global<G: Global>(&self) -> Result<bool> {
187 let app = self
188 .app
189 .upgrade()
190 .ok_or_else(|| anyhow!("app was released"))?;
191 let app = app.borrow_mut();
192 Ok(app.has_global::<G>())
193 }
194
195 /// Reads the global state of the specified type, passing it to the given callback.
196 ///
197 /// Panics if no global state of the specified type has been assigned.
198 /// Returns an error if the `App` has been dropped.
199 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
200 let app = self
201 .app
202 .upgrade()
203 .ok_or_else(|| anyhow!("app was released"))?;
204 let app = app.borrow_mut();
205 Ok(read(app.global(), &app))
206 }
207
208 /// Reads the global state of the specified type, passing it to the given callback.
209 ///
210 /// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
211 /// if no state of the specified type has been assigned.
212 ///
213 /// Returns an error if no state of the specified type has been assigned the `App` has been dropped.
214 pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
215 let app = self.app.upgrade()?;
216 let app = app.borrow_mut();
217 Some(read(app.try_global()?, &app))
218 }
219
220 /// A convenience method for [App::update_global]
221 /// for updating the global state of the specified type.
222 pub fn update_global<G: Global, R>(
223 &self,
224 update: impl FnOnce(&mut G, &mut App) -> R,
225 ) -> Result<R> {
226 let app = self
227 .app
228 .upgrade()
229 .ok_or_else(|| anyhow!("app was released"))?;
230 let mut app = app.borrow_mut();
231 Ok(app.update(|cx| cx.update_global(update)))
232 }
233}
234
235/// A cloneable, owned handle to the application context,
236/// composed with the window associated with the current task.
237#[derive(Clone, Deref, DerefMut)]
238pub struct AsyncWindowContext {
239 #[deref]
240 #[deref_mut]
241 app: AsyncApp,
242 window: AnyWindowHandle,
243}
244
245impl AsyncWindowContext {
246 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
247 Self { app, window }
248 }
249
250 /// Get the handle of the window this context is associated with.
251 pub fn window_handle(&self) -> AnyWindowHandle {
252 self.window
253 }
254
255 /// A convenience method for [`App::update_window`].
256 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
257 self.app
258 .update_window(self.window, |_, window, cx| update(window, cx))
259 }
260
261 /// A convenience method for [`App::update_window`].
262 pub fn update_root<R>(
263 &mut self,
264 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
265 ) -> Result<R> {
266 self.app.update_window(self.window, update)
267 }
268
269 /// A convenience method for [`Window::on_next_frame`].
270 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
271 self.window
272 .update(self, |_, window, _| window.on_next_frame(f))
273 .ok();
274 }
275
276 /// A convenience method for [`App::global`].
277 pub fn read_global<G: Global, R>(
278 &mut self,
279 read: impl FnOnce(&G, &Window, &App) -> R,
280 ) -> Result<R> {
281 self.window
282 .update(self, |_, window, cx| read(cx.global(), window, cx))
283 }
284
285 /// A convenience method for [`App::update_global`].
286 /// for updating the global state of the specified type.
287 pub fn update_global<G, R>(
288 &mut self,
289 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
290 ) -> Result<R>
291 where
292 G: Global,
293 {
294 self.window.update(self, |_, window, cx| {
295 cx.update_global(|global, cx| update(global, window, cx))
296 })
297 }
298
299 /// Schedule a future to be executed on the main thread. This is used for collecting
300 /// the results of background tasks and updating the UI.
301 #[track_caller]
302 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
303 where
304 Fut: Future<Output = R> + 'static,
305 R: 'static,
306 {
307 self.foreground_executor.spawn(f(self.clone()))
308 }
309
310 /// Present a platform dialog.
311 /// The provided message will be presented, along with buttons for each answer.
312 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
313 pub fn prompt(
314 &mut self,
315 level: PromptLevel,
316 message: &str,
317 detail: Option<&str>,
318 answers: &[&str],
319 ) -> oneshot::Receiver<usize> {
320 self.window
321 .update(self, |_, window, cx| {
322 window.prompt(level, message, detail, answers, cx)
323 })
324 .unwrap_or_else(|_| oneshot::channel().1)
325 }
326}
327
328impl AppContext for AsyncWindowContext {
329 type Result<T> = Result<T>;
330
331 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<'_, T>) -> T) -> Result<Entity<T>>
332 where
333 T: 'static,
334 {
335 self.window.update(self, |_, _, cx| cx.new(build_entity))
336 }
337
338 fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
339 self.window.update(self, |_, _, cx| cx.reserve_entity())
340 }
341
342 fn insert_entity<T: 'static>(
343 &mut self,
344 reservation: Reservation<T>,
345 build_entity: impl FnOnce(&mut Context<'_, T>) -> T,
346 ) -> Self::Result<Entity<T>> {
347 self.window
348 .update(self, |_, _, cx| cx.insert_entity(reservation, build_entity))
349 }
350
351 fn update_entity<T: 'static, R>(
352 &mut self,
353 handle: &Entity<T>,
354 update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
355 ) -> Result<R> {
356 self.window
357 .update(self, |_, _, cx| cx.update_entity(handle, update))
358 }
359
360 fn read_entity<T, R>(
361 &self,
362 handle: &Entity<T>,
363 read: impl FnOnce(&T, &App) -> R,
364 ) -> Self::Result<R>
365 where
366 T: 'static,
367 {
368 self.app.read_entity(handle, read)
369 }
370
371 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
372 where
373 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
374 {
375 self.app.update_window(window, update)
376 }
377
378 fn read_window<T, R>(
379 &self,
380 window: &WindowHandle<T>,
381 read: impl FnOnce(Entity<T>, &App) -> R,
382 ) -> Result<R>
383 where
384 T: 'static,
385 {
386 self.app.read_window(window, read)
387 }
388
389 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
390 where
391 R: Send + 'static,
392 {
393 self.app.background_executor.spawn(future)
394 }
395
396 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
397 where
398 G: Global,
399 {
400 self.app.read_global(callback)
401 }
402}
403
404impl VisualContext for AsyncWindowContext {
405 fn window_handle(&self) -> AnyWindowHandle {
406 self.window
407 }
408
409 fn new_window_entity<T: 'static>(
410 &mut self,
411 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
412 ) -> Self::Result<Entity<T>> {
413 self.window
414 .update(self, |_, window, cx| cx.new(|cx| build_entity(window, cx)))
415 }
416
417 fn update_window_entity<T: 'static, R>(
418 &mut self,
419 view: &Entity<T>,
420 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
421 ) -> Self::Result<R> {
422 self.window.update(self, |_, window, cx| {
423 view.update(cx, |entity, cx| update(entity, window, cx))
424 })
425 }
426
427 fn replace_root_view<V>(
428 &mut self,
429 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
430 ) -> Self::Result<Entity<V>>
431 where
432 V: 'static + Render,
433 {
434 self.window
435 .update(self, |_, window, cx| window.replace_root(cx, build_view))
436 }
437
438 fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
439 where
440 V: Focusable,
441 {
442 self.window.update(self, |_, window, cx| {
443 view.read(cx).focus_handle(cx).clone().focus(window);
444 })
445 }
446}