git_panel.rs

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