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