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