git_panel.rs

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