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                            .iter()
1055                            .map(|entries| entries.repo_path.clone())
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        self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1739             async move {
1740                let _defer = cx.on_drop(&this, |this, _cx| {
1741                    this.generate_commit_message_task.take();
1742                });
1743
1744                let mut diff_text = diff.await??;
1745
1746                const ONE_MB: usize = 1_000_000;
1747                if diff_text.len() > ONE_MB {
1748                    diff_text = diff_text.chars().take(ONE_MB).collect()
1749                }
1750
1751                let subject = this.update(cx, |this, cx| {
1752                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1753                })?;
1754
1755                let text_empty = subject.trim().is_empty();
1756
1757                let content = if text_empty {
1758                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1759                } else {
1760                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1761                };
1762
1763                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1764
1765                let request = LanguageModelRequest {
1766                    thread_id: None,
1767                    prompt_id: None,
1768                    mode: None,
1769                    messages: vec![LanguageModelRequestMessage {
1770                        role: Role::User,
1771                        content: vec![content.into()],
1772                        cache: false,
1773                    }],
1774                    tools: Vec::new(),
1775                    stop: Vec::new(),
1776                    temperature: None,
1777                };
1778
1779                let stream = model.stream_completion_text(request, &cx);
1780                let mut messages = stream.await?;
1781
1782                if !text_empty {
1783                    this.update(cx, |this, cx| {
1784                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1785                            let insert_position = buffer.anchor_before(buffer.len());
1786                            buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1787                        });
1788                    })?;
1789                }
1790
1791                while let Some(message) = messages.stream.next().await {
1792                    let text = message?;
1793
1794                    this.update(cx, |this, cx| {
1795                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1796                            let insert_position = buffer.anchor_before(buffer.len());
1797                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1798                        });
1799                    })?;
1800                }
1801
1802                anyhow::Ok(())
1803            }
1804            .log_err().await
1805        }));
1806    }
1807
1808    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1809        if !self.can_push_and_pull(cx) {
1810            return;
1811        }
1812
1813        let Some(repo) = self.active_repository.clone() else {
1814            return;
1815        };
1816        telemetry::event!("Git Fetched");
1817        let askpass = self.askpass_delegate("git fetch", window, cx);
1818        let this = cx.weak_entity();
1819        window
1820            .spawn(cx, async move |cx| {
1821                let fetch = repo.update(cx, |repo, cx| repo.fetch(askpass, cx))?;
1822
1823                let remote_message = fetch.await?;
1824                this.update(cx, |this, cx| {
1825                    let action = RemoteAction::Fetch;
1826                    match remote_message {
1827                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1828                        Err(e) => {
1829                            log::error!("Error while fetching {:?}", e);
1830                            this.show_error_toast(action.name(), e, cx)
1831                        }
1832                    }
1833
1834                    anyhow::Ok(())
1835                })
1836                .ok();
1837                anyhow::Ok(())
1838            })
1839            .detach_and_log_err(cx);
1840    }
1841
1842    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1843        let worktrees = self
1844            .project
1845            .read(cx)
1846            .visible_worktrees(cx)
1847            .collect::<Vec<_>>();
1848
1849        let worktree = if worktrees.len() == 1 {
1850            Task::ready(Some(worktrees.first().unwrap().clone()))
1851        } else if worktrees.len() == 0 {
1852            let result = window.prompt(
1853                PromptLevel::Warning,
1854                "Unable to initialize a git repository",
1855                Some("Open a directory first"),
1856                &["Ok"],
1857                cx,
1858            );
1859            cx.background_executor()
1860                .spawn(async move {
1861                    result.await.ok();
1862                })
1863                .detach();
1864            return;
1865        } else {
1866            let worktree_directories = worktrees
1867                .iter()
1868                .map(|worktree| worktree.read(cx).abs_path())
1869                .map(|worktree_abs_path| {
1870                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1871                        Path::new("~")
1872                            .join(path)
1873                            .to_string_lossy()
1874                            .to_string()
1875                            .into()
1876                    } else {
1877                        worktree_abs_path.to_string_lossy().to_string().into()
1878                    }
1879                })
1880                .collect_vec();
1881            let prompt = picker_prompt::prompt(
1882                "Where would you like to initialize this git repository?",
1883                worktree_directories,
1884                self.workspace.clone(),
1885                window,
1886                cx,
1887            );
1888
1889            cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
1890        };
1891
1892        cx.spawn_in(window, async move |this, cx| {
1893            let worktree = match worktree.await {
1894                Some(worktree) => worktree,
1895                None => {
1896                    return;
1897                }
1898            };
1899
1900            let Ok(result) = this.update(cx, |this, cx| {
1901                let fallback_branch_name = GitPanelSettings::get_global(cx)
1902                    .fallback_branch_name
1903                    .clone();
1904                this.project.read(cx).git_init(
1905                    worktree.read(cx).abs_path(),
1906                    fallback_branch_name,
1907                    cx,
1908                )
1909            }) else {
1910                return;
1911            };
1912
1913            let result = result.await;
1914
1915            this.update_in(cx, |this, _, cx| match result {
1916                Ok(()) => {}
1917                Err(e) => this.show_error_toast("init", e, cx),
1918            })
1919            .ok();
1920        })
1921        .detach();
1922    }
1923
1924    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1925        if !self.can_push_and_pull(cx) {
1926            return;
1927        }
1928        let Some(repo) = self.active_repository.clone() else {
1929            return;
1930        };
1931        let Some(branch) = repo.read(cx).branch.as_ref() else {
1932            return;
1933        };
1934        telemetry::event!("Git Pulled");
1935        let branch = branch.clone();
1936        let remote = self.get_current_remote(window, cx);
1937        cx.spawn_in(window, async move |this, cx| {
1938            let remote = match remote.await {
1939                Ok(Some(remote)) => remote,
1940                Ok(None) => {
1941                    return Ok(());
1942                }
1943                Err(e) => {
1944                    log::error!("Failed to get current remote: {}", e);
1945                    this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
1946                        .ok();
1947                    return Ok(());
1948                }
1949            };
1950
1951            let askpass = this.update_in(cx, |this, window, cx| {
1952                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1953            })?;
1954
1955            let pull = repo.update(cx, |repo, cx| {
1956                repo.pull(
1957                    branch.name().to_owned().into(),
1958                    remote.name.clone(),
1959                    askpass,
1960                    cx,
1961                )
1962            })?;
1963
1964            let remote_message = pull.await?;
1965
1966            let action = RemoteAction::Pull(remote);
1967            this.update(cx, |this, cx| match remote_message {
1968                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1969                Err(e) => {
1970                    log::error!("Error while pulling {:?}", e);
1971                    this.show_error_toast(action.name(), e, cx)
1972                }
1973            })
1974            .ok();
1975
1976            anyhow::Ok(())
1977        })
1978        .detach_and_log_err(cx);
1979    }
1980
1981    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1982        if !self.can_push_and_pull(cx) {
1983            return;
1984        }
1985        let Some(repo) = self.active_repository.clone() else {
1986            return;
1987        };
1988        let Some(branch) = repo.read(cx).branch.as_ref() else {
1989            return;
1990        };
1991        telemetry::event!("Git Pushed");
1992        let branch = branch.clone();
1993
1994        let options = if force_push {
1995            Some(PushOptions::Force)
1996        } else {
1997            match branch.upstream {
1998                Some(Upstream {
1999                    tracking: UpstreamTracking::Gone,
2000                    ..
2001                })
2002                | None => Some(PushOptions::SetUpstream),
2003                _ => None,
2004            }
2005        };
2006        let remote = self.get_current_remote(window, cx);
2007
2008        cx.spawn_in(window, async move |this, cx| {
2009            let remote = match remote.await {
2010                Ok(Some(remote)) => remote,
2011                Ok(None) => {
2012                    return Ok(());
2013                }
2014                Err(e) => {
2015                    log::error!("Failed to get current remote: {}", e);
2016                    this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2017                        .ok();
2018                    return Ok(());
2019                }
2020            };
2021
2022            let askpass_delegate = this.update_in(cx, |this, window, cx| {
2023                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2024            })?;
2025
2026            let push = repo.update(cx, |repo, cx| {
2027                repo.push(
2028                    branch.name().to_owned().into(),
2029                    remote.name.clone(),
2030                    options,
2031                    askpass_delegate,
2032                    cx,
2033                )
2034            })?;
2035
2036            let remote_output = push.await?;
2037
2038            let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2039            this.update(cx, |this, cx| match remote_output {
2040                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2041                Err(e) => {
2042                    log::error!("Error while pushing {:?}", e);
2043                    this.show_error_toast(action.name(), e, cx)
2044                }
2045            })?;
2046
2047            anyhow::Ok(())
2048        })
2049        .detach_and_log_err(cx);
2050    }
2051
2052    fn askpass_delegate(
2053        &self,
2054        operation: impl Into<SharedString>,
2055        window: &mut Window,
2056        cx: &mut Context<Self>,
2057    ) -> AskPassDelegate {
2058        let this = cx.weak_entity();
2059        let operation = operation.into();
2060        let window = window.window_handle();
2061        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2062            window
2063                .update(cx, |_, window, cx| {
2064                    this.update(cx, |this, cx| {
2065                        this.workspace.update(cx, |workspace, cx| {
2066                            workspace.toggle_modal(window, cx, |window, cx| {
2067                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2068                            });
2069                        })
2070                    })
2071                })
2072                .ok();
2073        })
2074    }
2075
2076    fn can_push_and_pull(&self, cx: &App) -> bool {
2077        !self.project.read(cx).is_via_collab()
2078    }
2079
2080    fn get_current_remote(
2081        &mut self,
2082        window: &mut Window,
2083        cx: &mut Context<Self>,
2084    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2085        let repo = self.active_repository.clone();
2086        let workspace = self.workspace.clone();
2087        let mut cx = window.to_async(cx);
2088
2089        async move {
2090            let Some(repo) = repo else {
2091                return Err(anyhow::anyhow!("No active repository"));
2092            };
2093
2094            let mut current_remotes: Vec<Remote> = repo
2095                .update(&mut cx, |repo, _| {
2096                    let Some(current_branch) = repo.branch.as_ref() else {
2097                        return Err(anyhow::anyhow!("No active branch"));
2098                    };
2099
2100                    Ok(repo.get_remotes(Some(current_branch.name().to_string())))
2101                })??
2102                .await??;
2103
2104            if current_remotes.len() == 0 {
2105                return Err(anyhow::anyhow!("No active remote"));
2106            } else if current_remotes.len() == 1 {
2107                return Ok(Some(current_remotes.pop().unwrap()));
2108            } else {
2109                let current_remotes: Vec<_> = current_remotes
2110                    .into_iter()
2111                    .map(|remotes| remotes.name)
2112                    .collect();
2113                let selection = cx
2114                    .update(|window, cx| {
2115                        picker_prompt::prompt(
2116                            "Pick which remote to push to",
2117                            current_remotes.clone(),
2118                            workspace,
2119                            window,
2120                            cx,
2121                        )
2122                    })?
2123                    .await;
2124
2125                Ok(selection.map(|selection| Remote {
2126                    name: current_remotes[selection].clone(),
2127                }))
2128            }
2129        }
2130    }
2131
2132    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2133        let mut new_co_authors = Vec::new();
2134        let project = self.project.read(cx);
2135
2136        let Some(room) = self
2137            .workspace
2138            .upgrade()
2139            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2140        else {
2141            return Vec::default();
2142        };
2143
2144        let room = room.read(cx);
2145
2146        for (peer_id, collaborator) in project.collaborators() {
2147            if collaborator.is_host {
2148                continue;
2149            }
2150
2151            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2152                continue;
2153            };
2154            if participant.can_write() && participant.user.email.is_some() {
2155                let email = participant.user.email.clone().unwrap();
2156
2157                new_co_authors.push((
2158                    participant
2159                        .user
2160                        .name
2161                        .clone()
2162                        .unwrap_or_else(|| participant.user.github_login.clone()),
2163                    email,
2164                ))
2165            }
2166        }
2167        if !project.is_local() && !project.is_read_only(cx) {
2168            if let Some(user) = room.local_participant_user(cx) {
2169                if let Some(email) = user.email.clone() {
2170                    new_co_authors.push((
2171                        user.name
2172                            .clone()
2173                            .unwrap_or_else(|| user.github_login.clone()),
2174                        email.clone(),
2175                    ))
2176                }
2177            }
2178        }
2179        new_co_authors
2180    }
2181
2182    fn toggle_fill_co_authors(
2183        &mut self,
2184        _: &ToggleFillCoAuthors,
2185        _: &mut Window,
2186        cx: &mut Context<Self>,
2187    ) {
2188        self.add_coauthors = !self.add_coauthors;
2189        cx.notify();
2190    }
2191
2192    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2193        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2194
2195        let existing_text = message.to_ascii_lowercase();
2196        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2197        let mut ends_with_co_authors = false;
2198        let existing_co_authors = existing_text
2199            .lines()
2200            .filter_map(|line| {
2201                let line = line.trim();
2202                if line.starts_with(&lowercase_co_author_prefix) {
2203                    ends_with_co_authors = true;
2204                    Some(line)
2205                } else {
2206                    ends_with_co_authors = false;
2207                    None
2208                }
2209            })
2210            .collect::<HashSet<_>>();
2211
2212        let new_co_authors = self
2213            .potential_co_authors(cx)
2214            .into_iter()
2215            .filter(|(_, email)| {
2216                !existing_co_authors
2217                    .iter()
2218                    .any(|existing| existing.contains(email.as_str()))
2219            })
2220            .collect::<Vec<_>>();
2221
2222        if new_co_authors.is_empty() {
2223            return;
2224        }
2225
2226        if !ends_with_co_authors {
2227            message.push('\n');
2228        }
2229        for (name, email) in new_co_authors {
2230            message.push('\n');
2231            message.push_str(CO_AUTHOR_PREFIX);
2232            message.push_str(&name);
2233            message.push_str(" <");
2234            message.push_str(&email);
2235            message.push('>');
2236        }
2237        message.push('\n');
2238    }
2239
2240    fn schedule_update(
2241        &mut self,
2242        clear_pending: bool,
2243        window: &mut Window,
2244        cx: &mut Context<Self>,
2245    ) {
2246        let handle = cx.entity().downgrade();
2247        self.reopen_commit_buffer(window, cx);
2248        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2249            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2250            if let Some(git_panel) = handle.upgrade() {
2251                git_panel
2252                    .update_in(cx, |git_panel, window, cx| {
2253                        if clear_pending {
2254                            git_panel.clear_pending();
2255                        }
2256                        git_panel.update_visible_entries(cx);
2257                        git_panel.update_scrollbar_properties(window, cx);
2258                    })
2259                    .ok();
2260            }
2261        });
2262    }
2263
2264    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2265        let Some(active_repo) = self.active_repository.as_ref() else {
2266            return;
2267        };
2268        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2269            let project = self.project.read(cx);
2270            active_repo.open_commit_buffer(
2271                Some(project.languages().clone()),
2272                project.buffer_store().clone(),
2273                cx,
2274            )
2275        });
2276
2277        cx.spawn_in(window, async move |git_panel, cx| {
2278            let buffer = load_buffer.await?;
2279            git_panel.update_in(cx, |git_panel, window, cx| {
2280                if git_panel
2281                    .commit_editor
2282                    .read(cx)
2283                    .buffer()
2284                    .read(cx)
2285                    .as_singleton()
2286                    .as_ref()
2287                    != Some(&buffer)
2288                {
2289                    git_panel.commit_editor = cx.new(|cx| {
2290                        commit_message_editor(
2291                            buffer,
2292                            git_panel.suggest_commit_message(cx).map(SharedString::from),
2293                            git_panel.project.clone(),
2294                            true,
2295                            window,
2296                            cx,
2297                        )
2298                    });
2299                }
2300            })
2301        })
2302        .detach_and_log_err(cx);
2303    }
2304
2305    fn clear_pending(&mut self) {
2306        self.pending.retain(|v| !v.finished)
2307    }
2308
2309    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2310        self.entries.clear();
2311        self.single_staged_entry.take();
2312        self.single_tracked_entry.take();
2313        self.conflicted_count = 0;
2314        self.conflicted_staged_count = 0;
2315        self.new_count = 0;
2316        self.tracked_count = 0;
2317        self.new_staged_count = 0;
2318        self.tracked_staged_count = 0;
2319        self.entry_count = 0;
2320
2321        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2322
2323        let mut changed_entries = Vec::new();
2324        let mut new_entries = Vec::new();
2325        let mut conflict_entries = Vec::new();
2326        let mut last_staged = None;
2327        let mut staged_count = 0;
2328        let mut max_width_item: Option<(RepoPath, usize)> = None;
2329
2330        let Some(repo) = self.active_repository.as_ref() else {
2331            // Just clear entries if no repository is active.
2332            cx.notify();
2333            return;
2334        };
2335
2336        let repo = repo.read(cx);
2337
2338        for entry in repo.cached_status() {
2339            let is_conflict = repo.has_conflict(&entry.repo_path);
2340            let is_new = entry.status.is_created();
2341            let staging = entry.status.staging();
2342
2343            if self.pending.iter().any(|pending| {
2344                pending.target_status == TargetStatus::Reverted
2345                    && !pending.finished
2346                    && pending
2347                        .entries
2348                        .iter()
2349                        .any(|pending| pending.repo_path == entry.repo_path)
2350            }) {
2351                continue;
2352            }
2353
2354            let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2355            let entry = GitStatusEntry {
2356                repo_path: entry.repo_path.clone(),
2357                abs_path,
2358                status: entry.status,
2359                staging,
2360            };
2361
2362            if staging.has_staged() {
2363                staged_count += 1;
2364                last_staged = Some(entry.clone());
2365            }
2366
2367            let width_estimate = Self::item_width_estimate(
2368                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2369                entry.display_name().len(),
2370            );
2371
2372            match max_width_item.as_mut() {
2373                Some((repo_path, estimate)) => {
2374                    if width_estimate > *estimate {
2375                        *repo_path = entry.repo_path.clone();
2376                        *estimate = width_estimate;
2377                    }
2378                }
2379                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2380            }
2381
2382            if sort_by_path {
2383                changed_entries.push(entry);
2384            } else if is_conflict {
2385                conflict_entries.push(entry);
2386            } else if is_new {
2387                new_entries.push(entry);
2388            } else {
2389                changed_entries.push(entry);
2390            }
2391        }
2392
2393        let mut pending_staged_count = 0;
2394        let mut last_pending_staged = None;
2395        let mut pending_status_for_last_staged = None;
2396        for pending in self.pending.iter() {
2397            if pending.target_status == TargetStatus::Staged {
2398                pending_staged_count += pending.entries.len();
2399                last_pending_staged = pending.entries.iter().next().cloned();
2400            }
2401            if let Some(last_staged) = &last_staged {
2402                if pending
2403                    .entries
2404                    .iter()
2405                    .any(|entry| entry.repo_path == last_staged.repo_path)
2406                {
2407                    pending_status_for_last_staged = Some(pending.target_status);
2408                }
2409            }
2410        }
2411
2412        if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2413            match pending_status_for_last_staged {
2414                Some(TargetStatus::Staged) | None => {
2415                    self.single_staged_entry = last_staged;
2416                }
2417                _ => {}
2418            }
2419        } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2420            self.single_staged_entry = last_pending_staged;
2421        }
2422
2423        if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2424            self.single_tracked_entry = changed_entries.first().cloned();
2425        }
2426
2427        if conflict_entries.len() > 0 {
2428            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2429                header: Section::Conflict,
2430            }));
2431            self.entries.extend(
2432                conflict_entries
2433                    .into_iter()
2434                    .map(GitListEntry::GitStatusEntry),
2435            );
2436        }
2437
2438        if changed_entries.len() > 0 {
2439            if !sort_by_path {
2440                self.entries.push(GitListEntry::Header(GitHeaderEntry {
2441                    header: Section::Tracked,
2442                }));
2443            }
2444            self.entries.extend(
2445                changed_entries
2446                    .into_iter()
2447                    .map(GitListEntry::GitStatusEntry),
2448            );
2449        }
2450        if new_entries.len() > 0 {
2451            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2452                header: Section::New,
2453            }));
2454            self.entries
2455                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2456        }
2457
2458        if let Some((repo_path, _)) = max_width_item {
2459            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2460                GitListEntry::GitStatusEntry(git_status_entry) => {
2461                    git_status_entry.repo_path == repo_path
2462                }
2463                GitListEntry::Header(_) => false,
2464            });
2465        }
2466
2467        self.update_counts(repo);
2468
2469        self.select_first_entry_if_none(cx);
2470
2471        let suggested_commit_message = self.suggest_commit_message(cx);
2472        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2473
2474        self.commit_editor.update(cx, |editor, cx| {
2475            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2476        });
2477
2478        cx.notify();
2479    }
2480
2481    fn header_state(&self, header_type: Section) -> ToggleState {
2482        let (staged_count, count) = match header_type {
2483            Section::New => (self.new_staged_count, self.new_count),
2484            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2485            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2486        };
2487        if staged_count == 0 {
2488            ToggleState::Unselected
2489        } else if count == staged_count {
2490            ToggleState::Selected
2491        } else {
2492            ToggleState::Indeterminate
2493        }
2494    }
2495
2496    fn update_counts(&mut self, repo: &Repository) {
2497        self.show_placeholders = false;
2498        self.conflicted_count = 0;
2499        self.conflicted_staged_count = 0;
2500        self.new_count = 0;
2501        self.tracked_count = 0;
2502        self.new_staged_count = 0;
2503        self.tracked_staged_count = 0;
2504        self.entry_count = 0;
2505        for entry in &self.entries {
2506            let Some(status_entry) = entry.status_entry() else {
2507                continue;
2508            };
2509            self.entry_count += 1;
2510            if repo.has_conflict(&status_entry.repo_path) {
2511                self.conflicted_count += 1;
2512                if self.entry_staging(status_entry).has_staged() {
2513                    self.conflicted_staged_count += 1;
2514                }
2515            } else if status_entry.status.is_created() {
2516                self.new_count += 1;
2517                if self.entry_staging(status_entry).has_staged() {
2518                    self.new_staged_count += 1;
2519                }
2520            } else {
2521                self.tracked_count += 1;
2522                if self.entry_staging(status_entry).has_staged() {
2523                    self.tracked_staged_count += 1;
2524                }
2525            }
2526        }
2527    }
2528
2529    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2530        for pending in self.pending.iter().rev() {
2531            if pending
2532                .entries
2533                .iter()
2534                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2535            {
2536                match pending.target_status {
2537                    TargetStatus::Staged => return StageStatus::Staged,
2538                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2539                    TargetStatus::Reverted => continue,
2540                    TargetStatus::Unchanged => continue,
2541                }
2542            }
2543        }
2544        entry.staging
2545    }
2546
2547    pub(crate) fn has_staged_changes(&self) -> bool {
2548        self.tracked_staged_count > 0
2549            || self.new_staged_count > 0
2550            || self.conflicted_staged_count > 0
2551    }
2552
2553    pub(crate) fn has_unstaged_changes(&self) -> bool {
2554        self.tracked_count > self.tracked_staged_count
2555            || self.new_count > self.new_staged_count
2556            || self.conflicted_count > self.conflicted_staged_count
2557    }
2558
2559    fn has_tracked_changes(&self) -> bool {
2560        self.tracked_count > 0
2561    }
2562
2563    pub fn has_unstaged_conflicts(&self) -> bool {
2564        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2565    }
2566
2567    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2568        let action = action.into();
2569        let Some(workspace) = self.workspace.upgrade() else {
2570            return;
2571        };
2572
2573        let message = e.to_string().trim().to_string();
2574        if message
2575            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2576            .next()
2577            .is_some()
2578        {
2579            return; // Hide the cancelled by user message
2580        } else {
2581            workspace.update(cx, |workspace, cx| {
2582                let workspace_weak = cx.weak_entity();
2583                let toast =
2584                    StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2585                        this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2586                            .action("View Log", move |window, cx| {
2587                                let message = message.clone();
2588                                let action = action.clone();
2589                                workspace_weak
2590                                    .update(cx, move |workspace, cx| {
2591                                        Self::open_output(action, workspace, &message, window, cx)
2592                                    })
2593                                    .ok();
2594                            })
2595                    });
2596                workspace.toggle_status_toast(toast, cx)
2597            });
2598        }
2599    }
2600
2601    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2602        let Some(workspace) = self.workspace.upgrade() else {
2603            return;
2604        };
2605
2606        workspace.update(cx, |workspace, cx| {
2607            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2608            let workspace_weak = cx.weak_entity();
2609            let operation = action.name();
2610
2611            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2612                use remote_output::SuccessStyle::*;
2613                match style {
2614                    Toast { .. } => this,
2615                    ToastWithLog { output } => this
2616                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2617                        .action("View Log", move |window, cx| {
2618                            let output = output.clone();
2619                            let output =
2620                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2621                            workspace_weak
2622                                .update(cx, move |workspace, cx| {
2623                                    Self::open_output(operation, workspace, &output, window, cx)
2624                                })
2625                                .ok();
2626                        }),
2627                    PushPrLink { link } => this
2628                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2629                        .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2630                }
2631            });
2632            workspace.toggle_status_toast(status_toast, cx)
2633        });
2634    }
2635
2636    fn open_output(
2637        operation: impl Into<SharedString>,
2638        workspace: &mut Workspace,
2639        output: &str,
2640        window: &mut Window,
2641        cx: &mut Context<Workspace>,
2642    ) {
2643        let operation = operation.into();
2644        let buffer = cx.new(|cx| Buffer::local(output, cx));
2645        buffer.update(cx, |buffer, cx| {
2646            buffer.set_capability(language::Capability::ReadOnly, cx);
2647        });
2648        let editor = cx.new(|cx| {
2649            let mut editor = Editor::for_buffer(buffer, None, window, cx);
2650            editor.buffer().update(cx, |buffer, cx| {
2651                buffer.set_title(format!("Output from git {operation}"), cx);
2652            });
2653            editor.set_read_only(true);
2654            editor
2655        });
2656
2657        workspace.add_item_to_center(Box::new(editor), window, cx);
2658    }
2659
2660    pub fn can_commit(&self) -> bool {
2661        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2662    }
2663
2664    pub fn can_stage_all(&self) -> bool {
2665        self.has_unstaged_changes()
2666    }
2667
2668    pub fn can_unstage_all(&self) -> bool {
2669        self.has_staged_changes()
2670    }
2671
2672    // eventually we'll need to take depth into account here
2673    // if we add a tree view
2674    fn item_width_estimate(path: usize, file_name: usize) -> usize {
2675        path + file_name
2676    }
2677
2678    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2679        let focus_handle = self.focus_handle.clone();
2680        let has_tracked_changes = self.has_tracked_changes();
2681        let has_staged_changes = self.has_staged_changes();
2682        let has_unstaged_changes = self.has_unstaged_changes();
2683        let has_new_changes = self.new_count > 0;
2684
2685        PopoverMenu::new(id.into())
2686            .trigger(
2687                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2688                    .icon_size(IconSize::Small)
2689                    .icon_color(Color::Muted),
2690            )
2691            .menu(move |window, cx| {
2692                Some(git_panel_context_menu(
2693                    focus_handle.clone(),
2694                    GitMenuState {
2695                        has_tracked_changes,
2696                        has_staged_changes,
2697                        has_unstaged_changes,
2698                        has_new_changes,
2699                    },
2700                    window,
2701                    cx,
2702                ))
2703            })
2704            .anchor(Corner::TopRight)
2705    }
2706
2707    pub(crate) fn render_generate_commit_message_button(
2708        &self,
2709        cx: &Context<Self>,
2710    ) -> Option<AnyElement> {
2711        current_language_model(cx).is_some().then(|| {
2712            if self.generate_commit_message_task.is_some() {
2713                return h_flex()
2714                    .gap_1()
2715                    .child(
2716                        Icon::new(IconName::ArrowCircle)
2717                            .size(IconSize::XSmall)
2718                            .color(Color::Info)
2719                            .with_animation(
2720                                "arrow-circle",
2721                                Animation::new(Duration::from_secs(2)).repeat(),
2722                                |icon, delta| {
2723                                    icon.transform(Transformation::rotate(percentage(delta)))
2724                                },
2725                            ),
2726                    )
2727                    .child(
2728                        Label::new("Generating Commit...")
2729                            .size(LabelSize::Small)
2730                            .color(Color::Muted),
2731                    )
2732                    .into_any_element();
2733            }
2734
2735            let can_commit = self.can_commit();
2736            let editor_focus_handle = self.commit_editor.focus_handle(cx);
2737            IconButton::new("generate-commit-message", IconName::AiEdit)
2738                .shape(ui::IconButtonShape::Square)
2739                .icon_color(Color::Muted)
2740                .tooltip(move |window, cx| {
2741                    if can_commit {
2742                        Tooltip::for_action_in(
2743                            "Generate Commit Message",
2744                            &git::GenerateCommitMessage,
2745                            &editor_focus_handle,
2746                            window,
2747                            cx,
2748                        )
2749                    } else {
2750                        Tooltip::simple("No changes to commit", cx)
2751                    }
2752                })
2753                .disabled(!can_commit)
2754                .on_click(cx.listener(move |this, _event, _window, cx| {
2755                    this.generate_commit_message(cx);
2756                }))
2757                .into_any_element()
2758        })
2759    }
2760
2761    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2762        let potential_co_authors = self.potential_co_authors(cx);
2763
2764        let (tooltip_label, icon) = if self.add_coauthors {
2765            ("Add co-authored-by", IconName::UserCheck)
2766        } else {
2767            ("Remove co-authored-by", IconName::Person)
2768        };
2769
2770        if potential_co_authors.is_empty() {
2771            None
2772        } else {
2773            Some(
2774                IconButton::new("co-authors", icon)
2775                    .shape(ui::IconButtonShape::Square)
2776                    .icon_color(Color::Disabled)
2777                    .selected_icon_color(Color::Selected)
2778                    .toggle_state(self.add_coauthors)
2779                    .tooltip(move |_, cx| {
2780                        let title = format!(
2781                            "{}:{}{}",
2782                            tooltip_label,
2783                            if potential_co_authors.len() == 1 {
2784                                ""
2785                            } else {
2786                                "\n"
2787                            },
2788                            potential_co_authors
2789                                .iter()
2790                                .map(|(name, email)| format!(" {} <{}>", name, email))
2791                                .join("\n")
2792                        );
2793                        Tooltip::simple(title, cx)
2794                    })
2795                    .on_click(cx.listener(|this, _, _, cx| {
2796                        this.add_coauthors = !this.add_coauthors;
2797                        cx.notify();
2798                    }))
2799                    .into_any_element(),
2800            )
2801        }
2802    }
2803
2804    fn render_git_commit_menu(
2805        &self,
2806        id: impl Into<ElementId>,
2807        keybinding_target: Option<FocusHandle>,
2808    ) -> impl IntoElement {
2809        PopoverMenu::new(id.into())
2810            .trigger(
2811                ui::ButtonLike::new_rounded_right("commit-split-button-right")
2812                    .layer(ui::ElevationIndex::ModalSurface)
2813                    .size(ui::ButtonSize::None)
2814                    .child(
2815                        div()
2816                            .px_1()
2817                            .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
2818                    ),
2819            )
2820            .menu(move |window, cx| {
2821                Some(ContextMenu::build(window, cx, |context_menu, _, _| {
2822                    context_menu
2823                        .when_some(keybinding_target.clone(), |el, keybinding_target| {
2824                            el.context(keybinding_target.clone())
2825                        })
2826                        .action("Amend", Amend.boxed_clone())
2827                }))
2828            })
2829            .anchor(Corner::TopRight)
2830    }
2831
2832    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2833        if self.has_unstaged_conflicts() {
2834            (false, "You must resolve conflicts before committing")
2835        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2836            (false, "No changes to commit")
2837        } else if self.pending_commit.is_some() {
2838            (false, "Commit in progress")
2839        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2840            (false, "No commit message")
2841        } else if !self.has_write_access(cx) {
2842            (false, "You do not have write access to this project")
2843        } else {
2844            (true, self.commit_button_title())
2845        }
2846    }
2847
2848    pub fn commit_button_title(&self) -> &'static str {
2849        if self.amend_pending {
2850            if self.has_staged_changes() {
2851                "Amend"
2852            } else {
2853                "Amend Tracked"
2854            }
2855        } else {
2856            if self.has_staged_changes() {
2857                "Commit"
2858            } else {
2859                "Commit Tracked"
2860            }
2861        }
2862    }
2863
2864    fn expand_commit_editor(
2865        &mut self,
2866        _: &git::ExpandCommitEditor,
2867        window: &mut Window,
2868        cx: &mut Context<Self>,
2869    ) {
2870        let workspace = self.workspace.clone();
2871        window.defer(cx, move |window, cx| {
2872            workspace
2873                .update(cx, |workspace, cx| {
2874                    CommitModal::toggle(workspace, None, window, cx)
2875                })
2876                .ok();
2877        })
2878    }
2879
2880    fn render_panel_header(
2881        &self,
2882        window: &mut Window,
2883        cx: &mut Context<Self>,
2884    ) -> Option<impl IntoElement> {
2885        self.active_repository.as_ref()?;
2886
2887        let text;
2888        let action;
2889        let tooltip;
2890        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2891            text = "Unstage All";
2892            action = git::UnstageAll.boxed_clone();
2893            tooltip = "git reset";
2894        } else {
2895            text = "Stage All";
2896            action = git::StageAll.boxed_clone();
2897            tooltip = "git add --all ."
2898        }
2899
2900        let change_string = match self.entry_count {
2901            0 => "No Changes".to_string(),
2902            1 => "1 Change".to_string(),
2903            _ => format!("{} Changes", self.entry_count),
2904        };
2905
2906        Some(
2907            self.panel_header_container(window, cx)
2908                .px_2()
2909                .child(
2910                    panel_button(change_string)
2911                        .color(Color::Muted)
2912                        .tooltip(Tooltip::for_action_title_in(
2913                            "Open Diff",
2914                            &Diff,
2915                            &self.focus_handle,
2916                        ))
2917                        .on_click(|_, _, cx| {
2918                            cx.defer(|cx| {
2919                                cx.dispatch_action(&Diff);
2920                            })
2921                        }),
2922                )
2923                .child(div().flex_grow()) // spacer
2924                .child(self.render_overflow_menu("overflow_menu"))
2925                .child(div().w_2()) // another spacer
2926                .child(
2927                    panel_filled_button(text)
2928                        .tooltip(Tooltip::for_action_title_in(
2929                            tooltip,
2930                            action.as_ref(),
2931                            &self.focus_handle,
2932                        ))
2933                        .disabled(self.entry_count == 0)
2934                        .on_click(move |_, _, cx| {
2935                            let action = action.boxed_clone();
2936                            cx.defer(move |cx| {
2937                                cx.dispatch_action(action.as_ref());
2938                            })
2939                        }),
2940                ),
2941        )
2942    }
2943
2944    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2945        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
2946        if !self.can_push_and_pull(cx) {
2947            return None;
2948        }
2949        Some(
2950            h_flex()
2951                .gap_1()
2952                .flex_shrink_0()
2953                .when_some(branch, |this, branch| {
2954                    let focus_handle = Some(self.focus_handle(cx));
2955
2956                    this.children(render_remote_button(
2957                        "remote-button",
2958                        &branch,
2959                        focus_handle,
2960                        true,
2961                    ))
2962                })
2963                .into_any_element(),
2964        )
2965    }
2966
2967    pub fn render_footer(
2968        &self,
2969        window: &mut Window,
2970        cx: &mut Context<Self>,
2971    ) -> Option<impl IntoElement> {
2972        let active_repository = self.active_repository.clone()?;
2973        let panel_editor_style = panel_editor_style(true, window, cx);
2974
2975        let enable_coauthors = self.render_co_authors(cx);
2976
2977        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2978        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2979
2980        let branch = active_repository.read(cx).branch.clone();
2981        let head_commit = active_repository.read(cx).head_commit.clone();
2982
2983        let footer_size = px(32.);
2984        let gap = px(9.0);
2985        let max_height = panel_editor_style
2986            .text
2987            .line_height_in_pixels(window.rem_size())
2988            * MAX_PANEL_EDITOR_LINES
2989            + gap;
2990
2991        let git_panel = cx.entity().clone();
2992        let display_name = SharedString::from(Arc::from(
2993            active_repository
2994                .read(cx)
2995                .display_name()
2996                .trim_end_matches("/"),
2997        ));
2998        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2999            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3000        });
3001        let has_previous_commit = head_commit.is_some();
3002
3003        let footer = v_flex()
3004            .child(PanelRepoFooter::new(
3005                display_name,
3006                branch,
3007                head_commit,
3008                Some(git_panel.clone()),
3009            ))
3010            .child(
3011                panel_editor_container(window, cx)
3012                    .id("commit-editor-container")
3013                    .relative()
3014                    .w_full()
3015                    .h(max_height + footer_size)
3016                    .border_t_1()
3017                    .border_color(cx.theme().colors().border_variant)
3018                    .cursor_text()
3019                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3020                        window.focus(&this.commit_editor.focus_handle(cx));
3021                    }))
3022                    .child(
3023                        h_flex()
3024                            .id("commit-footer")
3025                            .border_t_1()
3026                            .when(editor_is_long, |el| {
3027                                el.border_color(cx.theme().colors().border_variant)
3028                            })
3029                            .absolute()
3030                            .bottom_0()
3031                            .left_0()
3032                            .w_full()
3033                            .px_2()
3034                            .h(footer_size)
3035                            .flex_none()
3036                            .justify_between()
3037                            .child(
3038                                self.render_generate_commit_message_button(cx)
3039                                    .unwrap_or_else(|| div().into_any_element()),
3040                            )
3041                            .child(
3042                                h_flex()
3043                                    .gap_0p5()
3044                                    .children(enable_coauthors)
3045                                    .child(self.render_commit_button(has_previous_commit, cx)),
3046                            ),
3047                    )
3048                    .child(
3049                        div()
3050                            .pr_2p5()
3051                            .on_action(|&editor::actions::MoveUp, _, cx| {
3052                                cx.stop_propagation();
3053                            })
3054                            .on_action(|&editor::actions::MoveDown, _, cx| {
3055                                cx.stop_propagation();
3056                            })
3057                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3058                    )
3059                    .child(
3060                        h_flex()
3061                            .absolute()
3062                            .top_2()
3063                            .right_2()
3064                            .opacity(0.5)
3065                            .hover(|this| this.opacity(1.0))
3066                            .child(
3067                                panel_icon_button("expand-commit-editor", IconName::Maximize)
3068                                    .icon_size(IconSize::Small)
3069                                    .size(ui::ButtonSize::Default)
3070                                    .tooltip(move |window, cx| {
3071                                        Tooltip::for_action_in(
3072                                            "Open Commit Modal",
3073                                            &git::ExpandCommitEditor,
3074                                            &expand_tooltip_focus_handle,
3075                                            window,
3076                                            cx,
3077                                        )
3078                                    })
3079                                    .on_click(cx.listener({
3080                                        move |_, _, window, cx| {
3081                                            window.dispatch_action(
3082                                                git::ExpandCommitEditor.boxed_clone(),
3083                                                cx,
3084                                            )
3085                                        }
3086                                    })),
3087                            ),
3088                    ),
3089            );
3090
3091        Some(footer)
3092    }
3093
3094    fn render_commit_button(
3095        &self,
3096        has_previous_commit: bool,
3097        cx: &mut Context<Self>,
3098    ) -> impl IntoElement {
3099        let (can_commit, tooltip) = self.configure_commit_button(cx);
3100        let title = self.commit_button_title();
3101        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3102        div()
3103            .id("commit-wrapper")
3104            .on_hover(cx.listener(move |this, hovered, _, cx| {
3105                this.show_placeholders =
3106                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3107                cx.notify()
3108            }))
3109            .when(self.amend_pending, {
3110                |this| {
3111                    this.h_flex()
3112                        .gap_1()
3113                        .child(
3114                            panel_filled_button("Cancel")
3115                                .tooltip({
3116                                    let handle = commit_tooltip_focus_handle.clone();
3117                                    move |window, cx| {
3118                                        Tooltip::for_action_in(
3119                                            "Cancel amend",
3120                                            &git::Cancel,
3121                                            &handle,
3122                                            window,
3123                                            cx,
3124                                        )
3125                                    }
3126                                })
3127                                .on_click(move |_, window, cx| {
3128                                    window.dispatch_action(Box::new(git::Cancel), cx);
3129                                }),
3130                        )
3131                        .child(
3132                            panel_filled_button(title)
3133                                .tooltip({
3134                                    let handle = commit_tooltip_focus_handle.clone();
3135                                    move |window, cx| {
3136                                        if can_commit {
3137                                            Tooltip::for_action_in(
3138                                                tooltip, &Amend, &handle, window, cx,
3139                                            )
3140                                        } else {
3141                                            Tooltip::simple(tooltip, cx)
3142                                        }
3143                                    }
3144                                })
3145                                .disabled(!can_commit || self.modal_open)
3146                                .on_click({
3147                                    let git_panel = cx.weak_entity();
3148                                    move |_, window, cx| {
3149                                        telemetry::event!("Git Amended", source = "Git Panel");
3150                                        git_panel
3151                                            .update(cx, |git_panel, cx| {
3152                                                git_panel.set_amend_pending(false, cx);
3153                                                git_panel.commit_changes(
3154                                                    CommitOptions { amend: true },
3155                                                    window,
3156                                                    cx,
3157                                                );
3158                                            })
3159                                            .ok();
3160                                    }
3161                                }),
3162                        )
3163                }
3164            })
3165            .when(!self.amend_pending, |this| {
3166                this.when(has_previous_commit, |this| {
3167                    this.child(SplitButton::new(
3168                        ui::ButtonLike::new_rounded_left(ElementId::Name(
3169                            format!("split-button-left-{}", title).into(),
3170                        ))
3171                        .layer(ui::ElevationIndex::ModalSurface)
3172                        .size(ui::ButtonSize::Compact)
3173                        .child(
3174                            div()
3175                                .child(Label::new(title).size(LabelSize::Small))
3176                                .mr_0p5(),
3177                        )
3178                        .on_click({
3179                            let git_panel = cx.weak_entity();
3180                            move |_, window, cx| {
3181                                telemetry::event!("Git Committed", source = "Git Panel");
3182                                git_panel
3183                                    .update(cx, |git_panel, cx| {
3184                                        git_panel.commit_changes(
3185                                            CommitOptions { amend: false },
3186                                            window,
3187                                            cx,
3188                                        );
3189                                    })
3190                                    .ok();
3191                            }
3192                        })
3193                        .disabled(!can_commit || self.modal_open)
3194                        .tooltip({
3195                            let handle = commit_tooltip_focus_handle.clone();
3196                            move |window, cx| {
3197                                if can_commit {
3198                                    Tooltip::with_meta_in(
3199                                        tooltip,
3200                                        Some(&git::Commit),
3201                                        "git commit",
3202                                        &handle.clone(),
3203                                        window,
3204                                        cx,
3205                                    )
3206                                } else {
3207                                    Tooltip::simple(tooltip, cx)
3208                                }
3209                            }
3210                        }),
3211                        self.render_git_commit_menu(
3212                            ElementId::Name(format!("split-button-right-{}", title).into()),
3213                            Some(commit_tooltip_focus_handle.clone()),
3214                        )
3215                        .into_any_element(),
3216                    ))
3217                })
3218                .when(!has_previous_commit, |this| {
3219                    this.child(
3220                        panel_filled_button(title)
3221                            .tooltip(move |window, cx| {
3222                                if can_commit {
3223                                    Tooltip::with_meta_in(
3224                                        tooltip,
3225                                        Some(&git::Commit),
3226                                        "git commit",
3227                                        &commit_tooltip_focus_handle,
3228                                        window,
3229                                        cx,
3230                                    )
3231                                } else {
3232                                    Tooltip::simple(tooltip, cx)
3233                                }
3234                            })
3235                            .disabled(!can_commit || self.modal_open)
3236                            .on_click({
3237                                let git_panel = cx.weak_entity();
3238                                move |_, window, cx| {
3239                                    telemetry::event!("Git Committed", source = "Git Panel");
3240                                    git_panel
3241                                        .update(cx, |git_panel, cx| {
3242                                            git_panel.commit_changes(
3243                                                CommitOptions { amend: false },
3244                                                window,
3245                                                cx,
3246                                            );
3247                                        })
3248                                        .ok();
3249                                }
3250                            }),
3251                    )
3252                })
3253            })
3254    }
3255
3256    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3257        div()
3258            .py_2()
3259            .px(px(8.))
3260            .border_color(cx.theme().colors().border)
3261            .child(
3262                Label::new(
3263                    "This will update your most recent commit. Cancel to make a new one instead.",
3264                )
3265                .size(LabelSize::Small),
3266            )
3267    }
3268
3269    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3270        let active_repository = self.active_repository.as_ref()?;
3271        let branch = active_repository.read(cx).branch.as_ref()?;
3272        let commit = branch.most_recent_commit.as_ref()?.clone();
3273        let workspace = self.workspace.clone();
3274
3275        let this = cx.entity();
3276        Some(
3277            h_flex()
3278                .items_center()
3279                .py_2()
3280                .px(px(8.))
3281                .border_color(cx.theme().colors().border)
3282                .gap_1p5()
3283                .child(
3284                    div()
3285                        .flex_grow()
3286                        .overflow_hidden()
3287                        .items_center()
3288                        .max_w(relative(0.85))
3289                        .h_full()
3290                        .child(
3291                            Label::new(commit.subject.clone())
3292                                .size(LabelSize::Small)
3293                                .truncate(),
3294                        )
3295                        .id("commit-msg-hover")
3296                        .on_click({
3297                            let commit = commit.clone();
3298                            let repo = active_repository.downgrade();
3299                            move |_, window, cx| {
3300                                CommitView::open(
3301                                    commit.clone(),
3302                                    repo.clone(),
3303                                    workspace.clone().clone(),
3304                                    window,
3305                                    cx,
3306                                );
3307                            }
3308                        })
3309                        .hoverable_tooltip({
3310                            let repo = active_repository.clone();
3311                            move |window, cx| {
3312                                GitPanelMessageTooltip::new(
3313                                    this.clone(),
3314                                    commit.sha.clone(),
3315                                    repo.clone(),
3316                                    window,
3317                                    cx,
3318                                )
3319                                .into()
3320                            }
3321                        }),
3322                )
3323                .child(div().flex_1())
3324                .when(commit.has_parent, |this| {
3325                    let has_unstaged = self.has_unstaged_changes();
3326                    this.child(
3327                        panel_icon_button("undo", IconName::Undo)
3328                            .icon_size(IconSize::Small)
3329                            .icon_color(Color::Muted)
3330                            .tooltip(move |window, cx| {
3331                                Tooltip::with_meta(
3332                                    "Uncommit",
3333                                    Some(&git::Uncommit),
3334                                    if has_unstaged {
3335                                        "git reset HEAD^ --soft"
3336                                    } else {
3337                                        "git reset HEAD^"
3338                                    },
3339                                    window,
3340                                    cx,
3341                                )
3342                            })
3343                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3344                    )
3345                }),
3346        )
3347    }
3348
3349    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3350        h_flex()
3351            .h_full()
3352            .flex_grow()
3353            .justify_center()
3354            .items_center()
3355            .child(
3356                v_flex()
3357                    .gap_2()
3358                    .child(h_flex().w_full().justify_around().child(
3359                        if self.active_repository.is_some() {
3360                            "No changes to commit"
3361                        } else {
3362                            "No Git repositories"
3363                        },
3364                    ))
3365                    .children({
3366                        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3367                        (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3368                            h_flex().w_full().justify_around().child(
3369                                panel_filled_button("Initialize Repository")
3370                                    .tooltip(Tooltip::for_action_title_in(
3371                                        "git init",
3372                                        &git::Init,
3373                                        &self.focus_handle,
3374                                    ))
3375                                    .on_click(move |_, _, cx| {
3376                                        cx.defer(move |cx| {
3377                                            cx.dispatch_action(&git::Init);
3378                                        })
3379                                    }),
3380                            )
3381                        })
3382                    })
3383                    .text_ui_sm(cx)
3384                    .mx_auto()
3385                    .text_color(Color::Placeholder.color(cx)),
3386            )
3387    }
3388
3389    fn render_vertical_scrollbar(
3390        &self,
3391        show_horizontal_scrollbar_container: bool,
3392        cx: &mut Context<Self>,
3393    ) -> impl IntoElement {
3394        div()
3395            .id("git-panel-vertical-scroll")
3396            .occlude()
3397            .flex_none()
3398            .h_full()
3399            .cursor_default()
3400            .absolute()
3401            .right_0()
3402            .top_0()
3403            .bottom_0()
3404            .w(px(12.))
3405            .when(show_horizontal_scrollbar_container, |this| {
3406                this.pb_neg_3p5()
3407            })
3408            .on_mouse_move(cx.listener(|_, _, _, cx| {
3409                cx.notify();
3410                cx.stop_propagation()
3411            }))
3412            .on_hover(|_, _, cx| {
3413                cx.stop_propagation();
3414            })
3415            .on_any_mouse_down(|_, _, cx| {
3416                cx.stop_propagation();
3417            })
3418            .on_mouse_up(
3419                MouseButton::Left,
3420                cx.listener(|this, _, window, cx| {
3421                    if !this.vertical_scrollbar.state.is_dragging()
3422                        && !this.focus_handle.contains_focused(window, cx)
3423                    {
3424                        this.vertical_scrollbar.hide(window, cx);
3425                        cx.notify();
3426                    }
3427
3428                    cx.stop_propagation();
3429                }),
3430            )
3431            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3432                cx.notify();
3433            }))
3434            .children(Scrollbar::vertical(
3435                // percentage as f32..end_offset as f32,
3436                self.vertical_scrollbar.state.clone(),
3437            ))
3438    }
3439
3440    /// Renders the horizontal scrollbar.
3441    ///
3442    /// The right offset is used to determine how far to the right the
3443    /// scrollbar should extend to, useful for ensuring it doesn't collide
3444    /// with the vertical scrollbar when visible.
3445    fn render_horizontal_scrollbar(
3446        &self,
3447        right_offset: Pixels,
3448        cx: &mut Context<Self>,
3449    ) -> impl IntoElement {
3450        div()
3451            .id("git-panel-horizontal-scroll")
3452            .occlude()
3453            .flex_none()
3454            .w_full()
3455            .cursor_default()
3456            .absolute()
3457            .bottom_neg_px()
3458            .left_0()
3459            .right_0()
3460            .pr(right_offset)
3461            .on_mouse_move(cx.listener(|_, _, _, cx| {
3462                cx.notify();
3463                cx.stop_propagation()
3464            }))
3465            .on_hover(|_, _, cx| {
3466                cx.stop_propagation();
3467            })
3468            .on_any_mouse_down(|_, _, cx| {
3469                cx.stop_propagation();
3470            })
3471            .on_mouse_up(
3472                MouseButton::Left,
3473                cx.listener(|this, _, window, cx| {
3474                    if !this.horizontal_scrollbar.state.is_dragging()
3475                        && !this.focus_handle.contains_focused(window, cx)
3476                    {
3477                        this.horizontal_scrollbar.hide(window, cx);
3478                        cx.notify();
3479                    }
3480
3481                    cx.stop_propagation();
3482                }),
3483            )
3484            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3485                cx.notify();
3486            }))
3487            .children(Scrollbar::horizontal(
3488                // percentage as f32..end_offset as f32,
3489                self.horizontal_scrollbar.state.clone(),
3490            ))
3491    }
3492
3493    fn render_buffer_header_controls(
3494        &self,
3495        entity: &Entity<Self>,
3496        file: &Arc<dyn File>,
3497        _: &Window,
3498        cx: &App,
3499    ) -> Option<AnyElement> {
3500        let repo = self.active_repository.as_ref()?.read(cx);
3501        let project_path = (file.worktree_id(cx), file.path()).into();
3502        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3503        let ix = self.entry_by_path(&repo_path, cx)?;
3504        let entry = self.entries.get(ix)?;
3505
3506        let entry_staging = self.entry_staging(entry.status_entry()?);
3507
3508        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3509            .disabled(!self.has_write_access(cx))
3510            .fill()
3511            .elevation(ElevationIndex::Surface)
3512            .on_click({
3513                let entry = entry.clone();
3514                let git_panel = entity.downgrade();
3515                move |_, window, cx| {
3516                    git_panel
3517                        .update(cx, |this, cx| {
3518                            this.toggle_staged_for_entry(&entry, window, cx);
3519                            cx.stop_propagation();
3520                        })
3521                        .ok();
3522                }
3523            });
3524        Some(
3525            h_flex()
3526                .id("start-slot")
3527                .text_lg()
3528                .child(checkbox)
3529                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3530                    // prevent the list item active state triggering when toggling checkbox
3531                    cx.stop_propagation();
3532                })
3533                .into_any_element(),
3534        )
3535    }
3536
3537    fn render_entries(
3538        &self,
3539        has_write_access: bool,
3540        _: &Window,
3541        cx: &mut Context<Self>,
3542    ) -> impl IntoElement {
3543        let entry_count = self.entries.len();
3544
3545        let scroll_track_size = px(16.);
3546
3547        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3548            // magic number
3549            px(3.)
3550        } else {
3551            px(0.)
3552        };
3553
3554        v_flex()
3555            .flex_1()
3556            .size_full()
3557            .overflow_hidden()
3558            .relative()
3559            // Show a border on the top and bottom of the container when
3560            // the vertical scrollbar container is visible so we don't have a
3561            // floating left border in the panel.
3562            .when(self.vertical_scrollbar.show_track, |this| {
3563                this.border_t_1()
3564                    .border_b_1()
3565                    .border_color(cx.theme().colors().border)
3566            })
3567            .child(
3568                h_flex()
3569                    .flex_1()
3570                    .size_full()
3571                    .relative()
3572                    .overflow_hidden()
3573                    .child(
3574                        uniform_list(cx.entity().clone(), "entries", entry_count, {
3575                            move |this, range, window, cx| {
3576                                let mut items = Vec::with_capacity(range.end - range.start);
3577
3578                                for ix in range {
3579                                    match &this.entries.get(ix) {
3580                                        Some(GitListEntry::GitStatusEntry(entry)) => {
3581                                            items.push(this.render_entry(
3582                                                ix,
3583                                                entry,
3584                                                has_write_access,
3585                                                window,
3586                                                cx,
3587                                            ));
3588                                        }
3589                                        Some(GitListEntry::Header(header)) => {
3590                                            items.push(this.render_list_header(
3591                                                ix,
3592                                                header,
3593                                                has_write_access,
3594                                                window,
3595                                                cx,
3596                                            ));
3597                                        }
3598                                        None => {}
3599                                    }
3600                                }
3601
3602                                items
3603                            }
3604                        })
3605                        .when(
3606                            !self.horizontal_scrollbar.show_track
3607                                && self.horizontal_scrollbar.show_scrollbar,
3608                            |this| {
3609                                // when not showing the horizontal scrollbar track, make sure we don't
3610                                // obscure the last entry
3611                                this.pb(scroll_track_size)
3612                            },
3613                        )
3614                        .size_full()
3615                        .flex_grow()
3616                        .with_sizing_behavior(ListSizingBehavior::Auto)
3617                        .with_horizontal_sizing_behavior(
3618                            ListHorizontalSizingBehavior::Unconstrained,
3619                        )
3620                        .with_width_from_item(self.max_width_item_index)
3621                        .track_scroll(self.scroll_handle.clone()),
3622                    )
3623                    .on_mouse_down(
3624                        MouseButton::Right,
3625                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3626                            this.deploy_panel_context_menu(event.position, window, cx)
3627                        }),
3628                    )
3629                    .when(self.vertical_scrollbar.show_track, |this| {
3630                        this.child(
3631                            v_flex()
3632                                .h_full()
3633                                .flex_none()
3634                                .w(scroll_track_size)
3635                                .bg(cx.theme().colors().panel_background)
3636                                .child(
3637                                    div()
3638                                        .size_full()
3639                                        .flex_1()
3640                                        .border_l_1()
3641                                        .border_color(cx.theme().colors().border),
3642                                ),
3643                        )
3644                    })
3645                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
3646                        this.child(
3647                            self.render_vertical_scrollbar(
3648                                self.horizontal_scrollbar.show_track,
3649                                cx,
3650                            ),
3651                        )
3652                    }),
3653            )
3654            .when(self.horizontal_scrollbar.show_track, |this| {
3655                this.child(
3656                    h_flex()
3657                        .w_full()
3658                        .h(scroll_track_size)
3659                        .flex_none()
3660                        .relative()
3661                        .child(
3662                            div()
3663                                .w_full()
3664                                .flex_1()
3665                                // for some reason the horizontal scrollbar is 1px
3666                                // taller than the vertical scrollbar??
3667                                .h(scroll_track_size - px(1.))
3668                                .bg(cx.theme().colors().panel_background)
3669                                .border_t_1()
3670                                .border_color(cx.theme().colors().border),
3671                        )
3672                        .when(self.vertical_scrollbar.show_track, |this| {
3673                            this.child(
3674                                div()
3675                                    .flex_none()
3676                                    // -1px prevents a missing pixel between the two container borders
3677                                    .w(scroll_track_size - px(1.))
3678                                    .h_full(),
3679                            )
3680                            .child(
3681                                // HACK: Fill the missing 1px 🥲
3682                                div()
3683                                    .absolute()
3684                                    .right(scroll_track_size - px(1.))
3685                                    .bottom(scroll_track_size - px(1.))
3686                                    .size_px()
3687                                    .bg(cx.theme().colors().border),
3688                            )
3689                        }),
3690                )
3691            })
3692            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3693                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3694            })
3695    }
3696
3697    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3698        Label::new(label.into()).color(color).single_line()
3699    }
3700
3701    fn list_item_height(&self) -> Rems {
3702        rems(1.75)
3703    }
3704
3705    fn render_list_header(
3706        &self,
3707        ix: usize,
3708        header: &GitHeaderEntry,
3709        _: bool,
3710        _: &Window,
3711        _: &Context<Self>,
3712    ) -> AnyElement {
3713        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3714
3715        h_flex()
3716            .id(id)
3717            .h(self.list_item_height())
3718            .w_full()
3719            .items_end()
3720            .px(rems(0.75)) // ~12px
3721            .pb(rems(0.3125)) // ~ 5px
3722            .child(
3723                Label::new(header.title())
3724                    .color(Color::Muted)
3725                    .size(LabelSize::Small)
3726                    .line_height_style(LineHeightStyle::UiLabel)
3727                    .single_line(),
3728            )
3729            .into_any_element()
3730    }
3731
3732    pub fn load_commit_details(
3733        &self,
3734        sha: String,
3735        cx: &mut Context<Self>,
3736    ) -> Task<anyhow::Result<CommitDetails>> {
3737        let Some(repo) = self.active_repository.clone() else {
3738            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3739        };
3740        repo.update(cx, |repo, cx| {
3741            let show = repo.show(sha);
3742            cx.spawn(async move |_, _| show.await?)
3743        })
3744    }
3745
3746    fn deploy_entry_context_menu(
3747        &mut self,
3748        position: Point<Pixels>,
3749        ix: usize,
3750        window: &mut Window,
3751        cx: &mut Context<Self>,
3752    ) {
3753        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3754            return;
3755        };
3756        let stage_title = if entry.status.staging().is_fully_staged() {
3757            "Unstage File"
3758        } else {
3759            "Stage File"
3760        };
3761        let restore_title = if entry.status.is_created() {
3762            "Trash File"
3763        } else {
3764            "Restore File"
3765        };
3766        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3767            context_menu
3768                .context(self.focus_handle.clone())
3769                .action(stage_title, ToggleStaged.boxed_clone())
3770                .action(restore_title, git::RestoreFile::default().boxed_clone())
3771                .separator()
3772                .action("Open Diff", Confirm.boxed_clone())
3773                .action("Open File", SecondaryConfirm.boxed_clone())
3774        });
3775        self.selected_entry = Some(ix);
3776        self.set_context_menu(context_menu, position, window, cx);
3777    }
3778
3779    fn deploy_panel_context_menu(
3780        &mut self,
3781        position: Point<Pixels>,
3782        window: &mut Window,
3783        cx: &mut Context<Self>,
3784    ) {
3785        let context_menu = git_panel_context_menu(
3786            self.focus_handle.clone(),
3787            GitMenuState {
3788                has_tracked_changes: self.has_tracked_changes(),
3789                has_staged_changes: self.has_staged_changes(),
3790                has_unstaged_changes: self.has_unstaged_changes(),
3791                has_new_changes: self.new_count > 0,
3792            },
3793            window,
3794            cx,
3795        );
3796        self.set_context_menu(context_menu, position, window, cx);
3797    }
3798
3799    fn set_context_menu(
3800        &mut self,
3801        context_menu: Entity<ContextMenu>,
3802        position: Point<Pixels>,
3803        window: &Window,
3804        cx: &mut Context<Self>,
3805    ) {
3806        let subscription = cx.subscribe_in(
3807            &context_menu,
3808            window,
3809            |this, _, _: &DismissEvent, window, cx| {
3810                if this.context_menu.as_ref().is_some_and(|context_menu| {
3811                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3812                }) {
3813                    cx.focus_self(window);
3814                }
3815                this.context_menu.take();
3816                cx.notify();
3817            },
3818        );
3819        self.context_menu = Some((context_menu, position, subscription));
3820        cx.notify();
3821    }
3822
3823    fn render_entry(
3824        &self,
3825        ix: usize,
3826        entry: &GitStatusEntry,
3827        has_write_access: bool,
3828        window: &Window,
3829        cx: &Context<Self>,
3830    ) -> AnyElement {
3831        let display_name = entry.display_name();
3832
3833        let selected = self.selected_entry == Some(ix);
3834        let marked = self.marked_entries.contains(&ix);
3835        let status_style = GitPanelSettings::get_global(cx).status_style;
3836        let status = entry.status;
3837        let modifiers = self.current_modifiers;
3838        let shift_held = modifiers.shift;
3839
3840        let has_conflict = status.is_conflicted();
3841        let is_modified = status.is_modified();
3842        let is_deleted = status.is_deleted();
3843
3844        let label_color = if status_style == StatusStyle::LabelColor {
3845            if has_conflict {
3846                Color::VersionControlConflict
3847            } else if is_modified {
3848                Color::VersionControlModified
3849            } else if is_deleted {
3850                // We don't want a bunch of red labels in the list
3851                Color::Disabled
3852            } else {
3853                Color::VersionControlAdded
3854            }
3855        } else {
3856            Color::Default
3857        };
3858
3859        let path_color = if status.is_deleted() {
3860            Color::Disabled
3861        } else {
3862            Color::Muted
3863        };
3864
3865        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3866        let checkbox_wrapper_id: ElementId =
3867            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3868        let checkbox_id: ElementId =
3869            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3870
3871        let entry_staging = self.entry_staging(entry);
3872        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3873        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
3874            is_staged = ToggleState::Selected;
3875        }
3876
3877        let handle = cx.weak_entity();
3878
3879        let selected_bg_alpha = 0.08;
3880        let marked_bg_alpha = 0.12;
3881        let state_opacity_step = 0.04;
3882
3883        let base_bg = match (selected, marked) {
3884            (true, true) => cx
3885                .theme()
3886                .status()
3887                .info
3888                .alpha(selected_bg_alpha + marked_bg_alpha),
3889            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3890            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3891            _ => cx.theme().colors().ghost_element_background,
3892        };
3893
3894        let hover_bg = if selected {
3895            cx.theme()
3896                .status()
3897                .info
3898                .alpha(selected_bg_alpha + state_opacity_step)
3899        } else {
3900            cx.theme().colors().ghost_element_hover
3901        };
3902
3903        let active_bg = if selected {
3904            cx.theme()
3905                .status()
3906                .info
3907                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3908        } else {
3909            cx.theme().colors().ghost_element_active
3910        };
3911
3912        h_flex()
3913            .id(id)
3914            .h(self.list_item_height())
3915            .w_full()
3916            .items_center()
3917            .border_1()
3918            .when(selected && self.focus_handle.is_focused(window), |el| {
3919                el.border_color(cx.theme().colors().border_focused)
3920            })
3921            .px(rems(0.75)) // ~12px
3922            .overflow_hidden()
3923            .flex_none()
3924            .gap_1p5()
3925            .bg(base_bg)
3926            .hover(|this| this.bg(hover_bg))
3927            .active(|this| this.bg(active_bg))
3928            .on_click({
3929                cx.listener(move |this, event: &ClickEvent, window, cx| {
3930                    this.selected_entry = Some(ix);
3931                    cx.notify();
3932                    if event.modifiers().secondary() {
3933                        this.open_file(&Default::default(), window, cx)
3934                    } else {
3935                        this.open_diff(&Default::default(), window, cx);
3936                        this.focus_handle.focus(window);
3937                    }
3938                })
3939            })
3940            .on_mouse_down(
3941                MouseButton::Right,
3942                move |event: &MouseDownEvent, window, cx| {
3943                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3944                    if event.button != MouseButton::Right {
3945                        return;
3946                    }
3947
3948                    let Some(this) = handle.upgrade() else {
3949                        return;
3950                    };
3951                    this.update(cx, |this, cx| {
3952                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3953                    });
3954                    cx.stop_propagation();
3955                },
3956            )
3957            // .on_secondary_mouse_down(cx.listener(
3958            //     move |this, event: &MouseDownEvent, window, cx| {
3959            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3960            //         cx.stop_propagation();
3961            //     },
3962            // ))
3963            .child(
3964                div()
3965                    .id(checkbox_wrapper_id)
3966                    .flex_none()
3967                    .occlude()
3968                    .cursor_pointer()
3969                    .child(
3970                        Checkbox::new(checkbox_id, is_staged)
3971                            .disabled(!has_write_access)
3972                            .fill()
3973                            .elevation(ElevationIndex::Surface)
3974                            .on_click({
3975                                let entry = entry.clone();
3976                                cx.listener(move |this, _, window, cx| {
3977                                    if !has_write_access {
3978                                        return;
3979                                    }
3980                                    this.toggle_staged_for_entry(
3981                                        &GitListEntry::GitStatusEntry(entry.clone()),
3982                                        window,
3983                                        cx,
3984                                    );
3985                                    cx.stop_propagation();
3986                                })
3987                            })
3988                            .tooltip(move |window, cx| {
3989                                let is_staged = entry_staging.is_fully_staged();
3990
3991                                let action = if is_staged { "Unstage" } else { "Stage" };
3992                                let tooltip_name = if shift_held {
3993                                    format!("{} section", action)
3994                                } else {
3995                                    action.to_string()
3996                                };
3997
3998                                let meta = if shift_held {
3999                                    format!(
4000                                        "Release shift to {} single entry",
4001                                        action.to_lowercase()
4002                                    )
4003                                } else {
4004                                    format!("Shift click to {} section", action.to_lowercase())
4005                                };
4006
4007                                Tooltip::with_meta(
4008                                    tooltip_name,
4009                                    Some(&ToggleStaged),
4010                                    meta,
4011                                    window,
4012                                    cx,
4013                                )
4014                            }),
4015                    ),
4016            )
4017            .child(git_status_icon(status))
4018            .child(
4019                h_flex()
4020                    .items_center()
4021                    .flex_1()
4022                    // .overflow_hidden()
4023                    .when_some(entry.parent_dir(), |this, parent| {
4024                        if !parent.is_empty() {
4025                            this.child(
4026                                self.entry_label(format!("{}/", parent), path_color)
4027                                    .when(status.is_deleted(), |this| this.strikethrough()),
4028                            )
4029                        } else {
4030                            this
4031                        }
4032                    })
4033                    .child(
4034                        self.entry_label(display_name.clone(), label_color)
4035                            .when(status.is_deleted(), |this| this.strikethrough()),
4036                    ),
4037            )
4038            .into_any_element()
4039    }
4040
4041    fn has_write_access(&self, cx: &App) -> bool {
4042        !self.project.read(cx).is_read_only(cx)
4043    }
4044
4045    pub fn amend_pending(&self) -> bool {
4046        self.amend_pending
4047    }
4048
4049    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4050        self.amend_pending = value;
4051        cx.notify();
4052    }
4053}
4054
4055fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
4056    assistant_settings::AssistantSettings::get_global(cx)
4057        .enabled
4058        .then(|| {
4059            let ConfiguredModel { provider, model } =
4060                LanguageModelRegistry::read_global(cx).commit_message_model()?;
4061
4062            provider.is_authenticated(cx).then(|| model)
4063        })
4064        .flatten()
4065}
4066
4067impl Render for GitPanel {
4068    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4069        let project = self.project.read(cx);
4070        let has_entries = self.entries.len() > 0;
4071        let room = self
4072            .workspace
4073            .upgrade()
4074            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4075
4076        let has_write_access = self.has_write_access(cx);
4077
4078        let has_co_authors = room.map_or(false, |room| {
4079            room.read(cx)
4080                .remote_participants()
4081                .values()
4082                .any(|remote_participant| remote_participant.can_write())
4083        });
4084
4085        v_flex()
4086            .id("git_panel")
4087            .key_context(self.dispatch_context(window, cx))
4088            .track_focus(&self.focus_handle)
4089            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
4090            .when(has_write_access && !project.is_read_only(cx), |this| {
4091                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4092                    .on_action(cx.listener(GitPanel::commit))
4093                    .on_action(cx.listener(GitPanel::amend))
4094                    .on_action(cx.listener(GitPanel::cancel))
4095                    .on_action(cx.listener(Self::stage_all))
4096                    .on_action(cx.listener(Self::unstage_all))
4097                    .on_action(cx.listener(Self::stage_selected))
4098                    .on_action(cx.listener(Self::unstage_selected))
4099                    .on_action(cx.listener(Self::restore_tracked_files))
4100                    .on_action(cx.listener(Self::revert_selected))
4101                    .on_action(cx.listener(Self::clean_all))
4102                    .on_action(cx.listener(Self::generate_commit_message_action))
4103            })
4104            .on_action(cx.listener(Self::select_first))
4105            .on_action(cx.listener(Self::select_next))
4106            .on_action(cx.listener(Self::select_previous))
4107            .on_action(cx.listener(Self::select_last))
4108            .on_action(cx.listener(Self::close_panel))
4109            .on_action(cx.listener(Self::open_diff))
4110            .on_action(cx.listener(Self::open_file))
4111            .on_action(cx.listener(Self::focus_changes_list))
4112            .on_action(cx.listener(Self::focus_editor))
4113            .on_action(cx.listener(Self::expand_commit_editor))
4114            .when(has_write_access && has_co_authors, |git_panel| {
4115                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4116            })
4117            .on_hover(cx.listener(move |this, hovered, window, cx| {
4118                if *hovered {
4119                    this.horizontal_scrollbar.show(cx);
4120                    this.vertical_scrollbar.show(cx);
4121                    cx.notify();
4122                } else if !this.focus_handle.contains_focused(window, cx) {
4123                    this.hide_scrollbars(window, cx);
4124                }
4125            }))
4126            .size_full()
4127            .overflow_hidden()
4128            .bg(cx.theme().colors().panel_background)
4129            .child(
4130                v_flex()
4131                    .size_full()
4132                    .children(self.render_panel_header(window, cx))
4133                    .map(|this| {
4134                        if has_entries {
4135                            this.child(self.render_entries(has_write_access, window, cx))
4136                        } else {
4137                            this.child(self.render_empty_state(cx).into_any_element())
4138                        }
4139                    })
4140                    .children(self.render_footer(window, cx))
4141                    .when(self.amend_pending, |this| {
4142                        this.child(self.render_pending_amend(cx))
4143                    })
4144                    .when(!self.amend_pending, |this| {
4145                        this.children(self.render_previous_commit(cx))
4146                    })
4147                    .into_any_element(),
4148            )
4149            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4150                deferred(
4151                    anchored()
4152                        .position(*position)
4153                        .anchor(Corner::TopLeft)
4154                        .child(menu.clone()),
4155                )
4156                .with_priority(1)
4157            }))
4158    }
4159}
4160
4161impl Focusable for GitPanel {
4162    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4163        if self.entries.is_empty() {
4164            self.commit_editor.focus_handle(cx)
4165        } else {
4166            self.focus_handle.clone()
4167        }
4168    }
4169}
4170
4171impl EventEmitter<Event> for GitPanel {}
4172
4173impl EventEmitter<PanelEvent> for GitPanel {}
4174
4175pub(crate) struct GitPanelAddon {
4176    pub(crate) workspace: WeakEntity<Workspace>,
4177}
4178
4179impl editor::Addon for GitPanelAddon {
4180    fn to_any(&self) -> &dyn std::any::Any {
4181        self
4182    }
4183
4184    fn render_buffer_header_controls(
4185        &self,
4186        excerpt_info: &ExcerptInfo,
4187        window: &Window,
4188        cx: &App,
4189    ) -> Option<AnyElement> {
4190        let file = excerpt_info.buffer.file()?;
4191        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4192
4193        git_panel
4194            .read(cx)
4195            .render_buffer_header_controls(&git_panel, &file, window, cx)
4196    }
4197}
4198
4199impl Panel for GitPanel {
4200    fn persistent_name() -> &'static str {
4201        "GitPanel"
4202    }
4203
4204    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4205        GitPanelSettings::get_global(cx).dock
4206    }
4207
4208    fn position_is_valid(&self, position: DockPosition) -> bool {
4209        matches!(position, DockPosition::Left | DockPosition::Right)
4210    }
4211
4212    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4213        settings::update_settings_file::<GitPanelSettings>(
4214            self.fs.clone(),
4215            cx,
4216            move |settings, _| settings.dock = Some(position),
4217        );
4218    }
4219
4220    fn size(&self, _: &Window, cx: &App) -> Pixels {
4221        self.width
4222            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4223    }
4224
4225    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4226        self.width = size;
4227        self.serialize(cx);
4228        cx.notify();
4229    }
4230
4231    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4232        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
4233    }
4234
4235    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4236        Some("Git Panel")
4237    }
4238
4239    fn toggle_action(&self) -> Box<dyn Action> {
4240        Box::new(ToggleFocus)
4241    }
4242
4243    fn activation_priority(&self) -> u32 {
4244        2
4245    }
4246}
4247
4248impl PanelHeader for GitPanel {}
4249
4250struct GitPanelMessageTooltip {
4251    commit_tooltip: Option<Entity<CommitTooltip>>,
4252}
4253
4254impl GitPanelMessageTooltip {
4255    fn new(
4256        git_panel: Entity<GitPanel>,
4257        sha: SharedString,
4258        repository: Entity<Repository>,
4259        window: &mut Window,
4260        cx: &mut App,
4261    ) -> Entity<Self> {
4262        cx.new(|cx| {
4263            cx.spawn_in(window, async move |this, cx| {
4264                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4265                    (
4266                        git_panel.load_commit_details(sha.to_string(), cx),
4267                        git_panel.workspace.clone(),
4268                    )
4269                })?;
4270                let details = details.await?;
4271
4272                let commit_details = crate::commit_tooltip::CommitDetails {
4273                    sha: details.sha.clone(),
4274                    author_name: details.author_name.clone(),
4275                    author_email: details.author_email.clone(),
4276                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4277                    message: Some(ParsedCommitMessage {
4278                        message: details.message.clone(),
4279                        ..Default::default()
4280                    }),
4281                };
4282
4283                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4284                    this.commit_tooltip = Some(cx.new(move |cx| {
4285                        CommitTooltip::new(commit_details, repository, workspace, cx)
4286                    }));
4287                    cx.notify();
4288                })
4289            })
4290            .detach();
4291
4292            Self {
4293                commit_tooltip: None,
4294            }
4295        })
4296    }
4297}
4298
4299impl Render for GitPanelMessageTooltip {
4300    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4301        if let Some(commit_tooltip) = &self.commit_tooltip {
4302            commit_tooltip.clone().into_any_element()
4303        } else {
4304            gpui::Empty.into_any_element()
4305        }
4306    }
4307}
4308
4309#[derive(IntoElement, RegisterComponent)]
4310pub struct PanelRepoFooter {
4311    active_repository: SharedString,
4312    branch: Option<Branch>,
4313    head_commit: Option<CommitDetails>,
4314
4315    // Getting a GitPanel in previews will be difficult.
4316    //
4317    // For now just take an option here, and we won't bind handlers to buttons in previews.
4318    git_panel: Option<Entity<GitPanel>>,
4319}
4320
4321impl PanelRepoFooter {
4322    pub fn new(
4323        active_repository: SharedString,
4324        branch: Option<Branch>,
4325        head_commit: Option<CommitDetails>,
4326        git_panel: Option<Entity<GitPanel>>,
4327    ) -> Self {
4328        Self {
4329            active_repository,
4330            branch,
4331            head_commit,
4332            git_panel,
4333        }
4334    }
4335
4336    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4337        Self {
4338            active_repository,
4339            branch,
4340            head_commit: None,
4341            git_panel: None,
4342        }
4343    }
4344}
4345
4346impl RenderOnce for PanelRepoFooter {
4347    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4348        let project = self
4349            .git_panel
4350            .as_ref()
4351            .map(|panel| panel.read(cx).project.clone());
4352
4353        let repo = self
4354            .git_panel
4355            .as_ref()
4356            .and_then(|panel| panel.read(cx).active_repository.clone());
4357
4358        let single_repo = project
4359            .as_ref()
4360            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4361            .unwrap_or(true);
4362
4363        const MAX_BRANCH_LEN: usize = 16;
4364        const MAX_REPO_LEN: usize = 16;
4365        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4366        const MAX_SHORT_SHA_LEN: usize = 8;
4367
4368        let branch_name = self
4369            .branch
4370            .as_ref()
4371            .map(|branch| branch.name().to_owned())
4372            .or_else(|| {
4373                self.head_commit.as_ref().map(|commit| {
4374                    commit
4375                        .sha
4376                        .chars()
4377                        .take(MAX_SHORT_SHA_LEN)
4378                        .collect::<String>()
4379                })
4380            })
4381            .unwrap_or_else(|| " (no branch)".to_owned());
4382        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4383
4384        let active_repo_name = self.active_repository.clone();
4385
4386        let branch_actual_len = branch_name.len();
4387        let repo_actual_len = active_repo_name.len();
4388
4389        // ideally, show the whole branch and repo names but
4390        // when we can't, use a budget to allocate space between the two
4391        let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4392            <= LABEL_CHARACTER_BUDGET
4393        {
4394            (repo_actual_len, branch_actual_len)
4395        } else {
4396            if branch_actual_len <= MAX_BRANCH_LEN {
4397                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4398                (repo_space, branch_actual_len)
4399            } else if repo_actual_len <= MAX_REPO_LEN {
4400                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4401                (repo_actual_len, branch_space)
4402            } else {
4403                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4404            }
4405        };
4406
4407        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4408            active_repo_name.to_string()
4409        } else {
4410            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4411        };
4412
4413        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4414            branch_name.to_string()
4415        } else {
4416            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4417        };
4418
4419        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4420            .style(ButtonStyle::Transparent)
4421            .size(ButtonSize::None)
4422            .label_size(LabelSize::Small)
4423            .color(Color::Muted);
4424
4425        let repo_selector = PopoverMenu::new("repository-switcher")
4426            .menu({
4427                let project = project.clone();
4428                move |window, cx| {
4429                    let project = project.clone()?;
4430                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4431                }
4432            })
4433            .trigger_with_tooltip(
4434                repo_selector_trigger.disabled(single_repo).truncate(true),
4435                Tooltip::text("Switch active repository"),
4436            )
4437            .anchor(Corner::BottomLeft)
4438            .into_any_element();
4439
4440        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4441            .style(ButtonStyle::Transparent)
4442            .size(ButtonSize::None)
4443            .label_size(LabelSize::Small)
4444            .truncate(true)
4445            .tooltip(Tooltip::for_action_title(
4446                "Switch Branch",
4447                &zed_actions::git::Switch,
4448            ))
4449            .on_click(|_, window, cx| {
4450                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4451            });
4452
4453        let branch_selector = PopoverMenu::new("popover-button")
4454            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4455            .trigger_with_tooltip(
4456                branch_selector_button,
4457                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4458            )
4459            .anchor(Corner::BottomLeft)
4460            .offset(gpui::Point {
4461                x: px(0.0),
4462                y: px(-2.0),
4463            });
4464
4465        h_flex()
4466            .w_full()
4467            .px_2()
4468            .h(px(36.))
4469            .items_center()
4470            .justify_between()
4471            .gap_1()
4472            .child(
4473                h_flex()
4474                    .flex_1()
4475                    .overflow_hidden()
4476                    .items_center()
4477                    .child(
4478                        div().child(
4479                            Icon::new(IconName::GitBranchSmall)
4480                                .size(IconSize::Small)
4481                                .color(if single_repo {
4482                                    Color::Disabled
4483                                } else {
4484                                    Color::Muted
4485                                }),
4486                        ),
4487                    )
4488                    .child(repo_selector)
4489                    .when(show_separator, |this| {
4490                        this.child(
4491                            div()
4492                                .text_color(cx.theme().colors().text_muted)
4493                                .text_sm()
4494                                .child("/"),
4495                        )
4496                    })
4497                    .child(branch_selector),
4498            )
4499            .children(if let Some(git_panel) = self.git_panel {
4500                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4501            } else {
4502                None
4503            })
4504    }
4505}
4506
4507impl Component for PanelRepoFooter {
4508    fn scope() -> ComponentScope {
4509        ComponentScope::VersionControl
4510    }
4511
4512    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4513        let unknown_upstream = None;
4514        let no_remote_upstream = Some(UpstreamTracking::Gone);
4515        let ahead_of_upstream = Some(
4516            UpstreamTrackingStatus {
4517                ahead: 2,
4518                behind: 0,
4519            }
4520            .into(),
4521        );
4522        let behind_upstream = Some(
4523            UpstreamTrackingStatus {
4524                ahead: 0,
4525                behind: 2,
4526            }
4527            .into(),
4528        );
4529        let ahead_and_behind_upstream = Some(
4530            UpstreamTrackingStatus {
4531                ahead: 3,
4532                behind: 1,
4533            }
4534            .into(),
4535        );
4536
4537        let not_ahead_or_behind_upstream = Some(
4538            UpstreamTrackingStatus {
4539                ahead: 0,
4540                behind: 0,
4541            }
4542            .into(),
4543        );
4544
4545        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4546            Branch {
4547                is_head: true,
4548                ref_name: "some-branch".into(),
4549                upstream: upstream.map(|tracking| Upstream {
4550                    ref_name: "origin/some-branch".into(),
4551                    tracking,
4552                }),
4553                most_recent_commit: Some(CommitSummary {
4554                    sha: "abc123".into(),
4555                    subject: "Modify stuff".into(),
4556                    commit_timestamp: 1710932954,
4557                    has_parent: true,
4558                }),
4559            }
4560        }
4561
4562        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4563            Branch {
4564                is_head: true,
4565                ref_name: branch_name.to_string().into(),
4566                upstream: upstream.map(|tracking| Upstream {
4567                    ref_name: format!("zed/{}", branch_name).into(),
4568                    tracking,
4569                }),
4570                most_recent_commit: Some(CommitSummary {
4571                    sha: "abc123".into(),
4572                    subject: "Modify stuff".into(),
4573                    commit_timestamp: 1710932954,
4574                    has_parent: true,
4575                }),
4576            }
4577        }
4578
4579        fn active_repository(id: usize) -> SharedString {
4580            format!("repo-{}", id).into()
4581        }
4582
4583        let example_width = px(340.);
4584        Some(
4585            v_flex()
4586                .gap_6()
4587                .w_full()
4588                .flex_none()
4589                .children(vec![
4590                    example_group_with_title(
4591                        "Action Button States",
4592                        vec![
4593                            single_example(
4594                                "No Branch",
4595                                div()
4596                                    .w(example_width)
4597                                    .overflow_hidden()
4598                                    .child(PanelRepoFooter::new_preview(
4599                                        active_repository(1).clone(),
4600                                        None,
4601                                    ))
4602                                    .into_any_element(),
4603                            ),
4604                            single_example(
4605                                "Remote status unknown",
4606                                div()
4607                                    .w(example_width)
4608                                    .overflow_hidden()
4609                                    .child(PanelRepoFooter::new_preview(
4610                                        active_repository(2).clone(),
4611                                        Some(branch(unknown_upstream)),
4612                                    ))
4613                                    .into_any_element(),
4614                            ),
4615                            single_example(
4616                                "No Remote Upstream",
4617                                div()
4618                                    .w(example_width)
4619                                    .overflow_hidden()
4620                                    .child(PanelRepoFooter::new_preview(
4621                                        active_repository(3).clone(),
4622                                        Some(branch(no_remote_upstream)),
4623                                    ))
4624                                    .into_any_element(),
4625                            ),
4626                            single_example(
4627                                "Not Ahead or Behind",
4628                                div()
4629                                    .w(example_width)
4630                                    .overflow_hidden()
4631                                    .child(PanelRepoFooter::new_preview(
4632                                        active_repository(4).clone(),
4633                                        Some(branch(not_ahead_or_behind_upstream)),
4634                                    ))
4635                                    .into_any_element(),
4636                            ),
4637                            single_example(
4638                                "Behind remote",
4639                                div()
4640                                    .w(example_width)
4641                                    .overflow_hidden()
4642                                    .child(PanelRepoFooter::new_preview(
4643                                        active_repository(5).clone(),
4644                                        Some(branch(behind_upstream)),
4645                                    ))
4646                                    .into_any_element(),
4647                            ),
4648                            single_example(
4649                                "Ahead of remote",
4650                                div()
4651                                    .w(example_width)
4652                                    .overflow_hidden()
4653                                    .child(PanelRepoFooter::new_preview(
4654                                        active_repository(6).clone(),
4655                                        Some(branch(ahead_of_upstream)),
4656                                    ))
4657                                    .into_any_element(),
4658                            ),
4659                            single_example(
4660                                "Ahead and behind remote",
4661                                div()
4662                                    .w(example_width)
4663                                    .overflow_hidden()
4664                                    .child(PanelRepoFooter::new_preview(
4665                                        active_repository(7).clone(),
4666                                        Some(branch(ahead_and_behind_upstream)),
4667                                    ))
4668                                    .into_any_element(),
4669                            ),
4670                        ],
4671                    )
4672                    .grow()
4673                    .vertical(),
4674                ])
4675                .children(vec![
4676                    example_group_with_title(
4677                        "Labels",
4678                        vec![
4679                            single_example(
4680                                "Short Branch & Repo",
4681                                div()
4682                                    .w(example_width)
4683                                    .overflow_hidden()
4684                                    .child(PanelRepoFooter::new_preview(
4685                                        SharedString::from("zed"),
4686                                        Some(custom("main", behind_upstream)),
4687                                    ))
4688                                    .into_any_element(),
4689                            ),
4690                            single_example(
4691                                "Long Branch",
4692                                div()
4693                                    .w(example_width)
4694                                    .overflow_hidden()
4695                                    .child(PanelRepoFooter::new_preview(
4696                                        SharedString::from("zed"),
4697                                        Some(custom(
4698                                            "redesign-and-update-git-ui-list-entry-style",
4699                                            behind_upstream,
4700                                        )),
4701                                    ))
4702                                    .into_any_element(),
4703                            ),
4704                            single_example(
4705                                "Long Repo",
4706                                div()
4707                                    .w(example_width)
4708                                    .overflow_hidden()
4709                                    .child(PanelRepoFooter::new_preview(
4710                                        SharedString::from("zed-industries-community-examples"),
4711                                        Some(custom("gpui", ahead_of_upstream)),
4712                                    ))
4713                                    .into_any_element(),
4714                            ),
4715                            single_example(
4716                                "Long Repo & Branch",
4717                                div()
4718                                    .w(example_width)
4719                                    .overflow_hidden()
4720                                    .child(PanelRepoFooter::new_preview(
4721                                        SharedString::from("zed-industries-community-examples"),
4722                                        Some(custom(
4723                                            "redesign-and-update-git-ui-list-entry-style",
4724                                            behind_upstream,
4725                                        )),
4726                                    ))
4727                                    .into_any_element(),
4728                            ),
4729                            single_example(
4730                                "Uppercase Repo",
4731                                div()
4732                                    .w(example_width)
4733                                    .overflow_hidden()
4734                                    .child(PanelRepoFooter::new_preview(
4735                                        SharedString::from("LICENSES"),
4736                                        Some(custom("main", ahead_of_upstream)),
4737                                    ))
4738                                    .into_any_element(),
4739                            ),
4740                            single_example(
4741                                "Uppercase Branch",
4742                                div()
4743                                    .w(example_width)
4744                                    .overflow_hidden()
4745                                    .child(PanelRepoFooter::new_preview(
4746                                        SharedString::from("zed"),
4747                                        Some(custom("update-README", behind_upstream)),
4748                                    ))
4749                                    .into_any_element(),
4750                            ),
4751                        ],
4752                    )
4753                    .grow()
4754                    .vertical(),
4755                ])
4756                .into_any_element(),
4757        )
4758    }
4759}
4760
4761#[cfg(test)]
4762mod tests {
4763    use git::status::StatusCode;
4764    use gpui::TestAppContext;
4765    use project::{FakeFs, WorktreeSettings};
4766    use serde_json::json;
4767    use settings::SettingsStore;
4768    use theme::LoadThemes;
4769    use util::path;
4770
4771    use super::*;
4772
4773    fn init_test(cx: &mut gpui::TestAppContext) {
4774        if std::env::var("RUST_LOG").is_ok() {
4775            env_logger::try_init().ok();
4776        }
4777
4778        cx.update(|cx| {
4779            let settings_store = SettingsStore::test(cx);
4780            cx.set_global(settings_store);
4781            AssistantSettings::register(cx);
4782            WorktreeSettings::register(cx);
4783            workspace::init_settings(cx);
4784            theme::init(LoadThemes::JustBase, cx);
4785            language::init(cx);
4786            editor::init(cx);
4787            Project::init_settings(cx);
4788            crate::init(cx);
4789        });
4790    }
4791
4792    #[gpui::test]
4793    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4794        init_test(cx);
4795        let fs = FakeFs::new(cx.background_executor.clone());
4796        fs.insert_tree(
4797            "/root",
4798            json!({
4799                "zed": {
4800                    ".git": {},
4801                    "crates": {
4802                        "gpui": {
4803                            "gpui.rs": "fn main() {}"
4804                        },
4805                        "util": {
4806                            "util.rs": "fn do_it() {}"
4807                        }
4808                    }
4809                },
4810            }),
4811        )
4812        .await;
4813
4814        fs.set_status_for_repo(
4815            Path::new(path!("/root/zed/.git")),
4816            &[
4817                (
4818                    Path::new("crates/gpui/gpui.rs"),
4819                    StatusCode::Modified.worktree(),
4820                ),
4821                (
4822                    Path::new("crates/util/util.rs"),
4823                    StatusCode::Modified.worktree(),
4824                ),
4825            ],
4826        );
4827
4828        let project =
4829            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4830        let (workspace, cx) =
4831            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4832
4833        cx.read(|cx| {
4834            project
4835                .read(cx)
4836                .worktrees(cx)
4837                .nth(0)
4838                .unwrap()
4839                .read(cx)
4840                .as_local()
4841                .unwrap()
4842                .scan_complete()
4843        })
4844        .await;
4845
4846        cx.executor().run_until_parked();
4847
4848        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4849        let panel = cx.new_window_entity(|window, cx| {
4850            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4851        });
4852
4853        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4854            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4855        });
4856        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4857        handle.await;
4858
4859        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4860        pretty_assertions::assert_eq!(
4861            entries,
4862            [
4863                GitListEntry::Header(GitHeaderEntry {
4864                    header: Section::Tracked
4865                }),
4866                GitListEntry::GitStatusEntry(GitStatusEntry {
4867                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4868                    repo_path: "crates/gpui/gpui.rs".into(),
4869                    status: StatusCode::Modified.worktree(),
4870                    staging: StageStatus::Unstaged,
4871                }),
4872                GitListEntry::GitStatusEntry(GitStatusEntry {
4873                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4874                    repo_path: "crates/util/util.rs".into(),
4875                    status: StatusCode::Modified.worktree(),
4876                    staging: StageStatus::Unstaged,
4877                },),
4878            ],
4879        );
4880
4881        // TODO(cole) restore this once repository deduplication is implemented properly.
4882        //cx.update_window_entity(&panel, |panel, window, cx| {
4883        //    panel.select_last(&Default::default(), window, cx);
4884        //    assert_eq!(panel.selected_entry, Some(2));
4885        //    panel.open_diff(&Default::default(), window, cx);
4886        //});
4887        //cx.run_until_parked();
4888
4889        //let worktree_roots = workspace.update(cx, |workspace, cx| {
4890        //    workspace
4891        //        .worktrees(cx)
4892        //        .map(|worktree| worktree.read(cx).abs_path())
4893        //        .collect::<Vec<_>>()
4894        //});
4895        //pretty_assertions::assert_eq!(
4896        //    worktree_roots,
4897        //    vec![
4898        //        Path::new(path!("/root/zed/crates/gpui")).into(),
4899        //        Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4900        //    ]
4901        //);
4902
4903        //project.update(cx, |project, cx| {
4904        //    let git_store = project.git_store().read(cx);
4905        //    // The repo that comes from the single-file worktree can't be selected through the UI.
4906        //    let filtered_entries = filtered_repository_entries(git_store, cx)
4907        //        .iter()
4908        //        .map(|repo| repo.read(cx).worktree_abs_path.clone())
4909        //        .collect::<Vec<_>>();
4910        //    assert_eq!(
4911        //        filtered_entries,
4912        //        [Path::new(path!("/root/zed/crates/gpui")).into()]
4913        //    );
4914        //    // But we can select it artificially here.
4915        //    let repo_from_single_file_worktree = git_store
4916        //        .repositories()
4917        //        .values()
4918        //        .find(|repo| {
4919        //            repo.read(cx).worktree_abs_path.as_ref()
4920        //                == Path::new(path!("/root/zed/crates/util/util.rs"))
4921        //        })
4922        //        .unwrap()
4923        //        .clone();
4924
4925        //    // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4926        //    repo_from_single_file_worktree.update(cx, |repo, cx| repo.set_as_active_repository(cx));
4927        //});
4928
4929        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4930            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4931        });
4932        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4933        handle.await;
4934        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4935        pretty_assertions::assert_eq!(
4936            entries,
4937            [
4938                GitListEntry::Header(GitHeaderEntry {
4939                    header: Section::Tracked
4940                }),
4941                GitListEntry::GitStatusEntry(GitStatusEntry {
4942                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4943                    repo_path: "crates/gpui/gpui.rs".into(),
4944                    status: StatusCode::Modified.worktree(),
4945                    staging: StageStatus::Unstaged,
4946                }),
4947                GitListEntry::GitStatusEntry(GitStatusEntry {
4948                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4949                    repo_path: "crates/util/util.rs".into(),
4950                    status: StatusCode::Modified.worktree(),
4951                    staging: StageStatus::Unstaged,
4952                },),
4953            ],
4954        );
4955    }
4956}