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 window_context_2
Antonio Scandurrac52b6328b7f7
diff --cc crates/copilot/src/sign_in.rsindex c08fc1be538,dc09ddf3f24..e67f1b3e431--- a/crates/copilot/src/sign_in.rs+++ b/crates/copilot/src/sign_in.rs@@@ -2,9 -2,9 +2,10 @@@ use crate::{request::PromptUserDeviceFluse gpui::{elements::*,geometry::rect::RectF,+ impl_internal_actions,platform::{WindowBounds, WindowKind, WindowOptions},- AppContext, ClipboardItem, Element, Entity, View, ViewContext, ViewHandle,+ AnyViewHandle, AppContext, ClipboardItem, Drawable, Element, Entity, View, ViewContext,+ ViewHandle,};use settings::Settings;use theme::ui::modal;@@@ -147,12 -159,11 +163,13 @@@ impl CopilotCodeVerification}fn render_prompting_modal(+ connect_clicked: bool,data: &PromptUserDeviceFlow,style: &theme::Copilot,- cx: &mut gpui::RenderContext<Self>,- ) -> ElementBox {+ cx: &mut ViewContext<Self>,+ ) -> Element<Self> {+ enum ConnectButton {}+Flex::column().with_children([Flex::column()@@@ -194,14 -205,21 +211,21 @@@.contained().with_style(style.auth.prompting.hint.container.clone()).boxed(),- theme::ui::cta_button_with_click(+ theme::ui::cta_button_with_click::<ConnectButton, _, _, _>(- "Connect to GitHub",+ if connect_clicked {+ "Waiting for connection..."+ } else {+ "Connect to GitHub"+ },style.auth.content_width,&style.auth.cta_button,cx,{let verification_uri = data.verification_uri.clone();- move |_, _, cx| cx.platform().open_url(&verification_uri)- move |_, cx| {++ move |_, _, cx| {+ cx.platform().open_url(&verification_uri);+ cx.dispatch_action(ClickedConnect)+ }},).boxed(),diff --cc crates/copilot_button/src/copilot_button.rsindex a1fff799421,b7e93536b98..a3560ab5a1c--- a/crates/copilot_button/src/copilot_button.rs+++ b/crates/copilot_button/src/copilot_button.rs@@@ -90,10 -156,10 +155,10 @@@ impl View for CopilotButton"CopilotButton"}- fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox {+ fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {let settings = cx.global::<Settings>();- if !settings.enable_copilot_integration {+ if !settings.features.copilot {return Empty::new().boxed();}@@@ -152,53 -218,24 +217,18 @@@.with_cursor_style(CursorStyle::PointingHand).on_click(MouseButton::Left, {let status = status.clone();- move |_, cx| match status {+ move |_, _, cx| match status {Status::Authorized => cx.dispatch_action(DeployCopilotMenu),- Status::Starting { ref task } => {- cx.dispatch_action(workspace::Toast::new(- COPILOT_STARTING_TOAST_ID,- "Copilot is starting...",- ));- let window_id = cx.window_id();- let task = task.to_owned();- cx.spawn_weak(|_this, mut cx| async move {- task.await;- cx.update(|cx| {- if let Some(copilot) = Copilot::global(cx) {- let status = copilot.read(cx).status();- match status {- Status::Authorized => cx.dispatch_action_at(- window_id,- view_id,- workspace::Toast::new(- COPILOT_STARTING_TOAST_ID,- "Copilot has started!",- ),- ),- _ => {- cx.dispatch_action_at(- window_id,- view_id,- DismissToast::new(COPILOT_STARTING_TOAST_ID),- );- cx.dispatch_global_action(SignIn)- }- }- }- })- })- .detach();- }Status::Error(ref e) => cx.dispatch_action(workspace::Toast::new_action(COPILOT_ERROR_TOAST_ID,format!("Copilot can't be started: {}", e),"Reinstall Copilot",Reinstall,)),- _ => cx.dispatch_action(SignIn),+ _ => cx.dispatch_action(DeployCopilotStartMenu),}})- .with_tooltip::<Self, _>(- 0,- "GitHub Copilot".into(),- None,- theme.tooltip.clone(),- cx,- )+ .with_tooltip::<Self>(0, "GitHub Copilot".into(), None, theme.tooltip.clone(), cx).boxed(),).with_child(diff --cc crates/editor/src/editor.rsindex d70ed96725b,59f8ab6acb4..4f88e91375f--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@@ -2828,41 -2939,83 +2943,86 @@@ impl Editorlet (buffer, buffer_position) =self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;self.copilot_state.pending_refresh = cx.spawn_weak(|this, mut cx| async move {- cx.background().timer(COPILOT_DEBOUNCE_TIMEOUT).await;- let (completion, completions_cycling) = copilot.update(&mut cx, |copilot, cx| {- (- copilot.completions(&buffer, buffer_position, cx),- copilot.completions_cycling(&buffer, buffer_position, cx),- )- });+ if debounce {+ cx.background().timer(COPILOT_DEBOUNCE_TIMEOUT).await;+ }++ let completions = copilot+ .update(&mut cx, |copilot, cx| {+ copilot.completions(&buffer, buffer_position, cx)+ })+ .await+ .log_err()+ .into_iter()+ .flatten()+ .collect_vec();- let (completion, completions_cycling) = futures::join!(completion, completions_cycling);- let mut completions = Vec::new();- completions.extend(completion.log_err().into_iter().flatten());- completions.extend(completions_cycling.log_err().into_iter().flatten());- this.upgrade(&cx)?.update(&mut cx, |this, cx| {- if !completions.is_empty() {- this.copilot_state.cycled = false;- this.copilot_state.pending_cycling_refresh = Task::ready(None);- this.copilot_state.completions.clear();- this.copilot_state.active_completion_index = 0;- this.copilot_state.excerpt_id = Some(cursor.excerpt_id);- for completion in completions {- this.copilot_state.push_completion(completion);+ this.upgrade(&cx)?+ .update(&mut cx, |this, cx| {+ if !completions.is_empty() {++ this.copilot_state.cycled = false;++ this.copilot_state.pending_cycling_refresh = Task::ready(None);+ this.copilot_state.completions.clear();+ this.copilot_state.active_completion_index = 0;+ this.copilot_state.excerpt_id = Some(cursor.excerpt_id);+ for completion in completions {+ this.copilot_state.push_completion(completion);+ }+ this.update_visible_copilot_suggestion(cx);}- this.update_visible_copilot_suggestion(cx);- }- });-+ })+ .log_err()?;-Some(())});Some(())}- fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {+ fn cycle_copilot_suggestions(+ &mut self,+ direction: Direction,+ cx: &mut ViewContext<Self>,+ ) -> Option<()> {+ let copilot = Copilot::global(cx)?;+ if self.mode != EditorMode::Full || !copilot.read(cx).status().is_authorized() {+ return None;+ }++ if self.copilot_state.cycled {+ self.copilot_state.cycle_completions(direction);+ self.update_visible_copilot_suggestion(cx);+ } else {+ let cursor = self.selections.newest_anchor().head();+ let (buffer, buffer_position) =+ self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;+ self.copilot_state.pending_cycling_refresh = cx.spawn_weak(|this, mut cx| async move {+ let completions = copilot+ .update(&mut cx, |copilot, cx| {+ copilot.completions_cycling(&buffer, buffer_position, cx)+ })+ .await;+- this.upgrade(&cx)?.update(&mut cx, |this, cx| {- this.copilot_state.cycled = true;- for completion in completions.log_err().into_iter().flatten() {- this.copilot_state.push_completion(completion);- }- this.copilot_state.cycle_completions(direction);- this.update_visible_copilot_suggestion(cx);- });++ this.upgrade(&cx)?++ .update(&mut cx, |this, cx| {++ this.copilot_state.cycled = true;++ for completion in completions.log_err().into_iter().flatten() {++ this.copilot_state.push_completion(completion);++ }++ this.copilot_state.cycle_completions(direction);++ this.update_visible_copilot_suggestion(cx);++ })++ .log_err()?;++ Some(())+ });+ }++ Some(())+ }++ fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {if !self.has_active_copilot_suggestion(cx) {- self.refresh_copilot_suggestions(cx);+ self.refresh_copilot_suggestions(false, cx);return;}diff --cc crates/editor/src/items.rsindex a6b8665350a,a9f82e0ccba..dd7249b6db2--- a/crates/editor/src/items.rs+++ b/crates/editor/src/items.rs@@@ -7,8 -7,8 +7,8 @@@ use anyhow::{Context, Result}use collections::HashSet;use futures::future::try_join_all;use gpui::{- elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, Subscription, Task,- View, ViewContext, ViewHandle, WeakViewHandle,+ elements::*, geometry::vector::vec2f, AppContext, AsyncAppContext, Entity, ModelHandle,- RenderContext, Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle,++ Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle,};use language::{proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, OffsetRangeExt, Point,@@@ -117,46 -115,29 +117,29 @@@ impl FollowableItem for Editormultibuffer});- cx.add_view(|cx| Editor::for_multibuffer(multibuffer, Some(project), cx))+ cx.add_view(|cx| {+ let mut editor =+ Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);+ editor.remote_id = Some(remote_id);+ editor+ })- })- });+ })?+ };- editor.update(&mut cx, |editor, cx| {- editor.remote_id = Some(remote_id);- let buffer = editor.buffer.read(cx).read(cx);- let selections = state- .selections- .into_iter()- .map(|selection| {- deserialize_selection(&buffer, selection)- .ok_or_else(|| anyhow!("invalid selection"))- })- .collect::<Result<Vec<_>>>()?;- let pending_selection = state- .pending_selection- .map(|selection| deserialize_selection(&buffer, selection))- .flatten();- let scroll_top_anchor = state- .scroll_top_anchor- .and_then(|anchor| deserialize_anchor(&buffer, anchor));- drop(buffer);-- if !selections.is_empty() || pending_selection.is_some() {- editor.set_selections_from_remote(selections, pending_selection, cx);- }-- if let Some(scroll_top_anchor) = scroll_top_anchor {- editor.set_scroll_anchor_remote(- ScrollAnchor {- top_anchor: scroll_top_anchor,- offset: vec2f(state.scroll_x, state.scroll_y),- },- cx,- );- }-- anyhow::Ok(())- })??;+ update_editor_from_message(+ editor.clone(),+ project,+ proto::update_view::Editor {+ selections: state.selections,+ pending_selection: state.pending_selection,+ scroll_top_anchor: state.scroll_top_anchor,+ scroll_x: state.scroll_x,+ scroll_y: state.scroll_y,+ ..Default::default()+ },+ &mut cx,+ )+ .await?;Ok(editor)}))@@@ -301,22 -282,96 +284,96 @@@cx: &mut ViewContext<Self>,) -> Task<Result<()>> {let update_view::Variant::Editor(message) = message;- let multibuffer = self.buffer.read(cx);- let multibuffer = multibuffer.read(cx);+ let project = project.clone();+ cx.spawn(|this, mut cx| async move {+ update_editor_from_message(this, project, message, &mut cx).await+ })+ }- let buffer_ids = message- .inserted_excerpts- .iter()- .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))- .collect::<HashSet<_>>();+ fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {+ match event {+ Event::Edited => true,+ Event::SelectionsChanged { local } => *local,+ Event::ScrollPositionChanged { local } => *local,+ _ => false,+ }+ }+ }- let mut removals = message- .deleted_excerpts+ async fn update_editor_from_message(+ this: ViewHandle<Editor>,+ project: ModelHandle<Project>,+ message: proto::update_view::Editor,+ cx: &mut AsyncAppContext,+ ) -> Result<()> {+ // Open all of the buffers of which excerpts were added to the editor.+ let inserted_excerpt_buffer_ids = message+ .inserted_excerpts+ .iter()+ .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))+ .collect::<HashSet<_>>();+ let inserted_excerpt_buffers = project.update(cx, |project, cx| {+ inserted_excerpt_buffer_ids.into_iter()- .map(ExcerptId::from_proto)- .collect::<Vec<_>>();- removals.sort_by(|a, b| a.cmp(&b, &multibuffer));+ .map(|id| project.open_buffer_by_id(id, cx))+ .collect::<Vec<_>>()+ });+ let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;++ // Update the editor's excerpts.+ this.update(cx, |editor, cx| {+ editor.buffer.update(cx, |multibuffer, cx| {+ let mut removed_excerpt_ids = message+ .deleted_excerpts+ .into_iter()+ .map(ExcerptId::from_proto)+ .collect::<Vec<_>>();+ removed_excerpt_ids.sort_by({+ let multibuffer = multibuffer.read(cx);+ move |a, b| a.cmp(&b, &multibuffer)+ });++ 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(removed_excerpt_ids, cx);+ });- });++ })?;+ // Deserialize the editor state.+ let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {+ let buffer = editor.buffer.read(cx).read(cx);let selections = message.selections.into_iter()@@@ -324,84 -379,45 +381,45 @@@.collect::<Vec<_>>();let pending_selection = message.pending_selection- .and_then(|selection| deserialize_selection(&multibuffer, selection));-+ .and_then(|selection| deserialize_selection(&buffer, selection));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() || pending_selection.is_some() {- this.set_selections_from_remote(selections, pending_selection, cx);- this.request_autoscroll_remotely(Autoscroll::newest(), cx);- } else if let Some(anchor) = scroll_top_anchor {- this.set_scroll_anchor_remote(ScrollAnchor {- top_anchor: anchor,- offset: vec2f(message.scroll_x, message.scroll_y)- }, cx);- }- })?;- Ok(())+ .and_then(|anchor| deserialize_anchor(&buffer, anchor));+ anyhow::Ok((selections, pending_selection, scroll_top_anchor))- })?;++ })??;++ // Wait until the buffer has received all of the operations referenced by+ // the editor's new state.+ this.update(cx, |editor, cx| {+ editor.buffer.update(cx, |buffer, cx| {+ buffer.wait_for_anchors(+ selections+ .iter()+ .chain(pending_selection.as_ref())+ .flat_map(|selection| [selection.start, selection.end])+ .chain(scroll_top_anchor),+ cx,+ )})- }-- fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {- match event {- Event::Edited => true,- Event::SelectionsChanged { local } => *local,- Event::ScrollPositionChanged { local } => *local,- _ => false,- })++ })?+ .await?;++ // Update the editor's state.+ this.update(cx, |editor, cx| {+ if !selections.is_empty() || pending_selection.is_some() {+ editor.set_selections_from_remote(selections, pending_selection, cx);+ editor.request_autoscroll_remotely(Autoscroll::newest(), cx);+ } else if let Some(scroll_top_anchor) = scroll_top_anchor {+ editor.set_scroll_anchor_remote(+ ScrollAnchor {+ top_anchor: scroll_top_anchor,+ offset: vec2f(message.scroll_x, message.scroll_y),+ },+ cx,+ );}- }- });++ })?;+ Ok(())}fn serialize_excerpt(diff --cc crates/feedback/src/feedback_editor.rsindex a8a10311232,f2d6c54aa74..8c06b1ecbdd--- a/crates/feedback/src/feedback_editor.rs+++ b/crates/feedback/src/feedback_editor.rs@@@ -245,7 -249,11 +246,11 @@@ impl Entity for FeedbackEditor}impl Item for FeedbackEditor {+ fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {+ Some("Send Feedback".into())+ }+- fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> ElementBox {+ fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> Element<Pane> {Flex::row().with_child(Svg::new("icons/feedback_16.svg")diff --cc crates/gpui/src/elements/tooltip.rsindex 1d17b62ba77,2f26ee116da..6d2d8d2cc4c--- a/crates/gpui/src/elements/tooltip.rs+++ b/crates/gpui/src/elements/tooltip.rs@@@ -132,12 -137,17 +132,17 @@@ impl<V: View> Tooltip<V>style: TooltipStyle,action: Option<Box<dyn Action>>,measure: bool,- ) -> impl Element {+ ) -> impl Drawable<V> {Flex::row().with_child({- let text = Text::new(text, style.text)- .constrained()- .with_max_width(style.max_text_width);+ let text = if let Some(max_text_width) = style.max_text_width {+ Text::new(text, style.text)+ .constrained()+ .with_max_width(max_text_width)+ } else {+ Text::new(text, style.text).constrained()+ };+if measure {text.flex(1., false).boxed()} else {diff --cc crates/journal/src/journal.rsindex f79f912ab84,bdc6f5893ff..c439edd87d4--- a/crates/journal/src/journal.rs+++ b/crates/journal/src/journal.rs@@@ -43,37 -44,40 +43,37 @@@ pub fn new_journal_entry(app_state: ArcOk::<_, std::io::Error>((journal_dir, entry_path))});- cx.spawn(|mut cx| {- async move {- let (journal_dir, entry_path) = create_entry.await?;- let (workspace, _) = cx- .update(|cx| workspace::open_paths(&[journal_dir], &app_state, None, cx))- .await;+ cx.spawn(|mut cx| async move {+ let (journal_dir, entry_path) = create_entry.await?;+ let (workspace, _) = cx- .update(|cx| workspace::open_paths(&[journal_dir], &app_state, cx))++ .update(|cx| workspace::open_paths(&[journal_dir], &app_state, None, cx))+ .await?;- let opened = workspace- .update(&mut cx, |workspace, cx| {- workspace.open_paths(vec![entry_path], true, cx)- })- .await;+ let opened = workspace+ .update(&mut cx, |workspace, cx| {+ workspace.open_paths(vec![entry_path], true, cx)+ })?+ .await;- if let Some(Some(Ok(item))) = opened.first() {- if let Some(editor) = item.downcast::<Editor>() {- editor.update(&mut cx, |editor, cx| {- let len = editor.buffer().read(cx).len(cx);- editor.change_selections(Some(Autoscroll::center()), cx, |s| {- s.select_ranges([len..len])- });- if len > 0 {- editor.insert("\n\n", cx);- }- editor.insert(&entry_heading, cx);- editor.insert("\n\n", cx);+ if let Some(Some(Ok(item))) = opened.first() {+ if let Some(editor) = item.downcast::<Editor>() {+ editor.update(&mut cx, |editor, cx| {+ let len = editor.buffer().read(cx).len(cx);+ editor.change_selections(Some(Autoscroll::center()), cx, |s| {+ s.select_ranges([len..len])});- }+ if len > 0 {+ editor.insert("\n\n", cx);+ }+ editor.insert(&entry_heading, cx);+ editor.insert("\n\n", cx);+ })?;}-- anyhow::Ok(())}- .log_err()++ anyhow::Ok(())})- .detach();+ .detach_and_log_err(cx);}fn journal_dir(settings: &Settings) -> Option<PathBuf> {diff --cc crates/picker/src/picker.rsindex 9d3061edd32,b17e61edddf..f973dddb3cc--- a/crates/picker/src/picker.rs+++ b/crates/picker/src/picker.rs@@@ -185,11 -181,13 +185,9 @@@ impl<D: PickerDelegate> Picker<D>max_size: vec2f(540., 420.),theme,confirmed: false,+ pending_update_matches: Task::ready(None),};- // TODO! How can the delegate notify the picker to update?- // cx.observe(&delegate, |_, _, cx| cx.notify()).detach();- cx.defer(|this, cx| {- if let Some(delegate) = this.delegate.upgrade(cx) {- cx.observe(&delegate, |_, _, cx| cx.notify()).detach();- this.update_matches(String::new(), cx)- }- });+ this.update_matches(String::new(), cx);this}diff --cc crates/recent_projects/src/recent_projects.rsindex afa04f414de,115f5792eb3..a055177a997--- a/crates/recent_projects/src/recent_projects.rs+++ b/crates/recent_projects/src/recent_projects.rs@@@ -138,13 -164,13 +138,13 @@@ impl PickerDelegate for RecentProjectsDTask::ready(())}- fn confirm(&mut self, cx: &mut ViewContext<Self>) {+ fn confirm(&mut self, cx: &mut ViewContext<RecentProjects>) {if let Some(selected_match) = &self.matches.get(self.selected_index()) {let workspace_location = &self.workspace_locations[selected_match.candidate_id];- cx.dispatch_global_action(OpenPaths {+ cx.dispatch_action(OpenPaths {paths: workspace_location.paths().as_ref().clone(),});- cx.emit(Event::Dismissed);+ cx.emit(PickerEvent::Dismiss);}}diff --cc crates/workspace/src/item.rsindex 6a7416849e2,6c41507478a..6b908d97ebb--- a/crates/workspace/src/item.rs+++ b/crates/workspace/src/item.rs@@@ -48,15 -44,14 +48,18 @@@ pub trait Item: Viewfn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {false}- fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {+ fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {+ None+ }+ fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<str>> {None}- fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)- -> ElementBox;+ fn tab_content(+ &self,+ detail: Option<usize>,+ style: &theme::Tab,+ cx: &AppContext,+ ) -> Element<Pane>;fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project::Item)) {}fn is_singleton(&self, _cx: &AppContext) -> bool {false@@@ -167,16 -162,13 +170,17 @@@pub trait ItemHandle: 'static + fmt::Debug {fn subscribe_to_item_events(&self,- cx: &mut AppContext,- handler: Box<dyn Fn(ItemEvent, &mut AppContext)>,+ cx: &mut WindowContext,+ handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,) -> gpui::Subscription;- fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;+ fn tab_tooltip_text<'a>(&self, cx: &'a AppContext) -> Option<Cow<'a, str>>;+ fn tab_description<'a>(&'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 tab_content(+ &self,+ detail: Option<usize>,+ style: &theme::Tab,+ cx: &AppContext,+ ) -> Element<Pane>;fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]>;diff --cc crates/workspace/src/pane.rsindex 2adc1e0a327,c394ae4631b..4e003d65d8c--- a/crates/workspace/src/pane.rs+++ b/crates/workspace/src/pane.rs@@@ -1396,39 -1396,56 +1399,56 @@@ impl Panelet hovered = mouse_state.hovered();enum Tab {}- MouseEventHandler::<Tab, Pane>::new(ix, cx, |_, cx| {- Self::render_tab::<Pane>(- &item,- pane.clone(),- ix == 0,- detail,- hovered,- tab_style,- cx,- )- })- .on_down(MouseButton::Left, move |_, _, cx| {- cx.dispatch_action(ActivateItem(ix));- })- .on_click(MouseButton::Middle, {- let item = item.clone();- let pane = pane.clone();- move |_, _, cx| {- cx.dispatch_action(CloseItemById {- item_id: item.id(),- pane: pane.clone(),- })- }- })- .on_down(MouseButton::Right, move |e, _, cx| {- let item = item.clone();- cx.dispatch_action(DeployTabContextMenu {- position: e.position,- item_id: item.id(),- pane: pane.clone(),- });- })- .boxed()+ let mouse_event_handler =- MouseEventHandler::<Tab>::new(ix, cx, |_, cx| {- Self::render_tab(++ MouseEventHandler::<Tab, Pane>::new(ix, cx, |_, cx| {++ Self::render_tab::<Pane>(+ &item,+ pane.clone(),+ ix == 0,+ detail,+ hovered,+ tab_style,+ cx,+ )+ })- .on_down(MouseButton::Left, move |_, cx| {++ .on_down(MouseButton::Left, move |_, _, cx| {+ cx.dispatch_action(ActivateItem(ix));+ })+ .on_click(MouseButton::Middle, {+ let item = item.clone();+ let pane = pane.clone();- move |_, cx: &mut EventContext| {++ move |_, _, cx| {+ cx.dispatch_action(CloseItemById {+ item_id: item.id(),+ pane: pane.clone(),+ })+ }+ })+ .on_down(+ MouseButton::Right,- move |e, cx| {++ move |e, _, cx| {+ let item = item.clone();+ cx.dispatch_action(DeployTabContextMenu {+ position: e.position,+ item_id: item.id(),+ pane: pane.clone(),+ });+ },+ );++ if let Some(tab_tooltip_text) = tab_tooltip_text {+ return mouse_event_handler- .with_tooltip::<Self, _>(++ .with_tooltip::<Self>(+ ix,+ tab_tooltip_text,+ None,+ tooltip_theme,+ cx,+ )+ .boxed();+ }++ mouse_event_handler.boxed()}});diff --cc crates/workspace/src/toolbar.rsindex c47b2718ffa,bffca3e3c82..291936aaa56--- a/crates/workspace/src/toolbar.rs+++ b/crates/workspace/src/toolbar.rs@@@ -299,8 -302,11 +302,11 @@@ impl<T: ToolbarItemView> ToolbarItemVie})}- fn pane_focus_update(&mut self, pane_focused: bool, cx: &mut AppContext) {+ fn pane_focus_update(&mut self, pane_focused: bool, cx: &mut WindowContext) {- self.update(cx, |this, cx| this.pane_focus_update(pane_focused, cx));+ self.update(cx, |this, cx| {+ this.pane_focus_update(pane_focused, cx);+ cx.notify();+ });}}diff --cc crates/workspace/src/workspace.rsindex 90fc3f2f072,a7dfe782219..6df269ff274--- a/crates/workspace/src/workspace.rs+++ b/crates/workspace/src/workspace.rs@@@ -303,15 -300,28 +303,28 @@@ pub fn init(app_state: Arc<AppState>, c}let app_state = app_state.upgrade()?;+ let window_id = cx.window_id();let action = action.clone();- let close = workspace.prepare_to_close(false, cx);+ let is_remote = workspace.project.read(cx).is_remote();+ let has_worktree = workspace.project.read(cx).worktrees(cx).next().is_some();+ let has_dirty_items = workspace.items(cx).any(|item| item.is_dirty(cx));+ let close_task = if is_remote || has_worktree || has_dirty_items {+ None+ } else {+ Some(workspace.prepare_to_close(false, cx))+ };Some(cx.spawn_weak(|_, mut cx| async move {- let can_close = close.await?;- if can_close {- cx.update(|cx| open_paths(&action.paths, &app_state, cx))- .await?;- }+ let window_id_to_replace = if let Some(close_task) = close_task {+ if !close_task.await? {+ return Ok(());+ }+ Some(window_id)+ } else {+ None+ };+ cx.update(|cx| open_paths(&action.paths, &app_state, window_id_to_replace, cx))- .await;++ .await?;Ok(())}))}@@@ -868,7 -885,7 +882,8 @@@ impl Workspace);cx.spawn(|mut cx| async move {-- let serialized_workspace = persistence::DB.workspace_for_roots(&abs_paths.as_slice());++ let mut serialized_workspace =++ persistence::DB.workspace_for_roots(&abs_paths.as_slice());let paths_to_open = serialized_workspace.as_ref()@@@ -915,7 -932,7 +930,7 @@@let mut workspace = Workspace::new(serialized_workspace,workspace_id,-- project_handle,++ project_handle.clone(),app_state.dock_default_item_factory,app_state.background_actions,cx,@@@ -924,46 -941,50 +939,54 @@@workspace};- let workspace = {- let (bounds, display) = if let Some(bounds) = window_bounds_override {- (Some(bounds), None)- } else {- serialized_workspace- .as_ref()- .and_then(|serialized_workspace| {- let display = serialized_workspace.display?;- let mut bounds = serialized_workspace.bounds?;-- // Stored bounds are relative to the containing display.- // So convert back to global coordinates if that screen still exists- if let WindowBounds::Fixed(mut window_bounds) = bounds {- if let Some(screen) = cx.platform().screen_by_id(display) {- let screen_bounds = screen.bounds();- window_bounds.set_origin_x(- window_bounds.origin_x() + screen_bounds.origin_x(),- );- window_bounds.set_origin_y(- window_bounds.origin_y() + screen_bounds.origin_y(),- );- bounds = WindowBounds::Fixed(window_bounds);- } else {- // Screen no longer exists. Return none here.- return None;- let workspace = if let Some(window_id) = requesting_window_id {- cx.update(|cx| {- cx.replace_root_view(window_id, |cx| build_workspace(cx, serialized_workspace))++ let workspace = requesting_window_id++ .and_then(|window_id| {++ cx.update(|cx| {++ cx.replace_root_view(window_id, |cx| {++ build_workspace(cx, serialized_workspace.take())++ })++ })+ })- } else {- let (bounds, display) = if let Some(bounds) = window_bounds_override {- (Some(bounds), None)- } else {- serialized_workspace- .as_ref()- .and_then(|serialized_workspace| {- let display = serialized_workspace.display?;- let mut bounds = serialized_workspace.bounds?;-- // Stored bounds are relative to the containing display.- // So convert back to global coordinates if that screen still exists- if let WindowBounds::Fixed(mut window_bounds) = bounds {- if let Some(screen) = cx.platform().screen_by_id(display) {- let screen_bounds = screen.bounds();- window_bounds.set_origin_x(- window_bounds.origin_x() + screen_bounds.origin_x(),- );- window_bounds.set_origin_y(- window_bounds.origin_y() + screen_bounds.origin_y(),- );- bounds = WindowBounds::Fixed(window_bounds);- } else {- // Screen no longer exists. Return none here.- return None;++ .unwrap_or_else(|| {++ let (bounds, display) = if let Some(bounds) = window_bounds_override {++ (Some(bounds), None)++ } else {++ serialized_workspace++ .as_ref()++ .and_then(|serialized_workspace| {++ let display = serialized_workspace.display?;++ let mut bounds = serialized_workspace.bounds?;++++ // Stored bounds are relative to the containing display.++ // So convert back to global coordinates if that screen still exists++ if let WindowBounds::Fixed(mut window_bounds) = bounds {++ if let Some(screen) = cx.platform().screen_by_id(display) {++ let screen_bounds = screen.bounds();++ window_bounds.set_origin_x(++ window_bounds.origin_x() + screen_bounds.origin_x(),++ );++ window_bounds.set_origin_y(++ window_bounds.origin_y() + screen_bounds.origin_y(),++ );++ bounds = WindowBounds::Fixed(window_bounds);++ } else {++ // Screen no longer exists. Return none here.++ return None;++ }}-- }-- Some((bounds, display))-- })-- .unzip()-- };++ Some((bounds, display))++ })++ .unzip()++ };-- // Use the serialized workspace to construct the new window-- cx.add_window(-- (app_state.build_window_options)(bounds, display, cx.platform().as_ref()),-- |cx| build_workspace(cx, serialized_workspace),-- )-- .1-- };++ // Use the serialized workspace to construct the new window++ cx.add_window(++ (app_state.build_window_options)(bounds, display, cx.platform().as_ref()),++ |cx| build_workspace(cx, serialized_workspace),++ )++ .1++ });notify_if_database_failed(&workspace, &mut cx);@@@ -1054,9 -1074,9 +1077,9 @@@F: 'static + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,{if self.project.read(cx).is_local() {- Task::Ready(Some(callback(self, cx)))+ Task::Ready(Some(Ok(callback(self, cx))))} else {- let task = Self::new_local(Vec::new(), app_state.clone(), cx);+ let task = Self::new_local(Vec::new(), app_state.clone(), None, cx);cx.spawn(|_vh, mut cx| async move {let (workspace, _) = task.await;workspace.update(&mut cx, callback)@@@ -3025,13 -3025,12 +3048,14 @@@ pub async fn last_opened_workspace_pathpub fn open_paths(abs_paths: &[PathBuf],app_state: &Arc<AppState>,+ requesting_window_id: Option<usize>,cx: &mut AppContext,-) -> Task<(- ViewHandle<Workspace>,- Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,-)> {+) -> Task<+ Result<(+ ViewHandle<Workspace>,+ Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,+ )>,+> {log::info!("open paths {:?}", abs_paths);// Open paths in existing workspace if possiblediff --cc crates/zed/src/main.rsindex 4cd7ae32df2,aec012db0bf..4b9916f8615--- a/crates/zed/src/main.rs+++ b/crates/zed/src/main.rs@@@ -606,75 -606,67 +606,75 @@@ async fn handle_cli_connection} else {paths};- let (workspace, items) = cx- .update(|cx| workspace::open_paths(&paths, &app_state, None, cx))- .await;let mut errored = false;- let mut item_release_futures = Vec::new();- cx.update(|cx| {- for (item, path) in items.into_iter().zip(&paths) {- match item {- Some(Ok(item)) => {- let released = oneshot::channel();- item.on_release(- cx,- Box::new(move |_| {- let _ = released.0.send(());- }),- )- .detach();- item_release_futures.push(released.1);+ match cx- .update(|cx| workspace::open_paths(&paths, &app_state, cx))++ .update(|cx| workspace::open_paths(&paths, &app_state, None, cx))+ .await+ {+ Ok((workspace, items)) => {+ let mut item_release_futures = Vec::new();+ cx.update(|cx| {+ for (item, path) in items.into_iter().zip(&paths) {+ match item {+ Some(Ok(item)) => {+ let released = oneshot::channel();+ item.on_release(+ cx,+ Box::new(move |_| {+ let _ = released.0.send(());+ }),+ )+ .detach();+ item_release_futures.push(released.1);+ }+ Some(Err(err)) => {+ responses+ .send(CliResponse::Stderr {+ message: format!(+ "error opening {:?}: {}",+ path, err+ ),+ })+ .log_err();+ errored = true;+ }+ None => {}+ }}- Some(Err(err)) => {- responses- .send(CliResponse::Stderr {- message: format!("error opening {:?}: {}", path, err),- })- .log_err();- errored = true;+ });++ if wait {+ let background = cx.background();+ let wait = async move {+ if paths.is_empty() {+ let (done_tx, done_rx) = oneshot::channel();+ let _subscription = cx.update(|cx| {+ cx.observe_release(&workspace, move |_, _| {+ let _ = done_tx.send(());+ })+ });+ drop(workspace);+ let _ = done_rx.await;+ } else {+ let _ =+ futures::future::try_join_all(item_release_futures).await;+ };}- None => {}- }- }- });-- if wait {- let background = cx.background();- let wait = async move {- if paths.is_empty() {- let (done_tx, done_rx) = oneshot::channel();- let _subscription = cx.update(|cx| {- cx.observe_release(&workspace, move |_, _| {- let _ = done_tx.send(());- })- });- drop(workspace);- let _ = done_rx.await;- } else {- let _ = futures::future::try_join_all(item_release_futures).await;- };- }- .fuse();- futures::pin_mut!(wait);-- loop {- // Repeatedly check if CLI is still open to avoid wasting resources- // waiting for files or workspaces to close.- let mut timer = background.timer(Duration::from_secs(1)).fuse();- futures::select_biased! {- _ = wait => break,- _ = timer => {- if responses.send(CliResponse::Ping).is_err() {- break;+ .fuse();+ futures::pin_mut!(wait);++ loop {+ // Repeatedly check if CLI is still open to avoid wasting resources+ // waiting for files or workspaces to close.+ let mut timer = background.timer(Duration::from_secs(1)).fuse();+ futures::select_biased! {+ _ = wait => break,+ _ = timer => {+ if responses.send(CliResponse::Ping).is_err() {+ break;+ }+ }}}}diff --cc crates/zed/src/zed.rsindex 4f9b8fca6cc,36703fae316..c6cfd8c1099--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@@ -705,16 -705,14 +706,16 @@@ mod testscx,)})- .await;+ .await+ .unwrap();assert_eq!(cx.window_ids().len(), 1);- cx.update(|cx| open_paths(&[PathBuf::from("/root/a")], &app_state, cx))+ cx.update(|cx| open_paths(&[PathBuf::from("/root/a")], &app_state, None, cx))- .await;+ .await+ .unwrap();assert_eq!(cx.window_ids().len(), 1);let workspace_1 = cx- .root_view(cx.window_ids()[0])+ .read_window(cx.window_ids()[0], |cx| cx.root_view().clone()).unwrap().downcast::<Workspace>().unwrap();@@@ -731,10 -730,11 +733,12 @@@cx,)})- .await;+ .await+ .unwrap();assert_eq!(cx.window_ids().len(), 2);+ // Replace existing windows+ let window_id = cx.window_ids()[0];cx.update(|cx| {open_paths(&[PathBuf::from("/root/c"), PathBuf::from("/root/d")],@@@ -742,9 -743,25 +747,26 @@@cx,)})- .await;+ .await+ .unwrap();- assert_eq!(cx.window_ids().len(), 3);+ assert_eq!(cx.window_ids().len(), 2);+ let workspace_1 = cx- .root_view(window_id)++ .read_window(cx.window_ids()[0], |cx| cx.root_view().clone())+ .unwrap()+ .clone()+ .downcast::<Workspace>()+ .unwrap();- workspace_1.read_with(cx, |workspace, cx| {++ workspace_1.update(cx, |workspace, cx| {+ assert_eq!(+ workspace+ .worktrees(cx)+ .map(|w| w.read(cx).abs_path())+ .collect::<Vec<_>>(),+ &[Path::new("/root/c").into(), Path::new("/root/d").into()]+ );+ assert!(workspace.left_sidebar().read(cx).is_open());+ assert!(workspace.active_pane().is_focused(cx));+ });}#[gpui::test]@@@ -756,9 -773,8 +778,9 @@@.insert_tree("/root", json!({"a": "hey"})).await;- cx.update(|cx| open_paths(&[PathBuf::from("/root/a")], &app_state, cx))+ cx.update(|cx| open_paths(&[PathBuf::from("/root/a")], &app_state, None, cx))- .await;+ .await+ .unwrap();assert_eq!(cx.window_ids().len(), 1);// When opening the workspace, the window is not in a edited state.@@@ -799,9 -816,8 +821,9 @@@assert!(!cx.is_window_edited(workspace.window_id()));// Opening the buffer again doesn't impact the window's edited state.- cx.update(|cx| open_paths(&[PathBuf::from("/root/a")], &app_state, cx))+ cx.update(|cx| open_paths(&[PathBuf::from("/root/a")], &app_state, None, cx))- .await;+ .await+ .unwrap();let editor = workspace.read_with(cx, |workspace, cx| {workspace.active_item(cx)