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