project_panel.rs

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