async_context.rs

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