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 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 })
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
263impl sum_tree::BackgroundSpawn for BackgroundExecutor {
264 type Task<R>
265 = Task<R>
266 where
267 R: Send + Sync;
268 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Self::Task<R>
269 where
270 R: Send + Sync + 'static,
271 {
272 self.spawn(future)
273 }
274}
275
276/// A cloneable, owned handle to the application context,
277/// composed with the window associated with the current task.
278#[derive(Clone, Deref, DerefMut)]
279pub struct AsyncWindowContext {
280 #[deref]
281 #[deref_mut]
282 app: AsyncApp,
283 window: AnyWindowHandle,
284}
285
286impl AsyncWindowContext {
287 pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
288 Self { app, window }
289 }
290
291 /// Get the handle of the window this context is associated with.
292 pub fn window_handle(&self) -> AnyWindowHandle {
293 self.window
294 }
295
296 /// A convenience method for [`App::update_window`].
297 pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
298 self.app
299 .update_window(self.window, |_, window, cx| update(window, cx))
300 }
301
302 /// A convenience method for [`App::update_window`].
303 pub fn update_root<R>(
304 &mut self,
305 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
306 ) -> Result<R> {
307 self.app.update_window(self.window, update)
308 }
309
310 /// A convenience method for [`Window::on_next_frame`].
311 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
312 self.window
313 .update(self, |_, window, _| window.on_next_frame(f))
314 .ok();
315 }
316
317 /// A convenience method for [`App::global`].
318 pub fn read_global<G: Global, R>(
319 &mut self,
320 read: impl FnOnce(&G, &Window, &App) -> R,
321 ) -> Result<R> {
322 self.window
323 .update(self, |_, window, cx| read(cx.global(), window, cx))
324 }
325
326 /// A convenience method for [`App::update_global`](BorrowAppContext::update_global).
327 /// for updating the global state of the specified type.
328 pub fn update_global<G, R>(
329 &mut self,
330 update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
331 ) -> Result<R>
332 where
333 G: Global,
334 {
335 self.window.update(self, |_, window, cx| {
336 cx.update_global(|global, cx| update(global, window, cx))
337 })
338 }
339
340 /// Schedule a future to be executed on the main thread. This is used for collecting
341 /// the results of background tasks and updating the UI.
342 #[track_caller]
343 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
344 where
345 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
346 R: 'static,
347 {
348 let mut cx = self.clone();
349 self.foreground_executor
350 .spawn(async move { f(&mut cx).await })
351 }
352
353 /// Present a platform dialog.
354 /// The provided message will be presented, along with buttons for each answer.
355 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
356 pub fn prompt<T>(
357 &mut self,
358 level: PromptLevel,
359 message: &str,
360 detail: Option<&str>,
361 answers: &[T],
362 ) -> oneshot::Receiver<usize>
363 where
364 T: Clone + Into<PromptButton>,
365 {
366 self.window
367 .update(self, |_, window, cx| {
368 window.prompt(level, message, detail, answers, cx)
369 })
370 .unwrap_or_else(|_| oneshot::channel().1)
371 }
372}
373
374impl AppContext for AsyncWindowContext {
375 type Result<T> = Result<T>;
376
377 fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Result<Entity<T>>
378 where
379 T: 'static,
380 {
381 self.window.update(self, |_, _, cx| cx.new(build_entity))
382 }
383
384 fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
385 self.window.update(self, |_, _, cx| cx.reserve_entity())
386 }
387
388 fn insert_entity<T: 'static>(
389 &mut self,
390 reservation: Reservation<T>,
391 build_entity: impl FnOnce(&mut Context<T>) -> T,
392 ) -> Self::Result<Entity<T>> {
393 self.window
394 .update(self, |_, _, cx| cx.insert_entity(reservation, build_entity))
395 }
396
397 fn update_entity<T: 'static, R>(
398 &mut self,
399 handle: &Entity<T>,
400 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
401 ) -> Result<R> {
402 self.window
403 .update(self, |_, _, cx| cx.update_entity(handle, update))
404 }
405
406 fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
407 where
408 T: 'static,
409 {
410 Err(anyhow!(
411 "Cannot use as_mut() from an async context, call `update`"
412 ))
413 }
414
415 fn read_entity<T, R>(
416 &self,
417 handle: &Entity<T>,
418 read: impl FnOnce(&T, &App) -> R,
419 ) -> Self::Result<R>
420 where
421 T: 'static,
422 {
423 self.app.read_entity(handle, read)
424 }
425
426 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
427 where
428 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
429 {
430 self.app.update_window(window, update)
431 }
432
433 fn read_window<T, R>(
434 &self,
435 window: &WindowHandle<T>,
436 read: impl FnOnce(Entity<T>, &App) -> R,
437 ) -> Result<R>
438 where
439 T: 'static,
440 {
441 self.app.read_window(window, read)
442 }
443
444 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
445 where
446 R: Send + 'static,
447 {
448 self.app.background_executor.spawn(future)
449 }
450
451 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
452 where
453 G: Global,
454 {
455 self.app.read_global(callback)
456 }
457}
458
459impl VisualContext for AsyncWindowContext {
460 fn window_handle(&self) -> AnyWindowHandle {
461 self.window
462 }
463
464 fn new_window_entity<T: 'static>(
465 &mut self,
466 build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
467 ) -> Self::Result<Entity<T>> {
468 self.window
469 .update(self, |_, window, cx| cx.new(|cx| build_entity(window, cx)))
470 }
471
472 fn update_window_entity<T: 'static, R>(
473 &mut self,
474 view: &Entity<T>,
475 update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
476 ) -> Self::Result<R> {
477 self.window.update(self, |_, window, cx| {
478 view.update(cx, |entity, cx| update(entity, window, cx))
479 })
480 }
481
482 fn replace_root_view<V>(
483 &mut self,
484 build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
485 ) -> Self::Result<Entity<V>>
486 where
487 V: 'static + Render,
488 {
489 self.window
490 .update(self, |_, window, cx| window.replace_root(cx, build_view))
491 }
492
493 fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
494 where
495 V: Focusable,
496 {
497 self.window.update(self, |_, window, cx| {
498 view.read(cx).focus_handle(cx).focus(window);
499 })
500 }
501}