git_panel.rs

   1use crate::git_panel_settings::StatusStyle;
   2use crate::repository_selector::RepositorySelectorPopoverMenu;
   3use crate::ProjectDiff;
   4use crate::{
   5    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
   6};
   7use collections::HashMap;
   8use db::kvp::KEY_VALUE_STORE;
   9use editor::{
  10    actions::MoveToEnd, scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode,
  11    EditorSettings, MultiBuffer, ShowScrollbar,
  12};
  13use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
  14use gpui::*;
  15use language::{Buffer, File};
  16use menu::{SelectFirst, SelectLast, SelectNext, SelectPrev};
  17use multi_buffer::ExcerptInfo;
  18use panel::{panel_editor_container, panel_editor_style, panel_filled_button, PanelHeader};
  19use project::{
  20    git::{GitEvent, Repository},
  21    Fs, Project, ProjectPath,
  22};
  23use serde::{Deserialize, Serialize};
  24use settings::Settings as _;
  25use std::{collections::HashSet, path::PathBuf, sync::Arc, time::Duration, usize};
  26use ui::{
  27    prelude::*, ButtonLike, Checkbox, CheckboxWithLabel, Divider, DividerColor, ElevationIndex,
  28    IndentGuideColors, ListItem, ListItemSpacing, Scrollbar, ScrollbarState, Tooltip,
  29};
  30use util::{maybe, ResultExt, TryFutureExt};
  31use workspace::{
  32    dock::{DockPosition, Panel, PanelEvent},
  33    notifications::{DetachAndPromptErr, NotificationId},
  34    Toast, Workspace,
  35};
  36
  37actions!(
  38    git_panel,
  39    [
  40        Close,
  41        ToggleFocus,
  42        OpenMenu,
  43        FocusEditor,
  44        FocusChanges,
  45        FillCoAuthors,
  46    ]
  47);
  48
  49const GIT_PANEL_KEY: &str = "GitPanel";
  50
  51const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
  52
  53pub fn init(cx: &mut App) {
  54    cx.observe_new(
  55        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
  56            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
  57                workspace.toggle_panel_focus::<GitPanel>(window, cx);
  58            });
  59
  60            workspace.register_action(|workspace, _: &Commit, window, cx| {
  61                workspace.open_panel::<GitPanel>(window, cx);
  62                if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
  63                    git_panel
  64                        .read(cx)
  65                        .commit_editor
  66                        .focus_handle(cx)
  67                        .focus(window);
  68                }
  69            });
  70        },
  71    )
  72    .detach();
  73}
  74
  75#[derive(Debug, Clone)]
  76pub enum Event {
  77    Focus,
  78    OpenedEntry { path: ProjectPath },
  79}
  80
  81#[derive(Serialize, Deserialize)]
  82struct SerializedGitPanel {
  83    width: Option<Pixels>,
  84}
  85
  86#[derive(Debug, PartialEq, Eq, Clone, Copy)]
  87enum Section {
  88    Conflict,
  89    Tracked,
  90    New,
  91}
  92
  93#[derive(Debug, PartialEq, Eq, Clone)]
  94struct GitHeaderEntry {
  95    header: Section,
  96}
  97
  98impl GitHeaderEntry {
  99    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
 100        let this = &self.header;
 101        let status = status_entry.status;
 102        match this {
 103            Section::Conflict => repo.has_conflict(&status_entry.repo_path),
 104            Section::Tracked => !status.is_created(),
 105            Section::New => status.is_created(),
 106        }
 107    }
 108    pub fn title(&self) -> &'static str {
 109        match self.header {
 110            Section::Conflict => "Conflicts",
 111            Section::Tracked => "Changed",
 112            Section::New => "New",
 113        }
 114    }
 115}
 116
 117#[derive(Debug, PartialEq, Eq, Clone)]
 118enum GitListEntry {
 119    GitStatusEntry(GitStatusEntry),
 120    Header(GitHeaderEntry),
 121}
 122
 123impl GitListEntry {
 124    fn status_entry(&self) -> Option<&GitStatusEntry> {
 125        match self {
 126            GitListEntry::GitStatusEntry(entry) => Some(entry),
 127            _ => None,
 128        }
 129    }
 130}
 131
 132#[derive(Debug, PartialEq, Eq, Clone)]
 133pub struct GitStatusEntry {
 134    pub(crate) depth: usize,
 135    pub(crate) display_name: String,
 136    pub(crate) repo_path: RepoPath,
 137    pub(crate) status: FileStatus,
 138    pub(crate) is_staged: Option<bool>,
 139}
 140
 141struct PendingOperation {
 142    finished: bool,
 143    will_become_staged: bool,
 144    repo_paths: HashSet<RepoPath>,
 145    op_id: usize,
 146}
 147
 148pub struct GitPanel {
 149    active_repository: Option<Entity<Repository>>,
 150    commit_editor: Entity<Editor>,
 151    conflicted_count: usize,
 152    conflicted_staged_count: usize,
 153    current_modifiers: Modifiers,
 154    enable_auto_coauthors: bool,
 155    entries: Vec<GitListEntry>,
 156    entries_by_path: collections::HashMap<RepoPath, usize>,
 157    focus_handle: FocusHandle,
 158    fs: Arc<dyn Fs>,
 159    hide_scrollbar_task: Option<Task<()>>,
 160    new_count: usize,
 161    new_staged_count: usize,
 162    pending: Vec<PendingOperation>,
 163    pending_commit: Option<Task<()>>,
 164    pending_serialization: Task<Option<()>>,
 165    project: Entity<Project>,
 166    repository_selector: Entity<RepositorySelector>,
 167    scroll_handle: UniformListScrollHandle,
 168    scrollbar_state: ScrollbarState,
 169    selected_entry: Option<usize>,
 170    show_scrollbar: bool,
 171    tracked_count: usize,
 172    tracked_staged_count: usize,
 173    update_visible_entries_task: Task<()>,
 174    width: Option<Pixels>,
 175    workspace: WeakEntity<Workspace>,
 176}
 177
 178fn commit_message_editor(
 179    commit_message_buffer: Entity<Buffer>,
 180    project: Entity<Project>,
 181    window: &mut Window,
 182    cx: &mut Context<'_, Editor>,
 183) -> Editor {
 184    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
 185    let mut commit_editor = Editor::new(
 186        EditorMode::AutoHeight { max_lines: 6 },
 187        buffer,
 188        None,
 189        false,
 190        window,
 191        cx,
 192    );
 193    commit_editor.set_collaboration_hub(Box::new(project));
 194    commit_editor.set_use_autoclose(false);
 195    commit_editor.set_show_gutter(false, cx);
 196    commit_editor.set_show_wrap_guides(false, cx);
 197    commit_editor.set_show_indent_guides(false, cx);
 198    commit_editor.set_placeholder_text("Enter commit message", cx);
 199    commit_editor
 200}
 201
 202impl GitPanel {
 203    pub fn new(
 204        workspace: &mut Workspace,
 205        window: &mut Window,
 206        cx: &mut Context<Workspace>,
 207    ) -> Entity<Self> {
 208        let fs = workspace.app_state().fs.clone();
 209        let project = workspace.project().clone();
 210        let git_state = project.read(cx).git_state().clone();
 211        let active_repository = project.read(cx).active_repository(cx);
 212        let workspace = cx.entity().downgrade();
 213
 214        let git_panel = cx.new(|cx| {
 215            let focus_handle = cx.focus_handle();
 216            cx.on_focus(&focus_handle, window, Self::focus_in).detach();
 217            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 218                this.hide_scrollbar(window, cx);
 219            })
 220            .detach();
 221
 222            // just to let us render a placeholder editor.
 223            // Once the active git repo is set, this buffer will be replaced.
 224            let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
 225            let commit_editor =
 226                cx.new(|cx| commit_message_editor(temporary_buffer, project.clone(), window, cx));
 227            commit_editor.update(cx, |editor, cx| {
 228                editor.clear(window, cx);
 229            });
 230
 231            let scroll_handle = UniformListScrollHandle::new();
 232
 233            cx.subscribe_in(
 234                &git_state,
 235                window,
 236                move |this, git_state, event, window, cx| match event {
 237                    GitEvent::FileSystemUpdated => {
 238                        this.schedule_update(false, window, cx);
 239                    }
 240                    GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
 241                        this.active_repository = git_state.read(cx).active_repository();
 242                        this.schedule_update(true, window, cx);
 243                    }
 244                },
 245            )
 246            .detach();
 247
 248            let scrollbar_state =
 249                ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
 250
 251            let repository_selector =
 252                cx.new(|cx| RepositorySelector::new(project.clone(), window, cx));
 253
 254            let mut git_panel = Self {
 255                active_repository,
 256                commit_editor,
 257                conflicted_count: 0,
 258                conflicted_staged_count: 0,
 259                current_modifiers: window.modifiers(),
 260                enable_auto_coauthors: true,
 261                entries: Vec::new(),
 262                entries_by_path: HashMap::default(),
 263                focus_handle: cx.focus_handle(),
 264                fs,
 265                hide_scrollbar_task: None,
 266                new_count: 0,
 267                new_staged_count: 0,
 268                pending: Vec::new(),
 269                pending_commit: None,
 270                pending_serialization: Task::ready(None),
 271                project,
 272                repository_selector,
 273                scroll_handle,
 274                scrollbar_state,
 275                selected_entry: None,
 276                show_scrollbar: false,
 277                tracked_count: 0,
 278                tracked_staged_count: 0,
 279                update_visible_entries_task: Task::ready(()),
 280                width: Some(px(360.)),
 281                workspace,
 282            };
 283            git_panel.schedule_update(false, window, cx);
 284            git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
 285            git_panel
 286        });
 287
 288        cx.subscribe_in(
 289            &git_panel,
 290            window,
 291            move |workspace, _, event: &Event, window, cx| match event.clone() {
 292                Event::OpenedEntry { path } => {
 293                    workspace
 294                        .open_path_preview(path, None, false, false, window, cx)
 295                        .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
 296                            Some(format!("{e}"))
 297                        });
 298                }
 299                Event::Focus => { /* TODO */ }
 300            },
 301        )
 302        .detach();
 303
 304        git_panel
 305    }
 306
 307    pub fn select_entry_by_path(
 308        &mut self,
 309        path: ProjectPath,
 310        _: &mut Window,
 311        cx: &mut Context<Self>,
 312    ) {
 313        let Some(git_repo) = self.active_repository.as_ref() else {
 314            return;
 315        };
 316        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
 317            return;
 318        };
 319        let Some(ix) = self.entries_by_path.get(&repo_path) else {
 320            return;
 321        };
 322        self.selected_entry = Some(*ix);
 323        cx.notify();
 324    }
 325
 326    fn serialize(&mut self, cx: &mut Context<Self>) {
 327        let width = self.width;
 328        self.pending_serialization = cx.background_executor().spawn(
 329            async move {
 330                KEY_VALUE_STORE
 331                    .write_kvp(
 332                        GIT_PANEL_KEY.into(),
 333                        serde_json::to_string(&SerializedGitPanel { width })?,
 334                    )
 335                    .await?;
 336                anyhow::Ok(())
 337            }
 338            .log_err(),
 339        );
 340    }
 341
 342    fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
 343        let mut dispatch_context = KeyContext::new_with_defaults();
 344        dispatch_context.add("GitPanel");
 345
 346        if self.is_focused(window, cx) {
 347            dispatch_context.add("menu");
 348            dispatch_context.add("ChangesList");
 349        }
 350
 351        if self.commit_editor.read(cx).is_focused(window) {
 352            dispatch_context.add("CommitEditor");
 353        }
 354
 355        dispatch_context
 356    }
 357
 358    fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
 359        window
 360            .focused(cx)
 361            .map_or(false, |focused| self.focus_handle == focused)
 362    }
 363
 364    fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
 365        cx.emit(PanelEvent::Close);
 366    }
 367
 368    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 369        if !self.focus_handle.contains_focused(window, cx) {
 370            cx.emit(Event::Focus);
 371        }
 372    }
 373
 374    fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
 375        GitPanelSettings::get_global(cx)
 376            .scrollbar
 377            .show
 378            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
 379    }
 380
 381    fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
 382        let show = self.show_scrollbar(cx);
 383        match show {
 384            ShowScrollbar::Auto => true,
 385            ShowScrollbar::System => true,
 386            ShowScrollbar::Always => true,
 387            ShowScrollbar::Never => false,
 388        }
 389    }
 390
 391    fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
 392        let show = self.show_scrollbar(cx);
 393        match show {
 394            ShowScrollbar::Auto => true,
 395            ShowScrollbar::System => cx
 396                .try_global::<ScrollbarAutoHide>()
 397                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
 398            ShowScrollbar::Always => false,
 399            ShowScrollbar::Never => true,
 400        }
 401    }
 402
 403    fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 404        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
 405        if !self.should_autohide_scrollbar(cx) {
 406            return;
 407        }
 408        self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
 409            cx.background_executor()
 410                .timer(SCROLLBAR_SHOW_INTERVAL)
 411                .await;
 412            panel
 413                .update(&mut cx, |panel, cx| {
 414                    panel.show_scrollbar = false;
 415                    cx.notify();
 416                })
 417                .log_err();
 418        }))
 419    }
 420
 421    fn handle_modifiers_changed(
 422        &mut self,
 423        event: &ModifiersChangedEvent,
 424        _: &mut Window,
 425        cx: &mut Context<Self>,
 426    ) {
 427        self.current_modifiers = event.modifiers;
 428        cx.notify();
 429    }
 430
 431    fn calculate_depth_and_difference(
 432        repo_path: &RepoPath,
 433        visible_entries: &HashSet<RepoPath>,
 434    ) -> (usize, usize) {
 435        let ancestors = repo_path.ancestors().skip(1);
 436        for ancestor in ancestors {
 437            if let Some(parent_entry) = visible_entries.get(ancestor) {
 438                let entry_component_count = repo_path.components().count();
 439                let parent_component_count = parent_entry.components().count();
 440
 441                let difference = entry_component_count - parent_component_count;
 442
 443                let parent_depth = parent_entry
 444                    .ancestors()
 445                    .skip(1) // Skip the parent itself
 446                    .filter(|ancestor| visible_entries.contains(*ancestor))
 447                    .count();
 448
 449                return (parent_depth + 1, difference);
 450            }
 451        }
 452
 453        (0, 0)
 454    }
 455
 456    fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
 457        if let Some(selected_entry) = self.selected_entry {
 458            self.scroll_handle
 459                .scroll_to_item(selected_entry, ScrollStrategy::Center);
 460        }
 461
 462        cx.notify();
 463    }
 464
 465    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
 466        if self.entries.first().is_some() {
 467            self.selected_entry = Some(0);
 468            self.scroll_to_selected_entry(cx);
 469        }
 470    }
 471
 472    fn select_prev(&mut self, _: &SelectPrev, _window: &mut Window, cx: &mut Context<Self>) {
 473        let item_count = self.entries.len();
 474        if item_count == 0 {
 475            return;
 476        }
 477
 478        if let Some(selected_entry) = self.selected_entry {
 479            let new_selected_entry = if selected_entry > 0 {
 480                selected_entry - 1
 481            } else {
 482                selected_entry
 483            };
 484
 485            self.selected_entry = Some(new_selected_entry);
 486
 487            self.scroll_to_selected_entry(cx);
 488        }
 489
 490        cx.notify();
 491    }
 492
 493    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
 494        let item_count = self.entries.len();
 495        if item_count == 0 {
 496            return;
 497        }
 498
 499        if let Some(selected_entry) = self.selected_entry {
 500            let new_selected_entry = if selected_entry < item_count - 1 {
 501                selected_entry + 1
 502            } else {
 503                selected_entry
 504            };
 505
 506            self.selected_entry = Some(new_selected_entry);
 507
 508            self.scroll_to_selected_entry(cx);
 509        }
 510
 511        cx.notify();
 512    }
 513
 514    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 515        if self.entries.last().is_some() {
 516            self.selected_entry = Some(self.entries.len() - 1);
 517            self.scroll_to_selected_entry(cx);
 518        }
 519    }
 520
 521    fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
 522        self.commit_editor.update(cx, |editor, cx| {
 523            window.focus(&editor.focus_handle(cx));
 524        });
 525        cx.notify();
 526    }
 527
 528    fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
 529        let have_entries = self
 530            .active_repository
 531            .as_ref()
 532            .map_or(false, |active_repository| {
 533                active_repository.read(cx).entry_count() > 0
 534            });
 535        if have_entries && self.selected_entry.is_none() {
 536            self.selected_entry = Some(0);
 537            self.scroll_to_selected_entry(cx);
 538            cx.notify();
 539        }
 540    }
 541
 542    fn focus_changes_list(
 543        &mut self,
 544        _: &FocusChanges,
 545        window: &mut Window,
 546        cx: &mut Context<Self>,
 547    ) {
 548        self.select_first_entry_if_none(cx);
 549
 550        cx.focus_self(window);
 551        cx.notify();
 552    }
 553
 554    fn get_selected_entry(&self) -> Option<&GitListEntry> {
 555        self.selected_entry.and_then(|i| self.entries.get(i))
 556    }
 557
 558    fn open_selected(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 559        maybe!({
 560            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 561
 562            self.workspace
 563                .update(cx, |workspace, cx| {
 564                    ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
 565                })
 566                .ok()
 567        });
 568        self.focus_handle.focus(window);
 569    }
 570
 571    fn toggle_staged_for_entry(
 572        &mut self,
 573        entry: &GitListEntry,
 574        _window: &mut Window,
 575        cx: &mut Context<Self>,
 576    ) {
 577        let Some(active_repository) = self.active_repository.as_ref() else {
 578            return;
 579        };
 580        let (stage, repo_paths) = match entry {
 581            GitListEntry::GitStatusEntry(status_entry) => {
 582                if status_entry.status.is_staged().unwrap_or(false) {
 583                    (false, vec![status_entry.repo_path.clone()])
 584                } else {
 585                    (true, vec![status_entry.repo_path.clone()])
 586                }
 587            }
 588            GitListEntry::Header(section) => {
 589                let goal_staged_state = !self.header_state(section.header).selected();
 590                let repository = active_repository.read(cx);
 591                let entries = self
 592                    .entries
 593                    .iter()
 594                    .filter_map(|entry| entry.status_entry())
 595                    .filter(|status_entry| {
 596                        section.contains(&status_entry, repository)
 597                            && status_entry.is_staged != Some(goal_staged_state)
 598                    })
 599                    .map(|status_entry| status_entry.repo_path.clone())
 600                    .collect::<Vec<_>>();
 601
 602                (goal_staged_state, entries)
 603            }
 604        };
 605
 606        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
 607        self.pending.push(PendingOperation {
 608            op_id,
 609            will_become_staged: stage,
 610            repo_paths: repo_paths.iter().cloned().collect(),
 611            finished: false,
 612        });
 613        let repo_paths = repo_paths.clone();
 614        let active_repository = active_repository.clone();
 615        let repository = active_repository.read(cx);
 616        self.update_counts(repository);
 617        cx.notify();
 618
 619        cx.spawn({
 620            |this, mut cx| async move {
 621                let result = cx
 622                    .update(|cx| {
 623                        if stage {
 624                            active_repository.read(cx).stage_entries(repo_paths.clone())
 625                        } else {
 626                            active_repository
 627                                .read(cx)
 628                                .unstage_entries(repo_paths.clone())
 629                        }
 630                    })?
 631                    .await?;
 632
 633                this.update(&mut cx, |this, cx| {
 634                    for pending in this.pending.iter_mut() {
 635                        if pending.op_id == op_id {
 636                            pending.finished = true
 637                        }
 638                    }
 639                    result
 640                        .map_err(|e| {
 641                            this.show_err_toast(e, cx);
 642                        })
 643                        .ok();
 644                    cx.notify();
 645                })
 646            }
 647        })
 648        .detach();
 649    }
 650
 651    fn toggle_staged_for_selected(
 652        &mut self,
 653        _: &git::ToggleStaged,
 654        window: &mut Window,
 655        cx: &mut Context<Self>,
 656    ) {
 657        if let Some(selected_entry) = self.get_selected_entry().cloned() {
 658            self.toggle_staged_for_entry(&selected_entry, window, cx);
 659        }
 660    }
 661
 662    /// Commit all staged changes
 663    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
 664        let editor = self.commit_editor.read(cx);
 665        if editor.is_empty(cx) {
 666            if !editor.focus_handle(cx).contains_focused(window, cx) {
 667                editor.focus_handle(cx).focus(window);
 668                return;
 669            }
 670        }
 671
 672        self.commit_changes(window, cx)
 673    }
 674
 675    fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 676        let Some(active_repository) = self.active_repository.clone() else {
 677            return;
 678        };
 679        let error_spawn = |message, window: &mut Window, cx: &mut App| {
 680            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
 681            cx.spawn(|_| async move {
 682                prompt.await.ok();
 683            })
 684            .detach();
 685        };
 686
 687        if self.has_unstaged_conflicts() {
 688            error_spawn(
 689                "There are still conflicts. You must stage these before committing",
 690                window,
 691                cx,
 692            );
 693            return;
 694        }
 695
 696        let message = self.commit_editor.read(cx).text(cx);
 697        if message.trim().is_empty() {
 698            self.commit_editor.read(cx).focus_handle(cx).focus(window);
 699            return;
 700        }
 701
 702        let task = if self.has_staged_changes() {
 703            // Repository serializes all git operations, so we can just send a commit immediately
 704            let commit_task = active_repository.read(cx).commit(message.into(), None);
 705            cx.background_executor()
 706                .spawn(async move { commit_task.await? })
 707        } else {
 708            let changed_files = self
 709                .entries
 710                .iter()
 711                .filter_map(|entry| entry.status_entry())
 712                .filter(|status_entry| !status_entry.status.is_created())
 713                .map(|status_entry| status_entry.repo_path.clone())
 714                .collect::<Vec<_>>();
 715
 716            if changed_files.is_empty() {
 717                error_spawn("No changes to commit", window, cx);
 718                return;
 719            }
 720
 721            let stage_task = active_repository.read(cx).stage_entries(changed_files);
 722            cx.spawn(|_, mut cx| async move {
 723                stage_task.await??;
 724                let commit_task = active_repository
 725                    .update(&mut cx, |repo, _| repo.commit(message.into(), None))?;
 726                commit_task.await?
 727            })
 728        };
 729        let task = cx.spawn_in(window, |this, mut cx| async move {
 730            let result = task.await;
 731            this.update_in(&mut cx, |this, window, cx| {
 732                this.pending_commit.take();
 733                match result {
 734                    Ok(()) => {
 735                        this.commit_editor
 736                            .update(cx, |editor, cx| editor.clear(window, cx));
 737                    }
 738                    Err(e) => this.show_err_toast(e, cx),
 739                }
 740            })
 741            .ok();
 742        });
 743
 744        self.pending_commit = Some(task);
 745    }
 746
 747    fn fill_co_authors(&mut self, _: &FillCoAuthors, window: &mut Window, cx: &mut Context<Self>) {
 748        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
 749
 750        let Some(room) = self
 751            .workspace
 752            .upgrade()
 753            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
 754        else {
 755            return;
 756        };
 757
 758        let mut existing_text = self.commit_editor.read(cx).text(cx);
 759        existing_text.make_ascii_lowercase();
 760        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
 761        let mut ends_with_co_authors = false;
 762        let existing_co_authors = existing_text
 763            .lines()
 764            .filter_map(|line| {
 765                let line = line.trim();
 766                if line.starts_with(&lowercase_co_author_prefix) {
 767                    ends_with_co_authors = true;
 768                    Some(line)
 769                } else {
 770                    ends_with_co_authors = false;
 771                    None
 772                }
 773            })
 774            .collect::<HashSet<_>>();
 775
 776        let project = self.project.read(cx);
 777        let room = room.read(cx);
 778        let mut new_co_authors = Vec::new();
 779
 780        for (peer_id, collaborator) in project.collaborators() {
 781            if collaborator.is_host {
 782                continue;
 783            }
 784
 785            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
 786                continue;
 787            };
 788            if participant.can_write() && participant.user.email.is_some() {
 789                let email = participant.user.email.clone().unwrap();
 790
 791                if !existing_co_authors.contains(&email.as_ref()) {
 792                    new_co_authors.push((
 793                        participant
 794                            .user
 795                            .name
 796                            .clone()
 797                            .unwrap_or_else(|| participant.user.github_login.clone()),
 798                        email,
 799                    ))
 800                }
 801            }
 802        }
 803        if !project.is_local() && !project.is_read_only(cx) {
 804            if let Some(user) = room.local_participant_user(cx) {
 805                if let Some(email) = user.email.clone() {
 806                    if !existing_co_authors.contains(&email.as_ref()) {
 807                        new_co_authors.push((
 808                            user.name
 809                                .clone()
 810                                .unwrap_or_else(|| user.github_login.clone()),
 811                            email.clone(),
 812                        ))
 813                    }
 814                }
 815            }
 816        }
 817        if new_co_authors.is_empty() {
 818            return;
 819        }
 820
 821        self.commit_editor.update(cx, |editor, cx| {
 822            let editor_end = editor.buffer().read(cx).read(cx).len();
 823            let mut edit = String::new();
 824            if !ends_with_co_authors {
 825                edit.push('\n');
 826            }
 827            for (name, email) in new_co_authors {
 828                edit.push('\n');
 829                edit.push_str(CO_AUTHOR_PREFIX);
 830                edit.push_str(&name);
 831                edit.push_str(" <");
 832                edit.push_str(&email);
 833                edit.push('>');
 834            }
 835
 836            editor.edit(Some((editor_end..editor_end, edit)), cx);
 837            editor.move_to_end(&MoveToEnd, window, cx);
 838            editor.focus_handle(cx).focus(window);
 839        });
 840    }
 841
 842    fn schedule_update(
 843        &mut self,
 844        clear_pending: bool,
 845        window: &mut Window,
 846        cx: &mut Context<Self>,
 847    ) {
 848        let handle = cx.entity().downgrade();
 849        self.reopen_commit_buffer(window, cx);
 850        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
 851            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 852            if let Some(git_panel) = handle.upgrade() {
 853                git_panel
 854                    .update_in(&mut cx, |git_panel, _, cx| {
 855                        if clear_pending {
 856                            git_panel.clear_pending();
 857                        }
 858                        git_panel.update_visible_entries(cx);
 859                    })
 860                    .ok();
 861            }
 862        });
 863    }
 864
 865    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 866        let Some(active_repo) = self.active_repository.as_ref() else {
 867            return;
 868        };
 869        let load_buffer = active_repo.update(cx, |active_repo, cx| {
 870            let project = self.project.read(cx);
 871            active_repo.open_commit_buffer(
 872                Some(project.languages().clone()),
 873                project.buffer_store().clone(),
 874                cx,
 875            )
 876        });
 877
 878        cx.spawn_in(window, |git_panel, mut cx| async move {
 879            let buffer = load_buffer.await?;
 880            git_panel.update_in(&mut cx, |git_panel, window, cx| {
 881                if git_panel
 882                    .commit_editor
 883                    .read(cx)
 884                    .buffer()
 885                    .read(cx)
 886                    .as_singleton()
 887                    .as_ref()
 888                    != Some(&buffer)
 889                {
 890                    git_panel.commit_editor = cx.new(|cx| {
 891                        commit_message_editor(buffer, git_panel.project.clone(), window, cx)
 892                    });
 893                }
 894            })
 895        })
 896        .detach_and_log_err(cx);
 897    }
 898
 899    fn clear_pending(&mut self) {
 900        self.pending.retain(|v| !v.finished)
 901    }
 902
 903    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
 904        self.entries.clear();
 905        self.entries_by_path.clear();
 906        let mut changed_entries = Vec::new();
 907        let mut new_entries = Vec::new();
 908        let mut conflict_entries = Vec::new();
 909
 910        let Some(repo) = self.active_repository.as_ref() else {
 911            // Just clear entries if no repository is active.
 912            cx.notify();
 913            return;
 914        };
 915
 916        // First pass - collect all paths
 917        let repo = repo.read(cx);
 918        let path_set = HashSet::from_iter(repo.status().map(|entry| entry.repo_path));
 919
 920        // Second pass - create entries with proper depth calculation
 921        for entry in repo.status() {
 922            let (depth, difference) =
 923                Self::calculate_depth_and_difference(&entry.repo_path, &path_set);
 924
 925            let is_conflict = repo.has_conflict(&entry.repo_path);
 926            let is_new = entry.status.is_created();
 927            let is_staged = entry.status.is_staged();
 928
 929            let display_name = if difference > 1 {
 930                // Show partial path for deeply nested files
 931                entry
 932                    .repo_path
 933                    .as_ref()
 934                    .iter()
 935                    .skip(entry.repo_path.components().count() - difference)
 936                    .collect::<PathBuf>()
 937                    .to_string_lossy()
 938                    .into_owned()
 939            } else {
 940                // Just show filename
 941                entry
 942                    .repo_path
 943                    .file_name()
 944                    .map(|name| name.to_string_lossy().into_owned())
 945                    .unwrap_or_default()
 946            };
 947
 948            let entry = GitStatusEntry {
 949                depth,
 950                display_name,
 951                repo_path: entry.repo_path.clone(),
 952                status: entry.status,
 953                is_staged,
 954            };
 955
 956            if is_conflict {
 957                conflict_entries.push(entry);
 958            } else if is_new {
 959                new_entries.push(entry);
 960            } else {
 961                changed_entries.push(entry);
 962            }
 963        }
 964
 965        // Sort entries by path to maintain consistent order
 966        conflict_entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
 967        changed_entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
 968        new_entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
 969
 970        if conflict_entries.len() > 0 {
 971            self.entries.push(GitListEntry::Header(GitHeaderEntry {
 972                header: Section::Conflict,
 973            }));
 974            self.entries.extend(
 975                conflict_entries
 976                    .into_iter()
 977                    .map(GitListEntry::GitStatusEntry),
 978            );
 979        }
 980
 981        if changed_entries.len() > 0 {
 982            self.entries.push(GitListEntry::Header(GitHeaderEntry {
 983                header: Section::Tracked,
 984            }));
 985            self.entries.extend(
 986                changed_entries
 987                    .into_iter()
 988                    .map(GitListEntry::GitStatusEntry),
 989            );
 990        }
 991        if new_entries.len() > 0 {
 992            self.entries.push(GitListEntry::Header(GitHeaderEntry {
 993                header: Section::New,
 994            }));
 995            self.entries
 996                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
 997        }
 998
 999        for (ix, entry) in self.entries.iter().enumerate() {
1000            if let Some(status_entry) = entry.status_entry() {
1001                self.entries_by_path
1002                    .insert(status_entry.repo_path.clone(), ix);
1003            }
1004        }
1005        self.update_counts(repo);
1006
1007        self.select_first_entry_if_none(cx);
1008
1009        cx.notify();
1010    }
1011
1012    fn toggle_auto_coauthors(&mut self, cx: &mut Context<Self>) {
1013        self.enable_auto_coauthors = !self.enable_auto_coauthors;
1014        cx.notify();
1015    }
1016
1017    fn header_state(&self, header_type: Section) -> ToggleState {
1018        let (staged_count, count) = match header_type {
1019            Section::New => (self.new_staged_count, self.new_count),
1020            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
1021            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
1022        };
1023        if staged_count == 0 {
1024            ToggleState::Unselected
1025        } else if count == staged_count {
1026            ToggleState::Selected
1027        } else {
1028            ToggleState::Indeterminate
1029        }
1030    }
1031
1032    fn update_counts(&mut self, repo: &Repository) {
1033        self.conflicted_count = 0;
1034        self.conflicted_staged_count = 0;
1035        self.new_count = 0;
1036        self.tracked_count = 0;
1037        self.new_staged_count = 0;
1038        self.tracked_staged_count = 0;
1039        for entry in &self.entries {
1040            let Some(status_entry) = entry.status_entry() else {
1041                continue;
1042            };
1043            if repo.has_conflict(&status_entry.repo_path) {
1044                self.conflicted_count += 1;
1045                if self.entry_is_staged(status_entry) != Some(false) {
1046                    self.conflicted_staged_count += 1;
1047                }
1048            } else if status_entry.status.is_created() {
1049                self.new_count += 1;
1050                if self.entry_is_staged(status_entry) != Some(false) {
1051                    self.new_staged_count += 1;
1052                }
1053            } else {
1054                self.tracked_count += 1;
1055                if self.entry_is_staged(status_entry) != Some(false) {
1056                    self.tracked_staged_count += 1;
1057                }
1058            }
1059        }
1060    }
1061
1062    fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
1063        for pending in self.pending.iter().rev() {
1064            if pending.repo_paths.contains(&entry.repo_path) {
1065                return Some(pending.will_become_staged);
1066            }
1067        }
1068        entry.is_staged
1069    }
1070
1071    fn has_staged_changes(&self) -> bool {
1072        self.tracked_staged_count > 0
1073            || self.new_staged_count > 0
1074            || self.conflicted_staged_count > 0
1075    }
1076
1077    fn has_tracked_changes(&self) -> bool {
1078        self.tracked_count > 0
1079    }
1080
1081    fn has_unstaged_conflicts(&self) -> bool {
1082        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
1083    }
1084
1085    fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
1086        let Some(workspace) = self.workspace.upgrade() else {
1087            return;
1088        };
1089        let notif_id = NotificationId::Named("git-operation-error".into());
1090
1091        let message = e.to_string();
1092        workspace.update(cx, |workspace, cx| {
1093            let toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
1094                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
1095            });
1096            workspace.show_toast(toast, cx);
1097        });
1098    }
1099
1100    pub fn panel_button(
1101        &self,
1102        id: impl Into<SharedString>,
1103        label: impl Into<SharedString>,
1104    ) -> Button {
1105        let id = id.into().clone();
1106        let label = label.into().clone();
1107
1108        Button::new(id, label)
1109            .label_size(LabelSize::Small)
1110            .layer(ElevationIndex::ElevatedSurface)
1111            .size(ButtonSize::Compact)
1112            .style(ButtonStyle::Filled)
1113    }
1114
1115    pub fn indent_size(&self, window: &Window, cx: &mut Context<Self>) -> Pixels {
1116        Checkbox::container_size(cx).to_pixels(window.rem_size())
1117    }
1118
1119    pub fn render_divider(&self, _cx: &mut Context<Self>) -> impl IntoElement {
1120        h_flex()
1121            .items_center()
1122            .h(px(8.))
1123            .child(Divider::horizontal_dashed().color(DividerColor::Border))
1124    }
1125
1126    pub fn render_panel_header(
1127        &self,
1128        window: &mut Window,
1129        cx: &mut Context<Self>,
1130    ) -> impl IntoElement {
1131        let all_repositories = self
1132            .project
1133            .read(cx)
1134            .git_state()
1135            .read(cx)
1136            .all_repositories();
1137
1138        let branch = self
1139            .active_repository
1140            .as_ref()
1141            .and_then(|repository| repository.read(cx).branch())
1142            .unwrap_or_else(|| "(no current branch)".into());
1143
1144        let has_repo_above = all_repositories.iter().any(|repo| {
1145            repo.read(cx)
1146                .repository_entry
1147                .work_directory
1148                .is_above_project()
1149        });
1150
1151        let icon_button = Button::new("branch-selector", branch)
1152            .color(Color::Muted)
1153            .style(ButtonStyle::Subtle)
1154            .icon(IconName::GitBranch)
1155            .icon_size(IconSize::Small)
1156            .icon_color(Color::Muted)
1157            .size(ButtonSize::Compact)
1158            .icon_position(IconPosition::Start)
1159            .tooltip(Tooltip::for_action_title(
1160                "Switch Branch",
1161                &zed_actions::git::Branch,
1162            ))
1163            .on_click(cx.listener(|_, _, window, cx| {
1164                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
1165            }))
1166            .style(ButtonStyle::Transparent);
1167
1168        self.panel_header_container(window, cx)
1169            .child(h_flex().pl_1().child(icon_button))
1170            .child(div().flex_grow())
1171            .when(all_repositories.len() > 1 || has_repo_above, |el| {
1172                el.child(self.render_repository_selector(cx))
1173            })
1174    }
1175
1176    pub fn render_repository_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
1177        let active_repository = self.project.read(cx).active_repository(cx);
1178        let repository_display_name = active_repository
1179            .as_ref()
1180            .map(|repo| repo.read(cx).display_name(self.project.read(cx), cx))
1181            .unwrap_or_default();
1182
1183        RepositorySelectorPopoverMenu::new(
1184            self.repository_selector.clone(),
1185            ButtonLike::new("active-repository")
1186                .style(ButtonStyle::Subtle)
1187                .child(Label::new(repository_display_name).size(LabelSize::Small)),
1188            Tooltip::text("Select a repository"),
1189        )
1190    }
1191
1192    pub fn render_commit_editor(
1193        &self,
1194        window: &mut Window,
1195        cx: &mut Context<Self>,
1196    ) -> impl IntoElement {
1197        let editor = self.commit_editor.clone();
1198        let can_commit = (self.has_staged_changes() || self.has_tracked_changes())
1199            && self.pending_commit.is_none()
1200            && !editor.read(cx).is_empty(cx)
1201            && !self.has_unstaged_conflicts()
1202            && self.has_write_access(cx);
1203        // let can_commit_all =
1204        //     !self.commit_pending && self.can_commit_all && !editor.read(cx).is_empty(cx);
1205        let panel_editor_style = panel_editor_style(true, window, cx);
1206
1207        let editor_focus_handle = editor.read(cx).focus_handle(cx).clone();
1208
1209        let focus_handle_1 = self.focus_handle(cx).clone();
1210        let tooltip = if self.has_staged_changes() {
1211            "Commit staged changes"
1212        } else {
1213            "Commit changes to tracked files"
1214        };
1215        let title = if self.has_staged_changes() {
1216            "Commit"
1217        } else {
1218            "Commit All"
1219        };
1220
1221        let commit_button = panel_filled_button(title)
1222            .tooltip(move |window, cx| {
1223                let focus_handle = focus_handle_1.clone();
1224                Tooltip::for_action_in(tooltip, &Commit, &focus_handle, window, cx)
1225            })
1226            .disabled(!can_commit)
1227            .on_click({
1228                cx.listener(move |this, _: &ClickEvent, window, cx| this.commit_changes(window, cx))
1229            });
1230
1231        let enable_coauthors = CheckboxWithLabel::new(
1232            "enable-coauthors",
1233            Label::new("Add Co-authors")
1234                .color(Color::Disabled)
1235                .size(LabelSize::XSmall),
1236            self.enable_auto_coauthors.into(),
1237            cx.listener(move |this, _, _, cx| this.toggle_auto_coauthors(cx)),
1238        );
1239
1240        let footer_size = px(32.);
1241        let gap = px(16.0);
1242
1243        let max_height = window.line_height() * 6. + gap + footer_size;
1244
1245        panel_editor_container(window, cx)
1246            .id("commit-editor-container")
1247            .relative()
1248            .h(max_height)
1249            .w_full()
1250            .border_t_1()
1251            .border_color(cx.theme().colors().border)
1252            .bg(cx.theme().colors().editor_background)
1253            .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
1254                window.focus(&editor_focus_handle);
1255            }))
1256            .child(EditorElement::new(&self.commit_editor, panel_editor_style))
1257            .child(
1258                h_flex()
1259                    .absolute()
1260                    .bottom_0()
1261                    .left_2()
1262                    .h(footer_size)
1263                    .flex_none()
1264                    .child(enable_coauthors),
1265            )
1266            .child(
1267                h_flex()
1268                    .absolute()
1269                    .bottom_0()
1270                    .right_2()
1271                    .h(footer_size)
1272                    .flex_none()
1273                    .child(commit_button),
1274            )
1275    }
1276
1277    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
1278        h_flex()
1279            .h_full()
1280            .flex_1()
1281            .justify_center()
1282            .items_center()
1283            .child(
1284                v_flex()
1285                    .gap_3()
1286                    .child(if self.active_repository.is_some() {
1287                        "No changes to commit"
1288                    } else {
1289                        "No Git repositories"
1290                    })
1291                    .text_ui_sm(cx)
1292                    .mx_auto()
1293                    .text_color(Color::Placeholder.color(cx)),
1294            )
1295    }
1296
1297    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
1298        let scroll_bar_style = self.show_scrollbar(cx);
1299        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
1300
1301        if !self.should_show_scrollbar(cx)
1302            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
1303        {
1304            return None;
1305        }
1306
1307        Some(
1308            div()
1309                .id("git-panel-vertical-scroll")
1310                .occlude()
1311                .flex_none()
1312                .h_full()
1313                .cursor_default()
1314                .when(show_container, |this| this.pl_1().px_1p5())
1315                .when(!show_container, |this| {
1316                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
1317                })
1318                .on_mouse_move(cx.listener(|_, _, _, cx| {
1319                    cx.notify();
1320                    cx.stop_propagation()
1321                }))
1322                .on_hover(|_, _, cx| {
1323                    cx.stop_propagation();
1324                })
1325                .on_any_mouse_down(|_, _, cx| {
1326                    cx.stop_propagation();
1327                })
1328                .on_mouse_up(
1329                    MouseButton::Left,
1330                    cx.listener(|this, _, window, cx| {
1331                        if !this.scrollbar_state.is_dragging()
1332                            && !this.focus_handle.contains_focused(window, cx)
1333                        {
1334                            this.hide_scrollbar(window, cx);
1335                            cx.notify();
1336                        }
1337
1338                        cx.stop_propagation();
1339                    }),
1340                )
1341                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
1342                    cx.notify();
1343                }))
1344                .children(Scrollbar::vertical(
1345                    // percentage as f32..end_offset as f32,
1346                    self.scrollbar_state.clone(),
1347                )),
1348        )
1349    }
1350
1351    pub fn render_buffer_header_controls(
1352        &self,
1353        entity: &Entity<Self>,
1354        file: &Arc<dyn File>,
1355        _: &Window,
1356        cx: &App,
1357    ) -> Option<AnyElement> {
1358        let repo = self.active_repository.as_ref()?.read(cx);
1359        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
1360        let ix = self.entries_by_path.get(&repo_path)?;
1361        let entry = self.entries.get(*ix)?;
1362
1363        let is_staged = self.entry_is_staged(entry.status_entry()?);
1364
1365        let checkbox = Checkbox::new("stage-file", is_staged.into())
1366            .disabled(!self.has_write_access(cx))
1367            .fill()
1368            .elevation(ElevationIndex::Surface)
1369            .on_click({
1370                let entry = entry.clone();
1371                let git_panel = entity.downgrade();
1372                move |_, window, cx| {
1373                    git_panel
1374                        .update(cx, |this, cx| {
1375                            this.toggle_staged_for_entry(&entry, window, cx);
1376                            cx.stop_propagation();
1377                        })
1378                        .ok();
1379                }
1380            });
1381        Some(
1382            h_flex()
1383                .id("start-slot")
1384                .child(checkbox)
1385                .child(git_status_icon(entry.status_entry()?.status, cx))
1386                .on_mouse_down(MouseButton::Left, |_, _, cx| {
1387                    // prevent the list item active state triggering when toggling checkbox
1388                    cx.stop_propagation();
1389                })
1390                .into_any_element(),
1391        )
1392    }
1393
1394    fn render_entries(
1395        &self,
1396        has_write_access: bool,
1397        window: &Window,
1398        cx: &mut Context<Self>,
1399    ) -> impl IntoElement {
1400        let entry_count = self.entries.len();
1401
1402        v_flex()
1403            .size_full()
1404            .flex_grow()
1405            .overflow_hidden()
1406            .child(
1407                uniform_list(cx.entity().clone(), "entries", entry_count, {
1408                    move |this, range, window, cx| {
1409                        let mut items = Vec::with_capacity(range.end - range.start);
1410
1411                        for ix in range {
1412                            match &this.entries.get(ix) {
1413                                Some(GitListEntry::GitStatusEntry(entry)) => {
1414                                    items.push(this.render_entry(
1415                                        ix,
1416                                        entry,
1417                                        has_write_access,
1418                                        window,
1419                                        cx,
1420                                    ));
1421                                }
1422                                Some(GitListEntry::Header(header)) => {
1423                                    items.push(this.render_list_header(
1424                                        ix,
1425                                        header,
1426                                        has_write_access,
1427                                        window,
1428                                        cx,
1429                                    ));
1430                                }
1431                                None => {}
1432                            }
1433                        }
1434
1435                        items
1436                    }
1437                })
1438                .with_decoration(
1439                    ui::indent_guides(
1440                        cx.entity().clone(),
1441                        self.indent_size(window, cx),
1442                        IndentGuideColors::panel(cx),
1443                        |this, range, _windows, _cx| {
1444                            this.entries
1445                                .iter()
1446                                .skip(range.start)
1447                                .map(|entry| match entry {
1448                                    GitListEntry::GitStatusEntry(_) => 1,
1449                                    GitListEntry::Header(_) => 0,
1450                                })
1451                                .collect()
1452                        },
1453                    )
1454                    .with_render_fn(
1455                        cx.entity().clone(),
1456                        move |_, params, _, _| {
1457                            let indent_size = params.indent_size;
1458                            let left_offset = indent_size - px(3.0);
1459                            let item_height = params.item_height;
1460
1461                            params
1462                                .indent_guides
1463                                .into_iter()
1464                                .enumerate()
1465                                .map(|(_, layout)| {
1466                                    let offset = if layout.continues_offscreen {
1467                                        px(0.)
1468                                    } else {
1469                                        px(4.0)
1470                                    };
1471                                    let bounds = Bounds::new(
1472                                        point(
1473                                            px(layout.offset.x as f32) * indent_size + left_offset,
1474                                            px(layout.offset.y as f32) * item_height + offset,
1475                                        ),
1476                                        size(
1477                                            px(1.),
1478                                            px(layout.length as f32) * item_height
1479                                                - px(offset.0 * 2.),
1480                                        ),
1481                                    );
1482                                    ui::RenderedIndentGuide {
1483                                        bounds,
1484                                        layout,
1485                                        is_active: false,
1486                                        hitbox: None,
1487                                    }
1488                                })
1489                                .collect()
1490                        },
1491                    ),
1492                )
1493                .size_full()
1494                .with_sizing_behavior(ListSizingBehavior::Infer)
1495                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
1496                .track_scroll(self.scroll_handle.clone()),
1497            )
1498            .children(self.render_scrollbar(cx))
1499    }
1500
1501    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
1502        Label::new(label.into()).color(color).single_line()
1503    }
1504
1505    fn render_list_header(
1506        &self,
1507        ix: usize,
1508        header: &GitHeaderEntry,
1509        has_write_access: bool,
1510        window: &Window,
1511        cx: &Context<Self>,
1512    ) -> AnyElement {
1513        let selected = self.selected_entry == Some(ix);
1514        let header_state = if self.has_staged_changes() {
1515            self.header_state(header.header)
1516        } else {
1517            match header.header {
1518                Section::Tracked | Section::Conflict => ToggleState::Selected,
1519                Section::New => ToggleState::Unselected,
1520            }
1521        };
1522
1523        let checkbox = Checkbox::new(("checkbox", ix), header_state)
1524            .disabled(!has_write_access)
1525            .fill()
1526            .placeholder(!self.has_staged_changes())
1527            .elevation(ElevationIndex::Surface)
1528            .on_click({
1529                let header = header.clone();
1530                cx.listener(move |this, _, window, cx| {
1531                    this.toggle_staged_for_entry(&GitListEntry::Header(header.clone()), window, cx);
1532                    cx.stop_propagation();
1533                })
1534            });
1535
1536        let start_slot = h_flex()
1537            .id(("start-slot", ix))
1538            .gap(DynamicSpacing::Base04.rems(cx))
1539            .child(checkbox)
1540            .tooltip(|window, cx| Tooltip::for_action("Stage File", &ToggleStaged, window, cx))
1541            .on_mouse_down(MouseButton::Left, |_, _, cx| {
1542                // prevent the list item active state triggering when toggling checkbox
1543                cx.stop_propagation();
1544            });
1545
1546        div()
1547            .w_full()
1548            .child(
1549                ListItem::new(ix)
1550                    .spacing(ListItemSpacing::Sparse)
1551                    .start_slot(start_slot)
1552                    .toggle_state(selected)
1553                    .focused(selected && self.focus_handle(cx).is_focused(window))
1554                    .disabled(!has_write_access)
1555                    .on_click({
1556                        cx.listener(move |this, _, _, cx| {
1557                            this.selected_entry = Some(ix);
1558                            cx.notify();
1559                        })
1560                    })
1561                    .child(h_flex().child(self.entry_label(header.title(), Color::Muted))),
1562            )
1563            .into_any_element()
1564    }
1565
1566    fn render_entry(
1567        &self,
1568        ix: usize,
1569        entry: &GitStatusEntry,
1570        has_write_access: bool,
1571        window: &Window,
1572        cx: &Context<Self>,
1573    ) -> AnyElement {
1574        let display_name = entry
1575            .repo_path
1576            .file_name()
1577            .map(|name| name.to_string_lossy().into_owned())
1578            .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
1579
1580        let repo_path = entry.repo_path.clone();
1581        let selected = self.selected_entry == Some(ix);
1582        let status_style = GitPanelSettings::get_global(cx).status_style;
1583        let status = entry.status;
1584        let has_conflict = status.is_conflicted();
1585        let is_modified = status.is_modified();
1586        let is_deleted = status.is_deleted();
1587
1588        let label_color = if status_style == StatusStyle::LabelColor {
1589            if has_conflict {
1590                Color::Conflict
1591            } else if is_modified {
1592                Color::Modified
1593            } else if is_deleted {
1594                // We don't want a bunch of red labels in the list
1595                Color::Disabled
1596            } else {
1597                Color::Created
1598            }
1599        } else {
1600            Color::Default
1601        };
1602
1603        let path_color = if status.is_deleted() {
1604            Color::Disabled
1605        } else {
1606            Color::Muted
1607        };
1608
1609        let id: ElementId = ElementId::Name(format!("entry_{}", display_name).into());
1610
1611        let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
1612
1613        if !self.has_staged_changes() && !entry.status.is_created() {
1614            is_staged = ToggleState::Selected;
1615        }
1616
1617        let checkbox = Checkbox::new(id, is_staged)
1618            .disabled(!has_write_access)
1619            .fill()
1620            .placeholder(!self.has_staged_changes())
1621            .elevation(ElevationIndex::Surface)
1622            .on_click({
1623                let entry = entry.clone();
1624                cx.listener(move |this, _, window, cx| {
1625                    this.toggle_staged_for_entry(
1626                        &GitListEntry::GitStatusEntry(entry.clone()),
1627                        window,
1628                        cx,
1629                    );
1630                    cx.stop_propagation();
1631                })
1632            });
1633
1634        let start_slot = h_flex()
1635            .id(("start-slot", ix))
1636            .gap(DynamicSpacing::Base04.rems(cx))
1637            .child(checkbox)
1638            .tooltip(|window, cx| Tooltip::for_action("Stage File", &ToggleStaged, window, cx))
1639            .child(git_status_icon(status, cx))
1640            .on_mouse_down(MouseButton::Left, |_, _, cx| {
1641                // prevent the list item active state triggering when toggling checkbox
1642                cx.stop_propagation();
1643            });
1644
1645        let id = ElementId::Name(format!("entry_{}", display_name).into());
1646
1647        div()
1648            .w_full()
1649            .child(
1650                ListItem::new(id)
1651                    .indent_level(1)
1652                    .indent_step_size(Checkbox::container_size(cx).to_pixels(window.rem_size()))
1653                    .spacing(ListItemSpacing::Sparse)
1654                    .start_slot(start_slot)
1655                    .toggle_state(selected)
1656                    .focused(selected && self.focus_handle(cx).is_focused(window))
1657                    .disabled(!has_write_access)
1658                    .on_click({
1659                        cx.listener(move |this, _, window, cx| {
1660                            this.selected_entry = Some(ix);
1661                            cx.notify();
1662                            this.open_selected(&Default::default(), window, cx);
1663                        })
1664                    })
1665                    .child(
1666                        h_flex()
1667                            .when_some(repo_path.parent(), |this, parent| {
1668                                let parent_str = parent.to_string_lossy();
1669                                if !parent_str.is_empty() {
1670                                    this.child(
1671                                        self.entry_label(format!("{}/", parent_str), path_color)
1672                                            .when(status.is_deleted(), |this| this.strikethrough()),
1673                                    )
1674                                } else {
1675                                    this
1676                                }
1677                            })
1678                            .child(
1679                                self.entry_label(display_name.clone(), label_color)
1680                                    .when(status.is_deleted(), |this| this.strikethrough()),
1681                            ),
1682                    ),
1683            )
1684            .into_any_element()
1685    }
1686
1687    fn has_write_access(&self, cx: &App) -> bool {
1688        !self.project.read(cx).is_read_only(cx)
1689    }
1690}
1691
1692impl Render for GitPanel {
1693    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1694        let project = self.project.read(cx);
1695        let has_entries = self
1696            .active_repository
1697            .as_ref()
1698            .map_or(false, |active_repository| {
1699                active_repository.read(cx).entry_count() > 0
1700            });
1701        let room = self
1702            .workspace
1703            .upgrade()
1704            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
1705
1706        let has_write_access = self.has_write_access(cx);
1707
1708        let has_co_authors = room.map_or(false, |room| {
1709            room.read(cx)
1710                .remote_participants()
1711                .values()
1712                .any(|remote_participant| remote_participant.can_write())
1713        });
1714
1715        v_flex()
1716            .id("git_panel")
1717            .key_context(self.dispatch_context(window, cx))
1718            .track_focus(&self.focus_handle)
1719            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
1720            .when(has_write_access && !project.is_read_only(cx), |this| {
1721                this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
1722                    this.toggle_staged_for_selected(&ToggleStaged, window, cx)
1723                }))
1724                .on_action(cx.listener(GitPanel::commit))
1725            })
1726            .when(self.is_focused(window, cx), |this| {
1727                this.on_action(cx.listener(Self::select_first))
1728                    .on_action(cx.listener(Self::select_next))
1729                    .on_action(cx.listener(Self::select_prev))
1730                    .on_action(cx.listener(Self::select_last))
1731                    .on_action(cx.listener(Self::close_panel))
1732            })
1733            .on_action(cx.listener(Self::open_selected))
1734            .on_action(cx.listener(Self::focus_changes_list))
1735            .on_action(cx.listener(Self::focus_editor))
1736            .on_action(cx.listener(Self::toggle_staged_for_selected))
1737            .when(has_write_access && has_co_authors, |git_panel| {
1738                git_panel.on_action(cx.listener(Self::fill_co_authors))
1739            })
1740            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
1741            .on_hover(cx.listener(|this, hovered, window, cx| {
1742                if *hovered {
1743                    this.show_scrollbar = true;
1744                    this.hide_scrollbar_task.take();
1745                    cx.notify();
1746                } else if !this.focus_handle.contains_focused(window, cx) {
1747                    this.hide_scrollbar(window, cx);
1748                }
1749            }))
1750            .size_full()
1751            .overflow_hidden()
1752            .bg(ElevationIndex::Surface.bg(cx))
1753            .child(self.render_panel_header(window, cx))
1754            .child(if has_entries {
1755                self.render_entries(has_write_access, window, cx)
1756                    .into_any_element()
1757            } else {
1758                self.render_empty_state(cx).into_any_element()
1759            })
1760            .child(self.render_commit_editor(window, cx))
1761    }
1762}
1763
1764impl Focusable for GitPanel {
1765    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1766        self.focus_handle.clone()
1767    }
1768}
1769
1770impl EventEmitter<Event> for GitPanel {}
1771
1772impl EventEmitter<PanelEvent> for GitPanel {}
1773
1774pub(crate) struct GitPanelAddon {
1775    pub(crate) git_panel: Entity<GitPanel>,
1776}
1777
1778impl editor::Addon for GitPanelAddon {
1779    fn to_any(&self) -> &dyn std::any::Any {
1780        self
1781    }
1782
1783    fn render_buffer_header_controls(
1784        &self,
1785        excerpt_info: &ExcerptInfo,
1786        window: &Window,
1787        cx: &App,
1788    ) -> Option<AnyElement> {
1789        let file = excerpt_info.buffer.file()?;
1790        let git_panel = self.git_panel.read(cx);
1791
1792        git_panel.render_buffer_header_controls(&self.git_panel, &file, window, cx)
1793    }
1794}
1795
1796impl Panel for GitPanel {
1797    fn persistent_name() -> &'static str {
1798        "GitPanel"
1799    }
1800
1801    fn position(&self, _: &Window, cx: &App) -> DockPosition {
1802        GitPanelSettings::get_global(cx).dock
1803    }
1804
1805    fn position_is_valid(&self, position: DockPosition) -> bool {
1806        matches!(position, DockPosition::Left | DockPosition::Right)
1807    }
1808
1809    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1810        settings::update_settings_file::<GitPanelSettings>(
1811            self.fs.clone(),
1812            cx,
1813            move |settings, _| settings.dock = Some(position),
1814        );
1815    }
1816
1817    fn size(&self, _: &Window, cx: &App) -> Pixels {
1818        self.width
1819            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
1820    }
1821
1822    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
1823        self.width = size;
1824        self.serialize(cx);
1825        cx.notify();
1826    }
1827
1828    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
1829        Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
1830    }
1831
1832    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1833        Some("Git Panel")
1834    }
1835
1836    fn toggle_action(&self) -> Box<dyn Action> {
1837        Box::new(ToggleFocus)
1838    }
1839
1840    fn activation_priority(&self) -> u32 {
1841        2
1842    }
1843}
1844
1845impl PanelHeader for GitPanel {}