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