git_panel.rs

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