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