Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Remove more Send bounds and simplify view rendering
Antonio Scandurra64ad8943ba69
diff --git a/crates/gpui2/src/action.rs b/crates/gpui2/src/action.rsindex 638e5c6ca3c..84843c98762 100644--- a/crates/gpui2/src/action.rs+++ b/crates/gpui2/src/action.rs@@ -4,7 +4,7 @@ use collections::{HashMap, HashSet};use serde::Deserialize;use std::any::{type_name, Any};-pub trait Action: Any + Send {+pub trait Action: 'static {fn qualified_name() -> SharedStringwhereSelf: Sized;@@ -19,7 +19,7 @@ pub trait Action: Any + Send {impl<A> Action for Awhere- A: for<'a> Deserialize<'a> + PartialEq + Any + Send + Clone + Default,+ A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + 'static,{fn qualified_name() -> SharedString {type_name::<A>().into()diff --git a/crates/gpui2/src/app.rs b/crates/gpui2/src/app.rsindex 265ce59a023..48a9324b059 100644--- a/crates/gpui2/src/app.rs+++ b/crates/gpui2/src/app.rs@@ -13,11 +13,12 @@ use smallvec::SmallVec;pub use test_context::*;use crate::{- current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource,- BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId, FocusEvent, FocusHandle,- FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId, Pixels, Platform, Point, Render,- SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,- TextSystem, View, Window, WindowContext, WindowHandle, WindowId,+ current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AnyWindowHandle,+ AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,+ Entity, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId,+ Pixels, Platform, Point, Render, SharedString, SubscriberSet, Subscription, SvgRenderer, Task,+ TextStyle, TextStyleRefinement, TextSystem, View, Window, WindowContext, WindowHandle,+ WindowId,};use anyhow::{anyhow, Result};use collections::{HashMap, HashSet, VecDeque};@@ -114,8 +115,8 @@ type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dtype FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;type Handler = Box<dyn FnMut(&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 ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + 'static>;+type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;+type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;pub struct AppContext {this: Weak<RefCell<AppContext>>,@@ -214,10 +215,9 @@ impl AppContext {pub fn quit(&mut self) {let mut futures = Vec::new();- self.quit_observers.clone().retain(&(), |observer| {+ for observer in self.quit_observers.remove(&()) {futures.push(observer(self));- true- });+ }self.windows.clear();self.flush_effects();@@ -255,37 +255,31 @@ impl AppContext {result}- pub(crate) fn read_window<R>(- &self,- id: WindowId,- read: impl FnOnce(&WindowContext) -> R,- ) -> Result<R> {- let window = self- .windows- .get(id)- .ok_or_else(|| anyhow!("window not found"))?- .as_ref()- .unwrap();- Ok(read(&WindowContext::immutable(self, &window)))+ pub fn windows(&self) -> Vec<AnyWindowHandle> {+ self.windows+ .values()+ .filter_map(|window| Some(window.as_ref()?.handle.clone()))+ .collect()}pub(crate) fn update_window<R>(&mut self,- id: WindowId,- update: impl FnOnce(&mut WindowContext) -> R,+ handle: AnyWindowHandle,+ update: impl FnOnce(AnyView, &mut WindowContext) -> R,) -> Result<R> {self.update(|cx| {let mut window = cx.windows- .get_mut(id)+ .get_mut(handle.id).ok_or_else(|| anyhow!("window not found"))?.take().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- .get_mut(id)+ .get_mut(handle.id).ok_or_else(|| anyhow!("window not found"))?.replace(window);@@ -305,7 +299,7 @@ impl AppContext {let id = cx.windows.insert(None);let handle = WindowHandle::new(id);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());cx.windows.get_mut(id).unwrap().replace(window);handle@@ -386,8 +380,11 @@ impl AppContext {self.apply_notify_effect(emitter);}Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),- Effect::FocusChanged { window_id, focused } => {- self.apply_focus_changed_effect(window_id, focused);+ Effect::FocusChanged {+ window_handle,+ focused,+ } => {+ self.apply_focus_changed_effect(window_handle, focused);}Effect::Refresh => {self.apply_refresh_effect();@@ -407,18 +404,18 @@ impl AppContext {let dirty_window_ids = self.windows.iter()- .filter_map(|(window_id, window)| {+ .filter_map(|(_, window)| {let window = window.as_ref().unwrap();if window.dirty {- Some(window_id)+ Some(window.handle.clone())} else {None}}).collect::<SmallVec<[_; 8]>>();- for dirty_window_id in dirty_window_ids {- self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();+ for dirty_window_handle in dirty_window_ids {+ dirty_window_handle.update(self, |_, cx| cx.draw()).unwrap();}}@@ -435,7 +432,7 @@ impl AppContext {for (entity_id, mut entity) in dropped {self.observers.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);}}@@ -446,27 +443,27 @@ impl AppContext {/// 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.fn release_dropped_focus_handles(&mut self) {- let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();- for window_id in window_ids {- self.update_window(window_id, |cx| {- let mut blur_window = false;- let focus = cx.window.focus;- cx.window.focus_handles.write().retain(|handle_id, count| {- if count.load(SeqCst) == 0 {- if focus == Some(handle_id) {- blur_window = true;+ for window_handle in self.windows() {+ window_handle+ .update(self, |_, cx| {+ let mut blur_window = false;+ let focus = cx.window.focus;+ cx.window.focus_handles.write().retain(|handle_id, count| {+ if count.load(SeqCst) == 0 {+ if focus == Some(handle_id) {+ blur_window = true;+ }+ false+ } else {+ true}- false- } else {- true- }- });+ });- if blur_window {- cx.blur();- }- })- .unwrap();+ if blur_window {+ cx.blur();+ }+ })+ .unwrap();}}@@ -483,30 +480,35 @@ impl AppContext {.retain(&emitter, |handler| handler(event.as_ref(), self));}- fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) {- self.update_window(window_id, |cx| {- if cx.window.focus == focused {- let mut listeners = mem::take(&mut cx.window.focus_listeners);- let focused =- focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());- let blurred = cx- .window- .last_blur- .take()- .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);+ fn apply_focus_changed_effect(+ &mut self,+ window_handle: AnyWindowHandle,+ focused: Option<FocusId>,+ ) {+ window_handle+ .update(self, |_, cx| {+ if cx.window.focus == focused {+ let mut listeners = mem::take(&mut cx.window.focus_listeners);+ let focused = focused+ .map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());+ let blurred = cx+ .window+ .last_blur+ .take()+ .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(..));- cx.window.focus_listeners = listeners;- }- })- .ok();+ listeners.extend(cx.window.focus_listeners.drain(..));+ cx.window.focus_listeners = listeners;+ }+ })+ .ok();}fn apply_refresh_effect(&mut self) {@@ -680,6 +682,24 @@ impl AppContext {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) {self.text_style_stack.push(text_style);}@@ -733,7 +753,6 @@ impl AppContext {}impl Context for AppContext {- type ModelContext<'a, T> = ModelContext<'a, T>;type Result<T> = T;/// 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.fn build_model<T: 'static>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Model<T> {self.update(|cx| {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)})}@@ -755,18 +774,38 @@ impl Context for AppContext {fn update_model<T: 'static, R>(&mut self,model: &Model<T>,- update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,+ update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,) -> R {self.update(|cx| {let mut entity = cx.entities.lease(model);- let result = update(- &mut entity,- &mut ModelContext::mutable(cx, model.downgrade()),- );+ let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));cx.entities.end_lease(entity);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.@@ -779,7 +818,7 @@ pub(crate) enum Effect {event: Box<dyn Any>,},FocusChanged {- window_id: WindowId,+ window_handle: AnyWindowHandle,focused: Option<FocusId>,},Refresh,diff --git a/crates/gpui2/src/app/async_context.rs b/crates/gpui2/src/app/async_context.rsindex fb941b91b8c..01af7ae1943 100644--- a/crates/gpui2/src/app/async_context.rs+++ b/crates/gpui2/src/app/async_context.rs@@ -1,8 +1,8 @@use crate::{- AnyWindowHandle, AppContext, BackgroundExecutor, Context, ForegroundExecutor, Model,- ModelContext, Result, Task, WindowContext,+ AnyView, AnyWindowHandle, AppContext, BackgroundExecutor, Context, ForegroundExecutor, Model,+ ModelContext, Render, Result, Task, View, ViewContext, VisualContext, WindowContext,};-use anyhow::anyhow;+use anyhow::{anyhow, Context as _};use derive_more::{Deref, DerefMut};use std::{cell::RefCell, future::Future, rc::Weak};@@ -14,12 +14,11 @@ pub struct AsyncAppContext {}impl Context for AsyncAppContext {- type ModelContext<'a, T> = ModelContext<'a, T>;type Result<T> = Result<T>;fn build_model<T: 'static>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Self::Result<Model<T>>whereT: 'static,@@ -35,7 +34,7 @@ impl Context for AsyncAppContext {fn update_model<T: 'static, R>(&mut self,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> {let app = self.app@@ -44,6 +43,15 @@ impl Context for AsyncAppContext {let mut app = app.borrow_mut();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 {@@ -74,30 +82,17 @@ impl AsyncAppContext {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>(&self,handle: AnyWindowHandle,- update: impl FnOnce(&mut WindowContext) -> R,+ update: impl FnOnce(AnyView, &mut WindowContext) -> R,) -> Result<R> {let app = self.app.upgrade().ok_or_else(|| anyhow!("app was released"))?;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>@@ -161,22 +156,22 @@ impl AsyncWindowContext {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)}- pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {- self.app- .update_window(self.window, |cx| cx.on_next_frame(f))- .ok();+ pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {+ self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();}pub fn read_global<G: 'static, R>(- &self,+ &mut self,read: impl FnOnce(&G, &WindowContext) -> R,) -> Result<R> {- self.app- .read_window(self.window, |cx| read(cx.global(), cx))+ self.window.update(self, |_, cx| read(cx.global(), cx))}pub fn update_global<G, R>(@@ -186,32 +181,79 @@ impl AsyncWindowContext {whereG: 'static,{- self.app- .update_window(self.window, |cx| cx.update_global(update))+ self.window.update(self, |_, 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 {- type ModelContext<'a, T> = ModelContext<'a, T>;type Result<T> = Result<T>;fn build_model<T>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Result<Model<T>>whereT: 'static,{- self.app- .update_window(self.window, |cx| cx.build_model(build_model))+ self.window+ .update(self, |_, cx| cx.build_model(build_model))}fn update_model<T: 'static, R>(&mut self,handle: &Model<T>,- update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,+ update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,) -> Result<R> {- self.app- .update_window(self.window, |cx| cx.update_model(handle, update))+ self.window+ .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))}}diff --git a/crates/gpui2/src/app/entity_map.rs b/crates/gpui2/src/app/entity_map.rsindex 4a4b178e1e0..e626f8c409d 100644--- a/crates/gpui2/src/app/entity_map.rs+++ b/crates/gpui2/src/app/entity_map.rs@@ -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 derive_more::{Deref, DerefMut};use parking_lot::{RwLock, RwLockUpgradableReadGuard};@@ -169,6 +169,10 @@ impl AnyModel {self.entity_id}+ pub fn entity_type(&self) -> TypeId {+ self.entity_type+ }+pub fn downgrade(&self) -> AnyWeakModel {AnyWeakModel {entity_id: self.entity_id,@@ -329,7 +333,7 @@ impl<T: 'static> Model<T> {pub fn update<C, R>(&self,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>whereC: Context,@@ -475,7 +479,7 @@ impl<T: 'static> WeakModel<T> {pub fn update<C, R>(&self,cx: &mut C,- update: impl FnOnce(&mut T, &mut C::ModelContext<'_, T>) -> R,+ update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,) -> Result<R>whereC: Context,diff --git a/crates/gpui2/src/app/model_context.rs b/crates/gpui2/src/app/model_context.rsindex f6982cdc1ff..cb25adfb634 100644--- a/crates/gpui2/src/app/model_context.rs+++ b/crates/gpui2/src/app/model_context.rs@@ -1,7 +1,8 @@use crate::{- AppContext, AsyncAppContext, Context, Effect, Entity, EntityId, EventEmitter, Model, Reference,- Subscription, Task, WeakModel,+ AnyView, AnyWindowHandle, AppContext, AsyncAppContext, Context, Effect, Entity, EntityId,+ EventEmitter, Model, Subscription, Task, WeakModel, WindowContext,};+use anyhow::Result;use derive_more::{Deref, DerefMut};use futures::FutureExt;use std::{@@ -14,16 +15,13 @@ use std::{pub struct ModelContext<'a, T> {#[deref]#[deref_mut]- app: Reference<'a, AppContext>,+ app: &'a mut AppContext,model_state: WeakModel<T>,}impl<'a, T: 'static> ModelContext<'a, T> {- pub(crate) fn mutable(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self {- Self {- app: Reference::Mutable(app),- model_state,- }+ pub(crate) fn new(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self {+ Self { app, model_state }}pub fn entity_id(&self) -> EntityId {@@ -95,7 +93,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {pub fn on_release(&mut self,- mut on_release: impl FnMut(&mut T, &mut AppContext) + 'static,+ on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,) -> SubscriptionwhereT: 'static,@@ -112,7 +110,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {pub fn observe_release<T2, E>(&mut self,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,) -> SubscriptionwhereT: Any,@@ -215,12 +213,11 @@ where}impl<'a, T> Context for ModelContext<'a, T> {- type ModelContext<'b, U> = ModelContext<'b, U>;type Result<U> = U;fn build_model<U: 'static>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, U>) -> U,+ build_model: impl FnOnce(&mut ModelContext<'_, U>) -> U,) -> Model<U> {self.app.build_model(build_model)}@@ -228,10 +225,17 @@ impl<'a, T> Context for ModelContext<'a, T> {fn update_model<U: 'static, R>(&mut self,handle: &Model<U>,- update: impl FnOnce(&mut U, &mut Self::ModelContext<'_, U>) -> R,+ update: impl FnOnce(&mut U, &mut ModelContext<'_, U>) -> R,) -> R {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> {diff --git a/crates/gpui2/src/app/test_context.rs b/crates/gpui2/src/app/test_context.rsindex 6affabdd238..27275d3a044 100644--- a/crates/gpui2/src/app/test_context.rs+++ b/crates/gpui2/src/app/test_context.rs@@ -1,7 +1,7 @@use crate::{- AnyWindowHandle, AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter,- ForegroundExecutor, Model, ModelContext, Result, Task, TestDispatcher, TestPlatform,- WindowContext,+ AnyView, AnyWindowHandle, AppContext, AsyncAppContext, BackgroundExecutor, Context,+ EventEmitter, ForegroundExecutor, Model, ModelContext, Result, Task, TestDispatcher,+ TestPlatform, WindowContext,};use anyhow::{anyhow, bail};use futures::{Stream, StreamExt};@@ -15,12 +15,11 @@ pub struct TestAppContext {}impl Context for TestAppContext {- type ModelContext<'a, T> = ModelContext<'a, T>;type Result<T> = T;fn build_model<T: 'static>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Self::Result<Model<T>>whereT: 'static,@@ -32,11 +31,19 @@ impl Context for TestAppContext {fn update_model<T: 'static, R>(&mut self,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> {let mut app = self.app.borrow_mut();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 {@@ -80,22 +87,13 @@ impl TestAppContext {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>(&self,handle: AnyWindowHandle,- update: impl FnOnce(&mut WindowContext) -> R,+ update: impl FnOnce(AnyView, &mut WindowContext) -> R,) -> R {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>diff --git a/crates/gpui2/src/assets.rs b/crates/gpui2/src/assets.rsindex 39c8562b697..baf75b8aabc 100644--- a/crates/gpui2/src/assets.rs+++ b/crates/gpui2/src/assets.rs@@ -8,7 +8,7 @@ use std::{sync::atomic::{AtomicUsize, Ordering::SeqCst},};-pub trait AssetSource: 'static + Send + Sync {+pub trait AssetSource: 'static {fn load(&self, path: &str) -> Result<Cow<[u8]>>;fn list(&self, path: &str) -> Result<Vec<SharedString>>;}diff --git a/crates/gpui2/src/element.rs b/crates/gpui2/src/element.rsindex e41dc4ebd54..4890b79a9ac 100644--- a/crates/gpui2/src/element.rs+++ b/crates/gpui2/src/element.rs@@ -219,7 +219,7 @@ impl<V, E, F> Element<V> for Option<F>whereV: 'static,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>;@@ -263,7 +263,7 @@ impl<V, E, F> Component<V> for Option<F>whereV: 'static,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> {AnyElement::new(self)@@ -274,7 +274,7 @@ impl<V, E, F> Component<V> for FwhereV: 'static,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> {AnyElement::new(Some(self))diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rsindex 6fe10d94a31..56940efce4a 100644--- a/crates/gpui2/src/elements/div.rs+++ b/crates/gpui2/src/elements/div.rs@@ -305,7 +305,6 @@ whereimpl<V, I, F> Component<V> for Div<V, I, F>where- // V: Any + Send + Sync,I: ElementInteraction<V>,F: ElementFocus<V>,{diff --git a/crates/gpui2/src/elements/text.rs b/crates/gpui2/src/elements/text.rsindex 3aff568c4c2..4bc37054902 100644--- a/crates/gpui2/src/elements/text.rs+++ b/crates/gpui2/src/elements/text.rs@@ -44,9 +44,6 @@ pub struct Text<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> {fn render(self) -> AnyElement<V> {AnyElement::new(self)diff --git a/crates/gpui2/src/focusable.rs b/crates/gpui2/src/focusable.rsindex d7cfc5fe8fc..99f8bb1dd61 100644--- a/crates/gpui2/src/focusable.rs+++ b/crates/gpui2/src/focusable.rs@@ -8,7 +8,7 @@ use smallvec::SmallVec;pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;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> {fn focus_listeners(&mut self) -> &mut FocusListeners<V>;@@ -42,7 +42,7 @@ pub trait Focusable<V: 'static>: Element<V> {fn on_focus(mut self,- listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,+ listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,) -> SelfwhereSelf: Sized,@@ -58,7 +58,7 @@ pub trait Focusable<V: 'static>: Element<V> {fn on_blur(mut self,- listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,+ listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,) -> SelfwhereSelf: Sized,@@ -74,7 +74,7 @@ pub trait Focusable<V: 'static>: Element<V> {fn on_focus_in(mut self,- listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,+ listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,) -> SelfwhereSelf: Sized,@@ -99,7 +99,7 @@ pub trait Focusable<V: 'static>: Element<V> {fn on_focus_out(mut self,- listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,+ listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,) -> SelfwhereSelf: 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_mut(&mut self) -> Option<&mut FocusEnabled<V>>;diff --git a/crates/gpui2/src/geometry.rs b/crates/gpui2/src/geometry.rsindex eedf8bbb2c1..7d4073144c3 100644--- a/crates/gpui2/src/geometry.rs+++ b/crates/gpui2/src/geometry.rs@@ -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)]pub struct Rems(f32);diff --git a/crates/gpui2/src/gpui2.rs b/crates/gpui2/src/gpui2.rsindex 755df91b930..49cc3cebc23 100644--- a/crates/gpui2/src/gpui2.rs+++ b/crates/gpui2/src/gpui2.rs@@ -68,34 +68,36 @@ use derive_more::{Deref, DerefMut};use std::{any::{Any, TypeId},borrow::{Borrow, BorrowMut},- ops::{Deref, DerefMut},};use taffy::TaffyLayoutEngine;type AnyBox = Box<dyn Any>;pub trait Context {- type ModelContext<'a, T>;type Result<T>;fn build_model<T: 'static>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Self::Result<Model<T>>;- fn update_model<T: 'static, R>(+ fn update_model<T, R>(&mut self,handle: &Model<T>,- update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,- ) -> Self::Result<R>;+ update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> 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 {- type ViewContext<'a, 'w, V>;-fn build_view<V>(&mut self,- build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,+ build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,) -> Self::Result<View<V>>whereV: 'static;@@ -103,12 +105,19 @@ pub trait VisualContext: Context {fn update_view<V: 'static, R>(&mut self,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>;++ 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 {- type Weak: 'static + Send;+ type Weak: 'static;fn entity_id(&self) -> EntityId;fn downgrade(&self) -> Self::Weak;@@ -128,7 +137,7 @@ pub trait BorrowAppContext {whereF: 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@@ -145,7 +154,7 @@ whereresult}- 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)}}@@ -208,30 +217,3 @@ impl<T: Into<ArcCow<'static, str>>> From<T> for SharedString {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,- }- }-}diff --git a/crates/gpui2/src/platform.rs b/crates/gpui2/src/platform.rsindex 705c2f83bbe..2dd4d8b666a 100644--- a/crates/gpui2/src/platform.rs+++ b/crates/gpui2/src/platform.rs@@ -9,12 +9,14 @@ use crate::{ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point,RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,};-use anyhow::anyhow;+use anyhow::{anyhow, bail};use async_task::Runnable;use futures::channel::oneshot;use parking::Unparker;use seahash::SeaHasher;use serde::{Deserialize, Serialize};+use sqlez::bindable::{Bind, Column, StaticColumnCount};+use sqlez::statement::Statement;use std::borrow::Cow;use std::hash::{Hash, Hasher};use std::time::Duration;@@ -27,6 +29,7 @@ use std::{str::FromStr,sync::Arc,};+use uuid::Uuid;pub use keystroke::*;#[cfg(target_os = "macos")]@@ -106,6 +109,9 @@ pub(crate) trait Platform: 'static {pub trait PlatformDisplay: Send + Sync + Debug {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 bounds(&self) -> Bounds<GlobalPixels>;}@@ -372,6 +378,64 @@ pub enum WindowBounds {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(+ ®ion.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)]pub enum WindowAppearance {Light,diff --git a/crates/gpui2/src/platform/mac/display.rs b/crates/gpui2/src/platform/mac/display.rsindex dc064293f34..b326eaa66d0 100644--- a/crates/gpui2/src/platform/mac/display.rs+++ b/crates/gpui2/src/platform/mac/display.rs@@ -1,9 +1,12 @@use crate::{point, size, Bounds, DisplayId, GlobalPixels, PlatformDisplay};+use anyhow::Result;+use core_foundation::uuid::{CFUUIDGetUUIDBytes, CFUUIDRef};use core_graphics::{display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList},geometry::{CGPoint, CGRect, CGSize},};use std::any::Any;+use uuid::Uuid;#[derive(Debug)]pub struct MacDisplay(pub(crate) CGDirectDisplayID);@@ -11,17 +14,23 @@ pub struct MacDisplay(pub(crate) CGDirectDisplayID);unsafe impl Send for 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> {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/// corner is at the origin of the AppKit coordinate system.pub fn primary() -> Self {Self::all().next().unwrap()}+ /// Obtains an iterator over all currently active system displays.pub fn all() -> impl Iterator<Item = Self> {unsafe {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.////// 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)}+ 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 {self}diff --git a/crates/gpui2/src/view.rs b/crates/gpui2/src/view.rsindex 06b20a30887..3cc4fdd4e34 100644--- a/crates/gpui2/src/view.rs+++ b/crates/gpui2/src/view.rs@@ -1,12 +1,12 @@use crate::{private::Sealed, AnyBox, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace,- BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, LayoutId, Model, Pixels,- Size, ViewContext, VisualContext, WeakModel, WindowContext,+ BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, Flatten, LayoutId,+ Model, Pixels, Size, ViewContext, VisualContext, WeakModel, WindowContext,};use anyhow::{Context, Result};use std::{any::{Any, TypeId},- marker::PhantomData,+ hash::{Hash, Hasher},};pub trait Render: 'static + Sized {@@ -52,7 +52,7 @@ impl<V: 'static> View<V> {pub fn update<C, R>(&self,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>whereC: VisualContext,@@ -73,55 +73,23 @@ impl<V> Clone for View<V> {}}-impl<V: Render, ParentViewState: 'static> Component<ParentViewState> for View<V> {- fn render(self) -> AnyElement<ParentViewState> {- AnyElement::new(EraseViewState {- view: self,- parent_view_state_type: PhantomData,- })+impl<V> Hash for View<V> {+ fn hash<H: Hasher>(&self, state: &mut H) {+ self.model.hash(state);}}-impl<V> Element<()> for View<V>-where- V: Render,-{- type ElementState = AnyElement<V>;-- fn id(&self) -> Option<crate::ElementId> {- Some(ElementId::View(self.model.entity_id))- }-- fn initialize(- &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- })+impl<V> PartialEq for View<V> {+ fn eq(&self, other: &Self) -> bool {+ self.model == other.model}+}- fn layout(- &mut self,- _: &mut (),- element: &mut Self::ElementState,- cx: &mut ViewContext<()>,- ) -> LayoutId {- self.update(cx, |state, cx| element.layout(state, cx))- }+impl<V> Eq for View<V> {}- fn paint(- &mut self,- _: Bounds<Pixels>,- _: &mut (),- element: &mut Self::ElementState,- cx: &mut ViewContext<()>,- ) {- self.update(cx, |state, cx| element.paint(state, cx))+impl<V: Render, ParentViewState: 'static> Component<ParentViewState> for View<V> {+ fn render(self) -> AnyElement<ParentViewState> {+ AnyElement::new(AnyView::from(self))}}@@ -134,13 +102,17 @@ impl<V: 'static> WeakView<V> {Entity::upgrade_from(self)}- pub fn update<R>(+ pub fn update<C, R>(&self,- cx: &mut WindowContext,- f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,- ) -> Result<R> {+ cx: &mut C,+ f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,+ ) -> Result<R>+ where+ C: VisualContext,+ Result<C::Result<R>>: Flatten<R>,+ {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> {- view: View<V>,- parent_view_state_type: PhantomData<ParentV>,-}--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> Hash for WeakView<V> {+ fn hash<H: Hasher>(&self, state: &mut H) {+ self.model.hash(state);}}-impl<V: Render, ParentV: 'static> Element<ParentV> for EraseViewState<V, ParentV> {- type ElementState = Box<dyn Any>;-- 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)+impl<V> PartialEq for WeakView<V> {+ fn eq(&self, other: &Self) -> bool {+ self.model == other.model}}-trait ViewObject: Send + Sync {- 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()- }-}+impl<V> Eq for WeakView<V> {}#[derive(Clone, Debug)]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}diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rsindex e7cfcf45eed..5f2de2e4282 100644--- a/crates/gpui2/src/window.rs+++ b/crates/gpui2/src/window.rs@@ -5,11 +5,11 @@ use crate::{Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,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,- 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 derive_more::{Deref, DerefMut};use parking_lot::RwLock;@@ -20,6 +20,7 @@ use std::{borrow::{Borrow, BorrowMut, Cow},fmt::Debug,future::Future,+ hash::{Hash, Hasher},marker::PhantomData,mem,sync::{@@ -156,7 +157,7 @@ impl Drop for FocusHandle {// Holds the state for a specific window.pub struct Window {- handle: AnyWindowHandle,+ pub(crate) handle: AnyWindowHandle,platform_window: Box<dyn PlatformWindow>,display_id: DisplayId,sprite_atlas: Arc<dyn PlatformAtlas>,@@ -201,23 +202,25 @@ impl Window {let content_size = platform_window.content_size();let scale_factor = platform_window.scale_factor();platform_window.on_resize(Box::new({- let cx = cx.to_async();+ let mut cx = cx.to_async();move |content_size, scale_factor| {- cx.update_window(handle, |cx| {- cx.window.scale_factor = scale_factor;- cx.window.scene_builder = SceneBuilder::new();- cx.window.content_size = content_size;- cx.window.display_id = cx.window.platform_window.display().id();- cx.window.dirty = true;- })- .log_err();+ handle+ .update(&mut cx, |_, cx| {+ cx.window.scale_factor = scale_factor;+ cx.window.scene_builder = SceneBuilder::new();+ cx.window.content_size = content_size;+ cx.window.display_id = cx.window.platform_window.display().id();+ cx.window.dirty = true;+ })+ .log_err();}}));platform_window.on_input({- let cx = cx.to_async();+ let mut cx = cx.to_async();Box::new(move |event| {- cx.update_window(handle, |cx| cx.dispatch_event(event))+ handle+ .update(&mut cx, |_, cx| cx.dispatch_event(event)).log_err().unwrap_or(true)})@@ -296,24 +299,14 @@ impl ContentMask<Pixels> {/// 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/// an `AppContext` and call any `AppContext` methods.-pub struct WindowContext<'a, 'w> {- pub(crate) app: Reference<'a, AppContext>,- pub(crate) window: Reference<'w, Window>,+pub struct WindowContext<'a> {+ pub(crate) app: &'a mut AppContext,+ pub(crate) window: &'a mut Window,}-impl<'a, 'w> WindowContext<'a, 'w> {- pub(crate) fn immutable(app: &'a AppContext, window: &'w Window) -> Self {- Self {- 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),- }+impl<'a> WindowContext<'a> {+ pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {+ Self { app, window }}/// 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);}- let window_id = self.window.handle.id;self.window.focus = Some(handle.id);self.app.push_effect(Effect::FocusChanged {- window_id,+ window_handle: self.window.handle,focused: Some(handle.id),});self.notify();@@ -360,15 +352,53 @@ impl<'a, 'w> WindowContext<'a, 'w> {self.window.last_blur = Some(self.window.focus);}- let window_id = self.window.handle.id;self.window.focus = None;self.app.push_effect(Effect::FocusChanged {- window_id,+ window_handle: self.window.handle,focused: None,});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/// await points in async code.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.- 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 display_id = self.window.display_id;@@ -387,12 +417,12 @@ impl<'a, 'w> WindowContext<'a, 'w> {return;}} else {- let async_cx = self.to_async();+ let mut async_cx = self.to_async();self.next_frame_callbacks.insert(display_id, vec![f]);self.platform().set_display_link_output_callback(display_id,Box::new(move |_current_time, _output_time| {- let _ = async_cx.update(|cx| {+ let _ = async_cx.update(|_, cx| {let callbacks = cx.next_frame_callbacks.get_mut(&display_id)@@ -1114,12 +1144,12 @@ impl<'a, 'w> WindowContext<'a, 'w> {/// is updated.pub fn observe_global<G: 'static>(&mut self,- f: impl Fn(&mut WindowContext<'_, '_>) + Send + 'static,+ f: impl Fn(&mut WindowContext<'_>) + 'static,) -> Subscription {- let window_id = self.window.handle.id;+ let window_handle = self.window.handle;self.global_observers.insert(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<'_, '_> {- type ModelContext<'a, T> = ModelContext<'a, T>;+impl Context for WindowContext<'_> {type Result<T> = T;fn build_model<T>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Model<T>whereT: 'static,{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)}fn update_model<T: 'static, R>(&mut self,model: &Model<T>,- update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,+ update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,) -> R {let mut entity = self.entities.lease(model);let result = update(&mut *entity,- &mut ModelContext::mutable(&mut *self.app, model.downgrade()),+ &mut ModelContext::new(&mut *self.app, model.downgrade()),);self.entities.end_lease(entity);result}-}-impl VisualContext for WindowContext<'_, '_> {- type ViewContext<'a, 'w, V> = ViewContext<'a, 'w, V>;+ 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<'_> {fn build_view<V>(&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>>whereV: 'static,@@ -1247,7 +1286,7 @@ impl VisualContext for WindowContext<'_, '_> {let view = View {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);self.entities.insert(slot, entity);view@@ -1257,17 +1296,35 @@ impl VisualContext for WindowContext<'_, '_> {fn update_view<T: 'static, R>(&mut self,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> {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);cx.app.entities.end_lease(lease);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;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 {&mut self.app}}-impl<'a, 'w> Borrow<AppContext> for WindowContext<'a, 'w> {+impl<'a> Borrow<AppContext> for WindowContext<'a> {fn borrow(&self) -> &AppContext {&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 {&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 {&self.window}}-impl BorrowMut<Window> for WindowContext<'_, '_> {+impl BorrowMut<Window> for WindowContext<'_> {fn borrow_mut(&mut self) -> &mut Window {&mut self.window}@@ -1469,52 +1526,48 @@ impl BorrowMut<Window> for WindowContext<'_, '_> {impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}-pub struct ViewContext<'a, 'w, V> {- window_cx: WindowContext<'a, 'w>,- view: WeakView<V>,+pub struct ViewContext<'a, V> {+ window_cx: WindowContext<'a>,+ view: &'a View<V>,}-impl<V> Borrow<AppContext> for ViewContext<'_, '_, V> {+impl<V> Borrow<AppContext> for ViewContext<'_, V> {fn borrow(&self) -> &AppContext {&*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 {&mut *self.window_cx.app}}-impl<V> Borrow<Window> for ViewContext<'_, '_, V> {+impl<V> Borrow<Window> for ViewContext<'_, V> {fn borrow(&self) -> &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 {&mut *self.window_cx.window}}-impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {- pub(crate) fn mutable(- app: &'a mut AppContext,- window: &'w mut Window,- view: WeakView<V>,- ) -> Self {+impl<'a, V: 'static> ViewContext<'a, V> {+ pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {Self {- window_cx: WindowContext::mutable(app, window),+ window_cx: WindowContext::new(app, window),view,}}- pub fn view(&self) -> WeakView<V> {+ pub fn view(&self) -> View<V> {self.view.clone()}- pub fn model(&self) -> WeakModel<V> {+ pub fn model(&self) -> Model<V> {self.view.model.clone()}@@ -1525,40 +1578,50 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {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- 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));}+ /// 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>(&mut self,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,) -> SubscriptionwhereV2: 'static,- V: Any + Send,+ V: 'static,E: Entity<V2>,{- let view = self.view();+ let view = self.view().downgrade();let entity_id = entity.entity_id();let entity = entity.downgrade();let window_handle = self.window.handle;self.app.observers.insert(entity_id,Box::new(move |cx| {- cx.update_window(window_handle.id, |cx| {- if let Some(handle) = E::upgrade_from(&entity) {- view.update(cx, |this, cx| on_notify(this, handle, cx))- .is_ok()- } else {- false- }- })- .unwrap_or(false)+ window_handle+ .update(cx, |_, cx| {+ if let Some(handle) = E::upgrade_from(&entity) {+ view.update(cx, |this, cx| on_notify(this, handle, cx))+ .is_ok()+ } else {+ false+ }+ })+ .unwrap_or(false)}),)}@@ -1566,44 +1629,44 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {pub fn subscribe<V2, E>(&mut self,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,) -> SubscriptionwhereV2: EventEmitter,E: Entity<V2>,{- let view = self.view();+ let view = self.view().downgrade();let entity_id = entity.entity_id();let handle = entity.downgrade();let window_handle = self.window.handle;self.app.event_listeners.insert(entity_id,Box::new(move |event, cx| {- cx.update_window(window_handle.id, |cx| {- if let Some(handle) = E::upgrade_from(&handle) {- let event = event.downcast_ref().expect("invalid event type");- view.update(cx, |this, cx| on_event(this, handle, event, cx))- .is_ok()- } else {- false- }- })- .unwrap_or(false)+ window_handle+ .update(cx, |_, cx| {+ if let Some(handle) = E::upgrade_from(&handle) {+ let event = event.downcast_ref().expect("invalid event type");+ view.update(cx, |this, cx| on_event(this, handle, event, cx))+ .is_ok()+ } else {+ false+ }+ })+ .unwrap_or(false)}),)}pub fn on_release(&mut self,- mut on_release: impl FnMut(&mut V, &mut WindowContext) + Send + 'static,+ on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,) -> Subscription {let window_handle = self.window.handle;self.app.release_listeners.insert(self.view.model.entity_id,Box::new(move |this, cx| {let this = this.downcast_mut().expect("invalid entity type");- // todo!("are we okay with silently swallowing the error?")- let _ = cx.update_window(window_handle.id, |cx| on_release(this, cx));+ let _ = window_handle.update(cx, |_, cx| on_release(this, cx));}),)}@@ -1611,21 +1674,21 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {pub fn observe_release<V2, E>(&mut self,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,) -> Subscriptionwhere- V: Any + Send,+ V: 'static,V2: 'static,E: Entity<V2>,{- let view = self.view();+ let view = self.view().downgrade();let entity_id = entity.entity_id();let window_handle = self.window.handle;self.app.release_listeners.insert(entity_id,Box::new(move |entity, cx| {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))});}),@@ -1641,9 +1704,9 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {pub fn on_focus_changed(&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| {handle.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();if !self.window.freeze_key_dispatch_stack {for (event_type, listener) in key_listeners {- let handle = self.view();+ let handle = self.view().downgrade();let listener = Box::new(move |event: &dyn Any,context_stack: &[&DispatchContext],phase: DispatchPhase,- cx: &mut WindowContext<'_, '_>| {+ cx: &mut WindowContext<'_>| {handle.update(cx, |view, cx| {listener(view, event, context_stack, phase, cx)@@ -1745,16 +1808,13 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {R: 'static,Fut: Future<Output = R> + 'static,{- let view = self.view();- self.window_cx.spawn(move |_, cx| {- let result = f(view, cx);- async move { result.await }- })+ let view = self.view().downgrade();+ self.window_cx.spawn(move |_, cx| f(view, cx))}pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> Rwhere- G: 'static + Send,+ G: 'static,{let mut global = self.app.lease_global::<G>();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>(&mut self,- f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + 'static,+ f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,) -> Subscription {- let window_id = self.window.handle.id;- let handle = self.view();+ let window_handle = self.window.handle;+ let view = self.view().downgrade();self.global_observers.insert(TypeId::of::<G>(),Box::new(move |cx| {- cx.update_window(window_id, |cx| {- handle.update(cx, |view, cx| f(view, cx)).is_ok()- })- .unwrap_or(false)+ window_handle+ .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())+ .unwrap_or(false)}),)}@@ -1783,7 +1842,7 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {&mut self,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| {handle.update(cx, |view, 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>whereV: EventEmitter,- V::Event: Any + Send,+ V::Event: 'static,{pub fn emit(&mut self, event: V::Event) {let emitter = self.view.model.entity_id;@@ -1806,13 +1865,12 @@ where}}-impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {- type ModelContext<'b, U> = ModelContext<'b, U>;+impl<V> Context for ViewContext<'_, V> {type Result<U> = U;fn build_model<T: 'static>(&mut self,- build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,+ build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,) -> Model<T> {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>(&mut self,model: &Model<T>,- update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,+ update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,) -> R {self.window_cx.update_model(model, update)}-}-impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {- type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;+ 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> {fn build_view<W: 'static>(&mut self,- build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W,+ build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,) -> Self::Result<View<W>> {self.window_cx.build_view(build_view)}@@ -1839,21 +1902,31 @@ impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {fn update_view<V2: 'static, R>(&mut self,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.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> {- type Target = WindowContext<'a, 'w>;+impl<'a, V> std::ops::Deref for ViewContext<'a, V> {+ type Target = WindowContext<'a>;fn deref(&self) -> &Self::Target {&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 {&mut self.window_cx}@@ -1868,42 +1941,74 @@ impl WindowId {}}-#[derive(PartialEq, Eq)]+#[derive(Deref, DerefMut)]pub struct WindowHandle<V> {- id: WindowId,+ #[deref]+ #[deref_mut]+ pub(crate) any_handle: AnyWindowHandle,state_type: PhantomData<V>,}-impl<S> Copy for WindowHandle<S> {}--impl<S> Clone for WindowHandle<S> {- fn clone(&self) -> Self {+impl<V: 'static + Render> WindowHandle<V> {+ pub fn new(id: WindowId) -> Self {WindowHandle {- id: self.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<S> WindowHandle<S> {- pub fn new(id: WindowId) -> Self {+impl<V> Copy for WindowHandle<V> {}++impl<V> Clone for WindowHandle<V> {+ fn clone(&self) -> Self {WindowHandle {- id,+ any_handle: self.any_handle,state_type: PhantomData,}}}-impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {+impl<V> PartialEq for WindowHandle<V> {+ fn eq(&self, other: &Self) -> bool {+ self.any_handle == other.any_handle+ }+}++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 {- AnyWindowHandle {- id: self.id,- state_type: TypeId::of::<S>(),- }+ self.any_handle}}-#[derive(Copy, Clone, PartialEq, Eq)]+#[derive(Copy, Clone, PartialEq, Eq, Hash)]pub struct AnyWindowHandle {pub(crate) id: WindowId,state_type: TypeId,@@ -1913,6 +2018,28 @@ impl AnyWindowHandle {pub fn window_id(&self) -> WindowId {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"))]