git_panel.rs

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