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