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((participant.user.github_login.clone(), email))
 793                }
 794            }
 795        }
 796        if !project.is_local() && !project.is_read_only(cx) {
 797            if let Some(user) = room.local_participant_user(cx) {
 798                if let Some(email) = user.email.clone() {
 799                    if !existing_co_authors.contains(&email.as_ref()) {
 800                        new_co_authors.push((user.github_login.clone(), email.clone()))
 801                    }
 802                }
 803            }
 804        }
 805        if new_co_authors.is_empty() {
 806            return;
 807        }
 808
 809        self.commit_editor.update(cx, |editor, cx| {
 810            let editor_end = editor.buffer().read(cx).read(cx).len();
 811            let mut edit = String::new();
 812            if !ends_with_co_authors {
 813                edit.push('\n');
 814            }
 815            for (name, email) in new_co_authors {
 816                edit.push('\n');
 817                edit.push_str(CO_AUTHOR_PREFIX);
 818                edit.push_str(&name);
 819                edit.push_str(" <");
 820                edit.push_str(&email);
 821                edit.push('>');
 822            }
 823
 824            editor.edit(Some((editor_end..editor_end, edit)), cx);
 825            editor.move_to_end(&MoveToEnd, window, cx);
 826            editor.focus_handle(cx).focus(window);
 827        });
 828    }
 829
 830    fn schedule_update(
 831        &mut self,
 832        clear_pending: bool,
 833        window: &mut Window,
 834        cx: &mut Context<Self>,
 835    ) {
 836        let handle = cx.entity().downgrade();
 837        self.reopen_commit_buffer(window, cx);
 838        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
 839            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 840            if let Some(git_panel) = handle.upgrade() {
 841                git_panel
 842                    .update_in(&mut cx, |git_panel, _, cx| {
 843                        if clear_pending {
 844                            git_panel.clear_pending();
 845                        }
 846                        git_panel.update_visible_entries(cx);
 847                    })
 848                    .ok();
 849            }
 850        });
 851    }
 852
 853    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 854        let Some(active_repo) = self.active_repository.as_ref() else {
 855            return;
 856        };
 857        let load_buffer = active_repo.update(cx, |active_repo, cx| {
 858            let project = self.project.read(cx);
 859            active_repo.open_commit_buffer(
 860                Some(project.languages().clone()),
 861                project.buffer_store().clone(),
 862                cx,
 863            )
 864        });
 865
 866        cx.spawn_in(window, |git_panel, mut cx| async move {
 867            let buffer = load_buffer.await?;
 868            git_panel.update_in(&mut cx, |git_panel, window, cx| {
 869                if git_panel
 870                    .commit_editor
 871                    .read(cx)
 872                    .buffer()
 873                    .read(cx)
 874                    .as_singleton()
 875                    .as_ref()
 876                    != Some(&buffer)
 877                {
 878                    git_panel.commit_editor = cx.new(|cx| {
 879                        commit_message_editor(buffer, git_panel.project.clone(), window, cx)
 880                    });
 881                }
 882            })
 883        })
 884        .detach_and_log_err(cx);
 885    }
 886
 887    fn clear_pending(&mut self) {
 888        self.pending.retain(|v| !v.finished)
 889    }
 890
 891    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
 892        self.entries.clear();
 893        self.entries_by_path.clear();
 894        let mut changed_entries = Vec::new();
 895        let mut new_entries = Vec::new();
 896        let mut conflict_entries = Vec::new();
 897
 898        let Some(repo) = self.active_repository.as_ref() else {
 899            // Just clear entries if no repository is active.
 900            cx.notify();
 901            return;
 902        };
 903
 904        // First pass - collect all paths
 905        let repo = repo.read(cx);
 906        let path_set = HashSet::from_iter(repo.status().map(|entry| entry.repo_path));
 907
 908        // Second pass - create entries with proper depth calculation
 909        for entry in repo.status() {
 910            let (depth, difference) =
 911                Self::calculate_depth_and_difference(&entry.repo_path, &path_set);
 912
 913            let is_conflict = repo.has_conflict(&entry.repo_path);
 914            let is_new = entry.status.is_created();
 915            let is_staged = entry.status.is_staged();
 916
 917            let display_name = if difference > 1 {
 918                // Show partial path for deeply nested files
 919                entry
 920                    .repo_path
 921                    .as_ref()
 922                    .iter()
 923                    .skip(entry.repo_path.components().count() - difference)
 924                    .collect::<PathBuf>()
 925                    .to_string_lossy()
 926                    .into_owned()
 927            } else {
 928                // Just show filename
 929                entry
 930                    .repo_path
 931                    .file_name()
 932                    .map(|name| name.to_string_lossy().into_owned())
 933                    .unwrap_or_default()
 934            };
 935
 936            let entry = GitStatusEntry {
 937                depth,
 938                display_name,
 939                repo_path: entry.repo_path.clone(),
 940                status: entry.status,
 941                is_staged,
 942            };
 943
 944            if is_conflict {
 945                conflict_entries.push(entry);
 946            } else if is_new {
 947                new_entries.push(entry);
 948            } else {
 949                changed_entries.push(entry);
 950            }
 951        }
 952
 953        // Sort entries by path to maintain consistent order
 954        conflict_entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
 955        changed_entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
 956        new_entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
 957
 958        if conflict_entries.len() > 0 {
 959            self.entries.push(GitListEntry::Header(GitHeaderEntry {
 960                header: Section::Conflict,
 961            }));
 962            self.entries.extend(
 963                conflict_entries
 964                    .into_iter()
 965                    .map(GitListEntry::GitStatusEntry),
 966            );
 967        }
 968
 969        if changed_entries.len() > 0 {
 970            self.entries.push(GitListEntry::Header(GitHeaderEntry {
 971                header: Section::Tracked,
 972            }));
 973            self.entries.extend(
 974                changed_entries
 975                    .into_iter()
 976                    .map(GitListEntry::GitStatusEntry),
 977            );
 978        }
 979        if new_entries.len() > 0 {
 980            self.entries.push(GitListEntry::Header(GitHeaderEntry {
 981                header: Section::New,
 982            }));
 983            self.entries
 984                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
 985        }
 986
 987        for (ix, entry) in self.entries.iter().enumerate() {
 988            if let Some(status_entry) = entry.status_entry() {
 989                self.entries_by_path
 990                    .insert(status_entry.repo_path.clone(), ix);
 991            }
 992        }
 993        self.update_counts(repo);
 994
 995        self.select_first_entry_if_none(cx);
 996
 997        cx.notify();
 998    }
 999
