git_panel.rs

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