async_context.rs

 1use crate::{AnyWindowHandle, AppContext, Context, Handle, ModelContext, Result, WindowContext};
 2use anyhow::anyhow;
 3use parking_lot::Mutex;
 4use std::sync::Weak;
 5
 6#[derive(Clone)]
 7pub struct AsyncContext(pub(crate) Weak<Mutex<AppContext>>);
 8
 9impl Context for AsyncContext {
10    type EntityContext<'a, 'b, T: 'static + Send + Sync> = ModelContext<'a, T>;
11    type Result<T> = Result<T>;
12
13    fn entity<T: Send + Sync + 'static>(
14        &mut self,
15        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
16    ) -> Result<Handle<T>> {
17        let app = self
18            .0
19            .upgrade()
20            .ok_or_else(|| anyhow!("app was released"))?;
21        let mut lock = app.lock();
22        Ok(lock.entity(build_entity))
23    }
24
25    fn update_entity<T: Send + Sync + 'static, R>(
26        &mut self,
27        handle: &Handle<T>,
28        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
29    ) -> Result<R> {
30        let app = self
31            .0
32            .upgrade()
33            .ok_or_else(|| anyhow!("app was released"))?;
34        let mut lock = app.lock();
35        Ok(lock.update_entity(handle, update))
36    }
37}
38
39impl AsyncContext {
40    pub fn update_window<T>(
41        &self,
42        handle: AnyWindowHandle,
43        update: impl FnOnce(&mut WindowContext) -> T + Send + Sync,
44    ) -> Result<T> {
45        let app = self
46            .0
47            .upgrade()
48            .ok_or_else(|| anyhow!("app was released"))?;
49        let mut app_context = app.lock();
50        app_context.update_window(handle.id, update)
51    }
52}