1use crate::{
2 AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
3 Entity, EntityId, EventEmitter, Focusable, ForegroundExecutor, Global, GpuiBorrow,
4 PromptButton, PromptLevel, Render, Reservation, Result, Subscription, Task, VisualContext,
5 Window, WindowHandle,
6};
7use anyhow::{Context as _, bail};
8use derive_more::{Deref, DerefMut};
9use futures::channel::oneshot;
10use futures::future::FutureExt;
11use std::{future::Future, rc::Weak};
12
13use super::{Context, WeakEntity};
14
15#[derive(Clone)]
22pub struct AsyncApp {
23 pub(crate) app: Weak<AppCell>,
24 pub(crate) background_executor: BackgroundExecutor,
25 pub(crate) foreground_executor: ForegroundExecutor,
26}
27
28impl AsyncApp {
29 fn app(&self) -> std::rc::Rc<AppCell> {
30 self.app
31 .upgrade()
32 .expect("app was released before async operation completed")
33 }
34}
35
36impl AppContext for AsyncApp {
37 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
38 let app = self.app();
39 let mut app = app.borrow_mut();
40 app.new(build_entity)
41 }
42
43 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
44 let app = self.app();
45 let mut app = app.borrow_mut();
46 app.reserve_entity()
47 }
48
49 fn insert_entity<T: 'static>(
50 &mut self,
51 reservation: Reservation<T>,
52 build_entity: impl FnOnce(&mut Context<T>) -> T,
53 ) -> Entity<T> {
54 let app = self.app();
55 let mut app = app.borrow_mut();
56 app.insert_entity(reservation, build_entity)
57 }
58
59 fn update_entity<T: 'static, R>(
60 &mut self,
61 handle: &Entity<T>,
62 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
63 ) -> R {
64 let app = self.app();
65 let mut app = app.borrow_mut();
66 app.update_entity(handle, update)
67 }
68
69 fn as_mut<'a, T>(&'a mut self, _handle: &Entity<T>) -> GpuiBorrow<'a, T>
70 where
71 T: 'static,
72 {
73 panic!("Cannot as_mut with an async context. Try calling update() first")
74 }
75
76 fn read_entity<T, R>(&self, handle: &Entity<T>, callback: impl FnOnce(&T, &App) -> R) -> R
77 where
78 T: 'static,
79 {
80 let app = self.app();
81 let lock = app.borrow();
82 lock.read_entity(handle, callback)
83 }
84
85 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
86 where
87 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
88 {
89 let app = self.app.upgrade().context("app was released")?;
90 let mut lock = app.try_borrow_mut()?;
91 if lock.quitting {
92 bail!("app is quitting");
93 }
94 lock.update_window(window, f)
95 }
96
97 fn with_window<R>(
98 &mut self,
99 entity_id: EntityId,
100 f: impl FnOnce(&mut Window, &mut App) -> R,
101 ) -> Option<R> {
102 let app = self.app.upgrade()?;
103 let mut lock = app.try_borrow_mut().ok()?;
104 if lock.quitting {
105 return None;
106 }
107 lock.with_window(entity_id, f)
108 }
109
110 fn read_window<T, R>(
111 &self,
112 window: &WindowHandle<T>,
113 read: impl FnOnce(Entity<T>, &App) -> R,
114 ) -> Result<R>
115 where
116 T: 'static,
117 {
118 let app = self.app.upgrade().context("app was released")?;
119 let lock = app.borrow();
120 if lock.quitting {
121 bail!("app is quitting");
122 }
123 lock.read_window(window, read)
124 }
125
126 #[track_caller]
127 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
128 where
129 R: Send + 'static,
130 {
131 self.background_executor.spawn(future)
132 }
133
134 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
135 where
136 G: Global,
137 {
138 let app = self.app();
139 let mut lock = app.borrow_mut();
140 lock.update(|this| this.read_global(callback))
141 }
142}
143
144impl AsyncApp {
145 pub fn refresh(&self) {
147 let app = self.app();
148 let mut lock = app.borrow_mut();
149 lock.update(|cx| cx.refresh_windows());
152 }
153
154 pub fn background_executor(&self) -> &BackgroundExecutor {
156 &self.background_executor
157 }
158
159 pub fn foreground_executor(&self) -> &ForegroundExecutor {
161 &self.foreground_executor
162 }
163
164 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
166 let app = self.app();
167 let mut lock = app.borrow_mut();
168 lock.update(f)
169 }
170
171 pub fn subscribe<T, Event>(
174 &mut self,
175 entity: &Entity<T>,
176 on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
177 ) -> Subscription
178 where
179 T: 'static + EventEmitter<Event>,
180 Event: 'static,
181 {
182 let app = self.app();
183 let mut lock = app.borrow_mut();
184 lock.subscribe(entity, on_event)
185 }
186
187 pub fn open_window<V>(
189 &self,
190 options: crate::WindowOptions,
191 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
192 ) -> Result<WindowHandle<V>>
193 where
194 V: 'static + Render,
195 {
196 let app = self.app();
197 let mut lock = app.borrow_mut();
198 if lock.quitting {
199 bail!("app is quitting");
200 }
201 lock.open_window(options, build_root_view)
202 }
203
204 #[track_caller]
206 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
207 where
208 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
209 R: 'static,
210 {
211 let mut cx = self.clone();
212 self.foreground_executor
213 .spawn(async move { f(&mut cx).await }.boxed_local())
214 }
215
216 pub fn has_global<G: Global>(&self) -> bool {
218 let app = self.app();
219 let app = app.borrow_mut();
220 app.has_global::<G>()
221 }
222
223 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
227 let app = self.app();
228 let app = app.borrow_mut();
229 read(app.global(), &app)
230 }
231
232 pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
236 let app = self.app();
237 let app = app.borrow_mut();
238 if app.quitting {
239 return None;
240 }
241 Some(read(app.try_global()?, &app))
242 }
243
244 pub fn read_default_global<G: Global + Default, R>(
247 &self,
248 read: impl FnOnce(&G, &App) -> R,
249 ) -> R {
250 let app = self.app();
251 let mut app = app.borrow_mut();
252 app.update(|cx| {
253 cx.default_global::<G>();
254 });
255 read(app.global(), &app)
256 }
257
258 pub fn update_global<G: Global, R>(&self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
261 let app = self.app();
262 let mut app = app.borrow_mut();
263 app.update(|cx| cx.update_global(update))
264 }
265
266 pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
268 &self,
269 entity: &WeakEntity<T>,
270 f: Callback,
271 ) -> gpui_util::Deferred<impl FnOnce() + use<T, Callback>> {
272 let entity = entity.clone();
273 let mut cx = self.clone();
274 gpui_util::defer(move || {
275 entity.update(&mut cx, f).ok();
276 })
277 }
278}
279
280#[derive(Clone, Deref, DerefMut)]
283pub struct AsyncWindowContext {
284 #[deref]
285 #[deref_mut]
286 app: AsyncApp,
287 window: AnyWindowHandle,
288}
289
290impl AsyncWindowContext {
291 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
292 Self { app, window }
293 }
294
295 pub fn window_handle(&self) -> AnyWindowHandle {
297 self.window
298 }
299
300 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
302 self.app
303 .update_window(self.window, |_, window, cx| update(window, cx))
304 }
305
306 pub fn update_root<R>(
308 &mut self,
309 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
310 ) -> Result<R> {
311 self.app.update_window(self.window, update)
312 }
313
314 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
316 self.app
317 .update_window(self.window, |_, window, _| window.on_next_frame(f))
318 .ok();
319 }
320
321 pub fn read_global<G: Global, R>(
323 &mut self,
324 read: impl FnOnce(&G, &Window, &App) -> R,
325 ) -> Result<R> {
326 self.app
327 .update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
328 }
329
330 pub fn update_global<G, R>(
333 &mut self,
334 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
335 ) -> Result<R>
336 where
337 G: Global,
338 {
339 self.app.update_window(self.window, |_, window, cx| {
340 cx.update_global(|global, cx| update(global, window, cx))
341 })
342 }
343
344 #[track_caller]
347 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
348 where
349 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
350 R: 'static,
351 {
352 let mut cx = self.clone();
353 self.foreground_executor
354 .spawn(async move { f(&mut cx).await }.boxed_local())
355 }
356
357 pub fn prompt<T>(
361 &mut self,
362 level: PromptLevel,
363 message: &str,
364 detail: Option<&str>,
365 answers: &[T],
366 ) -> oneshot::Receiver<usize>
367 where
368 T: Clone + Into<PromptButton>,
369 {
370 self.app
371 .update_window(self.window, |_, window, cx| {
372 window.prompt(level, message, detail, answers, cx)
373 })
374 .unwrap_or_else(|_| oneshot::channel().1)
375 }
376}
377
378impl AppContext for AsyncWindowContext {
379 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
380 where
381 T: 'static,
382 {
383 let mut build_entity = Some(build_entity);
384 match self.app.update_window(self.window, |_, _, cx| {
385 cx.new(
386 build_entity
387 .take()
388 .expect("build_entity is taken exactly once"),
389 )
390 }) {
391 Ok(entity) => entity,
392 Err(_) => self.app.new(
393 build_entity
394 .take()
395 .expect("update_window returned Err without invoking the closure"),
396 ),
397 }
398 }
399
400 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
401 self.app.reserve_entity()
402 }
403
404 fn insert_entity<T: 'static>(
405 &mut self,
406 reservation: Reservation<T>,
407 build_entity: impl FnOnce(&mut Context<T>) -> T,
408 ) -> Entity<T> {
409 let mut args = Some((reservation, build_entity));
410 match self.app.update_window(self.window, |_, _, cx| {
411 let (reservation, build_entity) = args.take().expect("args are taken exactly once");
412 cx.insert_entity(reservation, build_entity)
413 }) {
414 Ok(entity) => entity,
415 Err(_) => {
416 let (reservation, build_entity) = args
417 .take()
418 .expect("update_window returned Err without invoking the closure");
419 self.app.insert_entity(reservation, build_entity)
420 }
421 }
422 }
423
424 fn update_entity<T: 'static, R>(
425 &mut self,
426 handle: &Entity<T>,
427 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
428 ) -> R {
429 self.app.update_entity(handle, update)
430 }
431
432 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
433 where
434 T: 'static,
435 {
436 panic!("Cannot use as_mut() from an async context, call `update`")
437 }
438
439 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
440 where
441 T: 'static,
442 {
443 self.app.read_entity(handle, read)
444 }
445
446 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
447 where
448 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
449 {
450 self.app.update_window(window, update)
451 }
452
453 fn with_window<R>(
454 &mut self,
455 entity_id: EntityId,
456 f: impl FnOnce(&mut Window, &mut App) -> R,
457 ) -> Option<R> {
458 self.app.with_window(entity_id, f)
459 }
460
461 fn read_window<T, R>(
462 &self,
463 window: &WindowHandle<T>,
464 read: impl FnOnce(Entity<T>, &App) -> R,
465 ) -> Result<R>
466 where
467 T: 'static,
468 {
469 self.app.read_window(window, read)
470 }
471
472 #[track_caller]
473 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
474 where
475 R: Send + 'static,
476 {
477 self.app.background_executor.spawn(future)
478 }
479
480 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
481 where
482 G: Global,
483 {
484 self.app.read_global(callback)
485 }
486}
487
488impl VisualContext for AsyncWindowContext {
489 type Result<T> = Result<T>;
490
491 fn window_handle(&self) -> AnyWindowHandle {
492 self.window
493 }
494
495 fn new_window_entity<T: 'static>(
496 &mut self,
497 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
498 ) -> Result<Entity<T>> {
499 self.app.update_window(self.window, |_, window, cx| {
500 cx.new(|cx| build_entity(window, cx))
501 })
502 }
503
504 fn update_window_entity<T: 'static, R>(
505 &mut self,
506 view: &Entity<T>,
507 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
508 ) -> Result<R> {
509 let view = view.clone();
510 self.app
511 .with_window(view.entity_id(), |window, app| {
512 view.update(app, |entity, cx| update(entity, window, cx))
513 })
514 .context("entity has no current window")
515 }
516
517 fn replace_root_view<V>(
518 &mut self,
519 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
520 ) -> Result<Entity<V>>
521 where
522 V: 'static + Render,
523 {
524 self.app.update_window(self.window, |_, window, cx| {
525 window.replace_root(cx, build_view)
526 })
527 }
528
529 fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
530 where
531 V: Focusable,
532 {
533 self.app.update_window(self.window, |_, window, cx| {
534 view.read(cx).focus_handle(cx).focus(window, cx);
535 })
536 }
537}