1000    fn toggle_auto_coauthors(&mut self, cx: &mut Context<Self>) {
1001        self.enable_auto_coauthors = !self.enable_auto_coauthors;
1002        cx.notify();
1003    }
1004
1005    fn header_state(&self, header_type: Section) -> ToggleState {
1006        let (staged_count, count) = match header_type {
1007            Section::New => (self.new_staged_count, self.new_count),
1008            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
1009            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
1010        };
1011        if staged_count == 0 {
1012            ToggleState::Unselected
1013        } else if count == staged_count {
1014            ToggleState::Selected
1015        } else {
1016            ToggleState::Indeterminate
1017        }
1018    }
1019
1020    fn update_counts(&mut self, repo: &Repository) {
1021        self.conflicted_count = 0;
1022        self.conflicted_staged_count = 0;
1023        self.new_count = 0;
1024        self.tracked_count = 0;
1025        self.new_staged_count = 0;
1026        self.tracked_staged_count = 0;
1027        for entry in &self.entries {
1028            let Some(status_entry) = entry.status_entry() else {
1029                continue;
1030            };
1031            if repo.has_conflict(&status_entry.repo_path) {
1032                self.conflicted_count += 1;
1033                if self.entry_is_staged(status_entry) != Some(false) {
1034                    self.conflicted_staged_count += 1;
1035                }
1036            } else if status_entry.status.is_created() {
1037                self.new_count += 1;
1038                if self.entry_is_staged(status_entry) != Some(false) {
1039                    self.new_staged_count += 1;
1040                }
1041            } else {
1042                self.tracked_count += 1;
1043                if self.entry_is_staged(status_entry) != Some(false) {
1044                    self.tracked_staged_count += 1;
1045                }
1046            }
1047        }
1048    }
1049
1050    fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
1051        for pending in self.pending.iter().rev() {
1052            if pending.repo_paths.contains(&entry.repo_path) {
1053                return Some(pending.will_become_staged);
1054            }
1055        }
1056        entry.is_staged
1057    }
1058
1059    fn has_staged_changes(&self) -> bool {
1060        self.tracked_staged_count > 0
1061            || self.new_staged_count > 0
1062            || self.conflicted_staged_count > 0
1063    }
1064
1065    fn has_tracked_changes(&self) -> bool {
1066        self.tracked_count > 0
1067    }
1068
1069    fn has_unstaged_conflicts(&self) -> bool {
1070        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
1071    }
1072
1073    fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
1074        let Some(workspace) = self.workspace.upgrade() else {
1075            return;
1076        };
1077        let notif_id = NotificationId::Named("git-operation-error".into());
1078
1079        let message = e.to_string();
1080        workspace.update(cx, |workspace, cx| {
1081            let toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
1082                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
1083            });
1084            workspace.show_toast(toast, cx);
1085        });
1086    }
1087
1088    pub fn panel_button(
1089        &self,
1090        id: impl Into<SharedString>,
1091        label: impl Into<SharedString>,
1092    ) -> Button {
1093        let id = id.into().clone();
1094        let label = label.into().clone();
1095
1096        Button::new(id, label)
1097            .label_size(LabelSize::Small)
1098            .layer(ElevationIndex::ElevatedSurface)
1099            .size(ButtonSize::Compact)
1100            .style(ButtonStyle::Filled)
1101    }
1102
1103    pub fn indent_size(&self, window: &Window, cx: &mut Context<Self>) -> Pixels {
1104        Checkbox::container_size(cx).to_pixels(window.rem_size())
1105    }
1106
1107    pub fn render_divider(&self, _cx: &mut Context<Self>) -> impl IntoElement {
1108        h_flex()
1109            .items_center()
1110            .h(px(8.))
1111            .child(Divider::horizontal_dashed().color(DividerColor::Border))
1112    }
1113
1114    pub fn render_panel_header(
1115        &self,
1116        window: &mut Window,
1117        cx: &mut Context<Self>,
1118    ) -> impl IntoElement {
1119        let all_repositories = self
1120            .project
1121            .read(cx)
1122            .git_state()
1123            .read(cx)
1124            .all_repositories();
1125
1126        let branch = self
1127            .active_repository
1128            .as_ref()
1129            .and_then(|repository| repository.read(cx).branch())
1130            .unwrap_or_else(|| "(no current branch)".into());
1131
1132        let has_repo_above = all_repositories.iter().any(|repo| {
1133            repo.read(cx)
1134                .repository_entry
1135                .work_directory
1136                .is_above_project()
1137        });
1138
1139        let icon_button = Button::new("branch-selector", branch)
1140            .color(Color::Muted)
1141            .style(ButtonStyle::Subtle)
1142            .icon(IconName::GitBranch)
1143            .icon_size(IconSize::Small)
1144            .icon_color(Color::Muted)
1145            .size(ButtonSize::Compact)
1146            .icon_position(IconPosition::Start)
1147            .tooltip(Tooltip::for_action_title(
1148                "Switch Branch",
1149                &zed_actions::git::Branch,
1150            ))
1151            .on_click(cx.listener(|_, _, window, cx| {
1152                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
1153            }))
1154            .style(ButtonStyle::Transparent);
1155
1156        self.panel_header_container(window, cx)
1157            .child(h_flex().pl_1().child(icon_button))
1158            .child(div().flex_grow())
1159            .when(all_repositories.len() > 1 || has_repo_above, |el| {
1160                el.child(self.render_repository_selector(cx))
1161            })
1162    }
1163
1164    pub fn render_repository_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
1165        let active_repository = self.project.read(cx).active_repository(cx);
1166        let repository_display_name = active_repository
1167            .as_ref()
1168            .map(|repo| repo.read(cx).display_name(self.project.read(cx), cx))
1169            .unwrap_or_default();
1170
1171        RepositorySelectorPopoverMenu::new(
1172            self.repository_selector.clone(),
1173            ButtonLike::new("active-repository")
1174                .style(ButtonStyle::Subtle)
1175                .child(Label::new(repository_display_name).size(LabelSize::Small)),
1176            Tooltip::text("Select a repository"),
1177        )
1178    }
1179
1180    pub fn render_commit_editor(
1181        &self,
1182        window: &mut Window,
1183        cx: &mut Context<Self>,
1184    ) -> impl IntoElement {
1185        let editor = self.commit_editor.clone();
1186        let can_commit = (self.has_staged_changes() || self.has_tracked_changes())
1187            && self.pending_commit.is_none()
1188            && !editor.read(cx).is_empty(cx)
1189            && !self.has_unstaged_conflicts()
1190            && self.has_write_access(cx);
1191        // let can_commit_all =
1192        //     !self.commit_pending && self.can_commit_all && !editor.read(cx).is_empty(cx);
1193        let panel_editor_style = panel_editor_style(true, window, cx);
1194
1195        let editor_focus_handle = editor.read(cx).focus_handle(cx).clone();
1196
1197        let focus_handle_1 = self.focus_handle(cx).clone();
1198        let tooltip = if self.has_staged_changes() {
1199            "Commit staged changes"
1200        } else {
1201            "Commit changes to tracked files"
1202        };
1203        let title = if self.has_staged_changes() {
1204            "Commit"
1205        } else {
1206            "Commit All"
1207        };
1208
1209        let commit_button = panel_filled_button(title)
1210            .tooltip(move |window, cx| {
1211                let focus_handle = focus_handle_1.clone();
1212                Tooltip::for_action_in(tooltip, &Commit, &focus_handle, window, cx)
1213            })
1214            .disabled(!can_commit)
1215            .on_click({
1216                cx.listener(move |this, _: &ClickEvent, window, cx| this.commit_changes(window, cx))
1217            });
1218
1219        let enable_coauthors = CheckboxWithLabel::new(
1220            "enable-coauthors",
1221            Label::new("Add Co-authors")
1222                .color(Color::Disabled)
1223                .size(LabelSize::XSmall),
1224            self.enable_auto_coauthors.into(),
1225            cx.listener(move |this, _, _, cx| this.toggle_auto_coauthors(cx)),
1226        );
1227
1228        let footer_size = px(32.);
1229        let gap = px(16.0);
1230
1231        let max_height = window.line_height() * 6. + gap + footer_size;
1232
1233        panel_editor_container(window, cx)
1234            .id("commit-editor-container")
1235            .relative()
1236            .h(max_height)
1237            .w_full()
1238            .border_t_1()
1239            .border_color(cx.theme().colors().border)
1240            .bg(cx.theme().colors().editor_background)
1241            .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
1242                window.focus(&editor_focus_handle);
1243            }))
1244            .child(EditorElement::new(&self.commit_editor, panel_editor_style))
1245            .child(
1246                h_flex()
1247                    .absolute()
1248                    .bottom_0()
1249                    .left_2()
1250                    .h(footer_size)
1251                    .flex_none()
1252                    .child(enable_coauthors),
1253            )
1254            .child(
1255                h_flex()
1256                    .absolute()
1257                    .bottom_0()
1258                    .right_2()
1259                    .h(footer_size)
1260                    .flex_none()
1261                    .child(commit_button),
1262            )
1263    }
1264
1265    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
1266        h_flex()
1267            .h_full()
1268            .flex_1()
1269            .justify_center()
1270            .items_center()
1271            .child(
1272                v_flex()
1273                    .gap_3()
1274                    .child(if self.active_repository.is_some() {
1275                        "No changes to commit"
1276                    } else {
1277                        "No Git repositories"
1278                    })
1279                    .text_ui_sm(cx)
1280                    .mx_auto()
1281                    .text_color(Color::Placeholder.color(cx)),
1282            )
1283    }
1284
1285    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
1286        let scroll_bar_style = self.show_scrollbar(cx);
1287        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
1288
1289        if !self.should_show_scrollbar(cx)
1290            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
1291        {
1292            return None;
1293        }
1294
1295        Some(
1296            div()
1297                .id("git-panel-vertical-scroll")
1298                .occlude()
1299                .flex_none()
1300                .h_full()
1301                .cursor_default()
1302                .when(show_container, |this| this.pl_1().px_1p5())
1303                .when(!show_container, |this| {
1304                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
1305                })
1306                .on_mouse_move(cx.listener(|_, _, _, cx| {
1307                    cx.notify();
1308                    cx.stop_propagation()
1309                }))
1310                .on_hover(|_, _, cx| {
1311                    cx.stop_propagation();
1312                })
1313                .on_any_mouse_down(|_, _, cx| {
1314                    cx.stop_propagation();
1315                })
1316                .on_mouse_up(
1317                    MouseButton::Left,
1318                    cx.listener(|this, _, window, cx| {
1319                        if !this.scrollbar_state.is_dragging()
1320                            && !this.focus_handle.contains_focused(window, cx)
1321                        {
1322                            this.hide_scrollbar(window, cx);
1323                            cx.notify();
1324                        }
1325
1326                        cx.stop_propagation();
1327                    }),
1328                )
1329                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
1330                    cx.notify();
1331                }))
1332                .children(Scrollbar::vertical(
1333                    // percentage as f32..end_offset as f32,
1334                    self.scrollbar_state.clone(),
1335                )),
1336        )
1337    }
1338
1339    pub fn render_buffer_header_controls(
1340        &self,
1341        entity: &Entity<Self>,
1342        file: &Arc<dyn File>,
1343        _: &Window,
1344        cx: &App,
1345    ) -> Option<AnyElement> {
1346        let repo = self.active_repository.as_ref()?.read(cx);
1347        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
1348        let ix = self.entries_by_path.get(&repo_path)?;
1349        let entry = self.entries.get(*ix)?;
1350
1351        let is_staged = self.entry_is_staged(entry.status_entry()?);
1352
1353        let checkbox = Checkbox::new("stage-file", is_staged.into())
1354            .disabled(!self.has_write_access(cx))
1355            .fill()
1356            .elevation(ElevationIndex::Surface)
1357            .on_click({
1358                let entry = entry.clone();
1359                let git_panel = entity.downgrade();
1360                move |_, window, cx| {
1361                    git_panel
1362                        .update(cx, |this, cx| {
1363                            this.toggle_staged_for_entry(&entry, window, cx);
1364                            cx.stop_propagation();
1365                        })
1366                        .ok();
1367                }
1368            });
1369        Some(
1370            h_flex()
1371                .id("start-slot")
1372                .child(checkbox)
1373                .child(git_status_icon(entry.status_entry()?.status, cx))
1374                .on_mouse_down(MouseButton::Left, |_, _, cx| {
1375                    // prevent the list item active state triggering when toggling checkbox
1376                    cx.stop_propagation();
1377                })
1378                .into_any_element(),
1379        )
1380    }
1381
1382    fn render_entries(
1383        &self,
1384        has_write_access: bool,
1385        window: &Window,
1386        cx: &mut Context<Self>,
1387    ) -> impl IntoElement {
1388        let entry_count = self.entries.len();
1389
1390        v_flex()
1391            .size_full()
1392            .flex_grow()
1393            .overflow_hidden()
1394            .child(
1395                uniform_list(cx.entity().clone(), "entries", entry_count, {
1396                    move |this, range, window, cx| {
1397                        let mut items = Vec::with_capacity(range.end - range.start);
1398
1399                        for ix in range {
1400                            match &this.entries.get(ix) {
1401                                Some(GitListEntry::GitStatusEntry(entry)) => {
1402                                    items.push(this.render_entry(
1403                                        ix,
1404                                        entry,
1405                                        has_write_access,
1406                                        window,
1407                                        cx,
1408                                    ));
1409                                }
1410                                Some(GitListEntry::Header(header)) => {
1411                                    items.push(this.render_list_header(
1412                                        ix,
1413                                        header,
1414                                        has_write_access,
1415                                        window,
1416                                        cx,
1417                                    ));
1418                                }
1419                                None => {}
1420                            }
1421                        }
1422
1423                        items
1424                    }
1425                })
1426                .with_decoration(
1427                    ui::indent_guides(
1428                        cx.entity().clone(),
1429                        self.indent_size(window, cx),
1430                        IndentGuideColors::panel(cx),
1431                        |this, range, _windows, _cx| {
1432                            this.entries
1433                                .iter()
1434                                .skip(range.start)
1435                                .map(|entry| match entry {
1436                                    GitListEntry::GitStatusEntry(_) => 1,
1437                                    GitListEntry::Header(_) => 0,
1438                                })
1439                                .collect()
1440                        },
1441                    )
1442                    .with_render_fn(
1443                        cx.entity().clone(),
1444                        move |_, params, _, _| {
1445                            let indent_size = params.indent_size;
1446                            let left_offset = indent_size - px(3.0);
1447                            let item_height = params.item_height;
1448
1449                            params
1450                                .indent_guides
1451                                .into_iter()
1452                                .enumerate()
1453                                .map(|(_, layout)| {
1454                                    let offset = if layout.continues_offscreen {
1455                                        px(0.)
1456                                    } else {
1457                                        px(4.0)
1458                                    };
1459                                    let bounds = Bounds::new(
1460                                        point(
1461                                            px(layout.offset.x as f32) * indent_size + left_offset,
1462                                            px(layout.offset.y as f32) * item_height + offset,
1463                                        ),
1464                                        size(
1465                                            px(1.),
1466                                            px(layout.length as f32) * item_height
1467                                                - px(offset.0 * 2.),
1468                                        ),
1469                                    );
1470                                    ui::RenderedIndentGuide {
1471                                        bounds,
1472                                        layout,
1473                                        is_active: false,
1474                                        hitbox: None,
1475                                    }
1476                                })
1477                                .collect()
1478                        },
1479                    ),
1480                )
1481                .size_full()
1482                .with_sizing_behavior(ListSizingBehavior::Infer)
1483                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
1484                .track_scroll(self.scroll_handle.clone()),
1485            )
1486            .children(self.render_scrollbar(cx))
1487    }
1488
1489    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
1490        Label::new(label.into()).color(color).single_line()
1491    }
1492
1493    fn render_list_header(
1494        &self,
1495        ix: usize,
1496        header: &GitHeaderEntry,
1497        has_write_access: bool,
1498        window: &Window,
1499        cx: &Context<Self>,
1500    ) -> AnyElement {
1501        let selected = self.selected_entry == Some(ix);
1502        let header_state = if self.has_staged_changes() {
1503            self.header_state(header.header)
1504        } else {
1505            match header.header {
1506                Section::Tracked | Section::Conflict => ToggleState::Selected,
1507                Section::New => ToggleState::Unselected,
1508            }
1509        };
1510
1511        let checkbox = Checkbox::new(("checkbox", ix), header_state)
1512            .disabled(!has_write_access)
1513            .fill()
1514            .placeholder(!self.has_staged_changes())
1515            .elevation(ElevationIndex::Surface)
1516            .on_click({
1517                let header = header.clone();
1518                cx.listener(move |this, _, window, cx| {
1519                    this.toggle_staged_for_entry(&GitListEntry::Header(header.clone()), window, cx);
1520                    cx.stop_propagation();
1521                })
1522            });
1523
1524        let start_slot = h_flex()
1525            .id(("start-slot", ix))
1526            .gap(DynamicSpacing::Base04.rems(cx))
1527            .child(checkbox)
1528            .tooltip(|window, cx| Tooltip::for_action("Stage File", &ToggleStaged, window, cx))
1529            .on_mouse_down(MouseButton::Left, |_, _, cx| {
1530                // prevent the list item active state triggering when toggling checkbox
1531                cx.stop_propagation();
1532            });
1533
1534        div()
1535            .w_full()
1536            .child(
1537                ListItem::new(ix)
1538                    .spacing(ListItemSpacing::Sparse)
1539                    .start_slot(start_slot)
1540                    .toggle_state(selected)
1541                    .focused(selected && self.focus_handle(cx).is_focused(window))
1542                    .disabled(!has_write_access)
1543                    .on_click({
1544                        cx.listener(move |this, _, _, cx| {
1545                            this.selected_entry = Some(ix);
1546                            cx.notify();
1547                        })
1548                    })
1549                    .child(h_flex().child(self.entry_label(header.title(), Color::Muted))),
1550            )
1551            .into_any_element()
1552    }
1553
1554    fn render_entry(
1555        &self,
1556        ix: usize,
1557        entry: &GitStatusEntry,
1558        has_write_access: bool,
1559        window: &Window,
1560        cx: &Context<Self>,
1561    ) -> AnyElement {
1562        let display_name = entry
1563            .repo_path
1564            .file_name()
1565            .map(|name| name.to_string_lossy().into_owned())
1566            .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
1567
1568        let repo_path = entry.repo_path.clone();
1569        let selected = self.selected_entry == Some(ix);
1570        let status_style = GitPanelSettings::get_global(cx).status_style;
1571        let status = entry.status;
1572        let has_conflict = status.is_conflicted();
1573        let is_modified = status.is_modified();
1574        let is_deleted = status.is_deleted();
1575
1576        let label_color = if status_style == StatusStyle::LabelColor {
1577            if has_conflict {
1578                Color::Conflict
1579            } else if is_modified {
1580                Color::Modified
1581            } else if is_deleted {
1582                // We don't want a bunch of red labels in the list
1583                Color::Disabled
1584            } else {
1585                Color::Created
1586            }
1587        } else {
1588            Color::Default
1589        };
1590
1591        let path_color = if status.is_deleted() {
1592            Color::Disabled
1593        } else {
1594            Color::Muted
1595        };
1596
1597        let id: ElementId = ElementId::Name(format!("entry_{}", display_name).into());
1598
1599        let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
1600
1601        if !self.has_staged_changes() && !entry.status.is_created() {
1602            is_staged = ToggleState::Selected;
1603        }
1604
1605        let checkbox = Checkbox::new(id, is_staged)
1606            .disabled(!has_write_access)
1607            .fill()
1608            .placeholder(!self.has_staged_changes())
1609            .elevation(ElevationIndex::Surface)
1610            .on_click({
1611                let entry = entry.clone();
1612                cx.listener(move |this, _, window, cx| {
1613                    this.toggle_staged_for_entry(
1614                        &GitListEntry::GitStatusEntry(entry.clone()),
1615                        window,
1616                        cx,
1617                    );
1618                    cx.stop_propagation();
1619                })
1620            });
1621
1622        let start_slot = h_flex()
1623            .id(("start-slot", ix))
1624            .gap(DynamicSpacing::Base04.rems(cx))
1625            .child(checkbox)
1626            .tooltip(|window, cx| Tooltip::for_action("Stage File", &ToggleStaged, window, cx))
1627            .child(git_status_icon(status, cx))
1628            .on_mouse_down(MouseButton::Left, |_, _, cx| {
1629                // prevent the list item active state triggering when toggling checkbox
1630                cx.stop_propagation();
1631            });
1632
1633        let id = ElementId::Name(format!("entry_{}", display_name).into());
1634
1635        div()
1636            .w_full()
1637            .child(
1638                ListItem::new(id)
1639                    .indent_level(1)
1640                    .indent_step_size(Checkbox::container_size(cx).to_pixels(window.rem_size()))
1641                    .spacing(ListItemSpacing::Sparse)
1642                    .start_slot(start_slot)
1643                    .toggle_state(selected)
1644                    .focused(selected && self.focus_handle(cx).is_focused(window))
1645                    .disabled(!has_write_access)
1646                    .on_click({
1647                        cx.listener(move |this, _, window, cx| {
1648                            this.selected_entry = Some(ix);
1649                            cx.notify();
1650                            this.open_selected(&Default::default(), window, cx);
1651                        })
1652                    })
1653                    .child(
1654                        h_flex()
1655                            .when_some(repo_path.parent(), |this, parent| {
1656                                let parent_str = parent.to_string_lossy();
1657                                if !parent_str.is_empty() {
1658                                    this.child(
1659                                        self.entry_label(format!("{}/", parent_str), path_color)
1660                                            .when(status.is_deleted(), |this| this.strikethrough()),
1661                                    )
1662                                } else {
1663                                    this
1664                                }
1665                            })
1666                            .child(
1667                                self.entry_label(display_name.clone(), label_color)
1668                                    .when(status.is_deleted(), |this| this.strikethrough()),
1669                            ),
1670                    ),
1671            )
1672            .into_any_element()
1673    }
1674
1675    fn has_write_access(&self, cx: &App) -> bool {
1676        !self.project.read(cx).is_read_only(cx)
1677    }
1678}
1679
1680impl Render for GitPanel {
1681    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1682        let project = self.project.read(cx);
1683        let has_entries = self
1684            .active_repository
1685            .as_ref()
1686            .map_or(false, |active_repository| {
1687                active_repository.read(cx).entry_count() > 0
1688            });
1689        let room = self
1690            .workspace
1691            .upgrade()
1692            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
1693
1694        let has_write_access = self.has_write_access(cx);
1695
1696        let has_co_authors = room.map_or(false, |room| {
1697            room.read(cx)
1698                .remote_participants()
1699                .values()
1700                .any(|remote_participant| remote_participant.can_write())
1701        });
1702
1703        v_flex()
1704            .id("git_panel")
1705            .key_context(self.dispatch_context(window, cx))
1706            .track_focus(&self.focus_handle)
1707            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
1708            .when(has_write_access && !project.is_read_only(cx), |this| {
1709                this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
1710                    this.toggle_staged_for_selected(&ToggleStaged, window, cx)
1711                }))
1712                .on_action(cx.listener(GitPanel::commit))
1713            })
1714            .when(self.is_focused(window, cx), |this| {
1715                this.on_action(cx.listener(Self::select_first))
1716                    .on_action(cx.listener(Self::select_next))
1717                    .on_action(cx.listener(Self::select_prev))
1718                    .on_action(cx.listener(Self::select_last))
1719                    .on_action(cx.listener(Self::close_panel))
1720            })
1721            .on_action(cx.listener(Self::open_selected))
1722            .on_action(cx.listener(Self::focus_changes_list))
1723            .on_action(cx.listener(Self::focus_editor))
1724            .on_action(cx.listener(Self::toggle_staged_for_selected))
1725            .when(has_write_access && has_co_authors, |git_panel| {
1726                git_panel.on_action(cx.listener(Self::fill_co_authors))
1727            })
1728            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
1729            .on_hover(cx.listener(|this, hovered, window, cx| {
1730                if *hovered {
1731                    this.show_scrollbar = true;
1732                    this.hide_scrollbar_task.take();
1733                    cx.notify();
1734                } else if !this.focus_handle.contains_focused(window, cx) {
1735                    this.hide_scrollbar(window, cx);
1736                }
1737            }))
1738            .size_full()
1739            .overflow_hidden()
1740            .bg(ElevationIndex::Surface.bg(cx))
1741            .child(self.render_panel_header(window, cx))
1742            .child(if has_entries {
1743                self.render_entries(has_write_access, window, cx)
1744                    .into_any_element()
1745            } else {
1746                self.render_empty_state(cx).into_any_element()
1747            })
1748            .child(self.render_commit_editor(window, cx))
1749    }
1750}
1751
1752impl Focusable for GitPanel {
1753    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1754        self.focus_handle.clone()
1755    }
1756}
1757
1758impl EventEmitter<Event> for GitPanel {}
1759
1760impl EventEmitter<PanelEvent> for GitPanel {}
1761
1762pub(crate) struct GitPanelAddon {
1763    pub(crate) git_panel: Entity<GitPanel>,
1764}
1765
1766impl editor::Addon for GitPanelAddon {
1767    fn to_any(&self) -> &dyn std::any::Any {
1768        self
1769    }
1770
1771    fn render_buffer_header_controls(
1772        &self,
1773        excerpt_info: &ExcerptInfo,
1774        window: &Window,
1775        cx: &App,
1776    ) -> Option<AnyElement> {
1777        let file = excerpt_info.buffer.file()?;
1778        let git_panel = self.git_panel.read(cx);
1779
1780        git_panel.render_buffer_header_controls(&self.git_panel, &file, window, cx)
1781    }
1782}
1783
1784impl Panel for GitPanel {
1785    fn persistent_name() -> &'static str {
1786        "GitPanel"
1787    }
1788
1789    fn position(&self, _: &Window, cx: &App) -> DockPosition {
1790        GitPanelSettings::get_global(cx).dock
1791    }
1792
1793    fn position_is_valid(&self, position: DockPosition) -> bool {
1794        matches!(position, DockPosition::Left | DockPosition::Right)
1795    }
1796
1797    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1798        settings::update_settings_file::<GitPanelSettings>(
1799            self.fs.clone(),
1800            cx,
1801            move |settings, _| settings.dock = Some(position),
1802        );
1803    }
1804
1805    fn size(&self, _: &Window, cx: &App) -> Pixels {
1806        self.width
1807            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
1808    }
1809
1810    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
1811        self.width = size;
1812        self.serialize(cx);
1813        cx.notify();
1814    }
1815
1816    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
1817        Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
1818    }
1819
1820    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1821        Some("Git Panel")
1822    }
1823
1824    fn toggle_action(&self) -> Box<dyn Action> {
1825        Box::new(ToggleFocus)
1826    }
1827
1828    fn activation_priority(&self) -> u32 {
1829        2
1830    }
1831}
1832
1833impl PanelHeader for GitPanel {}