1mod project_panel_settings;
   2mod utils;
   3
   4use anyhow::{Context as _, Result};
   5use client::{ErrorCode, ErrorExt};
   6use collections::{BTreeSet, HashMap, hash_map};
   7use command_palette_hooks::CommandPaletteFilter;
   8use db::kvp::KEY_VALUE_STORE;
   9use editor::{
  10    Editor, EditorEvent,
  11    items::{
  12        entry_diagnostic_aware_icon_decoration_and_color,
  13        entry_diagnostic_aware_icon_name_and_color, entry_git_aware_label_color,
  14    },
  15};
  16use file_icons::FileIcons;
  17use git::status::GitSummary;
  18use git_ui::file_diff_view::FileDiffView;
  19use gpui::{
  20    Action, AnyElement, App, AsyncWindowContext, Bounds, ClipboardItem, Context, CursorStyle,
  21    DismissEvent, Div, DragMoveEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable,
  22    Hsla, InteractiveElement, KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior,
  23    Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, ParentElement, Pixels, Point,
  24    PromptLevel, Render, ScrollStrategy, Stateful, Styled, Subscription, Task,
  25    UniformListScrollHandle, WeakEntity, Window, actions, anchored, deferred, div, hsla,
  26    linear_color_stop, linear_gradient, point, px, size, transparent_white, uniform_list,
  27};
  28use language::DiagnosticSeverity;
  29use menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  30use project::{
  31    Entry, EntryKind, Fs, GitEntry, GitEntryRef, GitTraversal, Project, ProjectEntryId,
  32    ProjectPath, Worktree, WorktreeId,
  33    git_store::{GitStoreEvent, RepositoryEvent, git_traversal::ChildEntriesGitIter},
  34    project_settings::GoToDiagnosticSeverityFilter,
  35};
  36use project_panel_settings::ProjectPanelSettings;
  37use rayon::slice::ParallelSliceMut;
  38use schemars::JsonSchema;
  39use serde::{Deserialize, Serialize};
  40use settings::{
  41    DockSide, ProjectPanelEntrySpacing, Settings, SettingsStore, ShowDiagnostics, ShowIndentGuides,
  42    update_settings_file,
  43};
  44use smallvec::SmallVec;
  45use std::{any::TypeId, time::Instant};
  46use std::{
  47    cell::OnceCell,
  48    cmp,
  49    collections::HashSet,
  50    ops::Range,
  51    path::{Path, PathBuf},
  52    sync::Arc,
  53    time::Duration,
  54};
  55use theme::ThemeSettings;
  56use ui::{
  57    Color, ContextMenu, DecoratedIcon, Divider, Icon, IconDecoration, IconDecorationKind,
  58    IndentGuideColors, IndentGuideLayout, KeyBinding, Label, LabelSize, ListItem, ListItemSpacing,
  59    ScrollAxes, ScrollableHandle, Scrollbars, StickyCandidate, Tooltip, WithScrollbar, prelude::*,
  60    v_flex,
  61};
  62use util::{ResultExt, TakeUntilExt, TryFutureExt, maybe, paths::compare_paths, rel_path::RelPath};
  63use workspace::{
  64    DraggedSelection, OpenInTerminal, OpenOptions, OpenVisible, PreviewTabsSettings, SelectedEntry,
  65    SplitDirection, Workspace,
  66    dock::{DockPosition, Panel, PanelEvent},
  67    notifications::{DetachAndPromptErr, NotifyTaskExt},
  68};
  69use worktree::CreatedEntry;
  70use zed_actions::workspace::OpenWithSystem;
  71
  72const PROJECT_PANEL_KEY: &str = "ProjectPanel";
  73const NEW_ENTRY_ID: ProjectEntryId = ProjectEntryId::MAX;
  74
  75struct VisibleEntriesForWorktree {
  76    worktree_id: WorktreeId,
  77    entries: Vec<GitEntry>,
  78    index: OnceCell<HashSet<Arc<RelPath>>>,
  79}
  80
  81struct State {
  82    last_worktree_root_id: Option<ProjectEntryId>,
  83    /// Maps from leaf project entry ID to the currently selected ancestor.
  84    /// Relevant only for auto-fold dirs, where a single project panel entry may actually consist of several
  85    /// project entries (and all non-leaf nodes are guaranteed to be directories).
  86    ancestors: HashMap<ProjectEntryId, FoldedAncestors>,
  87    visible_entries: Vec<VisibleEntriesForWorktree>,
  88    max_width_item_index: Option<usize>,
  89    // Currently selected leaf entry (see auto-folding for a definition of that) in a file tree
  90    selection: Option<SelectedEntry>,
  91    edit_state: Option<EditState>,
  92    unfolded_dir_ids: HashSet<ProjectEntryId>,
  93    expanded_dir_ids: HashMap<WorktreeId, Vec<ProjectEntryId>>,
  94}
  95
  96impl State {
  97    fn derive(old: &Self) -> Self {
  98        Self {
  99            last_worktree_root_id: None,
 100            ancestors: Default::default(),
 101            visible_entries: Default::default(),
 102            max_width_item_index: None,
 103            edit_state: old.edit_state.clone(),
 104            unfolded_dir_ids: old.unfolded_dir_ids.clone(),
 105            selection: old.selection,
 106            expanded_dir_ids: old.expanded_dir_ids.clone(),
 107        }
 108    }
 109}
 110
 111pub struct ProjectPanel {
 112    project: Entity<Project>,
 113    fs: Arc<dyn Fs>,
 114    focus_handle: FocusHandle,
 115    scroll_handle: UniformListScrollHandle,
 116    // An update loop that keeps incrementing/decrementing scroll offset while there is a dragged entry that's
 117    // hovered over the start/end of a list.
 118    hover_scroll_task: Option<Task<()>>,
 119    rendered_entries_len: usize,
 120    folded_directory_drag_target: Option<FoldedDirectoryDragTarget>,
 121    drag_target_entry: Option<DragTarget>,
 122    marked_entries: Vec<SelectedEntry>,
 123    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 124    filename_editor: Entity<Editor>,
 125    clipboard: Option<ClipboardEntry>,
 126    _dragged_entry_destination: Option<Arc<Path>>,
 127    workspace: WeakEntity<Workspace>,
 128    width: Option<Pixels>,
 129    pending_serialization: Task<Option<()>>,
 130    diagnostics: HashMap<(WorktreeId, Arc<RelPath>), DiagnosticSeverity>,
 131    diagnostic_summary_update: Task<()>,
 132    // We keep track of the mouse down state on entries so we don't flash the UI
 133    // in case a user clicks to open a file.
 134    mouse_down: bool,
 135    hover_expand_task: Option<Task<()>>,
 136    previous_drag_position: Option<Point<Pixels>>,
 137    sticky_items_count: usize,
 138    last_reported_update: Instant,
 139    update_visible_entries_task: Task<()>,
 140    state: State,
 141}
 142
 143enum DragTarget {
 144    /// Dragging on an entry
 145    Entry {
 146        /// The entry currently under the mouse cursor during a drag operation
 147        entry_id: ProjectEntryId,
 148        /// Highlight this entry along with all of its children
 149        highlight_entry_id: ProjectEntryId,
 150    },
 151    /// Dragging on background
 152    Background,
 153}
 154
 155#[derive(Copy, Clone, Debug)]
 156struct FoldedDirectoryDragTarget {
 157    entry_id: ProjectEntryId,
 158    index: usize,
 159    /// Whether we are dragging over the delimiter rather than the component itself.
 160    is_delimiter_target: bool,
 161}
 162
 163#[derive(Clone, Debug)]
 164enum ValidationState {
 165    None,
 166    Warning(String),
 167    Error(String),
 168}
 169
 170#[derive(Clone, Debug)]
 171struct EditState {
 172    worktree_id: WorktreeId,
 173    entry_id: ProjectEntryId,
 174    leaf_entry_id: Option<ProjectEntryId>,
 175    is_dir: bool,
 176    depth: usize,
 177    processing_filename: Option<Arc<RelPath>>,
 178    previously_focused: Option<SelectedEntry>,
 179    validation_state: ValidationState,
 180}
 181
 182impl EditState {
 183    fn is_new_entry(&self) -> bool {
 184        self.leaf_entry_id.is_none()
 185    }
 186}
 187
 188#[derive(Clone, Debug)]
 189enum ClipboardEntry {
 190    Copied(BTreeSet<SelectedEntry>),
 191    Cut(BTreeSet<SelectedEntry>),
 192}
 193
 194#[derive(Debug, PartialEq, Eq, Clone)]
 195struct EntryDetails {
 196    filename: String,
 197    icon: Option<SharedString>,
 198    path: Arc<RelPath>,
 199    depth: usize,
 200    kind: EntryKind,
 201    is_ignored: bool,
 202    is_expanded: bool,
 203    is_selected: bool,
 204    is_marked: bool,
 205    is_editing: bool,
 206    is_processing: bool,
 207    is_cut: bool,
 208    sticky: Option<StickyDetails>,
 209    filename_text_color: Color,
 210    diagnostic_severity: Option<DiagnosticSeverity>,
 211    git_status: GitSummary,
 212    is_private: bool,
 213    worktree_id: WorktreeId,
 214    canonical_path: Option<Arc<Path>>,
 215}
 216
 217#[derive(Debug, PartialEq, Eq, Clone)]
 218struct StickyDetails {
 219    sticky_index: usize,
 220}
 221
 222/// Permanently deletes the selected file or directory.
 223#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
 224#[action(namespace = project_panel)]
 225#[serde(deny_unknown_fields)]
 226struct Delete {
 227    #[serde(default)]
 228    pub skip_prompt: bool,
 229}
 230
 231/// Moves the selected file or directory to the system trash.
 232#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
 233#[action(namespace = project_panel)]
 234#[serde(deny_unknown_fields)]
 235struct Trash {
 236    #[serde(default)]
 237    pub skip_prompt: bool,
 238}
 239
 240/// Selects the next entry with diagnostics.
 241#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
 242#[action(namespace = project_panel)]
 243#[serde(deny_unknown_fields)]
 244struct SelectNextDiagnostic {
 245    #[serde(default)]
 246    pub severity: GoToDiagnosticSeverityFilter,
 247}
 248
 249/// Selects the previous entry with diagnostics.
 250#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
 251#[action(namespace = project_panel)]
 252#[serde(deny_unknown_fields)]
 253struct SelectPrevDiagnostic {
 254    #[serde(default)]
 255    pub severity: GoToDiagnosticSeverityFilter,
 256}
 257
 258actions!(
 259    project_panel,
 260    [
 261        /// Expands the selected entry in the project tree.
 262        ExpandSelectedEntry,
 263        /// Collapses the selected entry in the project tree.
 264        CollapseSelectedEntry,
 265        /// Collapses all entries in the project tree.
 266        CollapseAllEntries,
 267        /// Creates a new directory.
 268        NewDirectory,
 269        /// Creates a new file.
 270        NewFile,
 271        /// Copies the selected file or directory.
 272        Copy,
 273        /// Duplicates the selected file or directory.
 274        Duplicate,
 275        /// Reveals the selected item in the system file manager.
 276        RevealInFileManager,
 277        /// Removes the selected folder from the project.
 278        RemoveFromProject,
 279        /// Cuts the selected file or directory.
 280        Cut,
 281        /// Pastes the previously cut or copied item.
 282        Paste,
 283        /// Renames the selected file or directory.
 284        Rename,
 285        /// Opens the selected file in the editor.
 286        Open,
 287        /// Opens the selected file in a permanent tab.
 288        OpenPermanent,
 289        /// Opens the selected file in a vertical split.
 290        OpenSplitVertical,
 291        /// Opens the selected file in a horizontal split.
 292        OpenSplitHorizontal,
 293        /// Toggles focus on the project panel.
 294        ToggleFocus,
 295        /// Toggles visibility of git-ignored files.
 296        ToggleHideGitIgnore,
 297        /// Starts a new search in the selected directory.
 298        NewSearchInDirectory,
 299        /// Unfolds the selected directory.
 300        UnfoldDirectory,
 301        /// Folds the selected directory.
 302        FoldDirectory,
 303        /// Scroll half a page upwards
 304        ScrollUp,
 305        /// Scroll half a page downwards
 306        ScrollDown,
 307        /// Scroll until the cursor displays at the center
 308        ScrollCursorCenter,
 309        /// Scroll until the cursor displays at the top
 310        ScrollCursorTop,
 311        /// Scroll until the cursor displays at the bottom
 312        ScrollCursorBottom,
 313        /// Selects the parent directory.
 314        SelectParent,
 315        /// Selects the next entry with git changes.
 316        SelectNextGitEntry,
 317        /// Selects the previous entry with git changes.
 318        SelectPrevGitEntry,
 319        /// Selects the next directory.
 320        SelectNextDirectory,
 321        /// Selects the previous directory.
 322        SelectPrevDirectory,
 323        /// Opens a diff view to compare two marked files.
 324        CompareMarkedFiles,
 325    ]
 326);
 327
 328#[derive(Clone, Debug, Default)]
 329struct FoldedAncestors {
 330    current_ancestor_depth: usize,
 331    ancestors: Vec<ProjectEntryId>,
 332}
 333
 334impl FoldedAncestors {
 335    fn max_ancestor_depth(&self) -> usize {
 336        self.ancestors.len()
 337    }
 338
 339    /// Note: This returns None for last item in ancestors list
 340    fn active_ancestor(&self) -> Option<ProjectEntryId> {
 341        if self.current_ancestor_depth == 0 {
 342            return None;
 343        }
 344        self.ancestors.get(self.current_ancestor_depth).copied()
 345    }
 346
 347    fn active_index(&self) -> usize {
 348        self.max_ancestor_depth()
 349            .saturating_sub(1)
 350            .saturating_sub(self.current_ancestor_depth)
 351    }
 352
 353    fn active_component(&self, file_name: &str) -> Option<String> {
 354        Path::new(file_name)
 355            .components()
 356            .nth(self.active_index())
 357            .map(|comp| comp.as_os_str().to_string_lossy().into_owned())
 358    }
 359}
 360
 361pub fn init_settings(cx: &mut App) {
 362    ProjectPanelSettings::register(cx);
 363}
 364
 365pub fn init(cx: &mut App) {
 366    init_settings(cx);
 367
 368    cx.observe_new(|workspace: &mut Workspace, _, _| {
 369        workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
 370            workspace.toggle_panel_focus::<ProjectPanel>(window, cx);
 371        });
 372
 373        workspace.register_action(|workspace, _: &ToggleHideGitIgnore, _, cx| {
 374            let fs = workspace.app_state().fs.clone();
 375            update_settings_file(fs, cx, move |setting, _| {
 376                setting.project_panel.get_or_insert_default().hide_gitignore = Some(
 377                    !setting
 378                        .project_panel
 379                        .get_or_insert_default()
 380                        .hide_gitignore
 381                        .unwrap_or(false),
 382                );
 383            })
 384        });
 385
 386        workspace.register_action(|workspace, action: &CollapseAllEntries, window, cx| {
 387            if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
 388                panel.update(cx, |panel, cx| {
 389                    panel.collapse_all_entries(action, window, cx);
 390                });
 391            }
 392        });
 393
 394        workspace.register_action(|workspace, action: &Rename, window, cx| {
 395            workspace.open_panel::<ProjectPanel>(window, cx);
 396            if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
 397                panel.update(cx, |panel, cx| {
 398                    if let Some(first_marked) = panel.marked_entries.first() {
 399                        let first_marked = *first_marked;
 400                        panel.marked_entries.clear();
 401                        panel.state.selection = Some(first_marked);
 402                    }
 403                    panel.rename(action, window, cx);
 404                });
 405            }
 406        });
 407
 408        workspace.register_action(|workspace, action: &Duplicate, window, cx| {
 409            workspace.open_panel::<ProjectPanel>(window, cx);
 410            if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
 411                panel.update(cx, |panel, cx| {
 412                    panel.duplicate(action, window, cx);
 413                });
 414            }
 415        });
 416
 417        workspace.register_action(|workspace, action: &Delete, window, cx| {
 418            if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
 419                panel.update(cx, |panel, cx| panel.delete(action, window, cx));
 420            }
 421        });
 422    })
 423    .detach();
 424}
 425
 426#[derive(Debug)]
 427pub enum Event {
 428    OpenedEntry {
 429        entry_id: ProjectEntryId,
 430        focus_opened_item: bool,
 431        allow_preview: bool,
 432    },
 433    SplitEntry {
 434        entry_id: ProjectEntryId,
 435        allow_preview: bool,
 436        split_direction: Option<SplitDirection>,
 437    },
 438    Focus,
 439}
 440
 441#[derive(Serialize, Deserialize)]
 442struct SerializedProjectPanel {
 443    width: Option<Pixels>,
 444}
 445
 446struct DraggedProjectEntryView {
 447    selection: SelectedEntry,
 448    icon: Option<SharedString>,
 449    filename: String,
 450    click_offset: Point<Pixels>,
 451    selections: Arc<[SelectedEntry]>,
 452}
 453
 454struct ItemColors {
 455    default: Hsla,
 456    hover: Hsla,
 457    drag_over: Hsla,
 458    marked: Hsla,
 459    focused: Hsla,
 460}
 461
 462fn get_item_color(is_sticky: bool, cx: &App) -> ItemColors {
 463    let colors = cx.theme().colors();
 464
 465    ItemColors {
 466        default: if is_sticky {
 467            colors.panel_overlay_background
 468        } else {
 469            colors.panel_background
 470        },
 471        hover: if is_sticky {
 472            colors.panel_overlay_hover
 473        } else {
 474            colors.element_hover
 475        },
 476        marked: colors.element_selected,
 477        focused: colors.panel_focused_border,
 478        drag_over: colors.drop_target_background,
 479    }
 480}
 481
 482impl ProjectPanel {
 483    fn new(
 484        workspace: &mut Workspace,
 485        window: &mut Window,
 486        cx: &mut Context<Workspace>,
 487    ) -> Entity<Self> {
 488        let project = workspace.project().clone();
 489        let git_store = project.read(cx).git_store().clone();
 490        let path_style = project.read(cx).path_style(cx);
 491        let project_panel = cx.new(|cx| {
 492            let focus_handle = cx.focus_handle();
 493            cx.on_focus(&focus_handle, window, Self::focus_in).detach();
 494            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 495                this.focus_out(window, cx);
 496            })
 497            .detach();
 498
 499            cx.subscribe_in(
 500                &git_store,
 501                window,
 502                |this, _, event, window, cx| match event {
 503                    GitStoreEvent::RepositoryUpdated(_, RepositoryEvent::Updated { .. }, _)
 504                    | GitStoreEvent::RepositoryAdded(_)
 505                    | GitStoreEvent::RepositoryRemoved(_) => {
 506                        this.update_visible_entries(None, false, false, window, cx);
 507                        cx.notify();
 508                    }
 509                    _ => {}
 510                },
 511            )
 512            .detach();
 513
 514            cx.subscribe_in(
 515                &project,
 516                window,
 517                |this, project, event, window, cx| match event {
 518                    project::Event::ActiveEntryChanged(Some(entry_id)) => {
 519                        if ProjectPanelSettings::get_global(cx).auto_reveal_entries {
 520                            this.reveal_entry(project.clone(), *entry_id, true, window, cx)
 521                                .ok();
 522                        }
 523                    }
 524                    project::Event::ActiveEntryChanged(None) => {
 525                        let is_active_item_file_diff_view = this
 526                            .workspace
 527                            .upgrade()
 528                            .and_then(|ws| ws.read(cx).active_item(cx))
 529                            .map(|item| {
 530                                item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some()
 531                            })
 532                            .unwrap_or(false);
 533                        if !is_active_item_file_diff_view {
 534                            this.marked_entries.clear();
 535                        }
 536                    }
 537                    project::Event::RevealInProjectPanel(entry_id) => {
 538                        if let Some(()) = this
 539                            .reveal_entry(project.clone(), *entry_id, false, window, cx)
 540                            .log_err()
 541                        {
 542                            cx.emit(PanelEvent::Activate);
 543                        }
 544                    }
 545                    project::Event::ActivateProjectPanel => {
 546                        cx.emit(PanelEvent::Activate);
 547                    }
 548                    project::Event::DiskBasedDiagnosticsFinished { .. }
 549                    | project::Event::DiagnosticsUpdated { .. } => {
 550                        if ProjectPanelSettings::get_global(cx).show_diagnostics
 551                            != ShowDiagnostics::Off
 552                        {
 553                            this.diagnostic_summary_update = cx.spawn(async move |this, cx| {
 554                                cx.background_executor()
 555                                    .timer(Duration::from_millis(30))
 556                                    .await;
 557                                this.update(cx, |this, cx| {
 558                                    this.update_diagnostics(cx);
 559                                    cx.notify();
 560                                })
 561                                .log_err();
 562                            });
 563                        }
 564                    }
 565                    project::Event::WorktreeRemoved(id) => {
 566                        this.state.expanded_dir_ids.remove(id);
 567                        this.update_visible_entries(None, false, false, window, cx);
 568                        cx.notify();
 569                    }
 570                    project::Event::WorktreeUpdatedEntries(_, _)
 571                    | project::Event::WorktreeAdded(_)
 572                    | project::Event::WorktreeOrderChanged => {
 573                        this.update_visible_entries(None, false, false, window, cx);
 574                        cx.notify();
 575                    }
 576                    project::Event::ExpandedAllForEntry(worktree_id, entry_id) => {
 577                        if let Some((worktree, expanded_dir_ids)) = project
 578                            .read(cx)
 579                            .worktree_for_id(*worktree_id, cx)
 580                            .zip(this.state.expanded_dir_ids.get_mut(worktree_id))
 581                        {
 582                            let worktree = worktree.read(cx);
 583
 584                            let Some(entry) = worktree.entry_for_id(*entry_id) else {
 585                                return;
 586                            };
 587                            let include_ignored_dirs = !entry.is_ignored;
 588
 589                            let mut dirs_to_expand = vec![*entry_id];
 590                            while let Some(current_id) = dirs_to_expand.pop() {
 591                                let Some(current_entry) = worktree.entry_for_id(current_id) else {
 592                                    continue;
 593                                };
 594                                for child in worktree.child_entries(¤t_entry.path) {
 595                                    if !child.is_dir() || (include_ignored_dirs && child.is_ignored)
 596                                    {
 597                                        continue;
 598                                    }
 599
 600                                    dirs_to_expand.push(child.id);
 601
 602                                    if let Err(ix) = expanded_dir_ids.binary_search(&child.id) {
 603                                        expanded_dir_ids.insert(ix, child.id);
 604                                    }
 605                                    this.state.unfolded_dir_ids.insert(child.id);
 606                                }
 607                            }
 608                            this.update_visible_entries(None, false, false, window, cx);
 609                            cx.notify();
 610                        }
 611                    }
 612                    _ => {}
 613                },
 614            )
 615            .detach();
 616
 617            let trash_action = [TypeId::of::<Trash>()];
 618            let is_remote = project.read(cx).is_via_collab();
 619
 620            if is_remote {
 621                CommandPaletteFilter::update_global(cx, |filter, _cx| {
 622                    filter.hide_action_types(&trash_action);
 623                });
 624            }
 625
 626            let filename_editor = cx.new(|cx| Editor::single_line(window, cx));
 627
 628            cx.subscribe_in(
 629                &filename_editor,
 630                window,
 631                |project_panel, _, editor_event, window, cx| match editor_event {
 632                    EditorEvent::BufferEdited => {
 633                        project_panel.populate_validation_error(cx);
 634                        project_panel.autoscroll(cx);
 635                    }
 636                    EditorEvent::SelectionsChanged { .. } => {
 637                        project_panel.autoscroll(cx);
 638                    }
 639                    EditorEvent::Blurred => {
 640                        if project_panel
 641                            .state
 642                            .edit_state
 643                            .as_ref()
 644                            .is_some_and(|state| state.processing_filename.is_none())
 645                        {
 646                            match project_panel.confirm_edit(window, cx) {
 647                                Some(task) => {
 648                                    task.detach_and_notify_err(window, cx);
 649                                }
 650                                None => {
 651                                    project_panel.state.edit_state = None;
 652                                    project_panel
 653                                        .update_visible_entries(None, false, false, window, cx);
 654                                    cx.notify();
 655                                }
 656                            }
 657                        }
 658                    }
 659                    _ => {}
 660                },
 661            )
 662            .detach();
 663
 664            cx.observe_global::<FileIcons>(|_, cx| {
 665                cx.notify();
 666            })
 667            .detach();
 668
 669            let mut project_panel_settings = *ProjectPanelSettings::get_global(cx);
 670            cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
 671                let new_settings = *ProjectPanelSettings::get_global(cx);
 672                if project_panel_settings != new_settings {
 673                    if project_panel_settings.hide_gitignore != new_settings.hide_gitignore {
 674                        this.update_visible_entries(None, false, false, window, cx);
 675                    }
 676                    if project_panel_settings.hide_root != new_settings.hide_root {
 677                        this.update_visible_entries(None, false, false, window, cx);
 678                    }
 679                    if project_panel_settings.hide_hidden != new_settings.hide_hidden {
 680                        this.update_visible_entries(None, false, false, window, cx);
 681                    }
 682                    if project_panel_settings.sticky_scroll && !new_settings.sticky_scroll {
 683                        this.sticky_items_count = 0;
 684                    }
 685                    project_panel_settings = new_settings;
 686                    this.update_diagnostics(cx);
 687                    cx.notify();
 688                }
 689            })
 690            .detach();
 691
 692            let scroll_handle = UniformListScrollHandle::new();
 693            let mut this = Self {
 694                project: project.clone(),
 695                hover_scroll_task: None,
 696                fs: workspace.app_state().fs.clone(),
 697                focus_handle,
 698                rendered_entries_len: 0,
 699                folded_directory_drag_target: None,
 700                drag_target_entry: None,
 701
 702                marked_entries: Default::default(),
 703                context_menu: None,
 704                filename_editor,
 705                clipboard: None,
 706                _dragged_entry_destination: None,
 707                workspace: workspace.weak_handle(),
 708                width: None,
 709                pending_serialization: Task::ready(None),
 710                diagnostics: Default::default(),
 711                diagnostic_summary_update: Task::ready(()),
 712                scroll_handle,
 713                mouse_down: false,
 714                hover_expand_task: None,
 715                previous_drag_position: None,
 716                sticky_items_count: 0,
 717                last_reported_update: Instant::now(),
 718                state: State {
 719                    max_width_item_index: None,
 720                    edit_state: None,
 721                    selection: None,
 722                    last_worktree_root_id: Default::default(),
 723                    visible_entries: Default::default(),
 724                    ancestors: Default::default(),
 725                    expanded_dir_ids: Default::default(),
 726                    unfolded_dir_ids: Default::default(),
 727                },
 728                update_visible_entries_task: Task::ready(()),
 729            };
 730            this.update_visible_entries(None, false, false, window, cx);
 731
 732            this
 733        });
 734
 735        cx.subscribe_in(&project_panel, window, {
 736            let project_panel = project_panel.downgrade();
 737            move |workspace, _, event, window, cx| match event {
 738                &Event::OpenedEntry {
 739                    entry_id,
 740                    focus_opened_item,
 741                    allow_preview,
 742                } => {
 743                    if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx)
 744                        && let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
 745                            let file_path = entry.path.clone();
 746                            let worktree_id = worktree.read(cx).id();
 747                            let entry_id = entry.id;
 748                            let is_via_ssh = project.read(cx).is_via_remote_server();
 749
 750                            workspace
 751                                .open_path_preview(
 752                                    ProjectPath {
 753                                        worktree_id,
 754                                        path: file_path.clone(),
 755                                    },
 756                                    None,
 757                                    focus_opened_item,
 758                                    allow_preview,
 759                                    true,
 760                                    window, cx,
 761                                )
 762                                .detach_and_prompt_err("Failed to open file", window, cx, move |e, _, _| {
 763                                    match e.error_code() {
 764                                        ErrorCode::Disconnected => if is_via_ssh {
 765                                            Some("Disconnected from SSH host".to_string())
 766                                        } else {
 767                                            Some("Disconnected from remote project".to_string())
 768                                        },
 769                                        ErrorCode::UnsharedItem => Some(format!(
 770                                            "{} is not shared by the host. This could be because it has been marked as `private`",
 771                                            file_path.display(path_style)
 772                                        )),
 773                                        // See note in worktree.rs where this error originates. Returning Some in this case prevents
 774                                        // the error popup from saying "Try Again", which is a red herring in this case
 775                                        ErrorCode::Internal if e.to_string().contains("File is too large to load") => Some(e.to_string()),
 776                                        _ => None,
 777                                    }
 778                                });
 779
 780                            if let Some(project_panel) = project_panel.upgrade() {
 781                                // Always select and mark the entry, regardless of whether it is opened or not.
 782                                project_panel.update(cx, |project_panel, _| {
 783                                    let entry = SelectedEntry { worktree_id, entry_id };
 784                                    project_panel.marked_entries.clear();
 785                                    project_panel.marked_entries.push(entry);
 786                                    project_panel.state.selection = Some(entry);
 787                                });
 788                                if !focus_opened_item {
 789                                    let focus_handle = project_panel.read(cx).focus_handle.clone();
 790                                    window.focus(&focus_handle);
 791                                }
 792                            }
 793                        }
 794                }
 795                &Event::SplitEntry {
 796                    entry_id,
 797                    allow_preview,
 798                    split_direction,
 799                } => {
 800                    if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx)
 801                        && let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
 802                            workspace
 803                                .split_path_preview(
 804                                    ProjectPath {
 805                                        worktree_id: worktree.read(cx).id(),
 806                                        path: entry.path.clone(),
 807                                    },
 808                                    allow_preview,
 809                                    split_direction,
 810                                    window, cx,
 811                                )
 812                                .detach_and_log_err(cx);
 813                        }
 814                }
 815
 816                _ => {}
 817            }
 818        })
 819        .detach();
 820
 821        project_panel
 822    }
 823
 824    pub async fn load(
 825        workspace: WeakEntity<Workspace>,
 826        mut cx: AsyncWindowContext,
 827    ) -> Result<Entity<Self>> {
 828        let serialized_panel = match workspace
 829            .read_with(&cx, |workspace, _| {
 830                ProjectPanel::serialization_key(workspace)
 831            })
 832            .ok()
 833            .flatten()
 834        {
 835            Some(serialization_key) => cx
 836                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 837                .await
 838                .context("loading project panel")
 839                .log_err()
 840                .flatten()
 841                .map(|panel| serde_json::from_str::<SerializedProjectPanel>(&panel))
 842                .transpose()
 843                .log_err()
 844                .flatten(),
 845            None => None,
 846        };
 847
 848        workspace.update_in(&mut cx, |workspace, window, cx| {
 849            let panel = ProjectPanel::new(workspace, window, cx);
 850            if let Some(serialized_panel) = serialized_panel {
 851                panel.update(cx, |panel, cx| {
 852                    panel.width = serialized_panel.width.map(|px| px.round());
 853                    cx.notify();
 854                });
 855            }
 856            panel
 857        })
 858    }
 859
 860    fn update_diagnostics(&mut self, cx: &mut Context<Self>) {
 861        let mut diagnostics: HashMap<(WorktreeId, Arc<RelPath>), DiagnosticSeverity> =
 862            Default::default();
 863        let show_diagnostics_setting = ProjectPanelSettings::get_global(cx).show_diagnostics;
 864
 865        if show_diagnostics_setting != ShowDiagnostics::Off {
 866            self.project
 867                .read(cx)
 868                .diagnostic_summaries(false, cx)
 869                .filter_map(|(path, _, diagnostic_summary)| {
 870                    if diagnostic_summary.error_count > 0 {
 871                        Some((path, DiagnosticSeverity::ERROR))
 872                    } else if show_diagnostics_setting == ShowDiagnostics::All
 873                        && diagnostic_summary.warning_count > 0
 874                    {
 875                        Some((path, DiagnosticSeverity::WARNING))
 876                    } else {
 877                        None
 878                    }
 879                })
 880                .for_each(|(project_path, diagnostic_severity)| {
 881                    let ancestors = project_path.path.ancestors().collect::<Vec<_>>();
 882                    for path in ancestors.into_iter().rev() {
 883                        Self::update_strongest_diagnostic_severity(
 884                            &mut diagnostics,
 885                            &project_path,
 886                            path.into(),
 887                            diagnostic_severity,
 888                        );
 889                    }
 890                });
 891        }
 892        self.diagnostics = diagnostics;
 893    }
 894
 895    fn update_strongest_diagnostic_severity(
 896        diagnostics: &mut HashMap<(WorktreeId, Arc<RelPath>), DiagnosticSeverity>,
 897        project_path: &ProjectPath,
 898        path_buffer: Arc<RelPath>,
 899        diagnostic_severity: DiagnosticSeverity,
 900    ) {
 901        diagnostics
 902            .entry((project_path.worktree_id, path_buffer))
 903            .and_modify(|strongest_diagnostic_severity| {
 904                *strongest_diagnostic_severity =
 905                    cmp::min(*strongest_diagnostic_severity, diagnostic_severity);
 906            })
 907            .or_insert(diagnostic_severity);
 908    }
 909
 910    fn serialization_key(workspace: &Workspace) -> Option<String> {
 911        workspace
 912            .database_id()
 913            .map(|id| i64::from(id).to_string())
 914            .or(workspace.session_id())
 915            .map(|id| format!("{}-{:?}", PROJECT_PANEL_KEY, id))
 916    }
 917
 918    fn serialize(&mut self, cx: &mut Context<Self>) {
 919        let Some(serialization_key) = self
 920            .workspace
 921            .read_with(cx, |workspace, _| {
 922                ProjectPanel::serialization_key(workspace)
 923            })
 924            .ok()
 925            .flatten()
 926        else {
 927            return;
 928        };
 929        let width = self.width;
 930        self.pending_serialization = cx.background_spawn(
 931            async move {
 932                KEY_VALUE_STORE
 933                    .write_kvp(
 934                        serialization_key,
 935                        serde_json::to_string(&SerializedProjectPanel { width })?,
 936                    )
 937                    .await?;
 938                anyhow::Ok(())
 939            }
 940            .log_err(),
 941        );
 942    }
 943
 944    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 945        if !self.focus_handle.contains_focused(window, cx) {
 946            cx.emit(Event::Focus);
 947        }
 948    }
 949
 950    fn focus_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 951        if !self.focus_handle.is_focused(window) {
 952            self.confirm(&Confirm, window, cx);
 953        }
 954    }
 955
 956    fn deploy_context_menu(
 957        &mut self,
 958        position: Point<Pixels>,
 959        entry_id: ProjectEntryId,
 960        window: &mut Window,
 961        cx: &mut Context<Self>,
 962    ) {
 963        let project = self.project.read(cx);
 964
 965        let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) {
 966            id
 967        } else {
 968            return;
 969        };
 970
 971        self.state.selection = Some(SelectedEntry {
 972            worktree_id,
 973            entry_id,
 974        });
 975
 976        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
 977            let auto_fold_dirs = ProjectPanelSettings::get_global(cx).auto_fold_dirs;
 978            let worktree = worktree.read(cx);
 979            let is_root = Some(entry) == worktree.root_entry();
 980            let is_dir = entry.is_dir();
 981            let is_foldable = auto_fold_dirs && self.is_foldable(entry, worktree);
 982            let is_unfoldable = auto_fold_dirs && self.is_unfoldable(entry, worktree);
 983            let is_read_only = project.is_read_only(cx);
 984            let is_remote = project.is_via_collab();
 985            let is_local = project.is_local();
 986
 987            let settings = ProjectPanelSettings::get_global(cx);
 988            let visible_worktrees_count = project.visible_worktrees(cx).count();
 989            let should_hide_rename = is_root
 990                && (cfg!(target_os = "windows")
 991                    || (settings.hide_root && visible_worktrees_count == 1));
 992            let should_show_compare = !is_dir && self.file_abs_paths_to_diff(cx).is_some();
 993
 994            let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
 995                menu.context(self.focus_handle.clone()).map(|menu| {
 996                    if is_read_only {
 997                        menu.when(is_dir, |menu| {
 998                            menu.action("Search Inside", Box::new(NewSearchInDirectory))
 999                        })
1000                    } else {
1001                        menu.action("New File", Box::new(NewFile))
1002                            .action("New Folder", Box::new(NewDirectory))
1003                            .separator()
1004                            .when(is_local && cfg!(target_os = "macos"), |menu| {
1005                                menu.action("Reveal in Finder", Box::new(RevealInFileManager))
1006                            })
1007                            .when(is_local && cfg!(not(target_os = "macos")), |menu| {
1008                                menu.action("Reveal in File Manager", Box::new(RevealInFileManager))
1009                            })
1010                            .when(is_local, |menu| {
1011                                menu.action("Open in Default App", Box::new(OpenWithSystem))
1012                            })
1013                            .action("Open in Terminal", Box::new(OpenInTerminal))
1014                            .when(is_dir, |menu| {
1015                                menu.separator()
1016                                    .action("Find in Folder…", Box::new(NewSearchInDirectory))
1017                            })
1018                            .when(is_unfoldable, |menu| {
1019                                menu.action("Unfold Directory", Box::new(UnfoldDirectory))
1020                            })
1021                            .when(is_foldable, |menu| {
1022                                menu.action("Fold Directory", Box::new(FoldDirectory))
1023                            })
1024                            .when(should_show_compare, |menu| {
1025                                menu.separator()
1026                                    .action("Compare marked files", Box::new(CompareMarkedFiles))
1027                            })
1028                            .separator()
1029                            .action("Cut", Box::new(Cut))
1030                            .action("Copy", Box::new(Copy))
1031                            .action("Duplicate", Box::new(Duplicate))
1032                            // TODO: Paste should always be visible, cbut disabled when clipboard is empty
1033                            .action_disabled_when(
1034                                self.clipboard.as_ref().is_none(),
1035                                "Paste",
1036                                Box::new(Paste),
1037                            )
1038                            .separator()
1039                            .action("Copy Path", Box::new(zed_actions::workspace::CopyPath))
1040                            .action(
1041                                "Copy Relative Path",
1042                                Box::new(zed_actions::workspace::CopyRelativePath),
1043                            )
1044                            .separator()
1045                            .when(!should_hide_rename, |menu| {
1046                                menu.action("Rename", Box::new(Rename))
1047                            })
1048                            .when(!is_root & !is_remote, |menu| {
1049                                menu.action("Trash", Box::new(Trash { skip_prompt: false }))
1050                            })
1051                            .when(!is_root, |menu| {
1052                                menu.action("Delete", Box::new(Delete { skip_prompt: false }))
1053                            })
1054                            .when(!is_remote & is_root, |menu| {
1055                                menu.separator()
1056                                    .action(
1057                                        "Add Folder to Project…",
1058                                        Box::new(workspace::AddFolderToProject),
1059                                    )
1060                                    .action("Remove from Project", Box::new(RemoveFromProject))
1061                            })
1062                            .when(is_root, |menu| {
1063                                menu.separator()
1064                                    .action("Collapse All", Box::new(CollapseAllEntries))
1065                            })
1066                    }
1067                })
1068            });
1069
1070            window.focus(&context_menu.focus_handle(cx));
1071            let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
1072                this.context_menu.take();
1073                cx.notify();
1074            });
1075            self.context_menu = Some((context_menu, position, subscription));
1076        }
1077
1078        cx.notify();
1079    }
1080
1081    fn is_unfoldable(&self, entry: &Entry, worktree: &Worktree) -> bool {
1082        if !entry.is_dir() || self.state.unfolded_dir_ids.contains(&entry.id) {
1083            return false;
1084        }
1085
1086        if let Some(parent_path) = entry.path.parent() {
1087            let snapshot = worktree.snapshot();
1088            let mut child_entries = snapshot.child_entries(parent_path);
1089            if let Some(child) = child_entries.next()
1090                && child_entries.next().is_none()
1091            {
1092                return child.kind.is_dir();
1093            }
1094        };
1095        false
1096    }
1097
1098    fn is_foldable(&self, entry: &Entry, worktree: &Worktree) -> bool {
1099        if entry.is_dir() {
1100            let snapshot = worktree.snapshot();
1101
1102            let mut child_entries = snapshot.child_entries(&entry.path);
1103            if let Some(child) = child_entries.next()
1104                && child_entries.next().is_none()
1105            {
1106                return child.kind.is_dir();
1107            }
1108        }
1109        false
1110    }
1111
1112    fn expand_selected_entry(
1113        &mut self,
1114        _: &ExpandSelectedEntry,
1115        window: &mut Window,
1116        cx: &mut Context<Self>,
1117    ) {
1118        if let Some((worktree, entry)) = self.selected_entry(cx) {
1119            if let Some(folded_ancestors) = self.state.ancestors.get_mut(&entry.id)
1120                && folded_ancestors.current_ancestor_depth > 0
1121            {
1122                folded_ancestors.current_ancestor_depth -= 1;
1123                cx.notify();
1124                return;
1125            }
1126            if entry.is_dir() {
1127                let worktree_id = worktree.id();
1128                let entry_id = entry.id;
1129                let expanded_dir_ids = if let Some(expanded_dir_ids) =
1130                    self.state.expanded_dir_ids.get_mut(&worktree_id)
1131                {
1132                    expanded_dir_ids
1133                } else {
1134                    return;
1135                };
1136
1137                match expanded_dir_ids.binary_search(&entry_id) {
1138                    Ok(_) => self.select_next(&SelectNext, window, cx),
1139                    Err(ix) => {
1140                        self.project.update(cx, |project, cx| {
1141                            project.expand_entry(worktree_id, entry_id, cx);
1142                        });
1143
1144                        expanded_dir_ids.insert(ix, entry_id);
1145                        self.update_visible_entries(None, false, false, window, cx);
1146                        cx.notify();
1147                    }
1148                }
1149            }
1150        }
1151    }
1152
1153    fn collapse_selected_entry(
1154        &mut self,
1155        _: &CollapseSelectedEntry,
1156        window: &mut Window,
1157        cx: &mut Context<Self>,
1158    ) {
1159        let Some((worktree, entry)) = self.selected_entry_handle(cx) else {
1160            return;
1161        };
1162        self.collapse_entry(entry.clone(), worktree, window, cx)
1163    }
1164
1165    fn collapse_entry(
1166        &mut self,
1167        entry: Entry,
1168        worktree: Entity<Worktree>,
1169        window: &mut Window,
1170        cx: &mut Context<Self>,
1171    ) {
1172        let worktree = worktree.read(cx);
1173        if let Some(folded_ancestors) = self.state.ancestors.get_mut(&entry.id)
1174            && folded_ancestors.current_ancestor_depth + 1 < folded_ancestors.max_ancestor_depth()
1175        {
1176            folded_ancestors.current_ancestor_depth += 1;
1177            cx.notify();
1178            return;
1179        }
1180        let worktree_id = worktree.id();
1181        let expanded_dir_ids =
1182            if let Some(expanded_dir_ids) = self.state.expanded_dir_ids.get_mut(&worktree_id) {
1183                expanded_dir_ids
1184            } else {
1185                return;
1186            };
1187
1188        let mut entry = &entry;
1189        loop {
1190            let entry_id = entry.id;
1191            match expanded_dir_ids.binary_search(&entry_id) {
1192                Ok(ix) => {
1193                    expanded_dir_ids.remove(ix);
1194                    self.update_visible_entries(
1195                        Some((worktree_id, entry_id)),
1196                        false,
1197                        false,
1198                        window,
1199                        cx,
1200                    );
1201                    cx.notify();
1202                    break;
1203                }
1204                Err(_) => {
1205                    if let Some(parent_entry) =
1206                        entry.path.parent().and_then(|p| worktree.entry_for_path(p))
1207                    {
1208                        entry = parent_entry;
1209                    } else {
1210                        break;
1211                    }
1212                }
1213            }
1214        }
1215    }
1216
1217    pub fn collapse_all_entries(
1218        &mut self,
1219        _: &CollapseAllEntries,
1220        window: &mut Window,
1221        cx: &mut Context<Self>,
1222    ) {
1223        // By keeping entries for fully collapsed worktrees, we avoid expanding them within update_visible_entries
1224        // (which is it's default behavior when there's no entry for a worktree in expanded_dir_ids).
1225        let multiple_worktrees = self.project.read(cx).worktrees(cx).count() > 1;
1226        let project = self.project.read(cx);
1227
1228        self.state
1229            .expanded_dir_ids
1230            .iter_mut()
1231            .for_each(|(worktree_id, expanded_entries)| {
1232                if multiple_worktrees {
1233                    *expanded_entries = Default::default();
1234                    return;
1235                }
1236
1237                let root_entry_id = project
1238                    .worktree_for_id(*worktree_id, cx)
1239                    .map(|worktree| worktree.read(cx).snapshot())
1240                    .and_then(|worktree_snapshot| {
1241                        worktree_snapshot.root_entry().map(|entry| entry.id)
1242                    });
1243
1244                match root_entry_id {
1245                    Some(id) => {
1246                        expanded_entries.retain(|entry_id| entry_id == &id);
1247                    }
1248                    None => *expanded_entries = Default::default(),
1249                };
1250            });
1251
1252        self.update_visible_entries(None, false, false, window, cx);
1253        cx.notify();
1254    }
1255
1256    fn toggle_expanded(
1257        &mut self,
1258        entry_id: ProjectEntryId,
1259        window: &mut Window,
1260        cx: &mut Context<Self>,
1261    ) {
1262        if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx)
1263            && let Some(expanded_dir_ids) = self.state.expanded_dir_ids.get_mut(&worktree_id)
1264        {
1265            self.project.update(cx, |project, cx| {
1266                match expanded_dir_ids.binary_search(&entry_id) {
1267                    Ok(ix) => {
1268                        expanded_dir_ids.remove(ix);
1269                    }
1270                    Err(ix) => {
1271                        project.expand_entry(worktree_id, entry_id, cx);
1272                        expanded_dir_ids.insert(ix, entry_id);
1273                    }
1274                }
1275            });
1276            self.update_visible_entries(Some((worktree_id, entry_id)), false, false, window, cx);
1277            window.focus(&self.focus_handle);
1278            cx.notify();
1279        }
1280    }
1281
1282    fn toggle_expand_all(
1283        &mut self,
1284        entry_id: ProjectEntryId,
1285        window: &mut Window,
1286        cx: &mut Context<Self>,
1287    ) {
1288        if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx)
1289            && let Some(expanded_dir_ids) = self.state.expanded_dir_ids.get_mut(&worktree_id)
1290        {
1291            match expanded_dir_ids.binary_search(&entry_id) {
1292                Ok(_ix) => {
1293                    self.collapse_all_for_entry(worktree_id, entry_id, cx);
1294                }
1295                Err(_ix) => {
1296                    self.expand_all_for_entry(worktree_id, entry_id, cx);
1297                }
1298            }
1299            self.update_visible_entries(Some((worktree_id, entry_id)), false, false, window, cx);
1300            window.focus(&self.focus_handle);
1301            cx.notify();
1302        }
1303    }
1304
1305    fn expand_all_for_entry(
1306        &mut self,
1307        worktree_id: WorktreeId,
1308        entry_id: ProjectEntryId,
1309        cx: &mut Context<Self>,
1310    ) {
1311        self.project.update(cx, |project, cx| {
1312            if let Some((worktree, expanded_dir_ids)) = project
1313                .worktree_for_id(worktree_id, cx)
1314                .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
1315            {
1316                if let Some(task) = project.expand_all_for_entry(worktree_id, entry_id, cx) {
1317                    task.detach();
1318                }
1319
1320                let worktree = worktree.read(cx);
1321
1322                if let Some(mut entry) = worktree.entry_for_id(entry_id) {
1323                    loop {
1324                        if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
1325                            expanded_dir_ids.insert(ix, entry.id);
1326                        }
1327
1328                        if let Some(parent_entry) =
1329                            entry.path.parent().and_then(|p| worktree.entry_for_path(p))
1330                        {
1331                            entry = parent_entry;
1332                        } else {
1333                            break;
1334                        }
1335                    }
1336                }
1337            }
1338        });
1339    }
1340
1341    fn collapse_all_for_entry(
1342        &mut self,
1343        worktree_id: WorktreeId,
1344        entry_id: ProjectEntryId,
1345        cx: &mut Context<Self>,
1346    ) {
1347        self.project.update(cx, |project, cx| {
1348            if let Some((worktree, expanded_dir_ids)) = project
1349                .worktree_for_id(worktree_id, cx)
1350                .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
1351            {
1352                let worktree = worktree.read(cx);
1353                let mut dirs_to_collapse = vec![entry_id];
1354                let auto_fold_enabled = ProjectPanelSettings::get_global(cx).auto_fold_dirs;
1355                while let Some(current_id) = dirs_to_collapse.pop() {
1356                    let Some(current_entry) = worktree.entry_for_id(current_id) else {
1357                        continue;
1358                    };
1359                    if let Ok(ix) = expanded_dir_ids.binary_search(¤t_id) {
1360                        expanded_dir_ids.remove(ix);
1361                    }
1362                    if auto_fold_enabled {
1363                        self.state.unfolded_dir_ids.remove(¤t_id);
1364                    }
1365                    for child in worktree.child_entries(¤t_entry.path) {
1366                        if child.is_dir() {
1367                            dirs_to_collapse.push(child.id);
1368                        }
1369                    }
1370                }
1371            }
1372        });
1373    }
1374
1375    fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
1376        if let Some(edit_state) = &self.state.edit_state
1377            && edit_state.processing_filename.is_none()
1378        {
1379            self.filename_editor.update(cx, |editor, cx| {
1380                editor.move_to_beginning_of_line(
1381                    &editor::actions::MoveToBeginningOfLine {
1382                        stop_at_soft_wraps: false,
1383                        stop_at_indent: false,
1384                    },
1385                    window,
1386                    cx,
1387                );
1388            });
1389            return;
1390        }
1391        if let Some(selection) = self.state.selection {
1392            let (mut worktree_ix, mut entry_ix, _) =
1393                self.index_for_selection(selection).unwrap_or_default();
1394            if entry_ix > 0 {
1395                entry_ix -= 1;
1396            } else if worktree_ix > 0 {
1397                worktree_ix -= 1;
1398                entry_ix = self.state.visible_entries[worktree_ix].entries.len() - 1;
1399            } else {
1400                return;
1401            }
1402
1403            let VisibleEntriesForWorktree {
1404                worktree_id,
1405                entries,
1406                ..
1407            } = &self.state.visible_entries[worktree_ix];
1408            let selection = SelectedEntry {
1409                worktree_id: *worktree_id,
1410                entry_id: entries[entry_ix].id,
1411            };
1412            self.state.selection = Some(selection);
1413            if window.modifiers().shift {
1414                self.marked_entries.push(selection);
1415            }
1416            self.autoscroll(cx);
1417            cx.notify();
1418        } else {
1419            self.select_first(&SelectFirst {}, window, cx);
1420        }
1421    }
1422
1423    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1424        if let Some(task) = self.confirm_edit(window, cx) {
1425            task.detach_and_notify_err(window, cx);
1426        }
1427    }
1428
1429    fn open(&mut self, _: &Open, window: &mut Window, cx: &mut Context<Self>) {
1430        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
1431        self.open_internal(true, !preview_tabs_enabled, None, window, cx);
1432    }
1433
1434    fn open_permanent(&mut self, _: &OpenPermanent, window: &mut Window, cx: &mut Context<Self>) {
1435        self.open_internal(false, true, None, window, cx);
1436    }
1437
1438    fn open_split_vertical(
1439        &mut self,
1440        _: &OpenSplitVertical,
1441        window: &mut Window,
1442        cx: &mut Context<Self>,
1443    ) {
1444        self.open_internal(false, true, Some(SplitDirection::vertical(cx)), window, cx);
1445    }
1446
1447    fn open_split_horizontal(
1448        &mut self,
1449        _: &OpenSplitHorizontal,
1450        window: &mut Window,
1451        cx: &mut Context<Self>,
1452    ) {
1453        self.open_internal(
1454            false,
1455            true,
1456            Some(SplitDirection::horizontal(cx)),
1457            window,
1458            cx,
1459        );
1460    }
1461
1462    fn open_internal(
1463        &mut self,
1464        allow_preview: bool,
1465        focus_opened_item: bool,
1466        split_direction: Option<SplitDirection>,
1467        window: &mut Window,
1468        cx: &mut Context<Self>,
1469    ) {
1470        if let Some((_, entry)) = self.selected_entry(cx) {
1471            if entry.is_file() {
1472                if split_direction.is_some() {
1473                    self.split_entry(entry.id, allow_preview, split_direction, cx);
1474                } else {
1475                    self.open_entry(entry.id, focus_opened_item, allow_preview, cx);
1476                }
1477                cx.notify();
1478            } else {
1479                self.toggle_expanded(entry.id, window, cx);
1480            }
1481        }
1482    }
1483
1484    fn populate_validation_error(&mut self, cx: &mut Context<Self>) {
1485        let edit_state = match self.state.edit_state.as_mut() {
1486            Some(state) => state,
1487            None => return,
1488        };
1489        let filename = self.filename_editor.read(cx).text(cx);
1490        if !filename.is_empty() {
1491            if filename.is_empty() {
1492                edit_state.validation_state =
1493                    ValidationState::Error("File or directory name cannot be empty.".to_string());
1494                cx.notify();
1495                return;
1496            }
1497
1498            let trimmed_filename = filename.trim();
1499            if trimmed_filename != filename {
1500                edit_state.validation_state = ValidationState::Warning(
1501                    "File or directory name contains leading or trailing whitespace.".to_string(),
1502                );
1503                cx.notify();
1504                return;
1505            }
1506            let trimmed_filename = trimmed_filename.trim_start_matches('/');
1507
1508            let Ok(filename) = RelPath::unix(trimmed_filename) else {
1509                edit_state.validation_state = ValidationState::Warning(
1510                    "File or directory name contains leading or trailing whitespace.".to_string(),
1511                );
1512                cx.notify();
1513                return;
1514            };
1515
1516            if let Some(worktree) = self
1517                .project
1518                .read(cx)
1519                .worktree_for_id(edit_state.worktree_id, cx)
1520                && let Some(entry) = worktree.read(cx).entry_for_id(edit_state.entry_id)
1521            {
1522                let mut already_exists = false;
1523                if edit_state.is_new_entry() {
1524                    let new_path = entry.path.join(filename);
1525                    if worktree.read(cx).entry_for_path(&new_path).is_some() {
1526                        already_exists = true;
1527                    }
1528                } else {
1529                    let new_path = if let Some(parent) = entry.path.clone().parent() {
1530                        parent.join(&filename)
1531                    } else {
1532                        filename.into()
1533                    };
1534                    if let Some(existing) = worktree.read(cx).entry_for_path(&new_path)
1535                        && existing.id != entry.id
1536                    {
1537                        already_exists = true;
1538                    }
1539                };
1540                if already_exists {
1541                    edit_state.validation_state = ValidationState::Error(format!(
1542                        "File or directory '{}' already exists at location. Please choose a different name.",
1543                        filename.as_unix_str()
1544                    ));
1545                    cx.notify();
1546                    return;
1547                }
1548            }
1549        }
1550        edit_state.validation_state = ValidationState::None;
1551        cx.notify();
1552    }
1553
1554    fn confirm_edit(
1555        &mut self,
1556        window: &mut Window,
1557        cx: &mut Context<Self>,
1558    ) -> Option<Task<Result<()>>> {
1559        let edit_state = self.state.edit_state.as_mut()?;
1560        let worktree_id = edit_state.worktree_id;
1561        let is_new_entry = edit_state.is_new_entry();
1562        let filename = self.filename_editor.read(cx).text(cx);
1563        if filename.trim().is_empty() {
1564            return None;
1565        }
1566
1567        let path_style = self.project.read(cx).path_style(cx);
1568        let filename_indicates_dir = if path_style.is_windows() {
1569            filename.ends_with('/') || filename.ends_with('\\')
1570        } else {
1571            filename.ends_with('/')
1572        };
1573        let filename = if path_style.is_windows() {
1574            filename.trim_start_matches(&['/', '\\'])
1575        } else {
1576            filename.trim_start_matches('/')
1577        };
1578        let filename = RelPath::new(filename.as_ref(), path_style).ok()?.into_arc();
1579
1580        edit_state.is_dir =
1581            edit_state.is_dir || (edit_state.is_new_entry() && filename_indicates_dir);
1582        let is_dir = edit_state.is_dir;
1583        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
1584        let entry = worktree.read(cx).entry_for_id(edit_state.entry_id)?.clone();
1585
1586        let edit_task;
1587        let edited_entry_id;
1588        if is_new_entry {
1589            self.state.selection = Some(SelectedEntry {
1590                worktree_id,
1591                entry_id: NEW_ENTRY_ID,
1592            });
1593            let new_path = entry.path.join(&filename);
1594            if worktree.read(cx).entry_for_path(&new_path).is_some() {
1595                return None;
1596            }
1597
1598            edited_entry_id = NEW_ENTRY_ID;
1599            edit_task = self.project.update(cx, |project, cx| {
1600                project.create_entry((worktree_id, new_path), is_dir, cx)
1601            });
1602        } else {
1603            let new_path = if let Some(parent) = entry.path.clone().parent() {
1604                parent.join(&filename)
1605            } else {
1606                filename.clone()
1607            };
1608            if let Some(existing) = worktree.read(cx).entry_for_path(&new_path) {
1609                if existing.id == entry.id {
1610                    window.focus(&self.focus_handle);
1611                }
1612                return None;
1613            }
1614            edited_entry_id = entry.id;
1615            edit_task = self.project.update(cx, |project, cx| {
1616                project.rename_entry(entry.id, (worktree_id, new_path).into(), cx)
1617            });
1618        };
1619
1620        window.focus(&self.focus_handle);
1621        edit_state.processing_filename = Some(filename);
1622        cx.notify();
1623
1624        Some(cx.spawn_in(window, async move |project_panel, cx| {
1625            let new_entry = edit_task.await;
1626            project_panel.update(cx, |project_panel, cx| {
1627                project_panel.state.edit_state = None;
1628                cx.notify();
1629            })?;
1630
1631            match new_entry {
1632                Err(e) => {
1633                    project_panel.update_in( cx, |project_panel, window, cx| {
1634                        project_panel.marked_entries.clear();
1635                        project_panel.update_visible_entries(None, false, false, window, cx);
1636                    }).ok();
1637                    Err(e)?;
1638                }
1639                Ok(CreatedEntry::Included(new_entry)) => {
1640                    project_panel.update_in( cx, |project_panel, window, cx| {
1641                        if let Some(selection) = &mut project_panel.state.selection
1642                            && selection.entry_id == edited_entry_id {
1643                                selection.worktree_id = worktree_id;
1644                                selection.entry_id = new_entry.id;
1645                                project_panel.marked_entries.clear();
1646                                project_panel.expand_to_selection(cx);
1647                            }
1648                        project_panel.update_visible_entries(None, false, false, window, cx);
1649                        if is_new_entry && !is_dir {
1650                            project_panel.open_entry(new_entry.id, true, false, cx);
1651                        }
1652                        cx.notify();
1653                    })?;
1654                }
1655                Ok(CreatedEntry::Excluded { abs_path }) => {
1656                    if let Some(open_task) = project_panel
1657                        .update_in(cx, |project_panel, window, cx| {
1658                            project_panel.marked_entries.clear();
1659                            project_panel.update_visible_entries(None, false, false, window, cx);
1660
1661                            if is_dir {
1662                                project_panel.project.update(cx, |_, cx| {
1663                                    cx.emit(project::Event::Toast {
1664                                        notification_id: "excluded-directory".into(),
1665                                        message: format!("Created an excluded directory at {abs_path:?}.\nAlter `file_scan_exclusions` in the settings to show it in the panel")
1666                                    })
1667                                });
1668                                None
1669                            } else {
1670                                project_panel
1671                                    .workspace
1672                                    .update(cx, |workspace, cx| {
1673                                        workspace.open_abs_path(abs_path, OpenOptions { visible: Some(OpenVisible::All), ..Default::default() }, window, cx)
1674                                    })
1675                                    .ok()
1676                            }
1677                        })
1678                        .ok()
1679                        .flatten()
1680                    {
1681                        let _ = open_task.await?;
1682                    }
1683                }
1684            }
1685            Ok(())
1686        }))
1687    }
1688
1689    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
1690        if cx.stop_active_drag(window) {
1691            self.drag_target_entry.take();
1692            self.hover_expand_task.take();
1693            return;
1694        }
1695
1696        let previous_edit_state = self.state.edit_state.take();
1697        self.update_visible_entries(None, false, false, window, cx);
1698        self.marked_entries.clear();
1699
1700        if let Some(previously_focused) =
1701            previous_edit_state.and_then(|edit_state| edit_state.previously_focused)
1702        {
1703            self.state.selection = Some(previously_focused);
1704            self.autoscroll(cx);
1705        }
1706
1707        window.focus(&self.focus_handle);
1708        cx.notify();
1709    }
1710
1711    fn open_entry(
1712        &mut self,
1713        entry_id: ProjectEntryId,
1714        focus_opened_item: bool,
1715        allow_preview: bool,
1716
1717        cx: &mut Context<Self>,
1718    ) {
1719        cx.emit(Event::OpenedEntry {
1720            entry_id,
1721            focus_opened_item,
1722            allow_preview,
1723        });
1724    }
1725
1726    fn split_entry(
1727        &mut self,
1728        entry_id: ProjectEntryId,
1729        allow_preview: bool,
1730        split_direction: Option<SplitDirection>,
1731
1732        cx: &mut Context<Self>,
1733    ) {
1734        cx.emit(Event::SplitEntry {
1735            entry_id,
1736            allow_preview,
1737            split_direction,
1738        });
1739    }
1740
1741    fn new_file(&mut self, _: &NewFile, window: &mut Window, cx: &mut Context<Self>) {
1742        self.add_entry(false, window, cx)
1743    }
1744
1745    fn new_directory(&mut self, _: &NewDirectory, window: &mut Window, cx: &mut Context<Self>) {
1746        self.add_entry(true, window, cx)
1747    }
1748
1749    fn add_entry(&mut self, is_dir: bool, window: &mut Window, cx: &mut Context<Self>) {
1750        let Some((worktree_id, entry_id)) = self
1751            .state
1752            .selection
1753            .map(|entry| (entry.worktree_id, entry.entry_id))
1754            .or_else(|| {
1755                let entry_id = self.state.last_worktree_root_id?;
1756                let worktree_id = self
1757                    .project
1758                    .read(cx)
1759                    .worktree_for_entry(entry_id, cx)?
1760                    .read(cx)
1761                    .id();
1762
1763                self.state.selection = Some(SelectedEntry {
1764                    worktree_id,
1765                    entry_id,
1766                });
1767
1768                Some((worktree_id, entry_id))
1769            })
1770        else {
1771            return;
1772        };
1773
1774        let directory_id;
1775        let new_entry_id = self.resolve_entry(entry_id);
1776        if let Some((worktree, expanded_dir_ids)) = self
1777            .project
1778            .read(cx)
1779            .worktree_for_id(worktree_id, cx)
1780            .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
1781        {
1782            let worktree = worktree.read(cx);
1783            if let Some(mut entry) = worktree.entry_for_id(new_entry_id) {
1784                loop {
1785                    if entry.is_dir() {
1786                        if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
1787                            expanded_dir_ids.insert(ix, entry.id);
1788                        }
1789                        directory_id = entry.id;
1790                        break;
1791                    } else {
1792                        if let Some(parent_path) = entry.path.parent()
1793                            && let Some(parent_entry) = worktree.entry_for_path(parent_path)
1794                        {
1795                            entry = parent_entry;
1796                            continue;
1797                        }
1798                        return;
1799                    }
1800                }
1801            } else {
1802                return;
1803            };
1804        } else {
1805            return;
1806        };
1807
1808        self.marked_entries.clear();
1809        self.state.edit_state = Some(EditState {
1810            worktree_id,
1811            entry_id: directory_id,
1812            leaf_entry_id: None,
1813            is_dir,
1814            processing_filename: None,
1815            previously_focused: self.state.selection,
1816            depth: 0,
1817            validation_state: ValidationState::None,
1818        });
1819        self.update_visible_entries(Some((worktree_id, NEW_ENTRY_ID)), true, true, window, cx);
1820        cx.notify();
1821    }
1822
1823    fn unflatten_entry_id(&self, leaf_entry_id: ProjectEntryId) -> ProjectEntryId {
1824        if let Some(ancestors) = self.state.ancestors.get(&leaf_entry_id) {
1825            ancestors
1826                .ancestors
1827                .get(ancestors.current_ancestor_depth)
1828                .copied()
1829                .unwrap_or(leaf_entry_id)
1830        } else {
1831            leaf_entry_id
1832        }
1833    }
1834
1835    fn rename_impl(
1836        &mut self,
1837        selection: Option<Range<usize>>,
1838        window: &mut Window,
1839        cx: &mut Context<Self>,
1840    ) {
1841        if let Some(SelectedEntry {
1842            worktree_id,
1843            entry_id,
1844        }) = self.state.selection
1845            && let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx)
1846        {
1847            let sub_entry_id = self.unflatten_entry_id(entry_id);
1848            if let Some(entry) = worktree.read(cx).entry_for_id(sub_entry_id) {
1849                #[cfg(target_os = "windows")]
1850                if Some(entry) == worktree.read(cx).root_entry() {
1851                    return;
1852                }
1853
1854                if Some(entry) == worktree.read(cx).root_entry() {
1855                    let settings = ProjectPanelSettings::get_global(cx);
1856                    let visible_worktrees_count =
1857                        self.project.read(cx).visible_worktrees(cx).count();
1858                    if settings.hide_root && visible_worktrees_count == 1 {
1859                        return;
1860                    }
1861                }
1862
1863                self.state.edit_state = Some(EditState {
1864                    worktree_id,
1865                    entry_id: sub_entry_id,
1866                    leaf_entry_id: Some(entry_id),
1867                    is_dir: entry.is_dir(),
1868                    processing_filename: None,
1869                    previously_focused: None,
1870                    depth: 0,
1871                    validation_state: ValidationState::None,
1872                });
1873                let file_name = entry.path.file_name().unwrap_or_default().to_string();
1874                let selection = selection.unwrap_or_else(|| {
1875                    let file_stem = entry.path.file_stem().map(|s| s.to_string());
1876                    let selection_end =
1877                        file_stem.map_or(file_name.len(), |file_stem| file_stem.len());
1878                    0..selection_end
1879                });
1880                self.filename_editor.update(cx, |editor, cx| {
1881                    editor.set_text(file_name, window, cx);
1882                    editor.change_selections(Default::default(), window, cx, |s| {
1883                        s.select_ranges([selection])
1884                    });
1885                    window.focus(&editor.focus_handle(cx));
1886                });
1887                self.update_visible_entries(None, false, true, window, cx);
1888                cx.notify();
1889            }
1890        }
1891    }
1892
1893    fn rename(&mut self, _: &Rename, window: &mut Window, cx: &mut Context<Self>) {
1894        self.rename_impl(None, window, cx);
1895    }
1896
1897    fn trash(&mut self, action: &Trash, window: &mut Window, cx: &mut Context<Self>) {
1898        self.remove(true, action.skip_prompt, window, cx);
1899    }
1900
1901    fn delete(&mut self, action: &Delete, window: &mut Window, cx: &mut Context<Self>) {
1902        self.remove(false, action.skip_prompt, window, cx);
1903    }
1904
1905    fn remove(
1906        &mut self,
1907        trash: bool,
1908        skip_prompt: bool,
1909        window: &mut Window,
1910        cx: &mut Context<ProjectPanel>,
1911    ) {
1912        maybe!({
1913            let items_to_delete = self.disjoint_entries(cx);
1914            if items_to_delete.is_empty() {
1915                return None;
1916            }
1917            let project = self.project.read(cx);
1918
1919            let mut dirty_buffers = 0;
1920            let file_paths = items_to_delete
1921                .iter()
1922                .filter_map(|selection| {
1923                    let project_path = project.path_for_entry(selection.entry_id, cx)?;
1924                    dirty_buffers +=
1925                        project.dirty_buffers(cx).any(|path| path == project_path) as usize;
1926                    Some((
1927                        selection.entry_id,
1928                        project_path.path.file_name()?.to_string(),
1929                    ))
1930                })
1931                .collect::<Vec<_>>();
1932            if file_paths.is_empty() {
1933                return None;
1934            }
1935            let answer = if !skip_prompt {
1936                let operation = if trash { "Trash" } else { "Delete" };
1937                let prompt = match file_paths.first() {
1938                    Some((_, path)) if file_paths.len() == 1 => {
1939                        let unsaved_warning = if dirty_buffers > 0 {
1940                            "\n\nIt has unsaved changes, which will be lost."
1941                        } else {
1942                            ""
1943                        };
1944
1945                        format!("{operation} {path}?{unsaved_warning}")
1946                    }
1947                    _ => {
1948                        const CUTOFF_POINT: usize = 10;
1949                        let names = if file_paths.len() > CUTOFF_POINT {
1950                            let truncated_path_counts = file_paths.len() - CUTOFF_POINT;
1951                            let mut paths = file_paths
1952                                .iter()
1953                                .map(|(_, path)| path.clone())
1954                                .take(CUTOFF_POINT)
1955                                .collect::<Vec<_>>();
1956                            paths.truncate(CUTOFF_POINT);
1957                            if truncated_path_counts == 1 {
1958                                paths.push(".. 1 file not shown".into());
1959                            } else {
1960                                paths.push(format!(".. {} files not shown", truncated_path_counts));
1961                            }
1962                            paths
1963                        } else {
1964                            file_paths.iter().map(|(_, path)| path.clone()).collect()
1965                        };
1966                        let unsaved_warning = if dirty_buffers == 0 {
1967                            String::new()
1968                        } else if dirty_buffers == 1 {
1969                            "\n\n1 of these has unsaved changes, which will be lost.".to_string()
1970                        } else {
1971                            format!(
1972                                "\n\n{dirty_buffers} of these have unsaved changes, which will be lost."
1973                            )
1974                        };
1975
1976                        format!(
1977                            "Do you want to {} the following {} files?\n{}{unsaved_warning}",
1978                            operation.to_lowercase(),
1979                            file_paths.len(),
1980                            names.join("\n")
1981                        )
1982                    }
1983                };
1984                Some(window.prompt(PromptLevel::Info, &prompt, None, &[operation, "Cancel"], cx))
1985            } else {
1986                None
1987            };
1988            let next_selection = self.find_next_selection_after_deletion(items_to_delete, cx);
1989            cx.spawn_in(window, async move |panel, cx| {
1990                if let Some(answer) = answer
1991                    && answer.await != Ok(0)
1992                {
1993                    return anyhow::Ok(());
1994                }
1995                for (entry_id, _) in file_paths {
1996                    panel
1997                        .update(cx, |panel, cx| {
1998                            panel
1999                                .project
2000                                .update(cx, |project, cx| project.delete_entry(entry_id, trash, cx))
2001                                .context("no such entry")
2002                        })??
2003                        .await?;
2004                }
2005                panel.update_in(cx, |panel, window, cx| {
2006                    if let Some(next_selection) = next_selection {
2007                        panel.update_visible_entries(
2008                            Some((next_selection.worktree_id, next_selection.entry_id)),
2009                            false,
2010                            true,
2011                            window,
2012                            cx,
2013                        );
2014                    } else {
2015                        panel.select_last(&SelectLast {}, window, cx);
2016                    }
2017                })?;
2018                Ok(())
2019            })
2020            .detach_and_log_err(cx);
2021            Some(())
2022        });
2023    }
2024
2025    fn find_next_selection_after_deletion(
2026        &self,
2027        sanitized_entries: BTreeSet<SelectedEntry>,
2028        cx: &mut Context<Self>,
2029    ) -> Option<SelectedEntry> {
2030        if sanitized_entries.is_empty() {
2031            return None;
2032        }
2033        let project = self.project.read(cx);
2034        let (worktree_id, worktree) = sanitized_entries
2035            .iter()
2036            .map(|entry| entry.worktree_id)
2037            .filter_map(|id| project.worktree_for_id(id, cx).map(|w| (id, w.read(cx))))
2038            .max_by(|(_, a), (_, b)| a.root_name().cmp(b.root_name()))?;
2039        let git_store = project.git_store().read(cx);
2040
2041        let marked_entries_in_worktree = sanitized_entries
2042            .iter()
2043            .filter(|e| e.worktree_id == worktree_id)
2044            .collect::<HashSet<_>>();
2045        let latest_entry = marked_entries_in_worktree
2046            .iter()
2047            .max_by(|a, b| {
2048                match (
2049                    worktree.entry_for_id(a.entry_id),
2050                    worktree.entry_for_id(b.entry_id),
2051                ) {
2052                    (Some(a), Some(b)) => compare_paths(
2053                        (a.path.as_std_path(), a.is_file()),
2054                        (b.path.as_std_path(), b.is_file()),
2055                    ),
2056                    _ => cmp::Ordering::Equal,
2057                }
2058            })
2059            .and_then(|e| worktree.entry_for_id(e.entry_id))?;
2060
2061        let parent_path = latest_entry.path.parent()?;
2062        let parent_entry = worktree.entry_for_path(parent_path)?;
2063
2064        // Remove all siblings that are being deleted except the last marked entry
2065        let repo_snapshots = git_store.repo_snapshots(cx);
2066        let worktree_snapshot = worktree.snapshot();
2067        let hide_gitignore = ProjectPanelSettings::get_global(cx).hide_gitignore;
2068        let mut siblings: Vec<_> =
2069            ChildEntriesGitIter::new(&repo_snapshots, &worktree_snapshot, parent_path)
2070                .filter(|sibling| {
2071                    (sibling.id == latest_entry.id)
2072                        || (!marked_entries_in_worktree.contains(&&SelectedEntry {
2073                            worktree_id,
2074                            entry_id: sibling.id,
2075                        }) && (!hide_gitignore || !sibling.is_ignored))
2076                })
2077                .map(|entry| entry.to_owned())
2078                .collect();
2079
2080        sort_worktree_entries(&mut siblings);
2081        let sibling_entry_index = siblings
2082            .iter()
2083            .position(|sibling| sibling.id == latest_entry.id)?;
2084
2085        if let Some(next_sibling) = sibling_entry_index
2086            .checked_add(1)
2087            .and_then(|i| siblings.get(i))
2088        {
2089            return Some(SelectedEntry {
2090                worktree_id,
2091                entry_id: next_sibling.id,
2092            });
2093        }
2094        if let Some(prev_sibling) = sibling_entry_index
2095            .checked_sub(1)
2096            .and_then(|i| siblings.get(i))
2097        {
2098            return Some(SelectedEntry {
2099                worktree_id,
2100                entry_id: prev_sibling.id,
2101            });
2102        }
2103        // No neighbour sibling found, fall back to parent
2104        Some(SelectedEntry {
2105            worktree_id,
2106            entry_id: parent_entry.id,
2107        })
2108    }
2109
2110    fn unfold_directory(
2111        &mut self,
2112        _: &UnfoldDirectory,
2113        window: &mut Window,
2114        cx: &mut Context<Self>,
2115    ) {
2116        if let Some((worktree, entry)) = self.selected_entry(cx) {
2117            self.state.unfolded_dir_ids.insert(entry.id);
2118
2119            let snapshot = worktree.snapshot();
2120            let mut parent_path = entry.path.parent();
2121            while let Some(path) = parent_path {
2122                if let Some(parent_entry) = worktree.entry_for_path(path) {
2123                    let mut children_iter = snapshot.child_entries(path);
2124
2125                    if children_iter.by_ref().take(2).count() > 1 {
2126                        break;
2127                    }
2128
2129                    self.state.unfolded_dir_ids.insert(parent_entry.id);
2130                    parent_path = path.parent();
2131                } else {
2132                    break;
2133                }
2134            }
2135
2136            self.update_visible_entries(None, false, true, window, cx);
2137            cx.notify();
2138        }
2139    }
2140
2141    fn fold_directory(&mut self, _: &FoldDirectory, window: &mut Window, cx: &mut Context<Self>) {
2142        if let Some((worktree, entry)) = self.selected_entry(cx) {
2143            self.state.unfolded_dir_ids.remove(&entry.id);
2144
2145            let snapshot = worktree.snapshot();
2146            let mut path = &*entry.path;
2147            loop {
2148                let mut child_entries_iter = snapshot.child_entries(path);
2149                if let Some(child) = child_entries_iter.next() {
2150                    if child_entries_iter.next().is_none() && child.is_dir() {
2151                        self.state.unfolded_dir_ids.remove(&child.id);
2152                        path = &*child.path;
2153                    } else {
2154                        break;
2155                    }
2156                } else {
2157                    break;
2158                }
2159            }
2160
2161            self.update_visible_entries(None, false, true, window, cx);
2162            cx.notify();
2163        }
2164    }
2165
2166    fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
2167        for _ in 0..self.rendered_entries_len / 2 {
2168            window.dispatch_action(SelectPrevious.boxed_clone(), cx);
2169        }
2170    }
2171
2172    fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
2173        for _ in 0..self.rendered_entries_len / 2 {
2174            window.dispatch_action(SelectNext.boxed_clone(), cx);
2175        }
2176    }
2177
2178    fn scroll_cursor_center(
2179        &mut self,
2180        _: &ScrollCursorCenter,
2181        _: &mut Window,
2182        cx: &mut Context<Self>,
2183    ) {
2184        if let Some((_, _, index)) = self
2185            .state
2186            .selection
2187            .and_then(|s| self.index_for_selection(s))
2188        {
2189            self.scroll_handle
2190                .scroll_to_item_strict(index, ScrollStrategy::Center);
2191            cx.notify();
2192        }
2193    }
2194
2195    fn scroll_cursor_top(&mut self, _: &ScrollCursorTop, _: &mut Window, cx: &mut Context<Self>) {
2196        if let Some((_, _, index)) = self
2197            .state
2198            .selection
2199            .and_then(|s| self.index_for_selection(s))
2200        {
2201            self.scroll_handle
2202                .scroll_to_item_strict(index, ScrollStrategy::Top);
2203            cx.notify();
2204        }
2205    }
2206
2207    fn scroll_cursor_bottom(
2208        &mut self,
2209        _: &ScrollCursorBottom,
2210        _: &mut Window,
2211        cx: &mut Context<Self>,
2212    ) {
2213        if let Some((_, _, index)) = self
2214            .state
2215            .selection
2216            .and_then(|s| self.index_for_selection(s))
2217        {
2218            self.scroll_handle
2219                .scroll_to_item_strict(index, ScrollStrategy::Bottom);
2220            cx.notify();
2221        }
2222    }
2223
2224    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2225        if let Some(edit_state) = &self.state.edit_state
2226            && edit_state.processing_filename.is_none()
2227        {
2228            self.filename_editor.update(cx, |editor, cx| {
2229                editor.move_to_end_of_line(
2230                    &editor::actions::MoveToEndOfLine {
2231                        stop_at_soft_wraps: false,
2232                    },
2233                    window,
2234                    cx,
2235                );
2236            });
2237            return;
2238        }
2239        if let Some(selection) = self.state.selection {
2240            let (mut worktree_ix, mut entry_ix, _) =
2241                self.index_for_selection(selection).unwrap_or_default();
2242            if let Some(worktree_entries) = self
2243                .state
2244                .visible_entries
2245                .get(worktree_ix)
2246                .map(|v| &v.entries)
2247            {
2248                if entry_ix + 1 < worktree_entries.len() {
2249                    entry_ix += 1;
2250                } else {
2251                    worktree_ix += 1;
2252                    entry_ix = 0;
2253                }
2254            }
2255
2256            if let Some(VisibleEntriesForWorktree {
2257                worktree_id,
2258                entries,
2259                ..
2260            }) = self.state.visible_entries.get(worktree_ix)
2261                && let Some(entry) = entries.get(entry_ix)
2262            {
2263                let selection = SelectedEntry {
2264                    worktree_id: *worktree_id,
2265                    entry_id: entry.id,
2266                };
2267                self.state.selection = Some(selection);
2268                if window.modifiers().shift {
2269                    self.marked_entries.push(selection);
2270                }
2271
2272                self.autoscroll(cx);
2273                cx.notify();
2274            }
2275        } else {
2276            self.select_first(&SelectFirst {}, window, cx);
2277        }
2278    }
2279
2280    fn select_prev_diagnostic(
2281        &mut self,
2282        action: &SelectPrevDiagnostic,
2283        window: &mut Window,
2284        cx: &mut Context<Self>,
2285    ) {
2286        let selection = self.find_entry(
2287            self.state.selection.as_ref(),
2288            true,
2289            |entry, worktree_id| {
2290                self.state.selection.is_none_or(|selection| {
2291                    if selection.worktree_id == worktree_id {
2292                        selection.entry_id != entry.id
2293                    } else {
2294                        true
2295                    }
2296                }) && entry.is_file()
2297                    && self
2298                        .diagnostics
2299                        .get(&(worktree_id, entry.path.clone()))
2300                        .is_some_and(|severity| action.severity.matches(*severity))
2301            },
2302            cx,
2303        );
2304
2305        if let Some(selection) = selection {
2306            self.state.selection = Some(selection);
2307            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2308            self.update_visible_entries(
2309                Some((selection.worktree_id, selection.entry_id)),
2310                false,
2311                true,
2312                window,
2313                cx,
2314            );
2315            cx.notify();
2316        }
2317    }
2318
2319    fn select_next_diagnostic(
2320        &mut self,
2321        action: &SelectNextDiagnostic,
2322        window: &mut Window,
2323        cx: &mut Context<Self>,
2324    ) {
2325        let selection = self.find_entry(
2326            self.state.selection.as_ref(),
2327            false,
2328            |entry, worktree_id| {
2329                self.state.selection.is_none_or(|selection| {
2330                    if selection.worktree_id == worktree_id {
2331                        selection.entry_id != entry.id
2332                    } else {
2333                        true
2334                    }
2335                }) && entry.is_file()
2336                    && self
2337                        .diagnostics
2338                        .get(&(worktree_id, entry.path.clone()))
2339                        .is_some_and(|severity| action.severity.matches(*severity))
2340            },
2341            cx,
2342        );
2343
2344        if let Some(selection) = selection {
2345            self.state.selection = Some(selection);
2346            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2347            self.update_visible_entries(
2348                Some((selection.worktree_id, selection.entry_id)),
2349                false,
2350                true,
2351                window,
2352                cx,
2353            );
2354            cx.notify();
2355        }
2356    }
2357
2358    fn select_prev_git_entry(
2359        &mut self,
2360        _: &SelectPrevGitEntry,
2361        window: &mut Window,
2362        cx: &mut Context<Self>,
2363    ) {
2364        let selection = self.find_entry(
2365            self.state.selection.as_ref(),
2366            true,
2367            |entry, worktree_id| {
2368                (self.state.selection.is_none()
2369                    || self.state.selection.is_some_and(|selection| {
2370                        if selection.worktree_id == worktree_id {
2371                            selection.entry_id != entry.id
2372                        } else {
2373                            true
2374                        }
2375                    }))
2376                    && entry.is_file()
2377                    && entry.git_summary.index.modified + entry.git_summary.worktree.modified > 0
2378            },
2379            cx,
2380        );
2381
2382        if let Some(selection) = selection {
2383            self.state.selection = Some(selection);
2384            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2385            self.update_visible_entries(
2386                Some((selection.worktree_id, selection.entry_id)),
2387                false,
2388                true,
2389                window,
2390                cx,
2391            );
2392            cx.notify();
2393        }
2394    }
2395
2396    fn select_prev_directory(
2397        &mut self,
2398        _: &SelectPrevDirectory,
2399        _: &mut Window,
2400        cx: &mut Context<Self>,
2401    ) {
2402        let selection = self.find_visible_entry(
2403            self.state.selection.as_ref(),
2404            true,
2405            |entry, worktree_id| {
2406                self.state.selection.is_none_or(|selection| {
2407                    if selection.worktree_id == worktree_id {
2408                        selection.entry_id != entry.id
2409                    } else {
2410                        true
2411                    }
2412                }) && entry.is_dir()
2413            },
2414            cx,
2415        );
2416
2417        if let Some(selection) = selection {
2418            self.state.selection = Some(selection);
2419            self.autoscroll(cx);
2420            cx.notify();
2421        }
2422    }
2423
2424    fn select_next_directory(
2425        &mut self,
2426        _: &SelectNextDirectory,
2427        _: &mut Window,
2428        cx: &mut Context<Self>,
2429    ) {
2430        let selection = self.find_visible_entry(
2431            self.state.selection.as_ref(),
2432            false,
2433            |entry, worktree_id| {
2434                self.state.selection.is_none_or(|selection| {
2435                    if selection.worktree_id == worktree_id {
2436                        selection.entry_id != entry.id
2437                    } else {
2438                        true
2439                    }
2440                }) && entry.is_dir()
2441            },
2442            cx,
2443        );
2444
2445        if let Some(selection) = selection {
2446            self.state.selection = Some(selection);
2447            self.autoscroll(cx);
2448            cx.notify();
2449        }
2450    }
2451
2452    fn select_next_git_entry(
2453        &mut self,
2454        _: &SelectNextGitEntry,
2455        window: &mut Window,
2456        cx: &mut Context<Self>,
2457    ) {
2458        let selection = self.find_entry(
2459            self.state.selection.as_ref(),
2460            false,
2461            |entry, worktree_id| {
2462                self.state.selection.is_none_or(|selection| {
2463                    if selection.worktree_id == worktree_id {
2464                        selection.entry_id != entry.id
2465                    } else {
2466                        true
2467                    }
2468                }) && entry.is_file()
2469                    && entry.git_summary.index.modified + entry.git_summary.worktree.modified > 0
2470            },
2471            cx,
2472        );
2473
2474        if let Some(selection) = selection {
2475            self.state.selection = Some(selection);
2476            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2477            self.update_visible_entries(
2478                Some((selection.worktree_id, selection.entry_id)),
2479                false,
2480                true,
2481                window,
2482                cx,
2483            );
2484            cx.notify();
2485        }
2486    }
2487
2488    fn select_parent(&mut self, _: &SelectParent, window: &mut Window, cx: &mut Context<Self>) {
2489        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2490            if let Some(parent) = entry.path.parent() {
2491                let worktree = worktree.read(cx);
2492                if let Some(parent_entry) = worktree.entry_for_path(parent) {
2493                    self.state.selection = Some(SelectedEntry {
2494                        worktree_id: worktree.id(),
2495                        entry_id: parent_entry.id,
2496                    });
2497                    self.autoscroll(cx);
2498                    cx.notify();
2499                }
2500            }
2501        } else {
2502            self.select_first(&SelectFirst {}, window, cx);
2503        }
2504    }
2505
2506    fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
2507        if let Some(VisibleEntriesForWorktree {
2508            worktree_id,
2509            entries,
2510            ..
2511        }) = self.state.visible_entries.first()
2512            && let Some(entry) = entries.first()
2513        {
2514            let selection = SelectedEntry {
2515                worktree_id: *worktree_id,
2516                entry_id: entry.id,
2517            };
2518            self.state.selection = Some(selection);
2519            if window.modifiers().shift {
2520                self.marked_entries.push(selection);
2521            }
2522            self.autoscroll(cx);
2523            cx.notify();
2524        }
2525    }
2526
2527    fn select_last(&mut self, _: &SelectLast, _: &mut Window, cx: &mut Context<Self>) {
2528        if let Some(VisibleEntriesForWorktree {
2529            worktree_id,
2530            entries,
2531            ..
2532        }) = self.state.visible_entries.last()
2533        {
2534            let worktree = self.project.read(cx).worktree_for_id(*worktree_id, cx);
2535            if let (Some(worktree), Some(entry)) = (worktree, entries.last()) {
2536                let worktree = worktree.read(cx);
2537                if let Some(entry) = worktree.entry_for_id(entry.id) {
2538                    let selection = SelectedEntry {
2539                        worktree_id: *worktree_id,
2540                        entry_id: entry.id,
2541                    };
2542                    self.state.selection = Some(selection);
2543                    self.autoscroll(cx);
2544                    cx.notify();
2545                }
2546            }
2547        }
2548    }
2549
2550    fn autoscroll(&mut self, cx: &mut Context<Self>) {
2551        if let Some((_, _, index)) = self
2552            .state
2553            .selection
2554            .and_then(|s| self.index_for_selection(s))
2555        {
2556            self.scroll_handle.scroll_to_item_with_offset(
2557                index,
2558                ScrollStrategy::Center,
2559                self.sticky_items_count,
2560            );
2561            cx.notify();
2562        }
2563    }
2564
2565    fn cut(&mut self, _: &Cut, _: &mut Window, cx: &mut Context<Self>) {
2566        let entries = self.disjoint_entries(cx);
2567        if !entries.is_empty() {
2568            self.clipboard = Some(ClipboardEntry::Cut(entries));
2569            cx.notify();
2570        }
2571    }
2572
2573    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
2574        let entries = self.disjoint_entries(cx);
2575        if !entries.is_empty() {
2576            self.clipboard = Some(ClipboardEntry::Copied(entries));
2577            cx.notify();
2578        }
2579    }
2580
2581    fn create_paste_path(
2582        &self,
2583        source: &SelectedEntry,
2584        (worktree, target_entry): (Entity<Worktree>, &Entry),
2585        cx: &App,
2586    ) -> Option<(Arc<RelPath>, Option<Range<usize>>)> {
2587        let mut new_path = target_entry.path.to_rel_path_buf();
2588        // If we're pasting into a file, or a directory into itself, go up one level.
2589        if target_entry.is_file() || (target_entry.is_dir() && target_entry.id == source.entry_id) {
2590            new_path.pop();
2591        }
2592        let clipboard_entry_file_name = self
2593            .project
2594            .read(cx)
2595            .path_for_entry(source.entry_id, cx)?
2596            .path
2597            .file_name()?
2598            .to_string();
2599        new_path.push(RelPath::unix(&clipboard_entry_file_name).unwrap());
2600        let extension = new_path.extension().map(|s| s.to_string());
2601        let file_name_without_extension = new_path.file_stem()?.to_string();
2602        let file_name_len = file_name_without_extension.len();
2603        let mut disambiguation_range = None;
2604        let mut ix = 0;
2605        {
2606            let worktree = worktree.read(cx);
2607            while worktree.entry_for_path(&new_path).is_some() {
2608                new_path.pop();
2609
2610                let mut new_file_name = file_name_without_extension.to_string();
2611
2612                let disambiguation = " copy";
2613                let mut disambiguation_len = disambiguation.len();
2614
2615                new_file_name.push_str(disambiguation);
2616
2617                if ix > 0 {
2618                    let extra_disambiguation = format!(" {}", ix);
2619                    disambiguation_len += extra_disambiguation.len();
2620                    new_file_name.push_str(&extra_disambiguation);
2621                }
2622                if let Some(extension) = extension.as_ref() {
2623                    new_file_name.push_str(".");
2624                    new_file_name.push_str(extension);
2625                }
2626
2627                new_path.push(RelPath::unix(&new_file_name).unwrap());
2628
2629                disambiguation_range = Some(file_name_len..(file_name_len + disambiguation_len));
2630                ix += 1;
2631            }
2632        }
2633        Some((new_path.as_rel_path().into(), disambiguation_range))
2634    }
2635
2636    fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
2637        maybe!({
2638            let (worktree, entry) = self.selected_entry_handle(cx)?;
2639            let entry = entry.clone();
2640            let worktree_id = worktree.read(cx).id();
2641            let clipboard_entries = self
2642                .clipboard
2643                .as_ref()
2644                .filter(|clipboard| !clipboard.items().is_empty())?;
2645
2646            enum PasteTask {
2647                Rename(Task<Result<CreatedEntry>>),
2648                Copy(Task<Result<Option<Entry>>>),
2649            }
2650
2651            let mut paste_tasks = Vec::new();
2652            let mut disambiguation_range = None;
2653            let clip_is_cut = clipboard_entries.is_cut();
2654            for clipboard_entry in clipboard_entries.items() {
2655                let (new_path, new_disambiguation_range) =
2656                    self.create_paste_path(clipboard_entry, self.selected_sub_entry(cx)?, cx)?;
2657                let clip_entry_id = clipboard_entry.entry_id;
2658                let task = if clipboard_entries.is_cut() {
2659                    let task = self.project.update(cx, |project, cx| {
2660                        project.rename_entry(clip_entry_id, (worktree_id, new_path).into(), cx)
2661                    });
2662                    PasteTask::Rename(task)
2663                } else {
2664                    let task = self.project.update(cx, |project, cx| {
2665                        project.copy_entry(clip_entry_id, (worktree_id, new_path).into(), cx)
2666                    });
2667                    PasteTask::Copy(task)
2668                };
2669                paste_tasks.push(task);
2670                disambiguation_range = new_disambiguation_range.or(disambiguation_range);
2671            }
2672
2673            let item_count = paste_tasks.len();
2674
2675            cx.spawn_in(window, async move |project_panel, cx| {
2676                let mut last_succeed = None;
2677                for task in paste_tasks {
2678                    match task {
2679                        PasteTask::Rename(task) => {
2680                            if let Some(CreatedEntry::Included(entry)) = task.await.log_err() {
2681                                last_succeed = Some(entry);
2682                            }
2683                        }
2684                        PasteTask::Copy(task) => {
2685                            if let Some(Some(entry)) = task.await.log_err() {
2686                                last_succeed = Some(entry);
2687                            }
2688                        }
2689                    }
2690                }
2691                // update selection
2692                if let Some(entry) = last_succeed {
2693                    project_panel
2694                        .update_in(cx, |project_panel, window, cx| {
2695                            project_panel.state.selection = Some(SelectedEntry {
2696                                worktree_id,
2697                                entry_id: entry.id,
2698                            });
2699
2700                            if item_count == 1 {
2701                                // open entry if not dir, and only focus if rename is not pending
2702                                if !entry.is_dir() {
2703                                    project_panel.open_entry(
2704                                        entry.id,
2705                                        disambiguation_range.is_none(),
2706                                        false,
2707                                        cx,
2708                                    );
2709                                }
2710
2711                                // if only one entry was pasted and it was disambiguated, open the rename editor
2712                                if disambiguation_range.is_some() {
2713                                    cx.defer_in(window, |this, window, cx| {
2714                                        this.rename_impl(disambiguation_range, window, cx);
2715                                    });
2716                                }
2717                            }
2718                        })
2719                        .ok();
2720                }
2721
2722                anyhow::Ok(())
2723            })
2724            .detach_and_log_err(cx);
2725
2726            if clip_is_cut {
2727                // Convert the clipboard cut entry to a copy entry after the first paste.
2728                self.clipboard = self.clipboard.take().map(ClipboardEntry::into_copy_entry);
2729            }
2730
2731            self.expand_entry(worktree_id, entry.id, cx);
2732            Some(())
2733        });
2734    }
2735
2736    fn duplicate(&mut self, _: &Duplicate, window: &mut Window, cx: &mut Context<Self>) {
2737        self.copy(&Copy {}, window, cx);
2738        self.paste(&Paste {}, window, cx);
2739    }
2740
2741    fn copy_path(
2742        &mut self,
2743        _: &zed_actions::workspace::CopyPath,
2744        _: &mut Window,
2745        cx: &mut Context<Self>,
2746    ) {
2747        let abs_file_paths = {
2748            let project = self.project.read(cx);
2749            self.effective_entries()
2750                .into_iter()
2751                .filter_map(|entry| {
2752                    let entry_path = project.path_for_entry(entry.entry_id, cx)?.path;
2753                    Some(
2754                        project
2755                            .worktree_for_id(entry.worktree_id, cx)?
2756                            .read(cx)
2757                            .absolutize(&entry_path)
2758                            .to_string_lossy()
2759                            .to_string(),
2760                    )
2761                })
2762                .collect::<Vec<_>>()
2763        };
2764        if !abs_file_paths.is_empty() {
2765            cx.write_to_clipboard(ClipboardItem::new_string(abs_file_paths.join("\n")));
2766        }
2767    }
2768
2769    fn copy_relative_path(
2770        &mut self,
2771        _: &zed_actions::workspace::CopyRelativePath,
2772        _: &mut Window,
2773        cx: &mut Context<Self>,
2774    ) {
2775        let path_style = self.project.read(cx).path_style(cx);
2776        let file_paths = {
2777            let project = self.project.read(cx);
2778            self.effective_entries()
2779                .into_iter()
2780                .filter_map(|entry| {
2781                    Some(
2782                        project
2783                            .path_for_entry(entry.entry_id, cx)?
2784                            .path
2785                            .display(path_style)
2786                            .into_owned(),
2787                    )
2788                })
2789                .collect::<Vec<_>>()
2790        };
2791        if !file_paths.is_empty() {
2792            cx.write_to_clipboard(ClipboardItem::new_string(file_paths.join("\n")));
2793        }
2794    }
2795
2796    fn reveal_in_finder(
2797        &mut self,
2798        _: &RevealInFileManager,
2799        _: &mut Window,
2800        cx: &mut Context<Self>,
2801    ) {
2802        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2803            cx.reveal_path(&worktree.read(cx).absolutize(&entry.path));
2804        }
2805    }
2806
2807    fn remove_from_project(
2808        &mut self,
2809        _: &RemoveFromProject,
2810        _window: &mut Window,
2811        cx: &mut Context<Self>,
2812    ) {
2813        for entry in self.effective_entries().iter() {
2814            let worktree_id = entry.worktree_id;
2815            self.project
2816                .update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
2817        }
2818    }
2819
2820    fn file_abs_paths_to_diff(&self, cx: &Context<Self>) -> Option<(PathBuf, PathBuf)> {
2821        let mut selections_abs_path = self
2822            .marked_entries
2823            .iter()
2824            .filter_map(|entry| {
2825                let project = self.project.read(cx);
2826                let worktree = project.worktree_for_id(entry.worktree_id, cx)?;
2827                let entry = worktree.read(cx).entry_for_id(entry.entry_id)?;
2828                if !entry.is_file() {
2829                    return None;
2830                }
2831                Some(worktree.read(cx).absolutize(&entry.path))
2832            })
2833            .rev();
2834
2835        let last_path = selections_abs_path.next()?;
2836        let previous_to_last = selections_abs_path.next()?;
2837        Some((previous_to_last, last_path))
2838    }
2839
2840    fn compare_marked_files(
2841        &mut self,
2842        _: &CompareMarkedFiles,
2843        window: &mut Window,
2844        cx: &mut Context<Self>,
2845    ) {
2846        let selected_files = self.file_abs_paths_to_diff(cx);
2847        if let Some((file_path1, file_path2)) = selected_files {
2848            self.workspace
2849                .update(cx, |workspace, cx| {
2850                    FileDiffView::open(file_path1, file_path2, workspace, window, cx)
2851                        .detach_and_log_err(cx);
2852                })
2853                .ok();
2854        }
2855    }
2856
2857    fn open_system(&mut self, _: &OpenWithSystem, _: &mut Window, cx: &mut Context<Self>) {
2858        if let Some((worktree, entry)) = self.selected_entry(cx) {
2859            let abs_path = worktree.absolutize(&entry.path);
2860            cx.open_with_system(&abs_path);
2861        }
2862    }
2863
2864    fn open_in_terminal(
2865        &mut self,
2866        _: &OpenInTerminal,
2867        window: &mut Window,
2868        cx: &mut Context<Self>,
2869    ) {
2870        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2871            let abs_path = match &entry.canonical_path {
2872                Some(canonical_path) => canonical_path.to_path_buf(),
2873                None => worktree.read(cx).absolutize(&entry.path),
2874            };
2875
2876            let working_directory = if entry.is_dir() {
2877                Some(abs_path)
2878            } else {
2879                abs_path.parent().map(|path| path.to_path_buf())
2880            };
2881            if let Some(working_directory) = working_directory {
2882                window.dispatch_action(
2883                    workspace::OpenTerminal { working_directory }.boxed_clone(),
2884                    cx,
2885                )
2886            }
2887        }
2888    }
2889
2890    pub fn new_search_in_directory(
2891        &mut self,
2892        _: &NewSearchInDirectory,
2893        window: &mut Window,
2894        cx: &mut Context<Self>,
2895    ) {
2896        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2897            let dir_path = if entry.is_dir() {
2898                entry.path.clone()
2899            } else {
2900                // entry is a file, use its parent directory
2901                match entry.path.parent() {
2902                    Some(parent) => Arc::from(parent),
2903                    None => {
2904                        // File at root, open search with empty filter
2905                        self.workspace
2906                            .update(cx, |workspace, cx| {
2907                                search::ProjectSearchView::new_search_in_directory(
2908                                    workspace,
2909                                    RelPath::empty(),
2910                                    window,
2911                                    cx,
2912                                );
2913                            })
2914                            .ok();
2915                        return;
2916                    }
2917                }
2918            };
2919
2920            let include_root = self.project.read(cx).visible_worktrees(cx).count() > 1;
2921            let dir_path = if include_root {
2922                worktree.read(cx).root_name().join(&dir_path)
2923            } else {
2924                dir_path
2925            };
2926
2927            self.workspace
2928                .update(cx, |workspace, cx| {
2929                    search::ProjectSearchView::new_search_in_directory(
2930                        workspace, &dir_path, window, cx,
2931                    );
2932                })
2933                .ok();
2934        }
2935    }
2936
2937    fn move_entry(
2938        &mut self,
2939        entry_to_move: ProjectEntryId,
2940        destination: ProjectEntryId,
2941        destination_is_file: bool,
2942        cx: &mut Context<Self>,
2943    ) {
2944        if self
2945            .project
2946            .read(cx)
2947            .entry_is_worktree_root(entry_to_move, cx)
2948        {
2949            self.move_worktree_root(entry_to_move, destination, cx)
2950        } else {
2951            self.move_worktree_entry(entry_to_move, destination, destination_is_file, cx)
2952        }
2953    }
2954
2955    fn move_worktree_root(
2956        &mut self,
2957        entry_to_move: ProjectEntryId,
2958        destination: ProjectEntryId,
2959        cx: &mut Context<Self>,
2960    ) {
2961        self.project.update(cx, |project, cx| {
2962            let Some(worktree_to_move) = project.worktree_for_entry(entry_to_move, cx) else {
2963                return;
2964            };
2965            let Some(destination_worktree) = project.worktree_for_entry(destination, cx) else {
2966                return;
2967            };
2968
2969            let worktree_id = worktree_to_move.read(cx).id();
2970            let destination_id = destination_worktree.read(cx).id();
2971
2972            project
2973                .move_worktree(worktree_id, destination_id, cx)
2974                .log_err();
2975        });
2976    }
2977
2978    fn move_worktree_entry(
2979        &mut self,
2980        entry_to_move: ProjectEntryId,
2981        destination_entry: ProjectEntryId,
2982        destination_is_file: bool,
2983        cx: &mut Context<Self>,
2984    ) {
2985        if entry_to_move == destination_entry {
2986            return;
2987        }
2988
2989        let destination_worktree = self.project.update(cx, |project, cx| {
2990            let source_path = project.path_for_entry(entry_to_move, cx)?;
2991            let destination_path = project.path_for_entry(destination_entry, cx)?;
2992            let destination_worktree_id = destination_path.worktree_id;
2993
2994            let mut destination_path = destination_path.path.as_ref();
2995            if destination_is_file {
2996                destination_path = destination_path.parent()?;
2997            }
2998
2999            let mut new_path = destination_path.to_rel_path_buf();
3000            new_path.push(RelPath::unix(source_path.path.file_name()?).unwrap());
3001            if new_path.as_rel_path() != source_path.path.as_ref() {
3002                let task = project.rename_entry(
3003                    entry_to_move,
3004                    (destination_worktree_id, new_path).into(),
3005                    cx,
3006                );
3007                cx.foreground_executor().spawn(task).detach_and_log_err(cx);
3008            }
3009
3010            project.worktree_id_for_entry(destination_entry, cx)
3011        });
3012
3013        if let Some(destination_worktree) = destination_worktree {
3014            self.expand_entry(destination_worktree, destination_entry, cx);
3015        }
3016    }
3017
3018    fn index_for_selection(&self, selection: SelectedEntry) -> Option<(usize, usize, usize)> {
3019        self.index_for_entry(selection.entry_id, selection.worktree_id)
3020    }
3021
3022    fn disjoint_entries(&self, cx: &App) -> BTreeSet<SelectedEntry> {
3023        let marked_entries = self.effective_entries();
3024        let mut sanitized_entries = BTreeSet::new();
3025        if marked_entries.is_empty() {
3026            return sanitized_entries;
3027        }
3028
3029        let project = self.project.read(cx);
3030        let marked_entries_by_worktree: HashMap<WorktreeId, Vec<SelectedEntry>> = marked_entries
3031            .into_iter()
3032            .filter(|entry| !project.entry_is_worktree_root(entry.entry_id, cx))
3033            .fold(HashMap::default(), |mut map, entry| {
3034                map.entry(entry.worktree_id).or_default().push(entry);
3035                map
3036            });
3037
3038        for (worktree_id, marked_entries) in marked_entries_by_worktree {
3039            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
3040                let worktree = worktree.read(cx);
3041                let marked_dir_paths = marked_entries
3042                    .iter()
3043                    .filter_map(|entry| {
3044                        worktree.entry_for_id(entry.entry_id).and_then(|entry| {
3045                            if entry.is_dir() {
3046                                Some(entry.path.as_ref())
3047                            } else {
3048                                None
3049                            }
3050                        })
3051                    })
3052                    .collect::<BTreeSet<_>>();
3053
3054                sanitized_entries.extend(marked_entries.into_iter().filter(|entry| {
3055                    let Some(entry_info) = worktree.entry_for_id(entry.entry_id) else {
3056                        return false;
3057                    };
3058                    let entry_path = entry_info.path.as_ref();
3059                    let inside_marked_dir = marked_dir_paths.iter().any(|&marked_dir_path| {
3060                        entry_path != marked_dir_path && entry_path.starts_with(marked_dir_path)
3061                    });
3062                    !inside_marked_dir
3063                }));
3064            }
3065        }
3066
3067        sanitized_entries
3068    }
3069
3070    fn effective_entries(&self) -> BTreeSet<SelectedEntry> {
3071        if let Some(selection) = self.state.selection {
3072            let selection = SelectedEntry {
3073                entry_id: self.resolve_entry(selection.entry_id),
3074                worktree_id: selection.worktree_id,
3075            };
3076
3077            // Default to using just the selected item when nothing is marked.
3078            if self.marked_entries.is_empty() {
3079                return BTreeSet::from([selection]);
3080            }
3081
3082            // Allow operating on the selected item even when something else is marked,
3083            // making it easier to perform one-off actions without clearing a mark.
3084            if self.marked_entries.len() == 1 && !self.marked_entries.contains(&selection) {
3085                return BTreeSet::from([selection]);
3086            }
3087        }
3088
3089        // Return only marked entries since we've already handled special cases where
3090        // only selection should take precedence. At this point, marked entries may or
3091        // may not include the current selection, which is intentional.
3092        self.marked_entries
3093            .iter()
3094            .map(|entry| SelectedEntry {
3095                entry_id: self.resolve_entry(entry.entry_id),
3096                worktree_id: entry.worktree_id,
3097            })
3098            .collect::<BTreeSet<_>>()
3099    }
3100
3101    /// Finds the currently selected subentry for a given leaf entry id. If a given entry
3102    /// has no ancestors, the project entry ID that's passed in is returned as-is.
3103    fn resolve_entry(&self, id: ProjectEntryId) -> ProjectEntryId {
3104        self.state
3105            .ancestors
3106            .get(&id)
3107            .and_then(|ancestors| ancestors.active_ancestor())
3108            .unwrap_or(id)
3109    }
3110
3111    pub fn selected_entry<'a>(&self, cx: &'a App) -> Option<(&'a Worktree, &'a project::Entry)> {
3112        let (worktree, entry) = self.selected_entry_handle(cx)?;
3113        Some((worktree.read(cx), entry))
3114    }
3115
3116    /// Compared to selected_entry, this function resolves to the currently
3117    /// selected subentry if dir auto-folding is enabled.
3118    fn selected_sub_entry<'a>(
3119        &self,
3120        cx: &'a App,
3121    ) -> Option<(Entity<Worktree>, &'a project::Entry)> {
3122        let (worktree, mut entry) = self.selected_entry_handle(cx)?;
3123
3124        let resolved_id = self.resolve_entry(entry.id);
3125        if resolved_id != entry.id {
3126            let worktree = worktree.read(cx);
3127            entry = worktree.entry_for_id(resolved_id)?;
3128        }
3129        Some((worktree, entry))
3130    }
3131    fn selected_entry_handle<'a>(
3132        &self,
3133        cx: &'a App,
3134    ) -> Option<(Entity<Worktree>, &'a project::Entry)> {
3135        let selection = self.state.selection?;
3136        let project = self.project.read(cx);
3137        let worktree = project.worktree_for_id(selection.worktree_id, cx)?;
3138        let entry = worktree.read(cx).entry_for_id(selection.entry_id)?;
3139        Some((worktree, entry))
3140    }
3141
3142    fn expand_to_selection(&mut self, cx: &mut Context<Self>) -> Option<()> {
3143        let (worktree, entry) = self.selected_entry(cx)?;
3144        let expanded_dir_ids = self
3145            .state
3146            .expanded_dir_ids
3147            .entry(worktree.id())
3148            .or_default();
3149
3150        for path in entry.path.ancestors() {
3151            let Some(entry) = worktree.entry_for_path(path) else {
3152                continue;
3153            };
3154            if entry.is_dir()
3155                && let Err(idx) = expanded_dir_ids.binary_search(&entry.id)
3156            {
3157                expanded_dir_ids.insert(idx, entry.id);
3158            }
3159        }
3160
3161        Some(())
3162    }
3163
3164    fn create_new_git_entry(
3165        parent_entry: &Entry,
3166        git_summary: GitSummary,
3167        new_entry_kind: EntryKind,
3168    ) -> GitEntry {
3169        GitEntry {
3170            entry: Entry {
3171                id: NEW_ENTRY_ID,
3172                kind: new_entry_kind,
3173                path: parent_entry.path.join(RelPath::unix("\0").unwrap()),
3174                inode: 0,
3175                mtime: parent_entry.mtime,
3176                size: parent_entry.size,
3177                is_ignored: parent_entry.is_ignored,
3178                is_hidden: parent_entry.is_hidden,
3179                is_external: false,
3180                is_private: false,
3181                is_always_included: parent_entry.is_always_included,
3182                canonical_path: parent_entry.canonical_path.clone(),
3183                char_bag: parent_entry.char_bag,
3184                is_fifo: parent_entry.is_fifo,
3185            },
3186            git_summary,
3187        }
3188    }
3189
3190    fn update_visible_entries(
3191        &mut self,
3192        new_selected_entry: Option<(WorktreeId, ProjectEntryId)>,
3193        focus_filename_editor: bool,
3194        autoscroll: bool,
3195        window: &mut Window,
3196        cx: &mut Context<Self>,
3197    ) {
3198        let now = Instant::now();
3199        let settings = ProjectPanelSettings::get_global(cx);
3200        let auto_collapse_dirs = settings.auto_fold_dirs;
3201        let hide_gitignore = settings.hide_gitignore;
3202        let project = self.project.read(cx);
3203        let repo_snapshots = project.git_store().read(cx).repo_snapshots(cx);
3204
3205        let old_ancestors = self.state.ancestors.clone();
3206        let mut new_state = State::derive(&self.state);
3207        new_state.last_worktree_root_id = project
3208            .visible_worktrees(cx)
3209            .next_back()
3210            .and_then(|worktree| worktree.read(cx).root_entry())
3211            .map(|entry| entry.id);
3212        let mut max_width_item = None;
3213
3214        let visible_worktrees: Vec<_> = project
3215            .visible_worktrees(cx)
3216            .map(|worktree| worktree.read(cx).snapshot())
3217            .collect();
3218        let hide_root = settings.hide_root && visible_worktrees.len() == 1;
3219        let hide_hidden = settings.hide_hidden;
3220        self.update_visible_entries_task = cx.spawn_in(window, async move |this, cx| {
3221            let new_state = cx
3222                .background_spawn(async move {
3223                    for worktree_snapshot in visible_worktrees {
3224                        let worktree_id = worktree_snapshot.id();
3225
3226                        let expanded_dir_ids = match new_state.expanded_dir_ids.entry(worktree_id) {
3227                            hash_map::Entry::Occupied(e) => e.into_mut(),
3228                            hash_map::Entry::Vacant(e) => {
3229                                // The first time a worktree's root entry becomes available,
3230                                // mark that root entry as expanded.
3231                                if let Some(entry) = worktree_snapshot.root_entry() {
3232                                    e.insert(vec![entry.id]).as_slice()
3233                                } else {
3234                                    &[]
3235                                }
3236                            }
3237                        };
3238
3239                        let mut new_entry_parent_id = None;
3240                        let mut new_entry_kind = EntryKind::Dir;
3241                        if let Some(edit_state) = &new_state.edit_state
3242                            && edit_state.worktree_id == worktree_id
3243                            && edit_state.is_new_entry()
3244                        {
3245                            new_entry_parent_id = Some(edit_state.entry_id);
3246                            new_entry_kind = if edit_state.is_dir {
3247                                EntryKind::Dir
3248                            } else {
3249                                EntryKind::File
3250                            };
3251                        }
3252
3253                        let mut visible_worktree_entries = Vec::new();
3254                        let mut entry_iter =
3255                            GitTraversal::new(&repo_snapshots, worktree_snapshot.entries(true, 0));
3256                        let mut auto_folded_ancestors = vec![];
3257                        let worktree_abs_path = worktree_snapshot.abs_path();
3258                        while let Some(entry) = entry_iter.entry() {
3259                            if hide_root && Some(entry.entry) == worktree_snapshot.root_entry() {
3260                                if new_entry_parent_id == Some(entry.id) {
3261                                    visible_worktree_entries.push(Self::create_new_git_entry(
3262                                        entry.entry,
3263                                        entry.git_summary,
3264                                        new_entry_kind,
3265                                    ));
3266                                    new_entry_parent_id = None;
3267                                }
3268                                entry_iter.advance();
3269                                continue;
3270                            }
3271                            if auto_collapse_dirs && entry.kind.is_dir() {
3272                                auto_folded_ancestors.push(entry.id);
3273                                if !new_state.unfolded_dir_ids.contains(&entry.id)
3274                                    && let Some(root_path) = worktree_snapshot.root_entry()
3275                                {
3276                                    let mut child_entries =
3277                                        worktree_snapshot.child_entries(&entry.path);
3278                                    if let Some(child) = child_entries.next()
3279                                        && entry.path != root_path.path
3280                                        && child_entries.next().is_none()
3281                                        && child.kind.is_dir()
3282                                    {
3283                                        entry_iter.advance();
3284
3285                                        continue;
3286                                    }
3287                                }
3288                                let depth = old_ancestors
3289                                    .get(&entry.id)
3290                                    .map(|ancestor| ancestor.current_ancestor_depth)
3291                                    .unwrap_or_default()
3292                                    .min(auto_folded_ancestors.len());
3293                                if let Some(edit_state) = &mut new_state.edit_state
3294                                    && edit_state.entry_id == entry.id
3295                                {
3296                                    edit_state.depth = depth;
3297                                }
3298                                let mut ancestors = std::mem::take(&mut auto_folded_ancestors);
3299                                if ancestors.len() > 1 {
3300                                    ancestors.reverse();
3301                                    new_state.ancestors.insert(
3302                                        entry.id,
3303                                        FoldedAncestors {
3304                                            current_ancestor_depth: depth,
3305                                            ancestors,
3306                                        },
3307                                    );
3308                                }
3309                            }
3310                            auto_folded_ancestors.clear();
3311                            if (!hide_gitignore || !entry.is_ignored)
3312                                && (!hide_hidden || !entry.is_hidden)
3313                            {
3314                                visible_worktree_entries.push(entry.to_owned());
3315                            }
3316                            let precedes_new_entry = if let Some(new_entry_id) = new_entry_parent_id
3317                            {
3318                                entry.id == new_entry_id || {
3319                                    new_state.ancestors.get(&entry.id).is_some_and(|entries| {
3320                                        entries.ancestors.contains(&new_entry_id)
3321                                    })
3322                                }
3323                            } else {
3324                                false
3325                            };
3326                            if precedes_new_entry
3327                                && (!hide_gitignore || !entry.is_ignored)
3328                                && (!hide_hidden || !entry.is_hidden)
3329                            {
3330                                visible_worktree_entries.push(Self::create_new_git_entry(
3331                                    entry.entry,
3332                                    entry.git_summary,
3333                                    new_entry_kind,
3334                                ));
3335                            }
3336
3337                            let (depth, chars) = if Some(entry.entry)
3338                                == worktree_snapshot.root_entry()
3339                            {
3340                                let Some(path_name) = worktree_abs_path.file_name() else {
3341                                    continue;
3342                                };
3343                                let depth = 0;
3344                                (depth, path_name.to_string_lossy().chars().count())
3345                            } else if entry.is_file() {
3346                                let Some(path_name) = entry
3347                                    .path
3348                                    .file_name()
3349                                    .with_context(|| {
3350                                        format!("Non-root entry has no file name: {entry:?}")
3351                                    })
3352                                    .log_err()
3353                                else {
3354                                    continue;
3355                                };
3356                                let depth = entry.path.ancestors().count() - 1;
3357                                (depth, path_name.chars().count())
3358                            } else {
3359                                let path = new_state
3360                                    .ancestors
3361                                    .get(&entry.id)
3362                                    .and_then(|ancestors| {
3363                                        let outermost_ancestor = ancestors.ancestors.last()?;
3364                                        let root_folded_entry = worktree_snapshot
3365                                            .entry_for_id(*outermost_ancestor)?
3366                                            .path
3367                                            .as_ref();
3368                                        entry.path.strip_prefix(root_folded_entry).ok().and_then(
3369                                            |suffix| {
3370                                                Some(
3371                                                    RelPath::unix(root_folded_entry.file_name()?)
3372                                                        .unwrap()
3373                                                        .join(suffix),
3374                                                )
3375                                            },
3376                                        )
3377                                    })
3378                                    .or_else(|| {
3379                                        entry.path.file_name().map(|file_name| {
3380                                            RelPath::unix(file_name).unwrap().into()
3381                                        })
3382                                    })
3383                                    .unwrap_or_else(|| entry.path.clone());
3384                                let depth = path.components().count();
3385                                (depth, path.as_unix_str().chars().count())
3386                            };
3387                            let width_estimate =
3388                                item_width_estimate(depth, chars, entry.canonical_path.is_some());
3389
3390                            match max_width_item.as_mut() {
3391                                Some((id, worktree_id, width)) => {
3392                                    if *width < width_estimate {
3393                                        *id = entry.id;
3394                                        *worktree_id = worktree_snapshot.id();
3395                                        *width = width_estimate;
3396                                    }
3397                                }
3398                                None => {
3399                                    max_width_item =
3400                                        Some((entry.id, worktree_snapshot.id(), width_estimate))
3401                                }
3402                            }
3403
3404                            if expanded_dir_ids.binary_search(&entry.id).is_err()
3405                                && entry_iter.advance_to_sibling()
3406                            {
3407                                continue;
3408                            }
3409                            entry_iter.advance();
3410                        }
3411
3412                        par_sort_worktree_entries(&mut visible_worktree_entries);
3413                        new_state.visible_entries.push(VisibleEntriesForWorktree {
3414                            worktree_id,
3415                            entries: visible_worktree_entries,
3416                            index: OnceCell::new(),
3417                        })
3418                    }
3419                    if let Some((project_entry_id, worktree_id, _)) = max_width_item {
3420                        let mut visited_worktrees_length = 0;
3421                        let index = new_state
3422                            .visible_entries
3423                            .iter()
3424                            .find_map(|visible_entries| {
3425                                if worktree_id == visible_entries.worktree_id {
3426                                    visible_entries
3427                                        .entries
3428                                        .iter()
3429                                        .position(|entry| entry.id == project_entry_id)
3430                                } else {
3431                                    visited_worktrees_length += visible_entries.entries.len();
3432                                    None
3433                                }
3434                            });
3435                        if let Some(index) = index {
3436                            new_state.max_width_item_index = Some(visited_worktrees_length + index);
3437                        }
3438                    }
3439                    new_state
3440                })
3441                .await;
3442            this.update_in(cx, |this, window, cx| {
3443                let current_selection = this.state.selection;
3444                this.state = new_state;
3445                if let Some((worktree_id, entry_id)) = new_selected_entry {
3446                    this.state.selection = Some(SelectedEntry {
3447                        worktree_id,
3448                        entry_id,
3449                    });
3450                } else {
3451                    this.state.selection = current_selection;
3452                }
3453                let elapsed = now.elapsed();
3454                if this.last_reported_update.elapsed() > Duration::from_secs(3600) {
3455                    telemetry::event!(
3456                        "Project Panel Updated",
3457                        elapsed_ms = elapsed.as_millis() as u64,
3458                        worktree_entries = this
3459                            .state
3460                            .visible_entries
3461                            .iter()
3462                            .map(|worktree| worktree.entries.len())
3463                            .sum::<usize>(),
3464                    )
3465                }
3466                if focus_filename_editor {
3467                    this.filename_editor.update(cx, |editor, cx| {
3468                        editor.clear(window, cx);
3469                        window.focus(&editor.focus_handle(cx));
3470                    });
3471                }
3472                if autoscroll {
3473                    this.autoscroll(cx);
3474                }
3475                cx.notify();
3476            })
3477            .ok();
3478        });
3479    }
3480
3481    fn expand_entry(
3482        &mut self,
3483        worktree_id: WorktreeId,
3484        entry_id: ProjectEntryId,
3485        cx: &mut Context<Self>,
3486    ) {
3487        self.project.update(cx, |project, cx| {
3488            if let Some((worktree, expanded_dir_ids)) = project
3489                .worktree_for_id(worktree_id, cx)
3490                .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
3491            {
3492                project.expand_entry(worktree_id, entry_id, cx);
3493                let worktree = worktree.read(cx);
3494
3495                if let Some(mut entry) = worktree.entry_for_id(entry_id) {
3496                    loop {
3497                        if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
3498                            expanded_dir_ids.insert(ix, entry.id);
3499                        }
3500
3501                        if let Some(parent_entry) =
3502                            entry.path.parent().and_then(|p| worktree.entry_for_path(p))
3503                        {
3504                            entry = parent_entry;
3505                        } else {
3506                            break;
3507                        }
3508                    }
3509                }
3510            }
3511        });
3512    }
3513
3514    fn drop_external_files(
3515        &mut self,
3516        paths: &[PathBuf],
3517        entry_id: ProjectEntryId,
3518        window: &mut Window,
3519        cx: &mut Context<Self>,
3520    ) {
3521        let mut paths: Vec<Arc<Path>> = paths.iter().map(|path| Arc::from(path.clone())).collect();
3522
3523        let open_file_after_drop = paths.len() == 1 && paths[0].is_file();
3524
3525        let Some((target_directory, worktree, fs)) = maybe!({
3526            let project = self.project.read(cx);
3527            let fs = project.fs().clone();
3528            let worktree = project.worktree_for_entry(entry_id, cx)?;
3529            let entry = worktree.read(cx).entry_for_id(entry_id)?;
3530            let path = entry.path.clone();
3531            let target_directory = if entry.is_dir() {
3532                path
3533            } else {
3534                path.parent()?.into()
3535            };
3536            Some((target_directory, worktree, fs))
3537        }) else {
3538            return;
3539        };
3540
3541        let mut paths_to_replace = Vec::new();
3542        for path in &paths {
3543            if let Some(name) = path.file_name()
3544                && let Some(name) = name.to_str()
3545            {
3546                let target_path = target_directory.join(RelPath::unix(name).unwrap());
3547                if worktree.read(cx).entry_for_path(&target_path).is_some() {
3548                    paths_to_replace.push((name.to_string(), path.clone()));
3549                }
3550            }
3551        }
3552
3553        cx.spawn_in(window, async move |this, cx| {
3554            async move {
3555                for (filename, original_path) in &paths_to_replace {
3556                    let answer = cx.update(|window, cx| {
3557                        window
3558                            .prompt(
3559                                PromptLevel::Info,
3560                                format!("A file or folder with name {filename} already exists in the destination folder. Do you want to replace it?").as_str(),
3561                                None,
3562                                &["Replace", "Cancel"],
3563                                cx,
3564                            )
3565                    })?.await?;
3566
3567                    if answer == 1
3568                        && let Some(item_idx) = paths.iter().position(|p| p == original_path) {
3569                            paths.remove(item_idx);
3570                        }
3571                }
3572
3573                if paths.is_empty() {
3574                    return Ok(());
3575                }
3576
3577                let task = worktree.update( cx, |worktree, cx| {
3578                    worktree.copy_external_entries(target_directory, paths, fs, cx)
3579                })?;
3580
3581                let opened_entries = task.await.with_context(|| "failed to copy external paths")?;
3582                this.update(cx, |this, cx| {
3583                    if open_file_after_drop && !opened_entries.is_empty() {
3584                        this.open_entry(opened_entries[0], true, false, cx);
3585                    }
3586                })
3587            }
3588            .log_err().await
3589        })
3590        .detach();
3591    }
3592
3593    fn refresh_drag_cursor_style(
3594        &self,
3595        modifiers: &Modifiers,
3596        window: &mut Window,
3597        cx: &mut Context<Self>,
3598    ) {
3599        if let Some(existing_cursor) = cx.active_drag_cursor_style() {
3600            let new_cursor = if Self::is_copy_modifier_set(modifiers) {
3601                CursorStyle::DragCopy
3602            } else {
3603                CursorStyle::PointingHand
3604            };
3605            if existing_cursor != new_cursor {
3606                cx.set_active_drag_cursor_style(new_cursor, window);
3607            }
3608        }
3609    }
3610
3611    fn is_copy_modifier_set(modifiers: &Modifiers) -> bool {
3612        cfg!(target_os = "macos") && modifiers.alt
3613            || cfg!(not(target_os = "macos")) && modifiers.control
3614    }
3615
3616    fn drag_onto(
3617        &mut self,
3618        selections: &DraggedSelection,
3619        target_entry_id: ProjectEntryId,
3620        is_file: bool,
3621        window: &mut Window,
3622        cx: &mut Context<Self>,
3623    ) {
3624        if Self::is_copy_modifier_set(&window.modifiers()) {
3625            let _ = maybe!({
3626                let project = self.project.read(cx);
3627                let target_worktree = project.worktree_for_entry(target_entry_id, cx)?;
3628                let worktree_id = target_worktree.read(cx).id();
3629                let target_entry = target_worktree
3630                    .read(cx)
3631                    .entry_for_id(target_entry_id)?
3632                    .clone();
3633
3634                let mut copy_tasks = Vec::new();
3635                let mut disambiguation_range = None;
3636                for selection in selections.items() {
3637                    let (new_path, new_disambiguation_range) = self.create_paste_path(
3638                        selection,
3639                        (target_worktree.clone(), &target_entry),
3640                        cx,
3641                    )?;
3642
3643                    let task = self.project.update(cx, |project, cx| {
3644                        project.copy_entry(selection.entry_id, (worktree_id, new_path).into(), cx)
3645                    });
3646                    copy_tasks.push(task);
3647                    disambiguation_range = new_disambiguation_range.or(disambiguation_range);
3648                }
3649
3650                let item_count = copy_tasks.len();
3651
3652                cx.spawn_in(window, async move |project_panel, cx| {
3653                    let mut last_succeed = None;
3654                    for task in copy_tasks.into_iter() {
3655                        if let Some(Some(entry)) = task.await.log_err() {
3656                            last_succeed = Some(entry.id);
3657                        }
3658                    }
3659                    // update selection
3660                    if let Some(entry_id) = last_succeed {
3661                        project_panel
3662                            .update_in(cx, |project_panel, window, cx| {
3663                                project_panel.state.selection = Some(SelectedEntry {
3664                                    worktree_id,
3665                                    entry_id,
3666                                });
3667
3668                                // if only one entry was dragged and it was disambiguated, open the rename editor
3669                                if item_count == 1 && disambiguation_range.is_some() {
3670                                    project_panel.rename_impl(disambiguation_range, window, cx);
3671                                }
3672                            })
3673                            .ok();
3674                    }
3675                })
3676                .detach();
3677                Some(())
3678            });
3679        } else {
3680            for selection in selections.items() {
3681                self.move_entry(selection.entry_id, target_entry_id, is_file, cx);
3682            }
3683        }
3684    }
3685
3686    fn index_for_entry(
3687        &self,
3688        entry_id: ProjectEntryId,
3689        worktree_id: WorktreeId,
3690    ) -> Option<(usize, usize, usize)> {
3691        let mut total_ix = 0;
3692        for (worktree_ix, visible) in self.state.visible_entries.iter().enumerate() {
3693            if worktree_id != visible.worktree_id {
3694                total_ix += visible.entries.len();
3695                continue;
3696            }
3697
3698            return visible
3699                .entries
3700                .iter()
3701                .enumerate()
3702                .find(|(_, entry)| entry.id == entry_id)
3703                .map(|(ix, _)| (worktree_ix, ix, total_ix + ix));
3704        }
3705        None
3706    }
3707
3708    fn entry_at_index(&self, index: usize) -> Option<(WorktreeId, GitEntryRef<'_>)> {
3709        let mut offset = 0;
3710        for worktree in &self.state.visible_entries {
3711            let current_len = worktree.entries.len();
3712            if index < offset + current_len {
3713                return worktree
3714                    .entries
3715                    .get(index - offset)
3716                    .map(|entry| (worktree.worktree_id, entry.to_ref()));
3717            }
3718            offset += current_len;
3719        }
3720        None
3721    }
3722
3723    fn iter_visible_entries(
3724        &self,
3725        range: Range<usize>,
3726        window: &mut Window,
3727        cx: &mut Context<ProjectPanel>,
3728        mut callback: impl FnMut(
3729            &Entry,
3730            usize,
3731            &HashSet<Arc<RelPath>>,
3732            &mut Window,
3733            &mut Context<ProjectPanel>,
3734        ),
3735    ) {
3736        let mut ix = 0;
3737        for visible in &self.state.visible_entries {
3738            if ix >= range.end {
3739                return;
3740            }
3741
3742            if ix + visible.entries.len() <= range.start {
3743                ix += visible.entries.len();
3744                continue;
3745            }
3746
3747            let end_ix = range.end.min(ix + visible.entries.len());
3748            let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3749            let entries = visible
3750                .index
3751                .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
3752            let base_index = ix + entry_range.start;
3753            for (i, entry) in visible.entries[entry_range].iter().enumerate() {
3754                let global_index = base_index + i;
3755                callback(entry, global_index, entries, window, cx);
3756            }
3757            ix = end_ix;
3758        }
3759    }
3760
3761    fn for_each_visible_entry(
3762        &self,
3763        range: Range<usize>,
3764        window: &mut Window,
3765        cx: &mut Context<ProjectPanel>,
3766        mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut Window, &mut Context<ProjectPanel>),
3767    ) {
3768        let mut ix = 0;
3769        for visible in &self.state.visible_entries {
3770            if ix >= range.end {
3771                return;
3772            }
3773
3774            if ix + visible.entries.len() <= range.start {
3775                ix += visible.entries.len();
3776                continue;
3777            }
3778
3779            let end_ix = range.end.min(ix + visible.entries.len());
3780            let git_status_setting = {
3781                let settings = ProjectPanelSettings::get_global(cx);
3782                settings.git_status
3783            };
3784            if let Some(worktree) = self
3785                .project
3786                .read(cx)
3787                .worktree_for_id(visible.worktree_id, cx)
3788            {
3789                let snapshot = worktree.read(cx).snapshot();
3790                let root_name = snapshot.root_name();
3791
3792                let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3793                let entries = visible
3794                    .index
3795                    .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
3796                for entry in visible.entries[entry_range].iter() {
3797                    let status = git_status_setting
3798                        .then_some(entry.git_summary)
3799                        .unwrap_or_default();
3800
3801                    let mut details = self.details_for_entry(
3802                        entry,
3803                        visible.worktree_id,
3804                        root_name,
3805                        entries,
3806                        status,
3807                        None,
3808                        window,
3809                        cx,
3810                    );
3811
3812                    if let Some(edit_state) = &self.state.edit_state {
3813                        let is_edited_entry = if edit_state.is_new_entry() {
3814                            entry.id == NEW_ENTRY_ID
3815                        } else {
3816                            entry.id == edit_state.entry_id
3817                                || self.state.ancestors.get(&entry.id).is_some_and(
3818                                    |auto_folded_dirs| {
3819                                        auto_folded_dirs.ancestors.contains(&edit_state.entry_id)
3820                                    },
3821                                )
3822                        };
3823
3824                        if is_edited_entry {
3825                            if let Some(processing_filename) = &edit_state.processing_filename {
3826                                details.is_processing = true;
3827                                if let Some(ancestors) = edit_state
3828                                    .leaf_entry_id
3829                                    .and_then(|entry| self.state.ancestors.get(&entry))
3830                                {
3831                                    let position = ancestors.ancestors.iter().position(|entry_id| *entry_id == edit_state.entry_id).expect("Edited sub-entry should be an ancestor of selected leaf entry") + 1;
3832                                    let all_components = ancestors.ancestors.len();
3833
3834                                    let prefix_components = all_components - position;
3835                                    let suffix_components = position.checked_sub(1);
3836                                    let mut previous_components =
3837                                        Path::new(&details.filename).components();
3838                                    let mut new_path = previous_components
3839                                        .by_ref()
3840                                        .take(prefix_components)
3841                                        .collect::<PathBuf>();
3842                                    if let Some(last_component) =
3843                                        processing_filename.components().next_back()
3844                                    {
3845                                        new_path.push(last_component);
3846                                        previous_components.next();
3847                                    }
3848
3849                                    if suffix_components.is_some() {
3850                                        new_path.push(previous_components);
3851                                    }
3852                                    if let Some(str) = new_path.to_str() {
3853                                        details.filename.clear();
3854                                        details.filename.push_str(str);
3855                                    }
3856                                } else {
3857                                    details.filename.clear();
3858                                    details.filename.push_str(processing_filename.as_unix_str());
3859                                }
3860                            } else {
3861                                if edit_state.is_new_entry() {
3862                                    details.filename.clear();
3863                                }
3864                                details.is_editing = true;
3865                            }
3866                        }
3867                    }
3868
3869                    callback(entry.id, details, window, cx);
3870                }
3871            }
3872            ix = end_ix;
3873        }
3874    }
3875
3876    fn find_entry_in_worktree(
3877        &self,
3878        worktree_id: WorktreeId,
3879        reverse_search: bool,
3880        only_visible_entries: bool,
3881        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
3882        cx: &mut Context<Self>,
3883    ) -> Option<GitEntry> {
3884        if only_visible_entries {
3885            let entries = self
3886                .state
3887                .visible_entries
3888                .iter()
3889                .find_map(|visible| {
3890                    if worktree_id == visible.worktree_id {
3891                        Some(&visible.entries)
3892                    } else {
3893                        None
3894                    }
3895                })?
3896                .clone();
3897
3898            return utils::ReversibleIterable::new(entries.iter(), reverse_search)
3899                .find(|ele| predicate(ele.to_ref(), worktree_id))
3900                .cloned();
3901        }
3902
3903        let repo_snapshots = self
3904            .project
3905            .read(cx)
3906            .git_store()
3907            .read(cx)
3908            .repo_snapshots(cx);
3909        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
3910        worktree.read_with(cx, |tree, _| {
3911            utils::ReversibleIterable::new(
3912                GitTraversal::new(&repo_snapshots, tree.entries(true, 0usize)),
3913                reverse_search,
3914            )
3915            .find_single_ended(|ele| predicate(*ele, worktree_id))
3916            .map(|ele| ele.to_owned())
3917        })
3918    }
3919
3920    fn find_entry(
3921        &self,
3922        start: Option<&SelectedEntry>,
3923        reverse_search: bool,
3924        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
3925        cx: &mut Context<Self>,
3926    ) -> Option<SelectedEntry> {
3927        let mut worktree_ids: Vec<_> = self
3928            .state
3929            .visible_entries
3930            .iter()
3931            .map(|worktree| worktree.worktree_id)
3932            .collect();
3933        let repo_snapshots = self
3934            .project
3935            .read(cx)
3936            .git_store()
3937            .read(cx)
3938            .repo_snapshots(cx);
3939
3940        let mut last_found: Option<SelectedEntry> = None;
3941
3942        if let Some(start) = start {
3943            let worktree = self
3944                .project
3945                .read(cx)
3946                .worktree_for_id(start.worktree_id, cx)?
3947                .read(cx);
3948
3949            let search = {
3950                let entry = worktree.entry_for_id(start.entry_id)?;
3951                let root_entry = worktree.root_entry()?;
3952                let tree_id = worktree.id();
3953
3954                let mut first_iter = GitTraversal::new(
3955                    &repo_snapshots,
3956                    worktree.traverse_from_path(true, true, true, entry.path.as_ref()),
3957                );
3958
3959                if reverse_search {
3960                    first_iter.next();
3961                }
3962
3963                let first = first_iter
3964                    .enumerate()
3965                    .take_until(|(count, entry)| entry.entry == root_entry && *count != 0usize)
3966                    .map(|(_, entry)| entry)
3967                    .find(|ele| predicate(*ele, tree_id))
3968                    .map(|ele| ele.to_owned());
3969
3970                let second_iter =
3971                    GitTraversal::new(&repo_snapshots, worktree.entries(true, 0usize));
3972
3973                let second = if reverse_search {
3974                    second_iter
3975                        .take_until(|ele| ele.id == start.entry_id)
3976                        .filter(|ele| predicate(*ele, tree_id))
3977                        .last()
3978                        .map(|ele| ele.to_owned())
3979                } else {
3980                    second_iter
3981                        .take_while(|ele| ele.id != start.entry_id)
3982                        .filter(|ele| predicate(*ele, tree_id))
3983                        .last()
3984                        .map(|ele| ele.to_owned())
3985                };
3986
3987                if reverse_search {
3988                    Some((second, first))
3989                } else {
3990                    Some((first, second))
3991                }
3992            };
3993
3994            if let Some((first, second)) = search {
3995                let first = first.map(|entry| SelectedEntry {
3996                    worktree_id: start.worktree_id,
3997                    entry_id: entry.id,
3998                });
3999
4000                let second = second.map(|entry| SelectedEntry {
4001                    worktree_id: start.worktree_id,
4002                    entry_id: entry.id,
4003                });
4004
4005                if first.is_some() {
4006                    return first;
4007                }
4008                last_found = second;
4009
4010                let idx = worktree_ids
4011                    .iter()
4012                    .enumerate()
4013                    .find(|(_, ele)| **ele == start.worktree_id)
4014                    .map(|(idx, _)| idx);
4015
4016                if let Some(idx) = idx {
4017                    worktree_ids.rotate_left(idx + 1usize);
4018                    worktree_ids.pop();
4019                }
4020            }
4021        }
4022
4023        for tree_id in worktree_ids.into_iter() {
4024            if let Some(found) =
4025                self.find_entry_in_worktree(tree_id, reverse_search, false, &predicate, cx)
4026            {
4027                return Some(SelectedEntry {
4028                    worktree_id: tree_id,
4029                    entry_id: found.id,
4030                });
4031            }
4032        }
4033
4034        last_found
4035    }
4036
4037    fn find_visible_entry(
4038        &self,
4039        start: Option<&SelectedEntry>,
4040        reverse_search: bool,
4041        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4042        cx: &mut Context<Self>,
4043    ) -> Option<SelectedEntry> {
4044        let mut worktree_ids: Vec<_> = self
4045            .state
4046            .visible_entries
4047            .iter()
4048            .map(|worktree| worktree.worktree_id)
4049            .collect();
4050
4051        let mut last_found: Option<SelectedEntry> = None;
4052
4053        if let Some(start) = start {
4054            let entries = self
4055                .state
4056                .visible_entries
4057                .iter()
4058                .find(|worktree| worktree.worktree_id == start.worktree_id)
4059                .map(|worktree| &worktree.entries)?;
4060
4061            let mut start_idx = entries
4062                .iter()
4063                .enumerate()
4064                .find(|(_, ele)| ele.id == start.entry_id)
4065                .map(|(idx, _)| idx)?;
4066
4067            if reverse_search {
4068                start_idx = start_idx.saturating_add(1usize);
4069            }
4070
4071            let (left, right) = entries.split_at_checked(start_idx)?;
4072
4073            let (first_iter, second_iter) = if reverse_search {
4074                (
4075                    utils::ReversibleIterable::new(left.iter(), reverse_search),
4076                    utils::ReversibleIterable::new(right.iter(), reverse_search),
4077                )
4078            } else {
4079                (
4080                    utils::ReversibleIterable::new(right.iter(), reverse_search),
4081                    utils::ReversibleIterable::new(left.iter(), reverse_search),
4082                )
4083            };
4084
4085            let first_search = first_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
4086            let second_search = second_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
4087
4088            if first_search.is_some() {
4089                return first_search.map(|entry| SelectedEntry {
4090                    worktree_id: start.worktree_id,
4091                    entry_id: entry.id,
4092                });
4093            }
4094
4095            last_found = second_search.map(|entry| SelectedEntry {
4096                worktree_id: start.worktree_id,
4097                entry_id: entry.id,
4098            });
4099
4100            let idx = worktree_ids
4101                .iter()
4102                .enumerate()
4103                .find(|(_, ele)| **ele == start.worktree_id)
4104                .map(|(idx, _)| idx);
4105
4106            if let Some(idx) = idx {
4107                worktree_ids.rotate_left(idx + 1usize);
4108                worktree_ids.pop();
4109            }
4110        }
4111
4112        for tree_id in worktree_ids.into_iter() {
4113            if let Some(found) =
4114                self.find_entry_in_worktree(tree_id, reverse_search, true, &predicate, cx)
4115            {
4116                return Some(SelectedEntry {
4117                    worktree_id: tree_id,
4118                    entry_id: found.id,
4119                });
4120            }
4121        }
4122
4123        last_found
4124    }
4125
4126    fn calculate_depth_and_difference(
4127        entry: &Entry,
4128        visible_worktree_entries: &HashSet<Arc<RelPath>>,
4129    ) -> (usize, usize) {
4130        let (depth, difference) = entry
4131            .path
4132            .ancestors()
4133            .skip(1) // Skip the entry itself
4134            .find_map(|ancestor| {
4135                if let Some(parent_entry) = visible_worktree_entries.get(ancestor) {
4136                    let entry_path_components_count = entry.path.components().count();
4137                    let parent_path_components_count = parent_entry.components().count();
4138                    let difference = entry_path_components_count - parent_path_components_count;
4139                    let depth = parent_entry
4140                        .ancestors()
4141                        .skip(1)
4142                        .filter(|ancestor| visible_worktree_entries.contains(*ancestor))
4143                        .count();
4144                    Some((depth + 1, difference))
4145                } else {
4146                    None
4147                }
4148            })
4149            .unwrap_or_else(|| (0, entry.path.components().count()));
4150
4151        (depth, difference)
4152    }
4153
4154    fn highlight_entry_for_external_drag(
4155        &self,
4156        target_entry: &Entry,
4157        target_worktree: &Worktree,
4158    ) -> Option<ProjectEntryId> {
4159        // Always highlight directory or parent directory if it's file
4160        if target_entry.is_dir() {
4161            Some(target_entry.id)
4162        } else {
4163            target_entry
4164                .path
4165                .parent()
4166                .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4167                .map(|parent_entry| parent_entry.id)
4168        }
4169    }
4170
4171    fn highlight_entry_for_selection_drag(
4172        &self,
4173        target_entry: &Entry,
4174        target_worktree: &Worktree,
4175        drag_state: &DraggedSelection,
4176        cx: &Context<Self>,
4177    ) -> Option<ProjectEntryId> {
4178        let target_parent_path = target_entry.path.parent();
4179
4180        // In case of single item drag, we do not highlight existing
4181        // directory which item belongs too
4182        if drag_state.items().count() == 1
4183            && drag_state.active_selection.worktree_id == target_worktree.id()
4184        {
4185            let active_entry_path = self
4186                .project
4187                .read(cx)
4188                .path_for_entry(drag_state.active_selection.entry_id, cx)?;
4189
4190            if let Some(active_parent_path) = active_entry_path.path.parent() {
4191                // Do not highlight active entry parent
4192                if active_parent_path == target_entry.path.as_ref() {
4193                    return None;
4194                }
4195
4196                // Do not highlight active entry sibling files
4197                if Some(active_parent_path) == target_parent_path && target_entry.is_file() {
4198                    return None;
4199                }
4200            }
4201        }
4202
4203        // Always highlight directory or parent directory if it's file
4204        if target_entry.is_dir() {
4205            Some(target_entry.id)
4206        } else {
4207            target_parent_path
4208                .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4209                .map(|parent_entry| parent_entry.id)
4210        }
4211    }
4212
4213    fn should_highlight_background_for_selection_drag(
4214        &self,
4215        drag_state: &DraggedSelection,
4216        last_root_id: ProjectEntryId,
4217        cx: &App,
4218    ) -> bool {
4219        // Always highlight for multiple entries
4220        if drag_state.items().count() > 1 {
4221            return true;
4222        }
4223
4224        // Since root will always have empty relative path
4225        if let Some(entry_path) = self
4226            .project
4227            .read(cx)
4228            .path_for_entry(drag_state.active_selection.entry_id, cx)
4229        {
4230            if let Some(parent_path) = entry_path.path.parent() {
4231                if !parent_path.is_empty() {
4232                    return true;
4233                }
4234            }
4235        }
4236
4237        // If parent is empty, check if different worktree
4238        if let Some(last_root_worktree_id) = self
4239            .project
4240            .read(cx)
4241            .worktree_id_for_entry(last_root_id, cx)
4242        {
4243            if drag_state.active_selection.worktree_id != last_root_worktree_id {
4244                return true;
4245            }
4246        }
4247
4248        false
4249    }
4250
4251    fn render_entry(
4252        &self,
4253        entry_id: ProjectEntryId,
4254        details: EntryDetails,
4255        window: &mut Window,
4256        cx: &mut Context<Self>,
4257    ) -> Stateful<Div> {
4258        const GROUP_NAME: &str = "project_entry";
4259
4260        let kind = details.kind;
4261        let is_sticky = details.sticky.is_some();
4262        let sticky_index = details.sticky.as_ref().map(|this| this.sticky_index);
4263        let settings = ProjectPanelSettings::get_global(cx);
4264        let show_editor = details.is_editing && !details.is_processing;
4265
4266        let selection = SelectedEntry {
4267            worktree_id: details.worktree_id,
4268            entry_id,
4269        };
4270
4271        let is_marked = self.marked_entries.contains(&selection);
4272        let is_active = self
4273            .state
4274            .selection
4275            .is_some_and(|selection| selection.entry_id == entry_id);
4276
4277        let file_name = details.filename.clone();
4278
4279        let mut icon = details.icon.clone();
4280        if settings.file_icons && show_editor && details.kind.is_file() {
4281            let filename = self.filename_editor.read(cx).text(cx);
4282            if filename.len() > 2 {
4283                icon = FileIcons::get_icon(Path::new(&filename), cx);
4284            }
4285        }
4286
4287        let filename_text_color = details.filename_text_color;
4288        let diagnostic_severity = details.diagnostic_severity;
4289        let item_colors = get_item_color(is_sticky, cx);
4290
4291        let canonical_path = details
4292            .canonical_path
4293            .as_ref()
4294            .map(|f| f.to_string_lossy().into_owned());
4295        let path_style = self.project.read(cx).path_style(cx);
4296        let path = details.path.clone();
4297        let path_for_external_paths = path.clone();
4298        let path_for_dragged_selection = path.clone();
4299
4300        let depth = details.depth;
4301        let worktree_id = details.worktree_id;
4302        let dragged_selection = DraggedSelection {
4303            active_selection: SelectedEntry {
4304                worktree_id: selection.worktree_id,
4305                entry_id: self.resolve_entry(selection.entry_id),
4306            },
4307            marked_selections: Arc::from(self.marked_entries.clone()),
4308        };
4309
4310        let bg_color = if is_marked {
4311            item_colors.marked
4312        } else {
4313            item_colors.default
4314        };
4315
4316        let bg_hover_color = if is_marked {
4317            item_colors.marked
4318        } else {
4319            item_colors.hover
4320        };
4321
4322        let validation_color_and_message = if show_editor {
4323            match self
4324                .state
4325                .edit_state
4326                .as_ref()
4327                .map_or(ValidationState::None, |e| e.validation_state.clone())
4328            {
4329                ValidationState::Error(msg) => Some((Color::Error.color(cx), msg)),
4330                ValidationState::Warning(msg) => Some((Color::Warning.color(cx), msg)),
4331                ValidationState::None => None,
4332            }
4333        } else {
4334            None
4335        };
4336
4337        let border_color =
4338            if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4339                match validation_color_and_message {
4340                    Some((color, _)) => color,
4341                    None => item_colors.focused,
4342                }
4343            } else {
4344                bg_color
4345            };
4346
4347        let border_hover_color =
4348            if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4349                match validation_color_and_message {
4350                    Some((color, _)) => color,
4351                    None => item_colors.focused,
4352                }
4353            } else {
4354                bg_hover_color
4355            };
4356
4357        let folded_directory_drag_target = self.folded_directory_drag_target;
4358        let is_highlighted = {
4359            if let Some(highlight_entry_id) =
4360                self.drag_target_entry
4361                    .as_ref()
4362                    .and_then(|drag_target| match drag_target {
4363                        DragTarget::Entry {
4364                            highlight_entry_id, ..
4365                        } => Some(*highlight_entry_id),
4366                        DragTarget::Background => self.state.last_worktree_root_id,
4367                    })
4368            {
4369                // Highlight if same entry or it's children
4370                if entry_id == highlight_entry_id {
4371                    true
4372                } else {
4373                    maybe!({
4374                        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4375                        let highlight_entry = worktree.read(cx).entry_for_id(highlight_entry_id)?;
4376                        Some(path.starts_with(&highlight_entry.path))
4377                    })
4378                    .unwrap_or(false)
4379                }
4380            } else {
4381                false
4382            }
4383        };
4384
4385        let id: ElementId = if is_sticky {
4386            SharedString::from(format!("project_panel_sticky_item_{}", entry_id.to_usize())).into()
4387        } else {
4388            (entry_id.to_proto() as usize).into()
4389        };
4390
4391        div()
4392            .id(id.clone())
4393            .relative()
4394            .group(GROUP_NAME)
4395            .cursor_pointer()
4396            .rounded_none()
4397            .bg(bg_color)
4398            .border_1()
4399            .border_r_2()
4400            .border_color(border_color)
4401            .hover(|style| style.bg(bg_hover_color).border_color(border_hover_color))
4402            .when(is_sticky, |this| {
4403                this.block_mouse_except_scroll()
4404            })
4405            .when(!is_sticky, |this| {
4406                this
4407                .when(is_highlighted && folded_directory_drag_target.is_none(), |this| this.border_color(transparent_white()).bg(item_colors.drag_over))
4408                .when(settings.drag_and_drop, |this| this
4409                .on_drag_move::<ExternalPaths>(cx.listener(
4410                    move |this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
4411                        let is_current_target = this.drag_target_entry.as_ref()
4412                             .and_then(|entry| match entry {
4413                                 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4414                                 DragTarget::Background { .. } => None,
4415                             }) == Some(entry_id);
4416
4417                        if !event.bounds.contains(&event.event.position) {
4418                            // Entry responsible for setting drag target is also responsible to
4419                            // clear it up after drag is out of bounds
4420                            if is_current_target {
4421                                this.drag_target_entry = None;
4422                            }
4423                            return;
4424                        }
4425
4426                        if is_current_target {
4427                            return;
4428                        }
4429
4430                        this.marked_entries.clear();
4431
4432                        let Some((entry_id, highlight_entry_id)) = maybe!({
4433                            let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4434                            let target_entry = target_worktree.entry_for_path(&path_for_external_paths)?;
4435                            let highlight_entry_id = this.highlight_entry_for_external_drag(target_entry, target_worktree)?;
4436                            Some((target_entry.id, highlight_entry_id))
4437                        }) else {
4438                            return;
4439                        };
4440
4441                        this.drag_target_entry = Some(DragTarget::Entry {
4442                            entry_id,
4443                            highlight_entry_id,
4444                        });
4445
4446                    },
4447                ))
4448                .on_drop(cx.listener(
4449                    move |this, external_paths: &ExternalPaths, window, cx| {
4450                        this.drag_target_entry = None;
4451                        this.hover_scroll_task.take();
4452                        this.drop_external_files(external_paths.paths(), entry_id, window, cx);
4453                        cx.stop_propagation();
4454                    },
4455                ))
4456                .on_drag_move::<DraggedSelection>(cx.listener(
4457                    move |this, event: &DragMoveEvent<DraggedSelection>, window, cx| {
4458                        let is_current_target = this.drag_target_entry.as_ref()
4459                             .and_then(|entry| match entry {
4460                                 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4461                                 DragTarget::Background { .. } => None,
4462                             }) == Some(entry_id);
4463
4464                        if !event.bounds.contains(&event.event.position) {
4465                            // Entry responsible for setting drag target is also responsible to
4466                            // clear it up after drag is out of bounds
4467                            if is_current_target {
4468                                this.drag_target_entry = None;
4469                            }
4470                            return;
4471                        }
4472
4473                        if is_current_target {
4474                            return;
4475                        }
4476
4477                        let drag_state = event.drag(cx);
4478
4479                        if drag_state.items().count() == 1 {
4480                            this.marked_entries.clear();
4481                            this.marked_entries.push(drag_state.active_selection);
4482                        }
4483
4484                        let Some((entry_id, highlight_entry_id)) = maybe!({
4485                            let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4486                            let target_entry = target_worktree.entry_for_path(&path_for_dragged_selection)?;
4487                            let highlight_entry_id = this.highlight_entry_for_selection_drag(target_entry, target_worktree, drag_state, cx)?;
4488                            Some((target_entry.id, highlight_entry_id))
4489                        }) else {
4490                            return;
4491                        };
4492
4493                        this.drag_target_entry = Some(DragTarget::Entry {
4494                            entry_id,
4495                            highlight_entry_id,
4496                        });
4497
4498                        this.hover_expand_task.take();
4499
4500                        if !kind.is_dir()
4501                            || this
4502                                .state
4503                                .expanded_dir_ids
4504                                .get(&details.worktree_id)
4505                                .is_some_and(|ids| ids.binary_search(&entry_id).is_ok())
4506                        {
4507                            return;
4508                        }
4509
4510                        let bounds = event.bounds;
4511                        this.hover_expand_task =
4512                            Some(cx.spawn_in(window, async move |this, cx| {
4513                                cx.background_executor()
4514                                    .timer(Duration::from_millis(500))
4515                                    .await;
4516                                this.update_in(cx, |this, window, cx| {
4517                                    this.hover_expand_task.take();
4518                                    if this.drag_target_entry.as_ref().and_then(|entry| match entry {
4519                                        DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4520                                        DragTarget::Background { .. } => None,
4521                                    }) == Some(entry_id)
4522                                        && bounds.contains(&window.mouse_position())
4523                                    {
4524                                        this.expand_entry(worktree_id, entry_id, cx);
4525                                        this.update_visible_entries(
4526                                            Some((worktree_id, entry_id)),
4527                                            false,
4528                                            false,
4529                                            window,
4530                                            cx,
4531                                        );
4532                                        cx.notify();
4533                                    }
4534                                })
4535                                .ok();
4536                            }));
4537                    },
4538                ))
4539                .on_drag(
4540                    dragged_selection,
4541                    {
4542                        let active_component = self.state.ancestors.get(&entry_id).and_then(|ancestors| ancestors.active_component(&details.filename));
4543                        move |selection, click_offset, _window, cx| {
4544                            let filename = active_component.as_ref().unwrap_or_else(|| &details.filename);
4545                            cx.new(|_| DraggedProjectEntryView {
4546                                icon: details.icon.clone(),
4547                                filename: filename.clone(),
4548                                click_offset,
4549                                selection: selection.active_selection,
4550                                selections: selection.marked_selections.clone(),
4551                            })
4552                        }
4553                    }
4554                )
4555                .on_drop(
4556                    cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4557                        this.drag_target_entry = None;
4558                        this.hover_scroll_task.take();
4559                        this.hover_expand_task.take();
4560                        if folded_directory_drag_target.is_some() {
4561                            return;
4562                        }
4563                        this.drag_onto(selections, entry_id, kind.is_file(), window, cx);
4564                    }),
4565                ))
4566            })
4567            .on_mouse_down(
4568                MouseButton::Left,
4569                cx.listener(move |this, _, _, cx| {
4570                    this.mouse_down = true;
4571                    cx.propagate();
4572                }),
4573            )
4574            .on_click(
4575                cx.listener(move |project_panel, event: &gpui::ClickEvent, window, cx| {
4576                    if event.is_right_click() || event.first_focus()
4577                        || show_editor
4578                    {
4579                        return;
4580                    }
4581                    if event.standard_click() {
4582                        project_panel.mouse_down = false;
4583                    }
4584                    cx.stop_propagation();
4585
4586                    if let Some(selection) = project_panel.state.selection.filter(|_| event.modifiers().shift) {
4587                        let current_selection = project_panel.index_for_selection(selection);
4588                        let clicked_entry = SelectedEntry {
4589                            entry_id,
4590                            worktree_id,
4591                        };
4592                        let target_selection = project_panel.index_for_selection(clicked_entry);
4593                        if let Some(((_, _, source_index), (_, _, target_index))) =
4594                            current_selection.zip(target_selection)
4595                        {
4596                            let range_start = source_index.min(target_index);
4597                            let range_end = source_index.max(target_index) + 1;
4598                            let mut new_selections = Vec::new();
4599                            project_panel.for_each_visible_entry(
4600                                range_start..range_end,
4601                                window,
4602                                cx,
4603                                |entry_id, details, _, _| {
4604                                    new_selections.push(SelectedEntry {
4605                                        entry_id,
4606                                        worktree_id: details.worktree_id,
4607                                    });
4608                                },
4609                            );
4610
4611                            for selection in &new_selections {
4612                                if !project_panel.marked_entries.contains(selection) {
4613                                    project_panel.marked_entries.push(*selection);
4614                                }
4615                            }
4616
4617                            project_panel.state.selection = Some(clicked_entry);
4618                            if !project_panel.marked_entries.contains(&clicked_entry) {
4619                                project_panel.marked_entries.push(clicked_entry);
4620                            }
4621                        }
4622                    } else if event.modifiers().secondary() {
4623                        if event.click_count() > 1 {
4624                            project_panel.split_entry(entry_id, false, None, cx);
4625                        } else {
4626                            project_panel.state.selection = Some(selection);
4627                            if let Some(position) = project_panel.marked_entries.iter().position(|e| *e == selection) {
4628                                project_panel.marked_entries.remove(position);
4629                            } else {
4630                                project_panel.marked_entries.push(selection);
4631                            }
4632                        }
4633                    } else if kind.is_dir() {
4634                        project_panel.marked_entries.clear();
4635                        if is_sticky
4636                            && let Some((_, _, index)) = project_panel.index_for_entry(entry_id, worktree_id) {
4637                                project_panel.scroll_handle.scroll_to_item_strict_with_offset(index, ScrollStrategy::Top, sticky_index.unwrap_or(0));
4638                                cx.notify();
4639                                // move down by 1px so that clicked item
4640                                // don't count as sticky anymore
4641                                cx.on_next_frame(window, |_, window, cx| {
4642                                    cx.on_next_frame(window, |this, _, cx| {
4643                                        let mut offset = this.scroll_handle.offset();
4644                                        offset.y += px(1.);
4645                                        this.scroll_handle.set_offset(offset);
4646                                        cx.notify();
4647                                    });
4648                                });
4649                                return;
4650                            }
4651                        if event.modifiers().alt {
4652                            project_panel.toggle_expand_all(entry_id, window, cx);
4653                        } else {
4654                            project_panel.toggle_expanded(entry_id, window, cx);
4655                        }
4656                    } else {
4657                        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
4658                        let click_count = event.click_count();
4659                        let focus_opened_item = !preview_tabs_enabled || click_count > 1;
4660                        let allow_preview = preview_tabs_enabled && click_count == 1;
4661                        project_panel.open_entry(entry_id, focus_opened_item, allow_preview, cx);
4662                    }
4663                }),
4664            )
4665            .child(
4666                ListItem::new(id)
4667                    .indent_level(depth)
4668                    .indent_step_size(px(settings.indent_size))
4669                    .spacing(match settings.entry_spacing {
4670                        ProjectPanelEntrySpacing::Comfortable => ListItemSpacing::Dense,
4671                        ProjectPanelEntrySpacing::Standard => {
4672                            ListItemSpacing::ExtraDense
4673                        }
4674                    })
4675                    .selectable(false)
4676                    .when_some(canonical_path, |this, path| {
4677                        this.end_slot::<AnyElement>(
4678                            div()
4679                                .id("symlink_icon")
4680                                .pr_3()
4681                                .tooltip(move |window, cx| {
4682                                    Tooltip::with_meta(
4683                                        path.to_string(),
4684                                        None,
4685                                        "Symbolic Link",
4686                                        window,
4687                                        cx,
4688                                    )
4689                                })
4690                                .child(
4691                                    Icon::new(IconName::ArrowUpRight)
4692                                        .size(IconSize::Indicator)
4693                                        .color(filename_text_color),
4694                                )
4695                                .into_any_element(),
4696                        )
4697                    })
4698                    .child(if let Some(icon) = &icon {
4699                        if let Some((_, decoration_color)) =
4700                            entry_diagnostic_aware_icon_decoration_and_color(diagnostic_severity)
4701                        {
4702                            let is_warning = diagnostic_severity
4703                                .map(|severity| matches!(severity, DiagnosticSeverity::WARNING))
4704                                .unwrap_or(false);
4705                            div().child(
4706                                DecoratedIcon::new(
4707                                    Icon::from_path(icon.clone()).color(Color::Muted),
4708                                    Some(
4709                                        IconDecoration::new(
4710                                            if kind.is_file() {
4711                                                if is_warning {
4712                                                    IconDecorationKind::Triangle
4713                                                } else {
4714                                                    IconDecorationKind::X
4715                                                }
4716                                            } else {
4717                                                IconDecorationKind::Dot
4718                                            },
4719                                            bg_color,
4720                                            cx,
4721                                        )
4722                                        .group_name(Some(GROUP_NAME.into()))
4723                                        .knockout_hover_color(bg_hover_color)
4724                                        .color(decoration_color.color(cx))
4725                                        .position(Point {
4726                                            x: px(-2.),
4727                                            y: px(-2.),
4728                                        }),
4729                                    ),
4730                                )
4731                                .into_any_element(),
4732                            )
4733                        } else {
4734                            h_flex().child(Icon::from_path(icon.to_string()).color(Color::Muted))
4735                        }
4736                    } else if let Some((icon_name, color)) =
4737                        entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
4738                    {
4739                        h_flex()
4740                            .size(IconSize::default().rems())
4741                            .child(Icon::new(icon_name).color(color).size(IconSize::Small))
4742                    } else {
4743                        h_flex()
4744                            .size(IconSize::default().rems())
4745                            .invisible()
4746                            .flex_none()
4747                    })
4748                    .child(
4749                        if let (Some(editor), true) = (Some(&self.filename_editor), show_editor) {
4750                            h_flex().h_6().w_full().child(editor.clone())
4751                        } else {
4752                            h_flex().h_6().map(|mut this| {
4753                                if let Some(folded_ancestors) = self.state.ancestors.get(&entry_id) {
4754                                    let components = Path::new(&file_name)
4755                                        .components()
4756                                        .map(|comp| comp.as_os_str().to_string_lossy().into_owned())
4757                                        .collect::<Vec<_>>();
4758                                    let active_index = folded_ancestors.active_index();
4759                                    let components_len = components.len();
4760                                    let delimiter = SharedString::new(path_style.separator());
4761                                    for (index, component) in components.iter().enumerate() {
4762                                        if index != 0 {
4763                                                let delimiter_target_index = index - 1;
4764                                                let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - delimiter_target_index).cloned();
4765                                                this = this.child(
4766                                                    div()
4767                                                    .when(!is_sticky, |div| {
4768                                                        div
4769                                                            .when(settings.drag_and_drop, |div| div
4770                                                            .on_drop(cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4771                                                            this.hover_scroll_task.take();
4772                                                            this.drag_target_entry = None;
4773                                                            this.folded_directory_drag_target = None;
4774                                                            if let Some(target_entry_id) = target_entry_id {
4775                                                                this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4776                                                            }
4777                                                        }))
4778                                                        .on_drag_move(cx.listener(
4779                                                            move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4780                                                                if event.bounds.contains(&event.event.position) {
4781                                                                    this.folded_directory_drag_target = Some(
4782                                                                        FoldedDirectoryDragTarget {
4783                                                                            entry_id,
4784                                                                            index: delimiter_target_index,
4785                                                                            is_delimiter_target: true,
4786                                                                        }
4787                                                                    );
4788                                                                } else {
4789                                                                    let is_current_target = this.folded_directory_drag_target
4790                                                                        .is_some_and(|target|
4791                                                                            target.entry_id == entry_id &&
4792                                                                            target.index == delimiter_target_index &&
4793                                                                            target.is_delimiter_target
4794                                                                        );
4795                                                                    if is_current_target {
4796                                                                        this.folded_directory_drag_target = None;
4797                                                                    }
4798                                                                }
4799
4800                                                            },
4801                                                        )))
4802                                                    })
4803                                                    .child(
4804                                                        Label::new(delimiter.clone())
4805                                                            .single_line()
4806                                                            .color(filename_text_color)
4807                                                    )
4808                                                );
4809                                        }
4810                                        let id = SharedString::from(format!(
4811                                            "project_panel_path_component_{}_{index}",
4812                                            entry_id.to_usize()
4813                                        ));
4814                                        let label = div()
4815                                            .id(id)
4816                                            .when(!is_sticky,| div| {
4817                                                div
4818                                                .when(index != components_len - 1, |div|{
4819                                                    let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - index).cloned();
4820                                                    div
4821                                                    .when(settings.drag_and_drop, |div| div
4822                                                    .on_drag_move(cx.listener(
4823                                                        move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4824                                                        if event.bounds.contains(&event.event.position) {
4825                                                                this.folded_directory_drag_target = Some(
4826                                                                    FoldedDirectoryDragTarget {
4827                                                                        entry_id,
4828                                                                        index,
4829                                                                        is_delimiter_target: false,
4830                                                                    }
4831                                                                );
4832                                                            } else {
4833                                                                let is_current_target = this.folded_directory_drag_target
4834                                                                    .as_ref()
4835                                                                    .is_some_and(|target|
4836                                                                        target.entry_id == entry_id &&
4837                                                                        target.index == index &&
4838                                                                        !target.is_delimiter_target
4839                                                                    );
4840                                                                if is_current_target {
4841                                                                    this.folded_directory_drag_target = None;
4842                                                                }
4843                                                            }
4844                                                        },
4845                                                    ))
4846                                                    .on_drop(cx.listener(move |this, selections: &DraggedSelection, window,cx| {
4847                                                        this.hover_scroll_task.take();
4848                                                        this.drag_target_entry = None;
4849                                                        this.folded_directory_drag_target = None;
4850                                                        if let Some(target_entry_id) = target_entry_id {
4851                                                            this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4852                                                        }
4853                                                    }))
4854                                                    .when(folded_directory_drag_target.is_some_and(|target|
4855                                                        target.entry_id == entry_id &&
4856                                                        target.index == index
4857                                                    ), |this| {
4858                                                        this.bg(item_colors.drag_over)
4859                                                    }))
4860                                                })
4861                                            })
4862                                            .on_mouse_down(
4863                                                MouseButton::Left,
4864                                                cx.listener(move |this, _, _, cx| {
4865                                                    if index != active_index
4866                                                        && let Some(folds) =
4867                                                            this.state.ancestors.get_mut(&entry_id)
4868                                                        {
4869                                                            folds.current_ancestor_depth =
4870                                                                components_len - 1 - index;
4871                                                            cx.notify();
4872                                                        }
4873                                                }),
4874                                            )
4875                                            .child(
4876                                                Label::new(component)
4877                                                    .single_line()
4878                                                    .color(filename_text_color)
4879                                                    .when(
4880                                                        index == active_index
4881                                                            && (is_active || is_marked),
4882                                                        |this| this.underline(),
4883                                                    ),
4884                                            );
4885
4886                                        this = this.child(label);
4887                                    }
4888
4889                                    this
4890                                } else {
4891                                    this.child(
4892                                        Label::new(file_name)
4893                                            .single_line()
4894                                            .color(filename_text_color),
4895                                    )
4896                                }
4897                            })
4898                        },
4899                    )
4900                    .on_secondary_mouse_down(cx.listener(
4901                        move |this, event: &MouseDownEvent, window, cx| {
4902                            // Stop propagation to prevent the catch-all context menu for the project
4903                            // panel from being deployed.
4904                            cx.stop_propagation();
4905                            // Some context menu actions apply to all marked entries. If the user
4906                            // right-clicks on an entry that is not marked, they may not realize the
4907                            // action applies to multiple entries. To avoid inadvertent changes, all
4908                            // entries are unmarked.
4909                            if !this.marked_entries.contains(&selection) {
4910                                this.marked_entries.clear();
4911                            }
4912                            this.deploy_context_menu(event.position, entry_id, window, cx);
4913                        },
4914                    ))
4915                    .overflow_x(),
4916            )
4917            .when_some(
4918                validation_color_and_message,
4919                |this, (color, message)| {
4920                    this
4921                    .relative()
4922                    .child(
4923                        deferred(
4924                            div()
4925                            .occlude()
4926                            .absolute()
4927                            .top_full()
4928                            .left(px(-1.)) // Used px over rem so that it doesn't change with font size
4929                            .right(px(-0.5))
4930                            .py_1()
4931                            .px_2()
4932                            .border_1()
4933                            .border_color(color)
4934                            .bg(cx.theme().colors().background)
4935                            .child(
4936                                Label::new(message)
4937                                .color(Color::from(color))
4938                                .size(LabelSize::Small)
4939                            )
4940                        )
4941                    )
4942                }
4943            )
4944    }
4945
4946    fn details_for_entry(
4947        &self,
4948        entry: &Entry,
4949        worktree_id: WorktreeId,
4950        root_name: &RelPath,
4951        entries_paths: &HashSet<Arc<RelPath>>,
4952        git_status: GitSummary,
4953        sticky: Option<StickyDetails>,
4954        _window: &mut Window,
4955        cx: &mut Context<Self>,
4956    ) -> EntryDetails {
4957        let (show_file_icons, show_folder_icons) = {
4958            let settings = ProjectPanelSettings::get_global(cx);
4959            (settings.file_icons, settings.folder_icons)
4960        };
4961
4962        let expanded_entry_ids = self
4963            .state
4964            .expanded_dir_ids
4965            .get(&worktree_id)
4966            .map(Vec::as_slice)
4967            .unwrap_or(&[]);
4968        let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
4969
4970        let icon = match entry.kind {
4971            EntryKind::File => {
4972                if show_file_icons {
4973                    FileIcons::get_icon(entry.path.as_std_path(), cx)
4974                } else {
4975                    None
4976                }
4977            }
4978            _ => {
4979                if show_folder_icons {
4980                    FileIcons::get_folder_icon(is_expanded, entry.path.as_std_path(), cx)
4981                } else {
4982                    FileIcons::get_chevron_icon(is_expanded, cx)
4983                }
4984            }
4985        };
4986
4987        let path_style = self.project.read(cx).path_style(cx);
4988        let (depth, difference) =
4989            ProjectPanel::calculate_depth_and_difference(entry, entries_paths);
4990
4991        let filename = if difference > 1 {
4992            entry
4993                .path
4994                .last_n_components(difference)
4995                .map_or(String::new(), |suffix| {
4996                    suffix.display(path_style).to_string()
4997                })
4998        } else {
4999            entry
5000                .path
5001                .file_name()
5002                .map(|name| name.to_string())
5003                .unwrap_or_else(|| root_name.as_unix_str().to_string())
5004        };
5005
5006        let selection = SelectedEntry {
5007            worktree_id,
5008            entry_id: entry.id,
5009        };
5010        let is_marked = self.marked_entries.contains(&selection);
5011        let is_selected = self.state.selection == Some(selection);
5012
5013        let diagnostic_severity = self
5014            .diagnostics
5015            .get(&(worktree_id, entry.path.clone()))
5016            .cloned();
5017
5018        let filename_text_color =
5019            entry_git_aware_label_color(git_status, entry.is_ignored, is_marked);
5020
5021        let is_cut = self
5022            .clipboard
5023            .as_ref()
5024            .is_some_and(|e| e.is_cut() && e.items().contains(&selection));
5025
5026        EntryDetails {
5027            filename,
5028            icon,
5029            path: entry.path.clone(),
5030            depth,
5031            kind: entry.kind,
5032            is_ignored: entry.is_ignored,
5033            is_expanded,
5034            is_selected,
5035            is_marked,
5036            is_editing: false,
5037            is_processing: false,
5038            is_cut,
5039            sticky,
5040            filename_text_color,
5041            diagnostic_severity,
5042            git_status,
5043            is_private: entry.is_private,
5044            worktree_id,
5045            canonical_path: entry.canonical_path.clone(),
5046        }
5047    }
5048
5049    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
5050        let mut dispatch_context = KeyContext::new_with_defaults();
5051        dispatch_context.add("ProjectPanel");
5052        dispatch_context.add("menu");
5053
5054        let identifier = if self.filename_editor.focus_handle(cx).is_focused(window) {
5055            "editing"
5056        } else {
5057            "not_editing"
5058        };
5059
5060        dispatch_context.add(identifier);
5061        dispatch_context
5062    }
5063
5064    fn reveal_entry(
5065        &mut self,
5066        project: Entity<Project>,
5067        entry_id: ProjectEntryId,
5068        skip_ignored: bool,
5069        window: &mut Window,
5070        cx: &mut Context<Self>,
5071    ) -> Result<()> {
5072        let worktree = project
5073            .read(cx)
5074            .worktree_for_entry(entry_id, cx)
5075            .context("can't reveal a non-existent entry in the project panel")?;
5076        let worktree = worktree.read(cx);
5077        if skip_ignored
5078            && worktree
5079                .entry_for_id(entry_id)
5080                .is_none_or(|entry| entry.is_ignored && !entry.is_always_included)
5081        {
5082            anyhow::bail!("can't reveal an ignored entry in the project panel");
5083        }
5084        let is_active_item_file_diff_view = self
5085            .workspace
5086            .upgrade()
5087            .and_then(|ws| ws.read(cx).active_item(cx))
5088            .map(|item| item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some())
5089            .unwrap_or(false);
5090        if is_active_item_file_diff_view {
5091            return Ok(());
5092        }
5093
5094        let worktree_id = worktree.id();
5095        self.expand_entry(worktree_id, entry_id, cx);
5096        self.update_visible_entries(Some((worktree_id, entry_id)), false, true, window, cx);
5097        self.marked_entries.clear();
5098        self.marked_entries.push(SelectedEntry {
5099            worktree_id,
5100            entry_id,
5101        });
5102        cx.notify();
5103        Ok(())
5104    }
5105
5106    fn find_active_indent_guide(
5107        &self,
5108        indent_guides: &[IndentGuideLayout],
5109        cx: &App,
5110    ) -> Option<usize> {
5111        let (worktree, entry) = self.selected_entry(cx)?;
5112
5113        // Find the parent entry of the indent guide, this will either be the
5114        // expanded folder we have selected, or the parent of the currently
5115        // selected file/collapsed directory
5116        let mut entry = entry;
5117        loop {
5118            let is_expanded_dir = entry.is_dir()
5119                && self
5120                    .state
5121                    .expanded_dir_ids
5122                    .get(&worktree.id())
5123                    .map(|ids| ids.binary_search(&entry.id).is_ok())
5124                    .unwrap_or(false);
5125            if is_expanded_dir {
5126                break;
5127            }
5128            entry = worktree.entry_for_path(&entry.path.parent()?)?;
5129        }
5130
5131        let (active_indent_range, depth) = {
5132            let (worktree_ix, child_offset, ix) = self.index_for_entry(entry.id, worktree.id())?;
5133            let child_paths = &self.state.visible_entries[worktree_ix].entries;
5134            let mut child_count = 0;
5135            let depth = entry.path.ancestors().count();
5136            while let Some(entry) = child_paths.get(child_offset + child_count + 1) {
5137                if entry.path.ancestors().count() <= depth {
5138                    break;
5139                }
5140                child_count += 1;
5141            }
5142
5143            let start = ix + 1;
5144            let end = start + child_count;
5145
5146            let visible_worktree = &self.state.visible_entries[worktree_ix];
5147            let visible_worktree_entries = visible_worktree.index.get_or_init(|| {
5148                visible_worktree
5149                    .entries
5150                    .iter()
5151                    .map(|e| e.path.clone())
5152                    .collect()
5153            });
5154
5155            // Calculate the actual depth of the entry, taking into account that directories can be auto-folded.
5156            let (depth, _) = Self::calculate_depth_and_difference(entry, visible_worktree_entries);
5157            (start..end, depth)
5158        };
5159
5160        let candidates = indent_guides
5161            .iter()
5162            .enumerate()
5163            .filter(|(_, indent_guide)| indent_guide.offset.x == depth);
5164
5165        for (i, indent) in candidates {
5166            // Find matches that are either an exact match, partially on screen, or inside the enclosing indent
5167            if active_indent_range.start <= indent.offset.y + indent.length
5168                && indent.offset.y <= active_indent_range.end
5169            {
5170                return Some(i);
5171            }
5172        }
5173        None
5174    }
5175
5176    fn render_sticky_entries(
5177        &self,
5178        child: StickyProjectPanelCandidate,
5179        window: &mut Window,
5180        cx: &mut Context<Self>,
5181    ) -> SmallVec<[AnyElement; 8]> {
5182        let project = self.project.read(cx);
5183
5184        let Some((worktree_id, entry_ref)) = self.entry_at_index(child.index) else {
5185            return SmallVec::new();
5186        };
5187
5188        let Some(visible) = self
5189            .state
5190            .visible_entries
5191            .iter()
5192            .find(|worktree| worktree.worktree_id == worktree_id)
5193        else {
5194            return SmallVec::new();
5195        };
5196
5197        let Some(worktree) = project.worktree_for_id(worktree_id, cx) else {
5198            return SmallVec::new();
5199        };
5200        let worktree = worktree.read(cx).snapshot();
5201
5202        let paths = visible
5203            .index
5204            .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
5205
5206        let mut sticky_parents = Vec::new();
5207        let mut current_path = entry_ref.path.clone();
5208
5209        'outer: loop {
5210            if let Some(parent_path) = current_path.parent() {
5211                for ancestor_path in parent_path.ancestors() {
5212                    if paths.contains(ancestor_path)
5213                        && let Some(parent_entry) = worktree.entry_for_path(ancestor_path)
5214                    {
5215                        sticky_parents.push(parent_entry.clone());
5216                        current_path = parent_entry.path.clone();
5217                        continue 'outer;
5218                    }
5219                }
5220            }
5221            break 'outer;
5222        }
5223
5224        if sticky_parents.is_empty() {
5225            return SmallVec::new();
5226        }
5227
5228        sticky_parents.reverse();
5229
5230        let panel_settings = ProjectPanelSettings::get_global(cx);
5231        let git_status_enabled = panel_settings.git_status;
5232        let root_name = worktree.root_name();
5233
5234        let git_summaries_by_id = if git_status_enabled {
5235            visible
5236                .entries
5237                .iter()
5238                .map(|e| (e.id, e.git_summary))
5239                .collect::<HashMap<_, _>>()
5240        } else {
5241            Default::default()
5242        };
5243
5244        // already checked if non empty above
5245        let last_item_index = sticky_parents.len() - 1;
5246        sticky_parents
5247            .iter()
5248            .enumerate()
5249            .map(|(index, entry)| {
5250                let git_status = git_summaries_by_id
5251                    .get(&entry.id)
5252                    .copied()
5253                    .unwrap_or_default();
5254                let sticky_details = Some(StickyDetails {
5255                    sticky_index: index,
5256                });
5257                let details = self.details_for_entry(
5258                    entry,
5259                    worktree_id,
5260                    root_name,
5261                    paths,
5262                    git_status,
5263                    sticky_details,
5264                    window,
5265                    cx,
5266                );
5267                self.render_entry(entry.id, details, window, cx)
5268                    .when(index == last_item_index, |this| {
5269                        let shadow_color_top = hsla(0.0, 0.0, 0.0, 0.1);
5270                        let shadow_color_bottom = hsla(0.0, 0.0, 0.0, 0.);
5271                        let sticky_shadow = div()
5272                            .absolute()
5273                            .left_0()
5274                            .bottom_neg_1p5()
5275                            .h_1p5()
5276                            .w_full()
5277                            .bg(linear_gradient(
5278                                0.,
5279                                linear_color_stop(shadow_color_top, 1.),
5280                                linear_color_stop(shadow_color_bottom, 0.),
5281                            ));
5282                        this.child(sticky_shadow)
5283                    })
5284                    .into_any()
5285            })
5286            .collect()
5287    }
5288}
5289
5290#[derive(Clone)]
5291struct StickyProjectPanelCandidate {
5292    index: usize,
5293    depth: usize,
5294}
5295
5296impl StickyCandidate for StickyProjectPanelCandidate {
5297    fn depth(&self) -> usize {
5298        self.depth
5299    }
5300}
5301
5302fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -> usize {
5303    const ICON_SIZE_FACTOR: usize = 2;
5304    let mut item_width = depth * ICON_SIZE_FACTOR + item_text_chars;
5305    if is_symlink {
5306        item_width += ICON_SIZE_FACTOR;
5307    }
5308    item_width
5309}
5310
5311impl Render for ProjectPanel {
5312    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5313        let has_worktree = !self.state.visible_entries.is_empty();
5314        let project = self.project.read(cx);
5315        let panel_settings = ProjectPanelSettings::get_global(cx);
5316        let indent_size = panel_settings.indent_size;
5317        let show_indent_guides = panel_settings.indent_guides.show == ShowIndentGuides::Always;
5318        let show_sticky_entries = {
5319            if panel_settings.sticky_scroll {
5320                let is_scrollable = self.scroll_handle.is_scrollable();
5321                let is_scrolled = self.scroll_handle.offset().y < px(0.);
5322                is_scrollable && is_scrolled
5323            } else {
5324                false
5325            }
5326        };
5327
5328        let is_local = project.is_local();
5329
5330        if has_worktree {
5331            let item_count = self
5332                .state
5333                .visible_entries
5334                .iter()
5335                .map(|worktree| worktree.entries.len())
5336                .sum();
5337
5338            fn handle_drag_move<T: 'static>(
5339                this: &mut ProjectPanel,
5340                e: &DragMoveEvent<T>,
5341                window: &mut Window,
5342                cx: &mut Context<ProjectPanel>,
5343            ) {
5344                if let Some(previous_position) = this.previous_drag_position {
5345                    // Refresh cursor only when an actual drag happens,
5346                    // because modifiers are not updated when the cursor is not moved.
5347                    if e.event.position != previous_position {
5348                        this.refresh_drag_cursor_style(&e.event.modifiers, window, cx);
5349                    }
5350                }
5351                this.previous_drag_position = Some(e.event.position);
5352
5353                if !e.bounds.contains(&e.event.position) {
5354                    this.drag_target_entry = None;
5355                    return;
5356                }
5357                this.hover_scroll_task.take();
5358                let panel_height = e.bounds.size.height;
5359                if panel_height <= px(0.) {
5360                    return;
5361                }
5362
5363                let event_offset = e.event.position.y - e.bounds.origin.y;
5364                // How far along in the project panel is our cursor? (0. is the top of a list, 1. is the bottom)
5365                let hovered_region_offset = event_offset / panel_height;
5366
5367                // We want the scrolling to be a bit faster when the cursor is closer to the edge of a list.
5368                // These pixels offsets were picked arbitrarily.
5369                let vertical_scroll_offset = if hovered_region_offset <= 0.05 {
5370                    8.
5371                } else if hovered_region_offset <= 0.15 {
5372                    5.
5373                } else if hovered_region_offset >= 0.95 {
5374                    -8.
5375                } else if hovered_region_offset >= 0.85 {
5376                    -5.
5377                } else {
5378                    return;
5379                };
5380                let adjustment = point(px(0.), px(vertical_scroll_offset));
5381                this.hover_scroll_task = Some(cx.spawn_in(window, async move |this, cx| {
5382                    loop {
5383                        let should_stop_scrolling = this
5384                            .update(cx, |this, cx| {
5385                                this.hover_scroll_task.as_ref()?;
5386                                let handle = this.scroll_handle.0.borrow_mut();
5387                                let offset = handle.base_handle.offset();
5388
5389                                handle.base_handle.set_offset(offset + adjustment);
5390                                cx.notify();
5391                                Some(())
5392                            })
5393                            .ok()
5394                            .flatten()
5395                            .is_some();
5396                        if should_stop_scrolling {
5397                            return;
5398                        }
5399                        cx.background_executor()
5400                            .timer(Duration::from_millis(16))
5401                            .await;
5402                    }
5403                }));
5404            }
5405            h_flex()
5406                .id("project-panel")
5407                .group("project-panel")
5408                .when(panel_settings.drag_and_drop, |this| {
5409                    this.on_drag_move(cx.listener(handle_drag_move::<ExternalPaths>))
5410                        .on_drag_move(cx.listener(handle_drag_move::<DraggedSelection>))
5411                })
5412                .size_full()
5413                .relative()
5414                .on_modifiers_changed(cx.listener(
5415                    |this, event: &ModifiersChangedEvent, window, cx| {
5416                        this.refresh_drag_cursor_style(&event.modifiers, window, cx);
5417                    },
5418                ))
5419                .key_context(self.dispatch_context(window, cx))
5420                .on_action(cx.listener(Self::scroll_up))
5421                .on_action(cx.listener(Self::scroll_down))
5422                .on_action(cx.listener(Self::scroll_cursor_center))
5423                .on_action(cx.listener(Self::scroll_cursor_top))
5424                .on_action(cx.listener(Self::scroll_cursor_bottom))
5425                .on_action(cx.listener(Self::select_next))
5426                .on_action(cx.listener(Self::select_previous))
5427                .on_action(cx.listener(Self::select_first))
5428                .on_action(cx.listener(Self::select_last))
5429                .on_action(cx.listener(Self::select_parent))
5430                .on_action(cx.listener(Self::select_next_git_entry))
5431                .on_action(cx.listener(Self::select_prev_git_entry))
5432                .on_action(cx.listener(Self::select_next_diagnostic))
5433                .on_action(cx.listener(Self::select_prev_diagnostic))
5434                .on_action(cx.listener(Self::select_next_directory))
5435                .on_action(cx.listener(Self::select_prev_directory))
5436                .on_action(cx.listener(Self::expand_selected_entry))
5437                .on_action(cx.listener(Self::collapse_selected_entry))
5438                .on_action(cx.listener(Self::collapse_all_entries))
5439                .on_action(cx.listener(Self::open))
5440                .on_action(cx.listener(Self::open_permanent))
5441                .on_action(cx.listener(Self::open_split_vertical))
5442                .on_action(cx.listener(Self::open_split_horizontal))
5443                .on_action(cx.listener(Self::confirm))
5444                .on_action(cx.listener(Self::cancel))
5445                .on_action(cx.listener(Self::copy_path))
5446                .on_action(cx.listener(Self::copy_relative_path))
5447                .on_action(cx.listener(Self::new_search_in_directory))
5448                .on_action(cx.listener(Self::unfold_directory))
5449                .on_action(cx.listener(Self::fold_directory))
5450                .on_action(cx.listener(Self::remove_from_project))
5451                .on_action(cx.listener(Self::compare_marked_files))
5452                .when(!project.is_read_only(cx), |el| {
5453                    el.on_action(cx.listener(Self::new_file))
5454                        .on_action(cx.listener(Self::new_directory))
5455                        .on_action(cx.listener(Self::rename))
5456                        .on_action(cx.listener(Self::delete))
5457                        .on_action(cx.listener(Self::trash))
5458                        .on_action(cx.listener(Self::cut))
5459                        .on_action(cx.listener(Self::copy))
5460                        .on_action(cx.listener(Self::paste))
5461                        .on_action(cx.listener(Self::duplicate))
5462                        .on_click(cx.listener(|this, event: &gpui::ClickEvent, window, cx| {
5463                            if event.click_count() > 1
5464                                && let Some(entry_id) = this.state.last_worktree_root_id
5465                            {
5466                                let project = this.project.read(cx);
5467
5468                                let worktree_id = if let Some(worktree) =
5469                                    project.worktree_for_entry(entry_id, cx)
5470                                {
5471                                    worktree.read(cx).id()
5472                                } else {
5473                                    return;
5474                                };
5475
5476                                this.state.selection = Some(SelectedEntry {
5477                                    worktree_id,
5478                                    entry_id,
5479                                });
5480
5481                                this.new_file(&NewFile, window, cx);
5482                            }
5483                        }))
5484                })
5485                .when(project.is_local(), |el| {
5486                    el.on_action(cx.listener(Self::reveal_in_finder))
5487                        .on_action(cx.listener(Self::open_system))
5488                        .on_action(cx.listener(Self::open_in_terminal))
5489                })
5490                .when(project.is_via_remote_server(), |el| {
5491                    el.on_action(cx.listener(Self::open_in_terminal))
5492                })
5493                .track_focus(&self.focus_handle(cx))
5494                .child(
5495                    v_flex()
5496                        .child(
5497                            uniform_list("entries", item_count, {
5498                                cx.processor(|this, range: Range<usize>, window, cx| {
5499                                    this.rendered_entries_len = range.end - range.start;
5500                                    let mut items = Vec::with_capacity(this.rendered_entries_len);
5501                                    this.for_each_visible_entry(
5502                                        range,
5503                                        window,
5504                                        cx,
5505                                        |id, details, window, cx| {
5506                                            items.push(this.render_entry(id, details, window, cx));
5507                                        },
5508                                    );
5509                                    items
5510                                })
5511                            })
5512                            .when(show_indent_guides, |list| {
5513                                list.with_decoration(
5514                                    ui::indent_guides(
5515                                        px(indent_size),
5516                                        IndentGuideColors::panel(cx),
5517                                    )
5518                                    .with_compute_indents_fn(
5519                                        cx.entity(),
5520                                        |this, range, window, cx| {
5521                                            let mut items =
5522                                                SmallVec::with_capacity(range.end - range.start);
5523                                            this.iter_visible_entries(
5524                                                range,
5525                                                window,
5526                                                cx,
5527                                                |entry, _, entries, _, _| {
5528                                                    let (depth, _) =
5529                                                        Self::calculate_depth_and_difference(
5530                                                            entry, entries,
5531                                                        );
5532                                                    items.push(depth);
5533                                                },
5534                                            );
5535                                            items
5536                                        },
5537                                    )
5538                                    .on_click(cx.listener(
5539                                        |this,
5540                                         active_indent_guide: &IndentGuideLayout,
5541                                         window,
5542                                         cx| {
5543                                            if window.modifiers().secondary() {
5544                                                let ix = active_indent_guide.offset.y;
5545                                                let Some((target_entry, worktree)) = maybe!({
5546                                                    let (worktree_id, entry) =
5547                                                        this.entry_at_index(ix)?;
5548                                                    let worktree = this
5549                                                        .project
5550                                                        .read(cx)
5551                                                        .worktree_for_id(worktree_id, cx)?;
5552                                                    let target_entry = worktree
5553                                                        .read(cx)
5554                                                        .entry_for_path(&entry.path.parent()?)?;
5555                                                    Some((target_entry, worktree))
5556                                                }) else {
5557                                                    return;
5558                                                };
5559
5560                                                this.collapse_entry(
5561                                                    target_entry.clone(),
5562                                                    worktree,
5563                                                    window,
5564                                                    cx,
5565                                                );
5566                                            }
5567                                        },
5568                                    ))
5569                                    .with_render_fn(
5570                                        cx.entity(),
5571                                        move |this, params, _, cx| {
5572                                            const LEFT_OFFSET: Pixels = px(14.);
5573                                            const PADDING_Y: Pixels = px(4.);
5574                                            const HITBOX_OVERDRAW: Pixels = px(3.);
5575
5576                                            let active_indent_guide_index = this
5577                                                .find_active_indent_guide(
5578                                                    ¶ms.indent_guides,
5579                                                    cx,
5580                                                );
5581
5582                                            let indent_size = params.indent_size;
5583                                            let item_height = params.item_height;
5584
5585                                            params
5586                                                .indent_guides
5587                                                .into_iter()
5588                                                .enumerate()
5589                                                .map(|(idx, layout)| {
5590                                                    let offset = if layout.continues_offscreen {
5591                                                        px(0.)
5592                                                    } else {
5593                                                        PADDING_Y
5594                                                    };
5595                                                    let bounds = Bounds::new(
5596                                                        point(
5597                                                            layout.offset.x * indent_size
5598                                                                + LEFT_OFFSET,
5599                                                            layout.offset.y * item_height + offset,
5600                                                        ),
5601                                                        size(
5602                                                            px(1.),
5603                                                            layout.length * item_height
5604                                                                - offset * 2.,
5605                                                        ),
5606                                                    );
5607                                                    ui::RenderedIndentGuide {
5608                                                        bounds,
5609                                                        layout,
5610                                                        is_active: Some(idx)
5611                                                            == active_indent_guide_index,
5612                                                        hitbox: Some(Bounds::new(
5613                                                            point(
5614                                                                bounds.origin.x - HITBOX_OVERDRAW,
5615                                                                bounds.origin.y,
5616                                                            ),
5617                                                            size(
5618                                                                bounds.size.width
5619                                                                    + HITBOX_OVERDRAW * 2.,
5620                                                                bounds.size.height,
5621                                                            ),
5622                                                        )),
5623                                                    }
5624                                                })
5625                                                .collect()
5626                                        },
5627                                    ),
5628                                )
5629                            })
5630                            .when(show_sticky_entries, |list| {
5631                                let sticky_items = ui::sticky_items(
5632                                    cx.entity(),
5633                                    |this, range, window, cx| {
5634                                        let mut items =
5635                                            SmallVec::with_capacity(range.end - range.start);
5636                                        this.iter_visible_entries(
5637                                            range,
5638                                            window,
5639                                            cx,
5640                                            |entry, index, entries, _, _| {
5641                                                let (depth, _) =
5642                                                    Self::calculate_depth_and_difference(
5643                                                        entry, entries,
5644                                                    );
5645                                                let candidate =
5646                                                    StickyProjectPanelCandidate { index, depth };
5647                                                items.push(candidate);
5648                                            },
5649                                        );
5650                                        items
5651                                    },
5652                                    |this, marker_entry, window, cx| {
5653                                        let sticky_entries =
5654                                            this.render_sticky_entries(marker_entry, window, cx);
5655                                        this.sticky_items_count = sticky_entries.len();
5656                                        sticky_entries
5657                                    },
5658                                );
5659                                list.with_decoration(if show_indent_guides {
5660                                    sticky_items.with_decoration(
5661                                        ui::indent_guides(
5662                                            px(indent_size),
5663                                            IndentGuideColors::panel(cx),
5664                                        )
5665                                        .with_render_fn(
5666                                            cx.entity(),
5667                                            move |_, params, _, _| {
5668                                                const LEFT_OFFSET: Pixels = px(14.);
5669
5670                                                let indent_size = params.indent_size;
5671                                                let item_height = params.item_height;
5672
5673                                                params
5674                                                    .indent_guides
5675                                                    .into_iter()
5676                                                    .map(|layout| {
5677                                                        let bounds = Bounds::new(
5678                                                            point(
5679                                                                layout.offset.x * indent_size
5680                                                                    + LEFT_OFFSET,
5681                                                                layout.offset.y * item_height,
5682                                                            ),
5683                                                            size(
5684                                                                px(1.),
5685                                                                layout.length * item_height,
5686                                                            ),
5687                                                        );
5688                                                        ui::RenderedIndentGuide {
5689                                                            bounds,
5690                                                            layout,
5691                                                            is_active: false,
5692                                                            hitbox: None,
5693                                                        }
5694                                                    })
5695                                                    .collect()
5696                                            },
5697                                        ),
5698                                    )
5699                                } else {
5700                                    sticky_items
5701                                })
5702                            })
5703                            .with_sizing_behavior(ListSizingBehavior::Infer)
5704                            .with_horizontal_sizing_behavior(
5705                                ListHorizontalSizingBehavior::Unconstrained,
5706                            )
5707                            .with_width_from_item(self.state.max_width_item_index)
5708                            .track_scroll(self.scroll_handle.clone()),
5709                        )
5710                        .child(
5711                            div()
5712                                .id("project-panel-blank-area")
5713                                .block_mouse_except_scroll()
5714                                .flex_grow()
5715                                .when(
5716                                    self.drag_target_entry.as_ref().is_some_and(
5717                                        |entry| match entry {
5718                                            DragTarget::Background => true,
5719                                            DragTarget::Entry {
5720                                                highlight_entry_id, ..
5721                                            } => self.state.last_worktree_root_id.is_some_and(
5722                                                |root_id| *highlight_entry_id == root_id,
5723                                            ),
5724                                        },
5725                                    ),
5726                                    |div| div.bg(cx.theme().colors().drop_target_background),
5727                                )
5728                                .on_drag_move::<ExternalPaths>(cx.listener(
5729                                    move |this, event: &DragMoveEvent<ExternalPaths>, _, _| {
5730                                        let Some(_last_root_id) = this.state.last_worktree_root_id
5731                                        else {
5732                                            return;
5733                                        };
5734                                        if event.bounds.contains(&event.event.position) {
5735                                            this.drag_target_entry = Some(DragTarget::Background);
5736                                        } else {
5737                                            if this.drag_target_entry.as_ref().is_some_and(|e| {
5738                                                matches!(e, DragTarget::Background)
5739                                            }) {
5740                                                this.drag_target_entry = None;
5741                                            }
5742                                        }
5743                                    },
5744                                ))
5745                                .on_drag_move::<DraggedSelection>(cx.listener(
5746                                    move |this, event: &DragMoveEvent<DraggedSelection>, _, cx| {
5747                                        let Some(last_root_id) = this.state.last_worktree_root_id
5748                                        else {
5749                                            return;
5750                                        };
5751                                        if event.bounds.contains(&event.event.position) {
5752                                            let drag_state = event.drag(cx);
5753                                            if this.should_highlight_background_for_selection_drag(
5754                                                &drag_state,
5755                                                last_root_id,
5756                                                cx,
5757                                            ) {
5758                                                this.drag_target_entry =
5759                                                    Some(DragTarget::Background);
5760                                            }
5761                                        } else {
5762                                            if this.drag_target_entry.as_ref().is_some_and(|e| {
5763                                                matches!(e, DragTarget::Background)
5764                                            }) {
5765                                                this.drag_target_entry = None;
5766                                            }
5767                                        }
5768                                    },
5769                                ))
5770                                .on_drop(cx.listener(
5771                                    move |this, external_paths: &ExternalPaths, window, cx| {
5772                                        this.drag_target_entry = None;
5773                                        this.hover_scroll_task.take();
5774                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5775                                            this.drop_external_files(
5776                                                external_paths.paths(),
5777                                                entry_id,
5778                                                window,
5779                                                cx,
5780                                            );
5781                                        }
5782                                        cx.stop_propagation();
5783                                    },
5784                                ))
5785                                .on_drop(cx.listener(
5786                                    move |this, selections: &DraggedSelection, window, cx| {
5787                                        this.drag_target_entry = None;
5788                                        this.hover_scroll_task.take();
5789                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5790                                            this.drag_onto(selections, entry_id, false, window, cx);
5791                                        }
5792                                        cx.stop_propagation();
5793                                    },
5794                                ))
5795                                .on_click(cx.listener(|this, event, window, cx| {
5796                                    if matches!(event, gpui::ClickEvent::Keyboard(_)) {
5797                                        return;
5798                                    }
5799                                    cx.stop_propagation();
5800                                    this.state.selection = None;
5801                                    this.marked_entries.clear();
5802                                    this.focus_handle(cx).focus(window);
5803                                }))
5804                                .on_mouse_down(
5805                                    MouseButton::Right,
5806                                    cx.listener(move |this, event: &MouseDownEvent, window, cx| {
5807                                        // When deploying the context menu anywhere below the last project entry,
5808                                        // act as if the user clicked the root of the last worktree.
5809                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5810                                            this.deploy_context_menu(
5811                                                event.position,
5812                                                entry_id,
5813                                                window,
5814                                                cx,
5815                                            );
5816                                        }
5817                                    }),
5818                                ),
5819                        )
5820                        .size_full(),
5821                )
5822                .custom_scrollbars(
5823                    Scrollbars::for_settings::<ProjectPanelSettings>()
5824                        .tracked_scroll_handle(self.scroll_handle.clone())
5825                        .with_track_along(
5826                            ScrollAxes::Horizontal,
5827                            cx.theme().colors().panel_background,
5828                        )
5829                        .notify_content(),
5830                    window,
5831                    cx,
5832                )
5833                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5834                    deferred(
5835                        anchored()
5836                            .position(*position)
5837                            .anchor(gpui::Corner::TopLeft)
5838                            .child(menu.clone()),
5839                    )
5840                    .with_priority(3)
5841                }))
5842        } else {
5843            let focus_handle = self.focus_handle(cx);
5844
5845            v_flex()
5846                .id("empty-project_panel")
5847                .p_4()
5848                .size_full()
5849                .items_center()
5850                .justify_center()
5851                .gap_1()
5852                .track_focus(&self.focus_handle(cx))
5853                .child(
5854                    Button::new("open_project", "Open Project")
5855                        .full_width()
5856                        .key_binding(KeyBinding::for_action_in(
5857                            &workspace::Open,
5858                            &focus_handle,
5859                            window,
5860                            cx,
5861                        ))
5862                        .on_click(cx.listener(|this, _, window, cx| {
5863                            this.workspace
5864                                .update(cx, |_, cx| {
5865                                    window.dispatch_action(workspace::Open.boxed_clone(), cx);
5866                                })
5867                                .log_err();
5868                        })),
5869                )
5870                .child(
5871                    h_flex()
5872                        .w_1_2()
5873                        .gap_2()
5874                        .child(Divider::horizontal())
5875                        .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
5876                        .child(Divider::horizontal()),
5877                )
5878                .child(
5879                    Button::new("clone_repo", "Clone Repository")
5880                        .full_width()
5881                        .on_click(cx.listener(|this, _, window, cx| {
5882                            this.workspace
5883                                .update(cx, |_, cx| {
5884                                    window.dispatch_action(git::Clone.boxed_clone(), cx);
5885                                })
5886                                .log_err();
5887                        })),
5888                )
5889                .when(is_local, |div| {
5890                    div.when(panel_settings.drag_and_drop, |div| {
5891                        div.drag_over::<ExternalPaths>(|style, _, _, cx| {
5892                            style.bg(cx.theme().colors().drop_target_background)
5893                        })
5894                        .on_drop(cx.listener(
5895                            move |this, external_paths: &ExternalPaths, window, cx| {
5896                                this.drag_target_entry = None;
5897                                this.hover_scroll_task.take();
5898                                if let Some(task) = this
5899                                    .workspace
5900                                    .update(cx, |workspace, cx| {
5901                                        workspace.open_workspace_for_paths(
5902                                            true,
5903                                            external_paths.paths().to_owned(),
5904                                            window,
5905                                            cx,
5906                                        )
5907                                    })
5908                                    .log_err()
5909                                {
5910                                    task.detach_and_log_err(cx);
5911                                }
5912                                cx.stop_propagation();
5913                            },
5914                        ))
5915                    })
5916                })
5917        }
5918    }
5919}
5920
5921impl Render for DraggedProjectEntryView {
5922    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5923        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
5924        h_flex()
5925            .font(ui_font)
5926            .pl(self.click_offset.x + px(12.))
5927            .pt(self.click_offset.y + px(12.))
5928            .child(
5929                div()
5930                    .flex()
5931                    .gap_1()
5932                    .items_center()
5933                    .py_1()
5934                    .px_2()
5935                    .rounded_lg()
5936                    .bg(cx.theme().colors().background)
5937                    .map(|this| {
5938                        if self.selections.len() > 1 && self.selections.contains(&self.selection) {
5939                            this.child(Label::new(format!("{} entries", self.selections.len())))
5940                        } else {
5941                            this.child(if let Some(icon) = &self.icon {
5942                                div().child(Icon::from_path(icon.clone()))
5943                            } else {
5944                                div()
5945                            })
5946                            .child(Label::new(self.filename.clone()))
5947                        }
5948                    }),
5949            )
5950    }
5951}
5952
5953impl EventEmitter<Event> for ProjectPanel {}
5954
5955impl EventEmitter<PanelEvent> for ProjectPanel {}
5956
5957impl Panel for ProjectPanel {
5958    fn position(&self, _: &Window, cx: &App) -> DockPosition {
5959        match ProjectPanelSettings::get_global(cx).dock {
5960            DockSide::Left => DockPosition::Left,
5961            DockSide::Right => DockPosition::Right,
5962        }
5963    }
5964
5965    fn position_is_valid(&self, position: DockPosition) -> bool {
5966        matches!(position, DockPosition::Left | DockPosition::Right)
5967    }
5968
5969    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5970        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5971            let dock = match position {
5972                DockPosition::Left | DockPosition::Bottom => DockSide::Left,
5973                DockPosition::Right => DockSide::Right,
5974            };
5975            settings.project_panel.get_or_insert_default().dock = Some(dock);
5976        });
5977    }
5978
5979    fn size(&self, _: &Window, cx: &App) -> Pixels {
5980        self.width
5981            .unwrap_or_else(|| ProjectPanelSettings::get_global(cx).default_width)
5982    }
5983
5984    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
5985        self.width = size;
5986        cx.notify();
5987        cx.defer_in(window, |this, _, cx| {
5988            this.serialize(cx);
5989        });
5990    }
5991
5992    fn icon(&self, _: &Window, cx: &App) -> Option<IconName> {
5993        ProjectPanelSettings::get_global(cx)
5994            .button
5995            .then_some(IconName::FileTree)
5996    }
5997
5998    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5999        Some("Project Panel")
6000    }
6001
6002    fn toggle_action(&self) -> Box<dyn Action> {
6003        Box::new(ToggleFocus)
6004    }
6005
6006    fn persistent_name() -> &'static str {
6007        "Project Panel"
6008    }
6009
6010    fn starts_open(&self, _: &Window, cx: &App) -> bool {
6011        if !ProjectPanelSettings::get_global(cx).starts_open {
6012            return false;
6013        }
6014
6015        let project = &self.project.read(cx);
6016        project.visible_worktrees(cx).any(|tree| {
6017            tree.read(cx)
6018                .root_entry()
6019                .is_some_and(|entry| entry.is_dir())
6020        })
6021    }
6022
6023    fn activation_priority(&self) -> u32 {
6024        0
6025    }
6026}
6027
6028impl Focusable for ProjectPanel {
6029    fn focus_handle(&self, _cx: &App) -> FocusHandle {
6030        self.focus_handle.clone()
6031    }
6032}
6033
6034impl ClipboardEntry {
6035    fn is_cut(&self) -> bool {
6036        matches!(self, Self::Cut { .. })
6037    }
6038
6039    fn items(&self) -> &BTreeSet<SelectedEntry> {
6040        match self {
6041            ClipboardEntry::Copied(entries) | ClipboardEntry::Cut(entries) => entries,
6042        }
6043    }
6044
6045    fn into_copy_entry(self) -> Self {
6046        match self {
6047            ClipboardEntry::Copied(_) => self,
6048            ClipboardEntry::Cut(entries) => ClipboardEntry::Copied(entries),
6049        }
6050    }
6051}
6052
6053fn cmp<T: AsRef<Entry>>(lhs: T, rhs: T) -> cmp::Ordering {
6054    let entry_a = lhs.as_ref();
6055    let entry_b = rhs.as_ref();
6056    util::paths::compare_rel_paths(
6057        (&entry_a.path, entry_a.is_file()),
6058        (&entry_b.path, entry_b.is_file()),
6059    )
6060}
6061
6062pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
6063    entries.sort_by(|lhs, rhs| cmp(lhs, rhs));
6064}
6065
6066pub fn par_sort_worktree_entries(entries: &mut Vec<GitEntry>) {
6067    entries.par_sort_by(|lhs, rhs| cmp(lhs, rhs));
6068}
6069
6070#[cfg(test)]
6071mod project_panel_tests;