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                .child(
2497                    panel_icon_button("undo", IconName::Undo)
2498                        .icon_size(IconSize::Small)
2499                        .icon_color(Color::Muted)
2500                        .tooltip(Tooltip::for_action_title(
2501                            if self.has_staged_changes() {
2502                                "git reset HEAD^ --soft"
2503                            } else {
2504                                "git reset HEAD^"
2505                            },
2506                            &git::Uncommit,
2507                        ))
2508                        .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2509                ),
2510        )
2511    }
2512
2513    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2514        h_flex()
2515            .h_full()
2516            .flex_grow()
2517            .justify_center()
2518            .items_center()
2519            .child(
2520                v_flex()
2521                    .gap_3()
2522                    .child(if self.active_repository.is_some() {
2523                        "No changes to commit"
2524                    } else {
2525                        "No Git repositories"
2526                    })
2527                    .text_ui_sm(cx)
2528                    .mx_auto()
2529                    .text_color(Color::Placeholder.color(cx)),
2530            )
2531    }
2532
2533    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2534        let scroll_bar_style = self.show_scrollbar(cx);
2535        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2536
2537        if !self.should_show_scrollbar(cx)
2538            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2539        {
2540            return None;
2541        }
2542
2543        Some(
2544            div()
2545                .id("git-panel-vertical-scroll")
2546                .occlude()
2547                .flex_none()
2548                .h_full()
2549                .cursor_default()
2550                .when(show_container, |this| this.pl_1().px_1p5())
2551                .when(!show_container, |this| {
2552                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
2553                })
2554                .on_mouse_move(cx.listener(|_, _, _, cx| {
2555                    cx.notify();
2556                    cx.stop_propagation()
2557                }))
2558                .on_hover(|_, _, cx| {
2559                    cx.stop_propagation();
2560                })
2561                .on_any_mouse_down(|_, _, cx| {
2562                    cx.stop_propagation();
2563                })
2564                .on_mouse_up(
2565                    MouseButton::Left,
2566                    cx.listener(|this, _, window, cx| {
2567                        if !this.scrollbar_state.is_dragging()
2568                            && !this.focus_handle.contains_focused(window, cx)
2569                        {
2570                            this.hide_scrollbar(window, cx);
2571                            cx.notify();
2572                        }
2573
2574                        cx.stop_propagation();
2575                    }),
2576                )
2577                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2578                    cx.notify();
2579                }))
2580                .children(Scrollbar::vertical(
2581                    // percentage as f32..end_offset as f32,
2582                    self.scrollbar_state.clone(),
2583                )),
2584        )
2585    }
2586
2587    fn render_buffer_header_controls(
2588        &self,
2589        entity: &Entity<Self>,
2590        file: &Arc<dyn File>,
2591        _: &Window,
2592        cx: &App,
2593    ) -> Option<AnyElement> {
2594        let repo = self.active_repository.as_ref()?.read(cx);
2595        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2596        let ix = self.entry_by_path(&repo_path)?;
2597        let entry = self.entries.get(ix)?;
2598
2599        let is_staged = self.entry_is_staged(entry.status_entry()?);
2600
2601        let checkbox = Checkbox::new("stage-file", is_staged.into())
2602            .disabled(!self.has_write_access(cx))
2603            .fill()
2604            .elevation(ElevationIndex::Surface)
2605            .on_click({
2606                let entry = entry.clone();
2607                let git_panel = entity.downgrade();
2608                move |_, window, cx| {
2609                    git_panel
2610                        .update(cx, |this, cx| {
2611                            this.toggle_staged_for_entry(&entry, window, cx);
2612                            cx.stop_propagation();
2613                        })
2614                        .ok();
2615                }
2616            });
2617        Some(
2618            h_flex()
2619                .id("start-slot")
2620                .text_lg()
2621                .child(checkbox)
2622                .on_mouse_down(MouseButton::Left, |_, _, cx| {
2623                    // prevent the list item active state triggering when toggling checkbox
2624                    cx.stop_propagation();
2625                })
2626                .into_any_element(),
2627        )
2628    }
2629
2630    fn render_entries(
2631        &self,
2632        has_write_access: bool,
2633        _: &Window,
2634        cx: &mut Context<Self>,
2635    ) -> impl IntoElement {
2636        let entry_count = self.entries.len();
2637
2638        h_flex()
2639            .size_full()
2640            .flex_grow()
2641            .overflow_hidden()
2642            .child(
2643                uniform_list(cx.entity().clone(), "entries", entry_count, {
2644                    move |this, range, window, cx| {
2645                        let mut items = Vec::with_capacity(range.end - range.start);
2646
2647                        for ix in range {
2648                            match &this.entries.get(ix) {
2649                                Some(GitListEntry::GitStatusEntry(entry)) => {
2650                                    items.push(this.render_entry(
2651                                        ix,
2652                                        entry,
2653                                        has_write_access,
2654                                        window,
2655                                        cx,
2656                                    ));
2657                                }
2658                                Some(GitListEntry::Header(header)) => {
2659                                    items.push(this.render_list_header(
2660                                        ix,
2661                                        header,
2662                                        has_write_access,
2663                                        window,
2664                                        cx,
2665                                    ));
2666                                }
2667                                None => {}
2668                            }
2669                        }
2670
2671                        items
2672                    }
2673                })
2674                .size_full()
2675                .with_sizing_behavior(ListSizingBehavior::Auto)
2676                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2677                .track_scroll(self.scroll_handle.clone()),
2678            )
2679            .on_mouse_down(
2680                MouseButton::Right,
2681                cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2682                    this.deploy_panel_context_menu(event.position, window, cx)
2683                }),
2684            )
2685            .children(self.render_scrollbar(cx))
2686    }
2687
2688    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2689        Label::new(label.into()).color(color).single_line()
2690    }
2691
2692    fn list_item_height(&self) -> Rems {
2693        rems(1.75)
2694    }
2695
2696    fn render_list_header(
2697        &self,
2698        ix: usize,
2699        header: &GitHeaderEntry,
2700        _: bool,
2701        _: &Window,
2702        _: &Context<Self>,
2703    ) -> AnyElement {
2704        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2705
2706        h_flex()
2707            .id(id)
2708            .h(self.list_item_height())
2709            .w_full()
2710            .items_end()
2711            .px(rems(0.75)) // ~12px
2712            .pb(rems(0.3125)) // ~ 5px
2713            .child(
2714                Label::new(header.title())
2715                    .color(Color::Muted)
2716                    .size(LabelSize::Small)
2717                    .line_height_style(LineHeightStyle::UiLabel)
2718                    .single_line(),
2719            )
2720            .into_any_element()
2721    }
2722
2723    fn load_commit_details(
2724        &self,
2725        sha: &str,
2726        cx: &mut Context<Self>,
2727    ) -> Task<anyhow::Result<CommitDetails>> {
2728        let Some(repo) = self.active_repository.clone() else {
2729            return Task::ready(Err(anyhow::anyhow!("no active repo")));
2730        };
2731        repo.update(cx, |repo, cx| {
2732            let show = repo.show(sha);
2733            cx.spawn(|_, _| async move { show.await? })
2734        })
2735    }
2736
2737    fn deploy_entry_context_menu(
2738        &mut self,
2739        position: Point<Pixels>,
2740        ix: usize,
2741        window: &mut Window,
2742        cx: &mut Context<Self>,
2743    ) {
2744        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2745            return;
2746        };
2747        let stage_title = if entry.status.is_staged() == Some(true) {
2748            "Unstage File"
2749        } else {
2750            "Stage File"
2751        };
2752        let restore_title = if entry.status.is_created() {
2753            "Trash File"
2754        } else {
2755            "Restore File"
2756        };
2757        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2758            context_menu
2759                .action(stage_title, ToggleStaged.boxed_clone())
2760                .action(restore_title, git::RestoreFile.boxed_clone())
2761                .separator()
2762                .action("Open Diff", Confirm.boxed_clone())
2763                .action("Open File", SecondaryConfirm.boxed_clone())
2764        });
2765        self.selected_entry = Some(ix);
2766        self.set_context_menu(context_menu, position, window, cx);
2767    }
2768
2769    fn deploy_panel_context_menu(
2770        &mut self,
2771        position: Point<Pixels>,
2772        window: &mut Window,
2773        cx: &mut Context<Self>,
2774    ) {
2775        let context_menu = git_panel_context_menu(window, cx);
2776        self.set_context_menu(context_menu, position, window, cx);
2777    }
2778
2779    fn set_context_menu(
2780        &mut self,
2781        context_menu: Entity<ContextMenu>,
2782        position: Point<Pixels>,
2783        window: &Window,
2784        cx: &mut Context<Self>,
2785    ) {
2786        let subscription = cx.subscribe_in(
2787            &context_menu,
2788            window,
2789            |this, _, _: &DismissEvent, window, cx| {
2790                if this.context_menu.as_ref().is_some_and(|context_menu| {
2791                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
2792                }) {
2793                    cx.focus_self(window);
2794                }
2795                this.context_menu.take();
2796                cx.notify();
2797            },
2798        );
2799        self.context_menu = Some((context_menu, position, subscription));
2800        cx.notify();
2801    }
2802
2803    fn render_entry(
2804        &self,
2805        ix: usize,
2806        entry: &GitStatusEntry,
2807        has_write_access: bool,
2808        window: &Window,
2809        cx: &Context<Self>,
2810    ) -> AnyElement {
2811        let display_name = entry
2812            .worktree_path
2813            .file_name()
2814            .map(|name| name.to_string_lossy().into_owned())
2815            .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2816
2817        let worktree_path = entry.worktree_path.clone();
2818        let selected = self.selected_entry == Some(ix);
2819        let marked = self.marked_entries.contains(&ix);
2820        let status_style = GitPanelSettings::get_global(cx).status_style;
2821        let status = entry.status;
2822        let has_conflict = status.is_conflicted();
2823        let is_modified = status.is_modified();
2824        let is_deleted = status.is_deleted();
2825
2826        let label_color = if status_style == StatusStyle::LabelColor {
2827            if has_conflict {
2828                Color::Conflict
2829            } else if is_modified {
2830                Color::Modified
2831            } else if is_deleted {
2832                // We don't want a bunch of red labels in the list
2833                Color::Disabled
2834            } else {
2835                Color::Created
2836            }
2837        } else {
2838            Color::Default
2839        };
2840
2841        let path_color = if status.is_deleted() {
2842            Color::Disabled
2843        } else {
2844            Color::Muted
2845        };
2846
2847        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2848        let checkbox_wrapper_id: ElementId =
2849            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2850        let checkbox_id: ElementId =
2851            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2852
2853        let is_entry_staged = self.entry_is_staged(entry);
2854        let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2855
2856        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2857            is_staged = ToggleState::Selected;
2858        }
2859
2860        let handle = cx.weak_entity();
2861
2862        let selected_bg_alpha = 0.08;
2863        let marked_bg_alpha = 0.12;
2864        let state_opacity_step = 0.04;
2865
2866        let base_bg = match (selected, marked) {
2867            (true, true) => cx
2868                .theme()
2869                .status()
2870                .info
2871                .alpha(selected_bg_alpha + marked_bg_alpha),
2872            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2873            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2874            _ => cx.theme().colors().ghost_element_background,
2875        };
2876
2877        let hover_bg = if selected {
2878            cx.theme()
2879                .status()
2880                .info
2881                .alpha(selected_bg_alpha + state_opacity_step)
2882        } else {
2883            cx.theme().colors().ghost_element_hover
2884        };
2885
2886        let active_bg = if selected {
2887            cx.theme()
2888                .status()
2889                .info
2890                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2891        } else {
2892            cx.theme().colors().ghost_element_active
2893        };
2894
2895        h_flex()
2896            .id(id)
2897            .h(self.list_item_height())
2898            .w_full()
2899            .items_center()
2900            .border_1()
2901            .when(selected && self.focus_handle.is_focused(window), |el| {
2902                el.border_color(cx.theme().colors().border_focused)
2903            })
2904            .px(rems(0.75)) // ~12px
2905            .overflow_hidden()
2906            .flex_none()
2907            .gap(DynamicSpacing::Base04.rems(cx))
2908            .bg(base_bg)
2909            .hover(|this| this.bg(hover_bg))
2910            .active(|this| this.bg(active_bg))
2911            .on_click({
2912                cx.listener(move |this, event: &ClickEvent, window, cx| {
2913                    this.selected_entry = Some(ix);
2914                    cx.notify();
2915                    if event.modifiers().secondary() {
2916                        this.open_file(&Default::default(), window, cx)
2917                    } else {
2918                        this.open_diff(&Default::default(), window, cx);
2919                        this.focus_handle.focus(window);
2920                    }
2921                })
2922            })
2923            .on_mouse_down(
2924                MouseButton::Right,
2925                move |event: &MouseDownEvent, window, cx| {
2926                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2927                    if event.button != MouseButton::Right {
2928                        return;
2929                    }
2930
2931                    let Some(this) = handle.upgrade() else {
2932                        return;
2933                    };
2934                    this.update(cx, |this, cx| {
2935                        this.deploy_entry_context_menu(event.position, ix, window, cx);
2936                    });
2937                    cx.stop_propagation();
2938                },
2939            )
2940            // .on_secondary_mouse_down(cx.listener(
2941            //     move |this, event: &MouseDownEvent, window, cx| {
2942            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
2943            //         cx.stop_propagation();
2944            //     },
2945            // ))
2946            .child(
2947                div()
2948                    .id(checkbox_wrapper_id)
2949                    .flex_none()
2950                    .occlude()
2951                    .cursor_pointer()
2952                    .child(
2953                        Checkbox::new(checkbox_id, is_staged)
2954                            .disabled(!has_write_access)
2955                            .fill()
2956                            .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2957                            .elevation(ElevationIndex::Surface)
2958                            .on_click({
2959                                let entry = entry.clone();
2960                                cx.listener(move |this, _, window, cx| {
2961                                    if !has_write_access {
2962                                        return;
2963                                    }
2964                                    this.toggle_staged_for_entry(
2965                                        &GitListEntry::GitStatusEntry(entry.clone()),
2966                                        window,
2967                                        cx,
2968                                    );
2969                                    cx.stop_propagation();
2970                                })
2971                            })
2972                            .tooltip(move |window, cx| {
2973                                let tooltip_name = if is_entry_staged.unwrap_or(false) {
2974                                    "Unstage"
2975                                } else {
2976                                    "Stage"
2977                                };
2978
2979                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2980                            }),
2981                    ),
2982            )
2983            .child(git_status_icon(status, cx))
2984            .child(
2985                h_flex()
2986                    .items_center()
2987                    .overflow_hidden()
2988                    .when_some(worktree_path.parent(), |this, parent| {
2989                        let parent_str = parent.to_string_lossy();
2990                        if !parent_str.is_empty() {
2991                            this.child(
2992                                self.entry_label(format!("{}/", parent_str), path_color)
2993                                    .when(status.is_deleted(), |this| this.strikethrough()),
2994                            )
2995                        } else {
2996                            this
2997                        }
2998                    })
2999                    .child(
3000                        self.entry_label(display_name.clone(), label_color)
3001                            .when(status.is_deleted(), |this| this.strikethrough()),
3002                    ),
3003            )
3004            .into_any_element()
3005    }
3006
3007    fn has_write_access(&self, cx: &App) -> bool {
3008        !self.project.read(cx).is_read_only(cx)
3009    }
3010}
3011
3012fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3013    let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3014    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3015    provider.is_authenticated(cx).then(|| model)
3016}
3017
3018impl Render for GitPanel {
3019    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3020        let project = self.project.read(cx);
3021        let has_entries = self.entries.len() > 0;
3022        let room = self
3023            .workspace
3024            .upgrade()
3025            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3026
3027        let has_write_access = self.has_write_access(cx);
3028
3029        let has_co_authors = room.map_or(false, |room| {
3030            room.read(cx)
3031                .remote_participants()
3032                .values()
3033                .any(|remote_participant| remote_participant.can_write())
3034        });
3035
3036        v_flex()
3037            .id("git_panel")
3038            .key_context(self.dispatch_context(window, cx))
3039            .track_focus(&self.focus_handle)
3040            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3041            .when(has_write_access && !project.is_read_only(cx), |this| {
3042                this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
3043                    this.toggle_staged_for_selected(&ToggleStaged, window, cx)
3044                }))
3045                .on_action(cx.listener(GitPanel::commit))
3046            })
3047            .on_action(cx.listener(Self::select_first))
3048            .on_action(cx.listener(Self::select_next))
3049            .on_action(cx.listener(Self::select_previous))
3050            .on_action(cx.listener(Self::select_last))
3051            .on_action(cx.listener(Self::close_panel))
3052            .on_action(cx.listener(Self::open_diff))
3053            .on_action(cx.listener(Self::open_file))
3054            .on_action(cx.listener(Self::revert_selected))
3055            .on_action(cx.listener(Self::focus_changes_list))
3056            .on_action(cx.listener(Self::focus_editor))
3057            .on_action(cx.listener(Self::toggle_staged_for_selected))
3058            .on_action(cx.listener(Self::stage_all))
3059            .on_action(cx.listener(Self::unstage_all))
3060            .on_action(cx.listener(Self::restore_tracked_files))
3061            .on_action(cx.listener(Self::clean_all))
3062            .on_action(cx.listener(Self::expand_commit_editor))
3063            .on_action(cx.listener(Self::generate_commit_message_action))
3064            .when(has_write_access && has_co_authors, |git_panel| {
3065                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3066            })
3067            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3068            .on_hover(cx.listener(|this, hovered, window, cx| {
3069                if *hovered {
3070                    this.show_scrollbar = true;
3071                    this.hide_scrollbar_task.take();
3072                    cx.notify();
3073                } else if !this.focus_handle.contains_focused(window, cx) {
3074                    this.hide_scrollbar(window, cx);
3075                }
3076            }))
3077            .size_full()
3078            .overflow_hidden()
3079            .bg(ElevationIndex::Surface.bg(cx))
3080            .child(
3081                v_flex()
3082                    .size_full()
3083                    .map(|this| {
3084                        if has_entries {
3085                            this.child(self.render_entries(has_write_access, window, cx))
3086                        } else {
3087                            this.child(self.render_empty_state(cx).into_any_element())
3088                        }
3089                    })
3090                    .children(self.render_footer(window, cx))
3091                    .children(self.render_previous_commit(cx))
3092                    .into_any_element(),
3093            )
3094            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3095                deferred(
3096                    anchored()
3097                        .position(*position)
3098                        .anchor(gpui::Corner::TopLeft)
3099                        .child(menu.clone()),
3100                )
3101                .with_priority(1)
3102            }))
3103    }
3104}
3105
3106impl Focusable for GitPanel {
3107    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3108        self.focus_handle.clone()
3109    }
3110}
3111
3112impl EventEmitter<Event> for GitPanel {}
3113
3114impl EventEmitter<PanelEvent> for GitPanel {}
3115
3116pub(crate) struct GitPanelAddon {
3117    pub(crate) workspace: WeakEntity<Workspace>,
3118}
3119
3120impl editor::Addon for GitPanelAddon {
3121    fn to_any(&self) -> &dyn std::any::Any {
3122        self
3123    }
3124
3125    fn render_buffer_header_controls(
3126        &self,
3127        excerpt_info: &ExcerptInfo,
3128        window: &Window,
3129        cx: &App,
3130    ) -> Option<AnyElement> {
3131        let file = excerpt_info.buffer.file()?;
3132        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3133
3134        git_panel
3135            .read(cx)
3136            .render_buffer_header_controls(&git_panel, &file, window, cx)
3137    }
3138}
3139
3140impl Panel for GitPanel {
3141    fn persistent_name() -> &'static str {
3142        "GitPanel"
3143    }
3144
3145    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3146        GitPanelSettings::get_global(cx).dock
3147    }
3148
3149    fn position_is_valid(&self, position: DockPosition) -> bool {
3150        matches!(position, DockPosition::Left | DockPosition::Right)
3151    }
3152
3153    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3154        settings::update_settings_file::<GitPanelSettings>(
3155            self.fs.clone(),
3156            cx,
3157            move |settings, _| settings.dock = Some(position),
3158        );
3159    }
3160
3161    fn size(&self, _: &Window, cx: &App) -> Pixels {
3162        self.width
3163            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3164    }
3165
3166    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3167        self.width = size;
3168        self.serialize(cx);
3169        cx.notify();
3170    }
3171
3172    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3173        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3174    }
3175
3176    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3177        Some("Git Panel")
3178    }
3179
3180    fn toggle_action(&self) -> Box<dyn Action> {
3181        Box::new(ToggleFocus)
3182    }
3183
3184    fn activation_priority(&self) -> u32 {
3185        2
3186    }
3187}
3188
3189impl PanelHeader for GitPanel {}
3190
3191struct GitPanelMessageTooltip {
3192    commit_tooltip: Option<Entity<CommitTooltip>>,
3193}
3194
3195impl GitPanelMessageTooltip {
3196    fn new(
3197        git_panel: Entity<GitPanel>,
3198        sha: SharedString,
3199        window: &mut Window,
3200        cx: &mut App,
3201    ) -> Entity<Self> {
3202        cx.new(|cx| {
3203            cx.spawn_in(window, |this, mut cx| async move {
3204                let details = git_panel
3205                    .update(&mut cx, |git_panel, cx| {
3206                        git_panel.load_commit_details(&sha, cx)
3207                    })?
3208                    .await?;
3209
3210                let commit_details = editor::commit_tooltip::CommitDetails {
3211                    sha: details.sha.clone(),
3212                    committer_name: details.committer_name.clone(),
3213                    committer_email: details.committer_email.clone(),
3214                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3215                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3216                        message: details.message.clone(),
3217                        ..Default::default()
3218                    }),
3219                };
3220
3221                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3222                    this.commit_tooltip =
3223                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3224                    cx.notify();
3225                })
3226            })
3227            .detach();
3228
3229            Self {
3230                commit_tooltip: None,
3231            }
3232        })
3233    }
3234}
3235
3236impl Render for GitPanelMessageTooltip {
3237    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3238        if let Some(commit_tooltip) = &self.commit_tooltip {
3239            commit_tooltip.clone().into_any_element()
3240        } else {
3241            gpui::Empty.into_any_element()
3242        }
3243    }
3244}
3245
3246fn git_action_tooltip(
3247    label: impl Into<SharedString>,
3248    action: &dyn Action,
3249    command: impl Into<SharedString>,
3250    focus_handle: Option<FocusHandle>,
3251    window: &mut Window,
3252    cx: &mut App,
3253) -> AnyView {
3254    let label = label.into();
3255    let command = command.into();
3256
3257    if let Some(handle) = focus_handle {
3258        Tooltip::with_meta_in(
3259            label.clone(),
3260            Some(action),
3261            command.clone(),
3262            &handle,
3263            window,
3264            cx,
3265        )
3266    } else {
3267        Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
3268    }
3269}
3270
3271#[derive(IntoElement)]
3272struct SplitButton {
3273    pub left: ButtonLike,
3274    pub right: AnyElement,
3275}
3276
3277impl SplitButton {
3278    fn new(
3279        id: impl Into<SharedString>,
3280        left_label: impl Into<SharedString>,
3281        ahead_count: usize,
3282        behind_count: usize,
3283        left_icon: Option<IconName>,
3284        left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
3285        tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
3286    ) -> Self {
3287        let id = id.into();
3288
3289        fn count(count: usize) -> impl IntoElement {
3290            h_flex()
3291                .ml_neg_px()
3292                .h(rems(0.875))
3293                .items_center()
3294                .overflow_hidden()
3295                .px_0p5()
3296                .child(
3297                    Label::new(count.to_string())
3298                        .size(LabelSize::XSmall)
3299                        .line_height_style(LineHeightStyle::UiLabel),
3300                )
3301        }
3302
3303        let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
3304
3305        let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
3306            format!("split-button-left-{}", id).into(),
3307        ))
3308        .layer(ui::ElevationIndex::ModalSurface)
3309        .size(ui::ButtonSize::Compact)
3310        .when(should_render_counts, |this| {
3311            this.child(
3312                h_flex()
3313                    .ml_neg_0p5()
3314                    .mr_1()
3315                    .when(behind_count > 0, |this| {
3316                        this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
3317                            .child(count(behind_count))
3318                    })
3319                    .when(ahead_count > 0, |this| {
3320                        this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
3321                            .child(count(ahead_count))
3322                    }),
3323            )
3324        })
3325        .when_some(left_icon, |this, left_icon| {
3326            this.child(
3327                h_flex()
3328                    .ml_neg_0p5()
3329                    .mr_1()
3330                    .child(Icon::new(left_icon).size(IconSize::XSmall)),
3331            )
3332        })
3333        .child(
3334            div()
3335                .child(Label::new(left_label).size(LabelSize::Small))
3336                .mr_0p5(),
3337        )
3338        .on_click(left_on_click)
3339        .tooltip(tooltip);
3340
3341        let right =
3342            render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
3343                .into_any_element();
3344        // .on_click(right_on_click);
3345
3346        Self { left, right }
3347    }
3348}
3349
3350impl RenderOnce for SplitButton {
3351    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3352        h_flex()
3353            .rounded_md()
3354            .border_1()
3355            .border_color(cx.theme().colors().text_muted.alpha(0.12))
3356            .child(self.left)
3357            .child(
3358                div()
3359                    .h_full()
3360                    .w_px()
3361                    .bg(cx.theme().colors().text_muted.alpha(0.16)),
3362            )
3363            .child(self.right)
3364            .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3365            .shadow(smallvec![BoxShadow {
3366                color: hsla(0.0, 0.0, 0.0, 0.16),
3367                offset: point(px(0.), px(1.)),
3368                blur_radius: px(0.),
3369                spread_radius: px(0.),
3370            }])
3371    }
3372}
3373
3374fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3375    PopoverMenu::new(id.into())
3376        .trigger(
3377            ui::ButtonLike::new_rounded_right("split-button-right")
3378                .layer(ui::ElevationIndex::ModalSurface)
3379                .size(ui::ButtonSize::None)
3380                .child(
3381                    div()
3382                        .px_1()
3383                        .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3384                ),
3385        )
3386        .menu(move |window, cx| {
3387            Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3388                context_menu
3389                    .action("Fetch", git::Fetch.boxed_clone())
3390                    .action("Pull", git::Pull.boxed_clone())
3391                    .separator()
3392                    .action("Push", git::Push.boxed_clone())
3393                    .action("Force Push", git::ForcePush.boxed_clone())
3394            }))
3395        })
3396        .anchor(Corner::TopRight)
3397}
3398
3399#[derive(IntoElement, IntoComponent)]
3400#[component(scope = "Version Control")]
3401pub struct PanelRepoFooter {
3402    id: SharedString,
3403    active_repository: SharedString,
3404    branch: Option<Branch>,
3405    // Getting a GitPanel in previews will be difficult.
3406    //
3407    // For now just take an option here, and we won't bind handlers to buttons in previews.
3408    git_panel: Option<Entity<GitPanel>>,
3409}
3410
3411impl PanelRepoFooter {
3412    pub fn new(
3413        id: impl Into<SharedString>,
3414        active_repository: SharedString,
3415        branch: Option<Branch>,
3416        git_panel: Option<Entity<GitPanel>>,
3417    ) -> Self {
3418        Self {
3419            id: id.into(),
3420            active_repository,
3421            branch,
3422            git_panel,
3423        }
3424    }
3425
3426    pub fn new_preview(
3427        id: impl Into<SharedString>,
3428        active_repository: SharedString,
3429        branch: Option<Branch>,
3430    ) -> Self {
3431        Self {
3432            id: id.into(),
3433            active_repository,
3434            branch,
3435            git_panel: None,
3436        }
3437    }
3438
3439    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3440        PopoverMenu::new(id.into())
3441            .trigger(
3442                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3443                    .icon_size(IconSize::Small)
3444                    .icon_color(Color::Muted),
3445            )
3446            .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3447            .anchor(Corner::TopRight)
3448    }
3449
3450    fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3451        if let Some(git_panel) = self.git_panel.clone() {
3452            Some(git_panel.focus_handle(cx))
3453        } else {
3454            None
3455        }
3456    }
3457
3458    fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3459        let panel = self.git_panel.clone();
3460        let panel_focus_handle = self.panel_focus_handle(cx);
3461
3462        SplitButton::new(
3463            id,
3464            "Push",
3465            ahead as usize,
3466            0,
3467            None,
3468            move |_, window, cx| {
3469                if let Some(panel) = panel.as_ref() {
3470                    panel.update(cx, |panel, cx| {
3471                        panel.push(false, window, cx);
3472                    });
3473                }
3474            },
3475            move |window, cx| {
3476                git_action_tooltip(
3477                    "Push committed changes to remote",
3478                    &git::Push,
3479                    "git push",
3480                    panel_focus_handle.clone(),
3481                    window,
3482                    cx,
3483                )
3484            },
3485        )
3486    }
3487
3488    fn render_pull_button(
3489        &self,
3490        id: SharedString,
3491        ahead: u32,
3492        behind: u32,
3493        cx: &mut App,
3494    ) -> SplitButton {
3495        let panel = self.git_panel.clone();
3496        let panel_focus_handle = self.panel_focus_handle(cx);
3497
3498        SplitButton::new(
3499            id,
3500            "Pull",
3501            ahead as usize,
3502            behind as usize,
3503            None,
3504            move |_, window, cx| {
3505                if let Some(panel) = panel.as_ref() {
3506                    panel.update(cx, |panel, cx| {
3507                        panel.pull(window, cx);
3508                    });
3509                }
3510            },
3511            move |window, cx| {
3512                git_action_tooltip(
3513                    "Pull",
3514                    &git::Pull,
3515                    "git pull",
3516                    panel_focus_handle.clone(),
3517                    window,
3518                    cx,
3519                )
3520            },
3521        )
3522    }
3523
3524    fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3525        let panel = self.git_panel.clone();
3526        let panel_focus_handle = self.panel_focus_handle(cx);
3527
3528        SplitButton::new(
3529            id,
3530            "Fetch",
3531            0,
3532            0,
3533            Some(IconName::ArrowCircle),
3534            move |_, window, cx| {
3535                if let Some(panel) = panel.as_ref() {
3536                    panel.update(cx, |panel, cx| {
3537                        panel.fetch(window, cx);
3538                    });
3539                }
3540            },
3541            move |window, cx| {
3542                git_action_tooltip(
3543                    "Fetch updates from remote",
3544                    &git::Fetch,
3545                    "git fetch",
3546                    panel_focus_handle.clone(),
3547                    window,
3548                    cx,
3549                )
3550            },
3551        )
3552    }
3553
3554    fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3555        let panel = self.git_panel.clone();
3556        let panel_focus_handle = self.panel_focus_handle(cx);
3557
3558        SplitButton::new(
3559            id,
3560            "Publish",
3561            0,
3562            0,
3563            Some(IconName::ArrowUpFromLine),
3564            move |_, window, cx| {
3565                if let Some(panel) = panel.as_ref() {
3566                    panel.update(cx, |panel, cx| {
3567                        panel.push(false, window, cx);
3568                    });
3569                }
3570            },
3571            move |window, cx| {
3572                git_action_tooltip(
3573                    "Publish branch to remote",
3574                    &git::Push,
3575                    "git push --set-upstream",
3576                    panel_focus_handle.clone(),
3577                    window,
3578                    cx,
3579                )
3580            },
3581        )
3582    }
3583
3584    fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3585        let panel = self.git_panel.clone();
3586        let panel_focus_handle = self.panel_focus_handle(cx);
3587
3588        SplitButton::new(
3589            id,
3590            "Republish",
3591            0,
3592            0,
3593            Some(IconName::ArrowUpFromLine),
3594            move |_, window, cx| {
3595                if let Some(panel) = panel.as_ref() {
3596                    panel.update(cx, |panel, cx| {
3597                        panel.push(false, window, cx);
3598                    });
3599                }
3600            },
3601            move |window, cx| {
3602                git_action_tooltip(
3603                    "Re-publish branch to remote",
3604                    &git::Push,
3605                    "git push --set-upstream",
3606                    panel_focus_handle.clone(),
3607                    window,
3608                    cx,
3609                )
3610            },
3611        )
3612    }
3613
3614    fn render_relevant_button(
3615        &self,
3616        id: impl Into<SharedString>,
3617        branch: &Branch,
3618        cx: &mut App,
3619    ) -> Option<impl IntoElement> {
3620        if let Some(git_panel) = self.git_panel.as_ref() {
3621            if !git_panel.read(cx).can_push_and_pull(cx) {
3622                return None;
3623            }
3624        }
3625        let id = id.into();
3626        let upstream = branch.upstream.as_ref();
3627        Some(match upstream {
3628            Some(Upstream {
3629                tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3630                ..
3631            }) => match (*ahead, *behind) {
3632                (0, 0) => self.render_fetch_button(id, cx),
3633                (ahead, 0) => self.render_push_button(id, ahead, cx),
3634                (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3635            },
3636            Some(Upstream {
3637                tracking: UpstreamTracking::Gone,
3638                ..
3639            }) => self.render_republish_button(id, cx),
3640            None => self.render_publish_button(id, cx),
3641        })
3642    }
3643}
3644
3645impl RenderOnce for PanelRepoFooter {
3646    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3647        let active_repo = self.active_repository.clone();
3648        let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3649        let repo_selector_trigger = Button::new("repo-selector", active_repo)
3650            .style(ButtonStyle::Transparent)
3651            .size(ButtonSize::None)
3652            .label_size(LabelSize::Small)
3653            .color(Color::Muted);
3654
3655        let project = self
3656            .git_panel
3657            .as_ref()
3658            .map(|panel| panel.read(cx).project.clone());
3659
3660        let repo = self
3661            .git_panel
3662            .as_ref()
3663            .and_then(|panel| panel.read(cx).active_repository.clone());
3664
3665        let single_repo = project
3666            .as_ref()
3667            .map(|project| {
3668                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3669            })
3670            .unwrap_or(true);
3671
3672        let repo_selector = PopoverMenu::new("repository-switcher")
3673            .menu({
3674                let project = project.clone();
3675                move |window, cx| {
3676                    let project = project.clone()?;
3677                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3678                }
3679            })
3680            .trigger_with_tooltip(
3681                repo_selector_trigger.disabled(single_repo).truncate(true),
3682                Tooltip::text("Switch active repository"),
3683            )
3684            .attach(gpui::Corner::BottomLeft)
3685            .into_any_element();
3686
3687        let branch = self.branch.clone();
3688        let branch_name = branch
3689            .as_ref()
3690            .map_or(" (no branch)".into(), |branch| branch.name.clone());
3691
3692        let branch_selector_button = Button::new("branch-selector", branch_name)
3693            .style(ButtonStyle::Transparent)
3694            .size(ButtonSize::None)
3695            .label_size(LabelSize::Small)
3696            .truncate(true)
3697            .tooltip(Tooltip::for_action_title(
3698                "Switch Branch",
3699                &zed_actions::git::Branch,
3700            ))
3701            .on_click(|_, window, cx| {
3702                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3703            });
3704
3705        let branch_selector = PopoverMenu::new("popover-button")
3706            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3707            .trigger_with_tooltip(
3708                branch_selector_button,
3709                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3710            )
3711            .anchor(Corner::TopLeft)
3712            .offset(gpui::Point {
3713                x: px(0.0),
3714                y: px(-2.0),
3715            });
3716
3717        let spinner = self
3718            .git_panel
3719            .as_ref()
3720            .and_then(|git_panel| git_panel.read(cx).render_spinner());
3721
3722        h_flex()
3723            .w_full()
3724            .px_2()
3725            .h(px(36.))
3726            .items_center()
3727            .justify_between()
3728            .child(
3729                h_flex()
3730                    .flex_1()
3731                    .overflow_hidden()
3732                    .items_center()
3733                    .child(
3734                        div().child(
3735                            Icon::new(IconName::GitBranchSmall)
3736                                .size(IconSize::Small)
3737                                .color(Color::Muted),
3738                        ),
3739                    )
3740                    .child(repo_selector)
3741                    .when_some(branch.clone(), |this, _| {
3742                        this.child(
3743                            div()
3744                                .text_color(cx.theme().colors().text_muted)
3745                                .text_sm()
3746                                .child("/"),
3747                        )
3748                    })
3749                    .child(branch_selector),
3750            )
3751            .child(
3752                h_flex()
3753                    .gap_1()
3754                    .flex_shrink_0()
3755                    .children(spinner)
3756                    .child(self.render_overflow_menu(overflow_menu_id))
3757                    .when_some(branch, |this, branch| {
3758                        let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3759                        this.children(button)
3760                    }),
3761            )
3762    }
3763}
3764
3765impl ComponentPreview for PanelRepoFooter {
3766    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3767        let unknown_upstream = None;
3768        let no_remote_upstream = Some(UpstreamTracking::Gone);
3769        let ahead_of_upstream = Some(
3770            UpstreamTrackingStatus {
3771                ahead: 2,
3772                behind: 0,
3773            }
3774            .into(),
3775        );
3776        let behind_upstream = Some(
3777            UpstreamTrackingStatus {
3778                ahead: 0,
3779                behind: 2,
3780            }
3781            .into(),
3782        );
3783        let ahead_and_behind_upstream = Some(
3784            UpstreamTrackingStatus {
3785                ahead: 3,
3786                behind: 1,
3787            }
3788            .into(),
3789        );
3790
3791        let not_ahead_or_behind_upstream = Some(
3792            UpstreamTrackingStatus {
3793                ahead: 0,
3794                behind: 0,
3795            }
3796            .into(),
3797        );
3798
3799        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3800            Branch {
3801                is_head: true,
3802                name: "some-branch".into(),
3803                upstream: upstream.map(|tracking| Upstream {
3804                    ref_name: "origin/some-branch".into(),
3805                    tracking,
3806                }),
3807                most_recent_commit: Some(CommitSummary {
3808                    sha: "abc123".into(),
3809                    subject: "Modify stuff".into(),
3810                    commit_timestamp: 1710932954,
3811                }),
3812            }
3813        }
3814
3815        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3816            Branch {
3817                is_head: true,
3818                name: branch_name.to_string().into(),
3819                upstream: upstream.map(|tracking| Upstream {
3820                    ref_name: format!("zed/{}", branch_name).into(),
3821                    tracking,
3822                }),
3823                most_recent_commit: Some(CommitSummary {
3824                    sha: "abc123".into(),
3825                    subject: "Modify stuff".into(),
3826                    commit_timestamp: 1710932954,
3827                }),
3828            }
3829        }
3830
3831        fn active_repository(id: usize) -> SharedString {
3832            format!("repo-{}", id).into()
3833        }
3834
3835        let example_width = px(340.);
3836
3837        v_flex()
3838            .gap_6()
3839            .w_full()
3840            .flex_none()
3841            .children(vec![example_group_with_title(
3842                "Action Button States",
3843                vec![
3844                    single_example(
3845                        "No Branch",
3846                        div()
3847                            .w(example_width)
3848                            .overflow_hidden()
3849                            .child(PanelRepoFooter::new_preview(
3850                                "no-branch",
3851                                active_repository(1).clone(),
3852                                None,
3853                            ))
3854                            .into_any_element(),
3855                    )
3856                    .grow(),
3857                    single_example(
3858                        "Remote status unknown",
3859                        div()
3860                            .w(example_width)
3861                            .overflow_hidden()
3862                            .child(PanelRepoFooter::new_preview(
3863                                "unknown-upstream",
3864                                active_repository(2).clone(),
3865                                Some(branch(unknown_upstream)),
3866                            ))
3867                            .into_any_element(),
3868                    )
3869                    .grow(),
3870                    single_example(
3871                        "No Remote Upstream",
3872                        div()
3873                            .w(example_width)
3874                            .overflow_hidden()
3875                            .child(PanelRepoFooter::new_preview(
3876                                "no-remote-upstream",
3877                                active_repository(3).clone(),
3878                                Some(branch(no_remote_upstream)),
3879                            ))
3880                            .into_any_element(),
3881                    )
3882                    .grow(),
3883                    single_example(
3884                        "Not Ahead or Behind",
3885                        div()
3886                            .w(example_width)
3887                            .overflow_hidden()
3888                            .child(PanelRepoFooter::new_preview(
3889                                "not-ahead-or-behind",
3890                                active_repository(4).clone(),
3891                                Some(branch(not_ahead_or_behind_upstream)),
3892                            ))
3893                            .into_any_element(),
3894                    )
3895                    .grow(),
3896                    single_example(
3897                        "Behind remote",
3898                        div()
3899                            .w(example_width)
3900                            .overflow_hidden()
3901                            .child(PanelRepoFooter::new_preview(
3902                                "behind-remote",
3903                                active_repository(5).clone(),
3904                                Some(branch(behind_upstream)),
3905                            ))
3906                            .into_any_element(),
3907                    )
3908                    .grow(),
3909                    single_example(
3910                        "Ahead of remote",
3911                        div()
3912                            .w(example_width)
3913                            .overflow_hidden()
3914                            .child(PanelRepoFooter::new_preview(
3915                                "ahead-of-remote",
3916                                active_repository(6).clone(),
3917                                Some(branch(ahead_of_upstream)),
3918                            ))
3919                            .into_any_element(),
3920                    )
3921                    .grow(),
3922                    single_example(
3923                        "Ahead and behind remote",
3924                        div()
3925                            .w(example_width)
3926                            .overflow_hidden()
3927                            .child(PanelRepoFooter::new_preview(
3928                                "ahead-and-behind",
3929                                active_repository(7).clone(),
3930                                Some(branch(ahead_and_behind_upstream)),
3931                            ))
3932                            .into_any_element(),
3933                    )
3934                    .grow(),
3935                ],
3936            )
3937            .grow()
3938            .vertical()])
3939            .children(vec![example_group_with_title(
3940                "Labels",
3941                vec![
3942                    single_example(
3943                        "Short Branch & Repo",
3944                        div()
3945                            .w(example_width)
3946                            .overflow_hidden()
3947                            .child(PanelRepoFooter::new_preview(
3948                                "short-branch",
3949                                SharedString::from("zed"),
3950                                Some(custom("main", behind_upstream)),
3951                            ))
3952                            .into_any_element(),
3953                    )
3954                    .grow(),
3955                    single_example(
3956                        "Long Branch",
3957                        div()
3958                            .w(example_width)
3959                            .overflow_hidden()
3960                            .child(PanelRepoFooter::new_preview(
3961                                "long-branch",
3962                                SharedString::from("zed"),
3963                                Some(custom(
3964                                    "redesign-and-update-git-ui-list-entry-style",
3965                                    behind_upstream,
3966                                )),
3967                            ))
3968                            .into_any_element(),
3969                    )
3970                    .grow(),
3971                    single_example(
3972                        "Long Repo",
3973                        div()
3974                            .w(example_width)
3975                            .overflow_hidden()
3976                            .child(PanelRepoFooter::new_preview(
3977                                "long-repo",
3978                                SharedString::from("zed-industries-community-examples"),
3979                                Some(custom("gpui", ahead_of_upstream)),
3980                            ))
3981                            .into_any_element(),
3982                    )
3983                    .grow(),
3984                    single_example(
3985                        "Long Repo & Branch",
3986                        div()
3987                            .w(example_width)
3988                            .overflow_hidden()
3989                            .child(PanelRepoFooter::new_preview(
3990                                "long-repo-and-branch",
3991                                SharedString::from("zed-industries-community-examples"),
3992                                Some(custom(
3993                                    "redesign-and-update-git-ui-list-entry-style",
3994                                    behind_upstream,
3995                                )),
3996                            ))
3997                            .into_any_element(),
3998                    )
3999                    .grow(),
4000                    single_example(
4001                        "Uppercase Repo",
4002                        div()
4003                            .w(example_width)
4004                            .overflow_hidden()
4005                            .child(PanelRepoFooter::new_preview(
4006                                "uppercase-repo",
4007                                SharedString::from("LICENSES"),
4008                                Some(custom("main", ahead_of_upstream)),
4009                            ))
4010                            .into_any_element(),
4011                    )
4012                    .grow(),
4013                    single_example(
4014                        "Uppercase Branch",
4015                        div()
4016                            .w(example_width)
4017                            .overflow_hidden()
4018                            .child(PanelRepoFooter::new_preview(
4019                                "uppercase-branch",
4020                                SharedString::from("zed"),
4021                                Some(custom("update-README", behind_upstream)),
4022                            ))
4023                            .into_any_element(),
4024                    )
4025                    .grow(),
4026                ],
4027            )
4028            .grow()
4029            .vertical()])
4030            .into_any_element()
4031    }
4032}
4033
4034#[cfg(test)]
4035mod tests {
4036    use git::status::StatusCode;
4037    use gpui::TestAppContext;
4038    use project::{FakeFs, WorktreeSettings};
4039    use serde_json::json;
4040    use settings::SettingsStore;
4041    use theme::LoadThemes;
4042    use util::path;
4043
4044    use super::*;
4045
4046    fn init_test(cx: &mut gpui::TestAppContext) {
4047        if std::env::var("RUST_LOG").is_ok() {
4048            env_logger::try_init().ok();
4049        }
4050
4051        cx.update(|cx| {
4052            let settings_store = SettingsStore::test(cx);
4053            cx.set_global(settings_store);
4054            WorktreeSettings::register(cx);
4055            workspace::init_settings(cx);
4056            theme::init(LoadThemes::JustBase, cx);
4057            language::init(cx);
4058            editor::init(cx);
4059            Project::init_settings(cx);
4060            crate::init(cx);
4061        });
4062    }
4063
4064    #[gpui::test]
4065    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4066        init_test(cx);
4067        let fs = FakeFs::new(cx.background_executor.clone());
4068        fs.insert_tree(
4069            "/root",
4070            json!({
4071                "zed": {
4072                    ".git": {},
4073                    "crates": {
4074                        "gpui": {
4075                            "gpui.rs": "fn main() {}"
4076                        },
4077                        "util": {
4078                            "util.rs": "fn do_it() {}"
4079                        }
4080                    }
4081                },
4082            }),
4083        )
4084        .await;
4085
4086        fs.set_status_for_repo_via_git_operation(
4087            Path::new(path!("/root/zed/.git")),
4088            &[
4089                (
4090                    Path::new("crates/gpui/gpui.rs"),
4091                    StatusCode::Modified.worktree(),
4092                ),
4093                (
4094                    Path::new("crates/util/util.rs"),
4095                    StatusCode::Modified.worktree(),
4096                ),
4097            ],
4098        );
4099
4100        let project =
4101            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4102        let (workspace, cx) =
4103            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4104
4105        cx.read(|cx| {
4106            project
4107                .read(cx)
4108                .worktrees(cx)
4109                .nth(0)
4110                .unwrap()
4111                .read(cx)
4112                .as_local()
4113                .unwrap()
4114                .scan_complete()
4115        })
4116        .await;
4117
4118        cx.executor().run_until_parked();
4119
4120        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4121        let panel = cx.new_window_entity(|window, cx| {
4122            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4123        });
4124
4125        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4126            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4127        });
4128        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4129        handle.await;
4130
4131        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4132        pretty_assertions::assert_eq!(
4133            entries,
4134            [
4135                GitListEntry::Header(GitHeaderEntry {
4136                    header: Section::Tracked
4137                }),
4138                GitListEntry::GitStatusEntry(GitStatusEntry {
4139                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4140                    repo_path: "crates/gpui/gpui.rs".into(),
4141                    worktree_path: Path::new("gpui.rs").into(),
4142                    status: StatusCode::Modified.worktree(),
4143                    is_staged: Some(false),
4144                }),
4145                GitListEntry::GitStatusEntry(GitStatusEntry {
4146                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4147                    repo_path: "crates/util/util.rs".into(),
4148                    worktree_path: Path::new("../util/util.rs").into(),
4149                    status: StatusCode::Modified.worktree(),
4150                    is_staged: Some(false),
4151                },),
4152            ],
4153        );
4154
4155        cx.update_window_entity(&panel, |panel, window, cx| {
4156            panel.select_last(&Default::default(), window, cx);
4157            assert_eq!(panel.selected_entry, Some(2));
4158            panel.open_diff(&Default::default(), window, cx);
4159        });
4160        cx.run_until_parked();
4161
4162        let worktree_roots = workspace.update(cx, |workspace, cx| {
4163            workspace
4164                .worktrees(cx)
4165                .map(|worktree| worktree.read(cx).abs_path())
4166                .collect::<Vec<_>>()
4167        });
4168        pretty_assertions::assert_eq!(
4169            worktree_roots,
4170            vec![
4171                Path::new(path!("/root/zed/crates/gpui")).into(),
4172                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4173            ]
4174        );
4175
4176        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4177            let git_store = project.git_store().read(cx);
4178            // The repo that comes from the single-file worktree can't be selected through the UI.
4179            let filtered_entries = filtered_repository_entries(git_store, cx)
4180                .iter()
4181                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4182                .collect::<Vec<_>>();
4183            assert_eq!(
4184                filtered_entries,
4185                [Path::new(path!("/root/zed/crates/gpui")).into()]
4186            );
4187            // But we can select it artificially here.
4188            git_store
4189                .all_repositories()
4190                .into_iter()
4191                .find(|repo| {
4192                    &*repo.read(cx).worktree_abs_path
4193                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4194                })
4195                .unwrap()
4196        });
4197
4198        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4199        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4200        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4201            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4202        });
4203        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4204        handle.await;
4205        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4206        pretty_assertions::assert_eq!(
4207            entries,
4208            [
4209                GitListEntry::Header(GitHeaderEntry {
4210                    header: Section::Tracked
4211                }),
4212                GitListEntry::GitStatusEntry(GitStatusEntry {
4213                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4214                    repo_path: "crates/gpui/gpui.rs".into(),
4215                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4216                    status: StatusCode::Modified.worktree(),
4217                    is_staged: Some(false),
4218                }),
4219                GitListEntry::GitStatusEntry(GitStatusEntry {
4220                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4221                    repo_path: "crates/util/util.rs".into(),
4222                    worktree_path: Path::new("util.rs").into(),
4223                    status: StatusCode::Modified.worktree(),
4224                    is_staged: Some(false),
4225                },),
4226            ],
4227        );
4228    }
4229}