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(cx)
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, cx: &App) -> Option<String> {
1586        if let Some(merge_message) = self
1587            .active_repository
1588            .as_ref()
1589            .and_then(|repo| repo.read(cx).merge_message.as_ref())
1590        {
1591            return Some(merge_message.clone());
1592        }
1593
1594        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1595            Some(staged_entry)
1596        } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1597            Some(single_tracked_entry)
1598        } else {
1599            None
1600        }?;
1601
1602        let action_text = if git_status_entry.status.is_deleted() {
1603            Some("Delete")
1604        } else if git_status_entry.status.is_created() {
1605            Some("Create")
1606        } else if git_status_entry.status.is_modified() {
1607            Some("Update")
1608        } else {
1609            None
1610        }?;
1611
1612        let file_name = git_status_entry
1613            .repo_path
1614            .file_name()
1615            .unwrap_or_default()
1616            .to_string_lossy();
1617
1618        Some(format!("{} {}", action_text, file_name))
1619    }
1620
1621    fn generate_commit_message_action(
1622        &mut self,
1623        _: &git::GenerateCommitMessage,
1624        _window: &mut Window,
1625        cx: &mut Context<Self>,
1626    ) {
1627        self.generate_commit_message(cx);
1628    }
1629
1630    /// Generates a commit message using an LLM.
1631    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1632        if !self.can_commit() {
1633            return;
1634        }
1635
1636        let model = match current_language_model(cx) {
1637            Some(value) => value,
1638            None => return,
1639        };
1640
1641        let Some(repo) = self.active_repository.as_ref() else {
1642            return;
1643        };
1644
1645        telemetry::event!("Git Commit Message Generated");
1646
1647        let diff = repo.update(cx, |repo, cx| {
1648            if self.has_staged_changes() {
1649                repo.diff(DiffType::HeadToIndex, cx)
1650            } else {
1651                repo.diff(DiffType::HeadToWorktree, cx)
1652            }
1653        });
1654
1655        self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1656            async move {
1657                let _defer = util::defer({
1658                    let mut cx = cx.clone();
1659                    let this = this.clone();
1660                    move || {
1661                        this.update(&mut cx, |this, _cx| {
1662                            this.generate_commit_message_task.take();
1663                        })
1664                        .ok();
1665                    }
1666                });
1667
1668                let mut diff_text = diff.await??;
1669
1670                const ONE_MB: usize = 1_000_000;
1671                if diff_text.len() > ONE_MB {
1672                    diff_text = diff_text.chars().take(ONE_MB).collect()
1673                }
1674
1675                let subject = this.update(&mut cx, |this, cx| {
1676                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1677                })?;
1678
1679                let text_empty = subject.trim().is_empty();
1680
1681                let content = if text_empty {
1682                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1683                } else {
1684                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1685                };
1686
1687                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1688
1689                let request = LanguageModelRequest {
1690                    messages: vec![LanguageModelRequestMessage {
1691                        role: Role::User,
1692                        content: vec![content.into()],
1693                        cache: false,
1694                    }],
1695                    tools: Vec::new(),
1696                    stop: Vec::new(),
1697                    temperature: None,
1698                };
1699
1700                let stream = model.stream_completion_text(request, &cx);
1701                let mut messages = stream.await?;
1702
1703                if !text_empty {
1704                    this.update(&mut cx, |this, cx| {
1705                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1706                            let insert_position = buffer.anchor_before(buffer.len());
1707                            buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1708                        });
1709                    })?;
1710                }
1711
1712                while let Some(message) = messages.stream.next().await {
1713                    let text = message?;
1714
1715                    this.update(&mut cx, |this, cx| {
1716                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1717                            let insert_position = buffer.anchor_before(buffer.len());
1718                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1719                        });
1720                    })?;
1721                }
1722
1723                anyhow::Ok(())
1724            }
1725            .log_err()
1726        }));
1727    }
1728
1729    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1730        if !self.can_push_and_pull(cx) {
1731            return;
1732        }
1733
1734        let Some(repo) = self.active_repository.clone() else {
1735            return;
1736        };
1737        telemetry::event!("Git Fetched");
1738        let guard = self.start_remote_operation();
1739        let askpass = self.askpass_delegate("git fetch", window, cx);
1740        let this = cx.weak_entity();
1741        window
1742            .spawn(cx, |mut cx| async move {
1743                let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1744
1745                let remote_message = fetch.await?;
1746                drop(guard);
1747                this.update(&mut cx, |this, cx| {
1748                    let action = RemoteAction::Fetch;
1749                    match remote_message {
1750                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1751                        Err(e) => {
1752                            log::error!("Error while fetching {:?}", e);
1753                            this.show_error_toast(action.name(), e, cx)
1754                        }
1755                    }
1756
1757                    anyhow::Ok(())
1758                })
1759                .ok();
1760                anyhow::Ok(())
1761            })
1762            .detach_and_log_err(cx);
1763    }
1764
1765    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1766        let worktrees = self
1767            .project
1768            .read(cx)
1769            .visible_worktrees(cx)
1770            .collect::<Vec<_>>();
1771
1772        let worktree = if worktrees.len() == 1 {
1773            Task::ready(Some(worktrees.first().unwrap().clone()))
1774        } else if worktrees.len() == 0 {
1775            let result = window.prompt(
1776                PromptLevel::Warning,
1777                "Unable to initialize a git repository",
1778                Some("Open a directory first"),
1779                &["Ok"],
1780                cx,
1781            );
1782            cx.background_executor()
1783                .spawn(async move {
1784                    result.await.ok();
1785                })
1786                .detach();
1787            return;
1788        } else {
1789            let worktree_directories = worktrees
1790                .iter()
1791                .map(|worktree| worktree.read(cx).abs_path())
1792                .map(|worktree_abs_path| {
1793                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1794                        Path::new("~")
1795                            .join(path)
1796                            .to_string_lossy()
1797                            .to_string()
1798                            .into()
1799                    } else {
1800                        worktree_abs_path.to_string_lossy().to_string().into()
1801                    }
1802                })
1803                .collect_vec();
1804            let prompt = picker_prompt::prompt(
1805                "Where would you like to initialize this git repository?",
1806                worktree_directories,
1807                self.workspace.clone(),
1808                window,
1809                cx,
1810            );
1811
1812            cx.spawn(|_, _| async move { prompt.await.map(|ix| worktrees[ix].clone()) })
1813        };
1814
1815        cx.spawn_in(window, |this, mut cx| async move {
1816            let worktree = match worktree.await {
1817                Some(worktree) => worktree,
1818                None => {
1819                    return;
1820                }
1821            };
1822
1823            let Ok(result) = this.update(&mut cx, |this, cx| {
1824                let fallback_branch_name = GitPanelSettings::get_global(cx)
1825                    .fallback_branch_name
1826                    .clone();
1827                this.project.read(cx).git_init(
1828                    worktree.read(cx).abs_path(),
1829                    fallback_branch_name,
1830                    cx,
1831                )
1832            }) else {
1833                return;
1834            };
1835
1836            let result = result.await;
1837
1838            this.update_in(&mut cx, |this, _, cx| match result {
1839                Ok(()) => {}
1840                Err(e) => this.show_error_toast("init", e, cx),
1841            })
1842            .ok();
1843        })
1844        .detach();
1845    }
1846
1847    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1848        if !self.can_push_and_pull(cx) {
1849            return;
1850        }
1851        let Some(repo) = self.active_repository.clone() else {
1852            return;
1853        };
1854        let Some(branch) = repo.read(cx).current_branch() else {
1855            return;
1856        };
1857        telemetry::event!("Git Pulled");
1858        let branch = branch.clone();
1859        let remote = self.get_current_remote(window, cx);
1860        cx.spawn_in(window, move |this, mut cx| async move {
1861            let remote = match remote.await {
1862                Ok(Some(remote)) => remote,
1863                Ok(None) => {
1864                    return Ok(());
1865                }
1866                Err(e) => {
1867                    log::error!("Failed to get current remote: {}", e);
1868                    this.update(&mut cx, |this, cx| this.show_error_toast("pull", e, cx))
1869                        .ok();
1870                    return Ok(());
1871                }
1872            };
1873
1874            let askpass = this.update_in(&mut cx, |this, window, cx| {
1875                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1876            })?;
1877
1878            let guard = this
1879                .update(&mut cx, |this, _| this.start_remote_operation())
1880                .ok();
1881
1882            let pull = repo.update(&mut cx, |repo, cx| {
1883                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1884            })?;
1885
1886            let remote_message = pull.await?;
1887            drop(guard);
1888
1889            let action = RemoteAction::Pull(remote);
1890            this.update(&mut cx, |this, cx| match remote_message {
1891                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1892                Err(e) => {
1893                    log::error!("Error while pulling {:?}", e);
1894                    this.show_error_toast(action.name(), e, cx)
1895                }
1896            })
1897            .ok();
1898
1899            anyhow::Ok(())
1900        })
1901        .detach_and_log_err(cx);
1902    }
1903
1904    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1905        if !self.can_push_and_pull(cx) {
1906            return;
1907        }
1908        let Some(repo) = self.active_repository.clone() else {
1909            return;
1910        };
1911        let Some(branch) = repo.read(cx).current_branch() else {
1912            return;
1913        };
1914        telemetry::event!("Git Pushed");
1915        let branch = branch.clone();
1916
1917        let options = if force_push {
1918            Some(PushOptions::Force)
1919        } else {
1920            match branch.upstream {
1921                Some(Upstream {
1922                    tracking: UpstreamTracking::Gone,
1923                    ..
1924                })
1925                | None => Some(PushOptions::SetUpstream),
1926                _ => None,
1927            }
1928        };
1929        let remote = self.get_current_remote(window, cx);
1930
1931        cx.spawn_in(window, move |this, mut cx| async move {
1932            let remote = match remote.await {
1933                Ok(Some(remote)) => remote,
1934                Ok(None) => {
1935                    return Ok(());
1936                }
1937                Err(e) => {
1938                    log::error!("Failed to get current remote: {}", e);
1939                    this.update(&mut cx, |this, cx| this.show_error_toast("push", e, cx))
1940                        .ok();
1941                    return Ok(());
1942                }
1943            };
1944
1945            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1946                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1947            })?;
1948
1949            let guard = this
1950                .update(&mut cx, |this, _| this.start_remote_operation())
1951                .ok();
1952
1953            let push = repo.update(&mut cx, |repo, cx| {
1954                repo.push(
1955                    branch.name.clone(),
1956                    remote.name.clone(),
1957                    options,
1958                    askpass_delegate,
1959                    cx,
1960                )
1961            })?;
1962
1963            let remote_output = push.await?;
1964            drop(guard);
1965
1966            let action = RemoteAction::Push(branch.name, remote);
1967            this.update(&mut cx, |this, cx| match remote_output {
1968                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1969                Err(e) => {
1970                    log::error!("Error while pushing {:?}", e);
1971                    this.show_error_toast(action.name(), e, cx)
1972                }
1973            })?;
1974
1975            anyhow::Ok(())
1976        })
1977        .detach_and_log_err(cx);
1978    }
1979
1980    fn askpass_delegate(
1981        &self,
1982        operation: impl Into<SharedString>,
1983        window: &mut Window,
1984        cx: &mut Context<Self>,
1985    ) -> AskPassDelegate {
1986        let this = cx.weak_entity();
1987        let operation = operation.into();
1988        let window = window.window_handle();
1989        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1990            window
1991                .update(cx, |_, window, cx| {
1992                    this.update(cx, |this, cx| {
1993                        this.workspace.update(cx, |workspace, cx| {
1994                            workspace.toggle_modal(window, cx, |window, cx| {
1995                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1996                            });
1997                        })
1998                    })
1999                })
2000                .ok();
2001        })
2002    }
2003
2004    fn can_push_and_pull(&self, cx: &App) -> bool {
2005        crate::can_push_and_pull(&self.project, cx)
2006    }
2007
2008    fn get_current_remote(
2009        &mut self,
2010        window: &mut Window,
2011        cx: &mut Context<Self>,
2012    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
2013        let repo = self.active_repository.clone();
2014        let workspace = self.workspace.clone();
2015        let mut cx = window.to_async(cx);
2016
2017        async move {
2018            let Some(repo) = repo else {
2019                return Err(anyhow::anyhow!("No active repository"));
2020            };
2021
2022            let mut current_remotes: Vec<Remote> = repo
2023                .update(&mut cx, |repo, _| {
2024                    let Some(current_branch) = repo.current_branch() else {
2025                        return Err(anyhow::anyhow!("No active branch"));
2026                    };
2027
2028                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
2029                })??
2030                .await??;
2031
2032            if current_remotes.len() == 0 {
2033                return Err(anyhow::anyhow!("No active remote"));
2034            } else if current_remotes.len() == 1 {
2035                return Ok(Some(current_remotes.pop().unwrap()));
2036            } else {
2037                let current_remotes: Vec<_> = current_remotes
2038                    .into_iter()
2039                    .map(|remotes| remotes.name)
2040                    .collect();
2041                let selection = cx
2042                    .update(|window, cx| {
2043                        picker_prompt::prompt(
2044                            "Pick which remote to push to",
2045                            current_remotes.clone(),
2046                            workspace,
2047                            window,
2048                            cx,
2049                        )
2050                    })?
2051                    .await;
2052
2053                Ok(selection.map(|selection| Remote {
2054                    name: current_remotes[selection].clone(),
2055                }))
2056            }
2057        }
2058    }
2059
2060    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2061        let mut new_co_authors = Vec::new();
2062        let project = self.project.read(cx);
2063
2064        let Some(room) = self
2065            .workspace
2066            .upgrade()
2067            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2068        else {
2069            return Vec::default();
2070        };
2071
2072        let room = room.read(cx);
2073
2074        for (peer_id, collaborator) in project.collaborators() {
2075            if collaborator.is_host {
2076                continue;
2077            }
2078
2079            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2080                continue;
2081            };
2082            if participant.can_write() && participant.user.email.is_some() {
2083                let email = participant.user.email.clone().unwrap();
2084
2085                new_co_authors.push((
2086                    participant
2087                        .user
2088                        .name
2089                        .clone()
2090                        .unwrap_or_else(|| participant.user.github_login.clone()),
2091                    email,
2092                ))
2093            }
2094        }
2095        if !project.is_local() && !project.is_read_only(cx) {
2096            if let Some(user) = room.local_participant_user(cx) {
2097                if let Some(email) = user.email.clone() {
2098                    new_co_authors.push((
2099                        user.name
2100                            .clone()
2101                            .unwrap_or_else(|| user.github_login.clone()),
2102                        email.clone(),
2103                    ))
2104                }
2105            }
2106        }
2107        new_co_authors
2108    }
2109
2110    fn toggle_fill_co_authors(
2111        &mut self,
2112        _: &ToggleFillCoAuthors,
2113        _: &mut Window,
2114        cx: &mut Context<Self>,
2115    ) {
2116        self.add_coauthors = !self.add_coauthors;
2117        cx.notify();
2118    }
2119
2120    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2121        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2122
2123        let existing_text = message.to_ascii_lowercase();
2124        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2125        let mut ends_with_co_authors = false;
2126        let existing_co_authors = existing_text
2127            .lines()
2128            .filter_map(|line| {
2129                let line = line.trim();
2130                if line.starts_with(&lowercase_co_author_prefix) {
2131                    ends_with_co_authors = true;
2132                    Some(line)
2133                } else {
2134                    ends_with_co_authors = false;
2135                    None
2136                }
2137            })
2138            .collect::<HashSet<_>>();
2139
2140        let new_co_authors = self
2141            .potential_co_authors(cx)
2142            .into_iter()
2143            .filter(|(_, email)| {
2144                !existing_co_authors
2145                    .iter()
2146                    .any(|existing| existing.contains(email.as_str()))
2147            })
2148            .collect::<Vec<_>>();
2149
2150        if new_co_authors.is_empty() {
2151            return;
2152        }
2153
2154        if !ends_with_co_authors {
2155            message.push('\n');
2156        }
2157        for (name, email) in new_co_authors {
2158            message.push('\n');
2159            message.push_str(CO_AUTHOR_PREFIX);
2160            message.push_str(&name);
2161            message.push_str(" <");
2162            message.push_str(&email);
2163            message.push('>');
2164        }
2165        message.push('\n');
2166    }
2167
2168    fn schedule_update(
2169        &mut self,
2170        clear_pending: bool,
2171        window: &mut Window,
2172        cx: &mut Context<Self>,
2173    ) {
2174        let handle = cx.entity().downgrade();
2175        self.reopen_commit_buffer(window, cx);
2176        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
2177            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2178            if let Some(git_panel) = handle.upgrade() {
2179                git_panel
2180                    .update_in(&mut cx, |git_panel, window, cx| {
2181                        if clear_pending {
2182                            git_panel.clear_pending();
2183                        }
2184                        git_panel.update_visible_entries(cx);
2185                        git_panel.update_scrollbar_properties(window, cx);
2186                    })
2187                    .ok();
2188            }
2189        });
2190    }
2191
2192    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2193        let Some(active_repo) = self.active_repository.as_ref() else {
2194            return;
2195        };
2196        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2197            let project = self.project.read(cx);
2198            active_repo.open_commit_buffer(
2199                Some(project.languages().clone()),
2200                project.buffer_store().clone(),
2201                cx,
2202            )
2203        });
2204
2205        cx.spawn_in(window, |git_panel, mut cx| async move {
2206            let buffer = load_buffer.await?;
2207            git_panel.update_in(&mut cx, |git_panel, window, cx| {
2208                if git_panel
2209                    .commit_editor
2210                    .read(cx)
2211                    .buffer()
2212                    .read(cx)
2213                    .as_singleton()
2214                    .as_ref()
2215                    != Some(&buffer)
2216                {
2217                    git_panel.commit_editor = cx.new(|cx| {
2218                        commit_message_editor(
2219                            buffer,
2220                            git_panel.suggest_commit_message(cx).as_deref(),
2221                            git_panel.project.clone(),
2222                            true,
2223                            window,
2224                            cx,
2225                        )
2226                    });
2227                }
2228            })
2229        })
2230        .detach_and_log_err(cx);
2231    }
2232
2233    fn clear_pending(&mut self) {
2234        self.pending.retain(|v| !v.finished)
2235    }
2236
2237    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2238        self.entries.clear();
2239        self.single_staged_entry.take();
2240        self.single_tracked_entry.take();
2241        self.conflicted_count = 0;
2242        self.conflicted_staged_count = 0;
2243        self.new_count = 0;
2244        self.tracked_count = 0;
2245        self.new_staged_count = 0;
2246        self.tracked_staged_count = 0;
2247        self.entry_count = 0;
2248
2249        let mut changed_entries = Vec::new();
2250        let mut new_entries = Vec::new();
2251        let mut conflict_entries = Vec::new();
2252        let mut last_staged = None;
2253        let mut staged_count = 0;
2254        let mut max_width_item: Option<(RepoPath, usize)> = None;
2255
2256        let Some(repo) = self.active_repository.as_ref() else {
2257            // Just clear entries if no repository is active.
2258            cx.notify();
2259            return;
2260        };
2261
2262        let repo = repo.read(cx);
2263
2264        for entry in repo.status() {
2265            let is_conflict = repo.has_conflict(&entry.repo_path);
2266            let is_new = entry.status.is_created();
2267            let staging = entry.status.staging();
2268
2269            if self.pending.iter().any(|pending| {
2270                pending.target_status == TargetStatus::Reverted
2271                    && !pending.finished
2272                    && pending
2273                        .entries
2274                        .iter()
2275                        .any(|pending| pending.repo_path == entry.repo_path)
2276            }) {
2277                continue;
2278            }
2279
2280            // dot_git_abs path always has at least one component, namely .git.
2281            let abs_path = repo
2282                .dot_git_abs_path
2283                .parent()
2284                .unwrap()
2285                .join(&entry.repo_path);
2286            let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2287            let entry = GitStatusEntry {
2288                repo_path: entry.repo_path.clone(),
2289                worktree_path,
2290                abs_path,
2291                status: entry.status,
2292                staging,
2293            };
2294
2295            if staging.has_staged() {
2296                staged_count += 1;
2297                last_staged = Some(entry.clone());
2298            }
2299
2300            let width_estimate = Self::item_width_estimate(
2301                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2302                entry.display_name().len(),
2303            );
2304
2305            match max_width_item.as_mut() {
2306                Some((repo_path, estimate)) => {
2307                    if width_estimate > *estimate {
2308                        *repo_path = entry.repo_path.clone();
2309                        *estimate = width_estimate;
2310                    }
2311                }
2312                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2313            }
2314
2315            if is_conflict {
2316                conflict_entries.push(entry);
2317            } else if is_new {
2318                new_entries.push(entry);
2319            } else {
2320                changed_entries.push(entry);
2321            }
2322        }
2323
2324        let mut pending_staged_count = 0;
2325        let mut last_pending_staged = None;
2326        let mut pending_status_for_last_staged = None;
2327        for pending in self.pending.iter() {
2328            if pending.target_status == TargetStatus::Staged {
2329                pending_staged_count += pending.entries.len();
2330                last_pending_staged = pending.entries.iter().next().cloned();
2331            }
2332            if let Some(last_staged) = &last_staged {
2333                if pending
2334                    .entries
2335                    .iter()
2336                    .any(|entry| entry.repo_path == last_staged.repo_path)
2337                {
2338                    pending_status_for_last_staged = Some(pending.target_status);
2339                }
2340            }
2341        }
2342
2343        if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2344            match pending_status_for_last_staged {
2345                Some(TargetStatus::Staged) | None => {
2346                    self.single_staged_entry = last_staged;
2347                }
2348                _ => {}
2349            }
2350        } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2351            self.single_staged_entry = last_pending_staged;
2352        }
2353
2354        if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2355            self.single_tracked_entry = changed_entries.first().cloned();
2356        }
2357
2358        if conflict_entries.len() > 0 {
2359            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2360                header: Section::Conflict,
2361            }));
2362            self.entries.extend(
2363                conflict_entries
2364                    .into_iter()
2365                    .map(GitListEntry::GitStatusEntry),
2366            );
2367        }
2368
2369        if changed_entries.len() > 0 {
2370            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2371                header: Section::Tracked,
2372            }));
2373            self.entries.extend(
2374                changed_entries
2375                    .into_iter()
2376                    .map(GitListEntry::GitStatusEntry),
2377            );
2378        }
2379        if new_entries.len() > 0 {
2380            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2381                header: Section::New,
2382            }));
2383            self.entries
2384                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2385        }
2386
2387        if let Some((repo_path, _)) = max_width_item {
2388            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2389                GitListEntry::GitStatusEntry(git_status_entry) => {
2390                    git_status_entry.repo_path == repo_path
2391                }
2392                GitListEntry::Header(_) => false,
2393            });
2394        }
2395
2396        self.update_counts(repo);
2397
2398        self.select_first_entry_if_none(cx);
2399
2400        let suggested_commit_message = self.suggest_commit_message(cx);
2401        let placeholder_text = suggested_commit_message
2402            .as_deref()
2403            .unwrap_or("Enter commit message");
2404
2405        self.commit_editor.update(cx, |editor, cx| {
2406            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2407        });
2408
2409        cx.notify();
2410    }
2411
2412    fn header_state(&self, header_type: Section) -> ToggleState {
2413        let (staged_count, count) = match header_type {
2414            Section::New => (self.new_staged_count, self.new_count),
2415            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2416            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2417        };
2418        if staged_count == 0 {
2419            ToggleState::Unselected
2420        } else if count == staged_count {
2421            ToggleState::Selected
2422        } else {
2423            ToggleState::Indeterminate
2424        }
2425    }
2426
2427    fn update_counts(&mut self, repo: &Repository) {
2428        self.conflicted_count = 0;
2429        self.conflicted_staged_count = 0;
2430        self.new_count = 0;
2431        self.tracked_count = 0;
2432        self.new_staged_count = 0;
2433        self.tracked_staged_count = 0;
2434        self.entry_count = 0;
2435        for entry in &self.entries {
2436            let Some(status_entry) = entry.status_entry() else {
2437                continue;
2438            };
2439            self.entry_count += 1;
2440            if repo.has_conflict(&status_entry.repo_path) {
2441                self.conflicted_count += 1;
2442                if self.entry_staging(status_entry).has_staged() {
2443                    self.conflicted_staged_count += 1;
2444                }
2445            } else if status_entry.status.is_created() {
2446                self.new_count += 1;
2447                if self.entry_staging(status_entry).has_staged() {
2448                    self.new_staged_count += 1;
2449                }
2450            } else {
2451                self.tracked_count += 1;
2452                if self.entry_staging(status_entry).has_staged() {
2453                    self.tracked_staged_count += 1;
2454                }
2455            }
2456        }
2457    }
2458
2459    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2460        for pending in self.pending.iter().rev() {
2461            if pending
2462                .entries
2463                .iter()
2464                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2465            {
2466                match pending.target_status {
2467                    TargetStatus::Staged => return StageStatus::Staged,
2468                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2469                    TargetStatus::Reverted => continue,
2470                    TargetStatus::Unchanged => continue,
2471                }
2472            }
2473        }
2474        entry.staging
2475    }
2476
2477    pub(crate) fn has_staged_changes(&self) -> bool {
2478        self.tracked_staged_count > 0
2479            || self.new_staged_count > 0
2480            || self.conflicted_staged_count > 0
2481    }
2482
2483    pub(crate) fn has_unstaged_changes(&self) -> bool {
2484        self.tracked_count > self.tracked_staged_count
2485            || self.new_count > self.new_staged_count
2486            || self.conflicted_count > self.conflicted_staged_count
2487    }
2488
2489    fn has_conflicts(&self) -> bool {
2490        self.conflicted_count > 0
2491    }
2492
2493    fn has_tracked_changes(&self) -> bool {
2494        self.tracked_count > 0
2495    }
2496
2497    pub fn has_unstaged_conflicts(&self) -> bool {
2498        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2499    }
2500
2501    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2502        let action = action.into();
2503        let Some(workspace) = self.workspace.upgrade() else {
2504            return;
2505        };
2506
2507        let message = e.to_string().trim().to_string();
2508        if message
2509            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2510            .next()
2511            .is_some()
2512        {
2513            return; // Hide the cancelled by user message
2514        } else {
2515            let project = self.project.clone();
2516            workspace.update(cx, |workspace, cx| {
2517                let workspace_weak = cx.weak_entity();
2518                let toast =
2519                    StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2520                        this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2521                            .action("View Log", move |window, cx| {
2522                                let message = message.clone();
2523                                let project = project.clone();
2524                                let action = action.clone();
2525                                workspace_weak
2526                                    .update(cx, move |workspace, cx| {
2527                                        Self::open_output(
2528                                            project, action, workspace, &message, window, cx,
2529                                        )
2530                                    })
2531                                    .ok();
2532                            })
2533                    });
2534                workspace.toggle_status_toast(toast, cx)
2535            });
2536        }
2537    }
2538
2539    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2540        let Some(workspace) = self.workspace.upgrade() else {
2541            return;
2542        };
2543
2544        workspace.update(cx, |workspace, cx| {
2545            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2546            let workspace_weak = cx.weak_entity();
2547            let operation = action.name();
2548
2549            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2550                use remote_output::SuccessStyle::*;
2551                let project = self.project.clone();
2552                match style {
2553                    Toast { .. } => this,
2554                    ToastWithLog { output } => this
2555                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2556                        .action("View Log", move |window, cx| {
2557                            let output = output.clone();
2558                            let project = project.clone();
2559                            let output =
2560                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2561                            workspace_weak
2562                                .update(cx, move |workspace, cx| {
2563                                    Self::open_output(
2564                                        project, operation, workspace, &output, window, cx,
2565                                    )
2566                                })
2567                                .ok();
2568                        }),
2569                    PushPrLink { link } => this
2570                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2571                        .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2572                }
2573            });
2574            workspace.toggle_status_toast(status_toast, cx)
2575        });
2576    }
2577
2578    fn open_output(
2579        project: Entity<Project>,
2580        operation: impl Into<SharedString>,
2581        workspace: &mut Workspace,
2582        output: &str,
2583        window: &mut Window,
2584        cx: &mut Context<Workspace>,
2585    ) {
2586        let operation = operation.into();
2587        let buffer = cx.new(|cx| Buffer::local(output, cx));
2588        let editor = cx.new(|cx| {
2589            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2590            editor.buffer().update(cx, |buffer, cx| {
2591                buffer.set_title(format!("Output from git {operation}"), cx);
2592            });
2593            editor.set_read_only(true);
2594            editor
2595        });
2596
2597        workspace.add_item_to_center(Box::new(editor), window, cx);
2598    }
2599
2600    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2601        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2602            Icon::new(IconName::ArrowCircle)
2603                .size(IconSize::XSmall)
2604                .color(Color::Info)
2605                .with_animation(
2606                    "arrow-circle",
2607                    Animation::new(Duration::from_secs(2)).repeat(),
2608                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2609                )
2610                .into_any_element()
2611        })
2612    }
2613
2614    pub fn can_commit(&self) -> bool {
2615        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2616    }
2617
2618    pub fn can_stage_all(&self) -> bool {
2619        self.has_unstaged_changes()
2620    }
2621
2622    pub fn can_unstage_all(&self) -> bool {
2623        self.has_staged_changes()
2624    }
2625
2626    // eventually we'll need to take depth into account here
2627    // if we add a tree view
2628    fn item_width_estimate(path: usize, file_name: usize) -> usize {
2629        path + file_name
2630    }
2631
2632    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2633        let focus_handle = self.focus_handle.clone();
2634        PopoverMenu::new(id.into())
2635            .trigger(
2636                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2637                    .icon_size(IconSize::Small)
2638                    .icon_color(Color::Muted),
2639            )
2640            .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
2641            .anchor(Corner::TopRight)
2642    }
2643
2644    pub(crate) fn render_generate_commit_message_button(
2645        &self,
2646        cx: &Context<Self>,
2647    ) -> Option<AnyElement> {
2648        current_language_model(cx).is_some().then(|| {
2649            if self.generate_commit_message_task.is_some() {
2650                return h_flex()
2651                    .gap_1()
2652                    .child(
2653                        Icon::new(IconName::ArrowCircle)
2654                            .size(IconSize::XSmall)
2655                            .color(Color::Info)
2656                            .with_animation(
2657                                "arrow-circle",
2658                                Animation::new(Duration::from_secs(2)).repeat(),
2659                                |icon, delta| {
2660                                    icon.transform(Transformation::rotate(percentage(delta)))
2661                                },
2662                            ),
2663                    )
2664                    .child(
2665                        Label::new("Generating Commit...")
2666                            .size(LabelSize::Small)
2667                            .color(Color::Muted),
2668                    )
2669                    .into_any_element();
2670            }
2671
2672            let can_commit = self.can_commit();
2673            let editor_focus_handle = self.commit_editor.focus_handle(cx);
2674            IconButton::new("generate-commit-message", IconName::AiEdit)
2675                .shape(ui::IconButtonShape::Square)
2676                .icon_color(Color::Muted)
2677                .tooltip(move |window, cx| {
2678                    if can_commit {
2679                        Tooltip::for_action_in(
2680                            "Generate Commit Message",
2681                            &git::GenerateCommitMessage,
2682                            &editor_focus_handle,
2683                            window,
2684                            cx,
2685                        )
2686                    } else {
2687                        Tooltip::simple("No changes to commit", cx)
2688                    }
2689                })
2690                .disabled(!can_commit)
2691                .on_click(cx.listener(move |this, _event, _window, cx| {
2692                    this.generate_commit_message(cx);
2693                }))
2694                .into_any_element()
2695        })
2696    }
2697
2698    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2699        let potential_co_authors = self.potential_co_authors(cx);
2700        if potential_co_authors.is_empty() {
2701            None
2702        } else {
2703            Some(
2704                IconButton::new("co-authors", IconName::Person)
2705                    .shape(ui::IconButtonShape::Square)
2706                    .icon_color(Color::Disabled)
2707                    .selected_icon_color(Color::Selected)
2708                    .toggle_state(self.add_coauthors)
2709                    .tooltip(move |_, cx| {
2710                        let title = format!(
2711                            "Add co-authored-by:{}{}",
2712                            if potential_co_authors.len() == 1 {
2713                                ""
2714                            } else {
2715                                "\n"
2716                            },
2717                            potential_co_authors
2718                                .iter()
2719                                .map(|(name, email)| format!(" {} <{}>", name, email))
2720                                .join("\n")
2721                        );
2722                        Tooltip::simple(title, cx)
2723                    })
2724                    .on_click(cx.listener(|this, _, _, cx| {
2725                        this.add_coauthors = !this.add_coauthors;
2726                        cx.notify();
2727                    }))
2728                    .into_any_element(),
2729            )
2730        }
2731    }
2732
2733    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2734        if self.has_unstaged_conflicts() {
2735            (false, "You must resolve conflicts before committing")
2736        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2737            (false, "No changes to commit")
2738        } else if self.pending_commit.is_some() {
2739            (false, "Commit in progress")
2740        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2741            (false, "No commit message")
2742        } else if !self.has_write_access(cx) {
2743            (false, "You do not have write access to this project")
2744        } else {
2745            (true, self.commit_button_title())
2746        }
2747    }
2748
2749    pub fn commit_button_title(&self) -> &'static str {
2750        if self.has_staged_changes() {
2751            "Commit"
2752        } else {
2753            "Commit Tracked"
2754        }
2755    }
2756
2757    fn expand_commit_editor(
2758        &mut self,
2759        _: &git::ExpandCommitEditor,
2760        window: &mut Window,
2761        cx: &mut Context<Self>,
2762    ) {
2763        let workspace = self.workspace.clone();
2764        window.defer(cx, move |window, cx| {
2765            workspace
2766                .update(cx, |workspace, cx| {
2767                    CommitModal::toggle(workspace, window, cx)
2768                })
2769                .ok();
2770        })
2771    }
2772
2773    fn render_panel_header(
2774        &self,
2775        window: &mut Window,
2776        cx: &mut Context<Self>,
2777    ) -> Option<impl IntoElement> {
2778        self.active_repository.as_ref()?;
2779
2780        let text;
2781        let action;
2782        let tooltip;
2783        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2784            text = "Unstage All";
2785            action = git::UnstageAll.boxed_clone();
2786            tooltip = "git reset";
2787        } else {
2788            text = "Stage All";
2789            action = git::StageAll.boxed_clone();
2790            tooltip = "git add --all ."
2791        }
2792
2793        let change_string = match self.entry_count {
2794            0 => "No Changes".to_string(),
2795            1 => "1 Change".to_string(),
2796            _ => format!("{} Changes", self.entry_count),
2797        };
2798
2799        Some(
2800            self.panel_header_container(window, cx)
2801                .px_2()
2802                .child(
2803                    panel_button(change_string)
2804                        .color(Color::Muted)
2805                        .tooltip(Tooltip::for_action_title_in(
2806                            "Open diff",
2807                            &Diff,
2808                            &self.focus_handle,
2809                        ))
2810                        .on_click(|_, _, cx| {
2811                            cx.defer(|cx| {
2812                                cx.dispatch_action(&Diff);
2813                            })
2814                        }),
2815                )
2816                .child(div().flex_grow()) // spacer
2817                .child(self.render_overflow_menu("overflow_menu"))
2818                .child(div().w_2()) // another spacer
2819                .child(
2820                    panel_filled_button(text)
2821                        .tooltip(Tooltip::for_action_title_in(
2822                            tooltip,
2823                            action.as_ref(),
2824                            &self.focus_handle,
2825                        ))
2826                        .disabled(self.entry_count == 0)
2827                        .on_click(move |_, _, cx| {
2828                            let action = action.boxed_clone();
2829                            cx.defer(move |cx| {
2830                                cx.dispatch_action(action.as_ref());
2831                            })
2832                        }),
2833                ),
2834        )
2835    }
2836
2837    pub fn render_footer(
2838        &self,
2839        window: &mut Window,
2840        cx: &mut Context<Self>,
2841    ) -> Option<impl IntoElement> {
2842        let active_repository = self.active_repository.clone()?;
2843        let (can_commit, tooltip) = self.configure_commit_button(cx);
2844        let project = self.project.clone().read(cx);
2845        let panel_editor_style = panel_editor_style(true, window, cx);
2846
2847        let enable_coauthors = self.render_co_authors(cx);
2848        let title = self.commit_button_title();
2849
2850        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2851        let commit_tooltip_focus_handle = editor_focus_handle.clone();
2852        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2853
2854        let branch = active_repository.read(cx).current_branch().cloned();
2855
2856        let footer_size = px(32.);
2857        let gap = px(9.0);
2858        let max_height = panel_editor_style
2859            .text
2860            .line_height_in_pixels(window.rem_size())
2861            * MAX_PANEL_EDITOR_LINES
2862            + gap;
2863
2864        let git_panel = cx.entity().clone();
2865        let display_name = SharedString::from(Arc::from(
2866            active_repository
2867                .read(cx)
2868                .display_name(project, cx)
2869                .trim_end_matches("/"),
2870        ));
2871        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2872            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
2873        });
2874
2875        let footer = v_flex()
2876            .child(PanelRepoFooter::new(
2877                "footer-button",
2878                display_name,
2879                branch,
2880                Some(git_panel),
2881            ))
2882            .child(
2883                panel_editor_container(window, cx)
2884                    .id("commit-editor-container")
2885                    .relative()
2886                    .w_full()
2887                    .h(max_height + footer_size)
2888                    .border_t_1()
2889                    .border_color(cx.theme().colors().border_variant)
2890                    .cursor_text()
2891                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2892                        window.focus(&this.commit_editor.focus_handle(cx));
2893                    }))
2894                    .child(
2895                        h_flex()
2896                            .id("commit-footer")
2897                            .border_t_1()
2898                            .when(editor_is_long, |el| {
2899                                el.border_color(cx.theme().colors().border_variant)
2900                            })
2901                            .absolute()
2902                            .bottom_0()
2903                            .left_0()
2904                            .w_full()
2905                            .px_2()
2906                            .h(footer_size)
2907                            .flex_none()
2908                            .justify_between()
2909                            .child(
2910                                self.render_generate_commit_message_button(cx)
2911                                    .unwrap_or_else(|| div().into_any_element()),
2912                            )
2913                            .child(
2914                                h_flex().gap_0p5().children(enable_coauthors).child(
2915                                    panel_filled_button(title)
2916                                        .tooltip(move |window, cx| {
2917                                            if can_commit {
2918                                                Tooltip::for_action_in(
2919                                                    tooltip,
2920                                                    &Commit,
2921                                                    &commit_tooltip_focus_handle,
2922                                                    window,
2923                                                    cx,
2924                                                )
2925                                            } else {
2926                                                Tooltip::simple(tooltip, cx)
2927                                            }
2928                                        })
2929                                        .disabled(!can_commit || self.modal_open)
2930                                        .on_click({
2931                                            cx.listener(move |this, _: &ClickEvent, window, cx| {
2932                                                telemetry::event!(
2933                                                    "Git Committed",
2934                                                    source = "Git Panel"
2935                                                );
2936                                                this.commit_changes(window, cx)
2937                                            })
2938                                        }),
2939                                ),
2940                            ),
2941                    )
2942                    .child(
2943                        div()
2944                            .pr_2p5()
2945                            .on_action(|&editor::actions::MoveUp, _, cx| {
2946                                cx.stop_propagation();
2947                            })
2948                            .on_action(|&editor::actions::MoveDown, _, cx| {
2949                                cx.stop_propagation();
2950                            })
2951                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2952                    )
2953                    .child(
2954                        h_flex()
2955                            .absolute()
2956                            .top_2()
2957                            .right_2()
2958                            .opacity(0.5)
2959                            .hover(|this| this.opacity(1.0))
2960                            .child(
2961                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2962                                    .icon_size(IconSize::Small)
2963                                    .size(ui::ButtonSize::Default)
2964                                    .tooltip(move |window, cx| {
2965                                        Tooltip::for_action_in(
2966                                            "Open Commit Modal",
2967                                            &git::ExpandCommitEditor,
2968                                            &expand_tooltip_focus_handle,
2969                                            window,
2970                                            cx,
2971                                        )
2972                                    })
2973                                    .on_click(cx.listener({
2974                                        move |_, _, window, cx| {
2975                                            window.dispatch_action(
2976                                                git::ExpandCommitEditor.boxed_clone(),
2977                                                cx,
2978                                            )
2979                                        }
2980                                    })),
2981                            ),
2982                    ),
2983            );
2984
2985        Some(footer)
2986    }
2987
2988    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2989        let active_repository = self.active_repository.as_ref()?;
2990        let branch = active_repository.read(cx).current_branch()?;
2991        let commit = branch.most_recent_commit.as_ref()?.clone();
2992
2993        let this = cx.entity();
2994        Some(
2995            h_flex()
2996                .items_center()
2997                .py_2()
2998                .px(px(8.))
2999                .border_color(cx.theme().colors().border)
3000                .gap_1p5()
3001                .child(
3002                    div()
3003                        .flex_grow()
3004                        .overflow_hidden()
3005                        .items_center()
3006                        .max_w(relative(0.85))
3007                        .h_full()
3008                        .child(
3009                            Label::new(commit.subject.clone())
3010                                .size(LabelSize::Small)
3011                                .truncate(),
3012                        )
3013                        .id("commit-msg-hover")
3014                        .hoverable_tooltip(move |window, cx| {
3015                            GitPanelMessageTooltip::new(
3016                                this.clone(),
3017                                commit.sha.clone(),
3018                                window,
3019                                cx,
3020                            )
3021                            .into()
3022                        }),
3023                )
3024                .child(div().flex_1())
3025                .when(commit.has_parent, |this| {
3026                    let has_unstaged = self.has_unstaged_changes();
3027                    this.child(
3028                        panel_icon_button("undo", IconName::Undo)
3029                            .icon_size(IconSize::Small)
3030                            .icon_color(Color::Muted)
3031                            .tooltip(move |window, cx| {
3032                                Tooltip::with_meta(
3033                                    "Uncommit",
3034                                    Some(&git::Uncommit),
3035                                    if has_unstaged {
3036                                        "git reset HEAD^ --soft"
3037                                    } else {
3038                                        "git reset HEAD^"
3039                                    },
3040                                    window,
3041                                    cx,
3042                                )
3043                            })
3044                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3045                    )
3046                }),
3047        )
3048    }
3049
3050    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3051        h_flex()
3052            .h_full()
3053            .flex_grow()
3054            .justify_center()
3055            .items_center()
3056            .child(
3057                v_flex()
3058                    .gap_2()
3059                    .child(h_flex().w_full().justify_around().child(
3060                        if self.active_repository.is_some() {
3061                            "No changes to commit"
3062                        } else {
3063                            "No Git repositories"
3064                        },
3065                    ))
3066                    .children({
3067                        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3068                        (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3069                            h_flex().w_full().justify_around().child(
3070                                panel_filled_button("Initialize Repository")
3071                                    .tooltip(Tooltip::for_action_title_in(
3072                                        "git init",
3073                                        &git::Init,
3074                                        &self.focus_handle,
3075                                    ))
3076                                    .on_click(move |_, _, cx| {
3077                                        cx.defer(move |cx| {
3078                                            cx.dispatch_action(&git::Init);
3079                                        })
3080                                    }),
3081                            )
3082                        })
3083                    })
3084                    .text_ui_sm(cx)
3085                    .mx_auto()
3086                    .text_color(Color::Placeholder.color(cx)),
3087            )
3088    }
3089
3090    fn render_vertical_scrollbar(
3091        &self,
3092        show_horizontal_scrollbar_container: bool,
3093        cx: &mut Context<Self>,
3094    ) -> impl IntoElement {
3095        div()
3096            .id("git-panel-vertical-scroll")
3097            .occlude()
3098            .flex_none()
3099            .h_full()
3100            .cursor_default()
3101            .absolute()
3102            .right_0()
3103            .top_0()
3104            .bottom_0()
3105            .w(px(12.))
3106            .when(show_horizontal_scrollbar_container, |this| {
3107                this.pb_neg_3p5()
3108            })
3109            .on_mouse_move(cx.listener(|_, _, _, cx| {
3110                cx.notify();
3111                cx.stop_propagation()
3112            }))
3113            .on_hover(|_, _, cx| {
3114                cx.stop_propagation();
3115            })
3116            .on_any_mouse_down(|_, _, cx| {
3117                cx.stop_propagation();
3118            })
3119            .on_mouse_up(
3120                MouseButton::Left,
3121                cx.listener(|this, _, window, cx| {
3122                    if !this.vertical_scrollbar.state.is_dragging()
3123                        && !this.focus_handle.contains_focused(window, cx)
3124                    {
3125                        this.vertical_scrollbar.hide(window, cx);
3126                        cx.notify();
3127                    }
3128
3129                    cx.stop_propagation();
3130                }),
3131            )
3132            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3133                cx.notify();
3134            }))
3135            .children(Scrollbar::vertical(
3136                // percentage as f32..end_offset as f32,
3137                self.vertical_scrollbar.state.clone(),
3138            ))
3139    }
3140
3141    /// Renders the horizontal scrollbar.
3142    ///
3143    /// The right offset is used to determine how far to the right the
3144    /// scrollbar should extend to, useful for ensuring it doesn't collide
3145    /// with the vertical scrollbar when visible.
3146    fn render_horizontal_scrollbar(
3147        &self,
3148        right_offset: Pixels,
3149        cx: &mut Context<Self>,
3150    ) -> impl IntoElement {
3151        div()
3152            .id("git-panel-horizontal-scroll")
3153            .occlude()
3154            .flex_none()
3155            .w_full()
3156            .cursor_default()
3157            .absolute()
3158            .bottom_neg_px()
3159            .left_0()
3160            .right_0()
3161            .pr(right_offset)
3162            .on_mouse_move(cx.listener(|_, _, _, cx| {
3163                cx.notify();
3164                cx.stop_propagation()
3165            }))
3166            .on_hover(|_, _, cx| {
3167                cx.stop_propagation();
3168            })
3169            .on_any_mouse_down(|_, _, cx| {
3170                cx.stop_propagation();
3171            })
3172            .on_mouse_up(
3173                MouseButton::Left,
3174                cx.listener(|this, _, window, cx| {
3175                    if !this.horizontal_scrollbar.state.is_dragging()
3176                        && !this.focus_handle.contains_focused(window, cx)
3177                    {
3178                        this.horizontal_scrollbar.hide(window, cx);
3179                        cx.notify();
3180                    }
3181
3182                    cx.stop_propagation();
3183                }),
3184            )
3185            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3186                cx.notify();
3187            }))
3188            .children(Scrollbar::horizontal(
3189                // percentage as f32..end_offset as f32,
3190                self.horizontal_scrollbar.state.clone(),
3191            ))
3192    }
3193
3194    fn render_buffer_header_controls(
3195        &self,
3196        entity: &Entity<Self>,
3197        file: &Arc<dyn File>,
3198        _: &Window,
3199        cx: &App,
3200    ) -> Option<AnyElement> {
3201        let repo = self.active_repository.as_ref()?.read(cx);
3202        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
3203        let ix = self.entry_by_path(&repo_path)?;
3204        let entry = self.entries.get(ix)?;
3205
3206        let entry_staging = self.entry_staging(entry.status_entry()?);
3207
3208        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3209            .disabled(!self.has_write_access(cx))
3210            .fill()
3211            .elevation(ElevationIndex::Surface)
3212            .on_click({
3213                let entry = entry.clone();
3214                let git_panel = entity.downgrade();
3215                move |_, window, cx| {
3216                    git_panel
3217                        .update(cx, |this, cx| {
3218                            this.toggle_staged_for_entry(&entry, window, cx);
3219                            cx.stop_propagation();
3220                        })
3221                        .ok();
3222                }
3223            });
3224        Some(
3225            h_flex()
3226                .id("start-slot")
3227                .text_lg()
3228                .child(checkbox)
3229                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3230                    // prevent the list item active state triggering when toggling checkbox
3231                    cx.stop_propagation();
3232                })
3233                .into_any_element(),
3234        )
3235    }
3236
3237    fn render_entries(
3238        &self,
3239        has_write_access: bool,
3240        _: &Window,
3241        cx: &mut Context<Self>,
3242    ) -> impl IntoElement {
3243        let entry_count = self.entries.len();
3244
3245        let scroll_track_size = px(16.);
3246
3247        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3248            // magic number
3249            px(3.)
3250        } else {
3251            px(0.)
3252        };
3253
3254        v_flex()
3255            .flex_1()
3256            .size_full()
3257            .overflow_hidden()
3258            .relative()
3259            // Show a border on the top and bottom of the container when
3260            // the vertical scrollbar container is visible so we don't have a
3261            // floating left border in the panel.
3262            .when(self.vertical_scrollbar.show_track, |this| {
3263                this.border_t_1()
3264                    .border_b_1()
3265                    .border_color(cx.theme().colors().border)
3266            })
3267            .child(
3268                h_flex()
3269                    .flex_1()
3270                    .size_full()
3271                    .relative()
3272                    .overflow_hidden()
3273                    .child(
3274                        uniform_list(cx.entity().clone(), "entries", entry_count, {
3275                            move |this, range, window, cx| {
3276                                let mut items = Vec::with_capacity(range.end - range.start);
3277
3278                                for ix in range {
3279                                    match &this.entries.get(ix) {
3280                                        Some(GitListEntry::GitStatusEntry(entry)) => {
3281                                            items.push(this.render_entry(
3282                                                ix,
3283                                                entry,
3284                                                has_write_access,
3285                                                window,
3286                                                cx,
3287                                            ));
3288                                        }
3289                                        Some(GitListEntry::Header(header)) => {
3290                                            items.push(this.render_list_header(
3291                                                ix,
3292                                                header,
3293                                                has_write_access,
3294                                                window,
3295                                                cx,
3296                                            ));
3297                                        }
3298                                        None => {}
3299                                    }
3300                                }
3301
3302                                items
3303                            }
3304                        })
3305                        .size_full()
3306                        .flex_grow()
3307                        .with_sizing_behavior(ListSizingBehavior::Auto)
3308                        .with_horizontal_sizing_behavior(
3309                            ListHorizontalSizingBehavior::Unconstrained,
3310                        )
3311                        .with_width_from_item(self.max_width_item_index)
3312                        .track_scroll(self.scroll_handle.clone()),
3313                    )
3314                    .on_mouse_down(
3315                        MouseButton::Right,
3316                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3317                            this.deploy_panel_context_menu(event.position, window, cx)
3318                        }),
3319                    )
3320                    .when(self.vertical_scrollbar.show_track, |this| {
3321                        this.child(
3322                            v_flex()
3323                                .h_full()
3324                                .flex_none()
3325                                .w(scroll_track_size)
3326                                .bg(cx.theme().colors().panel_background)
3327                                .child(
3328                                    div()
3329                                        .size_full()
3330                                        .flex_1()
3331                                        .border_l_1()
3332                                        .border_color(cx.theme().colors().border),
3333                                ),
3334                        )
3335                    })
3336                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
3337                        this.child(
3338                            self.render_vertical_scrollbar(
3339                                self.horizontal_scrollbar.show_track,
3340                                cx,
3341                            ),
3342                        )
3343                    }),
3344            )
3345            .when(self.horizontal_scrollbar.show_track, |this| {
3346                this.child(
3347                    h_flex()
3348                        .w_full()
3349                        .h(scroll_track_size)
3350                        .flex_none()
3351                        .relative()
3352                        .child(
3353                            div()
3354                                .w_full()
3355                                .flex_1()
3356                                // for some reason the horizontal scrollbar is 1px
3357                                // taller than the vertical scrollbar??
3358                                .h(scroll_track_size - px(1.))
3359                                .bg(cx.theme().colors().panel_background)
3360                                .border_t_1()
3361                                .border_color(cx.theme().colors().border),
3362                        )
3363                        .when(self.vertical_scrollbar.show_track, |this| {
3364                            this.child(
3365                                div()
3366                                    .flex_none()
3367                                    // -1px prevents a missing pixel between the two container borders
3368                                    .w(scroll_track_size - px(1.))
3369                                    .h_full(),
3370                            )
3371                            .child(
3372                                // HACK: Fill the missing 1px 🥲
3373                                div()
3374                                    .absolute()
3375                                    .right(scroll_track_size - px(1.))
3376                                    .bottom(scroll_track_size - px(1.))
3377                                    .size_px()
3378                                    .bg(cx.theme().colors().border),
3379                            )
3380                        }),
3381                )
3382            })
3383            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3384                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3385            })
3386    }
3387
3388    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3389        Label::new(label.into()).color(color).single_line()
3390    }
3391
3392    fn list_item_height(&self) -> Rems {
3393        rems(1.75)
3394    }
3395
3396    fn render_list_header(
3397        &self,
3398        ix: usize,
3399        header: &GitHeaderEntry,
3400        _: bool,
3401        _: &Window,
3402        _: &Context<Self>,
3403    ) -> AnyElement {
3404        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3405
3406        h_flex()
3407            .id(id)
3408            .h(self.list_item_height())
3409            .w_full()
3410            .items_end()
3411            .px(rems(0.75)) // ~12px
3412            .pb(rems(0.3125)) // ~ 5px
3413            .child(
3414                Label::new(header.title())
3415                    .color(Color::Muted)
3416                    .size(LabelSize::Small)
3417                    .line_height_style(LineHeightStyle::UiLabel)
3418                    .single_line(),
3419            )
3420            .into_any_element()
3421    }
3422
3423    fn load_commit_details(
3424        &self,
3425        sha: String,
3426        cx: &mut Context<Self>,
3427    ) -> Task<anyhow::Result<CommitDetails>> {
3428        let Some(repo) = self.active_repository.clone() else {
3429            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3430        };
3431        repo.update(cx, |repo, cx| {
3432            let show = repo.show(sha);
3433            cx.spawn(|_, _| async move { show.await? })
3434        })
3435    }
3436
3437    fn deploy_entry_context_menu(
3438        &mut self,
3439        position: Point<Pixels>,
3440        ix: usize,
3441        window: &mut Window,
3442        cx: &mut Context<Self>,
3443    ) {
3444        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3445            return;
3446        };
3447        let stage_title = if entry.status.staging().is_fully_staged() {
3448            "Unstage File"
3449        } else {
3450            "Stage File"
3451        };
3452        let restore_title = if entry.status.is_created() {
3453            "Trash File"
3454        } else {
3455            "Restore File"
3456        };
3457        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3458            context_menu
3459                .context(self.focus_handle.clone())
3460                .action(stage_title, ToggleStaged.boxed_clone())
3461                .action(restore_title, git::RestoreFile.boxed_clone())
3462                .separator()
3463                .action("Open Diff", Confirm.boxed_clone())
3464                .action("Open File", SecondaryConfirm.boxed_clone())
3465        });
3466        self.selected_entry = Some(ix);
3467        self.set_context_menu(context_menu, position, window, cx);
3468    }
3469
3470    fn deploy_panel_context_menu(
3471        &mut self,
3472        position: Point<Pixels>,
3473        window: &mut Window,
3474        cx: &mut Context<Self>,
3475    ) {
3476        let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3477        self.set_context_menu(context_menu, position, window, cx);
3478    }
3479
3480    fn set_context_menu(
3481        &mut self,
3482        context_menu: Entity<ContextMenu>,
3483        position: Point<Pixels>,
3484        window: &Window,
3485        cx: &mut Context<Self>,
3486    ) {
3487        let subscription = cx.subscribe_in(
3488            &context_menu,
3489            window,
3490            |this, _, _: &DismissEvent, window, cx| {
3491                if this.context_menu.as_ref().is_some_and(|context_menu| {
3492                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3493                }) {
3494                    cx.focus_self(window);
3495                }
3496                this.context_menu.take();
3497                cx.notify();
3498            },
3499        );
3500        self.context_menu = Some((context_menu, position, subscription));
3501        cx.notify();
3502    }
3503
3504    fn render_entry(
3505        &self,
3506        ix: usize,
3507        entry: &GitStatusEntry,
3508        has_write_access: bool,
3509        window: &Window,
3510        cx: &Context<Self>,
3511    ) -> AnyElement {
3512        let display_name = entry.display_name();
3513
3514        let selected = self.selected_entry == Some(ix);
3515        let marked = self.marked_entries.contains(&ix);
3516        let status_style = GitPanelSettings::get_global(cx).status_style;
3517        let status = entry.status;
3518        let modifiers = self.current_modifiers;
3519        let shift_held = modifiers.shift;
3520
3521        let has_conflict = status.is_conflicted();
3522        let is_modified = status.is_modified();
3523        let is_deleted = status.is_deleted();
3524
3525        let label_color = if status_style == StatusStyle::LabelColor {
3526            if has_conflict {
3527                Color::Conflict
3528            } else if is_modified {
3529                Color::Modified
3530            } else if is_deleted {
3531                // We don't want a bunch of red labels in the list
3532                Color::Disabled
3533            } else {
3534                Color::Created
3535            }
3536        } else {
3537            Color::Default
3538        };
3539
3540        let path_color = if status.is_deleted() {
3541            Color::Disabled
3542        } else {
3543            Color::Muted
3544        };
3545
3546        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3547        let checkbox_wrapper_id: ElementId =
3548            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3549        let checkbox_id: ElementId =
3550            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3551
3552        let entry_staging = self.entry_staging(entry);
3553        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3554
3555        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3556            is_staged = ToggleState::Selected;
3557        }
3558
3559        let handle = cx.weak_entity();
3560
3561        let selected_bg_alpha = 0.08;
3562        let marked_bg_alpha = 0.12;
3563        let state_opacity_step = 0.04;
3564
3565        let base_bg = match (selected, marked) {
3566            (true, true) => cx
3567                .theme()
3568                .status()
3569                .info
3570                .alpha(selected_bg_alpha + marked_bg_alpha),
3571            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3572            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3573            _ => cx.theme().colors().ghost_element_background,
3574        };
3575
3576        let hover_bg = if selected {
3577            cx.theme()
3578                .status()
3579                .info
3580                .alpha(selected_bg_alpha + state_opacity_step)
3581        } else {
3582            cx.theme().colors().ghost_element_hover
3583        };
3584
3585        let active_bg = if selected {
3586            cx.theme()
3587                .status()
3588                .info
3589                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3590        } else {
3591            cx.theme().colors().ghost_element_active
3592        };
3593
3594        h_flex()
3595            .id(id)
3596            .h(self.list_item_height())
3597            .w_full()
3598            .items_center()
3599            .border_1()
3600            .when(selected && self.focus_handle.is_focused(window), |el| {
3601                el.border_color(cx.theme().colors().border_focused)
3602            })
3603            .px(rems(0.75)) // ~12px
3604            .overflow_hidden()
3605            .flex_none()
3606            .gap_1p5()
3607            .bg(base_bg)
3608            .hover(|this| this.bg(hover_bg))
3609            .active(|this| this.bg(active_bg))
3610            .on_click({
3611                cx.listener(move |this, event: &ClickEvent, window, cx| {
3612                    this.selected_entry = Some(ix);
3613                    cx.notify();
3614                    if event.modifiers().secondary() {
3615                        this.open_file(&Default::default(), window, cx)
3616                    } else {
3617                        this.open_diff(&Default::default(), window, cx);
3618                        this.focus_handle.focus(window);
3619                    }
3620                })
3621            })
3622            .on_mouse_down(
3623                MouseButton::Right,
3624                move |event: &MouseDownEvent, window, cx| {
3625                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3626                    if event.button != MouseButton::Right {
3627                        return;
3628                    }
3629
3630                    let Some(this) = handle.upgrade() else {
3631                        return;
3632                    };
3633                    this.update(cx, |this, cx| {
3634                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3635                    });
3636                    cx.stop_propagation();
3637                },
3638            )
3639            // .on_secondary_mouse_down(cx.listener(
3640            //     move |this, event: &MouseDownEvent, window, cx| {
3641            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3642            //         cx.stop_propagation();
3643            //     },
3644            // ))
3645            .child(
3646                div()
3647                    .id(checkbox_wrapper_id)
3648                    .flex_none()
3649                    .occlude()
3650                    .cursor_pointer()
3651                    .child(
3652                        Checkbox::new(checkbox_id, is_staged)
3653                            .disabled(!has_write_access)
3654                            .fill()
3655                            .placeholder(
3656                                !self.has_staged_changes()
3657                                    && !self.has_conflicts()
3658                                    && !entry.status.is_created(),
3659                            )
3660                            .elevation(ElevationIndex::Surface)
3661                            .on_click({
3662                                let entry = entry.clone();
3663                                cx.listener(move |this, _, window, cx| {
3664                                    if !has_write_access {
3665                                        return;
3666                                    }
3667                                    this.toggle_staged_for_entry(
3668                                        &GitListEntry::GitStatusEntry(entry.clone()),
3669                                        window,
3670                                        cx,
3671                                    );
3672                                    cx.stop_propagation();
3673                                })
3674                            })
3675                            .tooltip(move |window, cx| {
3676                                let is_staged = entry_staging.is_fully_staged();
3677
3678                                let action = if is_staged { "Unstage" } else { "Stage" };
3679                                let tooltip_name = if shift_held {
3680                                    format!("{} section", action)
3681                                } else {
3682                                    action.to_string()
3683                                };
3684
3685                                let meta = if shift_held {
3686                                    format!(
3687                                        "Release shift to {} single entry",
3688                                        action.to_lowercase()
3689                                    )
3690                                } else {
3691                                    format!("Shift click to {} section", action.to_lowercase())
3692                                };
3693
3694                                Tooltip::with_meta(
3695                                    tooltip_name,
3696                                    Some(&ToggleStaged),
3697                                    meta,
3698                                    window,
3699                                    cx,
3700                                )
3701                            }),
3702                    ),
3703            )
3704            .child(git_status_icon(status))
3705            .child(
3706                h_flex()
3707                    .items_center()
3708                    .flex_1()
3709                    // .overflow_hidden()
3710                    .when_some(entry.parent_dir(), |this, parent| {
3711                        if !parent.is_empty() {
3712                            this.child(
3713                                self.entry_label(format!("{}/", parent), path_color)
3714                                    .when(status.is_deleted(), |this| this.strikethrough()),
3715                            )
3716                        } else {
3717                            this
3718                        }
3719                    })
3720                    .child(
3721                        self.entry_label(display_name.clone(), label_color)
3722                            .when(status.is_deleted(), |this| this.strikethrough()),
3723                    ),
3724            )
3725            .into_any_element()
3726    }
3727
3728    fn has_write_access(&self, cx: &App) -> bool {
3729        !self.project.read(cx).is_read_only(cx)
3730    }
3731}
3732
3733fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3734    assistant_settings::AssistantSettings::get_global(cx)
3735        .enabled
3736        .then(|| {
3737            let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3738            let model = LanguageModelRegistry::read_global(cx).active_model()?;
3739            provider.is_authenticated(cx).then(|| model)
3740        })
3741        .flatten()
3742}
3743
3744impl Render for GitPanel {
3745    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3746        let project = self.project.read(cx);
3747        let has_entries = self.entries.len() > 0;
3748        let room = self
3749            .workspace
3750            .upgrade()
3751            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3752
3753        let has_write_access = self.has_write_access(cx);
3754
3755        let has_co_authors = room.map_or(false, |room| {
3756            room.read(cx)
3757                .remote_participants()
3758                .values()
3759                .any(|remote_participant| remote_participant.can_write())
3760        });
3761
3762        v_flex()
3763            .id("git_panel")
3764            .key_context(self.dispatch_context(window, cx))
3765            .track_focus(&self.focus_handle)
3766            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3767            .when(has_write_access && !project.is_read_only(cx), |this| {
3768                this.on_action(cx.listener(Self::toggle_staged_for_selected))
3769                    .on_action(cx.listener(GitPanel::commit))
3770                    .on_action(cx.listener(Self::stage_all))
3771                    .on_action(cx.listener(Self::unstage_all))
3772                    .on_action(cx.listener(Self::stage_selected))
3773                    .on_action(cx.listener(Self::unstage_selected))
3774                    .on_action(cx.listener(Self::restore_tracked_files))
3775                    .on_action(cx.listener(Self::revert_selected))
3776                    .on_action(cx.listener(Self::clean_all))
3777                    .on_action(cx.listener(Self::generate_commit_message_action))
3778            })
3779            .on_action(cx.listener(Self::select_first))
3780            .on_action(cx.listener(Self::select_next))
3781            .on_action(cx.listener(Self::select_previous))
3782            .on_action(cx.listener(Self::select_last))
3783            .on_action(cx.listener(Self::close_panel))
3784            .on_action(cx.listener(Self::open_diff))
3785            .on_action(cx.listener(Self::open_file))
3786            .on_action(cx.listener(Self::focus_changes_list))
3787            .on_action(cx.listener(Self::focus_editor))
3788            .on_action(cx.listener(Self::expand_commit_editor))
3789            .when(has_write_access && has_co_authors, |git_panel| {
3790                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3791            })
3792            .on_hover(cx.listener(move |this, hovered, window, cx| {
3793                if *hovered {
3794                    this.horizontal_scrollbar.show(cx);
3795                    this.vertical_scrollbar.show(cx);
3796                    cx.notify();
3797                } else if !this.focus_handle.contains_focused(window, cx) {
3798                    this.hide_scrollbars(window, cx);
3799                }
3800            }))
3801            .size_full()
3802            .overflow_hidden()
3803            .bg(ElevationIndex::Surface.bg(cx))
3804            .child(
3805                v_flex()
3806                    .size_full()
3807                    .children(self.render_panel_header(window, cx))
3808                    .map(|this| {
3809                        if has_entries {
3810                            this.child(self.render_entries(has_write_access, window, cx))
3811                        } else {
3812                            this.child(self.render_empty_state(cx).into_any_element())
3813                        }
3814                    })
3815                    .children(self.render_footer(window, cx))
3816                    .children(self.render_previous_commit(cx))
3817                    .into_any_element(),
3818            )
3819            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3820                deferred(
3821                    anchored()
3822                        .position(*position)
3823                        .anchor(gpui::Corner::TopLeft)
3824                        .child(menu.clone()),
3825                )
3826                .with_priority(1)
3827            }))
3828    }
3829}
3830
3831impl Focusable for GitPanel {
3832    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3833        if self.entries.is_empty() {
3834            self.commit_editor.focus_handle(cx)
3835        } else {
3836            self.focus_handle.clone()
3837        }
3838    }
3839}
3840
3841impl EventEmitter<Event> for GitPanel {}
3842
3843impl EventEmitter<PanelEvent> for GitPanel {}
3844
3845pub(crate) struct GitPanelAddon {
3846    pub(crate) workspace: WeakEntity<Workspace>,
3847}
3848
3849impl editor::Addon for GitPanelAddon {
3850    fn to_any(&self) -> &dyn std::any::Any {
3851        self
3852    }
3853
3854    fn render_buffer_header_controls(
3855        &self,
3856        excerpt_info: &ExcerptInfo,
3857        window: &Window,
3858        cx: &App,
3859    ) -> Option<AnyElement> {
3860        let file = excerpt_info.buffer.file()?;
3861        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3862
3863        git_panel
3864            .read(cx)
3865            .render_buffer_header_controls(&git_panel, &file, window, cx)
3866    }
3867}
3868
3869impl Panel for GitPanel {
3870    fn persistent_name() -> &'static str {
3871        "GitPanel"
3872    }
3873
3874    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3875        GitPanelSettings::get_global(cx).dock
3876    }
3877
3878    fn position_is_valid(&self, position: DockPosition) -> bool {
3879        matches!(position, DockPosition::Left | DockPosition::Right)
3880    }
3881
3882    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3883        settings::update_settings_file::<GitPanelSettings>(
3884            self.fs.clone(),
3885            cx,
3886            move |settings, _| settings.dock = Some(position),
3887        );
3888    }
3889
3890    fn size(&self, _: &Window, cx: &App) -> Pixels {
3891        self.width
3892            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3893    }
3894
3895    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3896        self.width = size;
3897        self.serialize(cx);
3898        cx.notify();
3899    }
3900
3901    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3902        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3903    }
3904
3905    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3906        Some("Git Panel")
3907    }
3908
3909    fn toggle_action(&self) -> Box<dyn Action> {
3910        Box::new(ToggleFocus)
3911    }
3912
3913    fn activation_priority(&self) -> u32 {
3914        2
3915    }
3916}
3917
3918impl PanelHeader for GitPanel {}
3919
3920struct GitPanelMessageTooltip {
3921    commit_tooltip: Option<Entity<CommitTooltip>>,
3922}
3923
3924impl GitPanelMessageTooltip {
3925    fn new(
3926        git_panel: Entity<GitPanel>,
3927        sha: SharedString,
3928        window: &mut Window,
3929        cx: &mut App,
3930    ) -> Entity<Self> {
3931        cx.new(|cx| {
3932            cx.spawn_in(window, |this, mut cx| async move {
3933                let details = git_panel
3934                    .update(&mut cx, |git_panel, cx| {
3935                        git_panel.load_commit_details(sha.to_string(), cx)
3936                    })?
3937                    .await?;
3938
3939                let commit_details = editor::commit_tooltip::CommitDetails {
3940                    sha: details.sha.clone(),
3941                    committer_name: details.committer_name.clone(),
3942                    committer_email: details.committer_email.clone(),
3943                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3944                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3945                        message: details.message.clone(),
3946                        ..Default::default()
3947                    }),
3948                };
3949
3950                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3951                    this.commit_tooltip =
3952                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3953                    cx.notify();
3954                })
3955            })
3956            .detach();
3957
3958            Self {
3959                commit_tooltip: None,
3960            }
3961        })
3962    }
3963}
3964
3965impl Render for GitPanelMessageTooltip {
3966    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3967        if let Some(commit_tooltip) = &self.commit_tooltip {
3968            commit_tooltip.clone().into_any_element()
3969        } else {
3970            gpui::Empty.into_any_element()
3971        }
3972    }
3973}
3974
3975#[derive(IntoElement, IntoComponent)]
3976#[component(scope = "Version Control")]
3977pub struct PanelRepoFooter {
3978    id: SharedString,
3979    active_repository: SharedString,
3980    branch: Option<Branch>,
3981    // Getting a GitPanel in previews will be difficult.
3982    //
3983    // For now just take an option here, and we won't bind handlers to buttons in previews.
3984    git_panel: Option<Entity<GitPanel>>,
3985}
3986
3987impl PanelRepoFooter {
3988    pub fn new(
3989        id: impl Into<SharedString>,
3990        active_repository: SharedString,
3991        branch: Option<Branch>,
3992        git_panel: Option<Entity<GitPanel>>,
3993    ) -> Self {
3994        Self {
3995            id: id.into(),
3996            active_repository,
3997            branch,
3998            git_panel,
3999        }
4000    }
4001
4002    pub fn new_preview(
4003        id: impl Into<SharedString>,
4004        active_repository: SharedString,
4005        branch: Option<Branch>,
4006    ) -> Self {
4007        Self {
4008            id: id.into(),
4009            active_repository,
4010            branch,
4011            git_panel: None,
4012        }
4013    }
4014}
4015
4016impl RenderOnce for PanelRepoFooter {
4017    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4018        let project = self
4019            .git_panel
4020            .as_ref()
4021            .map(|panel| panel.read(cx).project.clone());
4022
4023        let repo = self
4024            .git_panel
4025            .as_ref()
4026            .and_then(|panel| panel.read(cx).active_repository.clone());
4027
4028        let single_repo = project
4029            .as_ref()
4030            .map(|project| {
4031                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
4032            })
4033            .unwrap_or(true);
4034
4035        const MAX_BRANCH_LEN: usize = 16;
4036        const MAX_REPO_LEN: usize = 16;
4037        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4038
4039        let branch = self.branch.clone();
4040        let branch_name = branch
4041            .as_ref()
4042            .map_or(" (no branch)".into(), |branch| branch.name.clone());
4043        let active_repo_name = self.active_repository.clone();
4044
4045        let branch_actual_len = branch_name.len();
4046        let repo_actual_len = active_repo_name.len();
4047
4048        // ideally, show the whole branch and repo names but
4049        // when we can't, use a budget to allocate space between the two
4050        let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4051            <= LABEL_CHARACTER_BUDGET
4052        {
4053            (repo_actual_len, branch_actual_len)
4054        } else {
4055            if branch_actual_len <= MAX_BRANCH_LEN {
4056                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4057                (repo_space, branch_actual_len)
4058            } else if repo_actual_len <= MAX_REPO_LEN {
4059                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4060                (repo_actual_len, branch_space)
4061            } else {
4062                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4063            }
4064        };
4065
4066        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4067            active_repo_name.to_string()
4068        } else {
4069            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4070        };
4071
4072        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4073            branch_name.to_string()
4074        } else {
4075            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4076        };
4077
4078        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4079            .style(ButtonStyle::Transparent)
4080            .size(ButtonSize::None)
4081            .label_size(LabelSize::Small)
4082            .color(Color::Muted);
4083
4084        let repo_selector = PopoverMenu::new("repository-switcher")
4085            .menu({
4086                let project = project.clone();
4087                move |window, cx| {
4088                    let project = project.clone()?;
4089                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
4090                }
4091            })
4092            .trigger_with_tooltip(
4093                repo_selector_trigger.disabled(single_repo).truncate(true),
4094                Tooltip::text("Switch active repository"),
4095            )
4096            .attach(gpui::Corner::BottomLeft)
4097            .into_any_element();
4098
4099        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4100            .style(ButtonStyle::Transparent)
4101            .size(ButtonSize::None)
4102            .label_size(LabelSize::Small)
4103            .truncate(true)
4104            .tooltip(Tooltip::for_action_title(
4105                "Switch Branch",
4106                &zed_actions::git::Branch,
4107            ))
4108            .on_click(|_, window, cx| {
4109                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
4110            });
4111
4112        let branch_selector = PopoverMenu::new("popover-button")
4113            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4114            .trigger_with_tooltip(
4115                branch_selector_button,
4116                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
4117            )
4118            .anchor(Corner::TopLeft)
4119            .offset(gpui::Point {
4120                x: px(0.0),
4121                y: px(-2.0),
4122            });
4123
4124        let spinner = self
4125            .git_panel
4126            .as_ref()
4127            .and_then(|git_panel| git_panel.read(cx).render_spinner());
4128
4129        h_flex()
4130            .w_full()
4131            .px_2()
4132            .h(px(36.))
4133            .items_center()
4134            .justify_between()
4135            .gap_1()
4136            .child(
4137                h_flex()
4138                    .flex_1()
4139                    .overflow_hidden()
4140                    .items_center()
4141                    .child(
4142                        div().child(
4143                            Icon::new(IconName::GitBranchSmall)
4144                                .size(IconSize::Small)
4145                                .color(if single_repo {
4146                                    Color::Disabled
4147                                } else {
4148                                    Color::Muted
4149                                }),
4150                        ),
4151                    )
4152                    .child(repo_selector)
4153                    .when_some(branch.clone(), |this, _| {
4154                        this.child(
4155                            div()
4156                                .text_color(cx.theme().colors().text_muted)
4157                                .text_sm()
4158                                .child("/"),
4159                        )
4160                    })
4161                    .child(branch_selector),
4162            )
4163            .child(
4164                h_flex()
4165                    .gap_1()
4166                    .flex_shrink_0()
4167                    .children(spinner)
4168                    .when_some(branch, |this, branch| {
4169                        let mut focus_handle = None;
4170                        if let Some(git_panel) = self.git_panel.as_ref() {
4171                            if !git_panel.read(cx).can_push_and_pull(cx) {
4172                                return this;
4173                            }
4174                            focus_handle = Some(git_panel.focus_handle(cx));
4175                        }
4176
4177                        this.children(render_remote_button(
4178                            self.id.clone(),
4179                            &branch,
4180                            focus_handle,
4181                            true,
4182                        ))
4183                    }),
4184            )
4185    }
4186}
4187
4188impl ComponentPreview for PanelRepoFooter {
4189    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
4190        let unknown_upstream = None;
4191        let no_remote_upstream = Some(UpstreamTracking::Gone);
4192        let ahead_of_upstream = Some(
4193            UpstreamTrackingStatus {
4194                ahead: 2,
4195                behind: 0,
4196            }
4197            .into(),
4198        );
4199        let behind_upstream = Some(
4200            UpstreamTrackingStatus {
4201                ahead: 0,
4202                behind: 2,
4203            }
4204            .into(),
4205        );
4206        let ahead_and_behind_upstream = Some(
4207            UpstreamTrackingStatus {
4208                ahead: 3,
4209                behind: 1,
4210            }
4211            .into(),
4212        );
4213
4214        let not_ahead_or_behind_upstream = Some(
4215            UpstreamTrackingStatus {
4216                ahead: 0,
4217                behind: 0,
4218            }
4219            .into(),
4220        );
4221
4222        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4223            Branch {
4224                is_head: true,
4225                name: "some-branch".into(),
4226                upstream: upstream.map(|tracking| Upstream {
4227                    ref_name: "origin/some-branch".into(),
4228                    tracking,
4229                }),
4230                most_recent_commit: Some(CommitSummary {
4231                    sha: "abc123".into(),
4232                    subject: "Modify stuff".into(),
4233                    commit_timestamp: 1710932954,
4234                    has_parent: true,
4235                }),
4236            }
4237        }
4238
4239        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4240            Branch {
4241                is_head: true,
4242                name: branch_name.to_string().into(),
4243                upstream: upstream.map(|tracking| Upstream {
4244                    ref_name: format!("zed/{}", branch_name).into(),
4245                    tracking,
4246                }),
4247                most_recent_commit: Some(CommitSummary {
4248                    sha: "abc123".into(),
4249                    subject: "Modify stuff".into(),
4250                    commit_timestamp: 1710932954,
4251                    has_parent: true,
4252                }),
4253            }
4254        }
4255
4256        fn active_repository(id: usize) -> SharedString {
4257            format!("repo-{}", id).into()
4258        }
4259
4260        let example_width = px(340.);
4261
4262        v_flex()
4263            .gap_6()
4264            .w_full()
4265            .flex_none()
4266            .children(vec![example_group_with_title(
4267                "Action Button States",
4268                vec![
4269                    single_example(
4270                        "No Branch",
4271                        div()
4272                            .w(example_width)
4273                            .overflow_hidden()
4274                            .child(PanelRepoFooter::new_preview(
4275                                "no-branch",
4276                                active_repository(1).clone(),
4277                                None,
4278                            ))
4279                            .into_any_element(),
4280                    )
4281                    .grow(),
4282                    single_example(
4283                        "Remote status unknown",
4284                        div()
4285                            .w(example_width)
4286                            .overflow_hidden()
4287                            .child(PanelRepoFooter::new_preview(
4288                                "unknown-upstream",
4289                                active_repository(2).clone(),
4290                                Some(branch(unknown_upstream)),
4291                            ))
4292                            .into_any_element(),
4293                    )
4294                    .grow(),
4295                    single_example(
4296                        "No Remote Upstream",
4297                        div()
4298                            .w(example_width)
4299                            .overflow_hidden()
4300                            .child(PanelRepoFooter::new_preview(
4301                                "no-remote-upstream",
4302                                active_repository(3).clone(),
4303                                Some(branch(no_remote_upstream)),
4304                            ))
4305                            .into_any_element(),
4306                    )
4307                    .grow(),
4308                    single_example(
4309                        "Not Ahead or Behind",
4310                        div()
4311                            .w(example_width)
4312                            .overflow_hidden()
4313                            .child(PanelRepoFooter::new_preview(
4314                                "not-ahead-or-behind",
4315                                active_repository(4).clone(),
4316                                Some(branch(not_ahead_or_behind_upstream)),
4317                            ))
4318                            .into_any_element(),
4319                    )
4320                    .grow(),
4321                    single_example(
4322                        "Behind remote",
4323                        div()
4324                            .w(example_width)
4325                            .overflow_hidden()
4326                            .child(PanelRepoFooter::new_preview(
4327                                "behind-remote",
4328                                active_repository(5).clone(),
4329                                Some(branch(behind_upstream)),
4330                            ))
4331                            .into_any_element(),
4332                    )
4333                    .grow(),
4334                    single_example(
4335                        "Ahead of remote",
4336                        div()
4337                            .w(example_width)
4338                            .overflow_hidden()
4339                            .child(PanelRepoFooter::new_preview(
4340                                "ahead-of-remote",
4341                                active_repository(6).clone(),
4342                                Some(branch(ahead_of_upstream)),
4343                            ))
4344                            .into_any_element(),
4345                    )
4346                    .grow(),
4347                    single_example(
4348                        "Ahead and behind remote",
4349                        div()
4350                            .w(example_width)
4351                            .overflow_hidden()
4352                            .child(PanelRepoFooter::new_preview(
4353                                "ahead-and-behind",
4354                                active_repository(7).clone(),
4355                                Some(branch(ahead_and_behind_upstream)),
4356                            ))
4357                            .into_any_element(),
4358                    )
4359                    .grow(),
4360                ],
4361            )
4362            .grow()
4363            .vertical()])
4364            .children(vec![example_group_with_title(
4365                "Labels",
4366                vec![
4367                    single_example(
4368                        "Short Branch & Repo",
4369                        div()
4370                            .w(example_width)
4371                            .overflow_hidden()
4372                            .child(PanelRepoFooter::new_preview(
4373                                "short-branch",
4374                                SharedString::from("zed"),
4375                                Some(custom("main", behind_upstream)),
4376                            ))
4377                            .into_any_element(),
4378                    )
4379                    .grow(),
4380                    single_example(
4381                        "Long Branch",
4382                        div()
4383                            .w(example_width)
4384                            .overflow_hidden()
4385                            .child(PanelRepoFooter::new_preview(
4386                                "long-branch",
4387                                SharedString::from("zed"),
4388                                Some(custom(
4389                                    "redesign-and-update-git-ui-list-entry-style",
4390                                    behind_upstream,
4391                                )),
4392                            ))
4393                            .into_any_element(),
4394                    )
4395                    .grow(),
4396                    single_example(
4397                        "Long Repo",
4398                        div()
4399                            .w(example_width)
4400                            .overflow_hidden()
4401                            .child(PanelRepoFooter::new_preview(
4402                                "long-repo",
4403                                SharedString::from("zed-industries-community-examples"),
4404                                Some(custom("gpui", ahead_of_upstream)),
4405                            ))
4406                            .into_any_element(),
4407                    )
4408                    .grow(),
4409                    single_example(
4410                        "Long Repo & Branch",
4411                        div()
4412                            .w(example_width)
4413                            .overflow_hidden()
4414                            .child(PanelRepoFooter::new_preview(
4415                                "long-repo-and-branch",
4416                                SharedString::from("zed-industries-community-examples"),
4417                                Some(custom(
4418                                    "redesign-and-update-git-ui-list-entry-style",
4419                                    behind_upstream,
4420                                )),
4421                            ))
4422                            .into_any_element(),
4423                    )
4424                    .grow(),
4425                    single_example(
4426                        "Uppercase Repo",
4427                        div()
4428                            .w(example_width)
4429                            .overflow_hidden()
4430                            .child(PanelRepoFooter::new_preview(
4431                                "uppercase-repo",
4432                                SharedString::from("LICENSES"),
4433                                Some(custom("main", ahead_of_upstream)),
4434                            ))
4435                            .into_any_element(),
4436                    )
4437                    .grow(),
4438                    single_example(
4439                        "Uppercase Branch",
4440                        div()
4441                            .w(example_width)
4442                            .overflow_hidden()
4443                            .child(PanelRepoFooter::new_preview(
4444                                "uppercase-branch",
4445                                SharedString::from("zed"),
4446                                Some(custom("update-README", behind_upstream)),
4447                            ))
4448                            .into_any_element(),
4449                    )
4450                    .grow(),
4451                ],
4452            )
4453            .grow()
4454            .vertical()])
4455            .into_any_element()
4456    }
4457}
4458
4459#[cfg(test)]
4460mod tests {
4461    use git::status::StatusCode;
4462    use gpui::TestAppContext;
4463    use project::{FakeFs, WorktreeSettings};
4464    use serde_json::json;
4465    use settings::SettingsStore;
4466    use theme::LoadThemes;
4467    use util::path;
4468
4469    use super::*;
4470
4471    fn init_test(cx: &mut gpui::TestAppContext) {
4472        if std::env::var("RUST_LOG").is_ok() {
4473            env_logger::try_init().ok();
4474        }
4475
4476        cx.update(|cx| {
4477            let settings_store = SettingsStore::test(cx);
4478            cx.set_global(settings_store);
4479            AssistantSettings::register(cx);
4480            WorktreeSettings::register(cx);
4481            workspace::init_settings(cx);
4482            theme::init(LoadThemes::JustBase, cx);
4483            language::init(cx);
4484            editor::init(cx);
4485            Project::init_settings(cx);
4486            crate::init(cx);
4487        });
4488    }
4489
4490    #[gpui::test]
4491    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4492        init_test(cx);
4493        let fs = FakeFs::new(cx.background_executor.clone());
4494        fs.insert_tree(
4495            "/root",
4496            json!({
4497                "zed": {
4498                    ".git": {},
4499                    "crates": {
4500                        "gpui": {
4501                            "gpui.rs": "fn main() {}"
4502                        },
4503                        "util": {
4504                            "util.rs": "fn do_it() {}"
4505                        }
4506                    }
4507                },
4508            }),
4509        )
4510        .await;
4511
4512        fs.set_status_for_repo_via_git_operation(
4513            Path::new(path!("/root/zed/.git")),
4514            &[
4515                (
4516                    Path::new("crates/gpui/gpui.rs"),
4517                    StatusCode::Modified.worktree(),
4518                ),
4519                (
4520                    Path::new("crates/util/util.rs"),
4521                    StatusCode::Modified.worktree(),
4522                ),
4523            ],
4524        );
4525
4526        let project =
4527            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4528        let (workspace, cx) =
4529            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4530
4531        cx.read(|cx| {
4532            project
4533                .read(cx)
4534                .worktrees(cx)
4535                .nth(0)
4536                .unwrap()
4537                .read(cx)
4538                .as_local()
4539                .unwrap()
4540                .scan_complete()
4541        })
4542        .await;
4543
4544        cx.executor().run_until_parked();
4545
4546        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4547        let panel = cx.new_window_entity(|window, cx| {
4548            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4549        });
4550
4551        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4552            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4553        });
4554        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4555        handle.await;
4556
4557        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4558        pretty_assertions::assert_eq!(
4559            entries,
4560            [
4561                GitListEntry::Header(GitHeaderEntry {
4562                    header: Section::Tracked
4563                }),
4564                GitListEntry::GitStatusEntry(GitStatusEntry {
4565                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4566                    repo_path: "crates/gpui/gpui.rs".into(),
4567                    worktree_path: Path::new("gpui.rs").into(),
4568                    status: StatusCode::Modified.worktree(),
4569                    staging: StageStatus::Unstaged,
4570                }),
4571                GitListEntry::GitStatusEntry(GitStatusEntry {
4572                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4573                    repo_path: "crates/util/util.rs".into(),
4574                    worktree_path: Path::new("../util/util.rs").into(),
4575                    status: StatusCode::Modified.worktree(),
4576                    staging: StageStatus::Unstaged,
4577                },),
4578            ],
4579        );
4580
4581        cx.update_window_entity(&panel, |panel, window, cx| {
4582            panel.select_last(&Default::default(), window, cx);
4583            assert_eq!(panel.selected_entry, Some(2));
4584            panel.open_diff(&Default::default(), window, cx);
4585        });
4586        cx.run_until_parked();
4587
4588        let worktree_roots = workspace.update(cx, |workspace, cx| {
4589            workspace
4590                .worktrees(cx)
4591                .map(|worktree| worktree.read(cx).abs_path())
4592                .collect::<Vec<_>>()
4593        });
4594        pretty_assertions::assert_eq!(
4595            worktree_roots,
4596            vec![
4597                Path::new(path!("/root/zed/crates/gpui")).into(),
4598                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4599            ]
4600        );
4601
4602        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4603            let git_store = project.git_store().read(cx);
4604            // The repo that comes from the single-file worktree can't be selected through the UI.
4605            let filtered_entries = filtered_repository_entries(git_store, cx)
4606                .iter()
4607                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4608                .collect::<Vec<_>>();
4609            assert_eq!(
4610                filtered_entries,
4611                [Path::new(path!("/root/zed/crates/gpui")).into()]
4612            );
4613            // But we can select it artificially here.
4614            git_store
4615                .all_repositories()
4616                .into_iter()
4617                .find(|repo| {
4618                    &*repo.read(cx).worktree_abs_path
4619                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4620                })
4621                .unwrap()
4622        });
4623
4624        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4625        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4626        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4627            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4628        });
4629        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4630        handle.await;
4631        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4632        pretty_assertions::assert_eq!(
4633            entries,
4634            [
4635                GitListEntry::Header(GitHeaderEntry {
4636                    header: Section::Tracked
4637                }),
4638                GitListEntry::GitStatusEntry(GitStatusEntry {
4639                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4640                    repo_path: "crates/gpui/gpui.rs".into(),
4641                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4642                    status: StatusCode::Modified.worktree(),
4643                    staging: StageStatus::Unstaged,
4644                }),
4645                GitListEntry::GitStatusEntry(GitStatusEntry {
4646                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4647                    repo_path: "crates/util/util.rs".into(),
4648                    worktree_path: Path::new("util.rs").into(),
4649                    status: StatusCode::Modified.worktree(),
4650                    staging: StageStatus::Unstaged,
4651                },),
4652            ],
4653        );
4654    }
4655}