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 _, anyhow};
7use derive_more::{Deref, DerefMut};
8use futures::channel::oneshot;
9use std::{future::Future, rc::Weak};
10
11use super::{Context, WeakEntity};
12
13#[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 as_mut<'a, T>(&'a mut self, _handle: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
62 where
63 T: 'static,
64 {
65 Err(anyhow!(
66 "Cannot as_mut with an async context. Try calling update() first"
67 ))
68 }
69
70 fn read_entity<T, R>(
71 &self,
72 handle: &Entity<T>,
73 callback: impl FnOnce(&T, &App) -> R,
74 ) -> Self::Result<R>
75 where
76 T: 'static,
77 {
78 let app = self.app.upgrade().context("app was released")?;
79 let lock = app.borrow();
80 Ok(lock.read_entity(handle, callback))
81 }
82
83 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
84 where
85 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
86 {
87 let app = self.app.upgrade().context("app was released")?;
88 let mut lock = app.try_borrow_mut()?;
89 lock.update_window(window, f)
90 }
91
92 fn read_window<T, R>(
93 &self,
94 window: &WindowHandle<T>,
95 read: impl FnOnce(Entity<T>, &App) -> R,
96 ) -> Result<R>
97 where
98 T: 'static,
99 {
100 let app = self.app.upgrade().context("app was released")?;
101 let lock = app.borrow();
102 lock.read_window(window, read)
103 }
104
105 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
106 where
107 R: Send + 'static,
108 {
109 self.background_executor.spawn(future)
110 }
111
112 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
113 where
114 G: Global,
115 {
116 let app = self.app.upgrade().context("app was released")?;
117 let mut lock = app.borrow_mut();
118 Ok(lock.update(|this| this.read_global(callback)))
119 }
120}
121
122impl AsyncApp {
123 pub fn refresh(&self) -> Result<()> {
125 let app = self.app.upgrade().context("app was released")?;
126 let mut lock = app.borrow_mut();
127 lock.update(|cx| cx.refresh_windows());
130 Ok(())
131 }
132
133 pub fn background_executor(&self) -> &BackgroundExecutor {
135 &self.background_executor
136 }
137
138 pub fn foreground_executor(&self) -> &ForegroundExecutor {
140 &self.foreground_executor
141 }
142
143 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R> {
145 let app = self.app.upgrade().context("app was released")?;
146 let mut lock = app.borrow_mut();
147 Ok(lock.update(f))
148 }
149
150 pub fn subscribe<T, Event>(
153 &mut self,
154 entity: &Entity<T>,
155 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
156 ) -> Result<Subscription>
157 where
158 T: 'static + EventEmitter<Event>,
159 Event: 'static,
160 {
161 let app = self.app.upgrade().context("app was released")?;
162 let mut lock = app.borrow_mut();
163 let subscription = lock.subscribe(entity, on_event);
164 Ok(subscription)
165 }
166
167 pub fn open_window<V>(
169 &self,
170 options: crate::WindowOptions,
171 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
172 ) -> Result<WindowHandle<V>>
173 where
174 V: 'static + Render,
175 {
176 let app = self.app.upgrade().context("app was released")?;
177 let mut lock = app.borrow_mut();
178 lock.open_window(options, build_root_view)
179 }
180
181 #[track_caller]
183 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
184 where
185 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
186 R: 'static,
187 {
188 let mut cx = self.clone();
189 self.foreground_executor
190 .spawn(async move { f(&mut cx).await })
191 }
192
193 pub fn has_global<G: Global>(&self) -> Result<bool> {
196 let app = self.app.upgrade().context("app was released")?;
197 let app = app.borrow_mut();
198 Ok(app.has_global::<G>())
199 }
200
201 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
206 let app = self.app.upgrade().context("app was released")?;
207 let app = app.borrow_mut();
208 Ok(read(app.global(), &app))
209 }
210
211 pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
218 let app = self.app.upgrade()?;
219 let app = app.borrow_mut();
220 Some(read(app.try_global()?, &app))
221 }
222
223 pub fn try_read_default_global<G: Global + Default, R>(
229 &self,
230 read: impl FnOnce(&G, &App) -> R,
231 ) -> Result<R> {
232 let app = self.app.upgrade().context("app was released")?;
233 let mut app = app.borrow_mut();
234 app.update(|cx| {
235 cx.default_global::<G>();
236 });
237 Ok(read(app.try_global().context("app was released")?, &app))
238 }
239
240 pub fn update_global<G: Global, R>(
243 &self,
244 update: impl FnOnce(&mut G, &mut App) -> R,
245 ) -> Result<R> {
246 let app = self.app.upgrade().context("app was released")?;
247 let mut app = app.borrow_mut();
248 Ok(app.update(|cx| cx.update_global(update)))
249 }
250
251 pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
253 &self,
254 entity: &WeakEntity<T>,
255 f: Callback,
256 ) -> util::Deferred<impl FnOnce() + use<T, Callback>> {
257 let entity = entity.clone();
258 let mut cx = self.clone();
259 util::defer(move || {
260 entity.update(&mut cx, f).ok();
261 })
262 }
263}
264
265#[derive(Clone, Deref, DerefMut)]
268pub struct AsyncWindowContext {
269 #[deref]
270 #[deref_mut]
271 app: AsyncApp,
272 window: AnyWindowHandle,
273}
274
275impl AsyncWindowContext {
276 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
277 Self { app, window }
278 }
279
280 pub fn window_handle(&self) -> AnyWindowHandle {
282 self.window
283 }
284
285 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
287 self.app
288 .update_window(self.window, |_, window, cx| update(window, cx))
289 }
290
291 pub fn update_root<R>(
293 &mut self,
294 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
295 ) -> Result<R> {
296 self.app.update_window(self.window, update)
297 }
298
299 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
301 self.window
302 .update(self, |_, window, _| window.on_next_frame(f))
303 .ok();
304 }
305
306 pub fn read_global<G: Global, R>(
308 &mut self,
309 read: impl FnOnce(&G, &Window, &App) -> R,
310 ) -> Result<R> {
311 self.window
312 .update(self, |_, window, cx| read(cx.global(), window, cx))
313 }
314
315 pub fn update_global<G, R>(
318 &mut self,
319 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
320 ) -> Result<R>
321 where
322 G: Global,
323 {
324 self.window.update(self, |_, window, cx| {
325 cx.update_global(|global, cx| update(global, window, cx))
326 })
327 }
328
329 #[track_caller]
332 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
333 where
334 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
335 R: 'static,
336 {
337 let mut cx = self.clone();
338 self.foreground_executor
339 .spawn(async move { f(&mut cx).await })
340 }
341
342 pub fn prompt<T>(
346 &mut self,
347 level: PromptLevel,
348 message: &str,
349 detail: Option<&str>,
350 answers: &[T],
351 ) -> oneshot::Receiver<usize>
352 where
353 T: Clone + Into<PromptButton>,
354 {
355 self.window
356 .update(self, |_, window, cx| {
357 window.prompt(level, message, detail, answers, cx)
358 })
359 .unwrap_or_else(|_| oneshot::channel().1)
360 }
361}
362
363impl AppContext for AsyncWindowContext {
364 type Result<T> = Result<T>;
365
366 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Result<Entity<T>>
367 where
368 T: 'static,
369 {
370 let mut build_entity = Some(build_entity);
371 match self.app.update_window(self.window, |_, _, cx| {
372 cx.new(
373 build_entity
374 .take()
375 .expect("build_entity is taken exactly once"),
376 )
377 }) {
378 Ok(entity) => Ok(entity),
379 Err(err) => {
380 let Some(build_entity) = build_entity.take() else {
381 return Err(err);
382 };
383 self.app.new(build_entity)
384 }
385 }
386 }
387
388 fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
389 self.app.reserve_entity()
390 }
391
392 fn insert_entity<T: 'static>(
393 &mut self,
394 reservation: Reservation<T>,
395 build_entity: impl FnOnce(&mut Context<T>) -> T,
396 ) -> Self::Result<Entity<T>> {
397 let mut args = Some((reservation, build_entity));
398 match self.app.update_window(self.window, |_, _, cx| {
399 let (reservation, build_entity) = args.take().expect("args are taken exactly once");
400 cx.insert_entity(reservation, build_entity)
401 }) {
402 Ok(entity) => Ok(entity),
403 Err(err) => {
404 let Some((reservation, build_entity)) = args.take() else {
405 return Err(err);
406 };
407 self.app.insert_entity(reservation, build_entity)
408 }
409 }
410 }
411
412 fn update_entity<T: 'static, R>(
413 &mut self,
414 handle: &Entity<T>,
415 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
416 ) -> Result<R> {
417 self.window
418 .update(self, |_, _, cx| cx.update_entity(handle, update))
419 }
420
421 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
422 where
423 T: 'static,
424 {
425 Err(anyhow!(
426 "Cannot use as_mut() from an async context, call `update`"
427 ))
428 }
429
430 fn read_entity<T, R>(
431 &self,
432 handle: &Entity<T>,
433 read: impl FnOnce(&T, &App) -> R,
434 ) -> Self::Result<R>
435 where
436 T: 'static,
437 {
438 self.app.read_entity(handle, read)
439 }
440
441 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
442 where
443 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
444 {
445 self.app.update_window(window, update)
446 }
447
448 fn read_window<T, R>(
449 &self,
450 window: &WindowHandle<T>,
451 read: impl FnOnce(Entity<T>, &App) -> R,
452 ) -> Result<R>
453 where
454 T: 'static,
455 {
456 self.app.read_window(window, read)
457 }
458
459 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
460 where
461 R: Send + 'static,
462 {
463 self.app.background_executor.spawn(future)
464 }
465
466 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
467 where
468 G: Global,
469 {
470 self.app.read_global(callback)
471 }
472}
473
474impl VisualContext for AsyncWindowContext {
475 fn window_handle(&self) -> AnyWindowHandle {
476 self.window
477 }
478
479 fn new_window_entity<T: 'static>(
480 &mut self,
481 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
482 ) -> Self::Result<Entity<T>> {
483 self.window
484 .update(self, |_, window, cx| cx.new(|cx| build_entity(window, cx)))
485 }
486
487 fn update_window_entity<T: 'static, R>(
488 &mut self,
489 view: &Entity<T>,
490 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
491 ) -> Self::Result<R> {
492 self.window.update(self, |_, window, cx| {
493 view.update(cx, |entity, cx| update(entity, window, cx))
494 })
495 }
496
497 fn replace_root_view<V>(
498 &mut self,
499 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
500 ) -> Self::Result<Entity<V>>
501 where
502 V: 'static + Render,
503 {
504 self.window
505 .update(self, |_, window, cx| window.replace_root(cx, build_view))
506 }
507
508 fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
509 where
510 V: Focusable,
511 {
512 self.window.update(self, |_, window, cx| {
513 view.read(cx).focus_handle(cx).focus(window);
514 })
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521 use crate::{Empty, TestAppContext};
522
523 struct TestEntity(usize);
524
525 #[test]
526 fn async_window_context_creates_entities_after_window_closes() {
527 let mut cx = TestAppContext::single();
528 let window = cx.add_window(|_, _| Empty);
529 let window: AnyWindowHandle = window.into();
530 let mut async_cx = cx
531 .update_window(window, |_, window, cx| window.to_async(cx))
532 .unwrap();
533
534 cx.update_window(window, |_, window, _| window.remove_window())
535 .unwrap();
536 assert!(cx.update_window(window, |_, _, _| ()).is_err());
537
538 let entity = async_cx.new(|_| TestEntity(1)).unwrap();
539 assert_eq!(
540 async_cx.read_entity(&entity, |entity, _| entity.0).unwrap(),
541 1
542 );
543
544 let reservation = async_cx.reserve_entity::<TestEntity>().unwrap();
545 let entity = async_cx
546 .insert_entity(reservation, |_| TestEntity(2))
547 .unwrap();
548 assert_eq!(
549 async_cx.read_entity(&entity, |entity, _| entity.0).unwrap(),
550 2
551 );
552 }
553}