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