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