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                        log::error!("Error while fetching {:?}", e);
1575                        this.show_err_toast(e, cx);
1576                    }
1577                }
1578
1579                anyhow::Ok(())
1580            })
1581            .ok();
1582            anyhow::Ok(())
1583        })
1584        .detach_and_log_err(cx);
1585    }
1586
1587    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1588        if !self.can_push_and_pull(cx) {
1589            return;
1590        }
1591        let Some(repo) = self.active_repository.clone() else {
1592            return;
1593        };
1594        let Some(branch) = repo.read(cx).current_branch() else {
1595            return;
1596        };
1597        telemetry::event!("Git Pulled");
1598        let branch = branch.clone();
1599        let remote = self.get_current_remote(window, cx);
1600        cx.spawn_in(window, move |this, mut cx| async move {
1601            let remote = match remote.await {
1602                Ok(Some(remote)) => remote,
1603                Ok(None) => {
1604                    return Ok(());
1605                }
1606                Err(e) => {
1607                    log::error!("Failed to get current remote: {}", e);
1608                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1609                        .ok();
1610                    return Ok(());
1611                }
1612            };
1613
1614            let askpass = this.update_in(&mut cx, |this, window, cx| {
1615                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1616            })?;
1617
1618            let guard = this
1619                .update(&mut cx, |this, _| this.start_remote_operation())
1620                .ok();
1621
1622            let pull = repo.update(&mut cx, |repo, cx| {
1623                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1624            })?;
1625
1626            let remote_message = pull.await?;
1627            drop(guard);
1628
1629            this.update(&mut cx, |this, cx| match remote_message {
1630                Ok(remote_message) => {
1631                    this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1632                }
1633                Err(err) => {
1634                    log::error!("Error while pull {:?}", err);
1635                    this.show_err_toast(err, cx)
1636                }
1637            })
1638            .ok();
1639
1640            anyhow::Ok(())
1641        })
1642        .detach_and_log_err(cx);
1643    }
1644
1645    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1646        if !self.can_push_and_pull(cx) {
1647            return;
1648        }
1649        let Some(repo) = self.active_repository.clone() else {
1650            return;
1651        };
1652        let Some(branch) = repo.read(cx).current_branch() else {
1653            return;
1654        };
1655        telemetry::event!("Git Pushed");
1656        let branch = branch.clone();
1657        let options = if force_push {
1658            PushOptions::Force
1659        } else {
1660            PushOptions::SetUpstream
1661        };
1662        let remote = self.get_current_remote(window, cx);
1663
1664        cx.spawn_in(window, move |this, mut cx| async move {
1665            let remote = match remote.await {
1666                Ok(Some(remote)) => remote,
1667                Ok(None) => {
1668                    return Ok(());
1669                }
1670                Err(e) => {
1671                    log::error!("Failed to get current remote: {}", e);
1672                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1673                        .ok();
1674                    return Ok(());
1675                }
1676            };
1677
1678            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1679                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1680            })?;
1681
1682            let guard = this
1683                .update(&mut cx, |this, _| this.start_remote_operation())
1684                .ok();
1685
1686            let push = repo.update(&mut cx, |repo, cx| {
1687                repo.push(
1688                    branch.name.clone(),
1689                    remote.name.clone(),
1690                    Some(options),
1691                    askpass_delegate,
1692                    cx,
1693                )
1694            })?;
1695
1696            let remote_output = push.await?;
1697            drop(guard);
1698
1699            this.update(&mut cx, |this, cx| match remote_output {
1700                Ok(remote_message) => {
1701                    this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1702                }
1703                Err(e) => {
1704                    log::error!("Error while pushing {:?}", e);
1705                    this.show_err_toast(e, cx);
1706                }
1707            })?;
1708
1709            anyhow::Ok(())
1710        })
1711        .detach_and_log_err(cx);
1712    }
1713
1714    fn askpass_delegate(
1715        &self,
1716        operation: impl Into<SharedString>,
1717        window: &mut Window,
1718        cx: &mut Context<Self>,
1719    ) -> AskPassDelegate {
1720        let this = cx.weak_entity();
1721        let operation = operation.into();
1722        let window = window.window_handle();
1723        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1724            window
1725                .update(cx, |_, window, cx| {
1726                    this.update(cx, |this, cx| {
1727                        this.workspace.update(cx, |workspace, cx| {
1728                            workspace.toggle_modal(window, cx, |window, cx| {
1729                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1730                            });
1731                        })
1732                    })
1733                })
1734                .ok();
1735        })
1736    }
1737
1738    fn can_push_and_pull(&self, cx: &App) -> bool {
1739        !self.project.read(cx).is_via_collab()
1740    }
1741
1742    fn get_current_remote(
1743        &mut self,
1744        window: &mut Window,
1745        cx: &mut Context<Self>,
1746    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
1747        let repo = self.active_repository.clone();
1748        let workspace = self.workspace.clone();
1749        let mut cx = window.to_async(cx);
1750
1751        async move {
1752            let Some(repo) = repo else {
1753                return Err(anyhow::anyhow!("No active repository"));
1754            };
1755
1756            let mut current_remotes: Vec<Remote> = repo
1757                .update(&mut cx, |repo, _| {
1758                    let Some(current_branch) = repo.current_branch() else {
1759                        return Err(anyhow::anyhow!("No active branch"));
1760                    };
1761
1762                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1763                })??
1764                .await??;
1765
1766            if current_remotes.len() == 0 {
1767                return Err(anyhow::anyhow!("No active remote"));
1768            } else if current_remotes.len() == 1 {
1769                return Ok(Some(current_remotes.pop().unwrap()));
1770            } else {
1771                let current_remotes: Vec<_> = current_remotes
1772                    .into_iter()
1773                    .map(|remotes| remotes.name)
1774                    .collect();
1775                let selection = cx
1776                    .update(|window, cx| {
1777                        picker_prompt::prompt(
1778                            "Pick which remote to push to",
1779                            current_remotes.clone(),
1780                            workspace,
1781                            window,
1782                            cx,
1783                        )
1784                    })?
1785                    .await?;
1786
1787                Ok(selection.map(|selection| Remote {
1788                    name: current_remotes[selection].clone(),
1789                }))
1790            }
1791        }
1792    }
1793
1794    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1795        let mut new_co_authors = Vec::new();
1796        let project = self.project.read(cx);
1797
1798        let Some(room) = self
1799            .workspace
1800            .upgrade()
1801            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1802        else {
1803            return Vec::default();
1804        };
1805
1806        let room = room.read(cx);
1807
1808        for (peer_id, collaborator) in project.collaborators() {
1809            if collaborator.is_host {
1810                continue;
1811            }
1812
1813            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1814                continue;
1815            };
1816            if participant.can_write() && participant.user.email.is_some() {
1817                let email = participant.user.email.clone().unwrap();
1818
1819                new_co_authors.push((
1820                    participant
1821                        .user
1822                        .name
1823                        .clone()
1824                        .unwrap_or_else(|| participant.user.github_login.clone()),
1825                    email,
1826                ))
1827            }
1828        }
1829        if !project.is_local() && !project.is_read_only(cx) {
1830            if let Some(user) = room.local_participant_user(cx) {
1831                if let Some(email) = user.email.clone() {
1832                    new_co_authors.push((
1833                        user.name
1834                            .clone()
1835                            .unwrap_or_else(|| user.github_login.clone()),
1836                        email.clone(),
1837                    ))
1838                }
1839            }
1840        }
1841        new_co_authors
1842    }
1843
1844    fn toggle_fill_co_authors(
1845        &mut self,
1846        _: &ToggleFillCoAuthors,
1847        _: &mut Window,
1848        cx: &mut Context<Self>,
1849    ) {
1850        self.add_coauthors = !self.add_coauthors;
1851        cx.notify();
1852    }
1853
1854    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1855        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1856
1857        let existing_text = message.to_ascii_lowercase();
1858        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1859        let mut ends_with_co_authors = false;
1860        let existing_co_authors = existing_text
1861            .lines()
1862            .filter_map(|line| {
1863                let line = line.trim();
1864                if line.starts_with(&lowercase_co_author_prefix) {
1865                    ends_with_co_authors = true;
1866                    Some(line)
1867                } else {
1868                    ends_with_co_authors = false;
1869                    None
1870                }
1871            })
1872            .collect::<HashSet<_>>();
1873
1874        let new_co_authors = self
1875            .potential_co_authors(cx)
1876            .into_iter()
1877            .filter(|(_, email)| {
1878                !existing_co_authors
1879                    .iter()
1880                    .any(|existing| existing.contains(email.as_str()))
1881            })
1882            .collect::<Vec<_>>();
1883
1884        if new_co_authors.is_empty() {
1885            return;
1886        }
1887
1888        if !ends_with_co_authors {
1889            message.push('\n');
1890        }
1891        for (name, email) in new_co_authors {
1892            message.push('\n');
1893            message.push_str(CO_AUTHOR_PREFIX);
1894            message.push_str(&name);
1895            message.push_str(" <");
1896            message.push_str(&email);
1897            message.push('>');
1898        }
1899        message.push('\n');
1900    }
1901
1902    fn schedule_update(
1903        &mut self,
1904        clear_pending: bool,
1905        window: &mut Window,
1906        cx: &mut Context<Self>,
1907    ) {
1908        let handle = cx.entity().downgrade();
1909        self.reopen_commit_buffer(window, cx);
1910        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1911            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1912            if let Some(git_panel) = handle.upgrade() {
1913                git_panel
1914                    .update_in(&mut cx, |git_panel, _, cx| {
1915                        if clear_pending {
1916                            git_panel.clear_pending();
1917                        }
1918                        git_panel.update_visible_entries(cx);
1919                        git_panel.update_editor_placeholder(cx);
1920                    })
1921                    .ok();
1922            }
1923        });
1924    }
1925
1926    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1927        let Some(active_repo) = self.active_repository.as_ref() else {
1928            return;
1929        };
1930        let load_buffer = active_repo.update(cx, |active_repo, cx| {
1931            let project = self.project.read(cx);
1932            active_repo.open_commit_buffer(
1933                Some(project.languages().clone()),
1934                project.buffer_store().clone(),
1935                cx,
1936            )
1937        });
1938
1939        cx.spawn_in(window, |git_panel, mut cx| async move {
1940            let buffer = load_buffer.await?;
1941            git_panel.update_in(&mut cx, |git_panel, window, cx| {
1942                if git_panel
1943                    .commit_editor
1944                    .read(cx)
1945                    .buffer()
1946                    .read(cx)
1947                    .as_singleton()
1948                    .as_ref()
1949                    != Some(&buffer)
1950                {
1951                    git_panel.commit_editor = cx.new(|cx| {
1952                        commit_message_editor(
1953                            buffer,
1954                            git_panel.suggest_commit_message().as_deref(),
1955                            git_panel.project.clone(),
1956                            true,
1957                            window,
1958                            cx,
1959                        )
1960                    });
1961                }
1962            })
1963        })
1964        .detach_and_log_err(cx);
1965    }
1966
1967    fn clear_pending(&mut self) {
1968        self.pending.retain(|v| !v.finished)
1969    }
1970
1971    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1972        self.entries.clear();
1973        let mut changed_entries = Vec::new();
1974        let mut new_entries = Vec::new();
1975        let mut conflict_entries = Vec::new();
1976
1977        let Some(repo) = self.active_repository.as_ref() else {
1978            // Just clear entries if no repository is active.
1979            cx.notify();
1980            return;
1981        };
1982
1983        let repo = repo.read(cx);
1984
1985        for entry in repo.status() {
1986            let is_conflict = repo.has_conflict(&entry.repo_path);
1987            let is_new = entry.status.is_created();
1988            let is_staged = entry.status.is_staged();
1989
1990            if self.pending.iter().any(|pending| {
1991                pending.target_status == TargetStatus::Reverted
1992                    && !pending.finished
1993                    && pending.repo_paths.contains(&entry.repo_path)
1994            }) {
1995                continue;
1996            }
1997
1998            // dot_git_abs path always has at least one component, namely .git.
1999            let abs_path = repo
2000                .dot_git_abs_path
2001                .parent()
2002                .unwrap()
2003                .join(&entry.repo_path);
2004            let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2005            let entry = GitStatusEntry {
2006                repo_path: entry.repo_path.clone(),
2007                worktree_path,
2008                abs_path,
2009                status: entry.status,
2010                is_staged,
2011            };
2012
2013            if is_conflict {
2014                conflict_entries.push(entry);
2015            } else if is_new {
2016                new_entries.push(entry);
2017            } else {
2018                changed_entries.push(entry);
2019            }
2020        }
2021
2022        if conflict_entries.len() > 0 {
2023            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2024                header: Section::Conflict,
2025            }));
2026            self.entries.extend(
2027                conflict_entries
2028                    .into_iter()
2029                    .map(GitListEntry::GitStatusEntry),
2030            );
2031        }
2032
2033        if changed_entries.len() > 0 {
2034            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2035                header: Section::Tracked,
2036            }));
2037            self.entries.extend(
2038                changed_entries
2039                    .into_iter()
2040                    .map(GitListEntry::GitStatusEntry),
2041            );
2042        }
2043        if new_entries.len() > 0 {
2044            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2045                header: Section::New,
2046            }));
2047            self.entries
2048                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2049        }
2050
2051        self.update_counts(repo);
2052
2053        self.select_first_entry_if_none(cx);
2054
2055        cx.notify();
2056    }
2057
2058    fn header_state(&self, header_type: Section) -> ToggleState {
2059        let (staged_count, count) = match header_type {
2060            Section::New => (self.new_staged_count, self.new_count),
2061            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2062            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2063        };
2064        if staged_count == 0 {
2065            ToggleState::Unselected
2066        } else if count == staged_count {
2067            ToggleState::Selected
2068        } else {
2069            ToggleState::Indeterminate
2070        }
2071    }
2072
2073    fn update_counts(&mut self, repo: &Repository) {
2074        self.conflicted_count = 0;
2075        self.conflicted_staged_count = 0;
2076        self.new_count = 0;
2077        self.tracked_count = 0;
2078        self.new_staged_count = 0;
2079        self.tracked_staged_count = 0;
2080        for entry in &self.entries {
2081            let Some(status_entry) = entry.status_entry() else {
2082                continue;
2083            };
2084            if repo.has_conflict(&status_entry.repo_path) {
2085                self.conflicted_count += 1;
2086                if self.entry_is_staged(status_entry) != Some(false) {
2087                    self.conflicted_staged_count += 1;
2088                }
2089            } else if status_entry.status.is_created() {
2090                self.new_count += 1;
2091                if self.entry_is_staged(status_entry) != Some(false) {
2092                    self.new_staged_count += 1;
2093                }
2094            } else {
2095                self.tracked_count += 1;
2096                if self.entry_is_staged(status_entry) != Some(false) {
2097                    self.tracked_staged_count += 1;
2098                }
2099            }
2100        }
2101    }
2102
2103    fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
2104        for pending in self.pending.iter().rev() {
2105            if pending.repo_paths.contains(&entry.repo_path) {
2106                match pending.target_status {
2107                    TargetStatus::Staged => return Some(true),
2108                    TargetStatus::Unstaged => return Some(false),
2109                    TargetStatus::Reverted => continue,
2110                    TargetStatus::Unchanged => continue,
2111                }
2112            }
2113        }
2114        entry.is_staged
2115    }
2116
2117    pub(crate) fn has_staged_changes(&self) -> bool {
2118        self.tracked_staged_count > 0
2119            || self.new_staged_count > 0
2120            || self.conflicted_staged_count > 0
2121    }
2122
2123    pub(crate) fn has_unstaged_changes(&self) -> bool {
2124        self.tracked_count > self.tracked_staged_count
2125            || self.new_count > self.new_staged_count
2126            || self.conflicted_count > self.conflicted_staged_count
2127    }
2128
2129    fn has_conflicts(&self) -> bool {
2130        self.conflicted_count > 0
2131    }
2132
2133    fn has_tracked_changes(&self) -> bool {
2134        self.tracked_count > 0
2135    }
2136
2137    pub fn has_unstaged_conflicts(&self) -> bool {
2138        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2139    }
2140
2141    fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
2142        let Some(workspace) = self.workspace.upgrade() else {
2143            return;
2144        };
2145        let notif_id = NotificationId::Named("git-operation-error".into());
2146
2147        let message = e.to_string().trim().to_string();
2148        let toast;
2149        if message
2150            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2151            .next()
2152            .is_some()
2153        {
2154            return; // Hide the cancelled by user message
2155        } else {
2156            toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
2157                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
2158            });
2159        }
2160        workspace.update(cx, |workspace, cx| {
2161            workspace.show_toast(toast, cx);
2162        });
2163    }
2164
2165    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2166        let Some(workspace) = self.workspace.upgrade() else {
2167            return;
2168        };
2169
2170        let notification_id = NotificationId::Named("git-remote-info".into());
2171
2172        workspace.update(cx, |workspace, cx| {
2173            workspace.show_notification(notification_id.clone(), cx, |cx| {
2174                let workspace = cx.weak_entity();
2175                cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
2176            });
2177        });
2178    }
2179
2180    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2181        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2182            Icon::new(IconName::ArrowCircle)
2183                .size(IconSize::XSmall)
2184                .color(Color::Info)
2185                .with_animation(
2186                    "arrow-circle",
2187                    Animation::new(Duration::from_secs(2)).repeat(),
2188                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2189                )
2190                .into_any_element()
2191        })
2192    }
2193
2194    pub fn can_commit(&self) -> bool {
2195        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2196    }
2197
2198    pub fn can_stage_all(&self) -> bool {
2199        self.has_unstaged_changes()
2200    }
2201
2202    pub fn can_unstage_all(&self) -> bool {
2203        self.has_staged_changes()
2204    }
2205
2206    pub(crate) fn render_generate_commit_message_button(
2207        &self,
2208        cx: &Context<Self>,
2209    ) -> Option<AnyElement> {
2210        current_language_model(cx).is_some().then(|| {
2211            if self.generate_commit_message_task.is_some() {
2212                return h_flex()
2213                    .gap_1()
2214                    .child(
2215                        Icon::new(IconName::ArrowCircle)
2216                            .size(IconSize::XSmall)
2217                            .color(Color::Info)
2218                            .with_animation(
2219                                "arrow-circle",
2220                                Animation::new(Duration::from_secs(2)).repeat(),
2221                                |icon, delta| {
2222                                    icon.transform(Transformation::rotate(percentage(delta)))
2223                                },
2224                            ),
2225                    )
2226                    .child(
2227                        Label::new("Generating Commit...")
2228                            .size(LabelSize::Small)
2229                            .color(Color::Muted),
2230                    )
2231                    .into_any_element();
2232            }
2233
2234            IconButton::new("generate-commit-message", IconName::AiEdit)
2235                .shape(ui::IconButtonShape::Square)
2236                .icon_color(Color::Muted)
2237                .tooltip(Tooltip::for_action_title_in(
2238                    "Generate Commit Message",
2239                    &git::GenerateCommitMessage,
2240                    &self.commit_editor.focus_handle(cx),
2241                ))
2242                .on_click(cx.listener(move |this, _event, _window, cx| {
2243                    this.generate_commit_message(cx);
2244                }))
2245                .into_any_element()
2246        })
2247    }
2248
2249    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2250        let potential_co_authors = self.potential_co_authors(cx);
2251        if potential_co_authors.is_empty() {
2252            None
2253        } else {
2254            Some(
2255                IconButton::new("co-authors", IconName::Person)
2256                    .shape(ui::IconButtonShape::Square)
2257                    .icon_color(Color::Disabled)
2258                    .selected_icon_color(Color::Selected)
2259                    .toggle_state(self.add_coauthors)
2260                    .tooltip(move |_, cx| {
2261                        let title = format!(
2262                            "Add co-authored-by:{}{}",
2263                            if potential_co_authors.len() == 1 {
2264                                ""
2265                            } else {
2266                                "\n"
2267                            },
2268                            potential_co_authors
2269                                .iter()
2270                                .map(|(name, email)| format!(" {} <{}>", name, email))
2271                                .join("\n")
2272                        );
2273                        Tooltip::simple(title, cx)
2274                    })
2275                    .on_click(cx.listener(|this, _, _, cx| {
2276                        this.add_coauthors = !this.add_coauthors;
2277                        cx.notify();
2278                    }))
2279                    .into_any_element(),
2280            )
2281        }
2282    }
2283
2284    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2285        if self.has_unstaged_conflicts() {
2286            (false, "You must resolve conflicts before committing")
2287        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2288            (
2289                false,
2290                "You must have either staged changes or tracked files to commit",
2291            )
2292        } else if self.pending_commit.is_some() {
2293            (false, "Commit in progress")
2294        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2295            (false, "No commit message")
2296        } else if !self.has_write_access(cx) {
2297            (false, "You do not have write access to this project")
2298        } else {
2299            (true, self.commit_button_title())
2300        }
2301    }
2302
2303    pub fn commit_button_title(&self) -> &'static str {
2304        if self.has_staged_changes() {
2305            "Commit"
2306        } else {
2307            "Commit Tracked"
2308        }
2309    }
2310
2311    fn expand_commit_editor(
2312        &mut self,
2313        _: &git::ExpandCommitEditor,
2314        window: &mut Window,
2315        cx: &mut Context<Self>,
2316    ) {
2317        let workspace = self.workspace.clone();
2318        window.defer(cx, move |window, cx| {
2319            workspace
2320                .update(cx, |workspace, cx| {
2321                    CommitModal::toggle(workspace, window, cx)
2322                })
2323                .ok();
2324        })
2325    }
2326
2327    pub fn render_footer(
2328        &self,
2329        window: &mut Window,
2330        cx: &mut Context<Self>,
2331    ) -> Option<impl IntoElement> {
2332        let active_repository = self.active_repository.clone()?;
2333        let (can_commit, tooltip) = self.configure_commit_button(cx);
2334        let project = self.project.clone().read(cx);
2335        let panel_editor_style = panel_editor_style(true, window, cx);
2336
2337        let enable_coauthors = self.render_co_authors(cx);
2338        let title = self.commit_button_title();
2339
2340        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2341        let commit_tooltip_focus_handle = editor_focus_handle.clone();
2342        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2343
2344        let branch = active_repository.read(cx).current_branch().cloned();
2345
2346        let footer_size = px(32.);
2347        let gap = px(8.0);
2348        let max_height = window.line_height() * 5. + gap + footer_size;
2349
2350        let git_panel = cx.entity().clone();
2351        let display_name = SharedString::from(Arc::from(
2352            active_repository
2353                .read(cx)
2354                .display_name(project, cx)
2355                .trim_end_matches("/"),
2356        ));
2357
2358        let footer = v_flex()
2359            .child(PanelRepoFooter::new(
2360                "footer-button",
2361                display_name,
2362                branch,
2363                Some(git_panel),
2364            ))
2365            .child(
2366                panel_editor_container(window, cx)
2367                    .id("commit-editor-container")
2368                    .relative()
2369                    .h(max_height)
2370                    .w_full()
2371                    .border_t_1()
2372                    .border_color(cx.theme().colors().border_variant)
2373                    .bg(cx.theme().colors().editor_background)
2374                    .cursor_text()
2375                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2376                        window.focus(&this.commit_editor.focus_handle(cx));
2377                    }))
2378                    .child(
2379                        h_flex()
2380                            .id("commit-footer")
2381                            .absolute()
2382                            .bottom_0()
2383                            .left_0()
2384                            .w_full()
2385                            .px_2()
2386                            .h(footer_size)
2387                            .flex_none()
2388                            .justify_between()
2389                            .child(
2390                                self.render_generate_commit_message_button(cx)
2391                                    .unwrap_or_else(|| div().into_any_element()),
2392                            )
2393                            .child(
2394                                h_flex().gap_0p5().children(enable_coauthors).child(
2395                                    panel_filled_button(title)
2396                                        .tooltip(move |window, cx| {
2397                                            if can_commit {
2398                                                Tooltip::for_action_in(
2399                                                    tooltip,
2400                                                    &Commit,
2401                                                    &commit_tooltip_focus_handle,
2402                                                    window,
2403                                                    cx,
2404                                                )
2405                                            } else {
2406                                                Tooltip::simple(tooltip, cx)
2407                                            }
2408                                        })
2409                                        .disabled(!can_commit || self.modal_open)
2410                                        .on_click({
2411                                            cx.listener(move |this, _: &ClickEvent, window, cx| {
2412                                                this.commit_changes(window, cx)
2413                                            })
2414                                        }),
2415                                ),
2416                            ),
2417                    )
2418                    .child(
2419                        div()
2420                            .pr_2p5()
2421                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2422                    )
2423                    .child(
2424                        h_flex()
2425                            .absolute()
2426                            .top_2()
2427                            .right_2()
2428                            .opacity(0.5)
2429                            .hover(|this| this.opacity(1.0))
2430                            .child(
2431                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2432                                    .icon_size(IconSize::Small)
2433                                    .size(ui::ButtonSize::Default)
2434                                    .tooltip(move |window, cx| {
2435                                        Tooltip::for_action_in(
2436                                            "Open Commit Modal",
2437                                            &git::ExpandCommitEditor,
2438                                            &expand_tooltip_focus_handle,
2439                                            window,
2440                                            cx,
2441                                        )
2442                                    })
2443                                    .on_click(cx.listener({
2444                                        move |_, _, window, cx| {
2445                                            window.dispatch_action(
2446                                                git::ExpandCommitEditor.boxed_clone(),
2447                                                cx,
2448                                            )
2449                                        }
2450                                    })),
2451                            ),
2452                    ),
2453            );
2454
2455        Some(footer)
2456    }
2457
2458    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2459        let active_repository = self.active_repository.as_ref()?;
2460        let branch = active_repository.read(cx).current_branch()?;
2461        let commit = branch.most_recent_commit.as_ref()?.clone();
2462
2463        let this = cx.entity();
2464        Some(
2465            h_flex()
2466                .items_center()
2467                .py_2()
2468                .px(px(8.))
2469                // .bg(cx.theme().colors().background)
2470                // .border_t_1()
2471                .border_color(cx.theme().colors().border)
2472                .gap_1p5()
2473                .child(
2474                    div()
2475                        .flex_grow()
2476                        .overflow_hidden()
2477                        .max_w(relative(0.6))
2478                        .h_full()
2479                        .child(
2480                            Label::new(commit.subject.clone())
2481                                .size(LabelSize::Small)
2482                                .truncate(),
2483                        )
2484                        .id("commit-msg-hover")
2485                        .hoverable_tooltip(move |window, cx| {
2486                            GitPanelMessageTooltip::new(
2487                                this.clone(),
2488                                commit.sha.clone(),
2489                                window,
2490                                cx,
2491                            )
2492                            .into()
2493                        }),
2494                )
2495                .child(div().flex_1())
2496                .when(commit.has_parent, |this| {
2497                    let has_unstaged = self.has_unstaged_changes();
2498                    this.child(
2499                        panel_icon_button("undo", IconName::Undo)
2500                            .icon_size(IconSize::Small)
2501                            .icon_color(Color::Muted)
2502                            .tooltip(move |window, cx| {
2503                                Tooltip::with_meta(
2504                                    "Uncommit",
2505                                    Some(&git::Uncommit),
2506                                    if has_unstaged {
2507                                        "git reset HEAD^ --soft"
2508                                    } else {
2509                                        "git reset HEAD^"
2510                                    },
2511                                    window,
2512                                    cx,
2513                                )
2514                            })
2515                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2516                    )
2517                }),
2518        )
2519    }
2520
2521    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2522        h_flex()
2523            .h_full()
2524            .flex_grow()
2525            .justify_center()
2526            .items_center()
2527            .child(
2528                v_flex()
2529                    .gap_3()
2530                    .child(if self.active_repository.is_some() {
2531                        "No changes to commit"
2532                    } else {
2533                        "No Git repositories"
2534                    })
2535                    .text_ui_sm(cx)
2536                    .mx_auto()
2537                    .text_color(Color::Placeholder.color(cx)),
2538            )
2539    }
2540
2541    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2542        let scroll_bar_style = self.show_scrollbar(cx);
2543        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2544
2545        if !self.should_show_scrollbar(cx)
2546            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2547        {
2548            return None;
2549        }
2550
2551        Some(
2552            div()
2553                .id("git-panel-vertical-scroll")
2554                .occlude()
2555                .flex_none()
2556                .h_full()
2557                .cursor_default()
2558                .when(show_container, |this| this.pl_1().px_1p5())
2559                .when(!show_container, |this| {
2560                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
2561                })
2562                .on_mouse_move(cx.listener(|_, _, _, cx| {
2563                    cx.notify();
2564                    cx.stop_propagation()
2565                }))
2566                .on_hover(|_, _, cx| {
2567                    cx.stop_propagation();
2568                })
2569                .on_any_mouse_down(|_, _, cx| {
2570                    cx.stop_propagation();
2571                })
2572                .on_mouse_up(
2573                    MouseButton::Left,
2574                    cx.listener(|this, _, window, cx| {
2575                        if !this.scrollbar_state.is_dragging()
2576                            && !this.focus_handle.contains_focused(window, cx)
2577                        {
2578                            this.hide_scrollbar(window, cx);
2579                            cx.notify();
2580                        }
2581
2582                        cx.stop_propagation();
2583                    }),
2584                )
2585                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2586                    cx.notify();
2587                }))
2588                .children(Scrollbar::vertical(
2589                    // percentage as f32..end_offset as f32,
2590                    self.scrollbar_state.clone(),
2591                )),
2592        )
2593    }
2594
2595    fn render_buffer_header_controls(
2596        &self,
2597        entity: &Entity<Self>,
2598        file: &Arc<dyn File>,
2599        _: &Window,
2600        cx: &App,
2601    ) -> Option<AnyElement> {
2602        let repo = self.active_repository.as_ref()?.read(cx);
2603        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2604        let ix = self.entry_by_path(&repo_path)?;
2605        let entry = self.entries.get(ix)?;
2606
2607        let is_staged = self.entry_is_staged(entry.status_entry()?);
2608
2609        let checkbox = Checkbox::new("stage-file", is_staged.into())
2610            .disabled(!self.has_write_access(cx))
2611            .fill()
2612            .elevation(ElevationIndex::Surface)
2613            .on_click({
2614                let entry = entry.clone();
2615                let git_panel = entity.downgrade();
2616                move |_, window, cx| {
2617                    git_panel
2618                        .update(cx, |this, cx| {
2619                            this.toggle_staged_for_entry(&entry, window, cx);
2620                            cx.stop_propagation();
2621                        })
2622                        .ok();
2623                }
2624            });
2625        Some(
2626            h_flex()
2627                .id("start-slot")
2628                .text_lg()
2629                .child(checkbox)
2630                .on_mouse_down(MouseButton::Left, |_, _, cx| {
2631                    // prevent the list item active state triggering when toggling checkbox
2632                    cx.stop_propagation();
2633                })
2634                .into_any_element(),
2635        )
2636    }
2637
2638    fn render_entries(
2639        &self,
2640        has_write_access: bool,
2641        _: &Window,
2642        cx: &mut Context<Self>,
2643    ) -> impl IntoElement {
2644        let entry_count = self.entries.len();
2645
2646        h_flex()
2647            .size_full()
2648            .flex_grow()
2649            .overflow_hidden()
2650            .child(
2651                uniform_list(cx.entity().clone(), "entries", entry_count, {
2652                    move |this, range, window, cx| {
2653                        let mut items = Vec::with_capacity(range.end - range.start);
2654
2655                        for ix in range {
2656                            match &this.entries.get(ix) {
2657                                Some(GitListEntry::GitStatusEntry(entry)) => {
2658                                    items.push(this.render_entry(
2659                                        ix,
2660                                        entry,
2661                                        has_write_access,
2662                                        window,
2663                                        cx,
2664                                    ));
2665                                }
2666                                Some(GitListEntry::Header(header)) => {
2667                                    items.push(this.render_list_header(
2668                                        ix,
2669                                        header,
2670                                        has_write_access,
2671                                        window,
2672                                        cx,
2673                                    ));
2674                                }
2675                                None => {}
2676                            }
2677                        }
2678
2679                        items
2680                    }
2681                })
2682                .size_full()
2683                .with_sizing_behavior(ListSizingBehavior::Auto)
2684                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2685                .track_scroll(self.scroll_handle.clone()),
2686            )
2687            .on_mouse_down(
2688                MouseButton::Right,
2689                cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2690                    this.deploy_panel_context_menu(event.position, window, cx)
2691                }),
2692            )
2693            .children(self.render_scrollbar(cx))
2694    }
2695
2696    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2697        Label::new(label.into()).color(color).single_line()
2698    }
2699
2700    fn list_item_height(&self) -> Rems {
2701        rems(1.75)
2702    }
2703
2704    fn render_list_header(
2705        &self,
2706        ix: usize,
2707        header: &GitHeaderEntry,
2708        _: bool,
2709        _: &Window,
2710        _: &Context<Self>,
2711    ) -> AnyElement {
2712        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2713
2714        h_flex()
2715            .id(id)
2716            .h(self.list_item_height())
2717            .w_full()
2718            .items_end()
2719            .px(rems(0.75)) // ~12px
2720            .pb(rems(0.3125)) // ~ 5px
2721            .child(
2722                Label::new(header.title())
2723                    .color(Color::Muted)
2724                    .size(LabelSize::Small)
2725                    .line_height_style(LineHeightStyle::UiLabel)
2726                    .single_line(),
2727            )
2728            .into_any_element()
2729    }
2730
2731    fn load_commit_details(
2732        &self,
2733        sha: &str,
2734        cx: &mut Context<Self>,
2735    ) -> Task<anyhow::Result<CommitDetails>> {
2736        let Some(repo) = self.active_repository.clone() else {
2737            return Task::ready(Err(anyhow::anyhow!("no active repo")));
2738        };
2739        repo.update(cx, |repo, cx| {
2740            let show = repo.show(sha);
2741            cx.spawn(|_, _| async move { show.await? })
2742        })
2743    }
2744
2745    fn deploy_entry_context_menu(
2746        &mut self,
2747        position: Point<Pixels>,
2748        ix: usize,
2749        window: &mut Window,
2750        cx: &mut Context<Self>,
2751    ) {
2752        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2753            return;
2754        };
2755        let stage_title = if entry.status.is_staged() == Some(true) {
2756            "Unstage File"
2757        } else {
2758            "Stage File"
2759        };
2760        let restore_title = if entry.status.is_created() {
2761            "Trash File"
2762        } else {
2763            "Restore File"
2764        };
2765        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2766            context_menu
2767                .action(stage_title, ToggleStaged.boxed_clone())
2768                .action(restore_title, git::RestoreFile.boxed_clone())
2769                .separator()
2770                .action("Open Diff", Confirm.boxed_clone())
2771                .action("Open File", SecondaryConfirm.boxed_clone())
2772        });
2773        self.selected_entry = Some(ix);
2774        self.set_context_menu(context_menu, position, window, cx);
2775    }
2776
2777    fn deploy_panel_context_menu(
2778        &mut self,
2779        position: Point<Pixels>,
2780        window: &mut Window,
2781        cx: &mut Context<Self>,
2782    ) {
2783        let context_menu = git_panel_context_menu(window, cx);
2784        self.set_context_menu(context_menu, position, window, cx);
2785    }
2786
2787    fn set_context_menu(
2788        &mut self,
2789        context_menu: Entity<ContextMenu>,
2790        position: Point<Pixels>,
2791        window: &Window,
2792        cx: &mut Context<Self>,
2793    ) {
2794        let subscription = cx.subscribe_in(
2795            &context_menu,
2796            window,
2797            |this, _, _: &DismissEvent, window, cx| {
2798                if this.context_menu.as_ref().is_some_and(|context_menu| {
2799                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
2800                }) {
2801                    cx.focus_self(window);
2802                }
2803                this.context_menu.take();
2804                cx.notify();
2805            },
2806        );
2807        self.context_menu = Some((context_menu, position, subscription));
2808        cx.notify();
2809    }
2810
2811    fn render_entry(
2812        &self,
2813        ix: usize,
2814        entry: &GitStatusEntry,
2815        has_write_access: bool,
2816        window: &Window,
2817        cx: &Context<Self>,
2818    ) -> AnyElement {
2819        let display_name = entry
2820            .worktree_path
2821            .file_name()
2822            .map(|name| name.to_string_lossy().into_owned())
2823            .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2824
2825        let worktree_path = entry.worktree_path.clone();
2826        let selected = self.selected_entry == Some(ix);
2827        let marked = self.marked_entries.contains(&ix);
2828        let status_style = GitPanelSettings::get_global(cx).status_style;
2829        let status = entry.status;
2830        let has_conflict = status.is_conflicted();
2831        let is_modified = status.is_modified();
2832        let is_deleted = status.is_deleted();
2833
2834        let label_color = if status_style == StatusStyle::LabelColor {
2835            if has_conflict {
2836                Color::Conflict
2837            } else if is_modified {
2838                Color::Modified
2839            } else if is_deleted {
2840                // We don't want a bunch of red labels in the list
2841                Color::Disabled
2842            } else {
2843                Color::Created
2844            }
2845        } else {
2846            Color::Default
2847        };
2848
2849        let path_color = if status.is_deleted() {
2850            Color::Disabled
2851        } else {
2852            Color::Muted
2853        };
2854
2855        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2856        let checkbox_wrapper_id: ElementId =
2857            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2858        let checkbox_id: ElementId =
2859            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2860
2861        let is_entry_staged = self.entry_is_staged(entry);
2862        let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2863
2864        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2865            is_staged = ToggleState::Selected;
2866        }
2867
2868        let handle = cx.weak_entity();
2869
2870        let selected_bg_alpha = 0.08;
2871        let marked_bg_alpha = 0.12;
2872        let state_opacity_step = 0.04;
2873
2874        let base_bg = match (selected, marked) {
2875            (true, true) => cx
2876                .theme()
2877                .status()
2878                .info
2879                .alpha(selected_bg_alpha + marked_bg_alpha),
2880            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2881            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2882            _ => cx.theme().colors().ghost_element_background,
2883        };
2884
2885        let hover_bg = if selected {
2886            cx.theme()
2887                .status()
2888                .info
2889                .alpha(selected_bg_alpha + state_opacity_step)
2890        } else {
2891            cx.theme().colors().ghost_element_hover
2892        };
2893
2894        let active_bg = if selected {
2895            cx.theme()
2896                .status()
2897                .info
2898                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2899        } else {
2900            cx.theme().colors().ghost_element_active
2901        };
2902
2903        h_flex()
2904            .id(id)
2905            .h(self.list_item_height())
2906            .w_full()
2907            .items_center()
2908            .border_1()
2909            .when(selected && self.focus_handle.is_focused(window), |el| {
2910                el.border_color(cx.theme().colors().border_focused)
2911            })
2912            .px(rems(0.75)) // ~12px
2913            .overflow_hidden()
2914            .flex_none()
2915            .gap(DynamicSpacing::Base04.rems(cx))
2916            .bg(base_bg)
2917            .hover(|this| this.bg(hover_bg))
2918            .active(|this| this.bg(active_bg))
2919            .on_click({
2920                cx.listener(move |this, event: &ClickEvent, window, cx| {
2921                    this.selected_entry = Some(ix);
2922                    cx.notify();
2923                    if event.modifiers().secondary() {
2924                        this.open_file(&Default::default(), window, cx)
2925                    } else {
2926                        this.open_diff(&Default::default(), window, cx);
2927                        this.focus_handle.focus(window);
2928                    }
2929                })
2930            })
2931            .on_mouse_down(
2932                MouseButton::Right,
2933                move |event: &MouseDownEvent, window, cx| {
2934                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2935                    if event.button != MouseButton::Right {
2936                        return;
2937                    }
2938
2939                    let Some(this) = handle.upgrade() else {
2940                        return;
2941                    };
2942                    this.update(cx, |this, cx| {
2943                        this.deploy_entry_context_menu(event.position, ix, window, cx);
2944                    });
2945                    cx.stop_propagation();
2946                },
2947            )
2948            // .on_secondary_mouse_down(cx.listener(
2949            //     move |this, event: &MouseDownEvent, window, cx| {
2950            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
2951            //         cx.stop_propagation();
2952            //     },
2953            // ))
2954            .child(
2955                div()
2956                    .id(checkbox_wrapper_id)
2957                    .flex_none()
2958                    .occlude()
2959                    .cursor_pointer()
2960                    .child(
2961                        Checkbox::new(checkbox_id, is_staged)
2962                            .disabled(!has_write_access)
2963                            .fill()
2964                            .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2965                            .elevation(ElevationIndex::Surface)
2966                            .on_click({
2967                                let entry = entry.clone();
2968                                cx.listener(move |this, _, window, cx| {
2969                                    if !has_write_access {
2970                                        return;
2971                                    }
2972                                    this.toggle_staged_for_entry(
2973                                        &GitListEntry::GitStatusEntry(entry.clone()),
2974                                        window,
2975                                        cx,
2976                                    );
2977                                    cx.stop_propagation();
2978                                })
2979                            })
2980                            .tooltip(move |window, cx| {
2981                                let tooltip_name = if is_entry_staged.unwrap_or(false) {
2982                                    "Unstage"
2983                                } else {
2984                                    "Stage"
2985                                };
2986
2987                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2988                            }),
2989                    ),
2990            )
2991            .child(git_status_icon(status, cx))
2992            .child(
2993                h_flex()
2994                    .items_center()
2995                    .overflow_hidden()
2996                    .when_some(worktree_path.parent(), |this, parent| {
2997                        let parent_str = parent.to_string_lossy();
2998                        if !parent_str.is_empty() {
2999                            this.child(
3000                                self.entry_label(format!("{}/", parent_str), path_color)
3001                                    .when(status.is_deleted(), |this| this.strikethrough()),
3002                            )
3003                        } else {
3004                            this
3005                        }
3006                    })
3007                    .child(
3008                        self.entry_label(display_name.clone(), label_color)
3009                            .when(status.is_deleted(), |this| this.strikethrough()),
3010                    ),
3011            )
3012            .into_any_element()
3013    }
3014
3015    fn has_write_access(&self, cx: &App) -> bool {
3016        !self.project.read(cx).is_read_only(cx)
3017    }
3018}
3019
3020fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3021    let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3022    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3023    provider.is_authenticated(cx).then(|| model)
3024}
3025
3026impl Render for GitPanel {
3027    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3028        let project = self.project.read(cx);
3029        let has_entries = self.entries.len() > 0;
3030        let room = self
3031            .workspace
3032            .upgrade()
3033            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3034
3035        let has_write_access = self.has_write_access(cx);
3036
3037        let has_co_authors = room.map_or(false, |room| {
3038            room.read(cx)
3039                .remote_participants()
3040                .values()
3041                .any(|remote_participant| remote_participant.can_write())
3042        });
3043
3044        v_flex()
3045            .id("git_panel")
3046            .key_context(self.dispatch_context(window, cx))
3047            .track_focus(&self.focus_handle)
3048            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3049            .when(has_write_access && !project.is_read_only(cx), |this| {
3050                this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
3051                    this.toggle_staged_for_selected(&ToggleStaged, window, cx)
3052                }))
3053                .on_action(cx.listener(GitPanel::commit))
3054            })
3055            .on_action(cx.listener(Self::select_first))
3056            .on_action(cx.listener(Self::select_next))
3057            .on_action(cx.listener(Self::select_previous))
3058            .on_action(cx.listener(Self::select_last))
3059            .on_action(cx.listener(Self::close_panel))
3060            .on_action(cx.listener(Self::open_diff))
3061            .on_action(cx.listener(Self::open_file))
3062            .on_action(cx.listener(Self::revert_selected))
3063            .on_action(cx.listener(Self::focus_changes_list))
3064            .on_action(cx.listener(Self::focus_editor))
3065            .on_action(cx.listener(Self::toggle_staged_for_selected))
3066            .on_action(cx.listener(Self::stage_all))
3067            .on_action(cx.listener(Self::unstage_all))
3068            .on_action(cx.listener(Self::restore_tracked_files))
3069            .on_action(cx.listener(Self::clean_all))
3070            .on_action(cx.listener(Self::expand_commit_editor))
3071            .on_action(cx.listener(Self::generate_commit_message_action))
3072            .when(has_write_access && has_co_authors, |git_panel| {
3073                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3074            })
3075            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3076            .on_hover(cx.listener(|this, hovered, window, cx| {
3077                if *hovered {
3078                    this.show_scrollbar = true;
3079                    this.hide_scrollbar_task.take();
3080                    cx.notify();
3081                } else if !this.focus_handle.contains_focused(window, cx) {
3082                    this.hide_scrollbar(window, cx);
3083                }
3084            }))
3085            .size_full()
3086            .overflow_hidden()
3087            .bg(ElevationIndex::Surface.bg(cx))
3088            .child(
3089                v_flex()
3090                    .size_full()
3091                    .map(|this| {
3092                        if has_entries {
3093                            this.child(self.render_entries(has_write_access, window, cx))
3094                        } else {
3095                            this.child(self.render_empty_state(cx).into_any_element())
3096                        }
3097                    })
3098                    .children(self.render_footer(window, cx))
3099                    .children(self.render_previous_commit(cx))
3100                    .into_any_element(),
3101            )
3102            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3103                deferred(
3104                    anchored()
3105                        .position(*position)
3106                        .anchor(gpui::Corner::TopLeft)
3107                        .child(menu.clone()),
3108                )
3109                .with_priority(1)
3110            }))
3111    }
3112}
3113
3114impl Focusable for GitPanel {
3115    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3116        self.focus_handle.clone()
3117    }
3118}
3119
3120impl EventEmitter<Event> for GitPanel {}
3121
3122impl EventEmitter<PanelEvent> for GitPanel {}
3123
3124pub(crate) struct GitPanelAddon {
3125    pub(crate) workspace: WeakEntity<Workspace>,
3126}
3127
3128impl editor::Addon for GitPanelAddon {
3129    fn to_any(&self) -> &dyn std::any::Any {
3130        self
3131    }
3132
3133    fn render_buffer_header_controls(
3134        &self,
3135        excerpt_info: &ExcerptInfo,
3136        window: &Window,
3137        cx: &App,
3138    ) -> Option<AnyElement> {
3139        let file = excerpt_info.buffer.file()?;
3140        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3141
3142        git_panel
3143            .read(cx)
3144            .render_buffer_header_controls(&git_panel, &file, window, cx)
3145    }
3146}
3147
3148impl Panel for GitPanel {
3149    fn persistent_name() -> &'static str {
3150        "GitPanel"
3151    }
3152
3153    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3154        GitPanelSettings::get_global(cx).dock
3155    }
3156
3157    fn position_is_valid(&self, position: DockPosition) -> bool {
3158        matches!(position, DockPosition::Left | DockPosition::Right)
3159    }
3160
3161    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3162        settings::update_settings_file::<GitPanelSettings>(
3163            self.fs.clone(),
3164            cx,
3165            move |settings, _| settings.dock = Some(position),
3166        );
3167    }
3168
3169    fn size(&self, _: &Window, cx: &App) -> Pixels {
3170        self.width
3171            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3172    }
3173
3174    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3175        self.width = size;
3176        self.serialize(cx);
3177        cx.notify();
3178    }
3179
3180    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3181        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3182    }
3183
3184    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3185        Some("Git Panel")
3186    }
3187
3188    fn toggle_action(&self) -> Box<dyn Action> {
3189        Box::new(ToggleFocus)
3190    }
3191
3192    fn activation_priority(&self) -> u32 {
3193        2
3194    }
3195}
3196
3197impl PanelHeader for GitPanel {}
3198
3199struct GitPanelMessageTooltip {
3200    commit_tooltip: Option<Entity<CommitTooltip>>,
3201}
3202
3203impl GitPanelMessageTooltip {
3204    fn new(
3205        git_panel: Entity<GitPanel>,
3206        sha: SharedString,
3207        window: &mut Window,
3208        cx: &mut App,
3209    ) -> Entity<Self> {
3210        cx.new(|cx| {
3211            cx.spawn_in(window, |this, mut cx| async move {
3212                let details = git_panel
3213                    .update(&mut cx, |git_panel, cx| {
3214                        git_panel.load_commit_details(&sha, cx)
3215                    })?
3216                    .await?;
3217
3218                let commit_details = editor::commit_tooltip::CommitDetails {
3219                    sha: details.sha.clone(),
3220                    committer_name: details.committer_name.clone(),
3221                    committer_email: details.committer_email.clone(),
3222                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3223                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3224                        message: details.message.clone(),
3225                        ..Default::default()
3226                    }),
3227                };
3228
3229                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3230                    this.commit_tooltip =
3231                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3232                    cx.notify();
3233                })
3234            })
3235            .detach();
3236
3237            Self {
3238                commit_tooltip: None,
3239            }
3240        })
3241    }
3242}
3243
3244impl Render for GitPanelMessageTooltip {
3245    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3246        if let Some(commit_tooltip) = &self.commit_tooltip {
3247            commit_tooltip.clone().into_any_element()
3248        } else {
3249            gpui::Empty.into_any_element()
3250        }
3251    }
3252}
3253
3254fn git_action_tooltip(
3255    label: impl Into<SharedString>,
3256    action: &dyn Action,
3257    command: impl Into<SharedString>,
3258    focus_handle: Option<FocusHandle>,
3259    window: &mut Window,
3260    cx: &mut App,
3261) -> AnyView {
3262    let label = label.into();
3263    let command = command.into();
3264
3265    if let Some(handle) = focus_handle {
3266        Tooltip::with_meta_in(
3267            label.clone(),
3268            Some(action),
3269            command.clone(),
3270            &handle,
3271            window,
3272            cx,
3273        )
3274    } else {
3275        Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
3276    }
3277}
3278
3279#[derive(IntoElement)]
3280struct SplitButton {
3281    pub left: ButtonLike,
3282    pub right: AnyElement,
3283}
3284
3285impl SplitButton {
3286    fn new(
3287        id: impl Into<SharedString>,
3288        left_label: impl Into<SharedString>,
3289        ahead_count: usize,
3290        behind_count: usize,
3291        left_icon: Option<IconName>,
3292        left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
3293        tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
3294    ) -> Self {
3295        let id = id.into();
3296
3297        fn count(count: usize) -> impl IntoElement {
3298            h_flex()
3299                .ml_neg_px()
3300                .h(rems(0.875))
3301                .items_center()
3302                .overflow_hidden()
3303                .px_0p5()
3304                .child(
3305                    Label::new(count.to_string())
3306                        .size(LabelSize::XSmall)
3307                        .line_height_style(LineHeightStyle::UiLabel),
3308                )
3309        }
3310
3311        let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
3312
3313        let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
3314            format!("split-button-left-{}", id).into(),
3315        ))
3316        .layer(ui::ElevationIndex::ModalSurface)
3317        .size(ui::ButtonSize::Compact)
3318        .when(should_render_counts, |this| {
3319            this.child(
3320                h_flex()
3321                    .ml_neg_0p5()
3322                    .mr_1()
3323                    .when(behind_count > 0, |this| {
3324                        this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
3325                            .child(count(behind_count))
3326                    })
3327                    .when(ahead_count > 0, |this| {
3328                        this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
3329                            .child(count(ahead_count))
3330                    }),
3331            )
3332        })
3333        .when_some(left_icon, |this, left_icon| {
3334            this.child(
3335                h_flex()
3336                    .ml_neg_0p5()
3337                    .mr_1()
3338                    .child(Icon::new(left_icon).size(IconSize::XSmall)),
3339            )
3340        })
3341        .child(
3342            div()
3343                .child(Label::new(left_label).size(LabelSize::Small))
3344                .mr_0p5(),
3345        )
3346        .on_click(left_on_click)
3347        .tooltip(tooltip);
3348
3349        let right =
3350            render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
3351                .into_any_element();
3352        // .on_click(right_on_click);
3353
3354        Self { left, right }
3355    }
3356}
3357
3358impl RenderOnce for SplitButton {
3359    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3360        h_flex()
3361            .rounded_sm()
3362            .border_1()
3363            .border_color(cx.theme().colors().text_muted.alpha(0.12))
3364            .child(self.left)
3365            .child(
3366                div()
3367                    .h_full()
3368                    .w_px()
3369                    .bg(cx.theme().colors().text_muted.alpha(0.16)),
3370            )
3371            .child(self.right)
3372            .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3373            .shadow(smallvec![BoxShadow {
3374                color: hsla(0.0, 0.0, 0.0, 0.16),
3375                offset: point(px(0.), px(1.)),
3376                blur_radius: px(0.),
3377                spread_radius: px(0.),
3378            }])
3379    }
3380}
3381
3382fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3383    PopoverMenu::new(id.into())
3384        .trigger(
3385            ui::ButtonLike::new_rounded_right("split-button-right")
3386                .layer(ui::ElevationIndex::ModalSurface)
3387                .size(ui::ButtonSize::None)
3388                .child(
3389                    div()
3390                        .px_1()
3391                        .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3392                ),
3393        )
3394        .menu(move |window, cx| {
3395            Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3396                context_menu
3397                    .action("Fetch", git::Fetch.boxed_clone())
3398                    .action("Pull", git::Pull.boxed_clone())
3399                    .separator()
3400                    .action("Push", git::Push.boxed_clone())
3401                    .action("Force Push", git::ForcePush.boxed_clone())
3402            }))
3403        })
3404        .anchor(Corner::TopRight)
3405}
3406
3407#[derive(IntoElement, IntoComponent)]
3408#[component(scope = "Version Control")]
3409pub struct PanelRepoFooter {
3410    id: SharedString,
3411    active_repository: SharedString,
3412    branch: Option<Branch>,
3413    // Getting a GitPanel in previews will be difficult.
3414    //
3415    // For now just take an option here, and we won't bind handlers to buttons in previews.
3416    git_panel: Option<Entity<GitPanel>>,
3417}
3418
3419impl PanelRepoFooter {
3420    pub fn new(
3421        id: impl Into<SharedString>,
3422        active_repository: SharedString,
3423        branch: Option<Branch>,
3424        git_panel: Option<Entity<GitPanel>>,
3425    ) -> Self {
3426        Self {
3427            id: id.into(),
3428            active_repository,
3429            branch,
3430            git_panel,
3431        }
3432    }
3433
3434    pub fn new_preview(
3435        id: impl Into<SharedString>,
3436        active_repository: SharedString,
3437        branch: Option<Branch>,
3438    ) -> Self {
3439        Self {
3440            id: id.into(),
3441            active_repository,
3442            branch,
3443            git_panel: None,
3444        }
3445    }
3446
3447    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3448        PopoverMenu::new(id.into())
3449            .trigger(
3450                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3451                    .icon_size(IconSize::Small)
3452                    .icon_color(Color::Muted),
3453            )
3454            .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3455            .anchor(Corner::TopRight)
3456    }
3457
3458    fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3459        if let Some(git_panel) = self.git_panel.clone() {
3460            Some(git_panel.focus_handle(cx))
3461        } else {
3462            None
3463        }
3464    }
3465
3466    fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3467        let panel = self.git_panel.clone();
3468        let panel_focus_handle = self.panel_focus_handle(cx);
3469
3470        SplitButton::new(
3471            id,
3472            "Push",
3473            ahead as usize,
3474            0,
3475            None,
3476            move |_, window, cx| {
3477                if let Some(panel) = panel.as_ref() {
3478                    panel.update(cx, |panel, cx| {
3479                        panel.push(false, window, cx);
3480                    });
3481                }
3482            },
3483            move |window, cx| {
3484                git_action_tooltip(
3485                    "Push committed changes to remote",
3486                    &git::Push,
3487                    "git push",
3488                    panel_focus_handle.clone(),
3489                    window,
3490                    cx,
3491                )
3492            },
3493        )
3494    }
3495
3496    fn render_pull_button(
3497        &self,
3498        id: SharedString,
3499        ahead: u32,
3500        behind: u32,
3501        cx: &mut App,
3502    ) -> SplitButton {
3503        let panel = self.git_panel.clone();
3504        let panel_focus_handle = self.panel_focus_handle(cx);
3505
3506        SplitButton::new(
3507            id,
3508            "Pull",
3509            ahead as usize,
3510            behind as usize,
3511            None,
3512            move |_, window, cx| {
3513                if let Some(panel) = panel.as_ref() {
3514                    panel.update(cx, |panel, cx| {
3515                        panel.pull(window, cx);
3516                    });
3517                }
3518            },
3519            move |window, cx| {
3520                git_action_tooltip(
3521                    "Pull",
3522                    &git::Pull,
3523                    "git pull",
3524                    panel_focus_handle.clone(),
3525                    window,
3526                    cx,
3527                )
3528            },
3529        )
3530    }
3531
3532    fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3533        let panel = self.git_panel.clone();
3534        let panel_focus_handle = self.panel_focus_handle(cx);
3535
3536        SplitButton::new(
3537            id,
3538            "Fetch",
3539            0,
3540            0,
3541            Some(IconName::ArrowCircle),
3542            move |_, window, cx| {
3543                if let Some(panel) = panel.as_ref() {
3544                    panel.update(cx, |panel, cx| {
3545                        panel.fetch(window, cx);
3546                    });
3547                }
3548            },
3549            move |window, cx| {
3550                git_action_tooltip(
3551                    "Fetch updates from remote",
3552                    &git::Fetch,
3553                    "git fetch",
3554                    panel_focus_handle.clone(),
3555                    window,
3556                    cx,
3557                )
3558            },
3559        )
3560    }
3561
3562    fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3563        let panel = self.git_panel.clone();
3564        let panel_focus_handle = self.panel_focus_handle(cx);
3565
3566        SplitButton::new(
3567            id,
3568            "Publish",
3569            0,
3570            0,
3571            Some(IconName::ArrowUpFromLine),
3572            move |_, window, cx| {
3573                if let Some(panel) = panel.as_ref() {
3574                    panel.update(cx, |panel, cx| {
3575                        panel.push(false, window, cx);
3576                    });
3577                }
3578            },
3579            move |window, cx| {
3580                git_action_tooltip(
3581                    "Publish branch to remote",
3582                    &git::Push,
3583                    "git push --set-upstream",
3584                    panel_focus_handle.clone(),
3585                    window,
3586                    cx,
3587                )
3588            },
3589        )
3590    }
3591
3592    fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3593        let panel = self.git_panel.clone();
3594        let panel_focus_handle = self.panel_focus_handle(cx);
3595
3596        SplitButton::new(
3597            id,
3598            "Republish",
3599            0,
3600            0,
3601            Some(IconName::ArrowUpFromLine),
3602            move |_, window, cx| {
3603                if let Some(panel) = panel.as_ref() {
3604                    panel.update(cx, |panel, cx| {
3605                        panel.push(false, window, cx);
3606                    });
3607                }
3608            },
3609            move |window, cx| {
3610                git_action_tooltip(
3611                    "Re-publish branch to remote",
3612                    &git::Push,
3613                    "git push --set-upstream",
3614                    panel_focus_handle.clone(),
3615                    window,
3616                    cx,
3617                )
3618            },
3619        )
3620    }
3621
3622    fn render_relevant_button(
3623        &self,
3624        id: impl Into<SharedString>,
3625        branch: &Branch,
3626        cx: &mut App,
3627    ) -> Option<impl IntoElement> {
3628        if let Some(git_panel) = self.git_panel.as_ref() {
3629            if !git_panel.read(cx).can_push_and_pull(cx) {
3630                return None;
3631            }
3632        }
3633        let id = id.into();
3634        let upstream = branch.upstream.as_ref();
3635        Some(match upstream {
3636            Some(Upstream {
3637                tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3638                ..
3639            }) => match (*ahead, *behind) {
3640                (0, 0) => self.render_fetch_button(id, cx),
3641                (ahead, 0) => self.render_push_button(id, ahead, cx),
3642                (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3643            },
3644            Some(Upstream {
3645                tracking: UpstreamTracking::Gone,
3646                ..
3647            }) => self.render_republish_button(id, cx),
3648            None => self.render_publish_button(id, cx),
3649        })
3650    }
3651}
3652
3653impl RenderOnce for PanelRepoFooter {
3654    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3655        let active_repo = self.active_repository.clone();
3656        let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3657        let repo_selector_trigger = Button::new("repo-selector", active_repo)
3658            .style(ButtonStyle::Transparent)
3659            .size(ButtonSize::None)
3660            .label_size(LabelSize::Small)
3661            .color(Color::Muted);
3662
3663        let project = self
3664            .git_panel
3665            .as_ref()
3666            .map(|panel| panel.read(cx).project.clone());
3667
3668        let repo = self
3669            .git_panel
3670            .as_ref()
3671            .and_then(|panel| panel.read(cx).active_repository.clone());
3672
3673        let single_repo = project
3674            .as_ref()
3675            .map(|project| {
3676                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3677            })
3678            .unwrap_or(true);
3679
3680        let repo_selector = PopoverMenu::new("repository-switcher")
3681            .menu({
3682                let project = project.clone();
3683                move |window, cx| {
3684                    let project = project.clone()?;
3685                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3686                }
3687            })
3688            .trigger_with_tooltip(
3689                repo_selector_trigger.disabled(single_repo).truncate(true),
3690                Tooltip::text("Switch active repository"),
3691            )
3692            .attach(gpui::Corner::BottomLeft)
3693            .into_any_element();
3694
3695        let branch = self.branch.clone();
3696        let branch_name = branch
3697            .as_ref()
3698            .map_or(" (no branch)".into(), |branch| branch.name.clone());
3699
3700        let branch_selector_button = Button::new("branch-selector", branch_name)
3701            .style(ButtonStyle::Transparent)
3702            .size(ButtonSize::None)
3703            .label_size(LabelSize::Small)
3704            .truncate(true)
3705            .tooltip(Tooltip::for_action_title(
3706                "Switch Branch",
3707                &zed_actions::git::Branch,
3708            ))
3709            .on_click(|_, window, cx| {
3710                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3711            });
3712
3713        let branch_selector = PopoverMenu::new("popover-button")
3714            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3715            .trigger_with_tooltip(
3716                branch_selector_button,
3717                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3718            )
3719            .anchor(Corner::TopLeft)
3720            .offset(gpui::Point {
3721                x: px(0.0),
3722                y: px(-2.0),
3723            });
3724
3725        let spinner = self
3726            .git_panel
3727            .as_ref()
3728            .and_then(|git_panel| git_panel.read(cx).render_spinner());
3729
3730        h_flex()
3731            .w_full()
3732            .px_2()
3733            .h(px(36.))
3734            .items_center()
3735            .justify_between()
3736            .child(
3737                h_flex()
3738                    .flex_1()
3739                    .overflow_hidden()
3740                    .items_center()
3741                    .child(
3742                        div().child(
3743                            Icon::new(IconName::GitBranchSmall)
3744                                .size(IconSize::Small)
3745                                .color(Color::Muted),
3746                        ),
3747                    )
3748                    .child(repo_selector)
3749                    .when_some(branch.clone(), |this, _| {
3750                        this.child(
3751                            div()
3752                                .text_color(cx.theme().colors().text_muted)
3753                                .text_sm()
3754                                .child("/"),
3755                        )
3756                    })
3757                    .child(branch_selector),
3758            )
3759            .child(
3760                h_flex()
3761                    .gap_1()
3762                    .flex_shrink_0()
3763                    .children(spinner)
3764                    .child(self.render_overflow_menu(overflow_menu_id))
3765                    .when_some(branch, |this, branch| {
3766                        let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3767                        this.children(button)
3768                    }),
3769            )
3770    }
3771}
3772
3773impl ComponentPreview for PanelRepoFooter {
3774    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3775        let unknown_upstream = None;
3776        let no_remote_upstream = Some(UpstreamTracking::Gone);
3777        let ahead_of_upstream = Some(
3778            UpstreamTrackingStatus {
3779                ahead: 2,
3780                behind: 0,
3781            }
3782            .into(),
3783        );
3784        let behind_upstream = Some(
3785            UpstreamTrackingStatus {
3786                ahead: 0,
3787                behind: 2,
3788            }
3789            .into(),
3790        );
3791        let ahead_and_behind_upstream = Some(
3792            UpstreamTrackingStatus {
3793                ahead: 3,
3794                behind: 1,
3795            }
3796            .into(),
3797        );
3798
3799        let not_ahead_or_behind_upstream = Some(
3800            UpstreamTrackingStatus {
3801                ahead: 0,
3802                behind: 0,
3803            }
3804            .into(),
3805        );
3806
3807        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3808            Branch {
3809                is_head: true,
3810                name: "some-branch".into(),
3811                upstream: upstream.map(|tracking| Upstream {
3812                    ref_name: "origin/some-branch".into(),
3813                    tracking,
3814                }),
3815                most_recent_commit: Some(CommitSummary {
3816                    sha: "abc123".into(),
3817                    subject: "Modify stuff".into(),
3818                    commit_timestamp: 1710932954,
3819                    has_parent: true,
3820                }),
3821            }
3822        }
3823
3824        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3825            Branch {
3826                is_head: true,
3827                name: branch_name.to_string().into(),
3828                upstream: upstream.map(|tracking| Upstream {
3829                    ref_name: format!("zed/{}", branch_name).into(),
3830                    tracking,
3831                }),
3832                most_recent_commit: Some(CommitSummary {
3833                    sha: "abc123".into(),
3834                    subject: "Modify stuff".into(),
3835                    commit_timestamp: 1710932954,
3836                    has_parent: true,
3837                }),
3838            }
3839        }
3840
3841        fn active_repository(id: usize) -> SharedString {
3842            format!("repo-{}", id).into()
3843        }
3844
3845        let example_width = px(340.);
3846
3847        v_flex()
3848            .gap_6()
3849            .w_full()
3850            .flex_none()
3851            .children(vec![example_group_with_title(
3852                "Action Button States",
3853                vec![
3854                    single_example(
3855                        "No Branch",
3856                        div()
3857                            .w(example_width)
3858                            .overflow_hidden()
3859                            .child(PanelRepoFooter::new_preview(
3860                                "no-branch",
3861                                active_repository(1).clone(),
3862                                None,
3863                            ))
3864                            .into_any_element(),
3865                    )
3866                    .grow(),
3867                    single_example(
3868                        "Remote status unknown",
3869                        div()
3870                            .w(example_width)
3871                            .overflow_hidden()
3872                            .child(PanelRepoFooter::new_preview(
3873                                "unknown-upstream",
3874                                active_repository(2).clone(),
3875                                Some(branch(unknown_upstream)),
3876                            ))
3877                            .into_any_element(),
3878                    )
3879                    .grow(),
3880                    single_example(
3881                        "No Remote Upstream",
3882                        div()
3883                            .w(example_width)
3884                            .overflow_hidden()
3885                            .child(PanelRepoFooter::new_preview(
3886                                "no-remote-upstream",
3887                                active_repository(3).clone(),
3888                                Some(branch(no_remote_upstream)),
3889                            ))
3890                            .into_any_element(),
3891                    )
3892                    .grow(),
3893                    single_example(
3894                        "Not Ahead or Behind",
3895                        div()
3896                            .w(example_width)
3897                            .overflow_hidden()
3898                            .child(PanelRepoFooter::new_preview(
3899                                "not-ahead-or-behind",
3900                                active_repository(4).clone(),
3901                                Some(branch(not_ahead_or_behind_upstream)),
3902                            ))
3903                            .into_any_element(),
3904                    )
3905                    .grow(),
3906                    single_example(
3907                        "Behind remote",
3908                        div()
3909                            .w(example_width)
3910                            .overflow_hidden()
3911                            .child(PanelRepoFooter::new_preview(
3912                                "behind-remote",
3913                                active_repository(5).clone(),
3914                                Some(branch(behind_upstream)),
3915                            ))
3916                            .into_any_element(),
3917                    )
3918                    .grow(),
3919                    single_example(
3920                        "Ahead of remote",
3921                        div()
3922                            .w(example_width)
3923                            .overflow_hidden()
3924                            .child(PanelRepoFooter::new_preview(
3925                                "ahead-of-remote",
3926                                active_repository(6).clone(),
3927                                Some(branch(ahead_of_upstream)),
3928                            ))
3929                            .into_any_element(),
3930                    )
3931                    .grow(),
3932                    single_example(
3933                        "Ahead and behind remote",
3934                        div()
3935                            .w(example_width)
3936                            .overflow_hidden()
3937                            .child(PanelRepoFooter::new_preview(
3938                                "ahead-and-behind",
3939                                active_repository(7).clone(),
3940                                Some(branch(ahead_and_behind_upstream)),
3941                            ))
3942                            .into_any_element(),
3943                    )
3944                    .grow(),
3945                ],
3946            )
3947            .grow()
3948            .vertical()])
3949            .children(vec![example_group_with_title(
3950                "Labels",
3951                vec![
3952                    single_example(
3953                        "Short Branch & Repo",
3954                        div()
3955                            .w(example_width)
3956                            .overflow_hidden()
3957                            .child(PanelRepoFooter::new_preview(
3958                                "short-branch",
3959                                SharedString::from("zed"),
3960                                Some(custom("main", behind_upstream)),
3961                            ))
3962                            .into_any_element(),
3963                    )
3964                    .grow(),
3965                    single_example(
3966                        "Long Branch",
3967                        div()
3968                            .w(example_width)
3969                            .overflow_hidden()
3970                            .child(PanelRepoFooter::new_preview(
3971                                "long-branch",
3972                                SharedString::from("zed"),
3973                                Some(custom(
3974                                    "redesign-and-update-git-ui-list-entry-style",
3975                                    behind_upstream,
3976                                )),
3977                            ))
3978                            .into_any_element(),
3979                    )
3980                    .grow(),
3981                    single_example(
3982                        "Long Repo",
3983                        div()
3984                            .w(example_width)
3985                            .overflow_hidden()
3986                            .child(PanelRepoFooter::new_preview(
3987                                "long-repo",
3988                                SharedString::from("zed-industries-community-examples"),
3989                                Some(custom("gpui", ahead_of_upstream)),
3990                            ))
3991                            .into_any_element(),
3992                    )
3993                    .grow(),
3994                    single_example(
3995                        "Long Repo & Branch",
3996                        div()
3997                            .w(example_width)
3998                            .overflow_hidden()
3999                            .child(PanelRepoFooter::new_preview(
4000                                "long-repo-and-branch",
4001                                SharedString::from("zed-industries-community-examples"),
4002                                Some(custom(
4003                                    "redesign-and-update-git-ui-list-entry-style",
4004                                    behind_upstream,
4005                                )),
4006                            ))
4007                            .into_any_element(),
4008                    )
4009                    .grow(),
4010                    single_example(
4011                        "Uppercase Repo",
4012                        div()
4013                            .w(example_width)
4014                            .overflow_hidden()
4015                            .child(PanelRepoFooter::new_preview(
4016                                "uppercase-repo",
4017                                SharedString::from("LICENSES"),
4018                                Some(custom("main", ahead_of_upstream)),
4019                            ))
4020                            .into_any_element(),
4021                    )
4022                    .grow(),
4023                    single_example(
4024                        "Uppercase Branch",
4025                        div()
4026                            .w(example_width)
4027                            .overflow_hidden()
4028                            .child(PanelRepoFooter::new_preview(
4029                                "uppercase-branch",
4030                                SharedString::from("zed"),
4031                                Some(custom("update-README", behind_upstream)),
4032                            ))
4033                            .into_any_element(),
4034                    )
4035                    .grow(),
4036                ],
4037            )
4038            .grow()
4039            .vertical()])
4040            .into_any_element()
4041    }
4042}
4043
4044#[cfg(test)]
4045mod tests {
4046    use git::status::StatusCode;
4047    use gpui::TestAppContext;
4048    use project::{FakeFs, WorktreeSettings};
4049    use serde_json::json;
4050    use settings::SettingsStore;
4051    use theme::LoadThemes;
4052    use util::path;
4053
4054    use super::*;
4055
4056    fn init_test(cx: &mut gpui::TestAppContext) {
4057        if std::env::var("RUST_LOG").is_ok() {
4058            env_logger::try_init().ok();
4059        }
4060
4061        cx.update(|cx| {
4062            let settings_store = SettingsStore::test(cx);
4063            cx.set_global(settings_store);
4064            WorktreeSettings::register(cx);
4065            workspace::init_settings(cx);
4066            theme::init(LoadThemes::JustBase, cx);
4067            language::init(cx);
4068            editor::init(cx);
4069            Project::init_settings(cx);
4070            crate::init(cx);
4071        });
4072    }
4073
4074    #[gpui::test]
4075    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4076        init_test(cx);
4077        let fs = FakeFs::new(cx.background_executor.clone());
4078        fs.insert_tree(
4079            "/root",
4080            json!({
4081                "zed": {
4082                    ".git": {},
4083                    "crates": {
4084                        "gpui": {
4085                            "gpui.rs": "fn main() {}"
4086                        },
4087                        "util": {
4088                            "util.rs": "fn do_it() {}"
4089                        }
4090                    }
4091                },
4092            }),
4093        )
4094        .await;
4095
4096        fs.set_status_for_repo_via_git_operation(
4097            Path::new(path!("/root/zed/.git")),
4098            &[
4099                (
4100                    Path::new("crates/gpui/gpui.rs"),
4101                    StatusCode::Modified.worktree(),
4102                ),
4103                (
4104                    Path::new("crates/util/util.rs"),
4105                    StatusCode::Modified.worktree(),
4106                ),
4107            ],
4108        );
4109
4110        let project =
4111            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4112        let (workspace, cx) =
4113            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4114
4115        cx.read(|cx| {
4116            project
4117                .read(cx)
4118                .worktrees(cx)
4119                .nth(0)
4120                .unwrap()
4121                .read(cx)
4122                .as_local()
4123                .unwrap()
4124                .scan_complete()
4125        })
4126        .await;
4127
4128        cx.executor().run_until_parked();
4129
4130        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4131        let panel = cx.new_window_entity(|window, cx| {
4132            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4133        });
4134
4135        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4136            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4137        });
4138        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4139        handle.await;
4140
4141        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4142        pretty_assertions::assert_eq!(
4143            entries,
4144            [
4145                GitListEntry::Header(GitHeaderEntry {
4146                    header: Section::Tracked
4147                }),
4148                GitListEntry::GitStatusEntry(GitStatusEntry {
4149                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4150                    repo_path: "crates/gpui/gpui.rs".into(),
4151                    worktree_path: Path::new("gpui.rs").into(),
4152                    status: StatusCode::Modified.worktree(),
4153                    is_staged: Some(false),
4154                }),
4155                GitListEntry::GitStatusEntry(GitStatusEntry {
4156                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4157                    repo_path: "crates/util/util.rs".into(),
4158                    worktree_path: Path::new("../util/util.rs").into(),
4159                    status: StatusCode::Modified.worktree(),
4160                    is_staged: Some(false),
4161                },),
4162            ],
4163        );
4164
4165        cx.update_window_entity(&panel, |panel, window, cx| {
4166            panel.select_last(&Default::default(), window, cx);
4167            assert_eq!(panel.selected_entry, Some(2));
4168            panel.open_diff(&Default::default(), window, cx);
4169        });
4170        cx.run_until_parked();
4171
4172        let worktree_roots = workspace.update(cx, |workspace, cx| {
4173            workspace
4174                .worktrees(cx)
4175                .map(|worktree| worktree.read(cx).abs_path())
4176                .collect::<Vec<_>>()
4177        });
4178        pretty_assertions::assert_eq!(
4179            worktree_roots,
4180            vec![
4181                Path::new(path!("/root/zed/crates/gpui")).into(),
4182                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4183            ]
4184        );
4185
4186        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4187            let git_store = project.git_store().read(cx);
4188            // The repo that comes from the single-file worktree can't be selected through the UI.
4189            let filtered_entries = filtered_repository_entries(git_store, cx)
4190                .iter()
4191                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4192                .collect::<Vec<_>>();
4193            assert_eq!(
4194                filtered_entries,
4195                [Path::new(path!("/root/zed/crates/gpui")).into()]
4196            );
4197            // But we can select it artificially here.
4198            git_store
4199                .all_repositories()
4200                .into_iter()
4201                .find(|repo| {
4202                    &*repo.read(cx).worktree_abs_path
4203                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4204                })
4205                .unwrap()
4206        });
4207
4208        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4209        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4210        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4211            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4212        });
4213        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4214        handle.await;
4215        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4216        pretty_assertions::assert_eq!(
4217            entries,
4218            [
4219                GitListEntry::Header(GitHeaderEntry {
4220                    header: Section::Tracked
4221                }),
4222                GitListEntry::GitStatusEntry(GitStatusEntry {
4223                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4224                    repo_path: "crates/gpui/gpui.rs".into(),
4225                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4226                    status: StatusCode::Modified.worktree(),
4227                    is_staged: Some(false),
4228                }),
4229                GitListEntry::GitStatusEntry(GitStatusEntry {
4230                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4231                    repo_path: "crates/util/util.rs".into(),
4232                    worktree_path: Path::new("util.rs").into(),
4233                    status: StatusCode::Modified.worktree(),
4234                    is_staged: Some(false),
4235                },),
4236            ],
4237        );
4238    }
4239}