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 commit = 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 commit = git_panel.can_commit();
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 commit,
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 commit: 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",
816 &StageAndNext {
817 whole_excerpt: false,
818 },
819 &focus_handle,
820 ))
821 // don't actually disable the button so it's mashable
822 .color(if button_states.stage {
823 Color::Default
824 } else {
825 Color::Disabled
826 })
827 .on_click(cx.listener(|this, _, window, cx| {
828 this.dispatch_action(
829 &StageAndNext {
830 whole_excerpt: false,
831 },
832 window,
833 cx,
834 )
835 })),
836 )
837 .child(
838 Button::new("unstage", "Unstage")
839 .tooltip(Tooltip::for_action_title_in(
840 "Unstage",
841 &UnstageAndNext {
842 whole_excerpt: false,
843 },
844 &focus_handle,
845 ))
846 .color(if button_states.unstage {
847 Color::Default
848 } else {
849 Color::Disabled
850 })
851 .on_click(cx.listener(|this, _, window, cx| {
852 this.dispatch_action(
853 &UnstageAndNext {
854 whole_excerpt: false,
855 },
856 window,
857 cx,
858 )
859 })),
860 )
861 }),
862 )
863 // n.b. the only reason these arrows are here is because we don't
864 // support "undo" for staging so we need a way to go back.
865 .child(
866 h_group_sm()
867 .child(
868 IconButton::new("up", IconName::ArrowUp)
869 .shape(ui::IconButtonShape::Square)
870 .tooltip(Tooltip::for_action_title_in(
871 "Go to previous hunk",
872 &GoToPreviousHunk {
873 center_cursor: false,
874 },
875 &focus_handle,
876 ))
877 .disabled(!button_states.prev_next)
878 .on_click(cx.listener(|this, _, window, cx| {
879 this.dispatch_action(
880 &GoToPreviousHunk {
881 center_cursor: true,
882 },
883 window,
884 cx,
885 )
886 })),
887 )
888 .child(
889 IconButton::new("down", IconName::ArrowDown)
890 .shape(ui::IconButtonShape::Square)
891 .tooltip(Tooltip::for_action_title_in(
892 "Go to next hunk",
893 &GoToHunk {
894 center_cursor: false,
895 },
896 &focus_handle,
897 ))
898 .disabled(!button_states.prev_next)
899 .on_click(cx.listener(|this, _, window, cx| {
900 this.dispatch_action(
901 &GoToHunk {
902 center_cursor: true,
903 },
904 window,
905 cx,
906 )
907 })),
908 ),
909 )
910 .child(vertical_divider())
911 .child(
912 h_group_sm()
913 .when(
914 button_states.unstage_all && !button_states.stage_all,
915 |el| {
916 el.child(
917 Button::new("unstage-all", "Unstage All")
918 .tooltip(Tooltip::for_action_title_in(
919 "Unstage all changes",
920 &UnstageAll,
921 &focus_handle,
922 ))
923 .on_click(cx.listener(|this, _, window, cx| {
924 this.dispatch_panel_action(&UnstageAll, window, cx)
925 })),
926 )
927 },
928 )
929 .when(
930 !button_states.unstage_all || button_states.stage_all,
931 |el| {
932 el.child(
933 // todo make it so that changing to say "Unstaged"
934 // doesn't change the position.
935 div().child(
936 Button::new("stage-all", "Stage All")
937 .disabled(!button_states.stage_all)
938 .tooltip(Tooltip::for_action_title_in(
939 "Stage all changes",
940 &StageAll,
941 &focus_handle,
942 ))
943 .on_click(cx.listener(|this, _, window, cx| {
944 this.dispatch_panel_action(&StageAll, window, cx)
945 })),
946 ),
947 )
948 },
949 )
950 .child(
951 Button::new("commit", "Commit")
952 .disabled(!button_states.commit)
953 .tooltip(Tooltip::for_action_title_in(
954 "Commit",
955 &ShowCommitEditor,
956 &focus_handle,
957 ))
958 .on_click(cx.listener(|this, _, window, cx| {
959 this.dispatch_action(&ShowCommitEditor, window, cx);
960 })),
961 ),
962 )
963 }
964}
965
966#[cfg(test)]
967mod tests {
968 use std::path::Path;
969
970 use collections::HashMap;
971 use editor::test::editor_test_context::assert_state_with_diff;
972 use git::status::{StatusCode, TrackedStatus};
973 use gpui::TestAppContext;
974 use project::FakeFs;
975 use serde_json::json;
976 use settings::SettingsStore;
977 use unindent::Unindent as _;
978 use util::path;
979
980 use super::*;
981
982 #[ctor::ctor]
983 fn init_logger() {
984 env_logger::init();
985 }
986
987 fn init_test(cx: &mut TestAppContext) {
988 cx.update(|cx| {
989 let store = SettingsStore::test(cx);
990 cx.set_global(store);
991 theme::init(theme::LoadThemes::JustBase, cx);
992 language::init(cx);
993 Project::init_settings(cx);
994 workspace::init_settings(cx);
995 editor::init(cx);
996 crate::init(cx);
997 });
998 }
999
1000 #[gpui::test]
1001 async fn test_save_after_restore(cx: &mut TestAppContext) {
1002 init_test(cx);
1003
1004 let fs = FakeFs::new(cx.executor());
1005 fs.insert_tree(
1006 path!("/project"),
1007 json!({
1008 ".git": {},
1009 "foo.txt": "FOO\n",
1010 }),
1011 )
1012 .await;
1013 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1014 let (workspace, cx) =
1015 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1016 let diff = cx.new_window_entity(|window, cx| {
1017 ProjectDiff::new(project.clone(), workspace, window, cx)
1018 });
1019 cx.run_until_parked();
1020
1021 fs.set_head_for_repo(
1022 path!("/project/.git").as_ref(),
1023 &[("foo.txt".into(), "foo\n".into())],
1024 );
1025 fs.set_index_for_repo(
1026 path!("/project/.git").as_ref(),
1027 &[("foo.txt".into(), "foo\n".into())],
1028 );
1029 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1030 state.statuses = HashMap::from_iter([(
1031 "foo.txt".into(),
1032 TrackedStatus {
1033 index_status: StatusCode::Unmodified,
1034 worktree_status: StatusCode::Modified,
1035 }
1036 .into(),
1037 )]);
1038 });
1039 cx.run_until_parked();
1040
1041 let editor = diff.update(cx, |diff, _| diff.editor.clone());
1042 assert_state_with_diff(
1043 &editor,
1044 cx,
1045 &"
1046 - foo
1047 + ˇFOO
1048 "
1049 .unindent(),
1050 );
1051
1052 editor.update_in(cx, |editor, window, cx| {
1053 editor.git_restore(&Default::default(), window, cx);
1054 });
1055 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1056 state.statuses = HashMap::default();
1057 });
1058 cx.run_until_parked();
1059
1060 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1061
1062 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1063 assert_eq!(text, "foo\n");
1064 }
1065
1066 #[gpui::test]
1067 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1068 init_test(cx);
1069
1070 let fs = FakeFs::new(cx.executor());
1071 fs.insert_tree(
1072 path!("/project"),
1073 json!({
1074 ".git": {},
1075 "bar": "BAR\n",
1076 "foo": "FOO\n",
1077 }),
1078 )
1079 .await;
1080 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1081 let (workspace, cx) =
1082 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1083 let diff = cx.new_window_entity(|window, cx| {
1084 ProjectDiff::new(project.clone(), workspace, window, cx)
1085 });
1086 cx.run_until_parked();
1087
1088 fs.set_head_for_repo(
1089 path!("/project/.git").as_ref(),
1090 &[
1091 ("bar".into(), "bar\n".into()),
1092 ("foo".into(), "foo\n".into()),
1093 ],
1094 );
1095 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1096 state.statuses = HashMap::from_iter([
1097 (
1098 "bar".into(),
1099 TrackedStatus {
1100 index_status: StatusCode::Unmodified,
1101 worktree_status: StatusCode::Modified,
1102 }
1103 .into(),
1104 ),
1105 (
1106 "foo".into(),
1107 TrackedStatus {
1108 index_status: StatusCode::Unmodified,
1109 worktree_status: StatusCode::Modified,
1110 }
1111 .into(),
1112 ),
1113 ]);
1114 });
1115 cx.run_until_parked();
1116
1117 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1118 diff.move_to_path(
1119 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("foo").into()),
1120 window,
1121 cx,
1122 );
1123 diff.editor.clone()
1124 });
1125 assert_state_with_diff(
1126 &editor,
1127 cx,
1128 &"
1129 - bar
1130 + BAR
1131
1132 - ˇfoo
1133 + FOO
1134 "
1135 .unindent(),
1136 );
1137
1138 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1139 diff.move_to_path(
1140 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("bar").into()),
1141 window,
1142 cx,
1143 );
1144 diff.editor.clone()
1145 });
1146 assert_state_with_diff(
1147 &editor,
1148 cx,
1149 &"
1150 - ˇbar
1151 + BAR
1152
1153 - foo
1154 + FOO
1155 "
1156 .unindent(),
1157 );
1158 }
1159
1160 #[gpui::test]
1161 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1162 init_test(cx);
1163
1164 let fs = FakeFs::new(cx.executor());
1165 fs.insert_tree(
1166 path!("/project"),
1167 json!({
1168 ".git": {},
1169 "foo": "modified\n",
1170 }),
1171 )
1172 .await;
1173 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1174 let (workspace, cx) =
1175 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1176 let buffer = project
1177 .update(cx, |project, cx| {
1178 project.open_local_buffer(path!("/project/foo"), cx)
1179 })
1180 .await
1181 .unwrap();
1182 let buffer_editor = cx.new_window_entity(|window, cx| {
1183 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1184 });
1185 let diff = cx.new_window_entity(|window, cx| {
1186 ProjectDiff::new(project.clone(), workspace, window, cx)
1187 });
1188 cx.run_until_parked();
1189
1190 fs.set_head_for_repo(
1191 path!("/project/.git").as_ref(),
1192 &[("foo".into(), "original\n".into())],
1193 );
1194 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1195 state.statuses = HashMap::from_iter([(
1196 "foo".into(),
1197 TrackedStatus {
1198 index_status: StatusCode::Unmodified,
1199 worktree_status: StatusCode::Modified,
1200 }
1201 .into(),
1202 )]);
1203 });
1204 cx.run_until_parked();
1205
1206 let diff_editor = diff.update(cx, |diff, _| diff.editor.clone());
1207
1208 assert_state_with_diff(
1209 &diff_editor,
1210 cx,
1211 &"
1212 - original
1213 + ˇmodified
1214 "
1215 .unindent(),
1216 );
1217
1218 let prev_buffer_hunks =
1219 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1220 let snapshot = buffer_editor.snapshot(window, cx);
1221 let snapshot = &snapshot.buffer_snapshot;
1222 let prev_buffer_hunks = buffer_editor
1223 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1224 .collect::<Vec<_>>();
1225 buffer_editor.git_restore(&Default::default(), window, cx);
1226 prev_buffer_hunks
1227 });
1228 assert_eq!(prev_buffer_hunks.len(), 1);
1229 cx.run_until_parked();
1230
1231 let new_buffer_hunks =
1232 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1233 let snapshot = buffer_editor.snapshot(window, cx);
1234 let snapshot = &snapshot.buffer_snapshot;
1235 let new_buffer_hunks = buffer_editor
1236 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1237 .collect::<Vec<_>>();
1238 buffer_editor.git_restore(&Default::default(), window, cx);
1239 new_buffer_hunks
1240 });
1241 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1242
1243 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1244 buffer_editor.set_text("different\n", window, cx);
1245 buffer_editor.save(false, project.clone(), window, cx)
1246 })
1247 .await
1248 .unwrap();
1249
1250 cx.run_until_parked();
1251
1252 assert_state_with_diff(
1253 &diff_editor,
1254 cx,
1255 &"
1256 - original
1257 + ˇdifferent
1258 "
1259 .unindent(),
1260 );
1261 }
1262}