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.scroll_to(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 scroll_to(
 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.scroll_to_path(path_key, window, cx)
 193    }
 194
 195    fn scroll_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 is_excerpt_newly_added = self.multibuffer.update(cx, |multibuffer, cx| {
 389            multibuffer.set_excerpts_for_path(
 390                path_key.clone(),
 391                buffer,
 392                diff_hunk_ranges,
 393                editor::DEFAULT_MULTIBUFFER_CONTEXT,
 394                cx,
 395            )
 396        });
 397
 398        if is_excerpt_newly_added && diff_buffer.file_status.is_deleted() {
 399            self.editor.update(cx, |editor, cx| {
 400                editor.fold_buffer(snapshot.text.remote_id(), cx)
 401            });
 402        }
 403
 404        if self.multibuffer.read(cx).is_empty()
 405            && self
 406                .editor
 407                .read(cx)
 408                .focus_handle(cx)
 409                .contains_focused(window, cx)
 410        {
 411            self.focus_handle.focus(window);
 412        } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
 413            self.editor.update(cx, |editor, cx| {
 414                editor.focus_handle(cx).focus(window);
 415            });
 416        }
 417        if self.pending_scroll.as_ref() == Some(&path_key) {
 418            self.scroll_to_path(path_key, window, cx);
 419        }
 420    }
 421
 422    pub async fn handle_status_updates(
 423        this: WeakEntity<Self>,
 424        mut recv: postage::watch::Receiver<()>,
 425        mut cx: AsyncWindowContext,
 426    ) -> Result<()> {
 427        while let Some(_) = recv.next().await {
 428            let buffers_to_load = this.update(&mut cx, |this, cx| this.load_buffers(cx))?;
 429            for buffer_to_load in buffers_to_load {
 430                if let Some(buffer) = buffer_to_load.await.log_err() {
 431                    cx.update(|window, cx| {
 432                        this.update(cx, |this, cx| this.register_buffer(buffer, window, cx))
 433                            .ok();
 434                    })?;
 435                }
 436            }
 437            this.update(&mut cx, |this, _| this.pending_scroll.take())?;
 438        }
 439
 440        Ok(())
 441    }
 442
 443    #[cfg(any(test, feature = "test-support"))]
 444    pub fn excerpt_paths(&self, cx: &App) -> Vec<String> {
 445        self.multibuffer
 446            .read(cx)
 447            .excerpt_paths()
 448            .map(|key| key.path().to_string_lossy().to_string())
 449            .collect()
 450    }
 451}
 452
 453impl EventEmitter<EditorEvent> for ProjectDiff {}
 454
 455impl Focusable for ProjectDiff {
 456    fn focus_handle(&self, cx: &App) -> FocusHandle {
 457        if self.multibuffer.read(cx).is_empty() {
 458            self.focus_handle.clone()
 459        } else {
 460            self.editor.focus_handle(cx)
 461        }
 462    }
 463}
 464
 465impl Item for ProjectDiff {
 466    type Event = EditorEvent;
 467
 468    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 469        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
 470    }
 471
 472    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 473        Editor::to_item_events(event, f)
 474    }
 475
 476    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 477        self.editor
 478            .update(cx, |editor, cx| editor.deactivated(window, cx));
 479    }
 480
 481    fn navigate(
 482        &mut self,
 483        data: Box<dyn Any>,
 484        window: &mut Window,
 485        cx: &mut Context<Self>,
 486    ) -> bool {
 487        self.editor
 488            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 489    }
 490
 491    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 492        Some("Project Diff".into())
 493    }
 494
 495    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
 496        Label::new("Uncommitted Changes")
 497            .color(if params.selected {
 498                Color::Default
 499            } else {
 500                Color::Muted
 501            })
 502            .into_any_element()
 503    }
 504
 505    fn telemetry_event_text(&self) -> Option<&'static str> {
 506        Some("Project Diff Opened")
 507    }
 508
 509    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 510        Some(Box::new(self.editor.clone()))
 511    }
 512
 513    fn for_each_project_item(
 514        &self,
 515        cx: &App,
 516        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 517    ) {
 518        self.editor.for_each_project_item(cx, f)
 519    }
 520
 521    fn is_singleton(&self, _: &App) -> bool {
 522        false
 523    }
 524
 525    fn set_nav_history(
 526        &mut self,
 527        nav_history: ItemNavHistory,
 528        _: &mut Window,
 529        cx: &mut Context<Self>,
 530    ) {
 531        self.editor.update(cx, |editor, _| {
 532            editor.set_nav_history(Some(nav_history));
 533        });
 534    }
 535
 536    fn clone_on_split(
 537        &self,
 538        _workspace_id: Option<workspace::WorkspaceId>,
 539        window: &mut Window,
 540        cx: &mut Context<Self>,
 541    ) -> Option<Entity<Self>>
 542    where
 543        Self: Sized,
 544    {
 545        let workspace = self.workspace.upgrade()?;
 546        Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
 547    }
 548
 549    fn is_dirty(&self, cx: &App) -> bool {
 550        self.multibuffer.read(cx).is_dirty(cx)
 551    }
 552
 553    fn has_conflict(&self, cx: &App) -> bool {
 554        self.multibuffer.read(cx).has_conflict(cx)
 555    }
 556
 557    fn can_save(&self, _: &App) -> bool {
 558        true
 559    }
 560
 561    fn save(
 562        &mut self,
 563        format: bool,
 564        project: Entity<Project>,
 565        window: &mut Window,
 566        cx: &mut Context<Self>,
 567    ) -> Task<Result<()>> {
 568        self.editor.save(format, project, window, cx)
 569    }
 570
 571    fn save_as(
 572        &mut self,
 573        _: Entity<Project>,
 574        _: ProjectPath,
 575        _window: &mut Window,
 576        _: &mut Context<Self>,
 577    ) -> Task<Result<()>> {
 578        unreachable!()
 579    }
 580
 581    fn reload(
 582        &mut self,
 583        project: Entity<Project>,
 584        window: &mut Window,
 585        cx: &mut Context<Self>,
 586    ) -> Task<Result<()>> {
 587        self.editor.reload(project, window, cx)
 588    }
 589
 590    fn act_as_type<'a>(
 591        &'a self,
 592        type_id: TypeId,
 593        self_handle: &'a Entity<Self>,
 594        _: &'a App,
 595    ) -> Option<AnyView> {
 596        if type_id == TypeId::of::<Self>() {
 597            Some(self_handle.to_any())
 598        } else if type_id == TypeId::of::<Editor>() {
 599            Some(self.editor.to_any())
 600        } else {
 601            None
 602        }
 603    }
 604
 605    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 606        ToolbarItemLocation::PrimaryLeft
 607    }
 608
 609    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 610        self.editor.breadcrumbs(theme, cx)
 611    }
 612
 613    fn added_to_workspace(
 614        &mut self,
 615        workspace: &mut Workspace,
 616        window: &mut Window,
 617        cx: &mut Context<Self>,
 618    ) {
 619        self.editor.update(cx, |editor, cx| {
 620            editor.added_to_workspace(workspace, window, cx)
 621        });
 622    }
 623}
 624
 625impl Render for ProjectDiff {
 626    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 627        let is_empty = self.multibuffer.read(cx).is_empty();
 628
 629        div()
 630            .track_focus(&self.focus_handle)
 631            .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
 632            .bg(cx.theme().colors().editor_background)
 633            .flex()
 634            .items_center()
 635            .justify_center()
 636            .size_full()
 637            .when(is_empty, |el| {
 638                el.child(Label::new("No uncommitted changes"))
 639            })
 640            .when(!is_empty, |el| el.child(self.editor.clone()))
 641    }
 642}
 643
 644impl SerializableItem for ProjectDiff {
 645    fn serialized_item_kind() -> &'static str {
 646        "ProjectDiff"
 647    }
 648
 649    fn cleanup(
 650        _: workspace::WorkspaceId,
 651        _: Vec<workspace::ItemId>,
 652        _: &mut Window,
 653        _: &mut App,
 654    ) -> Task<Result<()>> {
 655        Task::ready(Ok(()))
 656    }
 657
 658    fn deserialize(
 659        _project: Entity<Project>,
 660        workspace: WeakEntity<Workspace>,
 661        _workspace_id: workspace::WorkspaceId,
 662        _item_id: workspace::ItemId,
 663        window: &mut Window,
 664        cx: &mut App,
 665    ) -> Task<Result<Entity<Self>>> {
 666        window.spawn(cx, |mut cx| async move {
 667            workspace.update_in(&mut cx, |workspace, window, cx| {
 668                let workspace_handle = cx.entity();
 669                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
 670            })
 671        })
 672    }
 673
 674    fn serialize(
 675        &mut self,
 676        _workspace: &mut Workspace,
 677        _item_id: workspace::ItemId,
 678        _closing: bool,
 679        _window: &mut Window,
 680        _cx: &mut Context<Self>,
 681    ) -> Option<Task<Result<()>>> {
 682        None
 683    }
 684
 685    fn should_serialize(&self, _: &Self::Event) -> bool {
 686        false
 687    }
 688}
 689
 690pub struct ProjectDiffToolbar {
 691    project_diff: Option<WeakEntity<ProjectDiff>>,
 692    workspace: WeakEntity<Workspace>,
 693}
 694
 695impl ProjectDiffToolbar {
 696    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
 697        Self {
 698            project_diff: None,
 699            workspace: workspace.weak_handle(),
 700        }
 701    }
 702
 703    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
 704        self.project_diff.as_ref()?.upgrade()
 705    }
 706    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 707        if let Some(project_diff) = self.project_diff(cx) {
 708            project_diff.focus_handle(cx).focus(window);
 709        }
 710        let action = action.boxed_clone();
 711        cx.defer(move |cx| {
 712            cx.dispatch_action(action.as_ref());
 713        })
 714    }
 715    fn dispatch_panel_action(
 716        &self,
 717        action: &dyn Action,
 718        window: &mut Window,
 719        cx: &mut Context<Self>,
 720    ) {
 721        self.workspace
 722            .read_with(cx, |workspace, cx| {
 723                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
 724                    panel.focus_handle(cx).focus(window)
 725                }
 726            })
 727            .ok();
 728        let action = action.boxed_clone();
 729        cx.defer(move |cx| {
 730            cx.dispatch_action(action.as_ref());
 731        })
 732    }
 733}
 734
 735impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
 736
 737impl ToolbarItemView for ProjectDiffToolbar {
 738    fn set_active_pane_item(
 739        &mut self,
 740        active_pane_item: Option<&dyn ItemHandle>,
 741        _: &mut Window,
 742        cx: &mut Context<Self>,
 743    ) -> ToolbarItemLocation {
 744        self.project_diff = active_pane_item
 745            .and_then(|item| item.act_as::<ProjectDiff>(cx))
 746            .map(|entity| entity.downgrade());
 747        if self.project_diff.is_some() {
 748            ToolbarItemLocation::PrimaryRight
 749        } else {
 750            ToolbarItemLocation::Hidden
 751        }
 752    }
 753
 754    fn pane_focus_update(
 755        &mut self,
 756        _pane_focused: bool,
 757        _window: &mut Window,
 758        _cx: &mut Context<Self>,
 759    ) {
 760    }
 761}
 762
 763struct ButtonStates {
 764    stage: bool,
 765    unstage: bool,
 766    prev_next: bool,
 767    selection: bool,
 768    stage_all: bool,
 769    unstage_all: bool,
 770    commit: bool,
 771}
 772
 773impl Render for ProjectDiffToolbar {
 774    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 775        let Some(project_diff) = self.project_diff(cx) else {
 776            return div();
 777        };
 778        let focus_handle = project_diff.focus_handle(cx);
 779        let button_states = project_diff.read(cx).button_states(cx);
 780
 781        h_group_xl()
 782            .my_neg_1()
 783            .items_center()
 784            .py_1()
 785            .pl_2()
 786            .pr_1()
 787            .flex_wrap()
 788            .justify_between()
 789            .child(
 790                h_group_sm()
 791                    .when(button_states.selection, |el| {
 792                        el.child(
 793                            Button::new("stage", "Toggle Staged")
 794                                .tooltip(Tooltip::for_action_title_in(
 795                                    "Toggle Staged",
 796                                    &ToggleStaged,
 797                                    &focus_handle,
 798                                ))
 799                                .disabled(!button_states.stage && !button_states.unstage)
 800                                .on_click(cx.listener(|this, _, window, cx| {
 801                                    this.dispatch_action(&ToggleStaged, window, cx)
 802                                })),
 803                        )
 804                    })
 805                    .when(!button_states.selection, |el| {
 806                        el.child(
 807                            Button::new("stage", "Stage")
 808                                .tooltip(Tooltip::for_action_title_in(
 809                                    "Stage",
 810                                    &StageAndNext,
 811                                    &focus_handle,
 812                                ))
 813                                // don't actually disable the button so it's mashable
 814                                .color(if button_states.stage {
 815                                    Color::Default
 816                                } else {
 817                                    Color::Disabled
 818                                })
 819                                .on_click(cx.listener(|this, _, window, cx| {
 820                                    this.dispatch_action(&StageAndNext, window, cx)
 821                                })),
 822                        )
 823                        .child(
 824                            Button::new("unstage", "Unstage")
 825                                .tooltip(Tooltip::for_action_title_in(
 826                                    "Unstage",
 827                                    &UnstageAndNext,
 828                                    &focus_handle,
 829                                ))
 830                                .color(if button_states.unstage {
 831                                    Color::Default
 832                                } else {
 833                                    Color::Disabled
 834                                })
 835                                .on_click(cx.listener(|this, _, window, cx| {
 836                                    this.dispatch_action(&UnstageAndNext, window, cx)
 837                                })),
 838                        )
 839                    }),
 840            )
 841            // n.b. the only reason these arrows are here is because we don't
 842            // support "undo" for staging so we need a way to go back.
 843            .child(
 844                h_group_sm()
 845                    .child(
 846                        IconButton::new("up", IconName::ArrowUp)
 847                            .shape(ui::IconButtonShape::Square)
 848                            .tooltip(Tooltip::for_action_title_in(
 849                                "Go to previous hunk",
 850                                &GoToPrevHunk,
 851                                &focus_handle,
 852                            ))
 853                            .disabled(!button_states.prev_next)
 854                            .on_click(cx.listener(|this, _, window, cx| {
 855                                this.dispatch_action(&GoToPrevHunk, window, cx)
 856                            })),
 857                    )
 858                    .child(
 859                        IconButton::new("down", IconName::ArrowDown)
 860                            .shape(ui::IconButtonShape::Square)
 861                            .tooltip(Tooltip::for_action_title_in(
 862                                "Go to next hunk",
 863                                &GoToHunk,
 864                                &focus_handle,
 865                            ))
 866                            .disabled(!button_states.prev_next)
 867                            .on_click(cx.listener(|this, _, window, cx| {
 868                                this.dispatch_action(&GoToHunk, window, cx)
 869                            })),
 870                    ),
 871            )
 872            .child(vertical_divider())
 873            .child(
 874                h_group_sm()
 875                    .when(
 876                        button_states.unstage_all && !button_states.stage_all,
 877                        |el| {
 878                            el.child(
 879                                Button::new("unstage-all", "Unstage All")
 880                                    .tooltip(Tooltip::for_action_title_in(
 881                                        "Unstage all changes",
 882                                        &UnstageAll,
 883                                        &focus_handle,
 884                                    ))
 885                                    .on_click(cx.listener(|this, _, window, cx| {
 886                                        this.dispatch_panel_action(&UnstageAll, window, cx)
 887                                    })),
 888                            )
 889                        },
 890                    )
 891                    .when(
 892                        !button_states.unstage_all || button_states.stage_all,
 893                        |el| {
 894                            el.child(
 895                                // todo make it so that changing to say "Unstaged"
 896                                // doesn't change the position.
 897                                div().child(
 898                                    Button::new("stage-all", "Stage All")
 899                                        .disabled(!button_states.stage_all)
 900                                        .tooltip(Tooltip::for_action_title_in(
 901                                            "Stage all changes",
 902                                            &StageAll,
 903                                            &focus_handle,
 904                                        ))
 905                                        .on_click(cx.listener(|this, _, window, cx| {
 906                                            this.dispatch_panel_action(&StageAll, window, cx)
 907                                        })),
 908                                ),
 909                            )
 910                        },
 911                    )
 912                    .child(
 913                        Button::new("commit", "Commit")
 914                            .disabled(!button_states.commit)
 915                            .tooltip(Tooltip::for_action_title_in(
 916                                "Commit",
 917                                &Commit,
 918                                &focus_handle,
 919                            ))
 920                            .on_click(cx.listener(|this, _, window, cx| {
 921                                this.dispatch_action(&Commit, window, cx);
 922                            })),
 923                    ),
 924            )
 925    }
 926}
 927
 928#[cfg(test)]
 929mod tests {
 930    use collections::HashMap;
 931    use editor::test::editor_test_context::assert_state_with_diff;
 932    use git::status::{StatusCode, TrackedStatus};
 933    use gpui::TestAppContext;
 934    use project::FakeFs;
 935    use serde_json::json;
 936    use settings::SettingsStore;
 937    use unindent::Unindent as _;
 938    use util::path;
 939
 940    use super::*;
 941
 942    fn init_test(cx: &mut TestAppContext) {
 943        cx.update(|cx| {
 944            let store = SettingsStore::test(cx);
 945            cx.set_global(store);
 946            theme::init(theme::LoadThemes::JustBase, cx);
 947            language::init(cx);
 948            Project::init_settings(cx);
 949            workspace::init_settings(cx);
 950            editor::init(cx);
 951            crate::init(cx);
 952        });
 953    }
 954
 955    #[gpui::test]
 956    async fn test_save_after_restore(cx: &mut TestAppContext) {
 957        init_test(cx);
 958
 959        let fs = FakeFs::new(cx.executor());
 960        fs.insert_tree(
 961            path!("/project"),
 962            json!({
 963                ".git": {},
 964                "foo": "FOO\n",
 965            }),
 966        )
 967        .await;
 968        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
 969        let (workspace, cx) =
 970            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 971        let diff = cx.new_window_entity(|window, cx| {
 972            ProjectDiff::new(project.clone(), workspace, window, cx)
 973        });
 974        cx.run_until_parked();
 975
 976        fs.set_head_for_repo(
 977            path!("/project/.git").as_ref(),
 978            &[("foo".into(), "foo\n".into())],
 979        );
 980        fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
 981            state.statuses = HashMap::from_iter([(
 982                "foo".into(),
 983                TrackedStatus {
 984                    index_status: StatusCode::Unmodified,
 985                    worktree_status: StatusCode::Modified,
 986                }
 987                .into(),
 988            )]);
 989        });
 990        cx.run_until_parked();
 991
 992        let editor = diff.update(cx, |diff, _| diff.editor.clone());
 993        assert_state_with_diff(
 994            &editor,
 995            cx,
 996            &"
 997                - foo
 998                + FOO
 999                  ˇ"
1000            .unindent(),
1001        );
1002
1003        editor.update_in(cx, |editor, window, cx| {
1004            editor.restore_file(&Default::default(), window, cx);
1005        });
1006        fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1007            state.statuses = HashMap::default();
1008        });
1009        cx.run_until_parked();
1010
1011        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1012
1013        let text = String::from_utf8(fs.read_file_sync("/project/foo").unwrap()).unwrap();
1014        assert_eq!(text, "foo\n");
1015    }
1016}