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