Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
WIP: Merge branch 'main' into zed2-workspace
Nathan Sobo3e7df8297703
diff --cc crates/gpui2/src/app.rsindex 57b1d63f4b5,265ce59a023..97002a8304d--- a/crates/gpui2/src/app.rs+++ b/crates/gpui2/src/app.rs@@@ -11,15 -11,13 +11,14 @@@ use refineable::Refineableuse smallvec::SmallVec;#[cfg(any(test, feature = "test-support"))]pub use test_context::*;- use uuid::Uuid;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, ClipboardItem, Context, DispatchPhase, DisplayId, Entity, Executor,- FocusEvent, FocusHandle, FocusId, KeyBinding, Keymap, LayoutId, MainThread, MainThreadOnly,++ AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,++ Entity, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId,+ Pixels, Platform, PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription,+ SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, Window, WindowContext,+ WindowHandle, WindowId,};use anyhow::{anyhow, Result};use collections::{HashMap, HashSet, VecDeque};@@@ -260,13 -255,106 +256,99 @@@ impl AppContextresult}- 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,+ ) -> Result<R> {+ self.update(|cx| {+ let mut window = cx+ .windows+ .get_mut(id)+ .ok_or_else(|| anyhow!("window not found"))?+ .take()+ .unwrap();+- let result = update(&mut WindowContext::mutable(cx, &mut window));++ let result = update(&mut WindowContext::new(cx, &mut window));++ cx.windows+ .get_mut(id)+ .ok_or_else(|| anyhow!("window not found"))?+ .replace(window);++ Ok(result)+ })+ }++ /// Opens a new window with the given option and the root view returned by the given function.+ /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific+ /// functionality.+ pub fn open_window<V: Render>(+ &mut self,+ options: crate::WindowOptions,+ build_root_view: impl FnOnce(&mut WindowContext) -> View<V> + 'static,+ ) -> WindowHandle<V> {+ self.update(|cx| {+ 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+ })+ }++ pub(crate) fn platform(&self) -> &Rc<dyn Platform> {+ &self.platform+ }++ /// Instructs the platform to activate the application by bringing it to the foreground.+ pub fn activate(&self, ignoring_other_apps: bool) {+ self.platform().activate(ignoring_other_apps);+ }++ /// Writes data to the platform clipboard.+ pub fn write_to_clipboard(&self, item: ClipboardItem) {+ self.platform().write_to_clipboard(item)+ }++ /// Reads data from the platform clipboard.+ pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {+ self.platform().read_from_clipboard()+ }++ /// Writes credentials to the platform keychain.+ pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {+ self.platform().write_credentials(url, username, password)+ }++ /// Reads credentials from the platform keychain.+ pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {+ self.platform().read_credentials(url)+ }++ /// Deletes credentials from the platform keychain.+ pub fn delete_credentials(&self, url: &str) -> Result<()> {+ self.platform().delete_credentials(url)+ }++ /// Directs the platform's default browser to open the given URL.+ pub fn open_url(&self, url: &str) {+ self.platform().open_url(url);+ }++ pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {+ self.platform().path_for_auxiliary_executable(name)+ }+pub(crate) fn push_effect(&mut self, effect: Effect) {match &effect {Effect::Notify { emitter } => {@@@ -737,132 -767,8 +785,31 @@@ impl Context for AppContextresult})}++ fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>+ where+ F: FnOnce(AnyView, &mut Self::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)+ })+ }}- impl<C> MainThread<C>- where- C: Borrow<AppContext>,- {- pub(crate) fn platform(&self) -> &dyn Platform {- self.0.borrow().platform.borrow_on_main_thread()- }-- /// Instructs the platform to activate the application by bringing it to the foreground.- pub fn activate(&self, ignoring_other_apps: bool) {- self.platform().activate(ignoring_other_apps);- }-- /// Writes data to the platform clipboard.- pub fn write_to_clipboard(&self, item: ClipboardItem) {- self.platform().write_to_clipboard(item)- }-- /// Reads data from the platform clipboard.- pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {- self.platform().read_from_clipboard()- }-- /// Writes credentials to the platform keychain.- pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {- self.platform().write_credentials(url, username, password)- }-- /// Reads credentials from the platform keychain.- pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {- self.platform().read_credentials(url)- }-- /// Deletes credentials from the platform keychain.- pub fn delete_credentials(&self, url: &str) -> Result<()> {- self.platform().delete_credentials(url)- }-- /// Directs the platform's default browser to open the given URL.- pub fn open_url(&self, url: &str) {- self.platform().open_url(url);- }-- pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {- self.platform().path_for_auxiliary_executable(name)- }-- pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {- self.platform().displays()- }-- pub fn display_for_uuid(&self, uuid: Uuid) -> Option<Rc<dyn PlatformDisplay>> {- self.platform()- .displays()- .into_iter()- .find(|display| display.uuid().ok() == Some(uuid))- }- }-- impl MainThread<AppContext> {- fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {- self.0.update(|cx| {- update(unsafe {- std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)- })- })- }-- /// Opens a new window with the given option and the root view returned by the given function.- /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific- /// functionality.- pub fn open_window<V: Render>(- &mut self,- options: crate::WindowOptions,- build_root_view: impl FnOnce(&mut MainThread<WindowContext>) -> View<V> + Send + 'static,- ) -> WindowHandle<V> {- self.update(|cx| {- let id = cx.windows.insert(None);- let handle = WindowHandle::new(id);- let mut window = Window::new(handle.into(), options, cx);- let mut window_context = MainThread(WindowContext::new(cx, &mut window));- let root_view = build_root_view(&mut window_context);- window.root_view.replace(root_view.into());- cx.windows.get_mut(id).unwrap().replace(window);- handle- })- }-- /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides- /// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.- pub fn update_global<G: 'static + Send, R>(- &mut self,- update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,- ) -> R {- self.0.update_global(|global, cx| {- let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };- update(global, cx)- })- }- }-/// These effects are processed at the end of each application update cycle.pub(crate) enum Effect {Notify {@@@ -870,10 -776,10 +817,10 @@@},Emit {emitter: EntityId,- event: Box<dyn Any + Send + 'static>,+ event: Box<dyn Any>,},FocusChanged {- window_id: WindowId,+ window_handle: AnyWindowHandle,focused: Option<FocusId>,},Refresh,diff --cc crates/gpui2/src/app/async_context.rsindex d2820aa1fc1,fb941b91b8c..ef7108584e2--- a/crates/gpui2/src/app/async_context.rs+++ b/crates/gpui2/src/app/async_context.rs@@@ -1,11 -1,10 +1,11 @@@use crate::{- AnyView, AnyWindowHandle, AppContext, Context, Executor, MainThread, Model, ModelContext,- Render, Result, Task, View, ViewContext, VisualContext, WindowContext, WindowHandle,- 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,++ WindowHandle,};- use anyhow::Context as _;-use anyhow::anyhow;++use anyhow::{anyhow, Context as _};use derive_more::{Deref, DerefMut};- use parking_lot::Mutex;- use std::{future::Future, mem, sync::Weak};-use std::{cell::RefCell, future::Future, rc::Weak};++use std::{cell::RefCell, future::Future, mem, rc::Weak};#[derive(Clone)]pub struct AsyncAppContext {@@@ -35,19 -37,13 +39,22 @@@ impl Context for AsyncAppContexthandle: &Model<T>,update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,) -> Self::Result<R> {- let app = self.app.upgrade().context("app was released")?;- let mut lock = app.lock(); // Need this to compile- Ok(lock.update_model(handle, update))+ let app = self+ .app+ .upgrade()+ .ok_or_else(|| anyhow!("app was released"))?;+ 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 Self::WindowContext<'_>) -> T,+ {+ let app = self.app.upgrade().context("app was released")?;- let mut lock = app.lock(); // Need this to compile++ let mut lock = app.borrow_mut();+ lock.update_window(window, f)+ }}impl AsyncAppContext {@@@ -58,47 -57,55 +68,42 @@@Ok(())}- pub fn executor(&self) -> &Executor {- &self.executor+ pub fn background_executor(&self) -> &BackgroundExecutor {+ &self.background_executor}- pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> Result<R> {- let app = self.app.upgrade().context("app was released")?;- let mut lock = app.lock();- Ok(f(&mut *lock))+ pub fn foreground_executor(&self) -> &ForegroundExecutor {+ &self.foreground_executor}- pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>- where- Fut: Future<Output = R> + Send + 'static,- R: Send + 'static,- {- let this = self.clone();- self.executor.spawn(async move { f(this).await })+ pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> Result<R> {+ let app = self+ .app+ .upgrade()+ .ok_or_else(|| anyhow!("app was released"))?;+ let mut lock = app.borrow_mut();+ Ok(f(&mut *lock))}- pub fn spawn_on_main<Fut, R>(- 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,- f: impl FnOnce(MainThread<AsyncAppContext>) -> Fut + Send + 'static,- ) -> Task<R>- where- Fut: Future<Output = R> + 'static,- R: Send + 'static,- {- let this = self.clone();- self.executor.spawn_on_main(|| f(MainThread(this)))+ handle: AnyWindowHandle,+ update: impl FnOnce(&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)}- pub fn run_on_main<R>(- &self,- f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,- ) -> Result<Task<R>>+ pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>where- R: Send + 'static,+ Fut: Future<Output = R> + 'static,+ R: 'static,{- let app = self.app.upgrade().context("app was released")?;- let mut app_context = app.lock();- Ok(app_context.run_on_main(f))+ self.foreground_executor.spawn(f(self.clone()))}pub fn has_global<G: 'static>(&self) -> Result<bool> {@@@ -186,7 -176,7 +177,7 @@@ impl AsyncWindowContextread: impl FnOnce(&G, &WindowContext) -> R,) -> Result<R> {self.app- .update_window(self.window, |_, cx| read(cx.global(), cx))- .read_window(self.window, |cx| read(cx.global(), cx))++ .update_window(self.window, |cx| read(cx.global(), cx))}pub fn update_global<G, R>(@@@ -197,43 -187,8 +188,20 @@@G: 'static,{self.app- .update_window(self.window, |_, 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 + Send + 'static,+ ) -> Task<R>+ where+ Fut: Future<Output = R> + Send + 'static,+ R: Send + 'static,+ {+ let this = self.clone();- self.executor.spawn(async move { f(this).await })- }-- pub fn spawn_on_main<Fut, R>(- &self,- f: impl FnOnce(AsyncWindowContext) -> Fut + Send + 'static,- ) -> Task<R>- where- Fut: Future<Output = R> + 'static,- R: Send + 'static,- {- let this = self.clone();- self.executor.spawn_on_main(|| f(this))- }-- pub fn run_on_main<R>(- &mut self,- f: impl FnOnce(&mut MainThread<WindowContext>) -> R + Send + 'static,- ) -> Task<Result<R>>- where- R: Send + 'static,- {- self.update(|_, cx| cx.run_on_main(f))- .unwrap_or_else(|error| Task::ready(Err(error)))++ self.foreground_executor.spawn(async move { f(this).await })+ }}impl Context for AsyncWindowContext {@@@ -259,59 -212,6 +227,48 @@@update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,) -> Result<R> {self.app- .update_window(self.window, |_, cx| cx.update_model(handle, update))+ .update_window(self.window, |cx| cx.update_model(handle, update))}++ fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>+ where+ F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,+ {+ self.app.update_window(window, update)+ }+}++impl VisualContext for AsyncWindowContext {+ type ViewContext<'a, V: 'static> = ViewContext<'a, V>;++ fn build_view<V>(+ &mut self,+ build_view_state: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,+ ) -> Self::Result<View<V>>+ where- V: 'static + Send,++ V: 'static,+ {+ self.app- .update_window(self.window, |_, cx| cx.build_view(build_view_state))++ .update_window(self.window, |cx| cx.build_view(build_view_state))+ }++ fn update_view<V: 'static, R>(+ &mut self,+ view: &View<V>,+ update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, V>) -> R,+ ) -> Self::Result<R> {+ self.app- .update_window(self.window, |_, cx| cx.update_view(view, update))++ .update_window(self.window, |cx| cx.update_view(view, update))+ }++ fn replace_root_view<V>(+ &mut self,+ build_view: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,+ ) -> Self::Result<View<V>>+ where+ V: 'static + Send + Render,+ {+ self.app- .update_window(self.window, |_, cx| cx.replace_root_view(build_view))- }- }-- #[cfg(test)]- mod tests {- use super::*;-- #[test]- fn test_async_app_context_send_sync() {- fn assert_send_sync<T: Send + Sync>() {}- assert_send_sync::<AsyncAppContext>();++ .update_window(self.window, |cx| cx.replace_root_view(build_view))+ }}diff --cc crates/gpui2/src/app/model_context.rsindex e4db4ab64df,f6982cdc1ff..a764cd73661--- a/crates/gpui2/src/app/model_context.rs+++ b/crates/gpui2/src/app/model_context.rs@@@ -1,8 -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, MainThread, Model, Subscription, Task, WeakModel, WindowContext,++ EventEmitter, Model, Subscription, Task, WeakModel, WindowContext,};+use anyhow::Result;use derive_more::{Deref, DerefMut};use futures::FutureExt;use std::{diff --cc crates/gpui2/src/app/test_context.rsindex 90ea7dd91df,6affabdd238..9f6fb4d75a7--- a/crates/gpui2/src/app/test_context.rs+++ b/crates/gpui2/src/app/test_context.rs@@@ -1,9 -1,11 +1,11 @@@use crate::{- AnyView, AnyWindowHandle, AppContext, AsyncAppContext, Context, Executor, MainThread, Model,- ModelContext, Result, Task, TestDispatcher, TestPlatform, WindowContext,- 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 parking_lot::Mutex;- use std::{future::Future, sync::Arc};+ use anyhow::{anyhow, bail};+ use futures::{Stream, StreamExt};+ use std::{cell::RefCell, future::Future, rc::Rc, sync::Arc, time::Duration};#[derive(Clone)]pub struct TestAppContext {@@@ -32,17 -34,9 +35,17 @@@ impl Context for TestAppContexthandle: &Model<T>,update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,) -> Self::Result<R> {- let mut lock = self.app.lock();- lock.update_model(handle, update)+ 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 Self::WindowContext<'_>) -> T,+ {- let mut lock = self.app.lock();++ let mut lock = self.app.borrow_mut();+ lock.update_window(window, f)+ }}impl TestAppContext {@@@ -67,45 -67,43 +76,34 @@@Ok(())}- pub fn executor(&self) -> &Executor {- &self.executor+ pub fn executor(&self) -> &BackgroundExecutor {+ &self.background_executor}- pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {- let mut lock = self.app.lock();- f(&mut *lock)+ pub fn foreground_executor(&self) -> &ForegroundExecutor {+ &self.foreground_executor}- pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>- where- Fut: Future<Output = R> + Send + 'static,- R: Send + 'static,- {- let cx = self.to_async();- self.executor.spawn(async move { f(cx).await })+ pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {+ let mut cx = self.app.borrow_mut();+ cx.update(f)}- pub fn spawn_on_main<Fut, R>(- 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,- f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static,- ) -> Task<R>- where- Fut: Future<Output = R> + 'static,- R: Send + 'static,- {- let cx = self.to_async();- self.executor.spawn_on_main(|| f(cx))+ handle: AnyWindowHandle,+ update: impl FnOnce(&mut WindowContext) -> R,+ ) -> R {+ let mut app = self.app.borrow_mut();+ app.update_window(handle.id, update).unwrap()}- pub fn run_on_main<R>(- &self,- f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,- ) -> Task<R>+ pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>where- R: Send + 'static,+ Fut: Future<Output = R> + 'static,+ R: 'static,{- let mut app_context = self.app.lock();- app_context.run_on_main(f)+ self.foreground_executor.spawn(f(self.to_async()))}pub fn has_global<G: 'static>(&self) -> bool {diff --cc crates/gpui2/src/element.rsindex d11c0071866,e41dc4ebd54..4890b79a9ac--- a/crates/gpui2/src/element.rs+++ b/crates/gpui2/src/element.rs@@@ -220,8 -218,8 +218,8 @@@ impl<V> Component<V> for AnyElement<V>impl<V, E, F> Element<V> for Option<F>whereV: 'static,- E: 'static + Component<V> + Send,- F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + Send + '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>;@@@ -264,8 -262,8 +262,8 @@@impl<V, E, F> Component<V> for Option<F>whereV: 'static,- E: 'static + Component<V> + Send,- F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + Send + '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)@@@ -275,8 -273,8 +273,8 @@@impl<V, E, F> Component<V> for FwhereV: 'static,- E: 'static + Component<V> + Send,- F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + Send + '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 --cc crates/gpui2/src/gpui2.rsindex d016e174fe5,755df91b930..9801167583c--- a/crates/gpui2/src/gpui2.rs+++ b/crates/gpui2/src/gpui2.rs@@@ -68,27 -68,22 +68,22 @@@ use derive_more::{Deref, DerefMut}use std::{any::{Any, TypeId},borrow::{Borrow, BorrowMut},- mem,-- ops::{Deref, DerefMut},- sync::Arc,};use taffy::TaffyLayoutEngine;- type AnyBox = Box<dyn Any + Send>;+ type AnyBox = Box<dyn Any>;pub trait Context {+ type WindowContext<'a>: UpdateView;type ModelContext<'a, T>;type Result<T>;- fn build_model<T>(+ fn build_model<T: 'static>(&mut self,build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,- ) -> Self::Result<Model<T>>- where- T: 'static + Send;+ ) -> 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,@@@ -106,10 -95,10 +101,10 @@@ pub trait VisualContext: Contextfn build_view<V>(&mut self,- build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,+ build_view: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,) -> Self::Result<View<V>>where- V: 'static + Send;+ V: 'static;fn update_view<V: 'static, R>(&mut self,@@@ -383,32 -208,30 +231,3 @@@ impl<T: Into<ArcCow<'static, str>>> FroSelf(value.into())}}--- pub(crate) struct MainThreadOnly<T: ?Sized> {- executor: Executor,- value: Arc<T>,-pub enum Reference<'a, T> {- Immutable(&'a T),- Mutable(&'a mut T),--}--- impl<T: ?Sized> Clone for MainThreadOnly<T> {- fn clone(&self) -> Self {- Self {- executor: self.executor.clone(),- value: self.value.clone(),-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,-- }-- }--}-- /// Allows a value to be accessed only on the main thread, allowing a non-`Send` type- /// to become `Send`.- impl<T: 'static + ?Sized> MainThreadOnly<T> {- pub(crate) fn new(value: Arc<T>, executor: Executor) -> Self {- Self { executor, value }- }--- pub(crate) fn borrow_on_main_thread(&self) -> &T {- assert!(self.executor.is_main_thread());- &self.value-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,- }-- }--}-- unsafe impl<T: ?Sized> Send for MainThreadOnly<T> {}diff --cc crates/gpui2/src/platform.rsindex b2df16a20f1,705c2f83bbe..2dd4d8b666a--- a/crates/gpui2/src/platform.rs+++ b/crates/gpui2/src/platform.rs@@@ -5,17 -5,16 +5,18 @@@ mod macmod test;use crate::{- AnyWindowHandle, Bounds, DevicePixels, Executor, Font, FontId, FontMetrics, FontRun,- GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point, RenderGlyphParams,- RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,+ AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun,+ 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;diff --cc crates/gpui2/src/view.rsindex b40514b40e8,06b20a30887..82214b381d8--- a/crates/gpui2/src/view.rs+++ b/crates/gpui2/src/view.rs@@@ -5,8 -5,7 +5,8 @@@ use crate::};use anyhow::{Context, Result};use std::{- any::TypeId,+ any::{Any, TypeId},+ hash::{Hash, Hasher},marker::PhantomData,};@@@ -199,9 -166,9 +199,9 @@@ impl<V: Render, ParentV: 'static> Compo}impl<V: Render, ParentV: 'static> Element<ParentV> for EraseViewState<V, ParentV> {- type ElementState = AnyBox;+ type ElementState = Box<dyn Any>;- fn id(&self) -> Option<crate::ElementId> {+ fn id(&self) -> Option<ElementId> {Element::id(&self.view)}diff --cc crates/gpui2/src/window.rsindex 2c39815a4b8,e7cfcf45eed..ab12f08a1ce--- a/crates/gpui2/src/window.rs+++ b/crates/gpui2/src/window.rs@@@ -3,14 -3,13 +3,13 @@@ use crate::Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,- MainThread, MainThreadOnly, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton,- MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow,- Point, PolychromeSprite, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams,- ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine,- Task, Underline, UnderlineStyle, UpdateView, View, VisualContext, WeakView, WindowOptions,- SUBPIXEL_VARIANTS,+ 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, UpdateView, 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;@@@ -159,8 -156,8 +157,8 @@@ impl Drop for FocusHandle// Holds the state for a specific window.pub struct Window {- handle: AnyWindowHandle,+ pub(crate) handle: AnyWindowHandle,- platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,+ platform_window: Box<dyn PlatformWindow>,display_id: DisplayId,sprite_atlas: Arc<dyn PlatformAtlas>,rem_size: Pixels,@@@ -204,22 -201,16 +202,16 @@@ impl Windowlet 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| {- 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- .borrow_on_main_thread()- .display()- .id();- cx.window.dirty = true;- })- .log_err();+ 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();}}));@@@ -369,66 -369,6 +359,45 @@@ impl<'a> WindowContext<'a>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 + Send) {+ 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<'_>) + Send + '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)+ }),+ )+ }+- /// Schedule the given closure to be run on the main thread. It will be invoked with- /// a `MainThread<WindowContext>`, which provides access to platform-specific functionality- /// of the window.- pub fn run_on_main<R>(- &mut self,- f: impl FnOnce(&mut MainThread<WindowContext<'_>>) -> R + Send + 'static,- ) -> Task<Result<R>>- where- R: Send + 'static,- {- if self.executor.is_main_thread() {- Task::ready(Ok(f(unsafe {- mem::transmute::<&mut Self, &mut MainThread<Self>>(self)- })))- } else {- let handle = self.window.handle;- self.app- .run_on_main(move |cx| handle.update(cx, |_, cx| f(cx)))- }- }-/// Create an `AsyncWindowContext`, which has a static lifetime and can be held across/// await points in async code.pub fn to_async(&self) -> AsyncWindowContext {@@@ -439,44 -379,39 +408,39 @@@pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {let f = Box::new(f);let display_id = self.window.display_id;- self.run_on_main(move |cx| {- if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {- callbacks.push(f);- // If there was already a callback, it means that we already scheduled a frame.- if callbacks.len() > 1 {- return;- }- } else {- let mut async_cx = cx.to_async();- cx.next_frame_callbacks.insert(display_id, vec![f]);- cx.platform().set_display_link_output_callback(- display_id,- Box::new(move |_current_time, _output_time| {- let _ = async_cx.update(|_, cx| {- let callbacks = cx- .next_frame_callbacks- .get_mut(&display_id)- .unwrap()- .drain(..)- .collect::<Vec<_>>();- for callback in callbacks {- callback(cx);- }- cx.run_on_main(move |cx| {- if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {- cx.platform().stop_display_link(display_id);- }- })- .detach();- });- }),- );+ if let Some(callbacks) = self.next_frame_callbacks.get_mut(&display_id) {+ callbacks.push(f);+ // If there was already a callback, it means that we already scheduled a frame.+ if callbacks.len() > 1 {+ return;}+ } else {+ let 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)+ .unwrap()+ .drain(..)+ .collect::<Vec<_>>();+ for callback in callbacks {+ callback(cx);+ }- cx.platform().start_display_link(display_id);- })- .detach();+ if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {+ cx.platform().stop_display_link(display_id);+ }+ });+ }),+ );+ }++ self.platform().start_display_link(display_id);}/// Spawn the future returned by the given closure on the application thread pool.@@@ -1283,10 -1211,10 +1241,10 @@@ impl Context for WindowContext<'_>build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,) -> Model<T>where- T: 'static + Send,+ T: '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)}@@@ -1322,10 -1238,10 +1280,10 @@@ 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 Self::ViewContext<'_, V>) -> V,) -> Self::Result<View<V>>where- V: 'static + Send,+ V: 'static,{let slot = self.app.entities.reserve();let view = View {@@@ -1880,11 -1742,14 +1821,11 @@@ impl<'a, V: 'static> ViewContext<'a, Vf: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,) -> Task<R>where- R: Send + 'static,- Fut: Future<Output = R> + Send + 'static,+ 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) -> R@@@ -1915,9 -1781,9 +1856,9 @@@pub fn on_mouse_event<Event: 'static>(&mut self,- handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + '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| {handle.update(cx, |view, cx| {handler(view, event, phase, cx);@@@ -1940,18 -1806,7 +1881,8 @@@ wher}}- impl<V: 'static> MainThread<ViewContext<'_, V>> {- fn platform_window(&self) -> &dyn PlatformWindow {- self.window.platform_window.borrow_on_main_thread().as_ref()- }-- pub fn activate_window(&self) {- self.platform_window().activate();- }- }--impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {+impl<V> Context for ViewContext<'_, V> {+ type WindowContext<'a> = WindowContext<'a>;type ModelContext<'b, U> = ModelContext<'b, U>;type Result<U> = U;@@@ -1972,21 -1824,14 +1900,21 @@@) -> R {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 Self::WindowContext<'_>) -> T,+ {+ self.window_cx.update_window(window, update)+ }}-impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {- type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;+impl<V: 'static> VisualContext for ViewContext<'_, V> {+ type ViewContext<'a, W: 'static> = ViewContext<'a, W>;- fn build_view<W: 'static + Send>(+ fn build_view<W: 'static>(&mut self,- build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W,+ build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,) -> Self::Result<View<W>> {self.window_cx.build_view(build_view)}