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