git_panel.rs

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