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 self.app
385 .update_window(self.window, |_, _, cx| cx.new(build_entity))
386 .expect("window was unexpectedly closed")
387 }
388
389 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
390 self.app.reserve_entity()
391 }
392
393 fn insert_entity<T: 'static>(
394 &mut self,
395 reservation: Reservation<T>,
396 build_entity: impl FnOnce(&mut Context<T>) -> T,
397 ) -> Entity<T> {
398 self.app
399 .update_window(self.window, |_, _, cx| {
400 cx.insert_entity(reservation, build_entity)
401 })
402 .expect("window was unexpectedly closed")
403 }
404
405 fn update_entity<T: 'static, R>(
406 &mut self,
407 handle: &Entity<T>,
408 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
409 ) -> R {
410 self.app.update_entity(handle, update)
411 }
412
413 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
414 where
415 T: 'static,
416 {
417 panic!("Cannot use as_mut() from an async context, call `update`")
418 }
419
420 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
421 where
422 T: 'static,
423 {
424 self.app.read_entity(handle, read)
425 }
426
427 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
428 where
429 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
430 {
431 self.app.update_window(window, update)
432 }
433
434 fn with_window<R>(
435 &mut self,
436 entity_id: EntityId,
437 f: impl FnOnce(&mut Window, &mut App) -> R,
438 ) -> Option<R> {
439 self.app.with_window(entity_id, f)
440 }
441
442 fn read_window<T, R>(
443 &self,
444 window: &WindowHandle<T>,
445 read: impl FnOnce(Entity<T>, &App) -> R,
446 ) -> Result<R>
447 where
448 T: 'static,
449 {
450 self.app.read_window(window, read)
451 }
452
453 #[track_caller]
454 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
455 where
456 R: Send + 'static,
457 {
458 self.app.background_executor.spawn(future)
459 }
460
461 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
462 where
463 G: Global,
464 {
465 self.app.read_global(callback)
466 }
467}
468
469impl VisualContext for AsyncWindowContext {
470 type Result<T> = Result<T>;
471
472 fn window_handle(&self) -> AnyWindowHandle {
473 self.window
474 }
475
476 fn new_window_entity<T: 'static>(
477 &mut self,
478 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
479 ) -> Result<Entity<T>> {
480 self.app.update_window(self.window, |_, window, cx| {
481 cx.new(|cx| build_entity(window, cx))
482 })
483 }
484
485 fn update_window_entity<T: 'static, R>(
486 &mut self,
487 view: &Entity<T>,
488 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
489 ) -> Result<R> {
490 let view = view.clone();
491 self.app
492 .with_window(view.entity_id(), |window, app| {
493 view.update(app, |entity, cx| update(entity, window, cx))
494 })
495 .context("entity has no current window")
496 }
497
498 fn replace_root_view<V>(
499 &mut self,
500 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
501 ) -> Result<Entity<V>>
502 where
503 V: 'static + Render,
504 {
505 self.app.update_window(self.window, |_, window, cx| {
506 window.replace_root(cx, build_view)
507 })
508 }
509
510 fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
511 where
512 V: Focusable,
513 {
514 self.app.update_window(self.window, |_, window, cx| {
515 view.read(cx).focus_handle(cx).focus(window, cx);
516 })
517 }
518}