git_panel.rs

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