project_diff.rs

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