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.refresh_windows();
150 }
151
152 pub fn background_executor(&self) -> &BackgroundExecutor {
154 &self.background_executor
155 }
156
157 pub fn foreground_executor(&self) -> &ForegroundExecutor {
159 &self.foreground_executor
160 }
161
162 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
164 let app = self.app();
165 let mut lock = app.borrow_mut();
166 lock.update(f)
167 }
168
169 pub fn subscribe<T, Event>(
172 &mut self,
173 entity: &Entity<T>,
174 on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
175 ) -> Subscription
176 where
177 T: 'static + EventEmitter<Event>,
178 Event: 'static,
179 {
180 let app = self.app();
181 let mut lock = app.borrow_mut();
182 lock.subscribe(entity, on_event)
183 }
184
185 pub fn open_window<V>(
187 &self,
188 options: crate::WindowOptions,
189 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
190 ) -> Result<WindowHandle<V>>
191 where
192 V: 'static + Render,
193 {
194 let app = self.app();
195 let mut lock = app.borrow_mut();
196 if lock.quitting {
197 bail!("app is quitting");
198 }
199 lock.open_window(options, build_root_view)
200 }
201
202 #[track_caller]
204 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
205 where
206 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
207 R: 'static,
208 {
209 let mut cx = self.clone();
210 self.foreground_executor
211 .spawn(async move { f(&mut cx).await }.boxed_local())
212 }
213
214 pub fn has_global<G: Global>(&self) -> bool {
216 let app = self.app();
217 let app = app.borrow_mut();
218 app.has_global::<G>()
219 }
220
221 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
225 let app = self.app();
226 let app = app.borrow_mut();
227 read(app.global(), &app)
228 }
229
230 pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
234 let app = self.app();
235 let app = app.borrow_mut();
236 if app.quitting {
237 return None;
238 }
239 Some(read(app.try_global()?, &app))
240 }
241
242 pub fn read_default_global<G: Global + Default, R>(
245 &self,
246 read: impl FnOnce(&G, &App) -> R,
247 ) -> R {
248 let app = self.app();
249 let mut app = app.borrow_mut();
250 app.update(|cx| {
251 cx.default_global::<G>();
252 });
253 read(app.global(), &app)
254 }
255
256 pub fn update_global<G: Global, R>(&self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
259 let app = self.app();
260 let mut app = app.borrow_mut();
261 app.update(|cx| cx.update_global(update))
262 }
263
264 pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
266 &self,
267 entity: &WeakEntity<T>,
268 f: Callback,
269 ) -> gpui_util::Deferred<impl FnOnce() + use<T, Callback>> {
270 let entity = entity.clone();
271 let mut cx = self.clone();
272 gpui_util::defer(move || {
273 entity.update(&mut cx, f).ok();
274 })
275 }
276}
277
278#[derive(Clone, Deref, DerefMut)]
281pub struct AsyncWindowContext {
282 #[deref]
283 #[deref_mut]
284 app: AsyncApp,
285 window: AnyWindowHandle,
286}
287
288impl AsyncWindowContext {
289 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
290 Self { app, window }
291 }
292
293 pub fn window_handle(&self) -> AnyWindowHandle {
295 self.window
296 }
297
298 pub fn update_if_present<R>(
302 &mut self,
303 update: impl FnOnce(&mut Window, &mut App) -> R,
304 ) -> Result<Option<R>> {
305 let app = self.app.app.upgrade().context("app was released")?;
306 let mut app = app.try_borrow_mut()?;
307 if !app.windows.contains_key(self.window.window_id()) {
308 return Ok(None);
309 }
310 if app.quitting {
311 bail!("app is quitting");
312 }
313 app.update_window(self.window, |_, window, cx| update(window, cx))
314 .map(Some)
315 }
316
317 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
319 self.app
320 .update_window(self.window, |_, window, cx| update(window, cx))
321 }
322
323 pub fn update_root<R>(
325 &mut self,
326 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
327 ) -> Result<R> {
328 self.app.update_window(self.window, update)
329 }
330
331 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
333 self.app
334 .update_window(self.window, |_, window, _| window.on_next_frame(f))
335 .ok();
336 }
337
338 pub fn read_global<G: Global, R>(
340 &mut self,
341 read: impl FnOnce(&G, &Window, &App) -> R,
342 ) -> Result<R> {
343 self.app
344 .update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
345 }
346
347 pub fn update_global<G, R>(
350 &mut self,
351 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
352 ) -> Result<R>
353 where
354 G: Global,
355 {
356 self.app.update_window(self.window, |_, window, cx| {
357 cx.update_global(|global, cx| update(global, window, cx))
358 })
359 }
360
361 #[track_caller]
364 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
365 where
366 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
367 R: 'static,
368 {
369 let mut cx = self.clone();
370 self.foreground_executor
371 .spawn(async move { f(&mut cx).await }.boxed_local())
372 }
373
374 pub fn prompt<T>(
378 &mut self,
379 level: PromptLevel,
380 message: &str,
381 detail: Option<&str>,
382 answers: &[T],
383 ) -> oneshot::Receiver<usize>
384 where
385 T: Clone + Into<PromptButton>,
386 {
387 self.app
388 .update_window(self.window, |_, window, cx| {
389 window.prompt(level, message, detail, answers, cx)
390 })
391 .unwrap_or_else(|_| oneshot::channel().1)
392 }
393}
394
395impl AppContext for AsyncWindowContext {
396 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
397 where
398 T: 'static,
399 {
400 let mut build_entity = Some(build_entity);
401 match self.app.update_window(self.window, |_, _, cx| {
402 cx.new(
403 build_entity
404 .take()
405 .expect("build_entity is taken exactly once"),
406 )
407 }) {
408 Ok(entity) => entity,
409 Err(_) => self.app.new(
410 build_entity
411 .take()
412 .expect("update_window returned Err without invoking the closure"),
413 ),
414 }
415 }
416
417 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
418 self.app.reserve_entity()
419 }
420
421 fn insert_entity<T: 'static>(
422 &mut self,
423 reservation: Reservation<T>,
424 build_entity: impl FnOnce(&mut Context<T>) -> T,
425 ) -> Entity<T> {
426 let mut args = Some((reservation, build_entity));
427 match self.app.update_window(self.window, |_, _, cx| {
428 let (reservation, build_entity) = args.take().expect("args are taken exactly once");
429 cx.insert_entity(reservation, build_entity)
430 }) {
431 Ok(entity) => entity,
432 Err(_) => {
433 let (reservation, build_entity) = args
434 .take()
435 .expect("update_window returned Err without invoking the closure");
436 self.app.insert_entity(reservation, build_entity)
437 }
438 }
439 }
440
441 fn update_entity<T: 'static, R>(
442 &mut self,
443 handle: &Entity<T>,
444 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
445 ) -> R {
446 self.app.update_entity(handle, update)
447 }
448
449 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
450 where
451 T: 'static,
452 {
453 panic!("Cannot use as_mut() from an async context, call `update`")
454 }
455
456 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
457 where
458 T: 'static,
459 {
460 self.app.read_entity(handle, read)
461 }
462
463 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
464 where
465 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
466 {
467 self.app.update_window(window, update)
468 }
469
470 fn with_window<R>(
471 &mut self,
472 entity_id: EntityId,
473 f: impl FnOnce(&mut Window, &mut App) -> R,
474 ) -> Option<R> {
475 self.app.with_window(entity_id, f)
476 }
477
478 fn read_window<T, R>(
479 &self,
480 window: &WindowHandle<T>,
481 read: impl FnOnce(Entity<T>, &App) -> R,
482 ) -> Result<R>
483 where
484 T: 'static,
485 {
486 self.app.read_window(window, read)
487 }
488
489 #[track_caller]
490 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
491 where
492 R: Send + 'static,
493 {
494 self.app.background_executor.spawn(future)
495 }
496
497 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
498 where
499 G: Global,
500 {
501 self.app.read_global(callback)
502 }
503}
504
505impl VisualContext for AsyncWindowContext {
506 type Result<T> = Result<T>;
507
508 fn window_handle(&self) -> AnyWindowHandle {
509 self.window
510 }
511
512 fn new_window_entity<T: 'static>(
513 &mut self,
514 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
515 ) -> Result<Entity<T>> {
516 self.app.update_window(self.window, |_, window, cx| {
517 cx.new(|cx| build_entity(window, cx))
518 })
519 }
520
521 fn update_window_entity<T: 'static, R>(
522 &mut self,
523 view: &Entity<T>,
524 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
525 ) -> Result<R> {
526 let view = view.clone();
527 self.app
528 .with_window(view.entity_id(), |window, app| {
529 view.update(app, |entity, cx| update(entity, window, cx))
530 })
531 .context("entity has no current window")
532 }
533
534 fn replace_root_view<V>(
535 &mut self,
536 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
537 ) -> Result<Entity<V>>
538 where
539 V: 'static + Render,
540 {
541 self.app.update_window(self.window, |_, window, cx| {
542 window.replace_root(cx, build_view)
543 })
544 }
545
546 fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
547 where
548 V: Focusable,
549 {
550 self.app.update_window(self.window, |_, window, cx| {
551 view.read(cx).focus_handle(cx).focus(window, cx);
552 })
553 }
554}