git_panel.rs

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