1use crate::{
2 AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
3 Entity, EventEmitter, Focusable, ForegroundExecutor, Global, GpuiBorrow, PromptButton,
4 PromptLevel, Render, Reservation, Result, Subscription, Task, VisualContext, Window,
5 WindowHandle,
6};
7use anyhow::Context as _;
8use derive_more::{Deref, DerefMut};
9use futures::channel::oneshot;
10use smol::future::FutureExt;
11use std::{future::Future, rc::Weak};
12
13use super::{Context, WeakEntity};
14
15/// An async-friendly version of [App] with a static lifetime so it can be held across `await` points in async code.
16/// You're provided with an instance when calling [App::spawn], and you can also create one with [App::to_async].
17///
18/// Internally, this holds a weak reference to an `App`. Methods will panic if the app has been dropped,
19/// but this should not happen in practice when using foreground tasks spawned via `cx.spawn()`,
20/// as the executor checks if the app is alive before running each task.
21#[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 lock.update_window(window, f)
92 }
93
94 fn read_window<T, R>(
95 &self,
96 window: &WindowHandle<T>,
97 read: impl FnOnce(Entity<T>, &App) -> R,
98 ) -> Result<R>
99 where
100 T: 'static,
101 {
102 let app = self.app.upgrade().context("app was released")?;
103 let lock = app.borrow();
104 lock.read_window(window, read)
105 }
106
107 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
108 where
109 R: Send + 'static,
110 {
111 self.background_executor.spawn(future)
112 }
113
114 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
115 where
116 G: Global,
117 {
118 let app = self.app();
119 let mut lock = app.borrow_mut();
120 lock.update(|this| this.read_global(callback))
121 }
122}
123
124impl AsyncApp {
125 /// Schedules all windows in the application to be redrawn.
126 pub fn refresh(&self) {
127 let app = self.app();
128 let mut lock = app.borrow_mut();
129 lock.refresh_windows();
130 }
131
132 /// Get an executor which can be used to spawn futures in the background.
133 pub fn background_executor(&self) -> &BackgroundExecutor {
134 &self.background_executor
135 }
136
137 /// Get an executor which can be used to spawn futures in the foreground.
138 pub fn foreground_executor(&self) -> &ForegroundExecutor {
139 &self.foreground_executor
140 }
141
142 /// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
143 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
144 let app = self.app();
145 let mut lock = app.borrow_mut();
146 lock.update(f)
147 }
148
149 /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
150 /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
151 pub fn subscribe<T, Event>(
152 &mut self,
153 entity: &Entity<T>,
154 on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
155 ) -> Subscription
156 where
157 T: 'static + EventEmitter<Event>,
158 Event: 'static,
159 {
160 let app = self.app();
161 let mut lock = app.borrow_mut();
162 lock.subscribe(entity, on_event)
163 }
164
165 /// Open a window with the given options based on the root view returned by the given function.
166 pub fn open_window<V>(
167 &self,
168 options: crate::WindowOptions,
169 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
170 ) -> Result<WindowHandle<V>>
171 where
172 V: 'static + Render,
173 {
174 let app = self.app();
175 let mut lock = app.borrow_mut();
176 lock.open_window(options, build_root_view)
177 }
178
179 /// Schedule a future to be polled in the foreground.
180 #[track_caller]
181 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
182 where
183 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
184 R: 'static,
185 {
186 let mut cx = self.clone();
187 self.foreground_executor
188 .spawn(async move { f(&mut cx).await }.boxed_local())
189 }
190
191 /// Determine whether global state of the specified type has been assigned.
192 pub fn has_global<G: Global>(&self) -> bool {
193 let app = self.app();
194 let app = app.borrow_mut();
195 app.has_global::<G>()
196 }
197
198 /// Reads the global state of the specified type, passing it to the given callback.
199 ///
200 /// Panics if no global state of the specified type has been assigned.
201 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
202 let app = self.app();
203 let app = app.borrow_mut();
204 read(app.global(), &app)
205 }
206
207 /// Reads the global state of the specified type, passing it to the given callback.
208 ///
209 /// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
210 pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
211 let app = self.app();
212 let app = app.borrow_mut();
213 Some(read(app.try_global()?, &app))
214 }
215
216 /// Reads the global state of the specified type, passing it to the given callback.
217 /// A default value is assigned if a global of this type has not yet been assigned.
218 pub fn read_default_global<G: Global + Default, R>(
219 &self,
220 read: impl FnOnce(&G, &App) -> R,
221 ) -> R {
222 let app = self.app();
223 let mut app = app.borrow_mut();
224 app.update(|cx| {
225 cx.default_global::<G>();
226 });
227 read(app.global(), &app)
228 }
229
230 /// A convenience method for [`App::update_global`](BorrowAppContext::update_global)
231 /// for updating the global state of the specified type.
232 pub fn update_global<G: Global, R>(&self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
233 let app = self.app();
234 let mut app = app.borrow_mut();
235 app.update(|cx| cx.update_global(update))
236 }
237
238 /// Run something using this entity and cx, when the returned struct is dropped
239 pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
240 &self,
241 entity: &WeakEntity<T>,
242 f: Callback,
243 ) -> util::Deferred<impl FnOnce() + use<T, Callback>> {
244 let entity = entity.clone();
245 let mut cx = self.clone();
246 util::defer(move || {
247 entity.update(&mut cx, f).ok();
248 })
249 }
250}
251
252/// A cloneable, owned handle to the application context,
253/// composed with the window associated with the current task.
254#[derive(Clone, Deref, DerefMut)]
255pub struct AsyncWindowContext {
256 #[deref]
257 #[deref_mut]
258 app: AsyncApp,
259 window: AnyWindowHandle,
260}
261
262impl AsyncWindowContext {
263 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
264 Self { app, window }
265 }
266
267 /// Get the handle of the window this context is associated with.
268 pub fn window_handle(&self) -> AnyWindowHandle {
269 self.window
270 }
271
272 /// A convenience method for [`App::update_window`].
273 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
274 self.app
275 .update_window(self.window, |_, window, cx| update(window, cx))
276 }
277
278 /// A convenience method for [`App::update_window`].
279 pub fn update_root<R>(
280 &mut self,
281 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
282 ) -> Result<R> {
283 self.app.update_window(self.window, update)
284 }
285
286 /// A convenience method for [`Window::on_next_frame`].
287 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
288 self.app
289 .update_window(self.window, |_, window, _| window.on_next_frame(f))
290 .ok();
291 }
292
293 /// A convenience method for [`App::global`].
294 pub fn read_global<G: Global, R>(
295 &mut self,
296 read: impl FnOnce(&G, &Window, &App) -> R,
297 ) -> Result<R> {
298 self.app
299 .update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
300 }
301
302 /// A convenience method for [`App::update_global`](BorrowAppContext::update_global).
303 /// for updating the global state of the specified type.
304 pub fn update_global<G, R>(
305 &mut self,
306 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
307 ) -> Result<R>
308 where
309 G: Global,
310 {
311 self.app.update_window(self.window, |_, window, cx| {
312 cx.update_global(|global, cx| update(global, window, cx))
313 })
314 }
315
316 /// Schedule a future to be executed on the main thread. This is used for collecting
317 /// the results of background tasks and updating the UI.
318 #[track_caller]
319 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
320 where
321 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
322 R: 'static,
323 {
324 let mut cx = self.clone();
325 self.foreground_executor
326 .spawn(async move { f(&mut cx).await }.boxed_local())
327 }
328
329 /// Present a platform dialog.
330 /// The provided message will be presented, along with buttons for each answer.
331 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
332 pub fn prompt<T>(
333 &mut self,
334 level: PromptLevel,
335 message: &str,
336 detail: Option<&str>,
337 answers: &[T],
338 ) -> oneshot::Receiver<usize>
339 where
340 T: Clone + Into<PromptButton>,
341 {
342 self.app
343 .update_window(self.window, |_, window, cx| {
344 window.prompt(level, message, detail, answers, cx)
345 })
346 .unwrap_or_else(|_| oneshot::channel().1)
347 }
348}
349
350impl AppContext for AsyncWindowContext {
351 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
352 where
353 T: 'static,
354 {
355 self.app.new(build_entity)
356 }
357
358 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
359 self.app.reserve_entity()
360 }
361
362 fn insert_entity<T: 'static>(
363 &mut self,
364 reservation: Reservation<T>,
365 build_entity: impl FnOnce(&mut Context<T>) -> T,
366 ) -> Entity<T> {
367 self.app.insert_entity(reservation, build_entity)
368 }
369
370 fn update_entity<T: 'static, R>(
371 &mut self,
372 handle: &Entity<T>,
373 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
374 ) -> R {
375 self.app.update_entity(handle, update)
376 }
377
378 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
379 where
380 T: 'static,
381 {
382 panic!("Cannot use as_mut() from an async context, call `update`")
383 }
384
385 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
386 where
387 T: 'static,
388 {
389 self.app.read_entity(handle, read)
390 }
391
392 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
393 where
394 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
395 {
396 self.app.update_window(window, update)
397 }
398
399 fn read_window<T, R>(
400 &self,
401 window: &WindowHandle<T>,
402 read: impl FnOnce(Entity<T>, &App) -> R,
403 ) -> Result<R>
404 where
405 T: 'static,
406 {
407 self.app.read_window(window, read)
408 }
409
410 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
411 where
412 R: Send + 'static,
413 {
414 self.app.background_executor.spawn(future)
415 }
416
417 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
418 where
419 G: Global,
420 {
421 self.app.read_global(callback)
422 }
423}
424
425impl VisualContext for AsyncWindowContext {
426 type Result<T> = Result<T>;
427
428 fn window_handle(&self) -> AnyWindowHandle {
429 self.window
430 }
431
432 fn new_window_entity<T: 'static>(
433 &mut self,
434 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
435 ) -> Result<Entity<T>> {
436 self.app.update_window(self.window, |_, window, cx| {
437 cx.new(|cx| build_entity(window, cx))
438 })
439 }
440
441 fn update_window_entity<T: 'static, R>(
442 &mut self,
443 view: &Entity<T>,
444 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
445 ) -> Result<R> {
446 self.app.update_window(self.window, |_, window, cx| {
447 view.update(cx, |entity, cx| update(entity, window, cx))
448 })
449 }
450
451 fn replace_root_view<V>(
452 &mut self,
453 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
454 ) -> Result<Entity<V>>
455 where
456 V: 'static + Render,
457 {
458 self.app.update_window(self.window, |_, window, cx| {
459 window.replace_root(cx, build_view)
460 })
461 }
462
463 fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
464 where
465 V: Focusable,
466 {
467 self.app.update_window(self.window, |_, window, cx| {
468 view.read(cx).focus_handle(cx).focus(window, cx);
469 })
470 }
471}