git_panel.rs

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