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