project_diff.rs

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