async_context.rs

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