git_panel.rs

   1use crate::askpass_modal::AskPassModal;
   2use crate::commit_modal::CommitModal;
   3use crate::git_panel_settings::StatusStyle;
   4use crate::project_diff::Diff;
   5use crate::remote_output::{self, RemoteAction, SuccessMessage};
   6use crate::repository_selector::filtered_repository_entries;
   7use crate::{branch_picker, render_remote_button};
   8use crate::{
   9    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
  10};
  11use crate::{picker_prompt, project_diff, ProjectDiff};
  12use anyhow::Result;
  13use askpass::AskPassDelegate;
  14use assistant_settings::AssistantSettings;
  15use db::kvp::KEY_VALUE_STORE;
  16use editor::commit_tooltip::CommitTooltip;
  17
  18use editor::{
  19    scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
  20    ShowScrollbar,
  21};
  22use futures::StreamExt as _;
  23use git::repository::{
  24    Branch, CommitDetails, CommitSummary, DiffType, PushOptions, Remote, RemoteCommandOutput,
  25    ResetMode, Upstream, UpstreamTracking, UpstreamTrackingStatus,
  26};
  27use git::status::StageStatus;
  28use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
  29use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
  30use gpui::{
  31    actions, anchored, deferred, percentage, uniform_list, Action, Animation, AnimationExt as _,
  32    Axis, ClickEvent, Corner, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  33    KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior, Modifiers, ModifiersChangedEvent,
  34    MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Subscription, Task,
  35    Transformation, UniformListScrollHandle, WeakEntity,
  36};
  37use itertools::Itertools;
  38use language::{Buffer, File};
  39use language_model::{
  40    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
  41};
  42use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  43use multi_buffer::ExcerptInfo;
  44use panel::{
  45    panel_button, panel_editor_container, panel_editor_style, panel_filled_button,
  46    panel_icon_button, PanelHeader,
  47};
  48use project::{
  49    git::{GitEvent, Repository},
  50    Fs, Project, ProjectPath,
  51};
  52use serde::{Deserialize, Serialize};
  53use settings::{Settings as _, SettingsStore};
  54use std::cell::RefCell;
  55use std::future::Future;
  56use std::path::{Path, PathBuf};
  57use std::rc::Rc;
  58use std::{collections::HashSet, sync::Arc, time::Duration, usize};
  59use strum::{IntoEnumIterator, VariantNames};
  60use time::OffsetDateTime;
  61use ui::{
  62    prelude::*, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState,
  63    Tooltip,
  64};
  65use util::{maybe, post_inc, ResultExt, TryFutureExt};
  66use workspace::{AppState, OpenOptions, OpenVisible};
  67
  68use notifications::status_toast::{StatusToast, ToastIcon};
  69use workspace::{
  70    dock::{DockPosition, Panel, PanelEvent},
  71    notifications::DetachAndPromptErr,
  72    Workspace,
  73};
  74
  75actions!(
  76    git_panel,
  77    [
  78        Close,
  79        ToggleFocus,
  80        OpenMenu,
  81        FocusEditor,
  82        FocusChanges,
  83        ToggleFillCoAuthors,
  84        GenerateCommitMessage
  85    ]
  86);
  87
  88fn prompt<T>(
  89    msg: &str,
  90    detail: Option<&str>,
  91    window: &mut Window,
  92    cx: &mut App,
  93) -> Task<anyhow::Result<T>>
  94where
  95    T: IntoEnumIterator + VariantNames + 'static,
  96{
  97    let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
  98    cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
  99}
 100
 101#[derive(strum::EnumIter, strum::VariantNames)]
 102#[strum(serialize_all = "title_case")]
 103enum TrashCancel {
 104    Trash,
 105    Cancel,
 106}
 107
 108fn git_panel_context_menu(
 109    focus_handle: FocusHandle,
 110    window: &mut Window,
 111    cx: &mut App,
 112) -> Entity<ContextMenu> {
 113    ContextMenu::build(window, cx, |context_menu, _, _| {
 114        context_menu
 115            .context(focus_handle)
 116            .action("Stage All", StageAll.boxed_clone())
 117            .action("Unstage All", UnstageAll.boxed_clone())
 118            .separator()
 119            .action("Open Diff", project_diff::Diff.boxed_clone())
 120            .separator()
 121            .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
 122            .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
 123    })
 124}
 125
 126const GIT_PANEL_KEY: &str = "GitPanel";
 127
 128const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
 129
 130pub fn init(cx: &mut App) {
 131    cx.observe_new(
 132        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
 133            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
 134                workspace.toggle_panel_focus::<GitPanel>(window, cx);
 135            });
 136            workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
 137                CommitModal::toggle(workspace, window, cx)
 138            });
 139        },
 140    )
 141    .detach();
 142}
 143
 144#[derive(Debug, Clone)]
 145pub enum Event {
 146    Focus,
 147}
 148
 149#[derive(Serialize, Deserialize)]
 150struct SerializedGitPanel {
 151    width: Option<Pixels>,
 152}
 153
 154#[derive(Debug, PartialEq, Eq, Clone, Copy)]
 155enum Section {
 156    Conflict,
 157    Tracked,
 158    New,
 159}
 160
 161#[derive(Debug, PartialEq, Eq, Clone)]
 162struct GitHeaderEntry {
 163    header: Section,
 164}
 165
 166impl GitHeaderEntry {
 167    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
 168        let this = &self.header;
 169        let status = status_entry.status;
 170        match this {
 171            Section::Conflict => repo.has_conflict(&status_entry.repo_path),
 172            Section::Tracked => !status.is_created(),
 173            Section::New => status.is_created(),
 174        }
 175    }
 176    pub fn title(&self) -> &'static str {
 177        match self.header {
 178            Section::Conflict => "Conflicts",
 179            Section::Tracked => "Tracked",
 180            Section::New => "Untracked",
 181        }
 182    }
 183}
 184
 185#[derive(Debug, PartialEq, Eq, Clone)]
 186enum GitListEntry {
 187    GitStatusEntry(GitStatusEntry),
 188    Header(GitHeaderEntry),
 189}
 190
 191impl GitListEntry {
 192    fn status_entry(&self) -> Option<&GitStatusEntry> {
 193        match self {
 194            GitListEntry::GitStatusEntry(entry) => Some(entry),
 195            _ => None,
 196        }
 197    }
 198}
 199
 200#[derive(Debug, PartialEq, Eq, Clone)]
 201pub struct GitStatusEntry {
 202    pub(crate) repo_path: RepoPath,
 203    pub(crate) worktree_path: Arc<Path>,
 204    pub(crate) abs_path: PathBuf,
 205    pub(crate) status: FileStatus,
 206    pub(crate) staging: StageStatus,
 207}
 208
 209impl GitStatusEntry {
 210    fn display_name(&self) -> String {
 211        self.worktree_path
 212            .file_name()
 213            .map(|name| name.to_string_lossy().into_owned())
 214            .unwrap_or_else(|| self.worktree_path.to_string_lossy().into_owned())
 215    }
 216
 217    fn parent_dir(&self) -> Option<String> {
 218        self.worktree_path
 219            .parent()
 220            .map(|parent| parent.to_string_lossy().into_owned())
 221    }
 222}
 223
 224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 225enum TargetStatus {
 226    Staged,
 227    Unstaged,
 228    Reverted,
 229    Unchanged,
 230}
 231
 232struct PendingOperation {
 233    finished: bool,
 234    target_status: TargetStatus,
 235    entries: Vec<GitStatusEntry>,
 236    op_id: usize,
 237}
 238
 239type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
 240
 241// computed state related to how to render scrollbars
 242// one per axis
 243// on render we just read this off the panel
 244// we update it when
 245// - settings change
 246// - on focus in, on focus out, on hover, etc.
 247#[derive(Debug)]
 248struct ScrollbarProperties {
 249    axis: Axis,
 250    show_scrollbar: bool,
 251    show_track: bool,
 252    auto_hide: bool,
 253    hide_task: Option<Task<()>>,
 254    state: ScrollbarState,
 255}
 256
 257impl ScrollbarProperties {
 258    // Shows the scrollbar and cancels any pending hide task
 259    fn show(&mut self, cx: &mut Context<GitPanel>) {
 260        if !self.auto_hide {
 261            return;
 262        }
 263        self.show_scrollbar = true;
 264        self.hide_task.take();
 265        cx.notify();
 266    }
 267
 268    fn hide(&mut self, window: &mut Window, cx: &mut Context<GitPanel>) {
 269        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
 270
 271        if !self.auto_hide {
 272            return;
 273        }
 274
 275        let axis = self.axis;
 276        self.hide_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
 277            cx.background_executor()
 278                .timer(SCROLLBAR_SHOW_INTERVAL)
 279                .await;
 280
 281            if let Some(panel) = panel.upgrade() {
 282                panel
 283                    .update(&mut cx, |panel, cx| {
 284                        match axis {
 285                            Axis::Vertical => panel.vertical_scrollbar.show_scrollbar = false,
 286                            Axis::Horizontal => panel.horizontal_scrollbar.show_scrollbar = false,
 287                        }
 288                        cx.notify();
 289                    })
 290                    .log_err();
 291            }
 292        }));
 293    }
 294}
 295
 296pub struct GitPanel {
 297    remote_operation_id: u32,
 298    pending_remote_operations: RemoteOperations,
 299    pub(crate) active_repository: Option<Entity<Repository>>,
 300    pub(crate) commit_editor: Entity<Editor>,
 301    conflicted_count: usize,
 302    conflicted_staged_count: usize,
 303    current_modifiers: Modifiers,
 304    add_coauthors: bool,
 305    generate_commit_message_task: Option<Task<Option<()>>>,
 306    entries: Vec<GitListEntry>,
 307    single_staged_entry: Option<GitStatusEntry>,
 308    single_tracked_entry: Option<GitStatusEntry>,
 309    focus_handle: FocusHandle,
 310    fs: Arc<dyn Fs>,
 311    horizontal_scrollbar: ScrollbarProperties,
 312    vertical_scrollbar: ScrollbarProperties,
 313    new_count: usize,
 314    entry_count: usize,
 315    new_staged_count: usize,
 316    pending: Vec<PendingOperation>,
 317    pending_commit: Option<Task<()>>,
 318    pending_serialization: Task<Option<()>>,
 319    pub(crate) project: Entity<Project>,
 320    scroll_handle: UniformListScrollHandle,
 321    max_width_item_index: Option<usize>,
 322    selected_entry: Option<usize>,
 323    marked_entries: Vec<usize>,
 324    tracked_count: usize,
 325    tracked_staged_count: usize,
 326    update_visible_entries_task: Task<()>,
 327    width: Option<Pixels>,
 328    workspace: WeakEntity<Workspace>,
 329    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 330    modal_open: bool,
 331    _settings_subscription: Subscription,
 332}
 333
 334struct RemoteOperationGuard {
 335    id: u32,
 336    pending_remote_operations: RemoteOperations,
 337}
 338
 339impl Drop for RemoteOperationGuard {
 340    fn drop(&mut self) {
 341        self.pending_remote_operations.borrow_mut().remove(&self.id);
 342    }
 343}
 344
 345const MAX_PANEL_EDITOR_LINES: usize = 6;
 346
 347pub(crate) fn commit_message_editor(
 348    commit_message_buffer: Entity<Buffer>,
 349    placeholder: Option<&str>,
 350    project: Entity<Project>,
 351    in_panel: bool,
 352    window: &mut Window,
 353    cx: &mut Context<'_, Editor>,
 354) -> Editor {
 355    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
 356    let max_lines = if in_panel { MAX_PANEL_EDITOR_LINES } else { 18 };
 357    let mut commit_editor = Editor::new(
 358        EditorMode::AutoHeight { max_lines },
 359        buffer,
 360        None,
 361        false,
 362        window,
 363        cx,
 364    );
 365    commit_editor.set_collaboration_hub(Box::new(project));
 366    commit_editor.set_use_autoclose(false);
 367    commit_editor.set_show_gutter(false, cx);
 368    commit_editor.set_show_wrap_guides(false, cx);
 369    commit_editor.set_show_indent_guides(false, cx);
 370    commit_editor.set_hard_wrap(Some(72), cx);
 371    let placeholder = placeholder.unwrap_or("Enter commit message");
 372    commit_editor.set_placeholder_text(placeholder, cx);
 373    commit_editor
 374}
 375
 376impl GitPanel {
 377    pub fn new(
 378        workspace: Entity<Workspace>,
 379        project: Entity<Project>,
 380        app_state: Arc<AppState>,
 381        window: &mut Window,
 382        cx: &mut Context<Self>,
 383    ) -> Self {
 384        let fs = app_state.fs.clone();
 385        let git_store = project.read(cx).git_store().clone();
 386        let active_repository = project.read(cx).active_repository(cx);
 387        let workspace = workspace.downgrade();
 388
 389        let focus_handle = cx.focus_handle();
 390        cx.on_focus(&focus_handle, window, Self::focus_in).detach();
 391        cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 392            this.hide_scrollbars(window, cx);
 393        })
 394        .detach();
 395
 396        // just to let us render a placeholder editor.
 397        // Once the active git repo is set, this buffer will be replaced.
 398        let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
 399        let commit_editor = cx.new(|cx| {
 400            commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
 401        });
 402
 403        commit_editor.update(cx, |editor, cx| {
 404            editor.clear(window, cx);
 405        });
 406
 407        let scroll_handle = UniformListScrollHandle::new();
 408
 409        cx.subscribe_in(
 410            &git_store,
 411            window,
 412            move |this, git_store, event, window, cx| match event {
 413                GitEvent::FileSystemUpdated => {
 414                    this.schedule_update(false, window, cx);
 415                }
 416                GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
 417                    this.active_repository = git_store.read(cx).active_repository();
 418                    this.schedule_update(true, window, cx);
 419                }
 420                GitEvent::IndexWriteError(error) => {
 421                    this.workspace
 422                        .update(cx, |workspace, cx| {
 423                            workspace.show_error(error, cx);
 424                        })
 425                        .ok();
 426                }
 427            },
 428        )
 429        .detach();
 430
 431        let vertical_scrollbar = ScrollbarProperties {
 432            axis: Axis::Vertical,
 433            state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
 434            show_scrollbar: false,
 435            show_track: false,
 436            auto_hide: false,
 437            hide_task: None,
 438        };
 439
 440        let horizontal_scrollbar = ScrollbarProperties {
 441            axis: Axis::Horizontal,
 442            state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
 443            show_scrollbar: false,
 444            show_track: false,
 445            auto_hide: false,
 446            hide_task: None,
 447        };
 448
 449        let mut assistant_enabled = AssistantSettings::get_global(cx).enabled;
 450        let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {
 451            if assistant_enabled != AssistantSettings::get_global(cx).enabled {
 452                assistant_enabled = AssistantSettings::get_global(cx).enabled;
 453                cx.notify();
 454            }
 455        });
 456
 457        let mut git_panel = Self {
 458            pending_remote_operations: Default::default(),
 459            remote_operation_id: 0,
 460            active_repository,
 461            commit_editor,
 462            conflicted_count: 0,
 463            conflicted_staged_count: 0,
 464            current_modifiers: window.modifiers(),
 465            add_coauthors: true,
 466            generate_commit_message_task: None,
 467            entries: Vec::new(),
 468            focus_handle: cx.focus_handle(),
 469            fs,
 470            new_count: 0,
 471            new_staged_count: 0,
 472            pending: Vec::new(),
 473            pending_commit: None,
 474            pending_serialization: Task::ready(None),
 475            single_staged_entry: None,
 476            single_tracked_entry: None,
 477            project,
 478            scroll_handle,
 479            max_width_item_index: None,
 480            selected_entry: None,
 481            marked_entries: Vec::new(),
 482            tracked_count: 0,
 483            tracked_staged_count: 0,
 484            update_visible_entries_task: Task::ready(()),
 485            width: None,
 486            context_menu: None,
 487            workspace,
 488            modal_open: false,
 489            entry_count: 0,
 490            horizontal_scrollbar,
 491            vertical_scrollbar,
 492            _settings_subscription,
 493        };
 494        git_panel.schedule_update(false, window, cx);
 495        git_panel
 496    }
 497
 498    fn hide_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 499        self.horizontal_scrollbar.hide(window, cx);
 500        self.vertical_scrollbar.hide(window, cx);
 501    }
 502
 503    fn update_scrollbar_properties(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
 504        // TODO: This PR should have defined Editor's `scrollbar.axis`
 505        // as an Option<ScrollbarAxis>, not a ScrollbarAxes as it would allow you to
 506        // `.unwrap_or(EditorSettings::get_global(cx).scrollbar.show)`.
 507        //
 508        // Once this is fixed we can extend the GitPanelSettings with a `scrollbar.axis`
 509        // so we can show each axis based on the settings.
 510        //
 511        // We should fix this. PR: https://github.com/zed-industries/zed/pull/19495
 512
 513        let show_setting = GitPanelSettings::get_global(cx)
 514            .scrollbar
 515            .show
 516            .unwrap_or(EditorSettings::get_global(cx).scrollbar.show);
 517
 518        let scroll_handle = self.scroll_handle.0.borrow();
 519
 520        let autohide = |show: ShowScrollbar, cx: &mut Context<Self>| match show {
 521            ShowScrollbar::Auto => true,
 522            ShowScrollbar::System => cx
 523                .try_global::<ScrollbarAutoHide>()
 524                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
 525            ShowScrollbar::Always => false,
 526            ShowScrollbar::Never => false,
 527        };
 528
 529        let longest_item_width = scroll_handle.last_item_size.and_then(|size| {
 530            (size.contents.width > size.item.width).then_some(size.contents.width)
 531        });
 532
 533        // is there an item long enough that we should show a horizontal scrollbar?
 534        let item_wider_than_container = if let Some(longest_item_width) = longest_item_width {
 535            longest_item_width > px(scroll_handle.base_handle.bounds().size.width.0)
 536        } else {
 537            true
 538        };
 539
 540        let show_horizontal = match (show_setting, item_wider_than_container) {
 541            (_, false) => false,
 542            (ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always, true) => true,
 543            (ShowScrollbar::Never, true) => false,
 544        };
 545
 546        let show_vertical = match show_setting {
 547            ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always => true,
 548            ShowScrollbar::Never => false,
 549        };
 550
 551        let show_horizontal_track =
 552            show_horizontal && matches!(show_setting, ShowScrollbar::Always);
 553
 554        // TODO: we probably should hide the scroll track when the list doesn't need to scroll
 555        let show_vertical_track = show_vertical && matches!(show_setting, ShowScrollbar::Always);
 556
 557        self.vertical_scrollbar = ScrollbarProperties {
 558            axis: self.vertical_scrollbar.axis,
 559            state: self.vertical_scrollbar.state.clone(),
 560            show_scrollbar: show_vertical,
 561            show_track: show_vertical_track,
 562            auto_hide: autohide(show_setting, cx),
 563            hide_task: None,
 564        };
 565
 566        self.horizontal_scrollbar = ScrollbarProperties {
 567            axis: self.horizontal_scrollbar.axis,
 568            state: self.horizontal_scrollbar.state.clone(),
 569            show_scrollbar: show_horizontal,
 570            show_track: show_horizontal_track,
 571            auto_hide: autohide(show_setting, cx),
 572            hide_task: None,
 573        };
 574
 575        cx.notify();
 576    }
 577
 578    pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
 579        fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
 580        where
 581            F: Fn(usize) -> std::cmp::Ordering,
 582        {
 583            while low < high {
 584                let mid = low + (high - low) / 2;
 585                match is_target(mid) {
 586                    std::cmp::Ordering::Equal => return Some(mid),
 587                    std::cmp::Ordering::Less => low = mid + 1,
 588                    std::cmp::Ordering::Greater => high = mid,
 589                }
 590            }
 591            None
 592        }
 593        if self.conflicted_count > 0 {
 594            let conflicted_start = 1;
 595            if let Some(ix) = binary_search(
 596                conflicted_start,
 597                conflicted_start + self.conflicted_count,
 598                |ix| {
 599                    self.entries[ix]
 600                        .status_entry()
 601                        .unwrap()
 602                        .repo_path
 603                        .cmp(&path)
 604                },
 605            ) {
 606                return Some(ix);
 607            }
 608        }
 609        if self.tracked_count > 0 {
 610            let tracked_start = if self.conflicted_count > 0 {
 611                1 + self.conflicted_count
 612            } else {
 613                0
 614            } + 1;
 615            if let Some(ix) =
 616                binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
 617                    self.entries[ix]
 618                        .status_entry()
 619                        .unwrap()
 620                        .repo_path
 621                        .cmp(&path)
 622                })
 623            {
 624                return Some(ix);
 625            }
 626        }
 627        if self.new_count > 0 {
 628            let untracked_start = if self.conflicted_count > 0 {
 629                1 + self.conflicted_count
 630            } else {
 631                0
 632            } + if self.tracked_count > 0 {
 633                1 + self.tracked_count
 634            } else {
 635                0
 636            } + 1;
 637            if let Some(ix) =
 638                binary_search(untracked_start, untracked_start + self.new_count, |ix| {
 639                    self.entries[ix]
 640                        .status_entry()
 641                        .unwrap()
 642                        .repo_path
 643                        .cmp(&path)
 644                })
 645            {
 646                return Some(ix);
 647            }
 648        }
 649        None
 650    }
 651
 652    pub fn select_entry_by_path(
 653        &mut self,
 654        path: ProjectPath,
 655        _: &mut Window,
 656        cx: &mut Context<Self>,
 657    ) {
 658        let Some(git_repo) = self.active_repository.as_ref() else {
 659            return;
 660        };
 661        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
 662            return;
 663        };
 664        let Some(ix) = self.entry_by_path(&repo_path) else {
 665            return;
 666        };
 667        self.selected_entry = Some(ix);
 668        cx.notify();
 669    }
 670
 671    fn start_remote_operation(&mut self) -> RemoteOperationGuard {
 672        let id = post_inc(&mut self.remote_operation_id);
 673        self.pending_remote_operations.borrow_mut().insert(id);
 674
 675        RemoteOperationGuard {
 676            id,
 677            pending_remote_operations: self.pending_remote_operations.clone(),
 678        }
 679    }
 680
 681    fn serialize(&mut self, cx: &mut Context<Self>) {
 682        let width = self.width;
 683        self.pending_serialization = cx.background_spawn(
 684            async move {
 685                KEY_VALUE_STORE
 686                    .write_kvp(
 687                        GIT_PANEL_KEY.into(),
 688                        serde_json::to_string(&SerializedGitPanel { width })?,
 689                    )
 690                    .await?;
 691                anyhow::Ok(())
 692            }
 693            .log_err(),
 694        );
 695    }
 696
 697    pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
 698        self.modal_open = open;
 699        cx.notify();
 700    }
 701
 702    fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
 703        let mut dispatch_context = KeyContext::new_with_defaults();
 704        dispatch_context.add("GitPanel");
 705
 706        if window
 707            .focused(cx)
 708            .map_or(false, |focused| self.focus_handle == focused)
 709        {
 710            dispatch_context.add("menu");
 711            dispatch_context.add("ChangesList");
 712        }
 713
 714        if self.commit_editor.read(cx).is_focused(window) {
 715            dispatch_context.add("CommitEditor");
 716        }
 717
 718        dispatch_context
 719    }
 720
 721    fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
 722        cx.emit(PanelEvent::Close);
 723    }
 724
 725    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 726        if !self.focus_handle.contains_focused(window, cx) {
 727            cx.emit(Event::Focus);
 728        }
 729    }
 730
 731    fn handle_modifiers_changed(
 732        &mut self,
 733        event: &ModifiersChangedEvent,
 734        _: &mut Window,
 735        cx: &mut Context<Self>,
 736    ) {
 737        self.current_modifiers = event.modifiers;
 738        cx.notify();
 739    }
 740
 741    fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
 742        if let Some(selected_entry) = self.selected_entry {
 743            self.scroll_handle
 744                .scroll_to_item(selected_entry, ScrollStrategy::Center);
 745        }
 746
 747        cx.notify();
 748    }
 749
 750    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
 751        if !self.entries.is_empty() {
 752            self.selected_entry = Some(1);
 753            self.scroll_to_selected_entry(cx);
 754        }
 755    }
 756
 757    fn select_previous(
 758        &mut self,
 759        _: &SelectPrevious,
 760        _window: &mut Window,
 761        cx: &mut Context<Self>,
 762    ) {
 763        let item_count = self.entries.len();
 764        if item_count == 0 {
 765            return;
 766        }
 767
 768        if let Some(selected_entry) = self.selected_entry {
 769            let new_selected_entry = if selected_entry > 0 {
 770                selected_entry - 1
 771            } else {
 772                selected_entry
 773            };
 774
 775            if matches!(
 776                self.entries.get(new_selected_entry),
 777                Some(GitListEntry::Header(..))
 778            ) {
 779                if new_selected_entry > 0 {
 780                    self.selected_entry = Some(new_selected_entry - 1)
 781                }
 782            } else {
 783                self.selected_entry = Some(new_selected_entry);
 784            }
 785
 786            self.scroll_to_selected_entry(cx);
 787        }
 788
 789        cx.notify();
 790    }
 791
 792    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
 793        let item_count = self.entries.len();
 794        if item_count == 0 {
 795            return;
 796        }
 797
 798        if let Some(selected_entry) = self.selected_entry {
 799            let new_selected_entry = if selected_entry < item_count - 1 {
 800                selected_entry + 1
 801            } else {
 802                selected_entry
 803            };
 804            if matches!(
 805                self.entries.get(new_selected_entry),
 806                Some(GitListEntry::Header(..))
 807            ) {
 808                self.selected_entry = Some(new_selected_entry + 1);
 809            } else {
 810                self.selected_entry = Some(new_selected_entry);
 811            }
 812
 813            self.scroll_to_selected_entry(cx);
 814        }
 815
 816        cx.notify();
 817    }
 818
 819    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 820        if self.entries.last().is_some() {
 821            self.selected_entry = Some(self.entries.len() - 1);
 822            self.scroll_to_selected_entry(cx);
 823        }
 824    }
 825
 826    fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
 827        self.commit_editor.update(cx, |editor, cx| {
 828            window.focus(&editor.focus_handle(cx));
 829        });
 830        cx.notify();
 831    }
 832
 833    fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
 834        let have_entries = self
 835            .active_repository
 836            .as_ref()
 837            .map_or(false, |active_repository| {
 838                active_repository.read(cx).entry_count() > 0
 839            });
 840        if have_entries && self.selected_entry.is_none() {
 841            self.selected_entry = Some(1);
 842            self.scroll_to_selected_entry(cx);
 843            cx.notify();
 844        }
 845    }
 846
 847    fn focus_changes_list(
 848        &mut self,
 849        _: &FocusChanges,
 850        window: &mut Window,
 851        cx: &mut Context<Self>,
 852    ) {
 853        self.select_first_entry_if_none(cx);
 854
 855        cx.focus_self(window);
 856        cx.notify();
 857    }
 858
 859    fn get_selected_entry(&self) -> Option<&GitListEntry> {
 860        self.selected_entry.and_then(|i| self.entries.get(i))
 861    }
 862
 863    fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 864        maybe!({
 865            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 866            let workspace = self.workspace.upgrade()?;
 867            let git_repo = self.active_repository.as_ref()?;
 868
 869            if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
 870                if let Some(project_path) = project_diff.read(cx).active_path(cx) {
 871                    if Some(&entry.repo_path)
 872                        == git_repo
 873                            .read(cx)
 874                            .project_path_to_repo_path(&project_path)
 875                            .as_ref()
 876                    {
 877                        project_diff.focus_handle(cx).focus(window);
 878                        project_diff.update(cx, |project_diff, cx| project_diff.autoscroll(cx));
 879                        return None;
 880                    }
 881                }
 882            };
 883
 884            if entry.worktree_path.starts_with("..") {
 885                self.workspace
 886                    .update(cx, |workspace, cx| {
 887                        workspace
 888                            .open_abs_path(
 889                                entry.abs_path.clone(),
 890                                OpenOptions {
 891                                    visible: Some(OpenVisible::All),
 892                                    focus: Some(false),
 893                                    ..Default::default()
 894                                },
 895                                window,
 896                                cx,
 897                            )
 898                            .detach_and_log_err(cx);
 899                    })
 900                    .ok();
 901            } else {
 902                self.workspace
 903                    .update(cx, |workspace, cx| {
 904                        ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
 905                    })
 906                    .ok();
 907                self.focus_handle.focus(window);
 908            }
 909
 910            Some(())
 911        });
 912    }
 913
 914    fn open_file(
 915        &mut self,
 916        _: &menu::SecondaryConfirm,
 917        window: &mut Window,
 918        cx: &mut Context<Self>,
 919    ) {
 920        maybe!({
 921            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 922            let active_repo = self.active_repository.as_ref()?;
 923            let path = active_repo
 924                .read(cx)
 925                .repo_path_to_project_path(&entry.repo_path)?;
 926            if entry.status.is_deleted() {
 927                return None;
 928            }
 929
 930            self.workspace
 931                .update(cx, |workspace, cx| {
 932                    workspace
 933                        .open_path_preview(path, None, false, false, true, window, cx)
 934                        .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
 935                            Some(format!("{e}"))
 936                        });
 937                })
 938                .ok()
 939        });
 940    }
 941
 942    fn revert_selected(
 943        &mut self,
 944        _: &git::RestoreFile,
 945        window: &mut Window,
 946        cx: &mut Context<Self>,
 947    ) {
 948        maybe!({
 949            let list_entry = self.entries.get(self.selected_entry?)?.clone();
 950            let entry = list_entry.status_entry()?;
 951            self.revert_entry(&entry, window, cx);
 952            Some(())
 953        });
 954    }
 955
 956    fn revert_entry(
 957        &mut self,
 958        entry: &GitStatusEntry,
 959        window: &mut Window,
 960        cx: &mut Context<Self>,
 961    ) {
 962        maybe!({
 963            let active_repo = self.active_repository.clone()?;
 964            let path = active_repo
 965                .read(cx)
 966                .repo_path_to_project_path(&entry.repo_path)?;
 967            let workspace = self.workspace.clone();
 968
 969            if entry.status.staging().has_staged() {
 970                self.change_file_stage(false, vec![entry.clone()], cx);
 971            }
 972            let filename = path.path.file_name()?.to_string_lossy();
 973
 974            if !entry.status.is_created() {
 975                self.perform_checkout(vec![entry.clone()], cx);
 976            } else {
 977                let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
 978                cx.spawn_in(window, |_, mut cx| async move {
 979                    match prompt.await? {
 980                        TrashCancel::Trash => {}
 981                        TrashCancel::Cancel => return Ok(()),
 982                    }
 983                    let task = workspace.update(&mut cx, |workspace, cx| {
 984                        workspace
 985                            .project()
 986                            .update(cx, |project, cx| project.delete_file(path, true, cx))
 987                    })?;
 988                    if let Some(task) = task {
 989                        task.await?;
 990                    }
 991                    Ok(())
 992                })
 993                .detach_and_prompt_err(
 994                    "Failed to trash file",
 995                    window,
 996                    cx,
 997                    |e, _, _| Some(format!("{e}")),
 998                );
 999            }
1000            Some(())
1001        });
1002    }
1003
1004    fn perform_checkout(&mut self, entries: Vec<GitStatusEntry>, cx: &mut Context<Self>) {
1005        let workspace = self.workspace.clone();
1006        let Some(active_repository) = self.active_repository.clone() else {
1007            return;
1008        };
1009
1010        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1011        self.pending.push(PendingOperation {
1012            op_id,
1013            target_status: TargetStatus::Reverted,
1014            entries: entries.clone(),
1015            finished: false,
1016        });
1017        self.update_visible_entries(cx);
1018        let task = cx.spawn(|_, mut cx| async move {
1019            let tasks: Vec<_> = workspace.update(&mut cx, |workspace, cx| {
1020                workspace.project().update(cx, |project, cx| {
1021                    entries
1022                        .iter()
1023                        .filter_map(|entry| {
1024                            let path = active_repository
1025                                .read(cx)
1026                                .repo_path_to_project_path(&entry.repo_path)?;
1027                            Some(project.open_buffer(path, cx))
1028                        })
1029                        .collect()
1030                })
1031            })?;
1032
1033            let buffers = futures::future::join_all(tasks).await;
1034
1035            active_repository
1036                .update(&mut cx, |repo, cx| {
1037                    repo.checkout_files(
1038                        "HEAD",
1039                        entries
1040                            .iter()
1041                            .map(|entries| entries.repo_path.clone())
1042                            .collect(),
1043                        cx,
1044                    )
1045                })?
1046                .await??;
1047
1048            let tasks: Vec<_> = cx.update(|cx| {
1049                buffers
1050                    .iter()
1051                    .filter_map(|buffer| {
1052                        buffer.as_ref().ok()?.update(cx, |buffer, cx| {
1053                            buffer.is_dirty().then(|| buffer.reload(cx))
1054                        })
1055                    })
1056                    .collect()
1057            })?;
1058
1059            futures::future::join_all(tasks).await;
1060
1061            Ok(())
1062        });
1063
1064        cx.spawn(|this, mut cx| async move {
1065            let result = task.await;
1066
1067            this.update(&mut cx, |this, cx| {
1068                for pending in this.pending.iter_mut() {
1069                    if pending.op_id == op_id {
1070                        pending.finished = true;
1071                        if result.is_err() {
1072                            pending.target_status = TargetStatus::Unchanged;
1073                            this.update_visible_entries(cx);
1074                        }
1075                        break;
1076                    }
1077                }
1078                result
1079                    .map_err(|e| {
1080                        this.show_error_toast("checkout", e, cx);
1081                    })
1082                    .ok();
1083            })
1084            .ok();
1085        })
1086        .detach();
1087    }
1088
1089    fn restore_tracked_files(
1090        &mut self,
1091        _: &RestoreTrackedFiles,
1092        window: &mut Window,
1093        cx: &mut Context<Self>,
1094    ) {
1095        let entries = self
1096            .entries
1097            .iter()
1098            .filter_map(|entry| entry.status_entry().cloned())
1099            .filter(|status_entry| !status_entry.status.is_created())
1100            .collect::<Vec<_>>();
1101
1102        match entries.len() {
1103            0 => return,
1104            1 => return self.revert_entry(&entries[0], window, cx),
1105            _ => {}
1106        }
1107        let mut details = entries
1108            .iter()
1109            .filter_map(|entry| entry.repo_path.0.file_name())
1110            .map(|filename| filename.to_string_lossy())
1111            .take(5)
1112            .join("\n");
1113        if entries.len() > 5 {
1114            details.push_str(&format!("\nand {} more…", entries.len() - 5))
1115        }
1116
1117        #[derive(strum::EnumIter, strum::VariantNames)]
1118        #[strum(serialize_all = "title_case")]
1119        enum RestoreCancel {
1120            RestoreTrackedFiles,
1121            Cancel,
1122        }
1123        let prompt = prompt(
1124            "Discard changes to these files?",
1125            Some(&details),
1126            window,
1127            cx,
1128        );
1129        cx.spawn(|this, mut cx| async move {
1130            match prompt.await {
1131                Ok(RestoreCancel::RestoreTrackedFiles) => {
1132                    this.update(&mut cx, |this, cx| {
1133                        this.perform_checkout(entries, cx);
1134                    })
1135                    .ok();
1136                }
1137                _ => {
1138                    return;
1139                }
1140            }
1141        })
1142        .detach();
1143    }
1144
1145    fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
1146        let workspace = self.workspace.clone();
1147        let Some(active_repo) = self.active_repository.clone() else {
1148            return;
1149        };
1150        let to_delete = self
1151            .entries
1152            .iter()
1153            .filter_map(|entry| entry.status_entry())
1154            .filter(|status_entry| status_entry.status.is_created())
1155            .cloned()
1156            .collect::<Vec<_>>();
1157
1158        match to_delete.len() {
1159            0 => return,
1160            1 => return self.revert_entry(&to_delete[0], window, cx),
1161            _ => {}
1162        };
1163
1164        let mut details = to_delete
1165            .iter()
1166            .map(|entry| {
1167                entry
1168                    .repo_path
1169                    .0
1170                    .file_name()
1171                    .map(|f| f.to_string_lossy())
1172                    .unwrap_or_default()
1173            })
1174            .take(5)
1175            .join("\n");
1176
1177        if to_delete.len() > 5 {
1178            details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
1179        }
1180
1181        let prompt = prompt("Trash these files?", Some(&details), window, cx);
1182        cx.spawn_in(window, |this, mut cx| async move {
1183            match prompt.await? {
1184                TrashCancel::Trash => {}
1185                TrashCancel::Cancel => return Ok(()),
1186            }
1187            let tasks = workspace.update(&mut cx, |workspace, cx| {
1188                to_delete
1189                    .iter()
1190                    .filter_map(|entry| {
1191                        workspace.project().update(cx, |project, cx| {
1192                            let project_path = active_repo
1193                                .read(cx)
1194                                .repo_path_to_project_path(&entry.repo_path)?;
1195                            project.delete_file(project_path, true, cx)
1196                        })
1197                    })
1198                    .collect::<Vec<_>>()
1199            })?;
1200            let to_unstage = to_delete
1201                .into_iter()
1202                .filter(|entry| !entry.status.staging().is_fully_unstaged())
1203                .collect();
1204            this.update(&mut cx, |this, cx| {
1205                this.change_file_stage(false, to_unstage, cx)
1206            })?;
1207            for task in tasks {
1208                task.await?;
1209            }
1210            Ok(())
1211        })
1212        .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1213            Some(format!("{e}"))
1214        });
1215    }
1216
1217    pub fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1218        let entries = self
1219            .entries
1220            .iter()
1221            .filter_map(|entry| entry.status_entry())
1222            .filter(|status_entry| status_entry.staging.has_unstaged())
1223            .cloned()
1224            .collect::<Vec<_>>();
1225        self.change_file_stage(true, entries, cx);
1226    }
1227
1228    pub fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1229        let entries = self
1230            .entries
1231            .iter()
1232            .filter_map(|entry| entry.status_entry())
1233            .filter(|status_entry| status_entry.staging.has_staged())
1234            .cloned()
1235            .collect::<Vec<_>>();
1236        self.change_file_stage(false, entries, cx);
1237    }
1238
1239    fn toggle_staged_for_entry(
1240        &mut self,
1241        entry: &GitListEntry,
1242        _window: &mut Window,
1243        cx: &mut Context<Self>,
1244    ) {
1245        let Some(active_repository) = self.active_repository.as_ref() else {
1246            return;
1247        };
1248        let (stage, repo_paths) = match entry {
1249            GitListEntry::GitStatusEntry(status_entry) => {
1250                if status_entry.status.staging().is_fully_staged() {
1251                    (false, vec![status_entry.clone()])
1252                } else {
1253                    (true, vec![status_entry.clone()])
1254                }
1255            }
1256            GitListEntry::Header(section) => {
1257                let goal_staged_state = !self.header_state(section.header).selected();
1258                let repository = active_repository.read(cx);
1259                let entries = self
1260                    .entries
1261                    .iter()
1262                    .filter_map(|entry| entry.status_entry())
1263                    .filter(|status_entry| {
1264                        section.contains(&status_entry, repository)
1265                            && status_entry.staging.as_bool() != Some(goal_staged_state)
1266                    })
1267                    .map(|status_entry| status_entry.clone())
1268                    .collect::<Vec<_>>();
1269
1270                (goal_staged_state, entries)
1271            }
1272        };
1273        self.change_file_stage(stage, repo_paths, cx);
1274    }
1275
1276    fn change_file_stage(
1277        &mut self,
1278        stage: bool,
1279        entries: Vec<GitStatusEntry>,
1280        cx: &mut Context<Self>,
1281    ) {
1282        let Some(active_repository) = self.active_repository.clone() else {
1283            return;
1284        };
1285        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1286        self.pending.push(PendingOperation {
1287            op_id,
1288            target_status: if stage {
1289                TargetStatus::Staged
1290            } else {
1291                TargetStatus::Unstaged
1292            },
1293            entries: entries.clone(),
1294            finished: false,
1295        });
1296        let repository = active_repository.read(cx);
1297        self.update_counts(repository);
1298        cx.notify();
1299
1300        cx.spawn({
1301            |this, mut cx| async move {
1302                let result = cx
1303                    .update(|cx| {
1304                        if stage {
1305                            active_repository.update(cx, |repo, cx| {
1306                                let repo_paths = entries
1307                                    .iter()
1308                                    .map(|entry| entry.repo_path.clone())
1309                                    .collect();
1310                                repo.stage_entries(repo_paths, cx)
1311                            })
1312                        } else {
1313                            active_repository.update(cx, |repo, cx| {
1314                                let repo_paths = entries
1315                                    .iter()
1316                                    .map(|entry| entry.repo_path.clone())
1317                                    .collect();
1318                                repo.unstage_entries(repo_paths, cx)
1319                            })
1320                        }
1321                    })?
1322                    .await;
1323
1324                this.update(&mut cx, |this, cx| {
1325                    for pending in this.pending.iter_mut() {
1326                        if pending.op_id == op_id {
1327                            pending.finished = true
1328                        }
1329                    }
1330                    result
1331                        .map_err(|e| {
1332                            this.show_error_toast(if stage { "add" } else { "reset" }, e, cx);
1333                        })
1334                        .ok();
1335                    cx.notify();
1336                })
1337            }
1338        })
1339        .detach();
1340    }
1341
1342    pub fn total_staged_count(&self) -> usize {
1343        self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1344    }
1345
1346    pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1347        self.commit_editor
1348            .read(cx)
1349            .buffer()
1350            .read(cx)
1351            .as_singleton()
1352            .unwrap()
1353            .clone()
1354    }
1355
1356    fn toggle_staged_for_selected(
1357        &mut self,
1358        _: &git::ToggleStaged,
1359        window: &mut Window,
1360        cx: &mut Context<Self>,
1361    ) {
1362        if let Some(selected_entry) = self.get_selected_entry().cloned() {
1363            self.toggle_staged_for_entry(&selected_entry, window, cx);
1364        }
1365    }
1366
1367    fn stage_selected(&mut self, _: &git::StageFile, _window: &mut Window, cx: &mut Context<Self>) {
1368        let Some(selected_entry) = self.get_selected_entry() else {
1369            return;
1370        };
1371        let Some(status_entry) = selected_entry.status_entry() else {
1372            return;
1373        };
1374        if status_entry.staging != StageStatus::Staged {
1375            self.change_file_stage(true, vec![status_entry.clone()], cx);
1376        }
1377    }
1378
1379    fn unstage_selected(
1380        &mut self,
1381        _: &git::UnstageFile,
1382        _window: &mut Window,
1383        cx: &mut Context<Self>,
1384    ) {
1385        let Some(selected_entry) = self.get_selected_entry() else {
1386            return;
1387        };
1388        let Some(status_entry) = selected_entry.status_entry() else {
1389            return;
1390        };
1391        if status_entry.staging != StageStatus::Unstaged {
1392            self.change_file_stage(false, vec![status_entry.clone()], cx);
1393        }
1394    }
1395
1396    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1397        if self
1398            .commit_editor
1399            .focus_handle(cx)
1400            .contains_focused(window, cx)
1401        {
1402            telemetry::event!("Git Committed", source = "Git Panel");
1403            self.commit_changes(window, cx)
1404        } else {
1405            cx.propagate();
1406        }
1407    }
1408
1409    fn custom_or_suggested_commit_message(&self, cx: &mut Context<Self>) -> Option<String> {
1410        let message = self.commit_editor.read(cx).text(cx);
1411
1412        if !message.trim().is_empty() {
1413            return Some(message.to_string());
1414        }
1415
1416        self.suggest_commit_message()
1417            .filter(|message| !message.trim().is_empty())
1418    }
1419
1420    pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1421        let Some(active_repository) = self.active_repository.clone() else {
1422            return;
1423        };
1424        let error_spawn = |message, window: &mut Window, cx: &mut App| {
1425            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1426            cx.spawn(|_| async move {
1427                prompt.await.ok();
1428            })
1429            .detach();
1430        };
1431
1432        if self.has_unstaged_conflicts() {
1433            error_spawn(
1434                "There are still conflicts. You must stage these before committing",
1435                window,
1436                cx,
1437            );
1438            return;
1439        }
1440
1441        let commit_message = self.custom_or_suggested_commit_message(cx);
1442
1443        let Some(mut message) = commit_message else {
1444            self.commit_editor.read(cx).focus_handle(cx).focus(window);
1445            return;
1446        };
1447
1448        if self.add_coauthors {
1449            self.fill_co_authors(&mut message, cx);
1450        }
1451
1452        let task = if self.has_staged_changes() {
1453            // Repository serializes all git operations, so we can just send a commit immediately
1454            let commit_task =
1455                active_repository.update(cx, |repo, cx| repo.commit(message.into(), None, cx));
1456            cx.background_spawn(async move { commit_task.await? })
1457        } else {
1458            let changed_files = self
1459                .entries
1460                .iter()
1461                .filter_map(|entry| entry.status_entry())
1462                .filter(|status_entry| !status_entry.status.is_created())
1463                .map(|status_entry| status_entry.repo_path.clone())
1464                .collect::<Vec<_>>();
1465
1466            if changed_files.is_empty() {
1467                error_spawn("No changes to commit", window, cx);
1468                return;
1469            }
1470
1471            let stage_task =
1472                active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1473            cx.spawn(|_, mut cx| async move {
1474                stage_task.await?;
1475                let commit_task = active_repository
1476                    .update(&mut cx, |repo, cx| repo.commit(message.into(), None, cx))?;
1477                commit_task.await?
1478            })
1479        };
1480        let task = cx.spawn_in(window, |this, mut cx| async move {
1481            let result = task.await;
1482            this.update_in(&mut cx, |this, window, cx| {
1483                this.pending_commit.take();
1484                match result {
1485                    Ok(()) => {
1486                        this.commit_editor
1487                            .update(cx, |editor, cx| editor.clear(window, cx));
1488                    }
1489                    Err(e) => this.show_error_toast("commit", e, cx),
1490                }
1491            })
1492            .ok();
1493        });
1494
1495        self.pending_commit = Some(task);
1496    }
1497
1498    fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1499        let Some(repo) = self.active_repository.clone() else {
1500            return;
1501        };
1502        telemetry::event!("Git Uncommitted");
1503
1504        let confirmation = self.check_for_pushed_commits(window, cx);
1505        let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1506
1507        let task = cx.spawn_in(window, |this, mut cx| async move {
1508            let result = maybe!(async {
1509                if let Ok(true) = confirmation.await {
1510                    let prior_head = prior_head.await?;
1511
1512                    repo.update(&mut cx, |repo, cx| {
1513                        repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1514                    })?
1515                    .await??;
1516
1517                    Ok(Some(prior_head))
1518                } else {
1519                    Ok(None)
1520                }
1521            })
1522            .await;
1523
1524            this.update_in(&mut cx, |this, window, cx| {
1525                this.pending_commit.take();
1526                match result {
1527                    Ok(None) => {}
1528                    Ok(Some(prior_commit)) => {
1529                        this.commit_editor.update(cx, |editor, cx| {
1530                            editor.set_text(prior_commit.message, window, cx)
1531                        });
1532                    }
1533                    Err(e) => this.show_error_toast("reset", e, cx),
1534                }
1535            })
1536            .ok();
1537        });
1538
1539        self.pending_commit = Some(task);
1540    }
1541
1542    fn check_for_pushed_commits(
1543        &mut self,
1544        window: &mut Window,
1545        cx: &mut Context<Self>,
1546    ) -> impl Future<Output = Result<bool, anyhow::Error>> {
1547        let repo = self.active_repository.clone();
1548        let mut cx = window.to_async(cx);
1549
1550        async move {
1551            let Some(repo) = repo else {
1552                return Err(anyhow::anyhow!("No active repository"));
1553            };
1554
1555            let pushed_to: Vec<SharedString> = repo
1556                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1557                .await??;
1558
1559            if pushed_to.is_empty() {
1560                Ok(true)
1561            } else {
1562                #[derive(strum::EnumIter, strum::VariantNames)]
1563                #[strum(serialize_all = "title_case")]
1564                enum CancelUncommit {
1565                    Uncommit,
1566                    Cancel,
1567                }
1568                let detail = format!(
1569                    "This commit was already pushed to {}.",
1570                    pushed_to.into_iter().join(", ")
1571                );
1572                let result = cx
1573                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1574                    .await?;
1575
1576                match result {
1577                    CancelUncommit::Cancel => Ok(false),
1578                    CancelUncommit::Uncommit => Ok(true),
1579                }
1580            }
1581        }
1582    }
1583
1584    /// Suggests a commit message based on the changed files and their statuses
1585    pub fn suggest_commit_message(&self) -> Option<String> {
1586        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1587            Some(staged_entry)
1588        } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1589            Some(single_tracked_entry)
1590        } else {
1591            None
1592        }?;
1593
1594        let action_text = if git_status_entry.status.is_deleted() {
1595            Some("Delete")
1596        } else if git_status_entry.status.is_created() {
1597            Some("Create")
1598        } else if git_status_entry.status.is_modified() {
1599            Some("Update")
1600        } else {
1601            None
1602        }?;
1603
1604        let file_name = git_status_entry
1605            .repo_path
1606            .file_name()
1607            .unwrap_or_default()
1608            .to_string_lossy();
1609
1610        Some(format!("{} {}", action_text, file_name))
1611    }
1612
1613    fn generate_commit_message_action(
1614        &mut self,
1615        _: &git::GenerateCommitMessage,
1616        _window: &mut Window,
1617        cx: &mut Context<Self>,
1618    ) {
1619        self.generate_commit_message(cx);
1620    }
1621
1622    /// Generates a commit message using an LLM.
1623    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1624        if !self.can_commit() {
1625            return;
1626        }
1627
1628        let model = match current_language_model(cx) {
1629            Some(value) => value,
1630            None => return,
1631        };
1632
1633        let Some(repo) = self.active_repository.as_ref() else {
1634            return;
1635        };
1636
1637        telemetry::event!("Git Commit Message Generated");
1638
1639        let diff = repo.update(cx, |repo, cx| {
1640            if self.has_staged_changes() {
1641                repo.diff(DiffType::HeadToIndex, cx)
1642            } else {
1643                repo.diff(DiffType::HeadToWorktree, cx)
1644            }
1645        });
1646
1647        self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1648            async move {
1649                let _defer = util::defer({
1650                    let mut cx = cx.clone();
1651                    let this = this.clone();
1652                    move || {
1653                        this.update(&mut cx, |this, _cx| {
1654                            this.generate_commit_message_task.take();
1655                        })
1656                        .ok();
1657                    }
1658                });
1659
1660                let mut diff_text = diff.await??;
1661
1662                const ONE_MB: usize = 1_000_000;
1663                if diff_text.len() > ONE_MB {
1664                    diff_text = diff_text.chars().take(ONE_MB).collect()
1665                }
1666
1667                let subject = this.update(&mut cx, |this, cx| {
1668                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1669                })?;
1670
1671                let text_empty = subject.trim().is_empty();
1672
1673                let content = if text_empty {
1674                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1675                } else {
1676                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1677                };
1678
1679                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1680
1681                let request = LanguageModelRequest {
1682                    messages: vec![LanguageModelRequestMessage {
1683                        role: Role::User,
1684                        content: vec![content.into()],
1685                        cache: false,
1686                    }],
1687                    tools: Vec::new(),
1688                    stop: Vec::new(),
1689                    temperature: None,
1690                };
1691
1692                let stream = model.stream_completion_text(request, &cx);
1693                let mut messages = stream.await?;
1694
1695                if !text_empty {
1696                    this.update(&mut cx, |this, cx| {
1697                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1698                            let insert_position = buffer.anchor_before(buffer.len());
1699                            buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1700                        });
1701                    })?;
1702                }
1703
1704                while let Some(message) = messages.stream.next().await {
1705                    let text = message?;
1706
1707                    this.update(&mut cx, |this, cx| {
1708                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1709                            let insert_position = buffer.anchor_before(buffer.len());
1710                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1711                        });
1712                    })?;
1713                }
1714
1715                anyhow::Ok(())
1716            }
1717            .log_err()
1718        }));
1719    }
1720
1721    fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1722        let suggested_commit_message = self.suggest_commit_message();
1723        let placeholder_text = suggested_commit_message
1724            .as_deref()
1725            .unwrap_or("Enter commit message");
1726
1727        self.commit_editor.update(cx, |editor, cx| {
1728            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1729        });
1730
1731        cx.notify();
1732    }
1733
1734    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1735        if !self.can_push_and_pull(cx) {
1736            return;
1737        }
1738
1739        let Some(repo) = self.active_repository.clone() else {
1740            return;
1741        };
1742        telemetry::event!("Git Fetched");
1743        let guard = self.start_remote_operation();
1744        let askpass = self.askpass_delegate("git fetch", window, cx);
1745        let this = cx.weak_entity();
1746        window
1747            .spawn(cx, |mut cx| async move {
1748                let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1749
1750                let remote_message = fetch.await?;
1751                drop(guard);
1752                this.update(&mut cx, |this, cx| {
1753                    let action = RemoteAction::Fetch;
1754                    match remote_message {
1755                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1756                        Err(e) => {
1757                            log::error!("Error while fetching {:?}", e);
1758                            this.show_error_toast(action.name(), e, cx)
1759                        }
1760                    }
1761
1762                    anyhow::Ok(())
1763                })
1764                .ok();
1765                anyhow::Ok(())
1766            })
1767            .detach_and_log_err(cx);
1768    }
1769
1770    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1771        let worktrees = self
1772            .project
1773            .read(cx)
1774            .visible_worktrees(cx)
1775            .collect::<Vec<_>>();
1776
1777        let worktree = if worktrees.len() == 1 {
1778            Task::ready(Some(worktrees.first().unwrap().clone()))
1779        } else if worktrees.len() == 0 {
1780            let result = window.prompt(
1781                PromptLevel::Warning,
1782                "Unable to initialize a git repository",
1783                Some("Open a directory first"),
1784                &["Ok"],
1785                cx,
1786            );
1787            cx.background_executor()
1788                .spawn(async move {
1789                    result.await.ok();
1790                })
1791                .detach();
1792            return;
1793        } else {
1794            let worktree_directories = worktrees
1795                .iter()
1796                .map(|worktree| worktree.read(cx).abs_path())
1797                .map(|worktree_abs_path| {
1798                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1799                        Path::new("~")
1800                            .join(path)
1801                            .to_string_lossy()
1802                            .to_string()
1803                            .into()
1804                    } else {
1805                        worktree_abs_path.to_string_lossy().to_string().into()
1806                    }
1807                })
1808                .collect_vec();
1809            let prompt = picker_prompt::prompt(
1810                "Where would you like to initialize this git repository?",
1811                worktree_directories,
1812                self.workspace.clone(),
1813                window,
1814                cx,
1815            );
1816
1817            cx.spawn(|_, _| async move { prompt.await.map(|ix| worktrees[ix].clone()) })
1818        };
1819
1820        cx.spawn_in(window, |this, mut cx| async move {
1821            let worktree = match worktree.await {
1822                Some(worktree) => worktree,
1823                None => {
1824                    return;
1825                }
1826            };
1827
1828            let Ok(result) = this.update(&mut cx, |this, cx| {
1829                let fallback_branch_name = GitPanelSettings::get_global(cx)
1830                    .fallback_branch_name
1831                    .clone();
1832                this.project.read(cx).git_init(
1833                    worktree.read(cx).abs_path(),
1834                    fallback_branch_name,
1835                    cx,
1836                )
1837            }) else {
1838                return;
1839            };
1840
1841            let result = result.await;
1842
1843            this.update_in(&mut cx, |this, _, cx| match result {
1844                Ok(()) => {}
1845                Err(e) => this.show_error_toast("init", e, cx),
1846            })
1847            .ok();
1848        })
1849        .detach();
1850    }
1851
1852    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1853        if !self.can_push_and_pull(cx) {
1854            return;
1855        }
1856        let Some(repo) = self.active_repository.clone() else {
1857            return;
1858        };
1859        let Some(branch) = repo.read(cx).current_branch() else {
1860            return;
1861        };
1862        telemetry::event!("Git Pulled");
1863        let branch = branch.clone();
1864        let remote = self.get_current_remote(window, cx);
1865        cx.spawn_in(window, move |this, mut cx| async move {
1866            let remote = match remote.await {
1867                Ok(Some(remote)) => remote,
1868                Ok(None) => {
1869                    return Ok(());
1870                }
1871                Err(e) => {
1872                    log::error!("Failed to get current remote: {}", e);
1873                    this.update(&mut cx, |this, cx| this.show_error_toast("pull", e, cx))
1874                        .ok();
1875                    return Ok(());
1876                }
1877            };
1878
1879            let askpass = this.update_in(&mut cx, |this, window, cx| {
1880                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1881            })?;
1882
1883            let guard = this
1884                .update(&mut cx, |this, _| this.start_remote_operation())
1885                .ok();
1886
1887            let pull = repo.update(&mut cx, |repo, cx| {
1888                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1889            })?;
1890
1891            let remote_message = pull.await?;
1892            drop(guard);
1893
1894            let action = RemoteAction::Pull(remote);
1895            this.update(&mut cx, |this, cx| match remote_message {
1896                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1897                Err(e) => {
1898                    log::error!("Error while pulling {:?}", e);
1899                    this.show_error_toast(action.name(), e, cx)
1900                }
1901            })
1902            .ok();
1903
1904            anyhow::Ok(())
1905        })
1906        .detach_and_log_err(cx);
1907    }
1908
1909    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1910        if !self.can_push_and_pull(cx) {
1911            return;
1912        }
1913        let Some(repo) = self.active_repository.clone() else {
1914            return;
1915        };
1916        let Some(branch) = repo.read(cx).current_branch() else {
1917            return;
1918        };
1919        telemetry::event!("Git Pushed");
1920        let branch = branch.clone();
1921
1922        let options = if force_push {
1923            Some(PushOptions::Force)
1924        } else {
1925            match branch.upstream {
1926                Some(Upstream {
1927                    tracking: UpstreamTracking::Gone,
1928                    ..
1929                })
1930                | None => Some(PushOptions::SetUpstream),
1931                _ => None,
1932            }
1933        };
1934        let remote = self.get_current_remote(window, cx);
1935
1936        cx.spawn_in(window, move |this, mut cx| async move {
1937            let remote = match remote.await {
1938                Ok(Some(remote)) => remote,
1939                Ok(None) => {
1940                    return Ok(());
1941                }
1942                Err(e) => {
1943                    log::error!("Failed to get current remote: {}", e);
1944                    this.update(&mut cx, |this, cx| this.show_error_toast("push", e, cx))
1945                        .ok();
1946                    return Ok(());
1947                }
1948            };
1949
1950            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1951                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1952            })?;
1953
1954            let guard = this
1955                .update(&mut cx, |this, _| this.start_remote_operation())
1956                .ok();
1957
1958            let push = repo.update(&mut cx, |repo, cx| {
1959                repo.push(
1960                    branch.name.clone(),
1961                    remote.name.clone(),
1962                    options,
1963                    askpass_delegate,
1964                    cx,
1965                )
1966            })?;
1967
1968            let remote_output = push.await?;
1969            drop(guard);
1970
1971            let action = RemoteAction::Push(branch.name, remote);
1972            this.update(&mut cx, |this, cx| match remote_output {
1973                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1974                Err(e) => {
1975                    log::error!("Error while pushing {:?}", e);
1976                    this.show_error_toast(action.name(), e, cx)
1977                }
1978            })?;
1979
1980            anyhow::Ok(())
1981        })
1982        .detach_and_log_err(cx);
1983    }
1984
1985    fn askpass_delegate(
1986        &self,
1987        operation: impl Into<SharedString>,
1988        window: &mut Window,
1989        cx: &mut Context<Self>,
1990    ) -> AskPassDelegate {
1991        let this = cx.weak_entity();
1992        let operation = operation.into();
1993        let window = window.window_handle();
1994        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1995            window
1996                .update(cx, |_, window, cx| {
1997                    this.update(cx, |this, cx| {
1998                        this.workspace.update(cx, |workspace, cx| {
1999                            workspace.toggle_modal(window, cx, |window, cx| {
2000                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2001                            });
2002                        })
2003                    })
2004                })
2005                .ok();
2006        })
2007    }
2008
2009    fn can_push_and_pull(&self, cx: &App) -> bool {
2010        crate::can_push_and_pull(&self.project, cx)
2011    }
2012
2013    fn get_current_remote(
2014        &mut self,
2015        window: &mut Window,
2016        cx: &mut Context<Self>,
2017    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
2018        let repo = self.active_repository.clone();
2019        let workspace = self.workspace.clone();
2020        let mut cx = window.to_async(cx);
2021
2022        async move {
2023            let Some(repo) = repo else {
2024                return Err(anyhow::anyhow!("No active repository"));
2025            };
2026
2027            let mut current_remotes: Vec<Remote> = repo
2028                .update(&mut cx, |repo, _| {
2029                    let Some(current_branch) = repo.current_branch() else {
2030                        return Err(anyhow::anyhow!("No active branch"));
2031                    };
2032
2033                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
2034                })??
2035                .await??;
2036
2037            if current_remotes.len() == 0 {
2038                return Err(anyhow::anyhow!("No active remote"));
2039            } else if current_remotes.len() == 1 {
2040                return Ok(Some(current_remotes.pop().unwrap()));
2041            } else {
2042                let current_remotes: Vec<_> = current_remotes
2043                    .into_iter()
2044                    .map(|remotes| remotes.name)
2045                    .collect();
2046                let selection = cx
2047                    .update(|window, cx| {
2048                        picker_prompt::prompt(
2049                            "Pick which remote to push to",
2050                            current_remotes.clone(),
2051                            workspace,
2052                            window,
2053                            cx,
2054                        )
2055                    })?
2056                    .await;
2057
2058                Ok(selection.map(|selection| Remote {
2059                    name: current_remotes[selection].clone(),
2060                }))
2061            }
2062        }
2063    }
2064
2065    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2066        let mut new_co_authors = Vec::new();
2067        let project = self.project.read(cx);
2068
2069        let Some(room) = self
2070            .workspace
2071            .upgrade()
2072            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2073        else {
2074            return Vec::default();
2075        };
2076
2077        let room = room.read(cx);
2078
2079        for (peer_id, collaborator) in project.collaborators() {
2080            if collaborator.is_host {
2081                continue;
2082            }
2083
2084            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2085                continue;
2086            };
2087            if participant.can_write() && participant.user.email.is_some() {
2088                let email = participant.user.email.clone().unwrap();
2089
2090                new_co_authors.push((
2091                    participant
2092                        .user
2093                        .name
2094                        .clone()
2095                        .unwrap_or_else(|| participant.user.github_login.clone()),
2096                    email,
2097                ))
2098            }
2099        }
2100        if !project.is_local() && !project.is_read_only(cx) {
2101            if let Some(user) = room.local_participant_user(cx) {
2102                if let Some(email) = user.email.clone() {
2103                    new_co_authors.push((
2104                        user.name
2105                            .clone()
2106                            .unwrap_or_else(|| user.github_login.clone()),
2107                        email.clone(),
2108                    ))
2109                }
2110            }
2111        }
2112        new_co_authors
2113    }
2114
2115    fn toggle_fill_co_authors(
2116        &mut self,
2117        _: &ToggleFillCoAuthors,
2118        _: &mut Window,
2119        cx: &mut Context<Self>,
2120    ) {
2121        self.add_coauthors = !self.add_coauthors;
2122        cx.notify();
2123    }
2124
2125    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2126        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2127
2128        let existing_text = message.to_ascii_lowercase();
2129        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2130        let mut ends_with_co_authors = false;
2131        let existing_co_authors = existing_text
2132            .lines()
2133            .filter_map(|line| {
2134                let line = line.trim();
2135                if line.starts_with(&lowercase_co_author_prefix) {
2136                    ends_with_co_authors = true;
2137                    Some(line)
2138                } else {
2139                    ends_with_co_authors = false;
2140                    None
2141                }
2142            })
2143            .collect::<HashSet<_>>();
2144
2145        let new_co_authors = self
2146            .potential_co_authors(cx)
2147            .into_iter()
2148            .filter(|(_, email)| {
2149                !existing_co_authors
2150                    .iter()
2151                    .any(|existing| existing.contains(email.as_str()))
2152            })
2153            .collect::<Vec<_>>();
2154
2155        if new_co_authors.is_empty() {
2156            return;
2157        }
2158
2159        if !ends_with_co_authors {
2160            message.push('\n');
2161        }
2162        for (name, email) in new_co_authors {
2163            message.push('\n');
2164            message.push_str(CO_AUTHOR_PREFIX);
2165            message.push_str(&name);
2166            message.push_str(" <");
2167            message.push_str(&email);
2168            message.push('>');
2169        }
2170        message.push('\n');
2171    }
2172
2173    fn schedule_update(
2174        &mut self,
2175        clear_pending: bool,
2176        window: &mut Window,
2177        cx: &mut Context<Self>,
2178    ) {
2179        let handle = cx.entity().downgrade();
2180        self.reopen_commit_buffer(window, cx);
2181        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
2182            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2183            if let Some(git_panel) = handle.upgrade() {
2184                git_panel
2185                    .update_in(&mut cx, |git_panel, window, cx| {
2186                        if clear_pending {
2187                            git_panel.clear_pending();
2188                        }
2189                        git_panel.update_visible_entries(cx);
2190                        git_panel.update_editor_placeholder(cx);
2191                        git_panel.update_scrollbar_properties(window, cx);
2192                    })
2193                    .ok();
2194            }
2195        });
2196    }
2197
2198    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2199        let Some(active_repo) = self.active_repository.as_ref() else {
2200            return;
2201        };
2202        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2203            let project = self.project.read(cx);
2204            active_repo.open_commit_buffer(
2205                Some(project.languages().clone()),
2206                project.buffer_store().clone(),
2207                cx,
2208            )
2209        });
2210
2211        cx.spawn_in(window, |git_panel, mut cx| async move {
2212            let buffer = load_buffer.await?;
2213            git_panel.update_in(&mut cx, |git_panel, window, cx| {
2214                if git_panel
2215                    .commit_editor
2216                    .read(cx)
2217                    .buffer()
2218                    .read(cx)
2219                    .as_singleton()
2220                    .as_ref()
2221                    != Some(&buffer)
2222                {
2223                    git_panel.commit_editor = cx.new(|cx| {
2224                        commit_message_editor(
2225                            buffer,
2226                            git_panel.suggest_commit_message().as_deref(),
2227                            git_panel.project.clone(),
2228                            true,
2229                            window,
2230                            cx,
2231                        )
2232                    });
2233                }
2234            })
2235        })
2236        .detach_and_log_err(cx);
2237    }
2238
2239    fn clear_pending(&mut self) {
2240        self.pending.retain(|v| !v.finished)
2241    }
2242
2243    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2244        self.entries.clear();
2245        self.single_staged_entry.take();
2246        self.conflicted_count = 0;
2247        self.conflicted_staged_count = 0;
2248        self.new_count = 0;
2249        self.tracked_count = 0;
2250        self.new_staged_count = 0;
2251        self.tracked_staged_count = 0;
2252        self.entry_count = 0;
2253
2254        let mut changed_entries = Vec::new();
2255        let mut new_entries = Vec::new();
2256        let mut conflict_entries = Vec::new();
2257        let mut last_staged = None;
2258        let mut staged_count = 0;
2259        let mut max_width_item: Option<(RepoPath, usize)> = None;
2260
2261        let Some(repo) = self.active_repository.as_ref() else {
2262            // Just clear entries if no repository is active.
2263            cx.notify();
2264            return;
2265        };
2266
2267        let repo = repo.read(cx);
2268
2269        for entry in repo.status() {
2270            let is_conflict = repo.has_conflict(&entry.repo_path);
2271            let is_new = entry.status.is_created();
2272            let staging = entry.status.staging();
2273
2274            if self.pending.iter().any(|pending| {
2275                pending.target_status == TargetStatus::Reverted
2276                    && !pending.finished
2277                    && pending
2278                        .entries
2279                        .iter()
2280                        .any(|pending| pending.repo_path == entry.repo_path)
2281            }) {
2282                continue;
2283            }
2284
2285            // dot_git_abs path always has at least one component, namely .git.
2286            let abs_path = repo
2287                .dot_git_abs_path
2288                .parent()
2289                .unwrap()
2290                .join(&entry.repo_path);
2291            let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2292            let entry = GitStatusEntry {
2293                repo_path: entry.repo_path.clone(),
2294                worktree_path,
2295                abs_path,
2296                status: entry.status,
2297                staging,
2298            };
2299
2300            if staging.has_staged() {
2301                staged_count += 1;
2302                last_staged = Some(entry.clone());
2303            }
2304
2305            let width_estimate = Self::item_width_estimate(
2306                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2307                entry.display_name().len(),
2308            );
2309
2310            match max_width_item.as_mut() {
2311                Some((repo_path, estimate)) => {
2312                    if width_estimate > *estimate {
2313                        *repo_path = entry.repo_path.clone();
2314                        *estimate = width_estimate;
2315                    }
2316                }
2317                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2318            }
2319
2320            if is_conflict {
2321                conflict_entries.push(entry);
2322            } else if is_new {
2323                new_entries.push(entry);
2324            } else {
2325                changed_entries.push(entry);
2326            }
2327        }
2328
2329        let mut pending_staged_count = 0;
2330        let mut last_pending_staged = None;
2331        let mut pending_status_for_last_staged = None;
2332        for pending in self.pending.iter() {
2333            if pending.target_status == TargetStatus::Staged {
2334                pending_staged_count += pending.entries.len();
2335                last_pending_staged = pending.entries.iter().next().cloned();
2336            }
2337            if let Some(last_staged) = &last_staged {
2338                if pending
2339                    .entries
2340                    .iter()
2341                    .any(|entry| entry.repo_path == last_staged.repo_path)
2342                {
2343                    pending_status_for_last_staged = Some(pending.target_status);
2344                }
2345            }
2346        }
2347
2348        if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2349            match pending_status_for_last_staged {
2350                Some(TargetStatus::Staged) | None => {
2351                    self.single_staged_entry = last_staged;
2352                }
2353                _ => {}
2354            }
2355        } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2356            self.single_staged_entry = last_pending_staged;
2357        }
2358
2359        if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2360            self.single_tracked_entry = changed_entries.first().cloned();
2361        }
2362
2363        if conflict_entries.len() > 0 {
2364            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2365                header: Section::Conflict,
2366            }));
2367            self.entries.extend(
2368                conflict_entries
2369                    .into_iter()
2370                    .map(GitListEntry::GitStatusEntry),
2371            );
2372        }
2373
2374        if changed_entries.len() > 0 {
2375            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2376                header: Section::Tracked,
2377            }));
2378            self.entries.extend(
2379                changed_entries
2380                    .into_iter()
2381                    .map(GitListEntry::GitStatusEntry),
2382            );
2383        }
2384        if new_entries.len() > 0 {
2385            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2386                header: Section::New,
2387            }));
2388            self.entries
2389                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2390        }
2391
2392        if let Some((repo_path, _)) = max_width_item {
2393            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2394                GitListEntry::GitStatusEntry(git_status_entry) => {
2395                    git_status_entry.repo_path == repo_path
2396                }
2397                GitListEntry::Header(_) => false,
2398            });
2399        }
2400
2401        self.update_counts(repo);
2402
2403        self.select_first_entry_if_none(cx);
2404
2405        cx.notify();
2406    }
2407
2408    fn header_state(&self, header_type: Section) -> ToggleState {
2409        let (staged_count, count) = match header_type {
2410            Section::New => (self.new_staged_count, self.new_count),
2411            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2412            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2413        };
2414        if staged_count == 0 {
2415            ToggleState::Unselected
2416        } else if count == staged_count {
2417            ToggleState::Selected
2418        } else {
2419            ToggleState::Indeterminate
2420        }
2421    }
2422
2423    fn update_counts(&mut self, repo: &Repository) {
2424        self.conflicted_count = 0;
2425        self.conflicted_staged_count = 0;
2426        self.new_count = 0;
2427        self.tracked_count = 0;
2428        self.new_staged_count = 0;
2429        self.tracked_staged_count = 0;
2430        self.entry_count = 0;
2431        for entry in &self.entries {
2432            let Some(status_entry) = entry.status_entry() else {
2433                continue;
2434            };
2435            self.entry_count += 1;
2436            if repo.has_conflict(&status_entry.repo_path) {
2437                self.conflicted_count += 1;
2438                if self.entry_staging(status_entry).has_staged() {
2439                    self.conflicted_staged_count += 1;
2440                }
2441            } else if status_entry.status.is_created() {
2442                self.new_count += 1;
2443                if self.entry_staging(status_entry).has_staged() {
2444                    self.new_staged_count += 1;
2445                }
2446            } else {
2447                self.tracked_count += 1;
2448                if self.entry_staging(status_entry).has_staged() {
2449                    self.tracked_staged_count += 1;
2450                }
2451            }
2452        }
2453    }
2454
2455    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2456        for pending in self.pending.iter().rev() {
2457            if pending
2458                .entries
2459                .iter()
2460                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2461            {
2462                match pending.target_status {
2463                    TargetStatus::Staged => return StageStatus::Staged,
2464                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2465                    TargetStatus::Reverted => continue,
2466                    TargetStatus::Unchanged => continue,
2467                }
2468            }
2469        }
2470        entry.staging
2471    }
2472
2473    pub(crate) fn has_staged_changes(&self) -> bool {
2474        self.tracked_staged_count > 0
2475            || self.new_staged_count > 0
2476            || self.conflicted_staged_count > 0
2477    }
2478
2479    pub(crate) fn has_unstaged_changes(&self) -> bool {
2480        self.tracked_count > self.tracked_staged_count
2481            || self.new_count > self.new_staged_count
2482            || self.conflicted_count > self.conflicted_staged_count
2483    }
2484
2485    fn has_conflicts(&self) -> bool {
2486        self.conflicted_count > 0
2487    }
2488
2489    fn has_tracked_changes(&self) -> bool {
2490        self.tracked_count > 0
2491    }
2492
2493    pub fn has_unstaged_conflicts(&self) -> bool {
2494        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2495    }
2496
2497    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2498        let action = action.into();
2499        let Some(workspace) = self.workspace.upgrade() else {
2500            return;
2501        };
2502
2503        let message = e.to_string().trim().to_string();
2504        if message
2505            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2506            .next()
2507            .is_some()
2508        {
2509            return; // Hide the cancelled by user message
2510        } else {
2511            let project = self.project.clone();
2512            workspace.update(cx, |workspace, cx| {
2513                let workspace_weak = cx.weak_entity();
2514                let toast =
2515                    StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2516                        this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2517                            .action("View Log", move |window, cx| {
2518                                let message = message.clone();
2519                                let project = project.clone();
2520                                let action = action.clone();
2521                                workspace_weak
2522                                    .update(cx, move |workspace, cx| {
2523                                        Self::open_output(
2524                                            project, action, workspace, &message, window, cx,
2525                                        )
2526                                    })
2527                                    .ok();
2528                            })
2529                    });
2530                workspace.toggle_status_toast(toast, cx)
2531            });
2532        }
2533    }
2534
2535    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2536        let Some(workspace) = self.workspace.upgrade() else {
2537            return;
2538        };
2539
2540        workspace.update(cx, |workspace, cx| {
2541            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2542            let workspace_weak = cx.weak_entity();
2543            let operation = action.name();
2544
2545            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2546                use remote_output::SuccessStyle::*;
2547                let project = self.project.clone();
2548                match style {
2549                    Toast { .. } => this,
2550                    ToastWithLog { output } => this
2551                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2552                        .action("View Log", move |window, cx| {
2553                            let output = output.clone();
2554                            let project = project.clone();
2555                            let output =
2556                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2557                            workspace_weak
2558                                .update(cx, move |workspace, cx| {
2559                                    Self::open_output(
2560                                        project, operation, workspace, &output, window, cx,
2561                                    )
2562                                })
2563                                .ok();
2564                        }),
2565                    PushPrLink { link } => this
2566                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2567                        .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2568                }
2569            });
2570            workspace.toggle_status_toast(status_toast, cx)
2571        });
2572    }
2573
2574    fn open_output(
2575        project: Entity<Project>,
2576        operation: impl Into<SharedString>,
2577        workspace: &mut Workspace,
2578        output: &str,
2579        window: &mut Window,
2580        cx: &mut Context<Workspace>,
2581    ) {
2582        let operation = operation.into();
2583        let buffer = cx.new(|cx| Buffer::local(output, cx));
2584        let editor = cx.new(|cx| {
2585            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2586            editor.buffer().update(cx, |buffer, cx| {
2587                buffer.set_title(format!("Output from git {operation}"), cx);
2588            });
2589            editor.set_read_only(true);
2590            editor
2591        });
2592
2593        workspace.add_item_to_center(Box::new(editor), window, cx);
2594    }
2595
2596    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2597        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2598            Icon::new(IconName::ArrowCircle)
2599                .size(IconSize::XSmall)
2600                .color(Color::Info)
2601                .with_animation(
2602                    "arrow-circle",
2603                    Animation::new(Duration::from_secs(2)).repeat(),
2604                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2605                )
2606                .into_any_element()
2607        })
2608    }
2609
2610    pub fn can_commit(&self) -> bool {
2611        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2612    }
2613
2614    pub fn can_stage_all(&self) -> bool {
2615        self.has_unstaged_changes()
2616    }
2617
2618    pub fn can_unstage_all(&self) -> bool {
2619        self.has_staged_changes()
2620    }
2621
2622    // eventually we'll need to take depth into account here
2623    // if we add a tree view
2624    fn item_width_estimate(path: usize, file_name: usize) -> usize {
2625        path + file_name
2626    }
2627
2628    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2629        let focus_handle = self.focus_handle.clone();
2630        PopoverMenu::new(id.into())
2631            .trigger(
2632                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2633                    .icon_size(IconSize::Small)
2634                    .icon_color(Color::Muted),
2635            )
2636            .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
2637            .anchor(Corner::TopRight)
2638    }
2639
2640    pub(crate) fn render_generate_commit_message_button(
2641        &self,
2642        cx: &Context<Self>,
2643    ) -> Option<AnyElement> {
2644        current_language_model(cx).is_some().then(|| {
2645            if self.generate_commit_message_task.is_some() {
2646                return h_flex()
2647                    .gap_1()
2648                    .child(
2649                        Icon::new(IconName::ArrowCircle)
2650                            .size(IconSize::XSmall)
2651                            .color(Color::Info)
2652                            .with_animation(
2653                                "arrow-circle",
2654                                Animation::new(Duration::from_secs(2)).repeat(),
2655                                |icon, delta| {
2656                                    icon.transform(Transformation::rotate(percentage(delta)))
2657                                },
2658                            ),
2659                    )
2660                    .child(
2661                        Label::new("Generating Commit...")
2662                            .size(LabelSize::Small)
2663                            .color(Color::Muted),
2664                    )
2665                    .into_any_element();
2666            }
2667
2668            let can_commit = self.can_commit();
2669            let editor_focus_handle = self.commit_editor.focus_handle(cx);
2670            IconButton::new("generate-commit-message", IconName::AiEdit)
2671                .shape(ui::IconButtonShape::Square)
2672                .icon_color(Color::Muted)
2673                .tooltip(move |window, cx| {
2674                    if can_commit {
2675                        Tooltip::for_action_in(
2676                            "Generate Commit Message",
2677                            &git::GenerateCommitMessage,
2678                            &editor_focus_handle,
2679                            window,
2680                            cx,
2681                        )
2682                    } else {
2683                        Tooltip::simple("No changes to commit", cx)
2684                    }
2685                })
2686                .disabled(!can_commit)
2687                .on_click(cx.listener(move |this, _event, _window, cx| {
2688                    this.generate_commit_message(cx);
2689                }))
2690                .into_any_element()
2691        })
2692    }
2693
2694    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2695        let potential_co_authors = self.potential_co_authors(cx);
2696        if potential_co_authors.is_empty() {
2697            None
2698        } else {
2699            Some(
2700                IconButton::new("co-authors", IconName::Person)
2701                    .shape(ui::IconButtonShape::Square)
2702                    .icon_color(Color::Disabled)
2703                    .selected_icon_color(Color::Selected)
2704                    .toggle_state(self.add_coauthors)
2705                    .tooltip(move |_, cx| {
2706                        let title = format!(
2707                            "Add co-authored-by:{}{}",
2708                            if potential_co_authors.len() == 1 {
2709                                ""
2710                            } else {
2711                                "\n"
2712                            },
2713                            potential_co_authors
2714                                .iter()
2715                                .map(|(name, email)| format!(" {} <{}>", name, email))
2716                                .join("\n")
2717                        );
2718                        Tooltip::simple(title, cx)
2719                    })
2720                    .on_click(cx.listener(|this, _, _, cx| {
2721                        this.add_coauthors = !this.add_coauthors;
2722                        cx.notify();
2723                    }))
2724                    .into_any_element(),
2725            )
2726        }
2727    }
2728
2729    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2730        if self.has_unstaged_conflicts() {
2731            (false, "You must resolve conflicts before committing")
2732        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2733            (false, "No changes to commit")
2734        } else if self.pending_commit.is_some() {
2735            (false, "Commit in progress")
2736        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2737            (false, "No commit message")
2738        } else if !self.has_write_access(cx) {
2739            (false, "You do not have write access to this project")
2740        } else {
2741            (true, self.commit_button_title())
2742        }
2743    }
2744
2745    pub fn commit_button_title(&self) -> &'static str {
2746        if self.has_staged_changes() {
2747            "Commit"
2748        } else {
2749            "Commit Tracked"
2750        }
2751    }
2752
2753    fn expand_commit_editor(
2754        &mut self,
2755        _: &git::ExpandCommitEditor,
2756        window: &mut Window,
2757        cx: &mut Context<Self>,
2758    ) {
2759        let workspace = self.workspace.clone();
2760        window.defer(cx, move |window, cx| {
2761            workspace
2762                .update(cx, |workspace, cx| {
2763                    CommitModal::toggle(workspace, window, cx)
2764                })
2765                .ok();
2766        })
2767    }
2768
2769    fn render_panel_header(
2770        &self,
2771        window: &mut Window,
2772        cx: &mut Context<Self>,
2773    ) -> Option<impl IntoElement> {
2774        self.active_repository.as_ref()?;
2775
2776        let text;
2777        let action;
2778        let tooltip;
2779        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2780            text = "Unstage All";
2781            action = git::UnstageAll.boxed_clone();
2782            tooltip = "git reset";
2783        } else {
2784            text = "Stage All";
2785            action = git::StageAll.boxed_clone();
2786            tooltip = "git add --all ."
2787        }
2788
2789        let change_string = match self.entry_count {
2790            0 => "No Changes".to_string(),
2791            1 => "1 Change".to_string(),
2792            _ => format!("{} Changes", self.entry_count),
2793        };
2794
2795        Some(
2796            self.panel_header_container(window, cx)
2797                .px_2()
2798                .child(
2799                    panel_button(change_string)
2800                        .color(Color::Muted)
2801                        .tooltip(Tooltip::for_action_title_in(
2802                            "Open diff",
2803                            &Diff,
2804                            &self.focus_handle,
2805                        ))
2806                        .on_click(|_, _, cx| {
2807                            cx.defer(|cx| {
2808                                cx.dispatch_action(&Diff);
2809                            })
2810                        }),
2811                )
2812                .child(div().flex_grow()) // spacer
2813                .child(self.render_overflow_menu("overflow_menu"))
2814                .child(div().w_2()) // another spacer
2815                .child(
2816                    panel_filled_button(text)
2817                        .tooltip(Tooltip::for_action_title_in(
2818                            tooltip,
2819                            action.as_ref(),
2820                            &self.focus_handle,
2821                        ))
2822                        .disabled(self.entry_count == 0)
2823                        .on_click(move |_, _, cx| {
2824                            let action = action.boxed_clone();
2825                            cx.defer(move |cx| {
2826                                cx.dispatch_action(action.as_ref());
2827                            })
2828                        }),
2829                ),
2830        )
2831    }
2832
2833    pub fn render_footer(
2834        &self,
2835        window: &mut Window,
2836        cx: &mut Context<Self>,
2837    ) -> Option<impl IntoElement> {
2838        let active_repository = self.active_repository.clone()?;
2839        let (can_commit, tooltip) = self.configure_commit_button(cx);
2840        let project = self.project.clone().read(cx);
2841        let panel_editor_style = panel_editor_style(true, window, cx);
2842
2843        let enable_coauthors = self.render_co_authors(cx);
2844        let title = self.commit_button_title();
2845
2846        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2847        let commit_tooltip_focus_handle = editor_focus_handle.clone();
2848        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2849
2850        let branch = active_repository.read(cx).current_branch().cloned();
2851
2852        let footer_size = px(32.);
2853        let gap = px(9.0);
2854        let max_height = panel_editor_style
2855            .text
2856            .line_height_in_pixels(window.rem_size())
2857            * MAX_PANEL_EDITOR_LINES
2858            + gap;
2859
2860        let git_panel = cx.entity().clone();
2861        let display_name = SharedString::from(Arc::from(
2862            active_repository
2863                .read(cx)
2864                .display_name(project, cx)
2865                .trim_end_matches("/"),
2866        ));
2867        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2868            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
2869        });
2870
2871        let footer = v_flex()
2872            .child(PanelRepoFooter::new(
2873                "footer-button",
2874                display_name,
2875                branch,
2876                Some(git_panel),
2877            ))
2878            .child(
2879                panel_editor_container(window, cx)
2880                    .id("commit-editor-container")
2881                    .relative()
2882                    .w_full()
2883                    .h(max_height + footer_size)
2884                    .border_t_1()
2885                    .border_color(cx.theme().colors().border_variant)
2886                    .cursor_text()
2887                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2888                        window.focus(&this.commit_editor.focus_handle(cx));
2889                    }))
2890                    .child(
2891                        h_flex()
2892                            .id("commit-footer")
2893                            .border_t_1()
2894                            .when(editor_is_long, |el| {
2895                                el.border_color(cx.theme().colors().border_variant)
2896                            })
2897                            .absolute()
2898                            .bottom_0()
2899                            .left_0()
2900                            .w_full()
2901                            .px_2()
2902                            .h(footer_size)
2903                            .flex_none()
2904                            .justify_between()
2905                            .child(
2906                                self.render_generate_commit_message_button(cx)
2907                                    .unwrap_or_else(|| div().into_any_element()),
2908                            )
2909                            .child(
2910                                h_flex().gap_0p5().children(enable_coauthors).child(
2911                                    panel_filled_button(title)
2912                                        .tooltip(move |window, cx| {
2913                                            if can_commit {
2914                                                Tooltip::for_action_in(
2915                                                    tooltip,
2916                                                    &Commit,
2917                                                    &commit_tooltip_focus_handle,
2918                                                    window,
2919                                                    cx,
2920                                                )
2921                                            } else {
2922                                                Tooltip::simple(tooltip, cx)
2923                                            }
2924                                        })
2925                                        .disabled(!can_commit || self.modal_open)
2926                                        .on_click({
2927                                            cx.listener(move |this, _: &ClickEvent, window, cx| {
2928                                                this.commit_changes(window, cx)
2929                                            })
2930                                        }),
2931                                ),
2932                            ),
2933                    )
2934                    .child(
2935                        div()
2936                            .pr_2p5()
2937                            .on_action(|&editor::actions::MoveUp, _, cx| {
2938                                cx.stop_propagation();
2939                            })
2940                            .on_action(|&editor::actions::MoveDown, _, cx| {
2941                                cx.stop_propagation();
2942                            })
2943                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2944                    )
2945                    .child(
2946                        h_flex()
2947                            .absolute()
2948                            .top_2()
2949                            .right_2()
2950                            .opacity(0.5)
2951                            .hover(|this| this.opacity(1.0))
2952                            .child(
2953                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2954                                    .icon_size(IconSize::Small)
2955                                    .size(ui::ButtonSize::Default)
2956                                    .tooltip(move |window, cx| {
2957                                        Tooltip::for_action_in(
2958                                            "Open Commit Modal",
2959                                            &git::ExpandCommitEditor,
2960                                            &expand_tooltip_focus_handle,
2961                                            window,
2962                                            cx,
2963                                        )
2964                                    })
2965                                    .on_click(cx.listener({
2966                                        move |_, _, window, cx| {
2967                                            window.dispatch_action(
2968                                                git::ExpandCommitEditor.boxed_clone(),
2969                                                cx,
2970                                            )
2971                                        }
2972                                    })),
2973                            ),
2974                    ),
2975            );
2976
2977        Some(footer)
2978    }
2979
2980    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2981        let active_repository = self.active_repository.as_ref()?;
2982        let branch = active_repository.read(cx).current_branch()?;
2983        let commit = branch.most_recent_commit.as_ref()?.clone();
2984
2985        let this = cx.entity();
2986        Some(
2987            h_flex()
2988                .items_center()
2989                .py_2()
2990                .px(px(8.))
2991                .border_color(cx.theme().colors().border)
2992                .gap_1p5()
2993                .child(
2994                    div()
2995                        .flex_grow()
2996                        .overflow_hidden()
2997                        .items_center()
2998                        .max_w(relative(0.85))
2999                        .h_full()
3000                        .child(
3001                            Label::new(commit.subject.clone())
3002                                .size(LabelSize::Small)
3003                                .truncate(),
3004                        )
3005                        .id("commit-msg-hover")
3006                        .hoverable_tooltip(move |window, cx| {
3007                            GitPanelMessageTooltip::new(
3008                                this.clone(),
3009                                commit.sha.clone(),
3010                                window,
3011                                cx,
3012                            )
3013                            .into()
3014                        }),
3015                )
3016                .child(div().flex_1())
3017                .when(commit.has_parent, |this| {
3018                    let has_unstaged = self.has_unstaged_changes();
3019                    this.child(
3020                        panel_icon_button("undo", IconName::Undo)
3021                            .icon_size(IconSize::Small)
3022                            .icon_color(Color::Muted)
3023                            .tooltip(move |window, cx| {
3024                                Tooltip::with_meta(
3025                                    "Uncommit",
3026                                    Some(&git::Uncommit),
3027                                    if has_unstaged {
3028                                        "git reset HEAD^ --soft"
3029                                    } else {
3030                                        "git reset HEAD^"
3031                                    },
3032                                    window,
3033                                    cx,
3034                                )
3035                            })
3036                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3037                    )
3038                }),
3039        )
3040    }
3041
3042    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3043        h_flex()
3044            .h_full()
3045            .flex_grow()
3046            .justify_center()
3047            .items_center()
3048            .child(
3049                v_flex()
3050                    .gap_2()
3051                    .child(h_flex().w_full().justify_around().child(
3052                        if self.active_repository.is_some() {
3053                            "No changes to commit"
3054                        } else {
3055                            "No Git repositories"
3056                        },
3057                    ))
3058                    .children({
3059                        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3060                        (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3061                            h_flex().w_full().justify_around().child(
3062                                panel_filled_button("Initialize Repository")
3063                                    .tooltip(Tooltip::for_action_title_in(
3064                                        "git init",
3065                                        &git::Init,
3066                                        &self.focus_handle,
3067                                    ))
3068                                    .on_click(move |_, _, cx| {
3069                                        cx.defer(move |cx| {
3070                                            cx.dispatch_action(&git::Init);
3071                                        })
3072                                    }),
3073                            )
3074                        })
3075                    })
3076                    .text_ui_sm(cx)
3077                    .mx_auto()
3078                    .text_color(Color::Placeholder.color(cx)),
3079            )
3080    }
3081
3082    fn render_vertical_scrollbar(
3083        &self,
3084        show_horizontal_scrollbar_container: bool,
3085        cx: &mut Context<Self>,
3086    ) -> impl IntoElement {
3087        div()
3088            .id("git-panel-vertical-scroll")
3089            .occlude()
3090            .flex_none()
3091            .h_full()
3092            .cursor_default()
3093            .absolute()
3094            .right_0()
3095            .top_0()
3096            .bottom_0()
3097            .w(px(12.))
3098            .when(show_horizontal_scrollbar_container, |this| {
3099                this.pb_neg_3p5()
3100            })
3101            .on_mouse_move(cx.listener(|_, _, _, cx| {
3102                cx.notify();
3103                cx.stop_propagation()
3104            }))
3105            .on_hover(|_, _, cx| {
3106                cx.stop_propagation();
3107            })
3108            .on_any_mouse_down(|_, _, cx| {
3109                cx.stop_propagation();
3110            })
3111            .on_mouse_up(
3112                MouseButton::Left,
3113                cx.listener(|this, _, window, cx| {
3114                    if !this.vertical_scrollbar.state.is_dragging()
3115                        && !this.focus_handle.contains_focused(window, cx)
3116                    {
3117                        this.vertical_scrollbar.hide(window, cx);
3118                        cx.notify();
3119                    }
3120
3121                    cx.stop_propagation();
3122                }),
3123            )
3124            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3125                cx.notify();
3126            }))
3127            .children(Scrollbar::vertical(
3128                // percentage as f32..end_offset as f32,
3129                self.vertical_scrollbar.state.clone(),
3130            ))
3131    }
3132
3133    /// Renders the horizontal scrollbar.
3134    ///
3135    /// The right offset is used to determine how far to the right the
3136    /// scrollbar should extend to, useful for ensuring it doesn't collide
3137    /// with the vertical scrollbar when visible.
3138    fn render_horizontal_scrollbar(
3139        &self,
3140        right_offset: Pixels,
3141        cx: &mut Context<Self>,
3142    ) -> impl IntoElement {
3143        div()
3144            .id("git-panel-horizontal-scroll")
3145            .occlude()
3146            .flex_none()
3147            .w_full()
3148            .cursor_default()
3149            .absolute()
3150            .bottom_neg_px()
3151            .left_0()
3152            .right_0()
3153            .pr(right_offset)
3154            .on_mouse_move(cx.listener(|_, _, _, cx| {
3155                cx.notify();
3156                cx.stop_propagation()
3157            }))
3158            .on_hover(|_, _, cx| {
3159                cx.stop_propagation();
3160            })
3161            .on_any_mouse_down(|_, _, cx| {
3162                cx.stop_propagation();
3163            })
3164            .on_mouse_up(
3165                MouseButton::Left,
3166                cx.listener(|this, _, window, cx| {
3167                    if !this.horizontal_scrollbar.state.is_dragging()
3168                        && !this.focus_handle.contains_focused(window, cx)
3169                    {
3170                        this.horizontal_scrollbar.hide(window, cx);
3171                        cx.notify();
3172                    }
3173
3174                    cx.stop_propagation();
3175                }),
3176            )
3177            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3178                cx.notify();
3179            }))
3180            .children(Scrollbar::horizontal(
3181                // percentage as f32..end_offset as f32,
3182                self.horizontal_scrollbar.state.clone(),
3183            ))
3184    }
3185
3186    fn render_buffer_header_controls(
3187        &self,
3188        entity: &Entity<Self>,
3189        file: &Arc<dyn File>,
3190        _: &Window,
3191        cx: &App,
3192    ) -> Option<AnyElement> {
3193        let repo = self.active_repository.as_ref()?.read(cx);
3194        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
3195        let ix = self.entry_by_path(&repo_path)?;
3196        let entry = self.entries.get(ix)?;
3197
3198        let entry_staging = self.entry_staging(entry.status_entry()?);
3199
3200        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3201            .disabled(!self.has_write_access(cx))
3202            .fill()
3203            .elevation(ElevationIndex::Surface)
3204            .on_click({
3205                let entry = entry.clone();
3206                let git_panel = entity.downgrade();
3207                move |_, window, cx| {
3208                    git_panel
3209                        .update(cx, |this, cx| {
3210                            this.toggle_staged_for_entry(&entry, window, cx);
3211                            cx.stop_propagation();
3212                        })
3213                        .ok();
3214                }
3215            });
3216        Some(
3217            h_flex()
3218                .id("start-slot")
3219                .text_lg()
3220                .child(checkbox)
3221                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3222                    // prevent the list item active state triggering when toggling checkbox
3223                    cx.stop_propagation();
3224                })
3225                .into_any_element(),
3226        )
3227    }
3228
3229    fn render_entries(
3230        &self,
3231        has_write_access: bool,
3232        _: &Window,
3233        cx: &mut Context<Self>,
3234    ) -> impl IntoElement {
3235        let entry_count = self.entries.len();
3236
3237        let scroll_track_size = px(16.);
3238
3239        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3240            // magic number
3241            px(3.)
3242        } else {
3243            px(0.)
3244        };
3245
3246        v_flex()
3247            .flex_1()
3248            .size_full()
3249            .overflow_hidden()
3250            .relative()
3251            // Show a border on the top and bottom of the container when
3252            // the vertical scrollbar container is visible so we don't have a
3253            // floating left border in the panel.
3254            .when(self.vertical_scrollbar.show_track, |this| {
3255                this.border_t_1()
3256                    .border_b_1()
3257                    .border_color(cx.theme().colors().border)
3258            })
3259            .child(
3260                h_flex()
3261                    .flex_1()
3262                    .size_full()
3263                    .relative()
3264                    .overflow_hidden()
3265                    .child(
3266                        uniform_list(cx.entity().clone(), "entries", entry_count, {
3267                            move |this, range, window, cx| {
3268                                let mut items = Vec::with_capacity(range.end - range.start);
3269
3270                                for ix in range {
3271                                    match &this.entries.get(ix) {
3272                                        Some(GitListEntry::GitStatusEntry(entry)) => {
3273                                            items.push(this.render_entry(
3274                                                ix,
3275                                                entry,
3276                                                has_write_access,
3277                                                window,
3278                                                cx,
3279                                            ));
3280                                        }
3281                                        Some(GitListEntry::Header(header)) => {
3282                                            items.push(this.render_list_header(
3283                                                ix,
3284                                                header,
3285                                                has_write_access,
3286                                                window,
3287                                                cx,
3288                                            ));
3289                                        }
3290                                        None => {}
3291                                    }
3292                                }
3293
3294                                items
3295                            }
3296                        })
3297                        .size_full()
3298                        .flex_grow()
3299                        .with_sizing_behavior(ListSizingBehavior::Auto)
3300                        .with_horizontal_sizing_behavior(
3301                            ListHorizontalSizingBehavior::Unconstrained,
3302                        )
3303                        .with_width_from_item(self.max_width_item_index)
3304                        .track_scroll(self.scroll_handle.clone()),
3305                    )
3306                    .on_mouse_down(
3307                        MouseButton::Right,
3308                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3309                            this.deploy_panel_context_menu(event.position, window, cx)
3310                        }),
3311                    )
3312                    .when(self.vertical_scrollbar.show_track, |this| {
3313                        this.child(
3314                            v_flex()
3315                                .h_full()
3316                                .flex_none()
3317                                .w(scroll_track_size)
3318                                .bg(cx.theme().colors().panel_background)
3319                                .child(
3320                                    div()
3321                                        .size_full()
3322                                        .flex_1()
3323                                        .border_l_1()
3324                                        .border_color(cx.theme().colors().border),
3325                                ),
3326                        )
3327                    })
3328                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
3329                        this.child(
3330                            self.render_vertical_scrollbar(
3331                                self.horizontal_scrollbar.show_track,
3332                                cx,
3333                            ),
3334                        )
3335                    }),
3336            )
3337            .when(self.horizontal_scrollbar.show_track, |this| {
3338                this.child(
3339                    h_flex()
3340                        .w_full()
3341                        .h(scroll_track_size)
3342                        .flex_none()
3343                        .relative()
3344                        .child(
3345                            div()
3346                                .w_full()
3347                                .flex_1()
3348                                // for some reason the horizontal scrollbar is 1px
3349                                // taller than the vertical scrollbar??
3350                                .h(scroll_track_size - px(1.))
3351                                .bg(cx.theme().colors().panel_background)
3352                                .border_t_1()
3353                                .border_color(cx.theme().colors().border),
3354                        )
3355                        .when(self.vertical_scrollbar.show_track, |this| {
3356                            this.child(
3357                                div()
3358                                    .flex_none()
3359                                    // -1px prevents a missing pixel between the two container borders
3360                                    .w(scroll_track_size - px(1.))
3361                                    .h_full(),
3362                            )
3363                            .child(
3364                                // HACK: Fill the missing 1px 🥲
3365                                div()
3366                                    .absolute()
3367                                    .right(scroll_track_size - px(1.))
3368                                    .bottom(scroll_track_size - px(1.))
3369                                    .size_px()
3370                                    .bg(cx.theme().colors().border),
3371                            )
3372                        }),
3373                )
3374            })
3375            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3376                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3377            })
3378    }
3379
3380    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3381        Label::new(label.into()).color(color).single_line()
3382    }
3383
3384    fn list_item_height(&self) -> Rems {
3385        rems(1.75)
3386    }
3387
3388    fn render_list_header(
3389        &self,
3390        ix: usize,
3391        header: &GitHeaderEntry,
3392        _: bool,
3393        _: &Window,
3394        _: &Context<Self>,
3395    ) -> AnyElement {
3396        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3397
3398        h_flex()
3399            .id(id)
3400            .h(self.list_item_height())
3401            .w_full()
3402            .items_end()
3403            .px(rems(0.75)) // ~12px
3404            .pb(rems(0.3125)) // ~ 5px
3405            .child(
3406                Label::new(header.title())
3407                    .color(Color::Muted)
3408                    .size(LabelSize::Small)
3409                    .line_height_style(LineHeightStyle::UiLabel)
3410                    .single_line(),
3411            )
3412            .into_any_element()
3413    }
3414
3415    fn load_commit_details(
3416        &self,
3417        sha: String,
3418        cx: &mut Context<Self>,
3419    ) -> Task<anyhow::Result<CommitDetails>> {
3420        let Some(repo) = self.active_repository.clone() else {
3421            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3422        };
3423        repo.update(cx, |repo, cx| {
3424            let show = repo.show(sha);
3425            cx.spawn(|_, _| async move { show.await? })
3426        })
3427    }
3428
3429    fn deploy_entry_context_menu(
3430        &mut self,
3431        position: Point<Pixels>,
3432        ix: usize,
3433        window: &mut Window,
3434        cx: &mut Context<Self>,
3435    ) {
3436        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3437            return;
3438        };
3439        let stage_title = if entry.status.staging().is_fully_staged() {
3440            "Unstage File"
3441        } else {
3442            "Stage File"
3443        };
3444        let restore_title = if entry.status.is_created() {
3445            "Trash File"
3446        } else {
3447            "Restore File"
3448        };
3449        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3450            context_menu
3451                .context(self.focus_handle.clone())
3452                .action(stage_title, ToggleStaged.boxed_clone())
3453                .action(restore_title, git::RestoreFile.boxed_clone())
3454                .separator()
3455                .action("Open Diff", Confirm.boxed_clone())
3456                .action("Open File", SecondaryConfirm.boxed_clone())
3457        });
3458        self.selected_entry = Some(ix);
3459        self.set_context_menu(context_menu, position, window, cx);
3460    }
3461
3462    fn deploy_panel_context_menu(
3463        &mut self,
3464        position: Point<Pixels>,
3465        window: &mut Window,
3466        cx: &mut Context<Self>,
3467    ) {
3468        let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3469        self.set_context_menu(context_menu, position, window, cx);
3470    }
3471
3472    fn set_context_menu(
3473        &mut self,
3474        context_menu: Entity<ContextMenu>,
3475        position: Point<Pixels>,
3476        window: &Window,
3477        cx: &mut Context<Self>,
3478    ) {
3479        let subscription = cx.subscribe_in(
3480            &context_menu,
3481            window,
3482            |this, _, _: &DismissEvent, window, cx| {
3483                if this.context_menu.as_ref().is_some_and(|context_menu| {
3484                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3485                }) {
3486                    cx.focus_self(window);
3487                }
3488                this.context_menu.take();
3489                cx.notify();
3490            },
3491        );
3492        self.context_menu = Some((context_menu, position, subscription));
3493        cx.notify();
3494    }
3495
3496    fn render_entry(
3497        &self,
3498        ix: usize,
3499        entry: &GitStatusEntry,
3500        has_write_access: bool,
3501        window: &Window,
3502        cx: &Context<Self>,
3503    ) -> AnyElement {
3504        let display_name = entry.display_name();
3505
3506        let selected = self.selected_entry == Some(ix);
3507        let marked = self.marked_entries.contains(&ix);
3508        let status_style = GitPanelSettings::get_global(cx).status_style;
3509        let status = entry.status;
3510        let modifiers = self.current_modifiers;
3511        let shift_held = modifiers.shift;
3512
3513        let has_conflict = status.is_conflicted();
3514        let is_modified = status.is_modified();
3515        let is_deleted = status.is_deleted();
3516
3517        let label_color = if status_style == StatusStyle::LabelColor {
3518            if has_conflict {
3519                Color::Conflict
3520            } else if is_modified {
3521                Color::Modified
3522            } else if is_deleted {
3523                // We don't want a bunch of red labels in the list
3524                Color::Disabled
3525            } else {
3526                Color::Created
3527            }
3528        } else {
3529            Color::Default
3530        };
3531
3532        let path_color = if status.is_deleted() {
3533            Color::Disabled
3534        } else {
3535            Color::Muted
3536        };
3537
3538        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3539        let checkbox_wrapper_id: ElementId =
3540            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3541        let checkbox_id: ElementId =
3542            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3543
3544        let entry_staging = self.entry_staging(entry);
3545        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3546
3547        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3548            is_staged = ToggleState::Selected;
3549        }
3550
3551        let handle = cx.weak_entity();
3552
3553        let selected_bg_alpha = 0.08;
3554        let marked_bg_alpha = 0.12;
3555        let state_opacity_step = 0.04;
3556
3557        let base_bg = match (selected, marked) {
3558            (true, true) => cx
3559                .theme()
3560                .status()
3561                .info
3562                .alpha(selected_bg_alpha + marked_bg_alpha),
3563            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3564            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3565            _ => cx.theme().colors().ghost_element_background,
3566        };
3567
3568        let hover_bg = if selected {
3569            cx.theme()
3570                .status()
3571                .info
3572                .alpha(selected_bg_alpha + state_opacity_step)
3573        } else {
3574            cx.theme().colors().ghost_element_hover
3575        };
3576
3577        let active_bg = if selected {
3578            cx.theme()
3579                .status()
3580                .info
3581                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3582        } else {
3583            cx.theme().colors().ghost_element_active
3584        };
3585
3586        h_flex()
3587            .id(id)
3588            .h(self.list_item_height())
3589            .w_full()
3590            .items_center()
3591            .border_1()
3592            .when(selected && self.focus_handle.is_focused(window), |el| {
3593                el.border_color(cx.theme().colors().border_focused)
3594            })
3595            .px(rems(0.75)) // ~12px
3596            .overflow_hidden()
3597            .flex_none()
3598            .gap_1p5()
3599            .bg(base_bg)
3600            .hover(|this| this.bg(hover_bg))
3601            .active(|this| this.bg(active_bg))
3602            .on_click({
3603                cx.listener(move |this, event: &ClickEvent, window, cx| {
3604                    this.selected_entry = Some(ix);
3605                    cx.notify();
3606                    if event.modifiers().secondary() {
3607                        this.open_file(&Default::default(), window, cx)
3608                    } else {
3609                        this.open_diff(&Default::default(), window, cx);
3610                        this.focus_handle.focus(window);
3611                    }
3612                })
3613            })
3614            .on_mouse_down(
3615                MouseButton::Right,
3616                move |event: &MouseDownEvent, window, cx| {
3617                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3618                    if event.button != MouseButton::Right {
3619                        return;
3620                    }
3621
3622                    let Some(this) = handle.upgrade() else {
3623                        return;
3624                    };
3625                    this.update(cx, |this, cx| {
3626                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3627                    });
3628                    cx.stop_propagation();
3629                },
3630            )
3631            // .on_secondary_mouse_down(cx.listener(
3632            //     move |this, event: &MouseDownEvent, window, cx| {
3633            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3634            //         cx.stop_propagation();
3635            //     },
3636            // ))
3637            .child(
3638                div()
3639                    .id(checkbox_wrapper_id)
3640                    .flex_none()
3641                    .occlude()
3642                    .cursor_pointer()
3643                    .child(
3644                        Checkbox::new(checkbox_id, is_staged)
3645                            .disabled(!has_write_access)
3646                            .fill()
3647                            .placeholder(
3648                                !self.has_staged_changes()
3649                                    && !self.has_conflicts()
3650                                    && !entry.status.is_created(),
3651                            )
3652                            .elevation(ElevationIndex::Surface)
3653                            .on_click({
3654                                let entry = entry.clone();
3655                                cx.listener(move |this, _, window, cx| {
3656                                    if !has_write_access {
3657                                        return;
3658                                    }
3659                                    this.toggle_staged_for_entry(
3660                                        &GitListEntry::GitStatusEntry(entry.clone()),
3661                                        window,
3662                                        cx,
3663                                    );
3664                                    cx.stop_propagation();
3665                                })
3666                            })
3667                            .tooltip(move |window, cx| {
3668                                let is_staged = entry_staging.is_fully_staged();
3669
3670                                let action = if is_staged { "Unstage" } else { "Stage" };
3671                                let tooltip_name = if shift_held {
3672                                    format!("{} section", action)
3673                                } else {
3674                                    action.to_string()
3675                                };
3676
3677                                let meta = if shift_held {
3678                                    format!(
3679                                        "Release shift to {} single entry",
3680                                        action.to_lowercase()
3681                                    )
3682                                } else {
3683                                    format!("Shift click to {} section", action.to_lowercase())
3684                                };
3685
3686                                Tooltip::with_meta(
3687                                    tooltip_name,
3688                                    Some(&ToggleStaged),
3689                                    meta,
3690                                    window,
3691                                    cx,
3692                                )
3693                            }),
3694                    ),
3695            )
3696            .child(git_status_icon(status))
3697            .child(
3698                h_flex()
3699                    .items_center()
3700                    .flex_1()
3701                    // .overflow_hidden()
3702                    .when_some(entry.parent_dir(), |this, parent| {
3703                        if !parent.is_empty() {
3704                            this.child(
3705                                self.entry_label(format!("{}/", parent), path_color)
3706                                    .when(status.is_deleted(), |this| this.strikethrough()),
3707                            )
3708                        } else {
3709                            this
3710                        }
3711                    })
3712                    .child(
3713                        self.entry_label(display_name.clone(), label_color)
3714                            .when(status.is_deleted(), |this| this.strikethrough()),
3715                    ),
3716            )
3717            .into_any_element()
3718    }
3719
3720    fn has_write_access(&self, cx: &App) -> bool {
3721        !self.project.read(cx).is_read_only(cx)
3722    }
3723}
3724
3725fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3726    assistant_settings::AssistantSettings::get_global(cx)
3727        .enabled
3728        .then(|| {
3729            let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3730            let model = LanguageModelRegistry::read_global(cx).active_model()?;
3731            provider.is_authenticated(cx).then(|| model)
3732        })
3733        .flatten()
3734}
3735
3736impl Render for GitPanel {
3737    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3738        let project = self.project.read(cx);
3739        let has_entries = self.entries.len() > 0;
3740        let room = self
3741            .workspace
3742            .upgrade()
3743            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3744
3745        let has_write_access = self.has_write_access(cx);
3746
3747        let has_co_authors = room.map_or(false, |room| {
3748            room.read(cx)
3749                .remote_participants()
3750                .values()
3751                .any(|remote_participant| remote_participant.can_write())
3752        });
3753
3754        v_flex()
3755            .id("git_panel")
3756            .key_context(self.dispatch_context(window, cx))
3757            .track_focus(&self.focus_handle)
3758            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3759            .when(has_write_access && !project.is_read_only(cx), |this| {
3760                this.on_action(cx.listener(Self::toggle_staged_for_selected))
3761                    .on_action(cx.listener(GitPanel::commit))
3762                    .on_action(cx.listener(Self::stage_all))
3763                    .on_action(cx.listener(Self::unstage_all))
3764                    .on_action(cx.listener(Self::stage_selected))
3765                    .on_action(cx.listener(Self::unstage_selected))
3766                    .on_action(cx.listener(Self::restore_tracked_files))
3767                    .on_action(cx.listener(Self::revert_selected))
3768                    .on_action(cx.listener(Self::clean_all))
3769                    .on_action(cx.listener(Self::generate_commit_message_action))
3770            })
3771            .on_action(cx.listener(Self::select_first))
3772            .on_action(cx.listener(Self::select_next))
3773            .on_action(cx.listener(Self::select_previous))
3774            .on_action(cx.listener(Self::select_last))
3775            .on_action(cx.listener(Self::close_panel))
3776            .on_action(cx.listener(Self::open_diff))
3777            .on_action(cx.listener(Self::open_file))
3778            .on_action(cx.listener(Self::focus_changes_list))
3779            .on_action(cx.listener(Self::focus_editor))
3780            .on_action(cx.listener(Self::expand_commit_editor))
3781            .when(has_write_access && has_co_authors, |git_panel| {
3782                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3783            })
3784            .on_hover(cx.listener(move |this, hovered, window, cx| {
3785                if *hovered {
3786                    this.horizontal_scrollbar.show(cx);
3787                    this.vertical_scrollbar.show(cx);
3788                    cx.notify();
3789                } else if !this.focus_handle.contains_focused(window, cx) {
3790                    this.hide_scrollbars(window, cx);
3791                }
3792            }))
3793            .size_full()
3794            .overflow_hidden()
3795            .bg(ElevationIndex::Surface.bg(cx))
3796            .child(
3797                v_flex()
3798                    .size_full()
3799                    .children(self.render_panel_header(window, cx))
3800                    .map(|this| {
3801                        if has_entries {
3802                            this.child(self.render_entries(has_write_access, window, cx))
3803                        } else {
3804                            this.child(self.render_empty_state(cx).into_any_element())
3805                        }
3806                    })
3807                    .children(self.render_footer(window, cx))
3808                    .children(self.render_previous_commit(cx))
3809                    .into_any_element(),
3810            )
3811            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3812                deferred(
3813                    anchored()
3814                        .position(*position)
3815                        .anchor(gpui::Corner::TopLeft)
3816                        .child(menu.clone()),
3817                )
3818                .with_priority(1)
3819            }))
3820    }
3821}
3822
3823impl Focusable for GitPanel {
3824    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3825        if self.entries.is_empty() {
3826            self.commit_editor.focus_handle(cx)
3827        } else {
3828            self.focus_handle.clone()
3829        }
3830    }
3831}
3832
3833impl EventEmitter<Event> for GitPanel {}
3834
3835impl EventEmitter<PanelEvent> for GitPanel {}
3836
3837pub(crate) struct GitPanelAddon {
3838    pub(crate) workspace: WeakEntity<Workspace>,
3839}
3840
3841impl editor::Addon for GitPanelAddon {
3842    fn to_any(&self) -> &dyn std::any::Any {
3843        self
3844    }
3845
3846    fn render_buffer_header_controls(
3847        &self,
3848        excerpt_info: &ExcerptInfo,
3849        window: &Window,
3850        cx: &App,
3851    ) -> Option<AnyElement> {
3852        let file = excerpt_info.buffer.file()?;
3853        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3854
3855        git_panel
3856            .read(cx)
3857            .render_buffer_header_controls(&git_panel, &file, window, cx)
3858    }
3859}
3860
3861impl Panel for GitPanel {
3862    fn persistent_name() -> &'static str {
3863        "GitPanel"
3864    }
3865
3866    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3867        GitPanelSettings::get_global(cx).dock
3868    }
3869
3870    fn position_is_valid(&self, position: DockPosition) -> bool {
3871        matches!(position, DockPosition::Left | DockPosition::Right)
3872    }
3873
3874    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3875        settings::update_settings_file::<GitPanelSettings>(
3876            self.fs.clone(),
3877            cx,
3878            move |settings, _| settings.dock = Some(position),
3879        );
3880    }
3881
3882    fn size(&self, _: &Window, cx: &App) -> Pixels {
3883        self.width
3884            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3885    }
3886
3887    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3888        self.width = size;
3889        self.serialize(cx);
3890        cx.notify();
3891    }
3892
3893    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3894        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3895    }
3896
3897    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3898        Some("Git Panel")
3899    }
3900
3901    fn toggle_action(&self) -> Box<dyn Action> {
3902        Box::new(ToggleFocus)
3903    }
3904
3905    fn activation_priority(&self) -> u32 {
3906        2
3907    }
3908}
3909
3910impl PanelHeader for GitPanel {}
3911
3912struct GitPanelMessageTooltip {
3913    commit_tooltip: Option<Entity<CommitTooltip>>,
3914}
3915
3916impl GitPanelMessageTooltip {
3917    fn new(
3918        git_panel: Entity<GitPanel>,
3919        sha: SharedString,
3920        window: &mut Window,
3921        cx: &mut App,
3922    ) -> Entity<Self> {
3923        cx.new(|cx| {
3924            cx.spawn_in(window, |this, mut cx| async move {
3925                let details = git_panel
3926                    .update(&mut cx, |git_panel, cx| {
3927                        git_panel.load_commit_details(sha.to_string(), cx)
3928                    })?
3929                    .await?;
3930
3931                let commit_details = editor::commit_tooltip::CommitDetails {
3932                    sha: details.sha.clone(),
3933                    committer_name: details.committer_name.clone(),
3934                    committer_email: details.committer_email.clone(),
3935                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3936                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3937                        message: details.message.clone(),
3938                        ..Default::default()
3939                    }),
3940                };
3941
3942                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3943                    this.commit_tooltip =
3944                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3945                    cx.notify();
3946                })
3947            })
3948            .detach();
3949
3950            Self {
3951                commit_tooltip: None,
3952            }
3953        })
3954    }
3955}
3956
3957impl Render for GitPanelMessageTooltip {
3958    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3959        if let Some(commit_tooltip) = &self.commit_tooltip {
3960            commit_tooltip.clone().into_any_element()
3961        } else {
3962            gpui::Empty.into_any_element()
3963        }
3964    }
3965}
3966
3967#[derive(IntoElement, IntoComponent)]
3968#[component(scope = "Version Control")]
3969pub struct PanelRepoFooter {
3970    id: SharedString,
3971    active_repository: SharedString,
3972    branch: Option<Branch>,
3973    // Getting a GitPanel in previews will be difficult.
3974    //
3975    // For now just take an option here, and we won't bind handlers to buttons in previews.
3976    git_panel: Option<Entity<GitPanel>>,
3977}
3978
3979impl PanelRepoFooter {
3980    pub fn new(
3981        id: impl Into<SharedString>,
3982        active_repository: SharedString,
3983        branch: Option<Branch>,
3984        git_panel: Option<Entity<GitPanel>>,
3985    ) -> Self {
3986        Self {
3987            id: id.into(),
3988            active_repository,
3989            branch,
3990            git_panel,
3991        }
3992    }
3993
3994    pub fn new_preview(
3995        id: impl Into<SharedString>,
3996        active_repository: SharedString,
3997        branch: Option<Branch>,
3998    ) -> Self {
3999        Self {
4000            id: id.into(),
4001            active_repository,
4002            branch,
4003            git_panel: None,
4004        }
4005    }
4006}
4007
4008impl RenderOnce for PanelRepoFooter {
4009    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4010        let project = self
4011            .git_panel
4012            .as_ref()
4013            .map(|panel| panel.read(cx).project.clone());
4014
4015        let repo = self
4016            .git_panel
4017            .as_ref()
4018            .and_then(|panel| panel.read(cx).active_repository.clone());
4019
4020        let single_repo = project
4021            .as_ref()
4022            .map(|project| {
4023                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
4024            })
4025            .unwrap_or(true);
4026
4027        const MAX_BRANCH_LEN: usize = 16;
4028        const MAX_REPO_LEN: usize = 16;
4029        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4030
4031        let branch = self.branch.clone();
4032        let branch_name = branch
4033            .as_ref()
4034            .map_or(" (no branch)".into(), |branch| branch.name.clone());
4035        let active_repo_name = self.active_repository.clone();
4036
4037        let branch_actual_len = branch_name.len();
4038        let repo_actual_len = active_repo_name.len();
4039
4040        // ideally, show the whole branch and repo names but
4041        // when we can't, use a budget to allocate space between the two
4042        let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4043            <= LABEL_CHARACTER_BUDGET
4044        {
4045            (repo_actual_len, branch_actual_len)
4046        } else {
4047            if branch_actual_len <= MAX_BRANCH_LEN {
4048                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4049                (repo_space, branch_actual_len)
4050            } else if repo_actual_len <= MAX_REPO_LEN {
4051                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4052                (repo_actual_len, branch_space)
4053            } else {
4054                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4055            }
4056        };
4057
4058        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4059            active_repo_name.to_string()
4060        } else {
4061            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4062        };
4063
4064        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4065            branch_name.to_string()
4066        } else {
4067            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4068        };
4069
4070        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4071            .style(ButtonStyle::Transparent)
4072            .size(ButtonSize::None)
4073            .label_size(LabelSize::Small)
4074            .color(Color::Muted);
4075
4076        let repo_selector = PopoverMenu::new("repository-switcher")
4077            .menu({
4078                let project = project.clone();
4079                move |window, cx| {
4080                    let project = project.clone()?;
4081                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
4082                }
4083            })
4084            .trigger_with_tooltip(
4085                repo_selector_trigger.disabled(single_repo).truncate(true),
4086                Tooltip::text("Switch active repository"),
4087            )
4088            .attach(gpui::Corner::BottomLeft)
4089            .into_any_element();
4090
4091        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4092            .style(ButtonStyle::Transparent)
4093            .size(ButtonSize::None)
4094            .label_size(LabelSize::Small)
4095            .truncate(true)
4096            .tooltip(Tooltip::for_action_title(
4097                "Switch Branch",
4098                &zed_actions::git::Branch,
4099            ))
4100            .on_click(|_, window, cx| {
4101                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
4102            });
4103
4104        let branch_selector = PopoverMenu::new("popover-button")
4105            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4106            .trigger_with_tooltip(
4107                branch_selector_button,
4108                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
4109            )
4110            .anchor(Corner::TopLeft)
4111            .offset(gpui::Point {
4112                x: px(0.0),
4113                y: px(-2.0),
4114            });
4115
4116        let spinner = self
4117            .git_panel
4118            .as_ref()
4119            .and_then(|git_panel| git_panel.read(cx).render_spinner());
4120
4121        h_flex()
4122            .w_full()
4123            .px_2()
4124            .h(px(36.))
4125            .items_center()
4126            .justify_between()
4127            .gap_1()
4128            .child(
4129                h_flex()
4130                    .flex_1()
4131                    .overflow_hidden()
4132                    .items_center()
4133                    .child(
4134                        div().child(
4135                            Icon::new(IconName::GitBranchSmall)
4136                                .size(IconSize::Small)
4137                                .color(if single_repo {
4138                                    Color::Disabled
4139                                } else {
4140                                    Color::Muted
4141                                }),
4142                        ),
4143                    )
4144                    .child(repo_selector)
4145                    .when_some(branch.clone(), |this, _| {
4146                        this.child(
4147                            div()
4148                                .text_color(cx.theme().colors().text_muted)
4149                                .text_sm()
4150                                .child("/"),
4151                        )
4152                    })
4153                    .child(branch_selector),
4154            )
4155            .child(
4156                h_flex()
4157                    .gap_1()
4158                    .flex_shrink_0()
4159                    .children(spinner)
4160                    .when_some(branch, |this, branch| {
4161                        let mut focus_handle = None;
4162                        if let Some(git_panel) = self.git_panel.as_ref() {
4163                            if !git_panel.read(cx).can_push_and_pull(cx) {
4164                                return this;
4165                            }
4166                            focus_handle = Some(git_panel.focus_handle(cx));
4167                        }
4168
4169                        this.children(render_remote_button(
4170                            self.id.clone(),
4171                            &branch,
4172                            focus_handle,
4173                            true,
4174                        ))
4175                    }),
4176            )
4177    }
4178}
4179
4180impl ComponentPreview for PanelRepoFooter {
4181    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
4182        let unknown_upstream = None;
4183        let no_remote_upstream = Some(UpstreamTracking::Gone);
4184        let ahead_of_upstream = Some(
4185            UpstreamTrackingStatus {
4186                ahead: 2,
4187                behind: 0,
4188            }
4189            .into(),
4190        );
4191        let behind_upstream = Some(
4192            UpstreamTrackingStatus {
4193                ahead: 0,
4194                behind: 2,
4195            }
4196            .into(),
4197        );
4198        let ahead_and_behind_upstream = Some(
4199            UpstreamTrackingStatus {
4200                ahead: 3,
4201                behind: 1,
4202            }
4203            .into(),
4204        );
4205
4206        let not_ahead_or_behind_upstream = Some(
4207            UpstreamTrackingStatus {
4208                ahead: 0,
4209                behind: 0,
4210            }
4211            .into(),
4212        );
4213
4214        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4215            Branch {
4216                is_head: true,
4217                name: "some-branch".into(),
4218                upstream: upstream.map(|tracking| Upstream {
4219                    ref_name: "origin/some-branch".into(),
4220                    tracking,
4221                }),
4222                most_recent_commit: Some(CommitSummary {
4223                    sha: "abc123".into(),
4224                    subject: "Modify stuff".into(),
4225                    commit_timestamp: 1710932954,
4226                    has_parent: true,
4227                }),
4228            }
4229        }
4230
4231        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4232            Branch {
4233                is_head: true,
4234                name: branch_name.to_string().into(),
4235                upstream: upstream.map(|tracking| Upstream {
4236                    ref_name: format!("zed/{}", branch_name).into(),
4237                    tracking,
4238                }),
4239                most_recent_commit: Some(CommitSummary {
4240                    sha: "abc123".into(),
4241                    subject: "Modify stuff".into(),
4242                    commit_timestamp: 1710932954,
4243                    has_parent: true,
4244                }),
4245            }
4246        }
4247
4248        fn active_repository(id: usize) -> SharedString {
4249            format!("repo-{}", id).into()
4250        }
4251
4252        let example_width = px(340.);
4253
4254        v_flex()
4255            .gap_6()
4256            .w_full()
4257            .flex_none()
4258            .children(vec![example_group_with_title(
4259                "Action Button States",
4260                vec![
4261                    single_example(
4262                        "No Branch",
4263                        div()
4264                            .w(example_width)
4265                            .overflow_hidden()
4266                            .child(PanelRepoFooter::new_preview(
4267                                "no-branch",
4268                                active_repository(1).clone(),
4269                                None,
4270                            ))
4271                            .into_any_element(),
4272                    )
4273                    .grow(),
4274                    single_example(
4275                        "Remote status unknown",
4276                        div()
4277                            .w(example_width)
4278                            .overflow_hidden()
4279                            .child(PanelRepoFooter::new_preview(
4280                                "unknown-upstream",
4281                                active_repository(2).clone(),
4282                                Some(branch(unknown_upstream)),
4283                            ))
4284                            .into_any_element(),
4285                    )
4286                    .grow(),
4287                    single_example(
4288                        "No Remote Upstream",
4289                        div()
4290                            .w(example_width)
4291                            .overflow_hidden()
4292                            .child(PanelRepoFooter::new_preview(
4293                                "no-remote-upstream",
4294                                active_repository(3).clone(),
4295                                Some(branch(no_remote_upstream)),
4296                            ))
4297                            .into_any_element(),
4298                    )
4299                    .grow(),
4300                    single_example(
4301                        "Not Ahead or Behind",
4302                        div()
4303                            .w(example_width)
4304                            .overflow_hidden()
4305                            .child(PanelRepoFooter::new_preview(
4306                                "not-ahead-or-behind",
4307                                active_repository(4).clone(),
4308                                Some(branch(not_ahead_or_behind_upstream)),
4309                            ))
4310                            .into_any_element(),
4311                    )
4312                    .grow(),
4313                    single_example(
4314                        "Behind remote",
4315                        div()
4316                            .w(example_width)
4317                            .overflow_hidden()
4318                            .child(PanelRepoFooter::new_preview(
4319                                "behind-remote",
4320                                active_repository(5).clone(),
4321                                Some(branch(behind_upstream)),
4322                            ))
4323                            .into_any_element(),
4324                    )
4325                    .grow(),
4326                    single_example(
4327                        "Ahead of remote",
4328                        div()
4329                            .w(example_width)
4330                            .overflow_hidden()
4331                            .child(PanelRepoFooter::new_preview(
4332                                "ahead-of-remote",
4333                                active_repository(6).clone(),
4334                                Some(branch(ahead_of_upstream)),
4335                            ))
4336                            .into_any_element(),
4337                    )
4338                    .grow(),
4339                    single_example(
4340                        "Ahead and behind remote",
4341                        div()
4342                            .w(example_width)
4343                            .overflow_hidden()
4344                            .child(PanelRepoFooter::new_preview(
4345                                "ahead-and-behind",
4346                                active_repository(7).clone(),
4347                                Some(branch(ahead_and_behind_upstream)),
4348                            ))
4349                            .into_any_element(),
4350                    )
4351                    .grow(),
4352                ],
4353            )
4354            .grow()
4355            .vertical()])
4356            .children(vec![example_group_with_title(
4357                "Labels",
4358                vec![
4359                    single_example(
4360                        "Short Branch & Repo",
4361                        div()
4362                            .w(example_width)
4363                            .overflow_hidden()
4364                            .child(PanelRepoFooter::new_preview(
4365                                "short-branch",
4366                                SharedString::from("zed"),
4367                                Some(custom("main", behind_upstream)),
4368                            ))
4369                            .into_any_element(),
4370                    )
4371                    .grow(),
4372                    single_example(
4373                        "Long Branch",
4374                        div()
4375                            .w(example_width)
4376                            .overflow_hidden()
4377                            .child(PanelRepoFooter::new_preview(
4378                                "long-branch",
4379                                SharedString::from("zed"),
4380                                Some(custom(
4381                                    "redesign-and-update-git-ui-list-entry-style",
4382                                    behind_upstream,
4383                                )),
4384                            ))
4385                            .into_any_element(),
4386                    )
4387                    .grow(),
4388                    single_example(
4389                        "Long Repo",
4390                        div()
4391                            .w(example_width)
4392                            .overflow_hidden()
4393                            .child(PanelRepoFooter::new_preview(
4394                                "long-repo",
4395                                SharedString::from("zed-industries-community-examples"),
4396                                Some(custom("gpui", ahead_of_upstream)),
4397                            ))
4398                            .into_any_element(),
4399                    )
4400                    .grow(),
4401                    single_example(
4402                        "Long Repo & Branch",
4403                        div()
4404                            .w(example_width)
4405                            .overflow_hidden()
4406                            .child(PanelRepoFooter::new_preview(
4407                                "long-repo-and-branch",
4408                                SharedString::from("zed-industries-community-examples"),
4409                                Some(custom(
4410                                    "redesign-and-update-git-ui-list-entry-style",
4411                                    behind_upstream,
4412                                )),
4413                            ))
4414                            .into_any_element(),
4415                    )
4416                    .grow(),
4417                    single_example(
4418                        "Uppercase Repo",
4419                        div()
4420                            .w(example_width)
4421                            .overflow_hidden()
4422                            .child(PanelRepoFooter::new_preview(
4423                                "uppercase-repo",
4424                                SharedString::from("LICENSES"),
4425                                Some(custom("main", ahead_of_upstream)),
4426                            ))
4427                            .into_any_element(),
4428                    )
4429                    .grow(),
4430                    single_example(
4431                        "Uppercase Branch",
4432                        div()
4433                            .w(example_width)
4434                            .overflow_hidden()
4435                            .child(PanelRepoFooter::new_preview(
4436                                "uppercase-branch",
4437                                SharedString::from("zed"),
4438                                Some(custom("update-README", behind_upstream)),
4439                            ))
4440                            .into_any_element(),
4441                    )
4442                    .grow(),
4443                ],
4444            )
4445            .grow()
4446            .vertical()])
4447            .into_any_element()
4448    }
4449}
4450
4451#[cfg(test)]
4452mod tests {
4453    use git::status::StatusCode;
4454    use gpui::TestAppContext;
4455    use project::{FakeFs, WorktreeSettings};
4456    use serde_json::json;
4457    use settings::SettingsStore;
4458    use theme::LoadThemes;
4459    use util::path;
4460
4461    use super::*;
4462
4463    fn init_test(cx: &mut gpui::TestAppContext) {
4464        if std::env::var("RUST_LOG").is_ok() {
4465            env_logger::try_init().ok();
4466        }
4467
4468        cx.update(|cx| {
4469            let settings_store = SettingsStore::test(cx);
4470            cx.set_global(settings_store);
4471            AssistantSettings::register(cx);
4472            WorktreeSettings::register(cx);
4473            workspace::init_settings(cx);
4474            theme::init(LoadThemes::JustBase, cx);
4475            language::init(cx);
4476            editor::init(cx);
4477            Project::init_settings(cx);
4478            crate::init(cx);
4479        });
4480    }
4481
4482    #[gpui::test]
4483    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4484        init_test(cx);
4485        let fs = FakeFs::new(cx.background_executor.clone());
4486        fs.insert_tree(
4487            "/root",
4488            json!({
4489                "zed": {
4490                    ".git": {},
4491                    "crates": {
4492                        "gpui": {
4493                            "gpui.rs": "fn main() {}"
4494                        },
4495                        "util": {
4496                            "util.rs": "fn do_it() {}"
4497                        }
4498                    }
4499                },
4500            }),
4501        )
4502        .await;
4503
4504        fs.set_status_for_repo_via_git_operation(
4505            Path::new(path!("/root/zed/.git")),
4506            &[
4507                (
4508                    Path::new("crates/gpui/gpui.rs"),
4509                    StatusCode::Modified.worktree(),
4510                ),
4511                (
4512                    Path::new("crates/util/util.rs"),
4513                    StatusCode::Modified.worktree(),
4514                ),
4515            ],
4516        );
4517
4518        let project =
4519            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4520        let (workspace, cx) =
4521            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4522
4523        cx.read(|cx| {
4524            project
4525                .read(cx)
4526                .worktrees(cx)
4527                .nth(0)
4528                .unwrap()
4529                .read(cx)
4530                .as_local()
4531                .unwrap()
4532                .scan_complete()
4533        })
4534        .await;
4535
4536        cx.executor().run_until_parked();
4537
4538        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4539        let panel = cx.new_window_entity(|window, cx| {
4540            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4541        });
4542
4543        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4544            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4545        });
4546        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4547        handle.await;
4548
4549        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4550        pretty_assertions::assert_eq!(
4551            entries,
4552            [
4553                GitListEntry::Header(GitHeaderEntry {
4554                    header: Section::Tracked
4555                }),
4556                GitListEntry::GitStatusEntry(GitStatusEntry {
4557                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4558                    repo_path: "crates/gpui/gpui.rs".into(),
4559                    worktree_path: Path::new("gpui.rs").into(),
4560                    status: StatusCode::Modified.worktree(),
4561                    staging: StageStatus::Unstaged,
4562                }),
4563                GitListEntry::GitStatusEntry(GitStatusEntry {
4564                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4565                    repo_path: "crates/util/util.rs".into(),
4566                    worktree_path: Path::new("../util/util.rs").into(),
4567                    status: StatusCode::Modified.worktree(),
4568                    staging: StageStatus::Unstaged,
4569                },),
4570            ],
4571        );
4572
4573        cx.update_window_entity(&panel, |panel, window, cx| {
4574            panel.select_last(&Default::default(), window, cx);
4575            assert_eq!(panel.selected_entry, Some(2));
4576            panel.open_diff(&Default::default(), window, cx);
4577        });
4578        cx.run_until_parked();
4579
4580        let worktree_roots = workspace.update(cx, |workspace, cx| {
4581            workspace
4582                .worktrees(cx)
4583                .map(|worktree| worktree.read(cx).abs_path())
4584                .collect::<Vec<_>>()
4585        });
4586        pretty_assertions::assert_eq!(
4587            worktree_roots,
4588            vec![
4589                Path::new(path!("/root/zed/crates/gpui")).into(),
4590                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4591            ]
4592        );
4593
4594        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4595            let git_store = project.git_store().read(cx);
4596            // The repo that comes from the single-file worktree can't be selected through the UI.
4597            let filtered_entries = filtered_repository_entries(git_store, cx)
4598                .iter()
4599                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4600                .collect::<Vec<_>>();
4601            assert_eq!(
4602                filtered_entries,
4603                [Path::new(path!("/root/zed/crates/gpui")).into()]
4604            );
4605            // But we can select it artificially here.
4606            git_store
4607                .all_repositories()
4608                .into_iter()
4609                .find(|repo| {
4610                    &*repo.read(cx).worktree_abs_path
4611                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4612                })
4613                .unwrap()
4614        });
4615
4616        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4617        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4618        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4619            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4620        });
4621        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4622        handle.await;
4623        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4624        pretty_assertions::assert_eq!(
4625            entries,
4626            [
4627                GitListEntry::Header(GitHeaderEntry {
4628                    header: Section::Tracked
4629                }),
4630                GitListEntry::GitStatusEntry(GitStatusEntry {
4631                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4632                    repo_path: "crates/gpui/gpui.rs".into(),
4633                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4634                    status: StatusCode::Modified.worktree(),
4635                    staging: StageStatus::Unstaged,
4636                }),
4637                GitListEntry::GitStatusEntry(GitStatusEntry {
4638                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4639                    repo_path: "crates/util/util.rs".into(),
4640                    worktree_path: Path::new("util.rs").into(),
4641                    status: StatusCode::Modified.worktree(),
4642                    staging: StageStatus::Unstaged,
4643                },),
4644            ],
4645        );
4646    }
4647}