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