Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git_ui: Add split controls to commit view (#58163)
Sathwik Chirivelli52956d93e4cf
diff --git a/crates/editor/src/split.rs b/crates/editor/src/split.rsindex 82b92a8a217..11710744aa4 100644--- a/crates/editor/src/split.rs+++ b/crates/editor/src/split.rs@@ -18,7 +18,7 @@ use multi_buffer::{};use project::Project;use rope::Point;-use settings::{DiffViewStyle, SeedQuerySetting, Settings};+use settings::{DiffViewStyle, SeedQuerySetting, Settings, SettingsStore};use text::{Bias, BufferId, OffsetRangeExt as _, Patch, ToPoint as _};use ui::{App, Context, InteractiveElement as _, IntoElement as _, ParentElement as _, Render,@@ -536,6 +536,13 @@ impl SplittableEditor {cx.emit(event.clone());}}),+ cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {+ let diff_view_style = EditorSettings::get_global(cx).diff_view_style;+ if this.diff_view_style() != diff_view_style {+ this.toggle_split(&ToggleSplitDiff, window, cx);+ cx.notify();+ }+ }),];let this = cx.weak_entity();@@ -583,6 +590,10 @@ impl SplittableEditor {return;};let project = workspace.read(cx).project().clone();+ let all_paths = self.diff_paths(cx);+ if all_paths.is_empty() && !self.rhs_multibuffer.read(cx).is_empty() {+ return;+ }let is_rhs_singleton = self.rhs_multibuffer.read(cx).is_singleton();let lhs_multibuffer = cx.new(|cx| {@@ -741,18 +752,6 @@ impl SplittableEditor {})});- let all_paths: Vec<_> = {- let rhs_multibuffer = self.rhs_multibuffer.read(cx);- let rhs_multibuffer_snapshot = rhs_multibuffer.snapshot(cx);- rhs_multibuffer_snapshot- .buffers_with_paths()- .filter_map(|(buffer, path)| {- let diff = rhs_multibuffer.diff_for(buffer.remote_id())?;- Some((path.clone(), diff))- })- .collect()- };-self.lhs = Some(lhs);self.sync_lhs_for_paths(all_paths, cx);@@ -814,6 +813,18 @@ impl SplittableEditor {cx.notify();}+ fn diff_paths(&self, cx: &App) -> Vec<(PathKey, Entity<BufferDiff>)> {+ let rhs_multibuffer = self.rhs_multibuffer.read(cx);+ let rhs_multibuffer_snapshot = rhs_multibuffer.snapshot(cx);+ rhs_multibuffer_snapshot+ .buffers_with_paths()+ .filter_map(|(buffer, path)| {+ let diff = rhs_multibuffer.diff_for(buffer.remote_id())?;+ Some((path.clone(), diff))+ })+ .collect()+ }+fn activate_pane_left(&mut self,_: &ActivatePaneLeft,@@ -2113,8 +2124,8 @@ mod tests {use buffer_diff::BufferDiff;use collections::{HashMap, HashSet};use fs::FakeFs;- use gpui::Element as _;use gpui::{AppContext as _, Entity, Pixels, VisualTestContext};+ use gpui::{BorrowAppContext as _, Element as _};use language::language_settings::SoftWrap;use language::{Buffer, Capability};use multi_buffer::{MultiBuffer, PathKey};@@ -2142,10 +2153,16 @@ mod tests {cx.update(|cx| {let store = SettingsStore::test(cx);cx.set_global(store);+ cx.update_global::<SettingsStore, _>(|store, cx| {+ store.update_user_settings(cx, |settings| {+ settings.editor.diff_view_style = Some(style);+ });+ });theme_settings::init(theme::LoadThemes::JustBase, cx);crate::init(cx);});- let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let fs = FakeFs::new(cx.executor());+ let project = Project::test(fs as Arc<dyn fs::Fs>, [], cx).await;let (multi_workspace, cx) =cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());diff --git a/crates/git_ui/src/commit_view.rs b/crates/git_ui/src/commit_view.rsindex 5431723551f..247c98c5698 100644--- a/crates/git_ui/src/commit_view.rs+++ b/crates/git_ui/src/commit_view.rs@@ -2,7 +2,8 @@ use anyhow::{Context as _, Result};use buffer_diff::BufferDiff;use collections::HashMap;use editor::{- Addon, Editor, EditorEvent, MultiBuffer, hover_markdown_style, multibuffer_context_lines,+ Addon, Editor, EditorEvent, EditorSettings, MultiBuffer, SplittableEditor,+ hover_markdown_style, multibuffer_context_lines,};use futures_lite::future::yield_now;use git::repository::{CommitDetails, CommitDiff, RepoPath, is_binary_content};@@ -12,7 +13,7 @@ use git::{parse_git_remote_url,};use gpui::{- AnyElement, App, AppContext as _, AsyncApp, AsyncWindowContext, ClipboardItem, Context, Entity,+ AnyElement, App, AppContext as _, AsyncWindowContext, ClipboardItem, Context, Entity,EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, ParentElement,PromptLevel, Render, Styled, Task, WeakEntity, Window, actions,};@@ -23,6 +24,7 @@ use language::{use markdown::{Markdown, MarkdownElement};use multi_buffer::PathKey;use project::{Project, ProjectPath, WorktreeId, git_store::Repository};+use settings::{DiffViewStyle, Settings};use std::{any::{Any, TypeId},collections::HashSet,@@ -72,7 +74,7 @@ pub fn init(cx: &mut App) {pub struct CommitView {commit: CommitDetails,- editor: Entity<Editor>,+ editor: Entity<SplittableEditor>,message: Entity<Markdown>,message_expanded: bool,stash: Option<usize>,@@ -169,7 +171,9 @@ impl CommitView {window.spawn(cx, async move |cx| {- let (commit_diff, commit_details) = futures::join!(commit_diff?, commit_details?);+ let commit_diff = commit_diff?;+ let commit_details = commit_details?;+ let (commit_diff, commit_details) = futures::join!(commit_diff, commit_details);let mut commit_diff = commit_diff.log_err()?.log_err()?;let commit_details = commit_details.log_err()?.log_err()?;@@ -183,6 +187,7 @@ impl CommitView {workspace.update_in(cx, |workspace, window, cx| {let project = workspace.project();+ let workspace_entity = cx.entity();let workspace_handle = cx.weak_entity();let commit_view = cx.new(|cx| {CommitView::new(@@ -190,6 +195,7 @@ impl CommitView {commit_diff,repo,project.clone(),+ workspace_entity,workspace_handle,stash,window,@@ -235,13 +241,18 @@ impl CommitView {commit_diff: CommitDiff,repository: Entity<Repository>,project: Entity<Project>,+ workspace_entity: Entity<Workspace>,workspace: WeakEntity<Workspace>,stash: Option<usize>,window: &mut Window,cx: &mut Context<Self>,) -> Self {let language_registry = project.read(cx).languages().clone();- let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadOnly));+ let multibuffer = cx.new(|cx| {+ let mut multibuffer = MultiBuffer::new(Capability::ReadOnly);+ multibuffer.set_all_diff_hunks_expanded(cx);+ multibuffer+ });let message = cx.new(|cx| {Markdown::new(@@ -253,18 +264,23 @@ impl CommitView {});let editor = cx.new(|cx| {- let mut editor =- Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);+ let editor = SplittableEditor::new(+ EditorSettings::get_global(cx).diff_view_style,+ multibuffer.clone(),+ project.clone(),+ workspace_entity.clone(),+ window,+ cx,+ );- editor.disable_inline_diagnostics();- editor.set_show_bookmarks(false, cx);- editor.set_show_breakpoints(false, cx);- editor.set_show_diff_review_button(true, cx);- editor.set_expand_all_diff_hunks(cx);+ editor.rhs_editor().update(cx, |editor, cx| {+ editor.set_show_bookmarks(false, cx);+ editor.set_show_breakpoints(false, cx);+ editor.set_show_diff_review_button(true, cx);+ });editor});-let commit_sha = Arc::<str>::from(commit.sha.as_ref());let first_worktree_id = project@@ -275,7 +291,7 @@ impl CommitView {let repository_clone = repository.clone();- cx.spawn(async move |this, cx| {+ cx.spawn_in(window, async move |this, cx| {let mut binary_buffer_ids: HashSet<language::BufferId> = HashSet::default();let mut file_statuses: HashMap<language::BufferId, FileStatus> = HashMap::default();@@ -322,7 +338,7 @@ impl CommitView {}) as Arc<dyn language::File>;let buffer = build_buffer(new_text, file, &language_registry, cx).await?;- let buffer_id = cx.update(|cx| buffer.read(cx).remote_id());+ let buffer_id = cx.update(|_, cx| buffer.read(cx).remote_id())?;let status_code = if is_created {StatusCode::Added@@ -344,12 +360,15 @@ impl CommitView {}let buffer_diff = if is_binary {- None+ cx.update(|_, cx| {+ let snapshot = buffer.read(cx).snapshot();+ cx.new(|cx| BufferDiff::new_unchanged(&snapshot, cx))+ })?} else {- Some(build_buffer_diff(old_text, &buffer, &language_registry, cx).await?)+ build_buffer_diff(old_text, &buffer, &language_registry, cx).await?};- let (excerpt_ranges, path) = cx.update(|cx| {+ let (excerpt_ranges, path) = cx.update(|_, cx| {let snapshot = buffer.read(cx).snapshot();let path = PathKey::with_sort_prefix(FILE_NAMESPACE_SORT_PREFIX,@@ -357,7 +376,7 @@ impl CommitView {);let ranges = if is_binary {vec![language::Point::zero()..snapshot.max_point()]- } else if let Some(buffer_diff) = &buffer_diff {+ } else {let diff_snapshot = buffer_diff.read(cx).snapshot(cx);let mut hunks = diff_snapshot.hunks(&snapshot).peekable();if hunks.peek().is_none() {@@ -367,11 +386,9 @@ impl CommitView {.map(|hunk| hunk.buffer_range.to_point(&snapshot)).collect::<Vec<_>>()}- } else {- vec![language::Point::zero()..snapshot.max_point()]};(ranges, path)- });+ })?;// Batch the insertion of excerpts and yield between batches, to avoid blocking the main thread when a single file has many hunks.const EXCERPT_BATCH_SIZE: usize = 10;@@ -381,19 +398,18 @@ impl CommitView {let is_first_batch = batch_end == 0;batch_end = (batch_end + EXCERPT_BATCH_SIZE).min(total);let ranges = excerpt_ranges[..batch_end].to_vec();- this.update(cx, |this, cx| {- this.multibuffer.update(cx, |multibuffer, cx| {- multibuffer.set_excerpts_for_path(+ this.update_in(cx, |this, window, cx| {+ this.editor.update(cx, |editor, cx| {+ editor.update_excerpts_for_path(path.clone(),buffer.clone(),ranges,multibuffer_context_lines(cx),+ buffer_diff.clone(),cx,);- if is_first_batch {- if let Some(buffer_diff) = buffer_diff.clone() {- multibuffer.add_diff(buffer_diff, cx);- }+ if is_first_batch && editor.diff_view_style() == DiffViewStyle::Split {+ editor.split(window, cx);}});})?;@@ -405,15 +421,19 @@ impl CommitView {this.update(cx, |this, cx| {let commit_view = cx.weak_entity();- this.editor.update(cx, |editor, _cx| {- editor.register_addon(CommitDiffAddon {- file_statuses,- commit_view,+ this.editor.update(cx, |editor, cx| {+ editor.rhs_editor().update(cx, |editor, _cx| {+ editor.register_addon(CommitDiffAddon {+ file_statuses,+ commit_view,+ });});});if !binary_buffer_ids.is_empty() {this.editor.update(cx, |editor, cx| {- editor.fold_buffers(binary_buffer_ids, cx);+ editor.rhs_editor().update(cx, |editor, cx| {+ editor.fold_buffers(binary_buffer_ids, cx);+ });});}})?;@@ -506,6 +526,8 @@ impl CommitView {let Some(file) = self.editor.read(cx)+ .focused_editor()+ .read(cx).active_buffer(cx).and_then(|buffer| buffer.read(cx).file().cloned())else {@@ -532,13 +554,16 @@ impl CommitView {let avatar_size = rems_from_px(40.);let avatar_size_px = avatar_size.to_pixels(window.rem_size());let gutter_width = self.editor.update(cx, |editor, cx| {- let snapshot = editor.snapshot(window, cx);- let style = editor.style(cx);- let font_id = window.text_system().resolve_font(&style.text.font());- let font_size = style.text.font_size.to_pixels(window.rem_size());- snapshot- .gutter_dimensions(font_id, font_size, style, window, cx)- .full_width()+ let editor = editor.rhs_editor().clone();+ editor.update(cx, |editor, cx| {+ let snapshot = editor.snapshot(window, cx);+ let style = editor.style(cx);+ let font_id = window.text_system().resolve_font(&style.text.font());+ let font_size = style.text.font_size.to_pixels(window.rem_size());+ snapshot+ .gutter_dimensions(font_id, font_size, style, window, cx)+ .full_width()+ })});let avatar_min_side_padding = rems_from_px(6.).to_pixels(window.rem_size());let avatar_container_min = avatar_size_px + avatar_min_side_padding;@@ -908,12 +933,13 @@ async fn build_buffer(mut text: String,blob: Arc<dyn File>,language_registry: &Arc<language::LanguageRegistry>,- cx: &mut AsyncApp,+ cx: &mut AsyncWindowContext,) -> Result<Entity<Buffer>> {let line_ending = LineEnding::detect(&text);LineEnding::normalize(&mut text);let text = Rope::from(text);- let language = cx.update(|cx| language_registry.language_for_file(&blob, Some(&text), cx));+ let language =+ cx.update(|_, cx| language_registry.language_for_file(&blob, Some(&text), cx))?;let language = if let Some(language) = language {language_registry.load_language(&language)@@ -941,14 +967,14 @@ async fn build_buffer_diff(mut old_text: Option<String>,buffer: &Entity<Buffer>,language_registry: &Arc<LanguageRegistry>,- cx: &mut AsyncApp,+ cx: &mut AsyncWindowContext,) -> Result<Entity<BufferDiff>> {if let Some(old_text) = &mut old_text {LineEnding::normalize(old_text);}- let language = cx.update(|cx| buffer.read(cx).language().cloned());- let buffer = cx.update(|cx| buffer.read(cx).snapshot());+ let language = cx.update(|_, cx| buffer.read(cx).language().cloned())?;+ let buffer = cx.update(|_, cx| buffer.read(cx).snapshot())?;let diff = cx.new(|cx| BufferDiff::new(&buffer.text, cx));@@ -1042,12 +1068,14 @@ impl Item for CommitView {&'a self,type_id: TypeId,self_handle: &'a Entity<Self>,- _: &'a App,+ cx: &'a App,) -> Option<gpui::AnyEntity> {if type_id == TypeId::of::<Self>() {Some(self_handle.clone().into())- } else if type_id == TypeId::of::<Editor>() {+ } else if type_id == TypeId::of::<SplittableEditor>() {Some(self.editor.clone().into())+ } else if type_id == TypeId::of::<Editor>() {+ Some(self.editor.read(cx).rhs_editor().clone().into())} else {None}@@ -1062,7 +1090,7 @@ impl Item for CommitView {cx: &App,f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),) {- self.editor.for_each_project_item(cx, f)+ self.editor.read(cx).for_each_project_item(cx, f)}fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {@@ -1075,8 +1103,10 @@ impl Item for CommitView {_: &mut Window,cx: &mut Context<Self>,) {- self.editor.update(cx, |editor, _| {- editor.set_nav_history(Some(nav_history));+ self.editor.update(cx, |editor, cx| {+ editor.rhs_editor().update(cx, |editor, _| {+ editor.set_nav_history(Some(nav_history));+ });});}@@ -1117,37 +1147,59 @@ impl Item for CommitView {let file_statuses = self.editor.read(cx)+ .rhs_editor()+ .read(cx).addon::<CommitDiffAddon>().map(|addon| addon.file_statuses.clone()).unwrap_or_default();+ let Some(workspace_entity) = self.workspace.upgrade() else {+ return Task::ready(None);+ };+ let project = workspace_entity.read(cx).project().clone();+ let diff_view_style = self.editor.read(cx).diff_view_style();+ let multibuffer = self.multibuffer.clone();Task::ready(Some(cx.new(|cx| {let commit_view = cx.weak_entity();let editor = cx.new({let file_statuses = file_statuses.clone();- |cx| {- let mut editor = self- .editor- .update(cx, |editor, cx| editor.clone(window, cx));- editor.register_addon(CommitDiffAddon {- file_statuses,- commit_view,+ let project = project.clone();+ let workspace_entity = workspace_entity.clone();+ let multibuffer = multibuffer.clone();+ move |cx| {+ let editor = SplittableEditor::new(+ diff_view_style,+ multibuffer.clone(),+ project.clone(),+ workspace_entity.clone(),+ window,+ cx,+ );+ editor.rhs_editor().update(cx, |editor, cx| {+ editor.set_show_bookmarks(false, cx);+ editor.set_show_breakpoints(false, cx);+ editor.set_show_diff_review_button(true, cx);+ editor.register_addon(CommitDiffAddon {+ file_statuses,+ commit_view,+ });});editor}});- let multibuffer = editor.read(cx).buffer().clone();- let language_registry = self- .editor- .read(cx)- .project()- .map(|project| project.read(cx).languages().clone());- let message = cx- .new(|cx| Markdown::new(self.commit.message.clone(), language_registry, None, cx));+ let language_registry = project.read(cx).languages().clone();+ let message = cx.new(|cx| {+ Markdown::new(+ self.commit.message.clone(),+ Some(language_registry),+ None,+ cx,+ )+ });Self {editor,message,message_expanded: self.message_expanded,- multibuffer,+ multibuffer: self.multibuffer.clone(),commit: self.commit.clone(),stash: self.stash,repository: self.repository.clone(),@@ -1168,9 +1220,10 @@ impl Render for CommitView {.size_full().bg(cx.theme().colors().editor_background).child(self.render_header(window, cx))- .when(!self.editor.read(cx).is_empty(cx), |this| {- this.child(div().flex_grow_1().child(self.editor.clone()))- })+ .when(+ !self.editor.read(cx).rhs_editor().read(cx).is_empty(cx),+ |this| this.child(div().flex_grow(1.).child(self.editor.clone())),+ )}}