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