async_context.rs

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