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 _;
  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) liveness_token: std::sync::Weak<()>,
 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        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) -> R
115    where
116        G: Global,
117    {
118        let app = self.app();
119        let mut lock = app.borrow_mut();
120        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) {
127        let app = self.app();
128        let mut lock = app.borrow_mut();
129        lock.refresh_windows();
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) -> R {
144        let app = self.app();
145        let mut lock = app.borrow_mut();
146        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        on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
155    ) -> Subscription
156    where
157        T: 'static + EventEmitter<Event>,
158        Event: 'static,
159    {
160        let app = self.app();
161        let mut lock = app.borrow_mut();
162        lock.subscribe(entity, on_event)
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();
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 foreground.
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_context(self.liveness_token.clone(), async move { f(&mut cx).await })
189    }
190
191    /// Determine whether global state of the specified type has been assigned.
192    pub fn has_global<G: Global>(&self) -> bool {
193        let app = self.app();
194        let app = app.borrow_mut();
195        app.has_global::<G>()
196    }
197
198    /// Reads the global state of the specified type, passing it to the given callback.
199    ///
200    /// Panics if no global state of the specified type has been assigned.
201    pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
202        let app = self.app();
203        let app = app.borrow_mut();
204        read(app.global(), &app)
205    }
206
207    /// Reads the global state of the specified type, passing it to the given callback.
208    ///
209    /// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
210    pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
211        let app = self.app();
212        let app = app.borrow_mut();
213        Some(read(app.try_global()?, &app))
214    }
215
216    /// Reads the global state of the specified type, passing it to the given callback.
217    /// A default value is assigned if a global of this type has not yet been assigned.
218    pub fn read_default_global<G: Global + Default, R>(
219        &self,
220        read: impl FnOnce(&G, &App) -> R,
221    ) -> R {
222        let app = self.app();
223        let mut app = app.borrow_mut();
224        app.update(|cx| {
225            cx.default_global::<G>();
226        });
227        read(app.global(), &app)
228    }
229
230    /// A convenience method for [`App::update_global`](BorrowAppContext::update_global)
231    /// for updating the global state of the specified type.
232    pub fn update_global<G: Global, R>(&self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
233        let app = self.app();
234        let mut app = app.borrow_mut();
235        app.update(|cx| cx.update_global(update))
236    }
237
238    /// Run something using this entity and cx, when the returned struct is dropped
239    pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
240        &self,
241        entity: &WeakEntity<T>,
242        f: Callback,
243    ) -> util::Deferred<impl FnOnce() + use<T, Callback>> {
244        let entity = entity.clone();
245        let mut cx = self.clone();
246        util::defer(move || {
247            entity.update(&mut cx, f).ok();
248        })
249    }
250}
251
252/// A cloneable, owned handle to the application context,
253/// composed with the window associated with the current task.
254#[derive(Clone, Deref, DerefMut)]
255pub struct AsyncWindowContext {
256    #[deref]
257    #[deref_mut]
258    app: AsyncApp,
259    window: AnyWindowHandle,
260}
261
262impl AsyncWindowContext {
263    pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
264        Self { app, window }
265    }
266
267    /// Get the handle of the window this context is associated with.
268    pub fn window_handle(&self) -> AnyWindowHandle {
269        self.window
270    }
271
272    /// A convenience method for [`App::update_window`].
273    pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
274        self.app
275            .update_window(self.window, |_, window, cx| update(window, cx))
276    }
277
278    /// A convenience method for [`App::update_window`].
279    pub fn update_root<R>(
280        &mut self,
281        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
282    ) -> Result<R> {
283        self.app.update_window(self.window, update)
284    }
285
286    /// A convenience method for [`Window::on_next_frame`].
287    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
288        self.app
289            .update_window(self.window, |_, window, _| window.on_next_frame(f))
290            .ok();
291    }
292
293    /// A convenience method for [`App::global`].
294    pub fn read_global<G: Global, R>(
295        &mut self,
296        read: impl FnOnce(&G, &Window, &App) -> R,
297    ) -> Result<R> {
298        self.app
299            .update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
300    }
301
302    /// A convenience method for [`App::update_global`](BorrowAppContext::update_global).
303    /// for updating the global state of the specified type.
304    pub fn update_global<G, R>(
305        &mut self,
306        update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
307    ) -> Result<R>
308    where
309        G: Global,
310    {
311        self.app.update_window(self.window, |_, window, cx| {
312            cx.update_global(|global, cx| update(global, window, cx))
313        })
314    }
315
316    /// Schedule a future to be executed on the main thread. This is used for collecting
317    /// the results of background tasks and updating the UI.
318    #[track_caller]
319    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
320    where
321        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
322        R: 'static,
323    {
324        let mut cx = self.clone();
325        self.foreground_executor
326            .spawn_context(
327                self.app.liveness_token.clone(),
328                async move { f(&mut cx).await },
329            )
330    }
331
332    /// Present a platform dialog.
333    /// The provided message will be presented, along with buttons for each answer.
334    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
335    pub fn prompt<T>(
336        &mut self,
337        level: PromptLevel,
338        message: &str,
339        detail: Option<&str>,
340        answers: &[T],
341    ) -> oneshot::Receiver<usize>
342    where
343        T: Clone + Into<PromptButton>,
344    {
345        self.app
346            .update_window(self.window, |_, window, cx| {
347                window.prompt(level, message, detail, answers, cx)
348            })
349            .unwrap_or_else(|_| oneshot::channel().1)
350    }
351}
352
353impl AppContext for AsyncWindowContext {
354    fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
355    where
356        T: 'static,
357    {
358        self.app.new(build_entity)
359    }
360
361    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
362        self.app.reserve_entity()
363    }
364
365    fn insert_entity<T: 'static>(
366        &mut self,
367        reservation: Reservation<T>,
368        build_entity: impl FnOnce(&mut Context<T>) -> T,
369    ) -> Entity<T> {
370        self.app.insert_entity(reservation, build_entity)
371    }
372
373    fn update_entity<T: 'static, R>(
374        &mut self,
375        handle: &Entity<T>,
376        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
377    ) -> R {
378        self.app.update_entity(handle, update)
379    }
380
381    fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
382    where
383        T: 'static,
384    {
385        panic!("Cannot use as_mut() from an async context, call `update`")
386    }
387
388    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
389    where
390        T: 'static,
391    {
392        self.app.read_entity(handle, read)
393    }
394
395    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
396    where
397        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
398    {
399        self.app.update_window(window, update)
400    }
401
402    fn read_window<T, R>(
403        &self,
404        window: &WindowHandle<T>,
405        read: impl FnOnce(Entity<T>, &App) -> R,
406    ) -> Result<R>
407    where
408        T: 'static,
409    {
410        self.app.read_window(window, read)
411    }
412
413    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
414    where
415        R: Send + 'static,
416    {
417        self.app.background_executor.spawn(future)
418    }
419
420    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
421    where
422        G: Global,
423    {
424        self.app.read_global(callback)
425    }
426}
427
428impl VisualContext for AsyncWindowContext {
429    fn window_handle(&self) -> AnyWindowHandle {
430        self.window
431    }
432
433    fn new_window_entity<T: 'static>(
434        &mut self,
435        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
436    ) -> Result<Entity<T>> {
437        self.app.update_window(self.window, |_, window, cx| {
438            cx.new(|cx| build_entity(window, cx))
439        })
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    ) -> Result<R> {
447        self.app.update_window(self.window, |_, 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    ) -> Result<Entity<V>>
456    where
457        V: 'static + Render,
458    {
459        self.app.update_window(self.window, |_, window, cx| {
460            window.replace_root(cx, build_view)
461        })
462    }
463
464    fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
465    where
466        V: Focusable,
467    {
468        self.app.update_window(self.window, |_, window, cx| {
469            view.read(cx).focus_handle(cx).focus(window, cx);
470        })
471    }
472}