1use crate::git_panel::{GitPanel, GitPanelAddon, GitStatusEntry};
2use anyhow::Result;
3use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
4use collections::HashSet;
5use editor::{
6 actions::{GoToHunk, GoToPreviousHunk},
7 scroll::Autoscroll,
8 Editor, EditorEvent, ToPoint,
9};
10use feature_flags::FeatureFlagViewExt;
11use futures::StreamExt;
12use git::{
13 status::FileStatus, ShowCommitEditor, StageAll, StageAndNext, ToggleStaged, UnstageAll,
14 UnstageAndNext,
15};
16use gpui::{
17 actions, Action, AnyElement, AnyView, App, AppContext as _, AsyncWindowContext, Entity,
18 EventEmitter, FocusHandle, Focusable, Render, Subscription, Task, WeakEntity,
19};
20use language::{Anchor, Buffer, Capability, OffsetRangeExt};
21use multi_buffer::{MultiBuffer, PathKey};
22use project::{git::GitStore, Project, ProjectPath};
23use std::any::{Any, TypeId};
24use theme::ActiveTheme;
25use ui::{prelude::*, vertical_divider, Tooltip};
26use util::ResultExt as _;
27use workspace::{
28 item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
29 searchable::SearchableItemHandle,
30 ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
31 Workspace,
32};
33
34actions!(git, [Diff]);
35
36pub struct ProjectDiff {
37 multibuffer: Entity<MultiBuffer>,
38 editor: Entity<Editor>,
39 project: Entity<Project>,
40 git_store: Entity<GitStore>,
41 workspace: WeakEntity<Workspace>,
42 focus_handle: FocusHandle,
43 update_needed: postage::watch::Sender<()>,
44 pending_scroll: Option<PathKey>,
45
46 _task: Task<Result<()>>,
47 _subscription: Subscription,
48}
49
50#[derive(Debug)]
51struct DiffBuffer {
52 path_key: PathKey,
53 buffer: Entity<Buffer>,
54 diff: Entity<BufferDiff>,
55 file_status: FileStatus,
56}
57
58const CONFLICT_NAMESPACE: &'static str = "0";
59const TRACKED_NAMESPACE: &'static str = "1";
60const NEW_NAMESPACE: &'static str = "2";
61
62impl ProjectDiff {
63 pub(crate) fn register(
64 _: &mut Workspace,
65 window: Option<&mut Window>,
66 cx: &mut Context<Workspace>,
67 ) {
68 let Some(window) = window else { return };
69 cx.when_flag_enabled::<feature_flags::GitUiFeatureFlag>(window, |workspace, _, _cx| {
70 workspace.register_action(Self::deploy);
71 });
72
73 workspace::register_serializable_item::<ProjectDiff>(cx);
74 }
75
76 fn deploy(
77 workspace: &mut Workspace,
78 _: &Diff,
79 window: &mut Window,
80 cx: &mut Context<Workspace>,
81 ) {
82 Self::deploy_at(workspace, None, window, cx)
83 }
84
85 pub fn deploy_at(
86 workspace: &mut Workspace,
87 entry: Option<GitStatusEntry>,
88 window: &mut Window,
89 cx: &mut Context<Workspace>,
90 ) {
91 let project_diff = if let Some(existing) = workspace.item_of_type::<Self>(cx) {
92 workspace.activate_item(&existing, true, true, window, cx);
93 existing
94 } else {
95 let workspace_handle = cx.entity();
96 let project_diff =
97 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
98 workspace.add_item_to_active_pane(
99 Box::new(project_diff.clone()),
100 None,
101 true,
102 window,
103 cx,
104 );
105 project_diff
106 };
107 if let Some(entry) = entry {
108 project_diff.update(cx, |project_diff, cx| {
109 project_diff.move_to_entry(entry, window, cx);
110 })
111 }
112 }
113
114 fn new(
115 project: Entity<Project>,
116 workspace: Entity<Workspace>,
117 window: &mut Window,
118 cx: &mut Context<Self>,
119 ) -> Self {
120 let focus_handle = cx.focus_handle();
121 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
122
123 let editor = cx.new(|cx| {
124 let mut diff_display_editor = Editor::for_multibuffer(
125 multibuffer.clone(),
126 Some(project.clone()),
127 true,
128 window,
129 cx,
130 );
131 diff_display_editor.set_expand_all_diff_hunks(cx);
132 diff_display_editor.register_addon(GitPanelAddon {
133 workspace: workspace.downgrade(),
134 });
135 diff_display_editor
136 });
137 cx.subscribe_in(&editor, window, Self::handle_editor_event)
138 .detach();
139
140 let git_store = project.read(cx).git_store().clone();
141 let git_store_subscription = cx.subscribe_in(
142 &git_store,
143 window,
144 move |this, _git_store, _event, _window, _cx| {
145 *this.update_needed.borrow_mut() = ();
146 },
147 );
148
149 let (mut send, recv) = postage::watch::channel::<()>();
150 let worker = window.spawn(cx, {
151 let this = cx.weak_entity();
152 |cx| Self::handle_status_updates(this, recv, cx)
153 });
154 // Kick of a refresh immediately
155 *send.borrow_mut() = ();
156
157 Self {
158 project,
159 git_store: git_store.clone(),
160 workspace: workspace.downgrade(),
161 focus_handle,
162 editor,
163 multibuffer,
164 pending_scroll: None,
165 update_needed: send,
166 _task: worker,
167 _subscription: git_store_subscription,
168 }
169 }
170
171 pub fn move_to_entry(
172 &mut self,
173 entry: GitStatusEntry,
174 window: &mut Window,
175 cx: &mut Context<Self>,
176 ) {
177 let Some(git_repo) = self.git_store.read(cx).active_repository() else {
178 return;
179 };
180 let repo = git_repo.read(cx);
181
182 let namespace = if repo.has_conflict(&entry.repo_path) {
183 CONFLICT_NAMESPACE
184 } else if entry.status.is_created() {
185 NEW_NAMESPACE
186 } else {
187 TRACKED_NAMESPACE
188 };
189
190 let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
191
192 self.move_to_path(path_key, window, cx)
193 }
194
195 fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
196 if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
197 self.editor.update(cx, |editor, cx| {
198 editor.change_selections(Some(Autoscroll::focused()), window, cx, |s| {
199 s.select_ranges([position..position]);
200 })
201 });
202 } else {
203 self.pending_scroll = Some(path_key);
204 }
205 }
206
207 fn button_states(&self, cx: &App) -> ButtonStates {
208 let editor = self.editor.read(cx);
209 let snapshot = self.multibuffer.read(cx).snapshot(cx);
210 let prev_next = snapshot.diff_hunks().skip(1).next().is_some();
211 let mut selection = true;
212
213 let mut ranges = editor
214 .selections
215 .disjoint_anchor_ranges()
216 .collect::<Vec<_>>();
217 if !ranges.iter().any(|range| range.start != range.end) {
218 selection = false;
219 if let Some((excerpt_id, buffer, range)) = self.editor.read(cx).active_excerpt(cx) {
220 ranges = vec![multi_buffer::Anchor::range_in_buffer(
221 excerpt_id,
222 buffer.read(cx).remote_id(),
223 range,
224 )];
225 } else {
226 ranges = Vec::default();
227 }
228 }
229 let mut has_staged_hunks = false;
230 let mut has_unstaged_hunks = false;
231 for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
232 match hunk.secondary_status {
233 DiffHunkSecondaryStatus::HasSecondaryHunk
234 | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending => {
235 has_unstaged_hunks = true;
236 }
237 DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
238 has_staged_hunks = true;
239 has_unstaged_hunks = true;
240 }
241 DiffHunkSecondaryStatus::None
242 | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending => {
243 has_staged_hunks = true;
244 }
245 }
246 }
247 let mut commit = false;
248 let mut stage_all = false;
249 let mut unstage_all = false;
250 self.workspace
251 .read_with(cx, |workspace, cx| {
252 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
253 let git_panel = git_panel.read(cx);
254 commit = git_panel.can_commit();
255 stage_all = git_panel.can_stage_all();
256 unstage_all = git_panel.can_unstage_all();
257 }
258 })
259 .ok();
260
261 return ButtonStates {
262 stage: has_unstaged_hunks,
263 unstage: has_staged_hunks,
264 prev_next,
265 selection,
266 commit,
267 stage_all,
268 unstage_all,
269 };
270 }
271
272 fn handle_editor_event(
273 &mut self,
274 editor: &Entity<Editor>,
275 event: &EditorEvent,
276 window: &mut Window,
277 cx: &mut Context<Self>,
278 ) {
279 match event {
280 EditorEvent::ScrollPositionChanged { .. } => editor.update(cx, |editor, cx| {
281 let anchor = editor.scroll_manager.anchor().anchor;
282 let multibuffer = self.multibuffer.read(cx);
283 let snapshot = multibuffer.snapshot(cx);
284 let mut point = anchor.to_point(&snapshot);
285 point.row = (point.row + 1).min(snapshot.max_row().0);
286 point.column = 0;
287
288 let Some((_, buffer, _)) = self.multibuffer.read(cx).excerpt_containing(point, cx)
289 else {
290 return;
291 };
292 let Some(project_path) = buffer
293 .read(cx)
294 .file()
295 .map(|file| (file.worktree_id(cx), file.path().clone()))
296 else {
297 return;
298 };
299 self.workspace
300 .update(cx, |workspace, cx| {
301 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
302 git_panel.update(cx, |git_panel, cx| {
303 git_panel.select_entry_by_path(project_path.into(), window, cx)
304 })
305 }
306 })
307 .ok();
308 }),
309 _ => {}
310 }
311 }
312
313 fn load_buffers(&mut self, cx: &mut Context<Self>) -> Vec<Task<Result<DiffBuffer>>> {
314 let Some(repo) = self.git_store.read(cx).active_repository() else {
315 self.multibuffer.update(cx, |multibuffer, cx| {
316 multibuffer.clear(cx);
317 });
318 return vec![];
319 };
320
321 let mut previous_paths = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
322
323 let mut result = vec![];
324 repo.update(cx, |repo, cx| {
325 for entry in repo.status() {
326 if !entry.status.has_changes() {
327 continue;
328 }
329 let Some(project_path) = repo.repo_path_to_project_path(&entry.repo_path) else {
330 continue;
331 };
332 let namespace = if repo.has_conflict(&entry.repo_path) {
333 CONFLICT_NAMESPACE
334 } else if entry.status.is_created() {
335 NEW_NAMESPACE
336 } else {
337 TRACKED_NAMESPACE
338 };
339 let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
340
341 previous_paths.remove(&path_key);
342 let load_buffer = self
343 .project
344 .update(cx, |project, cx| project.open_buffer(project_path, cx));
345
346 let project = self.project.clone();
347 result.push(cx.spawn(|_, mut cx| async move {
348 let buffer = load_buffer.await?;
349 let changes = project
350 .update(&mut cx, |project, cx| {
351 project.open_uncommitted_diff(buffer.clone(), cx)
352 })?
353 .await?;
354 Ok(DiffBuffer {
355 path_key,
356 buffer,
357 diff: changes,
358 file_status: entry.status,
359 })
360 }));
361 }
362 });
363 self.multibuffer.update(cx, |multibuffer, cx| {
364 for path in previous_paths {
365 multibuffer.remove_excerpts_for_path(path, cx);
366 }
367 });
368 result
369 }
370
371 fn register_buffer(
372 &mut self,
373 diff_buffer: DiffBuffer,
374 window: &mut Window,
375 cx: &mut Context<Self>,
376 ) {
377 let path_key = diff_buffer.path_key;
378 let buffer = diff_buffer.buffer;
379 let diff = diff_buffer.diff;
380
381 let snapshot = buffer.read(cx).snapshot();
382 let diff = diff.read(cx);
383 let diff_hunk_ranges = diff
384 .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
385 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
386 .collect::<Vec<_>>();
387
388 let (was_empty, is_excerpt_newly_added) = self.multibuffer.update(cx, |multibuffer, cx| {
389 let was_empty = multibuffer.is_empty();
390 let is_newly_added = multibuffer.set_excerpts_for_path(
391 path_key.clone(),
392 buffer,
393 diff_hunk_ranges,
394 editor::DEFAULT_MULTIBUFFER_CONTEXT,
395 cx,
396 );
397 (was_empty, is_newly_added)
398 });
399
400 self.editor.update(cx, |editor, cx| {
401 if was_empty {
402 editor.change_selections(None, window, cx, |selections| {
403 // TODO select the very beginning (possibly inside a deletion)
404 selections.select_ranges([0..0])
405 });
406 }
407 if is_excerpt_newly_added && diff_buffer.file_status.is_deleted() {
408 editor.fold_buffer(snapshot.text.remote_id(), cx)
409 }
410 });
411
412 if self.multibuffer.read(cx).is_empty()
413 && self
414 .editor
415 .read(cx)
416 .focus_handle(cx)
417 .contains_focused(window, cx)
418 {
419 self.focus_handle.focus(window);
420 } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
421 self.editor.update(cx, |editor, cx| {
422 editor.focus_handle(cx).focus(window);
423 });
424 }
425 if self.pending_scroll.as_ref() == Some(&path_key) {
426 self.move_to_path(path_key, window, cx);
427 }
428 }
429
430 pub async fn handle_status_updates(
431 this: WeakEntity<Self>,
432 mut recv: postage::watch::Receiver<()>,
433 mut cx: AsyncWindowContext,
434 ) -> Result<()> {
435 while let Some(_) = recv.next().await {
436 let buffers_to_load = this.update(&mut cx, |this, cx| this.load_buffers(cx))?;
437 for buffer_to_load in buffers_to_load {
438 if let Some(buffer) = buffer_to_load.await.log_err() {
439 cx.update(|window, cx| {
440 this.update(cx, |this, cx| this.register_buffer(buffer, window, cx))
441 .ok();
442 })?;
443 }
444 }
445 this.update(&mut cx, |this, _| this.pending_scroll.take())?;
446 }
447
448 Ok(())
449 }
450
451 #[cfg(any(test, feature = "test-support"))]
452 pub fn excerpt_paths(&self, cx: &App) -> Vec<String> {
453 self.multibuffer
454 .read(cx)
455 .excerpt_paths()
456 .map(|key| key.path().to_string_lossy().to_string())
457 .collect()
458 }
459}
460
461impl EventEmitter<EditorEvent> for ProjectDiff {}
462
463impl Focusable for ProjectDiff {
464 fn focus_handle(&self, cx: &App) -> FocusHandle {
465 if self.multibuffer.read(cx).is_empty() {
466 self.focus_handle.clone()
467 } else {
468 self.editor.focus_handle(cx)
469 }
470 }
471}
472
473impl Item for ProjectDiff {
474 type Event = EditorEvent;
475
476 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
477 Some(Icon::new(IconName::GitBranch).color(Color::Muted))
478 }
479
480 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
481 Editor::to_item_events(event, f)
482 }
483
484 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
485 self.editor
486 .update(cx, |editor, cx| editor.deactivated(window, cx));
487 }
488
489 fn navigate(
490 &mut self,
491 data: Box<dyn Any>,
492 window: &mut Window,
493 cx: &mut Context<Self>,
494 ) -> bool {
495 self.editor
496 .update(cx, |editor, cx| editor.navigate(data, window, cx))
497 }
498
499 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
500 Some("Project Diff".into())
501 }
502
503 fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
504 Label::new("Uncommitted Changes")
505 .color(if params.selected {
506 Color::Default
507 } else {
508 Color::Muted
509 })
510 .into_any_element()
511 }
512
513 fn telemetry_event_text(&self) -> Option<&'static str> {
514 Some("Project Diff Opened")
515 }
516
517 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
518 Some(Box::new(self.editor.clone()))
519 }
520
521 fn for_each_project_item(
522 &self,
523 cx: &App,
524 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
525 ) {
526 self.editor.for_each_project_item(cx, f)
527 }
528
529 fn is_singleton(&self, _: &App) -> bool {
530 false
531 }
532
533 fn set_nav_history(
534 &mut self,
535 nav_history: ItemNavHistory,
536 _: &mut Window,
537 cx: &mut Context<Self>,
538 ) {
539 self.editor.update(cx, |editor, _| {
540 editor.set_nav_history(Some(nav_history));
541 });
542 }
543
544 fn clone_on_split(
545 &self,
546 _workspace_id: Option<workspace::WorkspaceId>,
547 window: &mut Window,
548 cx: &mut Context<Self>,
549 ) -> Option<Entity<Self>>
550 where
551 Self: Sized,
552 {
553 let workspace = self.workspace.upgrade()?;
554 Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
555 }
556
557 fn is_dirty(&self, cx: &App) -> bool {
558 self.multibuffer.read(cx).is_dirty(cx)
559 }
560
561 fn has_conflict(&self, cx: &App) -> bool {
562 self.multibuffer.read(cx).has_conflict(cx)
563 }
564
565 fn can_save(&self, _: &App) -> bool {
566 true
567 }
568
569 fn save(
570 &mut self,
571 format: bool,
572 project: Entity<Project>,
573 window: &mut Window,
574 cx: &mut Context<Self>,
575 ) -> Task<Result<()>> {
576 self.editor.save(format, project, window, cx)
577 }
578
579 fn save_as(
580 &mut self,
581 _: Entity<Project>,
582 _: ProjectPath,
583 _window: &mut Window,
584 _: &mut Context<Self>,
585 ) -> Task<Result<()>> {
586 unreachable!()
587 }
588
589 fn reload(
590 &mut self,
591 project: Entity<Project>,
592 window: &mut Window,
593 cx: &mut Context<Self>,
594 ) -> Task<Result<()>> {
595 self.editor.reload(project, window, cx)
596 }
597
598 fn act_as_type<'a>(
599 &'a self,
600 type_id: TypeId,
601 self_handle: &'a Entity<Self>,
602 _: &'a App,
603 ) -> Option<AnyView> {
604 if type_id == TypeId::of::<Self>() {
605 Some(self_handle.to_any())
606 } else if type_id == TypeId::of::<Editor>() {
607 Some(self.editor.to_any())
608 } else {
609 None
610 }
611 }
612
613 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
614 ToolbarItemLocation::PrimaryLeft
615 }
616
617 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
618 self.editor.breadcrumbs(theme, cx)
619 }
620
621 fn added_to_workspace(
622 &mut self,
623 workspace: &mut Workspace,
624 window: &mut Window,
625 cx: &mut Context<Self>,
626 ) {
627 self.editor.update(cx, |editor, cx| {
628 editor.added_to_workspace(workspace, window, cx)
629 });
630 }
631}
632
633impl Render for ProjectDiff {
634 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
635 let is_empty = self.multibuffer.read(cx).is_empty();
636
637 div()
638 .track_focus(&self.focus_handle)
639 .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
640 .bg(cx.theme().colors().editor_background)
641 .flex()
642 .items_center()
643 .justify_center()
644 .size_full()
645 .when(is_empty, |el| {
646 el.child(Label::new("No uncommitted changes"))
647 })
648 .when(!is_empty, |el| el.child(self.editor.clone()))
649 }
650}
651
652impl SerializableItem for ProjectDiff {
653 fn serialized_item_kind() -> &'static str {
654 "ProjectDiff"
655 }
656
657 fn cleanup(
658 _: workspace::WorkspaceId,
659 _: Vec<workspace::ItemId>,
660 _: &mut Window,
661 _: &mut App,
662 ) -> Task<Result<()>> {
663 Task::ready(Ok(()))
664 }
665
666 fn deserialize(
667 _project: Entity<Project>,
668 workspace: WeakEntity<Workspace>,
669 _workspace_id: workspace::WorkspaceId,
670 _item_id: workspace::ItemId,
671 window: &mut Window,
672 cx: &mut App,
673 ) -> Task<Result<Entity<Self>>> {
674 window.spawn(cx, |mut cx| async move {
675 workspace.update_in(&mut cx, |workspace, window, cx| {
676 let workspace_handle = cx.entity();
677 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
678 })
679 })
680 }
681
682 fn serialize(
683 &mut self,
684 _workspace: &mut Workspace,
685 _item_id: workspace::ItemId,
686 _closing: bool,
687 _window: &mut Window,
688 _cx: &mut Context<Self>,
689 ) -> Option<Task<Result<()>>> {
690 None
691 }
692
693 fn should_serialize(&self, _: &Self::Event) -> bool {
694 false
695 }
696}
697
698pub struct ProjectDiffToolbar {
699 project_diff: Option<WeakEntity<ProjectDiff>>,
700 workspace: WeakEntity<Workspace>,
701}
702
703impl ProjectDiffToolbar {
704 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
705 Self {
706 project_diff: None,
707 workspace: workspace.weak_handle(),
708 }
709 }
710
711 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
712 self.project_diff.as_ref()?.upgrade()
713 }
714 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
715 if let Some(project_diff) = self.project_diff(cx) {
716 project_diff.focus_handle(cx).focus(window);
717 }
718 let action = action.boxed_clone();
719 cx.defer(move |cx| {
720 cx.dispatch_action(action.as_ref());
721 })
722 }
723 fn dispatch_panel_action(
724 &self,
725 action: &dyn Action,
726 window: &mut Window,
727 cx: &mut Context<Self>,
728 ) {
729 self.workspace
730 .read_with(cx, |workspace, cx| {
731 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
732 panel.focus_handle(cx).focus(window)
733 }
734 })
735 .ok();
736 let action = action.boxed_clone();
737 cx.defer(move |cx| {
738 cx.dispatch_action(action.as_ref());
739 })
740 }
741}
742
743impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
744
745impl ToolbarItemView for ProjectDiffToolbar {
746 fn set_active_pane_item(
747 &mut self,
748 active_pane_item: Option<&dyn ItemHandle>,
749 _: &mut Window,
750 cx: &mut Context<Self>,
751 ) -> ToolbarItemLocation {
752 self.project_diff = active_pane_item
753 .and_then(|item| item.act_as::<ProjectDiff>(cx))
754 .map(|entity| entity.downgrade());
755 if self.project_diff.is_some() {
756 ToolbarItemLocation::PrimaryRight
757 } else {
758 ToolbarItemLocation::Hidden
759 }
760 }
761
762 fn pane_focus_update(
763 &mut self,
764 _pane_focused: bool,
765 _window: &mut Window,
766 _cx: &mut Context<Self>,
767 ) {
768 }
769}
770
771struct ButtonStates {
772 stage: bool,
773 unstage: bool,
774 prev_next: bool,
775 selection: bool,
776 stage_all: bool,
777 unstage_all: bool,
778 commit: bool,
779}
780
781impl Render for ProjectDiffToolbar {
782 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
783 let Some(project_diff) = self.project_diff(cx) else {
784 return div();
785 };
786 let focus_handle = project_diff.focus_handle(cx);
787 let button_states = project_diff.read(cx).button_states(cx);
788
789 h_group_xl()
790 .my_neg_1()
791 .items_center()
792 .py_1()
793 .pl_2()
794 .pr_1()
795 .flex_wrap()
796 .justify_between()
797 .child(
798 h_group_sm()
799 .when(button_states.selection, |el| {
800 el.child(
801 Button::new("stage", "Toggle Staged")
802 .tooltip(Tooltip::for_action_title_in(
803 "Toggle Staged",
804 &ToggleStaged,
805 &focus_handle,
806 ))
807 .disabled(!button_states.stage && !button_states.unstage)
808 .on_click(cx.listener(|this, _, window, cx| {
809 this.dispatch_action(&ToggleStaged, window, cx)
810 })),
811 )
812 })
813 .when(!button_states.selection, |el| {
814 el.child(
815 Button::new("stage", "Stage")
816 .tooltip(Tooltip::for_action_title_in(
817 "Stage",
818 &StageAndNext {
819 whole_excerpt: false,
820 },
821 &focus_handle,
822 ))
823 // don't actually disable the button so it's mashable
824 .color(if button_states.stage {
825 Color::Default
826 } else {
827 Color::Disabled
828 })
829 .on_click(cx.listener(|this, _, window, cx| {
830 this.dispatch_action(
831 &StageAndNext {
832 whole_excerpt: false,
833 },
834 window,
835 cx,
836 )
837 })),
838 )
839 .child(
840 Button::new("unstage", "Unstage")
841 .tooltip(Tooltip::for_action_title_in(
842 "Unstage",
843 &UnstageAndNext {
844 whole_excerpt: false,
845 },
846 &focus_handle,
847 ))
848 .color(if button_states.unstage {
849 Color::Default
850 } else {
851 Color::Disabled
852 })
853 .on_click(cx.listener(|this, _, window, cx| {
854 this.dispatch_action(
855 &UnstageAndNext {
856 whole_excerpt: false,
857 },
858 window,
859 cx,
860 )
861 })),
862 )
863 }),
864 )
865 // n.b. the only reason these arrows are here is because we don't
866 // support "undo" for staging so we need a way to go back.
867 .child(
868 h_group_sm()
869 .child(
870 IconButton::new("up", IconName::ArrowUp)
871 .shape(ui::IconButtonShape::Square)
872 .tooltip(Tooltip::for_action_title_in(
873 "Go to previous hunk",
874 &GoToPreviousHunk {
875 center_cursor: false,
876 },
877 &focus_handle,
878 ))
879 .disabled(!button_states.prev_next)
880 .on_click(cx.listener(|this, _, window, cx| {
881 this.dispatch_action(
882 &GoToPreviousHunk {
883 center_cursor: true,
884 },
885 window,
886 cx,
887 )
888 })),
889 )
890 .child(
891 IconButton::new("down", IconName::ArrowDown)
892 .shape(ui::IconButtonShape::Square)
893 .tooltip(Tooltip::for_action_title_in(
894 "Go to next hunk",
895 &GoToHunk {
896 center_cursor: false,
897 },
898 &focus_handle,
899 ))
900 .disabled(!button_states.prev_next)
901 .on_click(cx.listener(|this, _, window, cx| {
902 this.dispatch_action(
903 &GoToHunk {
904 center_cursor: true,
905 },
906 window,
907 cx,
908 )
909 })),
910 ),
911 )
912 .child(vertical_divider())
913 .child(
914 h_group_sm()
915 .when(
916 button_states.unstage_all && !button_states.stage_all,
917 |el| {
918 el.child(
919 Button::new("unstage-all", "Unstage All")
920 .tooltip(Tooltip::for_action_title_in(
921 "Unstage all changes",
922 &UnstageAll,
923 &focus_handle,
924 ))
925 .on_click(cx.listener(|this, _, window, cx| {
926 this.dispatch_panel_action(&UnstageAll, window, cx)
927 })),
928 )
929 },
930 )
931 .when(
932 !button_states.unstage_all || button_states.stage_all,
933 |el| {
934 el.child(
935 // todo make it so that changing to say "Unstaged"
936 // doesn't change the position.
937 div().child(
938 Button::new("stage-all", "Stage All")
939 .disabled(!button_states.stage_all)
940 .tooltip(Tooltip::for_action_title_in(
941 "Stage all changes",
942 &StageAll,
943 &focus_handle,
944 ))
945 .on_click(cx.listener(|this, _, window, cx| {
946 this.dispatch_panel_action(&StageAll, window, cx)
947 })),
948 ),
949 )
950 },
951 )
952 .child(
953 Button::new("commit", "Commit")
954 .disabled(!button_states.commit)
955 .tooltip(Tooltip::for_action_title_in(
956 "Commit",
957 &ShowCommitEditor,
958 &focus_handle,
959 ))
960 .on_click(cx.listener(|this, _, window, cx| {
961 this.dispatch_action(&ShowCommitEditor, window, cx);
962 })),
963 ),
964 )
965 }
966}
967
968#[cfg(test)]
969mod tests {
970 use std::path::Path;
971
972 use collections::HashMap;
973 use editor::test::editor_test_context::assert_state_with_diff;
974 use git::status::{StatusCode, TrackedStatus};
975 use gpui::TestAppContext;
976 use project::FakeFs;
977 use serde_json::json;
978 use settings::SettingsStore;
979 use unindent::Unindent as _;
980 use util::path;
981
982 use super::*;
983
984 #[ctor::ctor]
985 fn init_logger() {
986 env_logger::init();
987 }
988
989 fn init_test(cx: &mut TestAppContext) {
990 cx.update(|cx| {
991 let store = SettingsStore::test(cx);
992 cx.set_global(store);
993 theme::init(theme::LoadThemes::JustBase, cx);
994 language::init(cx);
995 Project::init_settings(cx);
996 workspace::init_settings(cx);
997 editor::init(cx);
998 crate::init(cx);
999 });
1000 }
1001
1002 #[gpui::test]
1003 async fn test_save_after_restore(cx: &mut TestAppContext) {
1004 init_test(cx);
1005
1006 let fs = FakeFs::new(cx.executor());
1007 fs.insert_tree(
1008 path!("/project"),
1009 json!({
1010 ".git": {},
1011 "foo.txt": "FOO\n",
1012 }),
1013 )
1014 .await;
1015 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1016 let (workspace, cx) =
1017 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1018 let diff = cx.new_window_entity(|window, cx| {
1019 ProjectDiff::new(project.clone(), workspace, window, cx)
1020 });
1021 cx.run_until_parked();
1022
1023 fs.set_head_for_repo(
1024 path!("/project/.git").as_ref(),
1025 &[("foo.txt".into(), "foo\n".into())],
1026 );
1027 fs.set_index_for_repo(
1028 path!("/project/.git").as_ref(),
1029 &[("foo.txt".into(), "foo\n".into())],
1030 );
1031 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1032 state.statuses = HashMap::from_iter([(
1033 "foo.txt".into(),
1034 TrackedStatus {
1035 index_status: StatusCode::Unmodified,
1036 worktree_status: StatusCode::Modified,
1037 }
1038 .into(),
1039 )]);
1040 });
1041 cx.run_until_parked();
1042
1043 let editor = diff.update(cx, |diff, _| diff.editor.clone());
1044 assert_state_with_diff(
1045 &editor,
1046 cx,
1047 &"
1048 - foo
1049 + ˇFOO
1050 "
1051 .unindent(),
1052 );
1053
1054 editor.update_in(cx, |editor, window, cx| {
1055 editor.git_restore(&Default::default(), window, cx);
1056 });
1057 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1058 state.statuses = HashMap::default();
1059 });
1060 cx.run_until_parked();
1061
1062 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1063
1064 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1065 assert_eq!(text, "foo\n");
1066 }
1067
1068 #[gpui::test]
1069 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1070 init_test(cx);
1071
1072 let fs = FakeFs::new(cx.executor());
1073 fs.insert_tree(
1074 path!("/project"),
1075 json!({
1076 ".git": {},
1077 "bar": "BAR\n",
1078 "foo": "FOO\n",
1079 }),
1080 )
1081 .await;
1082 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1083 let (workspace, cx) =
1084 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1085 let diff = cx.new_window_entity(|window, cx| {
1086 ProjectDiff::new(project.clone(), workspace, window, cx)
1087 });
1088 cx.run_until_parked();
1089
1090 fs.set_head_for_repo(
1091 path!("/project/.git").as_ref(),
1092 &[
1093 ("bar".into(), "bar\n".into()),
1094 ("foo".into(), "foo\n".into()),
1095 ],
1096 );
1097 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1098 state.statuses = HashMap::from_iter([
1099 (
1100 "bar".into(),
1101 TrackedStatus {
1102 index_status: StatusCode::Unmodified,
1103 worktree_status: StatusCode::Modified,
1104 }
1105 .into(),
1106 ),
1107 (
1108 "foo".into(),
1109 TrackedStatus {
1110 index_status: StatusCode::Unmodified,
1111 worktree_status: StatusCode::Modified,
1112 }
1113 .into(),
1114 ),
1115 ]);
1116 });
1117 cx.run_until_parked();
1118
1119 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1120 diff.move_to_path(
1121 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("foo").into()),
1122 window,
1123 cx,
1124 );
1125 diff.editor.clone()
1126 });
1127 assert_state_with_diff(
1128 &editor,
1129 cx,
1130 &"
1131 - bar
1132 + BAR
1133
1134 - ˇfoo
1135 + FOO
1136 "
1137 .unindent(),
1138 );
1139
1140 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1141 diff.move_to_path(
1142 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("bar").into()),
1143 window,
1144 cx,
1145 );
1146 diff.editor.clone()
1147 });
1148 assert_state_with_diff(
1149 &editor,
1150 cx,
1151 &"
1152 - ˇbar
1153 + BAR
1154
1155 - foo
1156 + FOO
1157 "
1158 .unindent(),
1159 );
1160 }
1161
1162 #[gpui::test]
1163 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1164 init_test(cx);
1165
1166 let fs = FakeFs::new(cx.executor());
1167 fs.insert_tree(
1168 path!("/project"),
1169 json!({
1170 ".git": {},
1171 "foo": "modified\n",
1172 }),
1173 )
1174 .await;
1175 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1176 let (workspace, cx) =
1177 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1178 let buffer = project
1179 .update(cx, |project, cx| {
1180 project.open_local_buffer(path!("/project/foo"), cx)
1181 })
1182 .await
1183 .unwrap();
1184 let buffer_editor = cx.new_window_entity(|window, cx| {
1185 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1186 });
1187 let diff = cx.new_window_entity(|window, cx| {
1188 ProjectDiff::new(project.clone(), workspace, window, cx)
1189 });
1190 cx.run_until_parked();
1191
1192 fs.set_head_for_repo(
1193 path!("/project/.git").as_ref(),
1194 &[("foo".into(), "original\n".into())],
1195 );
1196 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1197 state.statuses = HashMap::from_iter([(
1198 "foo".into(),
1199 TrackedStatus {
1200 index_status: StatusCode::Unmodified,
1201 worktree_status: StatusCode::Modified,
1202 }
1203 .into(),
1204 )]);
1205 });
1206 cx.run_until_parked();
1207
1208 let diff_editor = diff.update(cx, |diff, _| diff.editor.clone());
1209
1210 assert_state_with_diff(
1211 &diff_editor,
1212 cx,
1213 &"
1214 - original
1215 + ˇmodified
1216 "
1217 .unindent(),
1218 );
1219
1220 let prev_buffer_hunks =
1221 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1222 let snapshot = buffer_editor.snapshot(window, cx);
1223 let snapshot = &snapshot.buffer_snapshot;
1224 let prev_buffer_hunks = buffer_editor
1225 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1226 .collect::<Vec<_>>();
1227 buffer_editor.git_restore(&Default::default(), window, cx);
1228 prev_buffer_hunks
1229 });
1230 assert_eq!(prev_buffer_hunks.len(), 1);
1231 cx.run_until_parked();
1232
1233 let new_buffer_hunks =
1234 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1235 let snapshot = buffer_editor.snapshot(window, cx);
1236 let snapshot = &snapshot.buffer_snapshot;
1237 let new_buffer_hunks = buffer_editor
1238 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1239 .collect::<Vec<_>>();
1240 buffer_editor.git_restore(&Default::default(), window, cx);
1241 new_buffer_hunks
1242 });
1243 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1244
1245 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1246 buffer_editor.set_text("different\n", window, cx);
1247 buffer_editor.save(false, project.clone(), window, cx)
1248 })
1249 .await
1250 .unwrap();
1251
1252 cx.run_until_parked();
1253
1254 assert_state_with_diff(
1255 &diff_editor,
1256 cx,
1257 &"
1258 - original
1259 + ˇdifferent
1260 "
1261 .unindent(),
1262 );
1263 }
1264}