Remove more Send bounds and simplify view rendering

This commit is contained in:
Antonio Scandurra 2023-11-02 09:41:49 +01:00
parent 6cab5c2885
commit 64ad8943ba
17 changed files with 720 additions and 534 deletions

View file

@ -4,7 +4,7 @@ use collections::{HashMap, HashSet};
use serde::Deserialize; use serde::Deserialize;
use std::any::{type_name, Any}; use std::any::{type_name, Any};
pub trait Action: Any + Send { pub trait Action: 'static {
fn qualified_name() -> SharedString fn qualified_name() -> SharedString
where where
Self: Sized; Self: Sized;
@ -19,7 +19,7 @@ pub trait Action: Any + Send {
impl<A> Action for A impl<A> Action for A
where where
A: for<'a> Deserialize<'a> + PartialEq + Any + Send + Clone + Default, A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + 'static,
{ {
fn qualified_name() -> SharedString { fn qualified_name() -> SharedString {
type_name::<A>().into() type_name::<A>().into()

View file

@ -13,11 +13,12 @@ use smallvec::SmallVec;
pub use test_context::*; pub use test_context::*;
use crate::{ use crate::{
current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource, current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AnyWindowHandle,
BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId, FocusEvent, FocusHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,
FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId, Pixels, Platform, Point, Render, Entity, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId,
SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, Pixels, Platform, Point, Render, SharedString, SubscriberSet, Subscription, SvgRenderer, Task,
TextSystem, View, Window, WindowContext, WindowHandle, WindowId, TextStyle, TextStyleRefinement, TextSystem, View, Window, WindowContext, WindowHandle,
WindowId,
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use collections::{HashMap, HashSet, VecDeque}; use collections::{HashMap, HashSet, VecDeque};
@ -114,8 +115,8 @@ type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<d
type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>; type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>; type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>; type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
type QuitHandler = Box<dyn FnMut(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>; type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + 'static>; type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
pub struct AppContext { pub struct AppContext {
this: Weak<RefCell<AppContext>>, this: Weak<RefCell<AppContext>>,
@ -214,10 +215,9 @@ impl AppContext {
pub fn quit(&mut self) { pub fn quit(&mut self) {
let mut futures = Vec::new(); let mut futures = Vec::new();
self.quit_observers.clone().retain(&(), |observer| { for observer in self.quit_observers.remove(&()) {
futures.push(observer(self)); futures.push(observer(self));
true }
});
self.windows.clear(); self.windows.clear();
self.flush_effects(); self.flush_effects();
@ -255,37 +255,31 @@ impl AppContext {
result result
} }
pub(crate) fn read_window<R>( pub fn windows(&self) -> Vec<AnyWindowHandle> {
&self, self.windows
id: WindowId, .values()
read: impl FnOnce(&WindowContext) -> R, .filter_map(|window| Some(window.as_ref()?.handle.clone()))
) -> Result<R> { .collect()
let window = self
.windows
.get(id)
.ok_or_else(|| anyhow!("window not found"))?
.as_ref()
.unwrap();
Ok(read(&WindowContext::immutable(self, &window)))
} }
pub(crate) fn update_window<R>( pub(crate) fn update_window<R>(
&mut self, &mut self,
id: WindowId, handle: AnyWindowHandle,
update: impl FnOnce(&mut WindowContext) -> R, update: impl FnOnce(AnyView, &mut WindowContext) -> R,
) -> Result<R> { ) -> Result<R> {
self.update(|cx| { self.update(|cx| {
let mut window = cx let mut window = cx
.windows .windows
.get_mut(id) .get_mut(handle.id)
.ok_or_else(|| anyhow!("window not found"))? .ok_or_else(|| anyhow!("window not found"))?
.take() .take()
.unwrap(); .unwrap();
let result = update(&mut WindowContext::mutable(cx, &mut window)); let root_view = window.root_view.clone().unwrap();
let result = update(root_view, &mut WindowContext::new(cx, &mut window));
cx.windows cx.windows
.get_mut(id) .get_mut(handle.id)
.ok_or_else(|| anyhow!("window not found"))? .ok_or_else(|| anyhow!("window not found"))?
.replace(window); .replace(window);
@ -305,7 +299,7 @@ impl AppContext {
let id = cx.windows.insert(None); let id = cx.windows.insert(None);
let handle = WindowHandle::new(id); let handle = WindowHandle::new(id);
let mut window = Window::new(handle.into(), options, cx); let mut window = Window::new(handle.into(), options, cx);
let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window)); let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
window.root_view.replace(root_view.into()); window.root_view.replace(root_view.into());
cx.windows.get_mut(id).unwrap().replace(window); cx.windows.get_mut(id).unwrap().replace(window);
handle handle
@ -386,8 +380,11 @@ impl AppContext {
self.apply_notify_effect(emitter); self.apply_notify_effect(emitter);
} }
Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event), Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
Effect::FocusChanged { window_id, focused } => { Effect::FocusChanged {
self.apply_focus_changed_effect(window_id, focused); window_handle,
focused,
} => {
self.apply_focus_changed_effect(window_handle, focused);
} }
Effect::Refresh => { Effect::Refresh => {
self.apply_refresh_effect(); self.apply_refresh_effect();
@ -407,18 +404,18 @@ impl AppContext {
let dirty_window_ids = self let dirty_window_ids = self
.windows .windows
.iter() .iter()
.filter_map(|(window_id, window)| { .filter_map(|(_, window)| {
let window = window.as_ref().unwrap(); let window = window.as_ref().unwrap();
if window.dirty { if window.dirty {
Some(window_id) Some(window.handle.clone())
} else { } else {
None None
} }
}) })
.collect::<SmallVec<[_; 8]>>(); .collect::<SmallVec<[_; 8]>>();
for dirty_window_id in dirty_window_ids { for dirty_window_handle in dirty_window_ids {
self.update_window(dirty_window_id, |cx| cx.draw()).unwrap(); dirty_window_handle.update(self, |_, cx| cx.draw()).unwrap();
} }
} }
@ -435,7 +432,7 @@ impl AppContext {
for (entity_id, mut entity) in dropped { for (entity_id, mut entity) in dropped {
self.observers.remove(&entity_id); self.observers.remove(&entity_id);
self.event_listeners.remove(&entity_id); self.event_listeners.remove(&entity_id);
for mut release_callback in self.release_listeners.remove(&entity_id) { for release_callback in self.release_listeners.remove(&entity_id) {
release_callback(entity.as_mut(), self); release_callback(entity.as_mut(), self);
} }
} }
@ -446,27 +443,27 @@ impl AppContext {
/// For now, we simply blur the window if this happens, but we may want to support invoking /// For now, we simply blur the window if this happens, but we may want to support invoking
/// a window blur handler to restore focus to some logical element. /// a window blur handler to restore focus to some logical element.
fn release_dropped_focus_handles(&mut self) { fn release_dropped_focus_handles(&mut self) {
let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>(); for window_handle in self.windows() {
for window_id in window_ids { window_handle
self.update_window(window_id, |cx| { .update(self, |_, cx| {
let mut blur_window = false; let mut blur_window = false;
let focus = cx.window.focus; let focus = cx.window.focus;
cx.window.focus_handles.write().retain(|handle_id, count| { cx.window.focus_handles.write().retain(|handle_id, count| {
if count.load(SeqCst) == 0 { if count.load(SeqCst) == 0 {
if focus == Some(handle_id) { if focus == Some(handle_id) {
blur_window = true; blur_window = true;
}
false
} else {
true
} }
false });
} else {
true
}
});
if blur_window { if blur_window {
cx.blur(); cx.blur();
} }
}) })
.unwrap(); .unwrap();
} }
} }
@ -483,30 +480,35 @@ impl AppContext {
.retain(&emitter, |handler| handler(event.as_ref(), self)); .retain(&emitter, |handler| handler(event.as_ref(), self));
} }
fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) { fn apply_focus_changed_effect(
self.update_window(window_id, |cx| { &mut self,
if cx.window.focus == focused { window_handle: AnyWindowHandle,
let mut listeners = mem::take(&mut cx.window.focus_listeners); focused: Option<FocusId>,
let focused = ) {
focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap()); window_handle
let blurred = cx .update(self, |_, cx| {
.window if cx.window.focus == focused {
.last_blur let mut listeners = mem::take(&mut cx.window.focus_listeners);
.take() let focused = focused
.unwrap() .map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles)); let blurred = cx
if focused.is_some() || blurred.is_some() { .window
let event = FocusEvent { focused, blurred }; .last_blur
for listener in &listeners { .take()
listener(&event, cx); .unwrap()
.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
if focused.is_some() || blurred.is_some() {
let event = FocusEvent { focused, blurred };
for listener in &listeners {
listener(&event, cx);
}
} }
}
listeners.extend(cx.window.focus_listeners.drain(..)); listeners.extend(cx.window.focus_listeners.drain(..));
cx.window.focus_listeners = listeners; cx.window.focus_listeners = listeners;
} }
}) })
.ok(); .ok();
} }
fn apply_refresh_effect(&mut self) { fn apply_refresh_effect(&mut self) {
@ -680,6 +682,24 @@ impl AppContext {
self.globals_by_type.insert(global_type, lease.global); self.globals_by_type.insert(global_type, lease.global);
} }
pub fn observe_release<E, T>(
&mut self,
handle: &E,
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
) -> Subscription
where
E: Entity<T>,
T: 'static,
{
self.release_listeners.insert(
handle.entity_id(),
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
on_release(entity, cx)
}),
)
}
pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) { pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
self.text_style_stack.push(text_style); self.text_style_stack.push(text_style);
} }
@ -733,7 +753,6 @@ impl AppContext {
} }
impl Context for AppContext { impl Context for AppContext {
type ModelContext<'a, T> = ModelContext<'a, T>;
type Result<T> = T; type Result<T> = T;
/// Build an entity that is owned by the application. The given function will be invoked with /// Build an entity that is owned by the application. The given function will be invoked with
@ -741,11 +760,11 @@ impl Context for AppContext {
/// which can be used to access the entity in a context. /// which can be used to access the entity in a context.
fn build_model<T: 'static>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Model<T> { ) -> Model<T> {
self.update(|cx| { self.update(|cx| {
let slot = cx.entities.reserve(); let slot = cx.entities.reserve();
let entity = build_model(&mut ModelContext::mutable(cx, slot.downgrade())); let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
cx.entities.insert(slot, entity) cx.entities.insert(slot, entity)
}) })
} }
@ -755,18 +774,38 @@ impl Context for AppContext {
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
model: &Model<T>, model: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> R { ) -> R {
self.update(|cx| { self.update(|cx| {
let mut entity = cx.entities.lease(model); let mut entity = cx.entities.lease(model);
let result = update( let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
&mut entity,
&mut ModelContext::mutable(cx, model.downgrade()),
);
cx.entities.end_lease(entity); cx.entities.end_lease(entity);
result result
}) })
} }
fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
{
self.update(|cx| {
let mut window = cx
.windows
.get_mut(handle.id)
.ok_or_else(|| anyhow!("window not found"))?
.take()
.unwrap();
let root_view = window.root_view.clone().unwrap();
let result = update(root_view, &mut WindowContext::new(cx, &mut window));
cx.windows
.get_mut(handle.id)
.ok_or_else(|| anyhow!("window not found"))?
.replace(window);
Ok(result)
})
}
} }
/// These effects are processed at the end of each application update cycle. /// These effects are processed at the end of each application update cycle.
@ -779,7 +818,7 @@ pub(crate) enum Effect {
event: Box<dyn Any>, event: Box<dyn Any>,
}, },
FocusChanged { FocusChanged {
window_id: WindowId, window_handle: AnyWindowHandle,
focused: Option<FocusId>, focused: Option<FocusId>,
}, },
Refresh, Refresh,

View file

@ -1,8 +1,8 @@
use crate::{ use crate::{
AnyWindowHandle, AppContext, BackgroundExecutor, Context, ForegroundExecutor, Model, AnyView, AnyWindowHandle, AppContext, BackgroundExecutor, Context, ForegroundExecutor, Model,
ModelContext, Result, Task, WindowContext, ModelContext, Render, Result, Task, View, ViewContext, VisualContext, WindowContext,
}; };
use anyhow::anyhow; use anyhow::{anyhow, Context as _};
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use std::{cell::RefCell, future::Future, rc::Weak}; use std::{cell::RefCell, future::Future, rc::Weak};
@ -14,12 +14,11 @@ pub struct AsyncAppContext {
} }
impl Context for AsyncAppContext { impl Context for AsyncAppContext {
type ModelContext<'a, T> = ModelContext<'a, T>;
type Result<T> = Result<T>; type Result<T> = Result<T>;
fn build_model<T: 'static>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>> ) -> Self::Result<Model<T>>
where where
T: 'static, T: 'static,
@ -35,7 +34,7 @@ impl Context for AsyncAppContext {
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
handle: &Model<T>, handle: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> Self::Result<R> { ) -> Self::Result<R> {
let app = self let app = self
.app .app
@ -44,6 +43,15 @@ impl Context for AsyncAppContext {
let mut app = app.borrow_mut(); let mut app = app.borrow_mut();
Ok(app.update_model(handle, update)) Ok(app.update_model(handle, update))
} }
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
{
let app = self.app.upgrade().context("app was released")?;
let mut lock = app.borrow_mut();
lock.update_window(window, f)
}
} }
impl AsyncAppContext { impl AsyncAppContext {
@ -74,30 +82,17 @@ impl AsyncAppContext {
Ok(f(&mut *lock)) Ok(f(&mut *lock))
} }
pub fn read_window<R>(
&self,
handle: AnyWindowHandle,
update: impl FnOnce(&WindowContext) -> R,
) -> Result<R> {
let app = self
.app
.upgrade()
.ok_or_else(|| anyhow!("app was released"))?;
let app_context = app.borrow();
app_context.read_window(handle.id, update)
}
pub fn update_window<R>( pub fn update_window<R>(
&self, &self,
handle: AnyWindowHandle, handle: AnyWindowHandle,
update: impl FnOnce(&mut WindowContext) -> R, update: impl FnOnce(AnyView, &mut WindowContext) -> R,
) -> Result<R> { ) -> Result<R> {
let app = self let app = self
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut app_context = app.borrow_mut(); let mut app_context = app.borrow_mut();
app_context.update_window(handle.id, update) app_context.update_window(handle, update)
} }
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R> pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
@ -161,22 +156,22 @@ impl AsyncWindowContext {
Self { app, window } Self { app, window }
} }
pub fn update<R>(&self, update: impl FnOnce(&mut WindowContext) -> R) -> Result<R> { pub fn update<R>(
&mut self,
update: impl FnOnce(AnyView, &mut WindowContext) -> R,
) -> Result<R> {
self.app.update_window(self.window, update) self.app.update_window(self.window, update)
} }
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) { pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
self.app self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
.update_window(self.window, |cx| cx.on_next_frame(f))
.ok();
} }
pub fn read_global<G: 'static, R>( pub fn read_global<G: 'static, R>(
&self, &mut self,
read: impl FnOnce(&G, &WindowContext) -> R, read: impl FnOnce(&G, &WindowContext) -> R,
) -> Result<R> { ) -> Result<R> {
self.app self.window.update(self, |_, cx| read(cx.global(), cx))
.read_window(self.window, |cx| read(cx.global(), cx))
} }
pub fn update_global<G, R>( pub fn update_global<G, R>(
@ -186,32 +181,79 @@ impl AsyncWindowContext {
where where
G: 'static, G: 'static,
{ {
self.app self.window.update(self, |_, cx| cx.update_global(update))
.update_window(self.window, |cx| cx.update_global(update)) }
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut + 'static) -> Task<R>
where
Fut: Future<Output = R> + 'static,
R: 'static,
{
let this = self.clone();
self.foreground_executor.spawn(async move { f(this).await })
} }
} }
impl Context for AsyncWindowContext { impl Context for AsyncWindowContext {
type ModelContext<'a, T> = ModelContext<'a, T>;
type Result<T> = Result<T>; type Result<T> = Result<T>;
fn build_model<T>( fn build_model<T>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Result<Model<T>> ) -> Result<Model<T>>
where where
T: 'static, T: 'static,
{ {
self.app self.window
.update_window(self.window, |cx| cx.build_model(build_model)) .update(self, |_, cx| cx.build_model(build_model))
} }
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
handle: &Model<T>, handle: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> Result<R> { ) -> Result<R> {
self.app self.window
.update_window(self.window, |cx| cx.update_model(handle, update)) .update(self, |_, cx| cx.update_model(handle, update))
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
{
self.app.update_window(window, update)
}
}
impl VisualContext for AsyncWindowContext {
fn build_view<V>(
&mut self,
build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
) -> Self::Result<View<V>>
where
V: 'static,
{
self.window
.update(self, |_, cx| cx.build_view(build_view_state))
}
fn update_view<V: 'static, R>(
&mut self,
view: &View<V>,
update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
) -> Self::Result<R> {
self.window
.update(self, |_, cx| cx.update_view(view, update))
}
fn replace_root_view<V>(
&mut self,
build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
) -> Self::Result<View<V>>
where
V: Render,
{
self.window
.update(self, |_, cx| cx.replace_root_view(build_view))
} }
} }

View file

@ -1,4 +1,4 @@
use crate::{private::Sealed, AnyBox, AppContext, Context, Entity}; use crate::{private::Sealed, AnyBox, AppContext, Context, Entity, ModelContext};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use parking_lot::{RwLock, RwLockUpgradableReadGuard}; use parking_lot::{RwLock, RwLockUpgradableReadGuard};
@ -169,6 +169,10 @@ impl AnyModel {
self.entity_id self.entity_id
} }
pub fn entity_type(&self) -> TypeId {
self.entity_type
}
pub fn downgrade(&self) -> AnyWeakModel { pub fn downgrade(&self) -> AnyWeakModel {
AnyWeakModel { AnyWeakModel {
entity_id: self.entity_id, entity_id: self.entity_id,
@ -329,7 +333,7 @@ impl<T: 'static> Model<T> {
pub fn update<C, R>( pub fn update<C, R>(
&self, &self,
cx: &mut C, cx: &mut C,
update: impl FnOnce(&mut T, &mut C::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> C::Result<R> ) -> C::Result<R>
where where
C: Context, C: Context,
@ -475,7 +479,7 @@ impl<T: 'static> WeakModel<T> {
pub fn update<C, R>( pub fn update<C, R>(
&self, &self,
cx: &mut C, cx: &mut C,
update: impl FnOnce(&mut T, &mut C::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> Result<R> ) -> Result<R>
where where
C: Context, C: Context,

View file

@ -1,7 +1,8 @@
use crate::{ use crate::{
AppContext, AsyncAppContext, Context, Effect, Entity, EntityId, EventEmitter, Model, Reference, AnyView, AnyWindowHandle, AppContext, AsyncAppContext, Context, Effect, Entity, EntityId,
Subscription, Task, WeakModel, EventEmitter, Model, Subscription, Task, WeakModel, WindowContext,
}; };
use anyhow::Result;
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use futures::FutureExt; use futures::FutureExt;
use std::{ use std::{
@ -14,16 +15,13 @@ use std::{
pub struct ModelContext<'a, T> { pub struct ModelContext<'a, T> {
#[deref] #[deref]
#[deref_mut] #[deref_mut]
app: Reference<'a, AppContext>, app: &'a mut AppContext,
model_state: WeakModel<T>, model_state: WeakModel<T>,
} }
impl<'a, T: 'static> ModelContext<'a, T> { impl<'a, T: 'static> ModelContext<'a, T> {
pub(crate) fn mutable(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self { pub(crate) fn new(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self {
Self { Self { app, model_state }
app: Reference::Mutable(app),
model_state,
}
} }
pub fn entity_id(&self) -> EntityId { pub fn entity_id(&self) -> EntityId {
@ -95,7 +93,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
pub fn on_release( pub fn on_release(
&mut self, &mut self,
mut on_release: impl FnMut(&mut T, &mut AppContext) + 'static, on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
) -> Subscription ) -> Subscription
where where
T: 'static, T: 'static,
@ -112,7 +110,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
pub fn observe_release<T2, E>( pub fn observe_release<T2, E>(
&mut self, &mut self,
entity: &E, entity: &E,
mut on_release: impl FnMut(&mut T, &mut T2, &mut ModelContext<'_, T>) + 'static, on_release: impl FnOnce(&mut T, &mut T2, &mut ModelContext<'_, T>) + 'static,
) -> Subscription ) -> Subscription
where where
T: Any, T: Any,
@ -215,12 +213,11 @@ where
} }
impl<'a, T> Context for ModelContext<'a, T> { impl<'a, T> Context for ModelContext<'a, T> {
type ModelContext<'b, U> = ModelContext<'b, U>;
type Result<U> = U; type Result<U> = U;
fn build_model<U: 'static>( fn build_model<U: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, U>) -> U, build_model: impl FnOnce(&mut ModelContext<'_, U>) -> U,
) -> Model<U> { ) -> Model<U> {
self.app.build_model(build_model) self.app.build_model(build_model)
} }
@ -228,10 +225,17 @@ impl<'a, T> Context for ModelContext<'a, T> {
fn update_model<U: 'static, R>( fn update_model<U: 'static, R>(
&mut self, &mut self,
handle: &Model<U>, handle: &Model<U>,
update: impl FnOnce(&mut U, &mut Self::ModelContext<'_, U>) -> R, update: impl FnOnce(&mut U, &mut ModelContext<'_, U>) -> R,
) -> R { ) -> R {
self.app.update_model(handle, update) self.app.update_model(handle, update)
} }
fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> R,
{
self.app.update_window(window, update)
}
} }
impl<T> Borrow<AppContext> for ModelContext<'_, T> { impl<T> Borrow<AppContext> for ModelContext<'_, T> {

View file

@ -1,7 +1,7 @@
use crate::{ use crate::{
AnyWindowHandle, AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter, AnyView, AnyWindowHandle, AppContext, AsyncAppContext, BackgroundExecutor, Context,
ForegroundExecutor, Model, ModelContext, Result, Task, TestDispatcher, TestPlatform, EventEmitter, ForegroundExecutor, Model, ModelContext, Result, Task, TestDispatcher,
WindowContext, TestPlatform, WindowContext,
}; };
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
use futures::{Stream, StreamExt}; use futures::{Stream, StreamExt};
@ -15,12 +15,11 @@ pub struct TestAppContext {
} }
impl Context for TestAppContext { impl Context for TestAppContext {
type ModelContext<'a, T> = ModelContext<'a, T>;
type Result<T> = T; type Result<T> = T;
fn build_model<T: 'static>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>> ) -> Self::Result<Model<T>>
where where
T: 'static, T: 'static,
@ -32,11 +31,19 @@ impl Context for TestAppContext {
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
handle: &Model<T>, handle: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> Self::Result<R> { ) -> Self::Result<R> {
let mut app = self.app.borrow_mut(); let mut app = self.app.borrow_mut();
app.update_model(handle, update) app.update_model(handle, update)
} }
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
{
let mut lock = self.app.borrow_mut();
lock.update_window(window, f)
}
} }
impl TestAppContext { impl TestAppContext {
@ -80,22 +87,13 @@ impl TestAppContext {
cx.update(f) cx.update(f)
} }
pub fn read_window<R>(
&self,
handle: AnyWindowHandle,
read: impl FnOnce(&WindowContext) -> R,
) -> R {
let app_context = self.app.borrow();
app_context.read_window(handle.id, read).unwrap()
}
pub fn update_window<R>( pub fn update_window<R>(
&self, &self,
handle: AnyWindowHandle, handle: AnyWindowHandle,
update: impl FnOnce(&mut WindowContext) -> R, update: impl FnOnce(AnyView, &mut WindowContext) -> R,
) -> R { ) -> R {
let mut app = self.app.borrow_mut(); let mut app = self.app.borrow_mut();
app.update_window(handle.id, update).unwrap() app.update_window(handle, update).unwrap()
} }
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R> pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>

View file

@ -8,7 +8,7 @@ use std::{
sync::atomic::{AtomicUsize, Ordering::SeqCst}, sync::atomic::{AtomicUsize, Ordering::SeqCst},
}; };
pub trait AssetSource: 'static + Send + Sync { pub trait AssetSource: 'static {
fn load(&self, path: &str) -> Result<Cow<[u8]>>; fn load(&self, path: &str) -> Result<Cow<[u8]>>;
fn list(&self, path: &str) -> Result<Vec<SharedString>>; fn list(&self, path: &str) -> Result<Vec<SharedString>>;
} }

View file

@ -219,7 +219,7 @@ impl<V, E, F> Element<V> for Option<F>
where where
V: 'static, V: 'static,
E: 'static + Component<V>, E: 'static + Component<V>,
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + 'static, F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
{ {
type ElementState = AnyElement<V>; type ElementState = AnyElement<V>;
@ -263,7 +263,7 @@ impl<V, E, F> Component<V> for Option<F>
where where
V: 'static, V: 'static,
E: 'static + Component<V>, E: 'static + Component<V>,
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + 'static, F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
{ {
fn render(self) -> AnyElement<V> { fn render(self) -> AnyElement<V> {
AnyElement::new(self) AnyElement::new(self)
@ -274,7 +274,7 @@ impl<V, E, F> Component<V> for F
where where
V: 'static, V: 'static,
E: 'static + Component<V>, E: 'static + Component<V>,
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + 'static, F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
{ {
fn render(self) -> AnyElement<V> { fn render(self) -> AnyElement<V> {
AnyElement::new(Some(self)) AnyElement::new(Some(self))

View file

@ -305,7 +305,6 @@ where
impl<V, I, F> Component<V> for Div<V, I, F> impl<V, I, F> Component<V> for Div<V, I, F>
where where
// V: Any + Send + Sync,
I: ElementInteraction<V>, I: ElementInteraction<V>,
F: ElementFocus<V>, F: ElementFocus<V>,
{ {

View file

@ -44,9 +44,6 @@ pub struct Text<V> {
state_type: PhantomData<V>, state_type: PhantomData<V>,
} }
unsafe impl<V> Send for Text<V> {}
unsafe impl<V> Sync for Text<V> {}
impl<V: 'static> Component<V> for Text<V> { impl<V: 'static> Component<V> for Text<V> {
fn render(self) -> AnyElement<V> { fn render(self) -> AnyElement<V> {
AnyElement::new(self) AnyElement::new(self)

View file

@ -8,7 +8,7 @@ use smallvec::SmallVec;
pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>; pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;
pub type FocusListener<V> = pub type FocusListener<V> =
Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + Send + 'static>; Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + 'static>;
pub trait Focusable<V: 'static>: Element<V> { pub trait Focusable<V: 'static>: Element<V> {
fn focus_listeners(&mut self) -> &mut FocusListeners<V>; fn focus_listeners(&mut self) -> &mut FocusListeners<V>;
@ -42,7 +42,7 @@ pub trait Focusable<V: 'static>: Element<V> {
fn on_focus( fn on_focus(
mut self, mut self,
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -58,7 +58,7 @@ pub trait Focusable<V: 'static>: Element<V> {
fn on_blur( fn on_blur(
mut self, mut self,
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -74,7 +74,7 @@ pub trait Focusable<V: 'static>: Element<V> {
fn on_focus_in( fn on_focus_in(
mut self, mut self,
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -99,7 +99,7 @@ pub trait Focusable<V: 'static>: Element<V> {
fn on_focus_out( fn on_focus_out(
mut self, mut self,
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -122,7 +122,7 @@ pub trait Focusable<V: 'static>: Element<V> {
} }
} }
pub trait ElementFocus<V: 'static>: 'static + Send { pub trait ElementFocus<V: 'static>: 'static {
fn as_focusable(&self) -> Option<&FocusEnabled<V>>; fn as_focusable(&self) -> Option<&FocusEnabled<V>>;
fn as_focusable_mut(&mut self) -> Option<&mut FocusEnabled<V>>; fn as_focusable_mut(&mut self) -> Option<&mut FocusEnabled<V>>;

View file

@ -931,6 +931,18 @@ impl From<f64> for GlobalPixels {
} }
} }
impl sqlez::bindable::StaticColumnCount for GlobalPixels {}
impl sqlez::bindable::Bind for GlobalPixels {
fn bind(
&self,
statement: &sqlez::statement::Statement,
start_index: i32,
) -> anyhow::Result<i32> {
self.0.bind(statement, start_index)
}
}
#[derive(Clone, Copy, Default, Add, Sub, Mul, Div, Neg)] #[derive(Clone, Copy, Default, Add, Sub, Mul, Div, Neg)]
pub struct Rems(f32); pub struct Rems(f32);

View file

@ -68,34 +68,36 @@ use derive_more::{Deref, DerefMut};
use std::{ use std::{
any::{Any, TypeId}, any::{Any, TypeId},
borrow::{Borrow, BorrowMut}, borrow::{Borrow, BorrowMut},
ops::{Deref, DerefMut},
}; };
use taffy::TaffyLayoutEngine; use taffy::TaffyLayoutEngine;
type AnyBox = Box<dyn Any>; type AnyBox = Box<dyn Any>;
pub trait Context { pub trait Context {
type ModelContext<'a, T>;
type Result<T>; type Result<T>;
fn build_model<T: 'static>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>>; ) -> Self::Result<Model<T>>;
fn update_model<T: 'static, R>( fn update_model<T, R>(
&mut self, &mut self,
handle: &Model<T>, handle: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> Self::Result<R>; ) -> Self::Result<R>
where
T: 'static;
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T;
} }
pub trait VisualContext: Context { pub trait VisualContext: Context {
type ViewContext<'a, 'w, V>;
fn build_view<V>( fn build_view<V>(
&mut self, &mut self,
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V, build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
) -> Self::Result<View<V>> ) -> Self::Result<View<V>>
where where
V: 'static; V: 'static;
@ -103,12 +105,19 @@ pub trait VisualContext: Context {
fn update_view<V: 'static, R>( fn update_view<V: 'static, R>(
&mut self, &mut self,
view: &View<V>, view: &View<V>,
update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, '_, V>) -> R, update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
) -> Self::Result<R>; ) -> Self::Result<R>;
fn replace_root_view<V>(
&mut self,
build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
) -> Self::Result<View<V>>
where
V: Render;
} }
pub trait Entity<T>: Sealed { pub trait Entity<T>: Sealed {
type Weak: 'static + Send; type Weak: 'static;
fn entity_id(&self) -> EntityId; fn entity_id(&self) -> EntityId;
fn downgrade(&self) -> Self::Weak; fn downgrade(&self) -> Self::Weak;
@ -128,7 +137,7 @@ pub trait BorrowAppContext {
where where
F: FnOnce(&mut Self) -> R; F: FnOnce(&mut Self) -> R;
fn set_global<T: Send + 'static>(&mut self, global: T); fn set_global<T: 'static>(&mut self, global: T);
} }
impl<C> BorrowAppContext for C impl<C> BorrowAppContext for C
@ -145,7 +154,7 @@ where
result result
} }
fn set_global<G: 'static + Send>(&mut self, global: G) { fn set_global<G: 'static>(&mut self, global: G) {
self.borrow_mut().set_global(global) self.borrow_mut().set_global(global)
} }
} }
@ -208,30 +217,3 @@ impl<T: Into<ArcCow<'static, str>>> From<T> for SharedString {
Self(value.into()) Self(value.into())
} }
} }
pub enum Reference<'a, T> {
Immutable(&'a T),
Mutable(&'a mut T),
}
impl<'a, T> Deref for Reference<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match self {
Reference::Immutable(target) => target,
Reference::Mutable(target) => target,
}
}
}
impl<'a, T> DerefMut for Reference<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Reference::Immutable(_) => {
panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
}
Reference::Mutable(target) => target,
}
}
}

View file

@ -9,12 +9,14 @@ use crate::{
ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point, ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point,
RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,
}; };
use anyhow::anyhow; use anyhow::{anyhow, bail};
use async_task::Runnable; use async_task::Runnable;
use futures::channel::oneshot; use futures::channel::oneshot;
use parking::Unparker; use parking::Unparker;
use seahash::SeaHasher; use seahash::SeaHasher;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlez::bindable::{Bind, Column, StaticColumnCount};
use sqlez::statement::Statement;
use std::borrow::Cow; use std::borrow::Cow;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::time::Duration; use std::time::Duration;
@ -27,6 +29,7 @@ use std::{
str::FromStr, str::FromStr,
sync::Arc, sync::Arc,
}; };
use uuid::Uuid;
pub use keystroke::*; pub use keystroke::*;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -106,6 +109,9 @@ pub(crate) trait Platform: 'static {
pub trait PlatformDisplay: Send + Sync + Debug { pub trait PlatformDisplay: Send + Sync + Debug {
fn id(&self) -> DisplayId; fn id(&self) -> DisplayId;
/// Returns a stable identifier for this display that can be persisted and used
/// across system restarts.
fn uuid(&self) -> Result<Uuid>;
fn as_any(&self) -> &dyn Any; fn as_any(&self) -> &dyn Any;
fn bounds(&self) -> Bounds<GlobalPixels>; fn bounds(&self) -> Bounds<GlobalPixels>;
} }
@ -372,6 +378,64 @@ pub enum WindowBounds {
Fixed(Bounds<GlobalPixels>), Fixed(Bounds<GlobalPixels>),
} }
impl StaticColumnCount for WindowBounds {
fn column_count() -> usize {
5
}
}
impl Bind for WindowBounds {
fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
let (region, next_index) = match self {
WindowBounds::Fullscreen => {
let next_index = statement.bind(&"Fullscreen", start_index)?;
(None, next_index)
}
WindowBounds::Maximized => {
let next_index = statement.bind(&"Maximized", start_index)?;
(None, next_index)
}
WindowBounds::Fixed(region) => {
let next_index = statement.bind(&"Fixed", start_index)?;
(Some(*region), next_index)
}
};
statement.bind(
&region.map(|region| {
(
region.origin.x,
region.origin.y,
region.size.width,
region.size.height,
)
}),
next_index,
)
}
}
impl Column for WindowBounds {
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
let (window_state, next_index) = String::column(statement, start_index)?;
let bounds = match window_state.as_str() {
"Fullscreen" => WindowBounds::Fullscreen,
"Maximized" => WindowBounds::Maximized,
"Fixed" => {
// let ((x, y, width, height), _) = Column::column(statement, next_index)?;
// WindowBounds::Fixed(RectF::new(
// Vector2F::new(x, y),
// Vector2F::new(width, height),
// ))
todo!()
}
_ => bail!("Window State did not have a valid string"),
};
Ok((bounds, next_index + 4))
}
}
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub enum WindowAppearance { pub enum WindowAppearance {
Light, Light,

View file

@ -1,9 +1,12 @@
use crate::{point, size, Bounds, DisplayId, GlobalPixels, PlatformDisplay}; use crate::{point, size, Bounds, DisplayId, GlobalPixels, PlatformDisplay};
use anyhow::Result;
use core_foundation::uuid::{CFUUIDGetUUIDBytes, CFUUIDRef};
use core_graphics::{ use core_graphics::{
display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList}, display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList},
geometry::{CGPoint, CGRect, CGSize}, geometry::{CGPoint, CGRect, CGSize},
}; };
use std::any::Any; use std::any::Any;
use uuid::Uuid;
#[derive(Debug)] #[derive(Debug)]
pub struct MacDisplay(pub(crate) CGDirectDisplayID); pub struct MacDisplay(pub(crate) CGDirectDisplayID);
@ -11,17 +14,23 @@ pub struct MacDisplay(pub(crate) CGDirectDisplayID);
unsafe impl Send for MacDisplay {} unsafe impl Send for MacDisplay {}
impl MacDisplay { impl MacDisplay {
/// Get the screen with the given UUID. /// Get the screen with the given [DisplayId].
pub fn find_by_id(id: DisplayId) -> Option<Self> { pub fn find_by_id(id: DisplayId) -> Option<Self> {
Self::all().find(|screen| screen.id() == id) Self::all().find(|screen| screen.id() == id)
} }
/// Get the screen with the given persistent [Uuid].
pub fn find_by_uuid(uuid: Uuid) -> Option<Self> {
Self::all().find(|screen| screen.uuid().ok() == Some(uuid))
}
/// Get the primary screen - the one with the menu bar, and whose bottom left /// Get the primary screen - the one with the menu bar, and whose bottom left
/// corner is at the origin of the AppKit coordinate system. /// corner is at the origin of the AppKit coordinate system.
pub fn primary() -> Self { pub fn primary() -> Self {
Self::all().next().unwrap() Self::all().next().unwrap()
} }
/// Obtains an iterator over all currently active system displays.
pub fn all() -> impl Iterator<Item = Self> { pub fn all() -> impl Iterator<Item = Self> {
unsafe { unsafe {
let mut display_count: u32 = 0; let mut display_count: u32 = 0;
@ -40,6 +49,11 @@ impl MacDisplay {
} }
} }
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef;
}
/// Convert the given rectangle from CoreGraphics' native coordinate space to GPUI's coordinate space. /// Convert the given rectangle from CoreGraphics' native coordinate space to GPUI's coordinate space.
/// ///
/// CoreGraphics' coordinate space has its origin at the bottom left of the primary screen, /// CoreGraphics' coordinate space has its origin at the bottom left of the primary screen,
@ -88,6 +102,34 @@ impl PlatformDisplay for MacDisplay {
DisplayId(self.0) DisplayId(self.0)
} }
fn uuid(&self) -> Result<Uuid> {
let cfuuid = unsafe { CGDisplayCreateUUIDFromDisplayID(self.0 as CGDirectDisplayID) };
anyhow::ensure!(
!cfuuid.is_null(),
"AppKit returned a null from CGDisplayCreateUUIDFromDisplayID"
);
let bytes = unsafe { CFUUIDGetUUIDBytes(cfuuid) };
Ok(Uuid::from_bytes([
bytes.byte0,
bytes.byte1,
bytes.byte2,
bytes.byte3,
bytes.byte4,
bytes.byte5,
bytes.byte6,
bytes.byte7,
bytes.byte8,
bytes.byte9,
bytes.byte10,
bytes.byte11,
bytes.byte12,
bytes.byte13,
bytes.byte14,
bytes.byte15,
]))
}
fn as_any(&self) -> &dyn Any { fn as_any(&self) -> &dyn Any {
self self
} }

View file

@ -1,12 +1,12 @@
use crate::{ use crate::{
private::Sealed, AnyBox, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace, private::Sealed, AnyBox, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace,
BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, LayoutId, Model, Pixels, BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, Flatten, LayoutId,
Size, ViewContext, VisualContext, WeakModel, WindowContext, Model, Pixels, Size, ViewContext, VisualContext, WeakModel, WindowContext,
}; };
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::{ use std::{
any::{Any, TypeId}, any::{Any, TypeId},
marker::PhantomData, hash::{Hash, Hasher},
}; };
pub trait Render: 'static + Sized { pub trait Render: 'static + Sized {
@ -52,7 +52,7 @@ impl<V: 'static> View<V> {
pub fn update<C, R>( pub fn update<C, R>(
&self, &self,
cx: &mut C, cx: &mut C,
f: impl FnOnce(&mut V, &mut C::ViewContext<'_, '_, V>) -> R, f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
) -> C::Result<R> ) -> C::Result<R>
where where
C: VisualContext, C: VisualContext,
@ -73,55 +73,23 @@ impl<V> Clone for View<V> {
} }
} }
impl<V: Render, ParentViewState: 'static> Component<ParentViewState> for View<V> { impl<V> Hash for View<V> {
fn render(self) -> AnyElement<ParentViewState> { fn hash<H: Hasher>(&self, state: &mut H) {
AnyElement::new(EraseViewState { self.model.hash(state);
view: self,
parent_view_state_type: PhantomData,
})
} }
} }
impl<V> Element<()> for View<V> impl<V> PartialEq for View<V> {
where fn eq(&self, other: &Self) -> bool {
V: Render, self.model == other.model
{
type ElementState = AnyElement<V>;
fn id(&self) -> Option<crate::ElementId> {
Some(ElementId::View(self.model.entity_id))
} }
}
fn initialize( impl<V> Eq for View<V> {}
&mut self,
_: &mut (),
_: Option<Self::ElementState>,
cx: &mut ViewContext<()>,
) -> Self::ElementState {
self.update(cx, |state, cx| {
let mut any_element = AnyElement::new(state.render(cx));
any_element.initialize(state, cx);
any_element
})
}
fn layout( impl<V: Render, ParentViewState: 'static> Component<ParentViewState> for View<V> {
&mut self, fn render(self) -> AnyElement<ParentViewState> {
_: &mut (), AnyElement::new(AnyView::from(self))
element: &mut Self::ElementState,
cx: &mut ViewContext<()>,
) -> LayoutId {
self.update(cx, |state, cx| element.layout(state, cx))
}
fn paint(
&mut self,
_: Bounds<Pixels>,
_: &mut (),
element: &mut Self::ElementState,
cx: &mut ViewContext<()>,
) {
self.update(cx, |state, cx| element.paint(state, cx))
} }
} }
@ -134,13 +102,17 @@ impl<V: 'static> WeakView<V> {
Entity::upgrade_from(self) Entity::upgrade_from(self)
} }
pub fn update<R>( pub fn update<C, R>(
&self, &self,
cx: &mut WindowContext, cx: &mut C,
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R, f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
) -> Result<R> { ) -> Result<R>
where
C: VisualContext,
Result<C::Result<R>>: Flatten<R>,
{
let view = self.upgrade().context("error upgrading view")?; let view = self.upgrade().context("error upgrading view")?;
Ok(view.update(cx, f)) Ok(view.update(cx, f)).flatten()
} }
} }
@ -152,115 +124,19 @@ impl<V> Clone for WeakView<V> {
} }
} }
struct EraseViewState<V, ParentV> { impl<V> Hash for WeakView<V> {
view: View<V>, fn hash<H: Hasher>(&self, state: &mut H) {
parent_view_state_type: PhantomData<ParentV>, self.model.hash(state);
}
unsafe impl<V, ParentV> Send for EraseViewState<V, ParentV> {}
impl<V: Render, ParentV: 'static> Component<ParentV> for EraseViewState<V, ParentV> {
fn render(self) -> AnyElement<ParentV> {
AnyElement::new(self)
} }
} }
impl<V: Render, ParentV: 'static> Element<ParentV> for EraseViewState<V, ParentV> { impl<V> PartialEq for WeakView<V> {
type ElementState = Box<dyn Any>; fn eq(&self, other: &Self) -> bool {
self.model == other.model
fn id(&self) -> Option<crate::ElementId> {
Element::id(&self.view)
}
fn initialize(
&mut self,
_: &mut ParentV,
_: Option<Self::ElementState>,
cx: &mut ViewContext<ParentV>,
) -> Self::ElementState {
ViewObject::initialize(&mut self.view, cx)
}
fn layout(
&mut self,
_: &mut ParentV,
element: &mut Self::ElementState,
cx: &mut ViewContext<ParentV>,
) -> LayoutId {
ViewObject::layout(&mut self.view, element, cx)
}
fn paint(
&mut self,
bounds: Bounds<Pixels>,
_: &mut ParentV,
element: &mut Self::ElementState,
cx: &mut ViewContext<ParentV>,
) {
ViewObject::paint(&mut self.view, bounds, element, cx)
} }
} }
trait ViewObject: Send + Sync { impl<V> Eq for WeakView<V> {}
fn entity_type(&self) -> TypeId;
fn entity_id(&self) -> EntityId;
fn model(&self) -> AnyModel;
fn initialize(&self, cx: &mut WindowContext) -> AnyBox;
fn layout(&self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId;
fn paint(&self, bounds: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext);
fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}
impl<V> ViewObject for View<V>
where
V: Render,
{
fn entity_type(&self) -> TypeId {
TypeId::of::<V>()
}
fn entity_id(&self) -> EntityId {
Entity::entity_id(self)
}
fn model(&self) -> AnyModel {
self.model.clone().into_any()
}
fn initialize(&self, cx: &mut WindowContext) -> AnyBox {
cx.with_element_id(ViewObject::entity_id(self), |_global_id, cx| {
self.update(cx, |state, cx| {
let mut any_element = Box::new(AnyElement::new(state.render(cx)));
any_element.initialize(state, cx);
any_element
})
})
}
fn layout(&self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId {
cx.with_element_id(ViewObject::entity_id(self), |_global_id, cx| {
self.update(cx, |state, cx| {
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
element.layout(state, cx)
})
})
}
fn paint(&self, _: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext) {
cx.with_element_id(ViewObject::entity_id(self), |_global_id, cx| {
self.update(cx, |state, cx| {
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
element.paint(state, cx);
});
});
}
fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct(&format!("AnyView<{}>", std::any::type_name::<V>()))
.field("entity_id", &ViewObject::entity_id(self).as_u64())
.finish()
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct AnyView { pub struct AnyView {
@ -292,7 +168,7 @@ impl AnyView {
} }
} }
pub(crate) fn entity_type(&self) -> TypeId { pub fn entity_type(&self) -> TypeId {
self.model.entity_type self.model.entity_type
} }

View file

@ -5,11 +5,11 @@ use crate::{
Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId, Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad,
Reference, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder,
Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine, Task, Underline, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine, Task, Underline,
UnderlineStyle, View, VisualContext, WeakModel, WeakView, WindowOptions, SUBPIXEL_VARIANTS, UnderlineStyle, View, VisualContext, WeakView, WindowOptions, SUBPIXEL_VARIANTS,
}; };
use anyhow::Result; use anyhow::{anyhow, Result};
use collections::HashMap; use collections::HashMap;
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use parking_lot::RwLock; use parking_lot::RwLock;
@ -20,6 +20,7 @@ use std::{
borrow::{Borrow, BorrowMut, Cow}, borrow::{Borrow, BorrowMut, Cow},
fmt::Debug, fmt::Debug,
future::Future, future::Future,
hash::{Hash, Hasher},
marker::PhantomData, marker::PhantomData,
mem, mem,
sync::{ sync::{
@ -156,7 +157,7 @@ impl Drop for FocusHandle {
// Holds the state for a specific window. // Holds the state for a specific window.
pub struct Window { pub struct Window {
handle: AnyWindowHandle, pub(crate) handle: AnyWindowHandle,
platform_window: Box<dyn PlatformWindow>, platform_window: Box<dyn PlatformWindow>,
display_id: DisplayId, display_id: DisplayId,
sprite_atlas: Arc<dyn PlatformAtlas>, sprite_atlas: Arc<dyn PlatformAtlas>,
@ -201,23 +202,25 @@ impl Window {
let content_size = platform_window.content_size(); let content_size = platform_window.content_size();
let scale_factor = platform_window.scale_factor(); let scale_factor = platform_window.scale_factor();
platform_window.on_resize(Box::new({ platform_window.on_resize(Box::new({
let cx = cx.to_async(); let mut cx = cx.to_async();
move |content_size, scale_factor| { move |content_size, scale_factor| {
cx.update_window(handle, |cx| { handle
cx.window.scale_factor = scale_factor; .update(&mut cx, |_, cx| {
cx.window.scene_builder = SceneBuilder::new(); cx.window.scale_factor = scale_factor;
cx.window.content_size = content_size; cx.window.scene_builder = SceneBuilder::new();
cx.window.display_id = cx.window.platform_window.display().id(); cx.window.content_size = content_size;
cx.window.dirty = true; cx.window.display_id = cx.window.platform_window.display().id();
}) cx.window.dirty = true;
.log_err(); })
.log_err();
} }
})); }));
platform_window.on_input({ platform_window.on_input({
let cx = cx.to_async(); let mut cx = cx.to_async();
Box::new(move |event| { Box::new(move |event| {
cx.update_window(handle, |cx| cx.dispatch_event(event)) handle
.update(&mut cx, |_, cx| cx.dispatch_event(event))
.log_err() .log_err()
.unwrap_or(true) .unwrap_or(true)
}) })
@ -296,24 +299,14 @@ impl ContentMask<Pixels> {
/// Provides access to application state in the context of a single window. Derefs /// Provides access to application state in the context of a single window. Derefs
/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes /// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
/// an `AppContext` and call any `AppContext` methods. /// an `AppContext` and call any `AppContext` methods.
pub struct WindowContext<'a, 'w> { pub struct WindowContext<'a> {
pub(crate) app: Reference<'a, AppContext>, pub(crate) app: &'a mut AppContext,
pub(crate) window: Reference<'w, Window>, pub(crate) window: &'a mut Window,
} }
impl<'a, 'w> WindowContext<'a, 'w> { impl<'a> WindowContext<'a> {
pub(crate) fn immutable(app: &'a AppContext, window: &'w Window) -> Self { pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
Self { Self { app, window }
app: Reference::Immutable(app),
window: Reference::Immutable(window),
}
}
pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
Self {
app: Reference::Mutable(app),
window: Reference::Mutable(window),
}
} }
/// Obtain a handle to the window that belongs to this context. /// Obtain a handle to the window that belongs to this context.
@ -345,10 +338,9 @@ impl<'a, 'w> WindowContext<'a, 'w> {
self.window.last_blur = Some(self.window.focus); self.window.last_blur = Some(self.window.focus);
} }
let window_id = self.window.handle.id;
self.window.focus = Some(handle.id); self.window.focus = Some(handle.id);
self.app.push_effect(Effect::FocusChanged { self.app.push_effect(Effect::FocusChanged {
window_id, window_handle: self.window.handle,
focused: Some(handle.id), focused: Some(handle.id),
}); });
self.notify(); self.notify();
@ -360,15 +352,53 @@ impl<'a, 'w> WindowContext<'a, 'w> {
self.window.last_blur = Some(self.window.focus); self.window.last_blur = Some(self.window.focus);
} }
let window_id = self.window.handle.id;
self.window.focus = None; self.window.focus = None;
self.app.push_effect(Effect::FocusChanged { self.app.push_effect(Effect::FocusChanged {
window_id, window_handle: self.window.handle,
focused: None, focused: None,
}); });
self.notify(); self.notify();
} }
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
/// that are currently on the stack to be returned to the app.
pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
let handle = self.window.handle;
self.app.defer(move |cx| {
handle.update(cx, |_, cx| f(cx)).ok();
});
}
pub fn subscribe<Emitter, E>(
&mut self,
entity: &E,
mut on_event: impl FnMut(E, &Emitter::Event, &mut WindowContext<'_>) + 'static,
) -> Subscription
where
Emitter: EventEmitter,
E: Entity<Emitter>,
{
let entity_id = entity.entity_id();
let entity = entity.downgrade();
let window_handle = self.window.handle;
self.app.event_listeners.insert(
entity_id,
Box::new(move |event, cx| {
window_handle
.update(cx, |_, cx| {
if let Some(handle) = E::upgrade_from(&entity) {
let event = event.downcast_ref().expect("invalid event type");
on_event(handle, event, cx);
true
} else {
false
}
})
.unwrap_or(false)
}),
)
}
/// Create an `AsyncWindowContext`, which has a static lifetime and can be held across /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
/// await points in async code. /// await points in async code.
pub fn to_async(&self) -> AsyncWindowContext { pub fn to_async(&self) -> AsyncWindowContext {
@ -376,7 +406,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
} }
/// Schedule the given closure to be run directly after the current frame is rendered. /// Schedule the given closure to be run directly after the current frame is rendered.
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) { pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
let f = Box::new(f); let f = Box::new(f);
let display_id = self.window.display_id; let display_id = self.window.display_id;
@ -387,12 +417,12 @@ impl<'a, 'w> WindowContext<'a, 'w> {
return; return;
} }
} else { } else {
let async_cx = self.to_async(); let mut async_cx = self.to_async();
self.next_frame_callbacks.insert(display_id, vec![f]); self.next_frame_callbacks.insert(display_id, vec![f]);
self.platform().set_display_link_output_callback( self.platform().set_display_link_output_callback(
display_id, display_id,
Box::new(move |_current_time, _output_time| { Box::new(move |_current_time, _output_time| {
let _ = async_cx.update(|cx| { let _ = async_cx.update(|_, cx| {
let callbacks = cx let callbacks = cx
.next_frame_callbacks .next_frame_callbacks
.get_mut(&display_id) .get_mut(&display_id)
@ -1114,12 +1144,12 @@ impl<'a, 'w> WindowContext<'a, 'w> {
/// is updated. /// is updated.
pub fn observe_global<G: 'static>( pub fn observe_global<G: 'static>(
&mut self, &mut self,
f: impl Fn(&mut WindowContext<'_, '_>) + Send + 'static, f: impl Fn(&mut WindowContext<'_>) + 'static,
) -> Subscription { ) -> Subscription {
let window_id = self.window.handle.id; let window_handle = self.window.handle;
self.global_observers.insert( self.global_observers.insert(
TypeId::of::<G>(), TypeId::of::<G>(),
Box::new(move |cx| cx.update_window(window_id, |cx| f(cx)).is_ok()), Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
) )
} }
@ -1202,43 +1232,52 @@ impl<'a, 'w> WindowContext<'a, 'w> {
} }
} }
impl Context for WindowContext<'_, '_> { impl Context for WindowContext<'_> {
type ModelContext<'a, T> = ModelContext<'a, T>;
type Result<T> = T; type Result<T> = T;
fn build_model<T>( fn build_model<T>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Model<T> ) -> Model<T>
where where
T: 'static, T: 'static,
{ {
let slot = self.app.entities.reserve(); let slot = self.app.entities.reserve();
let model = build_model(&mut ModelContext::mutable(&mut *self.app, slot.downgrade())); let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
self.entities.insert(slot, model) self.entities.insert(slot, model)
} }
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
model: &Model<T>, model: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> R { ) -> R {
let mut entity = self.entities.lease(model); let mut entity = self.entities.lease(model);
let result = update( let result = update(
&mut *entity, &mut *entity,
&mut ModelContext::mutable(&mut *self.app, model.downgrade()), &mut ModelContext::new(&mut *self.app, model.downgrade()),
); );
self.entities.end_lease(entity); self.entities.end_lease(entity);
result result
} }
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
{
if window == self.window.handle {
let root_view = self.window.root_view.clone().unwrap();
Ok(update(root_view, self))
} else {
window.update(self.app, update)
}
}
} }
impl VisualContext for WindowContext<'_, '_> { impl VisualContext for WindowContext<'_> {
type ViewContext<'a, 'w, V> = ViewContext<'a, 'w, V>;
fn build_view<V>( fn build_view<V>(
&mut self, &mut self,
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V, build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
) -> Self::Result<View<V>> ) -> Self::Result<View<V>>
where where
V: 'static, V: 'static,
@ -1247,7 +1286,7 @@ impl VisualContext for WindowContext<'_, '_> {
let view = View { let view = View {
model: slot.clone(), model: slot.clone(),
}; };
let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade()); let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
let entity = build_view_state(&mut cx); let entity = build_view_state(&mut cx);
self.entities.insert(slot, entity); self.entities.insert(slot, entity);
view view
@ -1257,17 +1296,35 @@ impl VisualContext for WindowContext<'_, '_> {
fn update_view<T: 'static, R>( fn update_view<T: 'static, R>(
&mut self, &mut self,
view: &View<T>, view: &View<T>,
update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, '_, T>) -> R, update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
) -> Self::Result<R> { ) -> Self::Result<R> {
let mut lease = self.app.entities.lease(&view.model); let mut lease = self.app.entities.lease(&view.model);
let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade()); let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
let result = update(&mut *lease, &mut cx); let result = update(&mut *lease, &mut cx);
cx.app.entities.end_lease(lease); cx.app.entities.end_lease(lease);
result result
} }
fn replace_root_view<V>(
&mut self,
build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
) -> Self::Result<View<V>>
where
V: Render,
{
let slot = self.app.entities.reserve();
let view = View {
model: slot.clone(),
};
let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
let entity = build_view(&mut cx);
self.entities.insert(slot, entity);
self.window.root_view = Some(view.clone().into());
view
}
} }
impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> { impl<'a> std::ops::Deref for WindowContext<'a> {
type Target = AppContext; type Target = AppContext;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@ -1275,19 +1332,19 @@ impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
} }
} }
impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> { impl<'a> std::ops::DerefMut for WindowContext<'a> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.app &mut self.app
} }
} }
impl<'a, 'w> Borrow<AppContext> for WindowContext<'a, 'w> { impl<'a> Borrow<AppContext> for WindowContext<'a> {
fn borrow(&self) -> &AppContext { fn borrow(&self) -> &AppContext {
&self.app &self.app
} }
} }
impl<'a, 'w> BorrowMut<AppContext> for WindowContext<'a, 'w> { impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
fn borrow_mut(&mut self) -> &mut AppContext { fn borrow_mut(&mut self) -> &mut AppContext {
&mut self.app &mut self.app
} }
@ -1455,13 +1512,13 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
} }
} }
impl Borrow<Window> for WindowContext<'_, '_> { impl Borrow<Window> for WindowContext<'_> {
fn borrow(&self) -> &Window { fn borrow(&self) -> &Window {
&self.window &self.window
} }
} }
impl BorrowMut<Window> for WindowContext<'_, '_> { impl BorrowMut<Window> for WindowContext<'_> {
fn borrow_mut(&mut self) -> &mut Window { fn borrow_mut(&mut self) -> &mut Window {
&mut self.window &mut self.window
} }
@ -1469,52 +1526,48 @@ impl BorrowMut<Window> for WindowContext<'_, '_> {
impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {} impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
pub struct ViewContext<'a, 'w, V> { pub struct ViewContext<'a, V> {
window_cx: WindowContext<'a, 'w>, window_cx: WindowContext<'a>,
view: WeakView<V>, view: &'a View<V>,
} }
impl<V> Borrow<AppContext> for ViewContext<'_, '_, V> { impl<V> Borrow<AppContext> for ViewContext<'_, V> {
fn borrow(&self) -> &AppContext { fn borrow(&self) -> &AppContext {
&*self.window_cx.app &*self.window_cx.app
} }
} }
impl<V> BorrowMut<AppContext> for ViewContext<'_, '_, V> { impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
fn borrow_mut(&mut self) -> &mut AppContext { fn borrow_mut(&mut self) -> &mut AppContext {
&mut *self.window_cx.app &mut *self.window_cx.app
} }
} }
impl<V> Borrow<Window> for ViewContext<'_, '_, V> { impl<V> Borrow<Window> for ViewContext<'_, V> {
fn borrow(&self) -> &Window { fn borrow(&self) -> &Window {
&*self.window_cx.window &*self.window_cx.window
} }
} }
impl<V> BorrowMut<Window> for ViewContext<'_, '_, V> { impl<V> BorrowMut<Window> for ViewContext<'_, V> {
fn borrow_mut(&mut self) -> &mut Window { fn borrow_mut(&mut self) -> &mut Window {
&mut *self.window_cx.window &mut *self.window_cx.window
} }
} }
impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> { impl<'a, V: 'static> ViewContext<'a, V> {
pub(crate) fn mutable( pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
app: &'a mut AppContext,
window: &'w mut Window,
view: WeakView<V>,
) -> Self {
Self { Self {
window_cx: WindowContext::mutable(app, window), window_cx: WindowContext::new(app, window),
view, view,
} }
} }
pub fn view(&self) -> WeakView<V> { pub fn view(&self) -> View<V> {
self.view.clone() self.view.clone()
} }
pub fn model(&self) -> WeakModel<V> { pub fn model(&self) -> Model<V> {
self.view.model.clone() self.view.model.clone()
} }
@ -1525,40 +1578,50 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
result result
} }
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static) pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
where where
V: Any + Send, V: 'static,
{ {
let view = self.view().upgrade().unwrap(); let view = self.view();
self.window_cx.on_next_frame(move |cx| view.update(cx, f)); self.window_cx.on_next_frame(move |cx| view.update(cx, f));
} }
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
/// that are currently on the stack to be returned to the app.
pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
let view = self.view().downgrade();
self.window_cx.defer(move |cx| {
view.update(cx, f).ok();
});
}
pub fn observe<V2, E>( pub fn observe<V2, E>(
&mut self, &mut self,
entity: &E, entity: &E,
mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, '_, V>) + Send + 'static, mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
) -> Subscription ) -> Subscription
where where
V2: 'static, V2: 'static,
V: Any + Send, V: 'static,
E: Entity<V2>, E: Entity<V2>,
{ {
let view = self.view(); let view = self.view().downgrade();
let entity_id = entity.entity_id(); let entity_id = entity.entity_id();
let entity = entity.downgrade(); let entity = entity.downgrade();
let window_handle = self.window.handle; let window_handle = self.window.handle;
self.app.observers.insert( self.app.observers.insert(
entity_id, entity_id,
Box::new(move |cx| { Box::new(move |cx| {
cx.update_window(window_handle.id, |cx| { window_handle
if let Some(handle) = E::upgrade_from(&entity) { .update(cx, |_, cx| {
view.update(cx, |this, cx| on_notify(this, handle, cx)) if let Some(handle) = E::upgrade_from(&entity) {
.is_ok() view.update(cx, |this, cx| on_notify(this, handle, cx))
} else { .is_ok()
false } else {
} false
}) }
.unwrap_or(false) })
.unwrap_or(false)
}), }),
) )
} }
@ -1566,44 +1629,44 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
pub fn subscribe<V2, E>( pub fn subscribe<V2, E>(
&mut self, &mut self,
entity: &E, entity: &E,
mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, '_, V>) + Send + 'static, mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
) -> Subscription ) -> Subscription
where where
V2: EventEmitter, V2: EventEmitter,
E: Entity<V2>, E: Entity<V2>,
{ {
let view = self.view(); let view = self.view().downgrade();
let entity_id = entity.entity_id(); let entity_id = entity.entity_id();
let handle = entity.downgrade(); let handle = entity.downgrade();
let window_handle = self.window.handle; let window_handle = self.window.handle;
self.app.event_listeners.insert( self.app.event_listeners.insert(
entity_id, entity_id,
Box::new(move |event, cx| { Box::new(move |event, cx| {
cx.update_window(window_handle.id, |cx| { window_handle
if let Some(handle) = E::upgrade_from(&handle) { .update(cx, |_, cx| {
let event = event.downcast_ref().expect("invalid event type"); if let Some(handle) = E::upgrade_from(&handle) {
view.update(cx, |this, cx| on_event(this, handle, event, cx)) let event = event.downcast_ref().expect("invalid event type");
.is_ok() view.update(cx, |this, cx| on_event(this, handle, event, cx))
} else { .is_ok()
false } else {
} false
}) }
.unwrap_or(false) })
.unwrap_or(false)
}), }),
) )
} }
pub fn on_release( pub fn on_release(
&mut self, &mut self,
mut on_release: impl FnMut(&mut V, &mut WindowContext) + Send + 'static, on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
) -> Subscription { ) -> Subscription {
let window_handle = self.window.handle; let window_handle = self.window.handle;
self.app.release_listeners.insert( self.app.release_listeners.insert(
self.view.model.entity_id, self.view.model.entity_id,
Box::new(move |this, cx| { Box::new(move |this, cx| {
let this = this.downcast_mut().expect("invalid entity type"); let this = this.downcast_mut().expect("invalid entity type");
// todo!("are we okay with silently swallowing the error?") let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
let _ = cx.update_window(window_handle.id, |cx| on_release(this, cx));
}), }),
) )
} }
@ -1611,21 +1674,21 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
pub fn observe_release<V2, E>( pub fn observe_release<V2, E>(
&mut self, &mut self,
entity: &E, entity: &E,
mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, '_, V>) + Send + 'static, mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
) -> Subscription ) -> Subscription
where where
V: Any + Send, V: 'static,
V2: 'static, V2: 'static,
E: Entity<V2>, E: Entity<V2>,
{ {
let view = self.view(); let view = self.view().downgrade();
let entity_id = entity.entity_id(); let entity_id = entity.entity_id();
let window_handle = self.window.handle; let window_handle = self.window.handle;
self.app.release_listeners.insert( self.app.release_listeners.insert(
entity_id, entity_id,
Box::new(move |entity, cx| { Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type"); let entity = entity.downcast_mut().expect("invalid entity type");
let _ = cx.update_window(window_handle.id, |cx| { let _ = window_handle.update(cx, |_, cx| {
view.update(cx, |this, cx| on_release(this, entity, cx)) view.update(cx, |this, cx| on_release(this, entity, cx))
}); });
}), }),
@ -1641,9 +1704,9 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
pub fn on_focus_changed( pub fn on_focus_changed(
&mut self, &mut self,
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
) { ) {
let handle = self.view(); let handle = self.view().downgrade();
self.window.focus_listeners.push(Box::new(move |event, cx| { self.window.focus_listeners.push(Box::new(move |event, cx| {
handle handle
.update(cx, |view, cx| listener(view, event, cx)) .update(cx, |view, cx| listener(view, event, cx))
@ -1659,12 +1722,12 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
let old_stack_len = self.window.key_dispatch_stack.len(); let old_stack_len = self.window.key_dispatch_stack.len();
if !self.window.freeze_key_dispatch_stack { if !self.window.freeze_key_dispatch_stack {
for (event_type, listener) in key_listeners { for (event_type, listener) in key_listeners {
let handle = self.view(); let handle = self.view().downgrade();
let listener = Box::new( let listener = Box::new(
move |event: &dyn Any, move |event: &dyn Any,
context_stack: &[&DispatchContext], context_stack: &[&DispatchContext],
phase: DispatchPhase, phase: DispatchPhase,
cx: &mut WindowContext<'_, '_>| { cx: &mut WindowContext<'_>| {
handle handle
.update(cx, |view, cx| { .update(cx, |view, cx| {
listener(view, event, context_stack, phase, cx) listener(view, event, context_stack, phase, cx)
@ -1745,16 +1808,13 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
R: 'static, R: 'static,
Fut: Future<Output = R> + 'static, Fut: Future<Output = R> + 'static,
{ {
let view = self.view(); let view = self.view().downgrade();
self.window_cx.spawn(move |_, cx| { self.window_cx.spawn(move |_, cx| f(view, cx))
let result = f(view, cx);
async move { result.await }
})
} }
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
where where
G: 'static + Send, G: 'static,
{ {
let mut global = self.app.lease_global::<G>(); let mut global = self.app.lease_global::<G>();
let result = f(&mut global, self); let result = f(&mut global, self);
@ -1764,17 +1824,16 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
pub fn observe_global<G: 'static>( pub fn observe_global<G: 'static>(
&mut self, &mut self,
f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + 'static, f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
) -> Subscription { ) -> Subscription {
let window_id = self.window.handle.id; let window_handle = self.window.handle;
let handle = self.view(); let view = self.view().downgrade();
self.global_observers.insert( self.global_observers.insert(
TypeId::of::<G>(), TypeId::of::<G>(),
Box::new(move |cx| { Box::new(move |cx| {
cx.update_window(window_id, |cx| { window_handle
handle.update(cx, |view, cx| f(view, cx)).is_ok() .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
}) .unwrap_or(false)
.unwrap_or(false)
}), }),
) )
} }
@ -1783,7 +1842,7 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
&mut self, &mut self,
handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static, handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
) { ) {
let handle = self.view().upgrade().unwrap(); let handle = self.view();
self.window_cx.on_mouse_event(move |event, phase, cx| { self.window_cx.on_mouse_event(move |event, phase, cx| {
handle.update(cx, |view, cx| { handle.update(cx, |view, cx| {
handler(view, event, phase, cx); handler(view, event, phase, cx);
@ -1792,10 +1851,10 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
} }
} }
impl<'a, 'w, V> ViewContext<'a, 'w, V> impl<V> ViewContext<'_, V>
where where
V: EventEmitter, V: EventEmitter,
V::Event: Any + Send, V::Event: 'static,
{ {
pub fn emit(&mut self, event: V::Event) { pub fn emit(&mut self, event: V::Event) {
let emitter = self.view.model.entity_id; let emitter = self.view.model.entity_id;
@ -1806,13 +1865,12 @@ where
} }
} }
impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> { impl<V> Context for ViewContext<'_, V> {
type ModelContext<'b, U> = ModelContext<'b, U>;
type Result<U> = U; type Result<U> = U;
fn build_model<T: 'static>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
) -> Model<T> { ) -> Model<T> {
self.window_cx.build_model(build_model) self.window_cx.build_model(build_model)
} }
@ -1820,18 +1878,23 @@ impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
model: &Model<T>, model: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
) -> R { ) -> R {
self.window_cx.update_model(model, update) self.window_cx.update_model(model, update)
} }
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
where
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
{
self.window_cx.update_window(window, update)
}
} }
impl<V: 'static> VisualContext for ViewContext<'_, '_, V> { impl<V: 'static> VisualContext for ViewContext<'_, V> {
type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;
fn build_view<W: 'static>( fn build_view<W: 'static>(
&mut self, &mut self,
build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W, build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
) -> Self::Result<View<W>> { ) -> Self::Result<View<W>> {
self.window_cx.build_view(build_view) self.window_cx.build_view(build_view)
} }
@ -1839,21 +1902,31 @@ impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {
fn update_view<V2: 'static, R>( fn update_view<V2: 'static, R>(
&mut self, &mut self,
view: &View<V2>, view: &View<V2>,
update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, '_, V2>) -> R, update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
) -> Self::Result<R> { ) -> Self::Result<R> {
self.window_cx.update_view(view, update) self.window_cx.update_view(view, update)
} }
fn replace_root_view<W>(
&mut self,
build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
) -> Self::Result<View<W>>
where
W: Render,
{
self.window_cx.replace_root_view(build_view)
}
} }
impl<'a, 'w, V> std::ops::Deref for ViewContext<'a, 'w, V> { impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
type Target = WindowContext<'a, 'w>; type Target = WindowContext<'a>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.window_cx &self.window_cx
} }
} }
impl<'a, 'w, V> std::ops::DerefMut for ViewContext<'a, 'w, V> { impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.window_cx &mut self.window_cx
} }
@ -1868,42 +1941,74 @@ impl WindowId {
} }
} }
#[derive(PartialEq, Eq)] #[derive(Deref, DerefMut)]
pub struct WindowHandle<V> { pub struct WindowHandle<V> {
id: WindowId, #[deref]
#[deref_mut]
pub(crate) any_handle: AnyWindowHandle,
state_type: PhantomData<V>, state_type: PhantomData<V>,
} }
impl<S> Copy for WindowHandle<S> {} impl<V: 'static + Render> WindowHandle<V> {
impl<S> Clone for WindowHandle<S> {
fn clone(&self) -> Self {
WindowHandle {
id: self.id,
state_type: PhantomData,
}
}
}
impl<S> WindowHandle<S> {
pub fn new(id: WindowId) -> Self { pub fn new(id: WindowId) -> Self {
WindowHandle { WindowHandle {
id, any_handle: AnyWindowHandle {
id,
state_type: TypeId::of::<V>(),
},
state_type: PhantomData,
}
}
pub fn update<C, R>(
self,
cx: &mut C,
update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
) -> Result<R>
where
C: Context,
{
cx.update_window(self.any_handle, |root_view, cx| {
let view = root_view
.downcast::<V>()
.map_err(|_| anyhow!("the type of the window's root view has changed"))?;
Ok(cx.update_view(&view, update))
})?
}
}
impl<V> Copy for WindowHandle<V> {}
impl<V> Clone for WindowHandle<V> {
fn clone(&self) -> Self {
WindowHandle {
any_handle: self.any_handle,
state_type: PhantomData, state_type: PhantomData,
} }
} }
} }
impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> { impl<V> PartialEq for WindowHandle<V> {
fn into(self) -> AnyWindowHandle { fn eq(&self, other: &Self) -> bool {
AnyWindowHandle { self.any_handle == other.any_handle
id: self.id,
state_type: TypeId::of::<S>(),
}
} }
} }
#[derive(Copy, Clone, PartialEq, Eq)] impl<V> Eq for WindowHandle<V> {}
impl<V> Hash for WindowHandle<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.any_handle.hash(state);
}
}
impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
fn into(self) -> AnyWindowHandle {
self.any_handle
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct AnyWindowHandle { pub struct AnyWindowHandle {
pub(crate) id: WindowId, pub(crate) id: WindowId,
state_type: TypeId, state_type: TypeId,
@ -1913,6 +2018,28 @@ impl AnyWindowHandle {
pub fn window_id(&self) -> WindowId { pub fn window_id(&self) -> WindowId {
self.id self.id
} }
pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
if TypeId::of::<T>() == self.state_type {
Some(WindowHandle {
any_handle: *self,
state_type: PhantomData,
})
} else {
None
}
}
pub fn update<C, R>(
self,
cx: &mut C,
update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
) -> Result<R>
where
C: Context,
{
cx.update_window(self, update)
}
} }
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]