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