async_context.rs

  1use crate::{
  2    AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
  3    Entity, Focusable, ForegroundExecutor, Global, PromptLevel, Render, Reservation, Result, Task,
  4    VisualContext, Window, WindowHandle,
  5};
  6use anyhow::{anyhow, Context as _};
  7use derive_more::{Deref, DerefMut};
  8use futures::channel::oneshot;
  9use std::{future::Future, rc::Weak};
 10
 11use super::Context;
 12
 13/// An async-friendly version of [AppContext] with a static lifetime so it can be held across `await` points in async code.
 14/// You're provided with an instance when calling [AppContext::spawn], and you can also create one with [AppContext::to_async].
 15/// Internally, this holds a weak reference to an `AppContext`, so its methods are fallible to protect against cases where the [AppContext] 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_model: impl FnOnce(&mut Context<'_, T>) -> T,
 29    ) -> Self::Result<Entity<T>> {
 30        let app = self
 31            .app
 32            .upgrade()
 33            .ok_or_else(|| anyhow!("app was released"))?;
 34        let mut app = app.borrow_mut();
 35        Ok(app.new(build_model))
 36    }
 37
 38    fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
 39        let app = self
 40            .app
 41            .upgrade()
 42            .ok_or_else(|| anyhow!("app was released"))?;
 43        let mut app = app.borrow_mut();
 44        Ok(app.reserve_entity())
 45    }
 46
 47    fn insert_entity<T: 'static>(
 48        &mut self,
 49        reservation: Reservation<T>,
 50        build_model: impl FnOnce(&mut Context<'_, T>) -> T,
 51    ) -> Result<Entity<T>> {
 52        let app = self
 53            .app
 54            .upgrade()
 55            .ok_or_else(|| anyhow!("app was released"))?;
 56        let mut app = app.borrow_mut();
 57        Ok(app.insert_entity(reservation, build_model))
 58    }
 59
 60    fn update_entity<T: 'static, R>(
 61        &mut self,
 62        handle: &Entity<T>,
 63        update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
 64    ) -> Self::Result<R> {
 65        let app = self
 66            .app
 67            .upgrade()
 68            .ok_or_else(|| anyhow!("app was released"))?;
 69        let mut app = app.borrow_mut();
 70        Ok(app.update_entity(handle, update))
 71    }
 72
 73    fn read_entity<T, R>(
 74        &self,
 75        handle: &Entity<T>,
 76        callback: impl FnOnce(&T, &App) -> R,
 77    ) -> Self::Result<R>
 78    where
 79        T: 'static,
 80    {
 81        let app = self.app.upgrade().context("app was released")?;
 82        let lock = app.borrow();
 83        Ok(lock.read_entity(handle, callback))
 84    }
 85
 86    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
 87    where
 88        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
 89    {
 90        let app = self.app.upgrade().context("app was released")?;
 91        let mut lock = app.borrow_mut();
 92        lock.update_window(window, f)
 93    }
 94
 95    fn read_window<T, R>(
 96        &self,
 97        window: &WindowHandle<T>,
 98        read: impl FnOnce(Entity<T>, &App) -> R,
 99    ) -> Result<R>
