Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into multibuffer-following
Max Brunsfeldf797dfb88f64
diff --cc crates/editor/src/editor.rsindex de2db402043,ad21622fd9e..2cedc3e517c--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@@ -6584,30 -6085,8 +6096,16 @@@ impl Deref for EditorSnapshot}}- fn compute_scroll_position(- snapshot: &DisplaySnapshot,- mut scroll_position: Vector2F,- scroll_top_anchor: &Anchor,- ) -> Vector2F {- if *scroll_top_anchor != Anchor::min() {- let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;- scroll_position.set_y(scroll_top + scroll_position.y());- } else {- scroll_position.set_y(0.);- }- scroll_position- }--#[derive(Copy, Clone, Debug, PartialEq, Eq)]+#[derive(Clone, Debug, PartialEq, Eq)]pub enum Event {+ ExcerptsAdded {+ buffer: ModelHandle<Buffer>,+ predecessor: ExcerptId,+ excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,+ },+ ExcerptsRemoved {+ ids: Vec<ExcerptId>,+ },BufferEdited,Edited,Reparsed,@@@ -6615,14 -6094,9 +6113,13 @@@DirtyChanged,Saved,TitleChanged,- SelectionsChanged { local: bool },- ScrollPositionChanged { local: bool },+ SelectionsChanged {+ local: bool,+ },+ ScrollPositionChanged {+ local: bool,+ },Closed,- IgnoredInput,}pub struct EditorFocused(pub ViewHandle<Editor>);diff --cc crates/editor/src/items.rsindex 6447db02d0f,0efce57d5f2..49605a1d16c--- a/crates/editor/src/items.rs+++ b/crates/editor/src/items.rs@@@ -1,17 -1,9 +1,18 @@@+use crate::{+ display_map::ToDisplayPoint, link_go_to_definition::hide_link_definition,- movement::surrounding_word, Anchor, Autoscroll, Editor, Event, ExcerptId, ExcerptRange,- MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _, FORMAT_TIMEOUT,++ movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,++ Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _,++ FORMAT_TIMEOUT,+};- use anyhow::{anyhow, Result};+ use anyhow::{anyhow, Context, Result};+use collections::HashSet;+use futures::future::try_join_all;use futures::FutureExt;use gpui::{elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, MutableAppContext,- RenderContext, Subscription, Task, View, ViewContext, ViewHandle,+ RenderContext, Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle,};+use language::proto::serialize_anchor as serialize_text_anchor;use language::{Bias, Buffer, File as _, OffsetRangeExt, Point, SelectionGoal};use project::{File, FormatTrigger, Project, ProjectEntryId, ProjectPath};use rpc::proto::{self, update_view};@@@ -26,13 -17,20 +27,13 @@@ use std::path::{Path, PathBuf},};use text::Selection;- use util::TryFutureExt;+ use util::{ResultExt, TryFutureExt};use workspace::{+ item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},- FollowableItem, Item, ItemEvent, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView,- ToolbarItemLocation,+ ItemId, ItemNavHistory, Pane, StatusItemView, ToolbarItemLocation, Workspace, WorkspaceId,};-use crate::{- display_map::ToDisplayPoint, link_go_to_definition::hide_link_definition,- movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,- Event, ExcerptId, MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _,- FORMAT_TIMEOUT,-};-pub const MAX_TAB_TITLE_LEN: usize = 24;impl FollowableItem for Editor {@@@ -135,10 -86,19 +136,13 @@@if !selections.is_empty() {editor.set_selections_from_remote(selections, cx);}+- if let Some(anchor) = state.scroll_top_anchor {- editor.set_scroll_anchor_internal(+ if let Some(scroll_top_anchor) = scroll_top_anchor {- editor.set_scroll_top_anchor(- scroll_top_anchor,- vec2f(state.scroll_x, state.scroll_y),++ editor.set_scroll_anchor(+ ScrollAnchor {- top_anchor: Anchor {- buffer_id: Some(state.buffer_id as usize),- excerpt_id,- text_anchor: language::proto::deserialize_anchor(anchor)- .ok_or_else(|| anyhow!("invalid scroll top"))?,- },++ top_anchor: scroll_top_anchor,+ offset: vec2f(state.scroll_x, state.scroll_y),+ },- false,cx,);}@@@ -176,33 -135,15 +180,34 @@@}fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {- let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();+ let buffer = self.buffer.read(cx);+ let scroll_anchor = self.scroll_manager.anchor();+ let excerpts = buffer+ .read(cx)+ .excerpts()+ .map(|(id, buffer, range)| proto::Excerpt {+ id: id.to_proto(),+ buffer_id: buffer.remote_id(),+ context_start: Some(serialize_text_anchor(&range.context.start)),+ context_end: Some(serialize_text_anchor(&range.context.end)),+ primary_start: range+ .primary+ .as_ref()+ .map(|range| serialize_text_anchor(&range.start)),+ primary_end: range+ .primary+ .as_ref()+ .map(|range| serialize_text_anchor(&range.end)),+ })+ .collect();+Some(proto::view::Variant::Editor(proto::view::Editor {- buffer_id,- scroll_top_anchor: Some(language::proto::serialize_anchor(- &scroll_anchor.top_anchor.text_anchor,- )),+ singleton: buffer.is_singleton(),+ title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),+ excerpts,- scroll_top_anchor: Some(serialize_anchor(&self.scroll_top_anchor)),- scroll_x: self.scroll_position.x(),- scroll_y: self.scroll_position.y(),++ scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.top_anchor)),+ scroll_x: scroll_anchor.offset.x(),+ scroll_y: scroll_anchor.offset.y(),selections: self.selections.disjoint_anchors()@@@ -223,37 -164,13 +228,38 @@@match update {proto::update_view::Variant::Editor(update) => match event {+ Event::ExcerptsAdded {+ buffer,+ predecessor,+ excerpts,+ } => {+ let buffer_id = buffer.read(cx).remote_id();+ let mut excerpts = excerpts.iter();+ if let Some((id, range)) = excerpts.next() {+ update.inserted_excerpts.push(proto::ExcerptInsertion {+ previous_excerpt_id: Some(predecessor.to_proto()),+ excerpt: serialize_excerpt(buffer_id, id, range),+ });+ update.inserted_excerpts.extend(excerpts.map(|(id, range)| {+ proto::ExcerptInsertion {+ previous_excerpt_id: None,+ excerpt: serialize_excerpt(buffer_id, id, range),+ }+ }))+ }+ true+ }+ Event::ExcerptsRemoved { ids } => {+ update+ .deleted_excerpts+ .extend(ids.iter().map(ExcerptId::to_proto));+ true+ }Event::ScrollPositionChanged { .. } => {- update.scroll_top_anchor = Some(serialize_anchor(&self.scroll_top_anchor));- update.scroll_x = self.scroll_position.x();- update.scroll_y = self.scroll_position.y();+ let scroll_anchor = self.scroll_manager.anchor();- update.scroll_top_anchor = Some(language::proto::serialize_anchor(- &scroll_anchor.top_anchor.text_anchor,- ));++ update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.top_anchor));+ update.scroll_x = scroll_anchor.offset.x();+ update.scroll_y = scroll_anchor.offset.y();true}Event::SelectionsChanged { .. } => {@@@ -273,95 -190,45 +279,95 @@@fn apply_update_proto(&mut self,+ project: &ModelHandle<Project>,message: update_view::Variant,cx: &mut ViewContext<Self>,- ) -> Result<()> {- match message {- update_view::Variant::Editor(message) => {- let buffer = self.buffer.read(cx);- let buffer = buffer.read(cx);- let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();- let excerpt_id = excerpt_id.clone();- drop(buffer);+ ) -> Task<Result<()>> {+ let update_view::Variant::Editor(message) = message;+ let multibuffer = self.buffer.read(cx);+ let multibuffer = multibuffer.read(cx);- let selections = message- .selections- .into_iter()- .filter_map(|selection| {- deserialize_selection(&excerpt_id, buffer_id, selection)- })- .collect::<Vec<_>>();+ let buffer_ids = message+ .inserted_excerpts+ .iter()+ .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))+ .collect::<HashSet<_>>();++ let mut removals = message+ .deleted_excerpts+ .into_iter()+ .map(ExcerptId::from_proto)+ .collect::<Vec<_>>();+ removals.sort_by(|a, b| a.cmp(&b, &multibuffer));++ let selections = message+ .selections+ .into_iter()+ .filter_map(|selection| deserialize_selection(&multibuffer, selection))+ .collect::<Vec<_>>();+ let scroll_top_anchor = message+ .scroll_top_anchor+ .and_then(|anchor| deserialize_anchor(&multibuffer, anchor));+ drop(multibuffer);++ let buffers = project.update(cx, |project, cx| {+ buffer_ids+ .into_iter()+ .map(|id| project.open_buffer_by_id(id, cx))+ .collect::<Vec<_>>()+ });++ let project = project.clone();+ cx.spawn(|this, mut cx| async move {+ let _buffers = try_join_all(buffers).await?;+ this.update(&mut cx, |this, cx| {+ this.buffer.update(cx, |multibuffer, cx| {+ let mut insertions = message.inserted_excerpts.into_iter().peekable();+ while let Some(insertion) = insertions.next() {+ let Some(excerpt) = insertion.excerpt else { continue };+ let Some(previous_excerpt_id) = insertion.previous_excerpt_id else { continue };+ let buffer_id = excerpt.buffer_id;+ let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else { continue };++ let adjacent_excerpts = iter::from_fn(|| {+ let insertion = insertions.peek()?;+ if insertion.previous_excerpt_id.is_none()+ && insertion.excerpt.as_ref()?.buffer_id == buffer_id+ {+ insertions.next()?.excerpt+ } else {+ None+ }+ });++ multibuffer.insert_excerpts_with_ids_after(+ ExcerptId::from_proto(previous_excerpt_id),+ buffer,+ [excerpt]+ .into_iter()+ .chain(adjacent_excerpts)+ .filter_map(|excerpt| {+ Some((+ ExcerptId::from_proto(excerpt.id),+ deserialize_excerpt_range(excerpt)?,+ ))+ }),+ cx,+ );+ }++ multibuffer.remove_excerpts(removals, cx);+ });if !selections.is_empty() {- self.set_selections_from_remote(selections, cx);- self.request_autoscroll_remotely(Autoscroll::newest(), cx);- } else if let Some(anchor) = message.scroll_top_anchor {- self.set_scroll_anchor(- ScrollAnchor {- top_anchor: Anchor {- buffer_id: Some(buffer_id),- excerpt_id,- text_anchor: language::proto::deserialize_anchor(anchor)- .ok_or_else(|| anyhow!("invalid scroll top"))?,- },- offset: vec2f(message.scroll_x, message.scroll_y),- },- cx,- );+ this.set_selections_from_remote(selections, cx);+ this.request_autoscroll_remotely(Autoscroll::newest(), cx);+ } else if let Some(anchor) = scroll_top_anchor {- this.set_scroll_top_anchor(anchor, vec2f(message.scroll_x, message.scroll_y), cx);++ this.set_scroll_anchor(ScrollAnchor {top_anchor: anchor, offset: vec2f(message.scroll_x, message.scroll_y) }, cx);}- }- }- Ok(())+ });+ Ok(())+ })}fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {diff --cc crates/workspace/src/item.rsindex 00000000000,14f847fd54b..63394f361d9mode 000000,100644..100644--- a/crates/workspace/src/item.rs+++ b/crates/workspace/src/item.rs@@@ -1,0 -1,915 +1,918 @@@+ use std::{+ any::{Any, TypeId},+ borrow::Cow,+ cell::RefCell,+ fmt,+ path::PathBuf,+ rc::Rc,+ sync::atomic::{AtomicBool, Ordering},+ time::Duration,+ };++ use anyhow::Result;+ use client::proto;+ use gpui::{+ AnyViewHandle, AppContext, ElementBox, ModelHandle, MutableAppContext, Task, View, ViewContext,+ ViewHandle, WeakViewHandle,+ };+ use project::{Project, ProjectEntryId, ProjectPath};+ use settings::{Autosave, Settings};+ use smallvec::SmallVec;+ use theme::Theme;+ use util::ResultExt;++ use crate::{+ pane, persistence::model::ItemId, searchable::SearchableItemHandle, DelayedDebouncedEditAction,+ FollowableItemBuilders, ItemNavHistory, Pane, ToolbarItemLocation, Workspace, WorkspaceId,+ };++ #[derive(Eq, PartialEq, Hash)]+ pub enum ItemEvent {+ CloseItem,+ UpdateTab,+ UpdateBreadcrumbs,+ Edit,+ }++ pub trait Item: View {+ fn deactivated(&mut self, _: &mut ViewContext<Self>) {}+ fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}+ fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {+ false+ }+ fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {+ None+ }+ fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)+ -> ElementBox;+ fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;+ fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;+ fn is_singleton(&self, cx: &AppContext) -> bool;+ fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);+ fn clone_on_split(&self, _workspace_id: WorkspaceId, _: &mut ViewContext<Self>) -> Option<Self>+ where+ Self: Sized,+ {+ None+ }+ fn is_dirty(&self, _: &AppContext) -> bool {+ false+ }+ fn has_conflict(&self, _: &AppContext) -> bool {+ false+ }+ fn can_save(&self, cx: &AppContext) -> bool;+ fn save(+ &mut self,+ project: ModelHandle<Project>,+ cx: &mut ViewContext<Self>,+ ) -> Task<Result<()>>;+ fn save_as(+ &mut self,+ project: ModelHandle<Project>,+ abs_path: PathBuf,+ cx: &mut ViewContext<Self>,+ ) -> Task<Result<()>>;+ fn reload(+ &mut self,+ project: ModelHandle<Project>,+ cx: &mut ViewContext<Self>,+ ) -> Task<Result<()>>;+ fn git_diff_recalc(+ &mut self,+ _project: ModelHandle<Project>,+ _cx: &mut ViewContext<Self>,+ ) -> Task<Result<()>> {+ Task::ready(Ok(()))+ }+ fn to_item_events(event: &Self::Event) -> Vec<ItemEvent>;+ fn should_close_item_on_event(_: &Self::Event) -> bool {+ false+ }+ fn should_update_tab_on_event(_: &Self::Event) -> bool {+ false+ }+ fn is_edit_event(_: &Self::Event) -> bool {+ false+ }+ fn act_as_type(+ &self,+ type_id: TypeId,+ self_handle: &ViewHandle<Self>,+ _: &AppContext,+ ) -> Option<AnyViewHandle> {+ if TypeId::of::<Self>() == type_id {+ Some(self_handle.into())+ } else {+ None+ }+ }+ fn as_searchable(&self, _: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {+ None+ }++ fn breadcrumb_location(&self) -> ToolbarItemLocation {+ ToolbarItemLocation::Hidden+ }++ fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<ElementBox>> {+ None+ }++ fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}++ fn serialized_item_kind() -> Option<&'static str>;++ fn deserialize(+ project: ModelHandle<Project>,+ workspace: WeakViewHandle<Workspace>,+ workspace_id: WorkspaceId,+ item_id: ItemId,+ cx: &mut ViewContext<Pane>,+ ) -> Task<Result<ViewHandle<Self>>>;+ }++ pub trait ItemHandle: 'static + fmt::Debug {+ fn subscribe_to_item_events(+ &self,+ cx: &mut MutableAppContext,+ handler: Box<dyn Fn(ItemEvent, &mut MutableAppContext)>,+ ) -> gpui::Subscription;+ fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;+ fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)+ -> ElementBox;+ fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;+ fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;+ fn is_singleton(&self, cx: &AppContext) -> bool;+ fn boxed_clone(&self) -> Box<dyn ItemHandle>;+ fn clone_on_split(+ &self,+ workspace_id: WorkspaceId,+ cx: &mut MutableAppContext,+ ) -> Option<Box<dyn ItemHandle>>;+ fn added_to_pane(+ &self,+ workspace: &mut Workspace,+ pane: ViewHandle<Pane>,+ cx: &mut ViewContext<Workspace>,+ );+ fn deactivated(&self, cx: &mut MutableAppContext);+ fn workspace_deactivated(&self, cx: &mut MutableAppContext);+ fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;+ fn id(&self) -> usize;+ fn window_id(&self) -> usize;+ fn to_any(&self) -> AnyViewHandle;+ fn is_dirty(&self, cx: &AppContext) -> bool;+ fn has_conflict(&self, cx: &AppContext) -> bool;+ fn can_save(&self, cx: &AppContext) -> bool;+ fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;+ fn save_as(+ &self,+ project: ModelHandle<Project>,+ abs_path: PathBuf,+ cx: &mut MutableAppContext,+ ) -> Task<Result<()>>;+ fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)+ -> Task<Result<()>>;+ fn git_diff_recalc(+ &self,+ project: ModelHandle<Project>,+ cx: &mut MutableAppContext,+ ) -> Task<Result<()>>;+ fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;+ fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;+ fn on_release(+ &self,+ cx: &mut MutableAppContext,+ callback: Box<dyn FnOnce(&mut MutableAppContext)>,+ ) -> gpui::Subscription;+ fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;+ fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;+ fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<ElementBox>>;+ fn serialized_item_kind(&self) -> Option<&'static str>;+ }++ pub trait WeakItemHandle {+ fn id(&self) -> usize;+ fn window_id(&self) -> usize;+ fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;+ }++ impl dyn ItemHandle {+ pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {+ self.to_any().downcast()+ }++ pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {+ self.act_as_type(TypeId::of::<T>(), cx)+ .and_then(|t| t.downcast())+ }+ }++ impl<T: Item> ItemHandle for ViewHandle<T> {+ fn subscribe_to_item_events(+ &self,+ cx: &mut MutableAppContext,+ handler: Box<dyn Fn(ItemEvent, &mut MutableAppContext)>,+ ) -> gpui::Subscription {+ cx.subscribe(self, move |_, event, cx| {+ for item_event in T::to_item_events(event) {+ handler(item_event, cx)+ }+ })+ }++ fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {+ self.read(cx).tab_description(detail, cx)+ }++ fn tab_content(+ &self,+ detail: Option<usize>,+ style: &theme::Tab,+ cx: &AppContext,+ ) -> ElementBox {+ self.read(cx).tab_content(detail, style, cx)+ }++ fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {+ self.read(cx).project_path(cx)+ }++ fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {+ self.read(cx).project_entry_ids(cx)+ }++ fn is_singleton(&self, cx: &AppContext) -> bool {+ self.read(cx).is_singleton(cx)+ }++ fn boxed_clone(&self) -> Box<dyn ItemHandle> {+ Box::new(self.clone())+ }++ fn clone_on_split(+ &self,+ workspace_id: WorkspaceId,+ cx: &mut MutableAppContext,+ ) -> Option<Box<dyn ItemHandle>> {+ self.update(cx, |item, cx| {+ cx.add_option_view(|cx| item.clone_on_split(workspace_id, cx))+ })+ .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)+ }++ fn added_to_pane(+ &self,+ workspace: &mut Workspace,+ pane: ViewHandle<Pane>,+ cx: &mut ViewContext<Workspace>,+ ) {+ let history = pane.read(cx).nav_history_for_item(self);+ self.update(cx, |this, cx| {+ this.set_nav_history(history, cx);+ this.added_to_workspace(workspace, cx);+ });++ if let Some(followed_item) = self.to_followable_item_handle(cx) {+ if let Some(message) = followed_item.to_state_proto(cx) {+ workspace.update_followers(+ proto::update_followers::Variant::CreateView(proto::View {+ id: followed_item.id() as u64,+ variant: Some(message),+ leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),+ }),+ cx,+ );+ }+ }++ if workspace+ .panes_by_item+ .insert(self.id(), pane.downgrade())+ .is_none()+ {+ let mut pending_autosave = DelayedDebouncedEditAction::new();+ let mut pending_git_update = DelayedDebouncedEditAction::new();+ let pending_update = Rc::new(RefCell::new(None));+ let pending_update_scheduled = Rc::new(AtomicBool::new(false));++ let mut event_subscription =+ Some(cx.subscribe(self, move |workspace, item, event, cx| {+ let pane = if let Some(pane) = workspace+ .panes_by_item+ .get(&item.id())+ .and_then(|pane| pane.upgrade(cx))+ {+ pane+ } else {+ log::error!("unexpected item event after pane was dropped");+ return;+ };++ if let Some(item) = item.to_followable_item_handle(cx) {+ let leader_id = workspace.leader_for_pane(&pane);++ if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {+ workspace.unfollow(&pane, cx);+ }++ if item.add_event_to_update_proto(+ event,+ &mut *pending_update.borrow_mut(),+ cx,+ ) && !pending_update_scheduled.load(Ordering::SeqCst)+ {+ pending_update_scheduled.store(true, Ordering::SeqCst);+ cx.after_window_update({+ let pending_update = pending_update.clone();+ let pending_update_scheduled = pending_update_scheduled.clone();+ move |this, cx| {+ pending_update_scheduled.store(false, Ordering::SeqCst);+ this.update_followers(+ proto::update_followers::Variant::UpdateView(+ proto::UpdateView {+ id: item.id() as u64,+ variant: pending_update.borrow_mut().take(),+ leader_id: leader_id.map(|id| id.0),+ },+ ),+ cx,+ );+ }+ });+ }+ }++ for item_event in T::to_item_events(event).into_iter() {+ match item_event {+ ItemEvent::CloseItem => {+ Pane::close_item(workspace, pane, item.id(), cx)+ .detach_and_log_err(cx);+ return;+ }++ ItemEvent::UpdateTab => {+ pane.update(cx, |_, cx| {+ cx.emit(pane::Event::ChangeItemTitle);+ cx.notify();+ });+ }++ ItemEvent::Edit => {+ if let Autosave::AfterDelay { milliseconds } =+ cx.global::<Settings>().autosave+ {+ let delay = Duration::from_millis(milliseconds);+ let item = item.clone();+ pending_autosave.fire_new(+ delay,+ workspace,+ cx,+ |project, mut cx| async move {+ cx.update(|cx| Pane::autosave_item(&item, project, cx))+ .await+ .log_err();+ },+ );+ }++ let settings = cx.global::<Settings>();+ let debounce_delay = settings.git_overrides.gutter_debounce;++ let item = item.clone();++ if let Some(delay) = debounce_delay {+ const MIN_GIT_DELAY: u64 = 50;++ let delay = delay.max(MIN_GIT_DELAY);+ let duration = Duration::from_millis(delay);++ pending_git_update.fire_new(+ duration,+ workspace,+ cx,+ |project, mut cx| async move {+ cx.update(|cx| item.git_diff_recalc(project, cx))+ .await+ .log_err();+ },+ );+ } else {+ let project = workspace.project().downgrade();+ cx.spawn_weak(|_, mut cx| async move {+ if let Some(project) = project.upgrade(&cx) {+ cx.update(|cx| item.git_diff_recalc(project, cx))+ .await+ .log_err();+ }+ })+ .detach();+ }+ }++ _ => {}+ }+ }+ }));++ cx.observe_focus(self, move |workspace, item, focused, cx| {+ if !focused && cx.global::<Settings>().autosave == Autosave::OnFocusChange {+ Pane::autosave_item(&item, workspace.project.clone(), cx)+ .detach_and_log_err(cx);+ }+ })+ .detach();++ let item_id = self.id();+ cx.observe_release(self, move |workspace, _, _| {+ workspace.panes_by_item.remove(&item_id);+ event_subscription.take();+ })+ .detach();+ }++ cx.defer(|workspace, cx| {+ workspace.serialize_workspace(cx);+ });+ }++ fn deactivated(&self, cx: &mut MutableAppContext) {+ self.update(cx, |this, cx| this.deactivated(cx));+ }++ fn workspace_deactivated(&self, cx: &mut MutableAppContext) {+ self.update(cx, |this, cx| this.workspace_deactivated(cx));+ }++ fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {+ self.update(cx, |this, cx| this.navigate(data, cx))+ }++ fn id(&self) -> usize {+ self.id()+ }++ fn window_id(&self) -> usize {+ self.window_id()+ }++ fn to_any(&self) -> AnyViewHandle {+ self.into()+ }++ fn is_dirty(&self, cx: &AppContext) -> bool {+ self.read(cx).is_dirty(cx)+ }++ fn has_conflict(&self, cx: &AppContext) -> bool {+ self.read(cx).has_conflict(cx)+ }++ fn can_save(&self, cx: &AppContext) -> bool {+ self.read(cx).can_save(cx)+ }++ fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {+ self.update(cx, |item, cx| item.save(project, cx))+ }++ fn save_as(+ &self,+ project: ModelHandle<Project>,+ abs_path: PathBuf,+ cx: &mut MutableAppContext,+ ) -> Task<anyhow::Result<()>> {+ self.update(cx, |item, cx| item.save_as(project, abs_path, cx))+ }++ fn reload(+ &self,+ project: ModelHandle<Project>,+ cx: &mut MutableAppContext,+ ) -> Task<Result<()>> {+ self.update(cx, |item, cx| item.reload(project, cx))+ }++ fn git_diff_recalc(+ &self,+ project: ModelHandle<Project>,+ cx: &mut MutableAppContext,+ ) -> Task<Result<()>> {+ self.update(cx, |item, cx| item.git_diff_recalc(project, cx))+ }++ fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {+ self.read(cx).act_as_type(type_id, self, cx)+ }++ fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {+ if cx.has_global::<FollowableItemBuilders>() {+ let builders = cx.global::<FollowableItemBuilders>();+ let item = self.to_any();+ Some(builders.get(&item.view_type())?.1(item))+ } else {+ None+ }+ }++ fn on_release(+ &self,+ cx: &mut MutableAppContext,+ callback: Box<dyn FnOnce(&mut MutableAppContext)>,+ ) -> gpui::Subscription {+ cx.observe_release(self, move |_, cx| callback(cx))+ }++ fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {+ self.read(cx).as_searchable(self)+ }++ fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {+ self.read(cx).breadcrumb_location()+ }++ fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<ElementBox>> {+ self.read(cx).breadcrumbs(theme, cx)+ }++ fn serialized_item_kind(&self) -> Option<&'static str> {+ T::serialized_item_kind()+ }+ }++ impl From<Box<dyn ItemHandle>> for AnyViewHandle {+ fn from(val: Box<dyn ItemHandle>) -> Self {+ val.to_any()+ }+ }++ impl From<&Box<dyn ItemHandle>> for AnyViewHandle {+ fn from(val: &Box<dyn ItemHandle>) -> Self {+ val.to_any()+ }+ }++ impl Clone for Box<dyn ItemHandle> {+ fn clone(&self) -> Box<dyn ItemHandle> {+ self.boxed_clone()+ }+ }++ impl<T: Item> WeakItemHandle for WeakViewHandle<T> {+ fn id(&self) -> usize {+ self.id()+ }++ fn window_id(&self) -> usize {+ self.window_id()+ }++ fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {+ self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)+ }+ }++ pub trait ProjectItem: Item {+ type Item: project::Item;++ fn for_project_item(+ project: ModelHandle<Project>,+ item: ModelHandle<Self::Item>,+ cx: &mut ViewContext<Self>,+ ) -> Self;+ }++ pub trait FollowableItem: Item {+ fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;+ fn from_state_proto(+ pane: ViewHandle<Pane>,+ project: ModelHandle<Project>,+ state: &mut Option<proto::view::Variant>,+ cx: &mut MutableAppContext,+ ) -> Option<Task<Result<ViewHandle<Self>>>>;+ fn add_event_to_update_proto(+ &self,+ event: &Self::Event,+ update: &mut Option<proto::update_view::Variant>,+ cx: &AppContext,+ ) -> bool;+ fn apply_update_proto(+ &mut self,++ project: &ModelHandle<Project>,+ message: proto::update_view::Variant,+ cx: &mut ViewContext<Self>,- ) -> Result<()>;++ ) -> Task<Result<()>>;++ fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);+ fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;+ }++ pub trait FollowableItemHandle: ItemHandle {+ fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);+ fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;+ fn add_event_to_update_proto(+ &self,+ event: &dyn Any,+ update: &mut Option<proto::update_view::Variant>,+ cx: &AppContext,+ ) -> bool;+ fn apply_update_proto(+ &self,++ project: &ModelHandle<Project>,+ message: proto::update_view::Variant,+ cx: &mut MutableAppContext,- ) -> Result<()>;++ ) -> Task<Result<()>>;+ fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;+ }++ impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {+ fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {+ self.update(cx, |this, cx| {+ this.set_leader_replica_id(leader_replica_id, cx)+ })+ }++ fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {+ self.read(cx).to_state_proto(cx)+ }++ fn add_event_to_update_proto(+ &self,+ event: &dyn Any,+ update: &mut Option<proto::update_view::Variant>,+ cx: &AppContext,+ ) -> bool {+ if let Some(event) = event.downcast_ref() {+ self.read(cx).add_event_to_update_proto(event, update, cx)+ } else {+ false+ }+ }++ fn apply_update_proto(+ &self,++ project: &ModelHandle<Project>,+ message: proto::update_view::Variant,+ cx: &mut MutableAppContext,- ) -> Result<()> {- self.update(cx, |this, cx| this.apply_update_proto(message, cx))++ ) -> Task<Result<()>> {++ self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))+ }++ fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {+ if let Some(event) = event.downcast_ref() {+ T::should_unfollow_on_event(event, cx)+ } else {+ false+ }+ }+ }++ #[cfg(test)]+ pub(crate) mod test {+ use std::{any::Any, borrow::Cow, cell::Cell};++ use gpui::{+ elements::Empty, AppContext, Element, ElementBox, Entity, ModelHandle, RenderContext, Task,+ View, ViewContext, ViewHandle, WeakViewHandle,+ };+ use project::{Project, ProjectEntryId, ProjectPath};+ use smallvec::SmallVec;++ use crate::{sidebar::SidebarItem, ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};++ use super::{Item, ItemEvent};++ pub struct TestItem {+ pub workspace_id: WorkspaceId,+ pub state: String,+ pub label: String,+ pub save_count: usize,+ pub save_as_count: usize,+ pub reload_count: usize,+ pub is_dirty: bool,+ pub is_singleton: bool,+ pub has_conflict: bool,+ pub project_entry_ids: Vec<ProjectEntryId>,+ pub project_path: Option<ProjectPath>,+ pub nav_history: Option<ItemNavHistory>,+ pub tab_descriptions: Option<Vec<&'static str>>,+ pub tab_detail: Cell<Option<usize>>,+ }++ pub enum TestItemEvent {+ Edit,+ }++ impl Clone for TestItem {+ fn clone(&self) -> Self {+ Self {+ state: self.state.clone(),+ label: self.label.clone(),+ save_count: self.save_count,+ save_as_count: self.save_as_count,+ reload_count: self.reload_count,+ is_dirty: self.is_dirty,+ is_singleton: self.is_singleton,+ has_conflict: self.has_conflict,+ project_entry_ids: self.project_entry_ids.clone(),+ project_path: self.project_path.clone(),+ nav_history: None,+ tab_descriptions: None,+ tab_detail: Default::default(),+ workspace_id: self.workspace_id,+ }+ }+ }++ impl TestItem {+ pub fn new() -> Self {+ Self {+ state: String::new(),+ label: String::new(),+ save_count: 0,+ save_as_count: 0,+ reload_count: 0,+ is_dirty: false,+ has_conflict: false,+ project_entry_ids: Vec::new(),+ project_path: None,+ is_singleton: true,+ nav_history: None,+ tab_descriptions: None,+ tab_detail: Default::default(),+ workspace_id: 0,+ }+ }++ pub fn new_deserialized(id: WorkspaceId) -> Self {+ let mut this = Self::new();+ this.workspace_id = id;+ this+ }++ pub fn with_label(mut self, state: &str) -> Self {+ self.label = state.to_string();+ self+ }++ pub fn with_singleton(mut self, singleton: bool) -> Self {+ self.is_singleton = singleton;+ self+ }++ pub fn with_project_entry_ids(mut self, project_entry_ids: &[u64]) -> Self {+ self.project_entry_ids.extend(+ project_entry_ids+ .iter()+ .copied()+ .map(ProjectEntryId::from_proto),+ );+ self+ }++ pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {+ self.push_to_nav_history(cx);+ self.state = state;+ }++ fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {+ if let Some(history) = &mut self.nav_history {+ history.push(Some(Box::new(self.state.clone())), cx);+ }+ }+ }++ impl Entity for TestItem {+ type Event = TestItemEvent;+ }++ impl View for TestItem {+ fn ui_name() -> &'static str {+ "TestItem"+ }++ fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {+ Empty::new().boxed()+ }+ }++ impl Item for TestItem {+ fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {+ self.tab_descriptions.as_ref().and_then(|descriptions| {+ let description = *descriptions.get(detail).or_else(|| descriptions.last())?;+ Some(description.into())+ })+ }++ fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {+ self.tab_detail.set(detail);+ Empty::new().boxed()+ }++ fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {+ self.project_path.clone()+ }++ fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {+ self.project_entry_ids.iter().copied().collect()+ }++ fn is_singleton(&self, _: &AppContext) -> bool {+ self.is_singleton+ }++ fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {+ self.nav_history = Some(history);+ }++ fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {+ let state = *state.downcast::<String>().unwrap_or_default();+ if state != self.state {+ self.state = state;+ true+ } else {+ false+ }+ }++ fn deactivated(&mut self, cx: &mut ViewContext<Self>) {+ self.push_to_nav_history(cx);+ }++ fn clone_on_split(+ &self,+ _workspace_id: WorkspaceId,+ _: &mut ViewContext<Self>,+ ) -> Option<Self>+ where+ Self: Sized,+ {+ Some(self.clone())+ }++ fn is_dirty(&self, _: &AppContext) -> bool {+ self.is_dirty+ }++ fn has_conflict(&self, _: &AppContext) -> bool {+ self.has_conflict+ }++ fn can_save(&self, _: &AppContext) -> bool {+ !self.project_entry_ids.is_empty()+ }++ fn save(+ &mut self,+ _: ModelHandle<Project>,+ _: &mut ViewContext<Self>,+ ) -> Task<anyhow::Result<()>> {+ self.save_count += 1;+ self.is_dirty = false;+ Task::ready(Ok(()))+ }++ fn save_as(+ &mut self,+ _: ModelHandle<Project>,+ _: std::path::PathBuf,+ _: &mut ViewContext<Self>,+ ) -> Task<anyhow::Result<()>> {+ self.save_as_count += 1;+ self.is_dirty = false;+ Task::ready(Ok(()))+ }++ fn reload(+ &mut self,+ _: ModelHandle<Project>,+ _: &mut ViewContext<Self>,+ ) -> Task<anyhow::Result<()>> {+ self.reload_count += 1;+ self.is_dirty = false;+ Task::ready(Ok(()))+ }++ fn to_item_events(_: &Self::Event) -> Vec<ItemEvent> {+ vec![ItemEvent::UpdateTab, ItemEvent::Edit]+ }++ fn serialized_item_kind() -> Option<&'static str> {+ None+ }++ fn deserialize(+ _project: ModelHandle<Project>,+ _workspace: WeakViewHandle<Workspace>,+ workspace_id: WorkspaceId,+ _item_id: ItemId,+ cx: &mut ViewContext<Pane>,+ ) -> Task<anyhow::Result<ViewHandle<Self>>> {+ let view = cx.add_view(|_cx| Self::new_deserialized(workspace_id));+ Task::Ready(Some(anyhow::Ok(view)))+ }+ }++ impl SidebarItem for TestItem {}+ }diff --cc crates/workspace/src/workspace.rsindex e60c1fe3be7,7dc8ddab067..0d1564c396b--- a/crates/workspace/src/workspace.rs+++ b/crates/workspace/src/workspace.rs@@@ -15,14 -27,10 +18,14 @@@ use anyhow::{anyhow, Result}use call::ActiveCall;use client::{proto, Client, PeerId, TypedEnvelope, UserStore};use collections::{hash_map, HashMap, HashSet};- use dock::{DefaultItemFactory, Dock, ToggleDockButton};+ use dock::{Dock, DockDefaultItemFactory, ToggleDockButton};use drag_and_drop::DragAndDrop;use fs::{self, Fs};-use futures::{channel::oneshot, FutureExt, StreamExt};+use futures::{+ channel::{mpsc, oneshot},+ future::try_join_all,+ FutureExt, StreamExt,+};use gpui::{actions,elements::*,@@@ -32,13 -40,20 +35,32 @@@MouseButton, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, Task, View,ViewContext, ViewHandle, WeakViewHandle,};+ use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ProjectItem};use language::LanguageRegistry;++use std::{++ any::TypeId,++ borrow::Cow,++ future::Future,++ path::{Path, PathBuf},++ sync::Arc,++ time::Duration,++};+++use crate::{++ notifications::simple_message_notification::{MessageNotification, OsOpen},++ persistence::model::{SerializedPane, SerializedPaneGroup, SerializedWorkspace},++};use log::{error, warn};+ use notifications::NotificationHandle;pub use pane::*;pub use pane_group::*;+ use persistence::{model::SerializedItem, DB};+ pub use persistence::{+ model::{ItemId, WorkspaceLocation},+ WorkspaceDb,+ };use postage::prelude::Stream;- use project::{Project, ProjectEntryId, ProjectPath, ProjectStore, Worktree, WorktreeId};- use searchable::SearchableItemHandle;+ use project::{Project, ProjectEntryId, ProjectPath, Worktree, WorktreeId};use serde::Deserialize;use settings::{Autosave, DockAnchor, Settings};use shared_screen::SharedScreen;@@@ -64,25 -64,11 +71,6 @@@ use theme::{Theme, ThemeRegistry}pub use toolbar::{ToolbarItemLocation, ToolbarItemView};use util::ResultExt;- type ProjectItemBuilders = HashMap<- TypeId,- fn(ModelHandle<Project>, AnyModelHandle, &mut ViewContext<Pane>) -> Box<dyn ItemHandle>,- >;-- type FollowableItemBuilder = fn(- ViewHandle<Pane>,- ModelHandle<Project>,- &mut Option<proto::view::Variant>,- &mut MutableAppContext,- ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;- type FollowableItemBuilders = HashMap<- TypeId,- (- FollowableItemBuilder,- fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,- ),- >;-use crate::{- notifications::simple_message_notification::{MessageNotification, OsOpen},- persistence::model::{SerializedPane, SerializedPaneGroup, SerializedWorkspace},-};--#[derive(Clone, PartialEq)]pub struct RemoveWorktreeFromProject(pub WorktreeId);@@@ -587,482 -457,25 +459,6 @@@ impl DelayedDebouncedEditAction}}- pub trait ItemHandle: 'static + fmt::Debug {- fn subscribe_to_item_events(- &self,- cx: &mut MutableAppContext,- handler: Box<dyn Fn(ItemEvent, &mut MutableAppContext)>,- ) -> gpui::Subscription;- fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;- fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)- -> ElementBox;- fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;- fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;- fn is_singleton(&self, cx: &AppContext) -> bool;- fn boxed_clone(&self) -> Box<dyn ItemHandle>;- fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;- fn added_to_pane(- &self,- workspace: &mut Workspace,- pane: ViewHandle<Pane>,- cx: &mut ViewContext<Workspace>,- );- fn deactivated(&self, cx: &mut MutableAppContext);- fn workspace_deactivated(&self, cx: &mut MutableAppContext);- fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;- fn id(&self) -> usize;- fn window_id(&self) -> usize;- fn to_any(&self) -> AnyViewHandle;- fn is_dirty(&self, cx: &AppContext) -> bool;- fn has_conflict(&self, cx: &AppContext) -> bool;- fn can_save(&self, cx: &AppContext) -> bool;- fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;- fn save_as(- &self,- project: ModelHandle<Project>,- abs_path: PathBuf,- cx: &mut MutableAppContext,- ) -> Task<Result<()>>;- fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)- -> Task<Result<()>>;- fn git_diff_recalc(- &self,- project: ModelHandle<Project>,- cx: &mut MutableAppContext,- ) -> Task<Result<()>>;- fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;- fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;- fn on_release(- &self,- cx: &mut MutableAppContext,- callback: Box<dyn FnOnce(&mut MutableAppContext)>,- ) -> gpui::Subscription;- fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;- fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;- fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<ElementBox>>;- }-- pub trait WeakItemHandle {- fn id(&self) -> usize;- fn window_id(&self) -> usize;- fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;- }-- impl dyn ItemHandle {- pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {- self.to_any().downcast()- }-- pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {- self.act_as_type(TypeId::of::<T>(), cx)- .and_then(|t| t.downcast())- }- }-- impl<T: Item> ItemHandle for ViewHandle<T> {- fn subscribe_to_item_events(- &self,- cx: &mut MutableAppContext,- handler: Box<dyn Fn(ItemEvent, &mut MutableAppContext)>,- ) -> gpui::Subscription {- cx.subscribe(self, move |_, event, cx| {- for item_event in T::to_item_events(event) {- handler(item_event, cx)- }- })- }-- fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {- self.read(cx).tab_description(detail, cx)- }-- fn tab_content(- &self,- detail: Option<usize>,- style: &theme::Tab,- cx: &AppContext,- ) -> ElementBox {- self.read(cx).tab_content(detail, style, cx)- }-- fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {- self.read(cx).project_path(cx)- }-- fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {- self.read(cx).project_entry_ids(cx)- }-- fn is_singleton(&self, cx: &AppContext) -> bool {- self.read(cx).is_singleton(cx)- }-- fn boxed_clone(&self) -> Box<dyn ItemHandle> {- Box::new(self.clone())- }-- fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {- self.update(cx, |item, cx| {- cx.add_option_view(|cx| item.clone_on_split(cx))- })- .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)- }-- fn added_to_pane(- &self,- workspace: &mut Workspace,- pane: ViewHandle<Pane>,- cx: &mut ViewContext<Workspace>,- ) {- let history = pane.read(cx).nav_history_for_item(self);- self.update(cx, |this, cx| this.set_nav_history(history, cx));-- if let Some(followed_item) = self.to_followable_item_handle(cx) {- if let Some(message) = followed_item.to_state_proto(cx) {- workspace.update_followers(- proto::update_followers::Variant::CreateView(proto::View {- id: followed_item.id() as u64,- variant: Some(message),- leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),- }),- cx,- );- }- }-- if workspace- .panes_by_item- .insert(self.id(), pane.downgrade())- .is_none()- {- let mut pending_autosave = DelayedDebouncedEditAction::new();- let mut pending_git_update = DelayedDebouncedEditAction::new();- let pending_update = Rc::new(RefCell::new(None));- let pending_update_scheduled = Rc::new(AtomicBool::new(false));-- let mut event_subscription =- Some(cx.subscribe(self, move |workspace, item, event, cx| {- let pane = if let Some(pane) = workspace- .panes_by_item- .get(&item.id())- .and_then(|pane| pane.upgrade(cx))- {- pane- } else {- log::error!("unexpected item event after pane was dropped");- return;- };-- if let Some(item) = item.to_followable_item_handle(cx) {- let leader_id = workspace.leader_for_pane(&pane);-- if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {- workspace.unfollow(&pane, cx);- }-- if item.add_event_to_update_proto(- event,- &mut *pending_update.borrow_mut(),- cx,- ) && !pending_update_scheduled.load(SeqCst)- {- pending_update_scheduled.store(true, SeqCst);- cx.after_window_update({- let pending_update = pending_update.clone();- let pending_update_scheduled = pending_update_scheduled.clone();- move |this, cx| {- pending_update_scheduled.store(false, SeqCst);- this.update_followers(- proto::update_followers::Variant::UpdateView(- proto::UpdateView {- id: item.id() as u64,- variant: pending_update.borrow_mut().take(),- leader_id: leader_id.map(|id| id.0),- },- ),- cx,- );- }- });- }- }-- for item_event in T::to_item_events(event).into_iter() {- match item_event {- ItemEvent::CloseItem => {- Pane::close_item(workspace, pane, item.id(), cx)- .detach_and_log_err(cx);- return;- }-- ItemEvent::UpdateTab => {- pane.update(cx, |_, cx| {- cx.emit(pane::Event::ChangeItemTitle);- cx.notify();- });- }-- ItemEvent::Edit => {- if let Autosave::AfterDelay { milliseconds } =- cx.global::<Settings>().autosave- {- let delay = Duration::from_millis(milliseconds);- let item = item.clone();- pending_autosave.fire_new(- delay,- workspace,- cx,- |project, mut cx| async move {- cx.update(|cx| Pane::autosave_item(&item, project, cx))- .await- .log_err();- },- );- }-- let settings = cx.global::<Settings>();- let debounce_delay = settings.git_overrides.gutter_debounce;-- let item = item.clone();-- if let Some(delay) = debounce_delay {- const MIN_GIT_DELAY: u64 = 50;-- let delay = delay.max(MIN_GIT_DELAY);- let duration = Duration::from_millis(delay);-- pending_git_update.fire_new(- duration,- workspace,- cx,- |project, mut cx| async move {- cx.update(|cx| item.git_diff_recalc(project, cx))- .await- .log_err();- },- );- } else {- let project = workspace.project().downgrade();- cx.spawn_weak(|_, mut cx| async move {- if let Some(project) = project.upgrade(&cx) {- cx.update(|cx| item.git_diff_recalc(project, cx))- .await- .log_err();- }- })- .detach();- }- }-- _ => {}- }- }- }));-- cx.observe_focus(self, move |workspace, item, focused, cx| {- if !focused && cx.global::<Settings>().autosave == Autosave::OnFocusChange {- Pane::autosave_item(&item, workspace.project.clone(), cx)- .detach_and_log_err(cx);- }- })- .detach();-- let item_id = self.id();- cx.observe_release(self, move |workspace, _, _| {- workspace.panes_by_item.remove(&item_id);- event_subscription.take();- })- .detach();- }- }-- fn deactivated(&self, cx: &mut MutableAppContext) {- self.update(cx, |this, cx| this.deactivated(cx));- }-- fn workspace_deactivated(&self, cx: &mut MutableAppContext) {- self.update(cx, |this, cx| this.workspace_deactivated(cx));- }-- fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {- self.update(cx, |this, cx| this.navigate(data, cx))- }-- fn id(&self) -> usize {- self.id()- }-- fn window_id(&self) -> usize {- self.window_id()- }-- fn to_any(&self) -> AnyViewHandle {- self.into()- }-- fn is_dirty(&self, cx: &AppContext) -> bool {- self.read(cx).is_dirty(cx)- }-- fn has_conflict(&self, cx: &AppContext) -> bool {- self.read(cx).has_conflict(cx)- }-- fn can_save(&self, cx: &AppContext) -> bool {- self.read(cx).can_save(cx)- }-- fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {- self.update(cx, |item, cx| item.save(project, cx))- }-- fn save_as(- &self,- project: ModelHandle<Project>,- abs_path: PathBuf,- cx: &mut MutableAppContext,- ) -> Task<anyhow::Result<()>> {- self.update(cx, |item, cx| item.save_as(project, abs_path, cx))- }-- fn reload(- &self,- project: ModelHandle<Project>,- cx: &mut MutableAppContext,- ) -> Task<Result<()>> {- self.update(cx, |item, cx| item.reload(project, cx))- }-- fn git_diff_recalc(- &self,- project: ModelHandle<Project>,- cx: &mut MutableAppContext,- ) -> Task<Result<()>> {- self.update(cx, |item, cx| item.git_diff_recalc(project, cx))- }-- fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {- self.read(cx).act_as_type(type_id, self, cx)- }-- fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {- if cx.has_global::<FollowableItemBuilders>() {- let builders = cx.global::<FollowableItemBuilders>();- let item = self.to_any();- Some(builders.get(&item.view_type())?.1(item))- } else {- None- }- }-- fn on_release(- &self,- cx: &mut MutableAppContext,- callback: Box<dyn FnOnce(&mut MutableAppContext)>,- ) -> gpui::Subscription {- cx.observe_release(self, move |_, cx| callback(cx))- }-- fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {- self.read(cx).as_searchable(self)- }-- fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {- self.read(cx).breadcrumb_location()- }-- fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<ElementBox>> {- self.read(cx).breadcrumbs(theme, cx)- }- }-- impl From<Box<dyn ItemHandle>> for AnyViewHandle {- fn from(val: Box<dyn ItemHandle>) -> Self {- val.to_any()- }- }-- impl From<&Box<dyn ItemHandle>> for AnyViewHandle {- fn from(val: &Box<dyn ItemHandle>) -> Self {- val.to_any()- }- }-- impl Clone for Box<dyn ItemHandle> {- fn clone(&self) -> Box<dyn ItemHandle> {- self.boxed_clone()- }- }-- impl<T: Item> WeakItemHandle for WeakViewHandle<T> {- fn id(&self) -> usize {- self.id()- }-- fn window_id(&self) -> usize {- self.window_id()- }-- fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {- self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)- }- }-- pub trait Notification: View {- fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool;- }-- pub trait NotificationHandle {- fn id(&self) -> usize;- fn to_any(&self) -> AnyViewHandle;-#[derive(Default)]-struct LeaderState {- followers: HashSet<PeerId>,--}-- impl<T: Notification> NotificationHandle for ViewHandle<T> {- fn id(&self) -> usize {- self.id()- }--- fn to_any(&self) -> AnyViewHandle {- self.into()- }- }-type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;--- impl From<&dyn NotificationHandle> for AnyViewHandle {- fn from(val: &dyn NotificationHandle) -> Self {- val.to_any()- }-#[derive(Default)]-struct FollowerState {- active_view_id: Option<u64>,- items_by_leader_view_id: HashMap<u64, FollowerItem>,--}-- impl AppState {- #[cfg(any(test, feature = "test-support"))]- pub fn test(cx: &mut MutableAppContext) -> Arc<Self> {- use fs::HomeDir;-- cx.set_global(HomeDir(Path::new("/tmp/").to_path_buf()));- let settings = Settings::test(cx);- cx.set_global(settings);--- let fs = fs::FakeFs::new(cx.background().clone());- let languages = Arc::new(LanguageRegistry::test());- let http_client = client::test::FakeHttpClient::with_404_response();- let client = Client::new(http_client.clone(), cx);- let project_store = cx.add_model(|_| ProjectStore::new());- let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));- let themes = ThemeRegistry::new((), cx.font_cache().clone());- Arc::new(Self {- client,- themes,- fs,- languages,- user_store,- project_store,- initialize_workspace: |_, _, _| {},- build_window_options: Default::default,- default_item_factory: |_, _| unimplemented!(),- })- }-#[derive(Debug)]-enum FollowerItem {- Loading(Vec<proto::update_view::Variant>),- Loaded(Box<dyn FollowableItemHandle>),--}--pub enum Event {DockAnchorChanged,PaneAdded(ViewHandle<Pane>),@@@ -1093,28 -506,16 +489,31 @@@ pub struct Workspacelast_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,window_edited: bool,active_call: Option<(ModelHandle<ActiveCall>, Vec<gpui::Subscription>)>,+ leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,+ database_id: WorkspaceId,+ _apply_leader_updates: Task<Result<()>>,_observe_current_user: Task<()>,}+#[derive(Default)]+struct LeaderState {+ followers: HashSet<PeerId>,+}++type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;++#[derive(Default)]+struct FollowerState {+ active_view_id: Option<u64>,+ items_by_leader_view_id: HashMap<u64, Box<dyn FollowableItemHandle>>,+}+impl Workspace {pub fn new(+ serialized_workspace: Option<SerializedWorkspace>,+ workspace_id: WorkspaceId,project: ModelHandle<Project>,- dock_default_factory: DefaultItemFactory,+ dock_default_factory: DockDefaultItemFactory,cx: &mut ViewContext<Self>,) -> Self {cx.observe_fullscreen(|_, _, cx| cx.notify()).detach();@@@ -1174,26 -578,9 +576,23 @@@let handle = cx.handle();let weak_handle = cx.weak_handle();+ // All leader updates are enqueued and then processed in a single task, so+ // that each asynchronous operation can be run in order.+ let (leader_updates_tx, mut leader_updates_rx) =+ mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();+ let _apply_leader_updates = cx.spawn_weak(|this, mut cx| async move {+ while let Some((leader_id, update)) = leader_updates_rx.next().await {+ let Some(this) = this.upgrade(&cx) else { break };+ Self::process_leader_update(this, leader_id, update, &mut cx)+ .await+ .log_err();+ }++ Ok(())+ });+cx.emit_global(WorkspaceCreated(weak_handle.clone()));- let dock = Dock::new(cx, dock_default_factory);- let dock_pane = dock.pane().clone();-let left_sidebar = cx.add_view(|_| Sidebar::new(SidebarSide::Left));let right_sidebar = cx.add_view(|_| Sidebar::new(SidebarSide::Right));let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));@@@ -1220,41 -607,143 +619,145 @@@active_call = Some((call, subscriptions));}- let mut this = Workspace {- modal: None,- weak_self: weak_handle,- center: PaneGroup::new(center_pane.clone()),- dock,- // When removing an item, the last element remaining in this array- // is used to find where focus should fallback to. As such, the order- // of these two variables is important.- panes: vec![dock_pane, center_pane.clone()],- panes_by_item: Default::default(),- active_pane: center_pane.clone(),- last_active_center_pane: Some(center_pane.downgrade()),- status_bar,- titlebar_item: None,- notifications: Default::default(),- client,- remote_entity_subscription: None,- user_store,- fs,- left_sidebar,- right_sidebar,- project,- leader_state: Default::default(),- follower_states_by_leader: Default::default(),- last_leaders_by_pane: Default::default(),- window_edited: false,- active_call,- _observe_current_user,- _apply_leader_updates,- leader_updates_tx,- };- this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);- cx.defer(|this, cx| this.update_window_title(cx));+ let mut this = Workspace {+ modal: None,+ weak_self: weak_handle.clone(),+ center: PaneGroup::new(center_pane.clone()),+ dock,+ // When removing an item, the last element remaining in this array+ // is used to find where focus should fallback to. As such, the order+ // of these two variables is important.+ panes: vec![dock_pane.clone(), center_pane.clone()],+ panes_by_item: Default::default(),+ active_pane: center_pane.clone(),+ last_active_center_pane: Some(center_pane.downgrade()),+ status_bar,+ titlebar_item: None,+ notifications: Default::default(),+ client,+ remote_entity_subscription: None,+ user_store,+ fs,+ left_sidebar,+ right_sidebar,+ project: project.clone(),+ leader_state: Default::default(),+ follower_states_by_leader: Default::default(),+ last_leaders_by_pane: Default::default(),+ window_edited: false,+ active_call,+ database_id: workspace_id,+ _observe_current_user,++ _apply_leader_updates,++ leader_updates_tx,+ };+ this.project_remote_id_changed(project.read(cx).remote_id(), cx);+ cx.defer(|this, cx| this.update_window_title(cx));++ if let Some(serialized_workspace) = serialized_workspace {+ cx.defer(move |_, cx| {+ Self::load_from_serialized_workspace(weak_handle, serialized_workspace, cx)+ });+ }++ this+ }++ fn new_local(+ abs_paths: Vec<PathBuf>,+ app_state: Arc<AppState>,+ cx: &mut MutableAppContext,+ ) -> Task<(+ ViewHandle<Workspace>,+ Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,+ )> {+ let project_handle = Project::local(+ app_state.client.clone(),+ app_state.user_store.clone(),+ app_state.languages.clone(),+ app_state.fs.clone(),+ cx,+ );++ cx.spawn(|mut cx| async move {+ let serialized_workspace = persistence::DB.workspace_for_roots(&abs_paths.as_slice());++ let paths_to_open = serialized_workspace+ .as_ref()+ .map(|workspace| workspace.location.paths())+ .unwrap_or(Arc::new(abs_paths));++ // Get project paths for all of the abs_paths+ let mut worktree_roots: HashSet<Arc<Path>> = Default::default();+ let mut project_paths = Vec::new();+ for path in paths_to_open.iter() {+ if let Some((worktree, project_entry)) = cx+ .update(|cx| {+ Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)+ })+ .await+ .log_err()+ {+ worktree_roots.insert(worktree.read_with(&mut cx, |tree, _| tree.abs_path()));+ project_paths.push(Some(project_entry));+ } else {+ project_paths.push(None);+ }+ }++ let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {+ serialized_workspace.id+ } else {+ DB.next_id().await.unwrap_or(0)+ };++ // Use the serialized workspace to construct the new window+ let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {+ let mut workspace = Workspace::new(+ serialized_workspace,+ workspace_id,+ project_handle,+ app_state.dock_default_item_factory,+ cx,+ );+ (app_state.initialize_workspace)(&mut workspace, &app_state, cx);+ workspace+ });++ notify_if_database_failed(&workspace, &mut cx);++ // Call open path for each of the project paths+ // (this will bring them to the front if they were in the serialized workspace)+ debug_assert!(paths_to_open.len() == project_paths.len());+ let tasks = paths_to_open+ .iter()+ .cloned()+ .zip(project_paths.into_iter())+ .map(|(abs_path, project_path)| {+ let workspace = workspace.clone();+ cx.spawn(|mut cx| {+ let fs = app_state.fs.clone();+ async move {+ let project_path = project_path?;+ if fs.is_file(&abs_path).await {+ Some(+ workspace+ .update(&mut cx, |workspace, cx| {+ workspace.open_path(project_path, None, true, cx)+ })+ .await,+ )+ } else {+ None+ }+ }+ })+ });++ let opened_items = futures::future::join_all(tasks.into_iter()).await;- this+ (workspace, opened_items)+ })}pub fn weak_handle(&self) -> WeakViewHandle<Self> {diff --cc crates/zed/src/zed.rsindex cbbbe1cfea7,9a827da8b7c..099fb4eea93--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@@ -26,6 -21,6 +24,7 @@@ use gpui::AssetSource, AsyncAppContext, TitlebarOptions, ViewContext, WindowKind,};use language::Rope;++use lazy_static::lazy_static;pub use lsp;pub use project;use project_panel::ProjectPanel;@@@ -73,25 -68,6 +72,17 @@@ actions!const MIN_FONT_SIZE: f32 = 6.0;+lazy_static! {+ static ref ZED_WINDOW_SIZE: Option<Vector2F> = env::var("ZED_WINDOW_SIZE")+ .ok()+ .as_deref()+ .and_then(parse_pixel_position_env_var);+ static ref ZED_WINDOW_POSITION: Option<Vector2F> = env::var("ZED_WINDOW_POSITION")+ .ok()+ .as_deref()+ .and_then(parse_pixel_position_env_var);- pub static ref RELEASE_CHANNEL_NAME: String =- env::var("ZED_RELEASE_CHANNEL").unwrap_or(include_str!("../RELEASE_CHANNEL").to_string());- pub static ref RELEASE_CHANNEL: ReleaseChannel = match RELEASE_CHANNEL_NAME.as_str() {- "dev" => ReleaseChannel::Dev,- "preview" => ReleaseChannel::Preview,- "stable" => ReleaseChannel::Stable,- _ => panic!("invalid release channel {}", *RELEASE_CHANNEL_NAME),- };+}+pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {cx.add_action(about);cx.add_global_action(|_: &Hide, cx: &mut gpui::MutableAppContext| {