async_context.rs

  1use crate::{
  2    AnyView, AnyWindowHandle, App, AppCell, AppContext, AppLivenessToken, BackgroundExecutor,
  3    BorrowAppContext, Entity, EventEmitter, Focusable, ForegroundExecutor, Global, PromptButton,
  4    PromptLevel, Render, Reservation, Result, Subscription, Task, VisualContext, Window,
  5    WindowHandle,
  6};
  7use anyhow::{Context as _, anyhow};
  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/// Internally, this holds a weak reference to an `App`, so its methods are fallible to protect against cases where the [App] is dropped.
 17#[derive(Clone)]
 18pub struct AsyncApp {
 19    pub(crate) app: Weak<AppCell>,
 20    pub(crate) liveness_token: AppLivenessToken,
 21    pub(crate) background_executor: BackgroundExecutor,
 22    pub(crate) foreground_executor: ForegroundExecutor,
 23}
 24
 25impl AppContext for AsyncApp {
 26    type Result<T> = Result<T>;
 27
 28    fn new<T: 'static>(
 29        &mut self,
 30        build_entity: impl FnOnce(&mut Context<T>) -> T,
 31    ) -> Self::Result<Entity<T>> {
 32        let app = self.app.upgrade().context("app was released")?;
 33        let mut app = app.borrow_mut();
 34        Ok(app.new(build_entity))
 35    }
 36
 37    fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
 38        let app = self.app.upgrade().context("app was released")?;
 39        let mut app = app.borrow_mut();
 40        Ok(app.reserve_entity())
 41    }
 42
 43    fn insert_entity<T: 'static>(
 44        &mut self,
 45        reservation: Reservation<T>,
 46        build_entity: impl FnOnce(&mut Context<T>) -> T,
 47    ) -> Result<Entity<T>> {
 48        let app = self.app.upgrade().context("app was released")?;
 49        let mut app = app.borrow_mut();
 50        Ok(app.insert_entity(reservation, build_entity))
 51    }
 52
 53    fn update_entity<T: 'static, R>(
 54        &mut self,
 55        handle: &Entity<T>,
 56        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
 57    ) -> Self::Result<R> {
 58        let app = self.app.upgrade().context("app was released")?;
 59        let mut app = app.borrow_mut();
 60        Ok(app.update_entity(handle, update))
 61    }
 62
 63    fn as_mut<'a, T>(&'a mut self, _handle: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
 64    where
 65        T: 'static,
 66    {
 67        Err(anyhow!(
 68            "Cannot as_mut with an async context. Try calling update() first"
 69        ))
 70    }
 71
 72    fn read_entity<T, R>(
 73        &self,
 74        handle: &Entity<T>,
 75        callback: impl FnOnce(&T, &App) -> R,
 76    ) -> Self::Result<R>
 77    where
 78        T: 'static,
 79    {
 80        let app = self.app.upgrade().context("app was released")?;
 81        let lock = app.borrow();
 82        Ok(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) -> Self::Result<R>
115    where
116        G: Global,
117    {
118        let app = self.app.upgrade().context("app was released")?;
119        let mut lock = app.borrow_mut();
120        Ok(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) -> Result<()> {
127        let app = self.app.upgrade().context("app was released")?;
128        let mut lock = app.borrow_mut();
129        lock.refresh_windows();
130        Ok(())
131    }
132
133    /// Get an executor which can be used to spawn futures in the background.
134    pub fn background_executor(&self) -> &BackgroundExecutor {
135        &self.background_executor
136    }
137
138    /// Get an executor which can be used to spawn futures in the foreground.
139    pub fn foreground_executor(&self) -> &ForegroundExecutor {
140        &self.foreground_executor
141    }
142
143    /// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
144    pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R> {
145        let app = self.app.upgrade().context("app was released")?;
146        let mut lock = app.borrow_mut();
147        Ok(lock.update(f))
148    }
149
150    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
151    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
152    pub fn subscribe<T, Event>(
153        &mut self,
154        entity: &Entity<T>,
155        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
156    ) -> Result<Subscription>
157    where
158        T: 'static + EventEmitter<Event>,
159        Event: 'static,
160    {
161        let app = self.app.upgrade().context("app was released")?;
162        let mut lock = app.borrow_mut();
163        let subscription = lock.subscribe(entity, on_event);
164        Ok(subscription)
165    }
166
167    /// Open a window with the given options based on the root view returned by the given function.
168    pub fn open_window<V>(
169        &self,
170        options: crate::WindowOptions,
171        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
172    ) -> Result<WindowHandle<V>>
173    where
174        V: 'static + Render,
175    {
176        let app = self.app.upgrade().context("app was released")?;
177        let mut lock = app.borrow_mut();
178        lock.open_window(options, build_root_view)
179    }
180
181    /// Schedule a future to be polled in the foreground.
182    #[track_caller]
183    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
184    where
185        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
186        R: 'static,
187    {
188        let mut cx = self.clone();
189        self.foreground_executor
190            .spawn_context(self.liveness_token.clone(), async move { f(&mut cx).await })
191    }
192
193    /// Determine whether global state of the specified type has been assigned.
194    /// Returns an error if the `App` has been dropped.
195    pub fn has_global<G: Global>(&self) -> Result<bool> {
196        let app = self.app.upgrade().context("app was released")?;
197        let app = app.borrow_mut();
198        Ok(app.has_global::<G>())
199    }
200
201    /// Reads the global state of the specified type, passing it to the given callback.
202    ///
203    /// Panics if no global state of the specified type has been assigned.
204    /// Returns an error if the `App` has been dropped.
205    pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
206        let app = self.app.upgrade().context("app was released")?;
207        let app = app.borrow_mut();
208        Ok(read(app.global(), &app))
209    }
210
211    /// Reads the global state of the specified type, passing it to the given callback.
212    ///
213    /// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
214    /// if no state of the specified type has been assigned.
215    ///
216    /// Returns an error if no state of the specified type has been assigned the `App` has been dropped.
217    pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
218        let app = self.app.upgrade()?;
219        let app = app.borrow_mut();
220        Some(read(app.try_global()?, &app))
221    }
222
223    /// Reads the global state of the specified type, passing it to the given callback.
224    /// A default value is assigned if a global of this type has not yet been assigned.
225    ///
226    /// # Errors
227    /// If the app has ben dropped this returns an error.
228    pub fn try_read_default_global<G: Global + Default, R>(
229        &self,
230        read: impl FnOnce(&G, &App) -> R,
231    ) -> Result<R> {
232        let app = self.app.upgrade().context("app was released")?;
233        let mut app = app.borrow_mut();
234        app.update(|cx| {
235            cx.default_global::<G>();
236        });
237        Ok(read(app.try_global().context("app was released")?, &app))
238    }
239
240    /// A convenience method for [`App::update_global`](BorrowAppContext::update_global)
241    /// for updating the global state of the specified type.
242    pub fn update_global<G: Global, R>(
243        &self,
244        update: impl FnOnce(&mut G, &mut App) -> R,
245    ) -> Result<R> {
246        let app = self.app.upgrade().context("app was released")?;
247        let mut app = app.borrow_mut();
248        Ok(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    ) -> util::Deferred<impl FnOnce() + use<T, Callback>> {
257        let entity = entity.clone();
258        let mut cx = self.clone();
259        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_context(
340                self.app.liveness_token.clone(),
341                async move { f(&mut cx).await },
342            )
343    }
344
345    /// Present a platform dialog.
346    /// The provided message will be presented, along with buttons for each answer.
347    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
348    pub fn prompt<T>(
349        &mut self,
350        level: PromptLevel,
351        message: &str,
352        detail: Option<&str>,
353        answers: &[T],
354    ) -> oneshot::Receiver<usize>
355    where
356        T: Clone + Into<PromptButton>,
357    {
358        self.app
359            .update_window(self.window, |_, window, cx| {
360                window.prompt(level, message, detail, answers, cx)
361            })
362            .unwrap_or_else(|_| oneshot::channel().1)
363    }
364}
365
366impl AppContext for AsyncWindowContext {
367    type Result<T> = Result<T>;
368
369    fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Result<Entity<T>>
370    where
371        T: 'static,
372    {
373        self.app
374            .update_window(self.window, |_, _, cx| cx.new(build_entity))
375    }
376
377    fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
378        self.app
379            .update_window(self.window, |_, _, cx| cx.reserve_entity())
380    }
381
382    fn insert_entity<T: 'static>(
383        &mut self,
384        reservation: Reservation<T>,
385        build_entity: impl FnOnce(&mut Context<T>) -> T,
386    ) -> Self::Result<Entity<T>> {
387        self.app.update_window(self.window, |_, _, cx| {
388            cx.insert_entity(reservation, build_entity)
389        })
390    }
391
392    fn update_entity<T: 'static, R>(
393        &mut self,
394        handle: &Entity<T>,
395        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
396    ) -> Result<R> {
397        self.app
398            .update_window(self.window, |_, _, cx| cx.update_entity(handle, update))
399    }
400
401    fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
402    where
403        T: 'static,
404    {
405        Err(anyhow!(
406            "Cannot use as_mut() from an async context, call `update`"
407        ))
408    }
409
410    fn read_entity<T, R>(
411        &self,
412        handle: &Entity<T>,
413        read: impl FnOnce(&T, &App) -> R,
414    ) -> Self::Result<R>
415    where
416        T: 'static,
417    {
418        self.app.read_entity(handle, read)
419    }
420
421    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
422    where
423        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
424    {
425        self.app.update_window(window, update)
426    }
427
428    fn read_window<T, R>(
429        &self,
430        window: &WindowHandle<T>,
431        read: impl FnOnce(Entity<T>, &App) -> R,
432    ) -> Result<R>
433    where
434        T: 'static,
435    {
436        self.app.read_window(window, read)
437    }
438
439    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
440    where
441        R: Send + 'static,
442    {
443        self.app.background_executor.spawn(future)
444    }
445
446    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
447    where
448        G: Global,
449    {
450        self.app.read_global(callback)
451    }
452}
453
454impl VisualContext for AsyncWindowContext {
455    fn window_handle(&self) -> AnyWindowHandle {
456        self.window
457    }
458
459    fn new_window_entity<T: 'static>(
460        &mut self,
461        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
462    ) -> Self::Result<Entity<T>> {
463        self.app.update_window(self.window, |_, window, cx| {
464            cx.new(|cx| build_entity(window, cx))
465        })
466    }
467
468    fn update_window_entity<T: 'static, R>(
469        &mut self,
470        view: &Entity<T>,
471        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
472    ) -> Self::Result<R> {
473        self.app.update_window(self.window, |_, window, cx| {
474            view.update(cx, |entity, cx| update(entity, window, cx))
475        })
476    }
477
478    fn replace_root_view<V>(
479        &mut self,
480        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
481    ) -> Self::Result<Entity<V>>
482    where
483        V: 'static + Render,
484    {
485        self.app.update_window(self.window, |_, window, cx| {
486            window.replace_root(cx, build_view)
487        })
488    }
489
490    fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
491    where
492        V: Focusable,
493    {
494        self.app.update_window(self.window, |_, window, cx| {
495            view.read(cx).focus_handle(cx).focus(window, cx);
496        })
497    }
498}