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