git_panel.rs

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