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