1use crate::{
2 AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
3 Entity, EventEmitter, Focusable, ForegroundExecutor, Global, PromptLevel, Render, Reservation,
4 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(
318 &mut self,
319 level: PromptLevel,
320 message: &str,
321 detail: Option<&str>,
322 answers: &[&str],
323 ) -> oneshot::Receiver<usize> {
324 self.window
325 .update(self, |_, window, cx| {
326 window.prompt(level, message, detail, answers, cx)
327 })
328 .unwrap_or_else(|_| oneshot::channel().1)
329 }
330}
331
332impl AppContext for AsyncWindowContext {
333 type Result<T> = Result<T>;
334
335 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Result<Entity<T>>
336 where
337 T: 'static,
338 {
339 self.window.update(self, |_, _, cx| cx.new(build_entity))
340 }
341
342 fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
343 self.window.update(self, |_, _, cx| cx.reserve_entity())
344 }
345
346 fn insert_entity<T: 'static>(
347 &mut self,
348 reservation: Reservation<T>,
349 build_entity: impl FnOnce(&mut Context<T>) -> T,
350 ) -> Self::Result<Entity<T>> {
351 self.window
352 .update(self, |_, _, cx| cx.insert_entity(reservation, build_entity))
353 }
354
355 fn update_entity<T: 'static, R>(
356 &mut self,
357 handle: &Entity<T>,
358 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
359 ) -> Result<R> {
360 self.window
361 .update(self, |_, _, cx| cx.update_entity(handle, update))
362 }
363
364 fn read_entity<T, R>(
365 &self,
366 handle: &Entity<T>,
367 read: impl FnOnce(&T, &App) -> R,
368 ) -> Self::Result<R>
369 where
370 T: 'static,
371 {
372 self.app.read_entity(handle, read)
373 }
374
375 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
376 where
377 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
378 {
379 self.app.update_window(window, update)
380 }
381
382 fn read_window<T, R>(
383 &self,
384 window: &WindowHandle<T>,
385 read: impl FnOnce(Entity<T>, &App) -> R,
386 ) -> Result<R>
387 where
388 T: 'static,
389 {
390 self.app.read_window(window, read)
391 }
392
393 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
394 where
395 R: Send + 'static,
396 {
397 self.app.background_executor.spawn(future)
398 }
399
400 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
401 where
402 G: Global,
403 {
404 self.app.read_global(callback)
405 }
406}
407
408impl VisualContext for AsyncWindowContext {
409 fn window_handle(&self) -> AnyWindowHandle {
410 self.window
411 }
412
413 fn new_window_entity<T: 'static>(
414 &mut self,
415 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
416 ) -> Self::Result<Entity<T>> {
417 self.window
418 .update(self, |_, window, cx| cx.new(|cx| build_entity(window, cx)))
419 }
420
421 fn update_window_entity<T: 'static, R>(
422 &mut self,
423 view: &Entity<T>,
424 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
425 ) -> Self::Result<R> {
426 self.window.update(self, |_, window, cx| {
427 view.update(cx, |entity, cx| update(entity, window, cx))
428 })
429 }
430
431 fn replace_root_view<V>(
432 &mut self,
433 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
434 ) -> Self::Result<Entity<V>>
435 where
436 V: 'static + Render,
437 {
438 self.window
439 .update(self, |_, window, cx| window.replace_root(cx, build_view))
440 }
441
442 fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
443 where
444 V: Focusable,
445 {
446 self.window.update(self, |_, window, cx| {
447 view.read(cx).focus_handle(cx).clone().focus(window);
448 })
449 }
450}