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