Checkpoint

This commit is contained in:
Nathan Sobo 2023-10-04 15:05:04 -06:00
parent e68b24f839
commit 02d6b91b73
7 changed files with 156 additions and 98 deletions

View file

@ -1,13 +1,15 @@
use crate::{AnyWindowHandle, AppContext, Context, Handle, ModelContext, Result, WindowContext};
use crate::{
AnyWindowHandle, AppContext, Context, Handle, ModelContext, Result, ViewContext, WindowContext,
};
use anyhow::anyhow;
use parking_lot::Mutex;
use std::sync::Weak;
#[derive(Clone)]
pub struct AsyncContext(pub(crate) Weak<Mutex<AppContext>>);
pub struct AsyncAppContext(pub(crate) Weak<Mutex<AppContext>>);
impl Context for AsyncContext {
type EntityContext<'a, 'b, T: 'static + Send + Sync> = ModelContext<'a, T>;
impl Context for AsyncAppContext {
type EntityContext<'a, 'w, T: 'static + Send + Sync> = ModelContext<'a, T>;
type Result<T> = Result<T>;
fn entity<T: Send + Sync + 'static>(
@ -18,7 +20,7 @@ impl Context for AsyncContext {
.0
.upgrade()
.ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock();
let mut lock = app.lock(); // Does not compile without this variable.
Ok(lock.entity(build_entity))
}
@ -31,17 +33,17 @@ impl Context for AsyncContext {
.0
.upgrade()
.ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock();
let mut lock = app.lock(); // Does not compile without this variable.
Ok(lock.update_entity(handle, update))
}
}
impl AsyncContext {
pub fn update_window<T>(
impl AsyncAppContext {
pub fn update_window<R>(
&self,
handle: AnyWindowHandle,
update: impl FnOnce(&mut WindowContext) -> T + Send + Sync,
) -> Result<T> {
update: impl FnOnce(&mut WindowContext) -> R,
) -> Result<R> {
let app = self
.0
.upgrade()
@ -50,3 +52,37 @@ impl AsyncContext {
app_context.update_window(handle.id, update)
}
}
#[derive(Clone)]
pub struct AsyncWindowContext {
app: AsyncAppContext,
window: AnyWindowHandle,
}
impl AsyncWindowContext {
pub fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
Self { app, window }
}
}
impl Context for AsyncWindowContext {
type EntityContext<'a, 'w, T: 'static + Send + Sync> = ViewContext<'a, 'w, T>;
type Result<T> = Result<T>;
fn entity<R: Send + Sync + 'static>(
&mut self,
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, R>) -> R,
) -> Result<Handle<R>> {
self.app
.update_window(self.window, |cx| cx.entity(build_entity))
}
fn update_entity<T: Send + Sync + 'static, R>(
&mut self,
handle: &Handle<T>,
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
) -> Result<R> {
self.app
.update_window(self.window, |cx| cx.update_entity(handle, update))
}
}