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