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<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
300 self.app
301 .update_window(self.window, |_, window, cx| update(window, cx))
302 }
303
304 pub fn update_root<R>(
306 &mut self,
307 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
308 ) -> Result<R> {
309 self.app.update_window(self.window, update)
310 }
311
312 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
314 self.app
315 .update_window(self.window, |_, window, _| window.on_next_frame(f))
316 .ok();
317 }
318
319 pub fn read_global<G: Global, R>(
321 &mut self,
322 read: impl FnOnce(&G, &Window, &App) -> R,
323 ) -> Result<R> {
324 self.app
325 .update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
326 }
327
328 pub fn update_global<G, R>(
331 &mut self,
332 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
333 ) -> Result<R>
334 where
335 G: Global,
336 {
337 self.app.update_window(self.window, |_, window, cx| {
338 cx.update_global(|global, cx| update(global, window, cx))
339 })
340 }
341
342 #[track_caller]
345 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
346 where
347 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
348 R: 'static,
349 {
350 let mut cx = self.clone();
351 self.foreground_executor
352 .spawn(async move { f(&mut cx).await }.boxed_local())
353 }
354
355 pub fn prompt<T>(
359 &mut self,
360 level: PromptLevel,
361 message: &str,
362 detail: Option<&str>,
363 answers: &[T],
364 ) -> oneshot::Receiver<usize>
365 where
366 T: Clone + Into<PromptButton>,
367 {
368 self.app
369 .update_window(self.window, |_, window, cx| {
370 window.prompt(level, message, detail, answers, cx)
371 })
372 .unwrap_or_else(|_| oneshot::channel().1)
373 }
374}
375
376impl AppContext for AsyncWindowContext {
377 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
378 where
379 T: 'static,
380 {
381 let mut build_entity = Some(build_entity);
382 match self.app.update_window(self.window, |_, _, cx| {
383 cx.new(
384 build_entity
385 .take()
386 .expect("build_entity is taken exactly once"),
387 )
388 }) {
389 Ok(entity) => entity,
390 Err(_) => self.app.new(
391 build_entity
392 .take()
393 .expect("update_window returned Err without invoking the closure"),
394 ),
395 }
396 }
397
398 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
399 self.app.reserve_entity()
400 }
401
402 fn insert_entity<T: 'static>(
403 &mut self,
404 reservation: Reservation<T>,
405 build_entity: impl FnOnce(&mut Context<T>) -> T,
406 ) -> Entity<T> {
407 let mut args = Some((reservation, build_entity));
408 match self.app.update_window(self.window, |_, _, cx| {
409 let (reservation, build_entity) = args.take().expect("args are taken exactly once");
410 cx.insert_entity(reservation, build_entity)
411 }) {
412 Ok(entity) => entity,
413 Err(_) => {
414 let (reservation, build_entity) = args
415 .take()
416 .expect("update_window returned Err without invoking the closure");
417 self.app.insert_entity(reservation, build_entity)
418 }
419 }
420 }
421
422 fn update_entity<T: 'static, R>(
423 &mut self,
424 handle: &Entity<T>,
425 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
426 ) -> R {
427 self.app.update_entity(handle, update)
428 }
429
430 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
431 where
432 T: 'static,
433 {
434 panic!("Cannot use as_mut() from an async context, call `update`")
435 }
436
437 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
438 where
439 T: 'static,
440 {
441 self.app.read_entity(handle, read)
442 }
443
444 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
445 where
446 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
447 {
448 self.app.update_window(window, update)
449 }
450
451 fn with_window<R>(
452 &mut self,
453 entity_id: EntityId,
454 f: impl FnOnce(&mut Window, &mut App) -> R,
455 ) -> Option<R> {
456 self.app.with_window(entity_id, f)
457 }
458
459 fn read_window<T, R>(
460 &self,
461 window: &WindowHandle<T>,
462 read: impl FnOnce(Entity<T>, &App) -> R,
463 ) -> Result<R>
464 where
465 T: 'static,
466 {
467 self.app.read_window(window, read)
468 }
469
470 #[track_caller]
471 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
472 where
473 R: Send + 'static,
474 {
475 self.app.background_executor.spawn(future)
476 }
477
478 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
479 where
480 G: Global,
481 {
482 self.app.read_global(callback)
483 }
484}
485
486impl VisualContext for AsyncWindowContext {
487 type Result<T> = Result<T>;
488
489 fn window_handle(&self) -> AnyWindowHandle {
490 self.window
491 }
492
493 fn new_window_entity<T: 'static>(
494 &mut self,
495 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
496 ) -> Result<Entity<T>> {
497 self.app.update_window(self.window, |_, window, cx| {
498 cx.new(|cx| build_entity(window, cx))
499 })
500 }
501
502 fn update_window_entity<T: 'static, R>(
503 &mut self,
504 view: &Entity<T>,
505 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
506 ) -> Result<R> {
507 let view = view.clone();
508 self.app
509 .with_window(view.entity_id(), |window, app| {
510 view.update(app, |entity, cx| update(entity, window, cx))
511 })
512 .context("entity has no current window")
513 }
514
515 fn replace_root_view<V>(
516 &mut self,
517 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
518 ) -> Result<Entity<V>>
519 where
520 V: 'static + Render,
521 {
522 self.app.update_window(self.window, |_, window, cx| {
523 window.replace_root(cx, build_view)
524 })
525 }
526
527 fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
528 where
529 V: Focusable,
530 {
531 self.app.update_window(self.window, |_, window, cx| {
532 view.read(cx).focus_handle(cx).focus(window, cx);
533 })
534 }
535}