git_panel.rs

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