100    where
101        T: 'static,
102    {
103        let app = self.app.upgrade().context("app was released")?;
104        let lock = app.borrow();
105        lock.read_window(window, read)
106    }
107}
108
109impl AsyncApp {
110    /// Schedules all windows in the application to be redrawn.
111    pub fn refresh(&self) -> Result<()> {
112        let app = self
113            .app
114            .upgrade()
115            .ok_or_else(|| anyhow!("app was released"))?;
116        let mut lock = app.borrow_mut();
117        lock.refresh_windows();
118        Ok(())
119    }
120
121    /// Get an executor which can be used to spawn futures in the background.
122    pub fn background_executor(&self) -> &BackgroundExecutor {
123        &self.background_executor
124    }
125
126    /// Get an executor which can be used to spawn futures in the foreground.
127    pub fn foreground_executor(&self) -> &ForegroundExecutor {
128        &self.foreground_executor
129    }
130
131    /// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
132    pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R> {
133        let app = self
134            .app
135            .upgrade()
136            .ok_or_else(|| anyhow!("app was released"))?;
137        let mut lock = app.borrow_mut();
138        Ok(f(&mut lock))
139    }
140
141    /// Open a window with the given options based on the root view returned by the given function.
142    pub fn open_window<V>(
143        &self,
144        options: crate::WindowOptions,
145        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
146    ) -> Result<WindowHandle<V>>
147    where
148        V: 'static + Render,
149    {
150        let app = self
151            .app
152            .upgrade()
153            .ok_or_else(|| anyhow!("app was released"))?;
154        let mut lock = app.borrow_mut();
155        lock.open_window(options, build_root_view)
156    }
157
158    /// Schedule a future to be polled in the background.
159    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R>
160    where
161        Fut: Future<Output = R> + 'static,
162        R: 'static,
163    {
164        self.foreground_executor.spawn(f(self.clone()))
165    }
166
167    /// Determine whether global state of the specified type has been assigned.
168    /// Returns an error if the `AppContext` has been dropped.
169    pub fn has_global<G: Global>(&self) -> Result<bool> {
170        let app = self
171            .app
172            .upgrade()
173            .ok_or_else(|| anyhow!("app was released"))?;
174        let app = app.borrow_mut();
175        Ok(app.has_global::<G>())
176    }
177
178    /// Reads the global state of the specified type, passing it to the given callback.
179    ///
180    /// Panics if no global state of the specified type has been assigned.
181    /// Returns an error if the `AppContext` has been dropped.
182    pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
183        let app = self
184            .app
185            .upgrade()
186            .ok_or_else(|| anyhow!("app was released"))?;
187        let app = app.borrow_mut();
188        Ok(read(app.global(), &app))
189    }
190
191    /// Reads the global state of the specified type, passing it to the given callback.
192    ///
193    /// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
194    /// if no state of the specified type has been assigned.
195    ///
196    /// Returns an error if no state of the specified type has been assigned the `AppContext` has been dropped.
197    pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
198        let app = self.app.upgrade()?;
199        let app = app.borrow_mut();
200        Some(read(app.try_global()?, &app))
201    }
202
203    /// A convenience method for [AppContext::update_global]
204    /// for updating the global state of the specified type.
205    pub fn update_global<G: Global, R>(
206        &self,
207        update: impl FnOnce(&mut G, &mut App) -> R,
208    ) -> Result<R> {
209        let app = self
210            .app
211            .upgrade()
212            .ok_or_else(|| anyhow!("app was released"))?;
213        let mut app = app.borrow_mut();
214        Ok(app.update(|cx| cx.update_global(update)))
215    }
216}
217
218/// A cloneable, owned handle to the application context,
219/// composed with the window associated with the current task.
220#[derive(Clone, Deref, DerefMut)]
221pub struct AsyncWindowContext {
222    #[deref]
223    #[deref_mut]
224    app: AsyncApp,
225    window: AnyWindowHandle,
226}
227
228impl AsyncWindowContext {
229    pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
230        Self { app, window }
231    }
232
233    /// Get the handle of the window this context is associated with.
234    pub fn window_handle(&self) -> AnyWindowHandle {
235        self.window
236    }
237
238    /// A convenience method for [`AppContext::update_window`].
239    pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
240        self.app
241            .update_window(self.window, |_, window, cx| update(window, cx))
242    }
243
244    /// A convenience method for [`AppContext::update_window`].
245    pub fn update_root<R>(
246        &mut self,
247        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
248    ) -> Result<R> {
249        self.app.update_window(self.window, update)
250    }
251
252    /// A convenience method for [`Window::on_next_frame`].
253    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
254        self.window
255            .update(self, |_, window, _| window.on_next_frame(f))
256            .ok();
257    }
258
259    /// A convenience method for [`AppContext::global`].
260    pub fn read_global<G: Global, R>(
261        &mut self,
262        read: impl FnOnce(&G, &Window, &App) -> R,
263    ) -> Result<R> {
264        self.window
265            .update(self, |_, window, cx| read(cx.global(), window, cx))
266    }
267
268    /// A convenience method for [`AppContext::update_global`].
269    /// for updating the global state of the specified type.
270    pub fn update_global<G, R>(
271        &mut self,
272        update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
273    ) -> Result<R>
274    where
275        G: Global,
276    {
277        self.window.update(self, |_, window, cx| {
278            cx.update_global(|global, cx| update(global, window, cx))
279        })
280    }
281
282    /// Schedule a future to be executed on the main thread. This is used for collecting
283    /// the results of background tasks and updating the UI.
284    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
285    where
286        Fut: Future<Output = R> + 'static,
287        R: 'static,
288    {
289        self.foreground_executor.spawn(f(self.clone()))
290    }
291
292    /// Present a platform dialog.
293    /// The provided message will be presented, along with buttons for each answer.
294    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
295    pub fn prompt(
296        &mut self,
297        level: PromptLevel,
298        message: &str,
299        detail: Option<&str>,
300        answers: &[&str],
301    ) -> oneshot::Receiver<usize> {
302        self.window
303            .update(self, |_, window, cx| {
304                window.prompt(level, message, detail, answers, cx)
305            })
306            .unwrap_or_else(|_| oneshot::channel().1)
307    }
308}
309
310impl AppContext for AsyncWindowContext {
311    type Result<T> = Result<T>;
312
313    fn new<T>(&mut self, build_model: impl FnOnce(&mut Context<'_, T>) -> T) -> Result<Entity<T>>
314    where
315        T: 'static,
316    {
317        self.window.update(self, |_, _, cx| cx.new(build_model))
318    }
319
320    fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
321        self.window.update(self, |_, _, cx| cx.reserve_entity())
322    }
323
324    fn insert_entity<T: 'static>(
325        &mut self,
326        reservation: Reservation<T>,
327        build_model: impl FnOnce(&mut Context<'_, T>) -> T,
328    ) -> Self::Result<Entity<T>> {
329        self.window
330            .update(self, |_, _, cx| cx.insert_entity(reservation, build_model))
331    }
332
333    fn update_entity<T: 'static, R>(
334        &mut self,
335        handle: &Entity<T>,
336        update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
337    ) -> Result<R> {
338        self.window
339            .update(self, |_, _, cx| cx.update_entity(handle, update))
340    }
341
342    fn read_entity<T, R>(
343        &self,
344        handle: &Entity<T>,
345        read: impl FnOnce(&T, &App) -> R,
346    ) -> Self::Result<R>
347    where
348        T: 'static,
349    {
350        self.app.read_entity(handle, read)
351    }
352
353    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
354    where
355        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
356    {
357        self.app.update_window(window, update)
358    }
359
360    fn read_window<T, R>(
361        &self,
362        window: &WindowHandle<T>,
363        read: impl FnOnce(Entity<T>, &App) -> R,
364    ) -> Result<R>
365    where
366        T: 'static,
367    {
368        self.app.read_window(window, read)
369    }
370}
371
372impl VisualContext for AsyncWindowContext {
373    fn window_handle(&self) -> AnyWindowHandle {
374        self.window
375    }
376
377    fn new_window_entity<T: 'static>(
378        &mut self,
379        build_model: impl FnOnce(&mut Window, &mut Context<T>) -> T,
380    ) -> Self::Result<Entity<T>> {
381        self.window
382            .update(self, |_, window, cx| cx.new(|cx| build_model(window, cx)))
383    }
384
385    fn update_window_entity<T: 'static, R>(
386        &mut self,
387        view: &Entity<T>,
388        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
389    ) -> Self::Result<R> {
390        self.window.update(self, |_, window, cx| {
391            view.update(cx, |model, cx| update(model, window, cx))
392        })
393    }
394
395    fn replace_root_view<V>(
396        &mut self,
397        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
398    ) -> Self::Result<Entity<V>>
399    where
400        V: 'static + Render,
401    {
402        self.window
403            .update(self, |_, window, cx| window.replace_root(cx, build_view))
404    }
405
406    fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
407    where
408        V: Focusable,
409    {
410        self.window.update(self, |_, window, cx| {
411            view.read(cx).focus_handle(cx).clone().focus(window);
412        })
413    }
414}