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