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 = PreviewTabsSettings::get_global(cx).enabled;
1533        self.open_internal(true, !preview_tabs_enabled, None, window, cx);
1534    }
1535
1536    fn open_permanent(&mut self, _: &OpenPermanent, window: &mut Window, cx: &mut Context<Self>) {
1537        self.open_internal(false, true, None, window, cx);
1538    }
1539
1540    fn open_split_vertical(
1541        &mut self,
1542        _: &OpenSplitVertical,
1543        window: &mut Window,
1544        cx: &mut Context<Self>,
1545    ) {
1546        self.open_internal(false, true, Some(SplitDirection::vertical(cx)), window, cx);
1547    }
1548
1549    fn open_split_horizontal(
1550        &mut self,
1551        _: &OpenSplitHorizontal,
1552        window: &mut Window,
1553        cx: &mut Context<Self>,
1554    ) {
1555        self.open_internal(
1556            false,
1557            true,
1558            Some(SplitDirection::horizontal(cx)),
1559            window,
1560            cx,
1561        );
1562    }
1563
1564    fn open_internal(
1565        &mut self,
1566        allow_preview: bool,
1567        focus_opened_item: bool,
1568        split_direction: Option<SplitDirection>,
1569        window: &mut Window,
1570        cx: &mut Context<Self>,
1571    ) {
1572        if let Some((_, entry)) = self.selected_entry(cx) {
1573            if entry.is_file() {
1574                if split_direction.is_some() {
1575                    self.split_entry(entry.id, allow_preview, split_direction, cx);
1576                } else {
1577                    self.open_entry(entry.id, focus_opened_item, allow_preview, cx);
1578                }
1579                cx.notify();
1580            } else {
1581                self.toggle_expanded(entry.id, window, cx);
1582            }
1583        }
1584    }
1585
1586    fn populate_validation_error(&mut self, cx: &mut Context<Self>) {
1587        let edit_state = match self.state.edit_state.as_mut() {
1588            Some(state) => state,
1589            None => return,
1590        };
1591        let filename = self.filename_editor.read(cx).text(cx);
1592        if !filename.is_empty() {
1593            if filename.is_empty() {
1594                edit_state.validation_state =
1595                    ValidationState::Error("File or directory name cannot be empty.".to_string());
1596                cx.notify();
1597                return;
1598            }
1599
1600            let trimmed_filename = filename.trim();
1601            if trimmed_filename != filename {
1602                edit_state.validation_state = ValidationState::Warning(
1603                    "File or directory name contains leading or trailing whitespace.".to_string(),
1604                );
1605                cx.notify();
1606                return;
1607            }
1608            let trimmed_filename = trimmed_filename.trim_start_matches('/');
1609
1610            let Ok(filename) = RelPath::unix(trimmed_filename) else {
1611                edit_state.validation_state = ValidationState::Warning(
1612                    "File or directory name contains leading or trailing whitespace.".to_string(),
1613                );
1614                cx.notify();
1615                return;
1616            };
1617
1618            if let Some(worktree) = self
1619                .project
1620                .read(cx)
1621                .worktree_for_id(edit_state.worktree_id, cx)
1622                && let Some(entry) = worktree.read(cx).entry_for_id(edit_state.entry_id)
1623            {
1624                let mut already_exists = false;
1625                if edit_state.is_new_entry() {
1626                    let new_path = entry.path.join(filename);
1627                    if worktree.read(cx).entry_for_path(&new_path).is_some() {
1628                        already_exists = true;
1629                    }
1630                } else {
1631                    let new_path = if let Some(parent) = entry.path.clone().parent() {
1632                        parent.join(&filename)
1633                    } else {
1634                        filename.into()
1635                    };
1636                    if let Some(existing) = worktree.read(cx).entry_for_path(&new_path)
1637                        && existing.id != entry.id
1638                    {
1639                        already_exists = true;
1640                    }
1641                };
1642                if already_exists {
1643                    edit_state.validation_state = ValidationState::Error(format!(
1644                        "File or directory '{}' already exists at location. Please choose a different name.",
1645                        filename.as_unix_str()
1646                    ));
1647                    cx.notify();
1648                    return;
1649                }
1650            }
1651        }
1652        edit_state.validation_state = ValidationState::None;
1653        cx.notify();
1654    }
1655
1656    fn confirm_edit(
1657        &mut self,
1658        refocus: bool,
1659        window: &mut Window,
1660        cx: &mut Context<Self>,
1661    ) -> Option<Task<Result<()>>> {
1662        let edit_state = self.state.edit_state.as_mut()?;
1663        let worktree_id = edit_state.worktree_id;
1664        let is_new_entry = edit_state.is_new_entry();
1665        let filename = self.filename_editor.read(cx).text(cx);
1666        if filename.trim().is_empty() {
1667            return None;
1668        }
1669
1670        let path_style = self.project.read(cx).path_style(cx);
1671        let filename_indicates_dir = if path_style.is_windows() {
1672            filename.ends_with('/') || filename.ends_with('\\')
1673        } else {
1674            filename.ends_with('/')
1675        };
1676        let filename = if path_style.is_windows() {
1677            filename.trim_start_matches(&['/', '\\'])
1678        } else {
1679            filename.trim_start_matches('/')
1680        };
1681        let filename = RelPath::new(filename.as_ref(), path_style).ok()?.into_arc();
1682
1683        edit_state.is_dir =
1684            edit_state.is_dir || (edit_state.is_new_entry() && filename_indicates_dir);
1685        let is_dir = edit_state.is_dir;
1686        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
1687        let entry = worktree.read(cx).entry_for_id(edit_state.entry_id)?.clone();
1688
1689        let edit_task;
1690        let edited_entry_id;
1691        if is_new_entry {
1692            self.state.selection = Some(SelectedEntry {
1693                worktree_id,
1694                entry_id: NEW_ENTRY_ID,
1695            });
1696            let new_path = entry.path.join(&filename);
1697            if worktree.read(cx).entry_for_path(&new_path).is_some() {
1698                return None;
1699            }
1700
1701            edited_entry_id = NEW_ENTRY_ID;
1702            edit_task = self.project.update(cx, |project, cx| {
1703                project.create_entry((worktree_id, new_path), is_dir, cx)
1704            });
1705        } else {
1706            let new_path = if let Some(parent) = entry.path.clone().parent() {
1707                parent.join(&filename)
1708            } else {
1709                filename.clone()
1710            };
1711            if let Some(existing) = worktree.read(cx).entry_for_path(&new_path) {
1712                if existing.id == entry.id && refocus {
1713                    window.focus(&self.focus_handle);
1714                }
1715                return None;
1716            }
1717            edited_entry_id = entry.id;
1718            edit_task = self.project.update(cx, |project, cx| {
1719                project.rename_entry(entry.id, (worktree_id, new_path).into(), cx)
1720            });
1721        };
1722
1723        if refocus {
1724            window.focus(&self.focus_handle);
1725        }
1726        edit_state.processing_filename = Some(filename);
1727        cx.notify();
1728
1729        Some(cx.spawn_in(window, async move |project_panel, cx| {
1730            let new_entry = edit_task.await;
1731            project_panel.update(cx, |project_panel, cx| {
1732                project_panel.state.edit_state = None;
1733                cx.notify();
1734            })?;
1735
1736            match new_entry {
1737                Err(e) => {
1738                    project_panel
1739                        .update_in(cx, |project_panel, window, cx| {
1740                            project_panel.marked_entries.clear();
1741                            project_panel.update_visible_entries(None, false, false, window, cx);
1742                        })
1743                        .ok();
1744                    Err(e)?;
1745                }
1746                Ok(CreatedEntry::Included(new_entry)) => {
1747                    project_panel.update_in(cx, |project_panel, window, cx| {
1748                        if let Some(selection) = &mut project_panel.state.selection
1749                            && selection.entry_id == edited_entry_id
1750                        {
1751                            selection.worktree_id = worktree_id;
1752                            selection.entry_id = new_entry.id;
1753                            project_panel.marked_entries.clear();
1754                            project_panel.expand_to_selection(cx);
1755                        }
1756                        project_panel.update_visible_entries(None, false, false, window, cx);
1757                        if is_new_entry && !is_dir {
1758                            let settings = ProjectPanelSettings::get_global(cx);
1759                            if settings.auto_open.should_open_on_create() {
1760                                project_panel.open_entry(new_entry.id, true, false, cx);
1761                            }
1762                        }
1763                        cx.notify();
1764                    })?;
1765                }
1766                Ok(CreatedEntry::Excluded { abs_path }) => {
1767                    if let Some(open_task) = project_panel
1768                        .update_in(cx, |project_panel, window, cx| {
1769                            project_panel.marked_entries.clear();
1770                            project_panel.update_visible_entries(None, false, false, window, cx);
1771
1772                            if is_dir {
1773                                project_panel.project.update(cx, |_, cx| {
1774                                    cx.emit(project::Event::Toast {
1775                                        notification_id: "excluded-directory".into(),
1776                                        message: format!(
1777                                            concat!(
1778                                                "Created an excluded directory at {:?}.\n",
1779                                                "Alter `file_scan_exclusions` in the settings ",
1780                                                "to show it in the panel"
1781                                            ),
1782                                            abs_path
1783                                        ),
1784                                    })
1785                                });
1786                                None
1787                            } else {
1788                                project_panel
1789                                    .workspace
1790                                    .update(cx, |workspace, cx| {
1791                                        workspace.open_abs_path(
1792                                            abs_path,
1793                                            OpenOptions {
1794                                                visible: Some(OpenVisible::All),
1795                                                ..Default::default()
1796                                            },
1797                                            window,
1798                                            cx,
1799                                        )
1800                                    })
1801                                    .ok()
1802                            }
1803                        })
1804                        .ok()
1805                        .flatten()
1806                    {
1807                        let _ = open_task.await?;
1808                    }
1809                }
1810            }
1811            Ok(())
1812        }))
1813    }
1814
1815    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
1816        if cx.stop_active_drag(window) {
1817            self.drag_target_entry.take();
1818            self.hover_expand_task.take();
1819            return;
1820        }
1821
1822        let previous_edit_state = self.state.edit_state.take();
1823        self.update_visible_entries(None, false, false, window, cx);
1824        self.marked_entries.clear();
1825
1826        if let Some(previously_focused) =
1827            previous_edit_state.and_then(|edit_state| edit_state.previously_focused)
1828        {
1829            self.state.selection = Some(previously_focused);
1830            self.autoscroll(cx);
1831        }
1832
1833        window.focus(&self.focus_handle);
1834        cx.notify();
1835    }
1836
1837    fn open_entry(
1838        &mut self,
1839        entry_id: ProjectEntryId,
1840        focus_opened_item: bool,
1841        allow_preview: bool,
1842
1843        cx: &mut Context<Self>,
1844    ) {
1845        cx.emit(Event::OpenedEntry {
1846            entry_id,
1847            focus_opened_item,
1848            allow_preview,
1849        });
1850    }
1851
1852    fn split_entry(
1853        &mut self,
1854        entry_id: ProjectEntryId,
1855        allow_preview: bool,
1856        split_direction: Option<SplitDirection>,
1857
1858        cx: &mut Context<Self>,
1859    ) {
1860        cx.emit(Event::SplitEntry {
1861            entry_id,
1862            allow_preview,
1863            split_direction,
1864        });
1865    }
1866
1867    fn new_file(&mut self, _: &NewFile, window: &mut Window, cx: &mut Context<Self>) {
1868        self.add_entry(false, window, cx)
1869    }
1870
1871    fn new_directory(&mut self, _: &NewDirectory, window: &mut Window, cx: &mut Context<Self>) {
1872        self.add_entry(true, window, cx)
1873    }
1874
1875    fn add_entry(&mut self, is_dir: bool, window: &mut Window, cx: &mut Context<Self>) {
1876        let Some((worktree_id, entry_id)) = self
1877            .state
1878            .selection
1879            .map(|entry| (entry.worktree_id, entry.entry_id))
1880            .or_else(|| {
1881                let entry_id = self.state.last_worktree_root_id?;
1882                let worktree_id = self
1883                    .project
1884                    .read(cx)
1885                    .worktree_for_entry(entry_id, cx)?
1886                    .read(cx)
1887                    .id();
1888
1889                self.state.selection = Some(SelectedEntry {
1890                    worktree_id,
1891                    entry_id,
1892                });
1893
1894                Some((worktree_id, entry_id))
1895            })
1896        else {
1897            return;
1898        };
1899
1900        let directory_id;
1901        let new_entry_id = self.resolve_entry(entry_id);
1902        if let Some((worktree, expanded_dir_ids)) = self
1903            .project
1904            .read(cx)
1905            .worktree_for_id(worktree_id, cx)
1906            .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
1907        {
1908            let worktree = worktree.read(cx);
1909            if let Some(mut entry) = worktree.entry_for_id(new_entry_id) {
1910                loop {
1911                    if entry.is_dir() {
1912                        if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
1913                            expanded_dir_ids.insert(ix, entry.id);
1914                        }
1915                        directory_id = entry.id;
1916                        break;
1917                    } else {
1918                        if let Some(parent_path) = entry.path.parent()
1919                            && let Some(parent_entry) = worktree.entry_for_path(parent_path)
1920                        {
1921                            entry = parent_entry;
1922                            continue;
1923                        }
1924                        return;
1925                    }
1926                }
1927            } else {
1928                return;
1929            };
1930        } else {
1931            return;
1932        };
1933
1934        self.marked_entries.clear();
1935        self.state.edit_state = Some(EditState {
1936            worktree_id,
1937            entry_id: directory_id,
1938            leaf_entry_id: None,
1939            is_dir,
1940            processing_filename: None,
1941            previously_focused: self.state.selection,
1942            depth: 0,
1943            validation_state: ValidationState::None,
1944        });
1945        self.filename_editor.update(cx, |editor, cx| {
1946            editor.clear(window, cx);
1947        });
1948        self.update_visible_entries(Some((worktree_id, NEW_ENTRY_ID)), true, true, window, cx);
1949        cx.notify();
1950    }
1951
1952    fn unflatten_entry_id(&self, leaf_entry_id: ProjectEntryId) -> ProjectEntryId {
1953        if let Some(ancestors) = self.state.ancestors.get(&leaf_entry_id) {
1954            ancestors
1955                .ancestors
1956                .get(ancestors.current_ancestor_depth)
1957                .copied()
1958                .unwrap_or(leaf_entry_id)
1959        } else {
1960            leaf_entry_id
1961        }
1962    }
1963
1964    fn rename_impl(
1965        &mut self,
1966        selection: Option<Range<usize>>,
1967        window: &mut Window,
1968        cx: &mut Context<Self>,
1969    ) {
1970        if let Some(SelectedEntry {
1971            worktree_id,
1972            entry_id,
1973        }) = self.state.selection
1974            && let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx)
1975        {
1976            let sub_entry_id = self.unflatten_entry_id(entry_id);
1977            if let Some(entry) = worktree.read(cx).entry_for_id(sub_entry_id) {
1978                #[cfg(target_os = "windows")]
1979                if Some(entry) == worktree.read(cx).root_entry() {
1980                    return;
1981                }
1982
1983                if Some(entry) == worktree.read(cx).root_entry() {
1984                    let settings = ProjectPanelSettings::get_global(cx);
1985                    let visible_worktrees_count =
1986                        self.project.read(cx).visible_worktrees(cx).count();
1987                    if settings.hide_root && visible_worktrees_count == 1 {
1988                        return;
1989                    }
1990                }
1991
1992                self.state.edit_state = Some(EditState {
1993                    worktree_id,
1994                    entry_id: sub_entry_id,
1995                    leaf_entry_id: Some(entry_id),
1996                    is_dir: entry.is_dir(),
1997                    processing_filename: None,
1998                    previously_focused: None,
1999                    depth: 0,
2000                    validation_state: ValidationState::None,
2001                });
2002                let file_name = entry.path.file_name().unwrap_or_default().to_string();
2003                let selection = selection.unwrap_or_else(|| {
2004                    let file_stem = entry.path.file_stem().map(|s| s.to_string());
2005                    let selection_end =
2006                        file_stem.map_or(file_name.len(), |file_stem| file_stem.len());
2007                    0..selection_end
2008                });
2009                self.filename_editor.update(cx, |editor, cx| {
2010                    editor.set_text(file_name, window, cx);
2011                    editor.change_selections(Default::default(), window, cx, |s| {
2012                        s.select_ranges([
2013                            MultiBufferOffset(selection.start)..MultiBufferOffset(selection.end)
2014                        ])
2015                    });
2016                });
2017                self.update_visible_entries(None, true, true, window, cx);
2018                cx.notify();
2019            }
2020        }
2021    }
2022
2023    fn rename(&mut self, _: &Rename, window: &mut Window, cx: &mut Context<Self>) {
2024        self.rename_impl(None, window, cx);
2025    }
2026
2027    fn trash(&mut self, action: &Trash, window: &mut Window, cx: &mut Context<Self>) {
2028        self.remove(true, action.skip_prompt, window, cx);
2029    }
2030
2031    fn delete(&mut self, action: &Delete, window: &mut Window, cx: &mut Context<Self>) {
2032        self.remove(false, action.skip_prompt, window, cx);
2033    }
2034
2035    fn remove(
2036        &mut self,
2037        trash: bool,
2038        skip_prompt: bool,
2039        window: &mut Window,
2040        cx: &mut Context<ProjectPanel>,
2041    ) {
2042        maybe!({
2043            let items_to_delete = self.disjoint_entries(cx);
2044            if items_to_delete.is_empty() {
2045                return None;
2046            }
2047            let project = self.project.read(cx);
2048
2049            let mut dirty_buffers = 0;
2050            let file_paths = items_to_delete
2051                .iter()
2052                .filter_map(|selection| {
2053                    let project_path = project.path_for_entry(selection.entry_id, cx)?;
2054                    dirty_buffers +=
2055                        project.dirty_buffers(cx).any(|path| path == project_path) as usize;
2056                    Some((
2057                        selection.entry_id,
2058                        project_path.path.file_name()?.to_string(),
2059                    ))
2060                })
2061                .collect::<Vec<_>>();
2062            if file_paths.is_empty() {
2063                return None;
2064            }
2065            let answer = if !skip_prompt {
2066                let operation = if trash { "Trash" } else { "Delete" };
2067                let prompt = match file_paths.first() {
2068                    Some((_, path)) if file_paths.len() == 1 => {
2069                        let unsaved_warning = if dirty_buffers > 0 {
2070                            "\n\nIt has unsaved changes, which will be lost."
2071                        } else {
2072                            ""
2073                        };
2074
2075                        format!("{operation} {path}?{unsaved_warning}")
2076                    }
2077                    _ => {
2078                        const CUTOFF_POINT: usize = 10;
2079                        let names = if file_paths.len() > CUTOFF_POINT {
2080                            let truncated_path_counts = file_paths.len() - CUTOFF_POINT;
2081                            let mut paths = file_paths
2082                                .iter()
2083                                .map(|(_, path)| path.clone())
2084                                .take(CUTOFF_POINT)
2085                                .collect::<Vec<_>>();
2086                            paths.truncate(CUTOFF_POINT);
2087                            if truncated_path_counts == 1 {
2088                                paths.push(".. 1 file not shown".into());
2089                            } else {
2090                                paths.push(format!(".. {} files not shown", truncated_path_counts));
2091                            }
2092                            paths
2093                        } else {
2094                            file_paths.iter().map(|(_, path)| path.clone()).collect()
2095                        };
2096                        let unsaved_warning = if dirty_buffers == 0 {
2097                            String::new()
2098                        } else if dirty_buffers == 1 {
2099                            "\n\n1 of these has unsaved changes, which will be lost.".to_string()
2100                        } else {
2101                            format!(
2102                                "\n\n{dirty_buffers} of these have unsaved changes, which will be lost."
2103                            )
2104                        };
2105
2106                        format!(
2107                            "Do you want to {} the following {} files?\n{}{unsaved_warning}",
2108                            operation.to_lowercase(),
2109                            file_paths.len(),
2110                            names.join("\n")
2111                        )
2112                    }
2113                };
2114                Some(window.prompt(PromptLevel::Info, &prompt, None, &[operation, "Cancel"], cx))
2115            } else {
2116                None
2117            };
2118            let next_selection = self.find_next_selection_after_deletion(items_to_delete, cx);
2119            cx.spawn_in(window, async move |panel, cx| {
2120                if let Some(answer) = answer
2121                    && answer.await != Ok(0)
2122                {
2123                    return anyhow::Ok(());
2124                }
2125                for (entry_id, _) in file_paths {
2126                    panel
2127                        .update(cx, |panel, cx| {
2128                            panel
2129                                .project
2130                                .update(cx, |project, cx| project.delete_entry(entry_id, trash, cx))
2131                                .context("no such entry")
2132                        })??
2133                        .await?;
2134                }
2135                panel.update_in(cx, |panel, window, cx| {
2136                    if let Some(next_selection) = next_selection {
2137                        panel.update_visible_entries(
2138                            Some((next_selection.worktree_id, next_selection.entry_id)),
2139                            false,
2140                            true,
2141                            window,
2142                            cx,
2143                        );
2144                    } else {
2145                        panel.select_last(&SelectLast {}, window, cx);
2146                    }
2147                })?;
2148                Ok(())
2149            })
2150            .detach_and_log_err(cx);
2151            Some(())
2152        });
2153    }
2154
2155    fn find_next_selection_after_deletion(
2156        &self,
2157        sanitized_entries: BTreeSet<SelectedEntry>,
2158        cx: &mut Context<Self>,
2159    ) -> Option<SelectedEntry> {
2160        if sanitized_entries.is_empty() {
2161            return None;
2162        }
2163        let project = self.project.read(cx);
2164        let (worktree_id, worktree) = sanitized_entries
2165            .iter()
2166            .map(|entry| entry.worktree_id)
2167            .filter_map(|id| project.worktree_for_id(id, cx).map(|w| (id, w.read(cx))))
2168            .max_by(|(_, a), (_, b)| a.root_name().cmp(b.root_name()))?;
2169        let git_store = project.git_store().read(cx);
2170
2171        let marked_entries_in_worktree = sanitized_entries
2172            .iter()
2173            .filter(|e| e.worktree_id == worktree_id)
2174            .collect::<HashSet<_>>();
2175        let latest_entry = marked_entries_in_worktree
2176            .iter()
2177            .max_by(|a, b| {
2178                match (
2179                    worktree.entry_for_id(a.entry_id),
2180                    worktree.entry_for_id(b.entry_id),
2181                ) {
2182                    (Some(a), Some(b)) => compare_paths(
2183                        (a.path.as_std_path(), a.is_file()),
2184                        (b.path.as_std_path(), b.is_file()),
2185                    ),
2186                    _ => cmp::Ordering::Equal,
2187                }
2188            })
2189            .and_then(|e| worktree.entry_for_id(e.entry_id))?;
2190
2191        let parent_path = latest_entry.path.parent()?;
2192        let parent_entry = worktree.entry_for_path(parent_path)?;
2193
2194        // Remove all siblings that are being deleted except the last marked entry
2195        let repo_snapshots = git_store.repo_snapshots(cx);
2196        let worktree_snapshot = worktree.snapshot();
2197        let hide_gitignore = ProjectPanelSettings::get_global(cx).hide_gitignore;
2198        let mut siblings: Vec<_> =
2199            ChildEntriesGitIter::new(&repo_snapshots, &worktree_snapshot, parent_path)
2200                .filter(|sibling| {
2201                    (sibling.id == latest_entry.id)
2202                        || (!marked_entries_in_worktree.contains(&&SelectedEntry {
2203                            worktree_id,
2204                            entry_id: sibling.id,
2205                        }) && (!hide_gitignore || !sibling.is_ignored))
2206                })
2207                .map(|entry| entry.to_owned())
2208                .collect();
2209
2210        let mode = ProjectPanelSettings::get_global(cx).sort_mode;
2211        sort_worktree_entries_with_mode(&mut siblings, mode);
2212        let sibling_entry_index = siblings
2213            .iter()
2214            .position(|sibling| sibling.id == latest_entry.id)?;
2215
2216        if let Some(next_sibling) = sibling_entry_index
2217            .checked_add(1)
2218            .and_then(|i| siblings.get(i))
2219        {
2220            return Some(SelectedEntry {
2221                worktree_id,
2222                entry_id: next_sibling.id,
2223            });
2224        }
2225        if let Some(prev_sibling) = sibling_entry_index
2226            .checked_sub(1)
2227            .and_then(|i| siblings.get(i))
2228        {
2229            return Some(SelectedEntry {
2230                worktree_id,
2231                entry_id: prev_sibling.id,
2232            });
2233        }
2234        // No neighbour sibling found, fall back to parent
2235        Some(SelectedEntry {
2236            worktree_id,
2237            entry_id: parent_entry.id,
2238        })
2239    }
2240
2241    fn unfold_directory(
2242        &mut self,
2243        _: &UnfoldDirectory,
2244        window: &mut Window,
2245        cx: &mut Context<Self>,
2246    ) {
2247        if let Some((worktree, entry)) = self.selected_entry(cx) {
2248            self.state.unfolded_dir_ids.insert(entry.id);
2249
2250            let snapshot = worktree.snapshot();
2251            let mut parent_path = entry.path.parent();
2252            while let Some(path) = parent_path {
2253                if let Some(parent_entry) = worktree.entry_for_path(path) {
2254                    let mut children_iter = snapshot.child_entries(path);
2255
2256                    if children_iter.by_ref().take(2).count() > 1 {
2257                        break;
2258                    }
2259
2260                    self.state.unfolded_dir_ids.insert(parent_entry.id);
2261                    parent_path = path.parent();
2262                } else {
2263                    break;
2264                }
2265            }
2266
2267            self.update_visible_entries(None, false, true, window, cx);
2268            cx.notify();
2269        }
2270    }
2271
2272    fn fold_directory(&mut self, _: &FoldDirectory, window: &mut Window, cx: &mut Context<Self>) {
2273        if let Some((worktree, entry)) = self.selected_entry(cx) {
2274            self.state.unfolded_dir_ids.remove(&entry.id);
2275
2276            let snapshot = worktree.snapshot();
2277            let mut path = &*entry.path;
2278            loop {
2279                let mut child_entries_iter = snapshot.child_entries(path);
2280                if let Some(child) = child_entries_iter.next() {
2281                    if child_entries_iter.next().is_none() && child.is_dir() {
2282                        self.state.unfolded_dir_ids.remove(&child.id);
2283                        path = &*child.path;
2284                    } else {
2285                        break;
2286                    }
2287                } else {
2288                    break;
2289                }
2290            }
2291
2292            self.update_visible_entries(None, false, true, window, cx);
2293            cx.notify();
2294        }
2295    }
2296
2297    fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
2298        for _ in 0..self.rendered_entries_len / 2 {
2299            window.dispatch_action(SelectPrevious.boxed_clone(), cx);
2300        }
2301    }
2302
2303    fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
2304        for _ in 0..self.rendered_entries_len / 2 {
2305            window.dispatch_action(SelectNext.boxed_clone(), cx);
2306        }
2307    }
2308
2309    fn scroll_cursor_center(
2310        &mut self,
2311        _: &ScrollCursorCenter,
2312        _: &mut Window,
2313        cx: &mut Context<Self>,
2314    ) {
2315        if let Some((_, _, index)) = self
2316            .state
2317            .selection
2318            .and_then(|s| self.index_for_selection(s))
2319        {
2320            self.scroll_handle
2321                .scroll_to_item_strict(index, ScrollStrategy::Center);
2322            cx.notify();
2323        }
2324    }
2325
2326    fn scroll_cursor_top(&mut self, _: &ScrollCursorTop, _: &mut Window, cx: &mut Context<Self>) {
2327        if let Some((_, _, index)) = self
2328            .state
2329            .selection
2330            .and_then(|s| self.index_for_selection(s))
2331        {
2332            self.scroll_handle
2333                .scroll_to_item_strict(index, ScrollStrategy::Top);
2334            cx.notify();
2335        }
2336    }
2337
2338    fn scroll_cursor_bottom(
2339        &mut self,
2340        _: &ScrollCursorBottom,
2341        _: &mut Window,
2342        cx: &mut Context<Self>,
2343    ) {
2344        if let Some((_, _, index)) = self
2345            .state
2346            .selection
2347            .and_then(|s| self.index_for_selection(s))
2348        {
2349            self.scroll_handle
2350                .scroll_to_item_strict(index, ScrollStrategy::Bottom);
2351            cx.notify();
2352        }
2353    }
2354
2355    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2356        if let Some(edit_state) = &self.state.edit_state
2357            && edit_state.processing_filename.is_none()
2358        {
2359            self.filename_editor.update(cx, |editor, cx| {
2360                editor.move_to_end_of_line(
2361                    &editor::actions::MoveToEndOfLine {
2362                        stop_at_soft_wraps: false,
2363                    },
2364                    window,
2365                    cx,
2366                );
2367            });
2368            return;
2369        }
2370        if let Some(selection) = self.state.selection {
2371            let (mut worktree_ix, mut entry_ix, _) =
2372                self.index_for_selection(selection).unwrap_or_default();
2373            if let Some(worktree_entries) = self
2374                .state
2375                .visible_entries
2376                .get(worktree_ix)
2377                .map(|v| &v.entries)
2378            {
2379                if entry_ix + 1 < worktree_entries.len() {
2380                    entry_ix += 1;
2381                } else {
2382                    worktree_ix += 1;
2383                    entry_ix = 0;
2384                }
2385            }
2386
2387            if let Some(VisibleEntriesForWorktree {
2388                worktree_id,
2389                entries,
2390                ..
2391            }) = self.state.visible_entries.get(worktree_ix)
2392                && let Some(entry) = entries.get(entry_ix)
2393            {
2394                let selection = SelectedEntry {
2395                    worktree_id: *worktree_id,
2396                    entry_id: entry.id,
2397                };
2398                self.state.selection = Some(selection);
2399                if window.modifiers().shift {
2400                    self.marked_entries.push(selection);
2401                }
2402
2403                self.autoscroll(cx);
2404                cx.notify();
2405            }
2406        } else {
2407            self.select_first(&SelectFirst {}, window, cx);
2408        }
2409    }
2410
2411    fn select_prev_diagnostic(
2412        &mut self,
2413        action: &SelectPrevDiagnostic,
2414        window: &mut Window,
2415        cx: &mut Context<Self>,
2416    ) {
2417        let selection = self.find_entry(
2418            self.state.selection.as_ref(),
2419            true,
2420            |entry, worktree_id| {
2421                self.state.selection.is_none_or(|selection| {
2422                    if selection.worktree_id == worktree_id {
2423                        selection.entry_id != entry.id
2424                    } else {
2425                        true
2426                    }
2427                }) && entry.is_file()
2428                    && self
2429                        .diagnostics
2430                        .get(&(worktree_id, entry.path.clone()))
2431                        .is_some_and(|severity| action.severity.matches(*severity))
2432            },
2433            cx,
2434        );
2435
2436        if let Some(selection) = selection {
2437            self.state.selection = Some(selection);
2438            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2439            self.update_visible_entries(
2440                Some((selection.worktree_id, selection.entry_id)),
2441                false,
2442                true,
2443                window,
2444                cx,
2445            );
2446            cx.notify();
2447        }
2448    }
2449
2450    fn select_next_diagnostic(
2451        &mut self,
2452        action: &SelectNextDiagnostic,
2453        window: &mut Window,
2454        cx: &mut Context<Self>,
2455    ) {
2456        let selection = self.find_entry(
2457            self.state.selection.as_ref(),
2458            false,
2459            |entry, worktree_id| {
2460                self.state.selection.is_none_or(|selection| {
2461                    if selection.worktree_id == worktree_id {
2462                        selection.entry_id != entry.id
2463                    } else {
2464                        true
2465                    }
2466                }) && entry.is_file()
2467                    && self
2468                        .diagnostics
2469                        .get(&(worktree_id, entry.path.clone()))
2470                        .is_some_and(|severity| action.severity.matches(*severity))
2471            },
2472            cx,
2473        );
2474
2475        if let Some(selection) = selection {
2476            self.state.selection = Some(selection);
2477            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2478            self.update_visible_entries(
2479                Some((selection.worktree_id, selection.entry_id)),
2480                false,
2481                true,
2482                window,
2483                cx,
2484            );
2485            cx.notify();
2486        }
2487    }
2488
2489    fn select_prev_git_entry(
2490        &mut self,
2491        _: &SelectPrevGitEntry,
2492        window: &mut Window,
2493        cx: &mut Context<Self>,
2494    ) {
2495        let selection = self.find_entry(
2496            self.state.selection.as_ref(),
2497            true,
2498            |entry, worktree_id| {
2499                (self.state.selection.is_none()
2500                    || self.state.selection.is_some_and(|selection| {
2501                        if selection.worktree_id == worktree_id {
2502                            selection.entry_id != entry.id
2503                        } else {
2504                            true
2505                        }
2506                    }))
2507                    && entry.is_file()
2508                    && entry.git_summary.index.modified + entry.git_summary.worktree.modified > 0
2509            },
2510            cx,
2511        );
2512
2513        if let Some(selection) = selection {
2514            self.state.selection = Some(selection);
2515            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2516            self.update_visible_entries(
2517                Some((selection.worktree_id, selection.entry_id)),
2518                false,
2519                true,
2520                window,
2521                cx,
2522            );
2523            cx.notify();
2524        }
2525    }
2526
2527    fn select_prev_directory(
2528        &mut self,
2529        _: &SelectPrevDirectory,
2530        _: &mut Window,
2531        cx: &mut Context<Self>,
2532    ) {
2533        let selection = self.find_visible_entry(
2534            self.state.selection.as_ref(),
2535            true,
2536            |entry, worktree_id| {
2537                self.state.selection.is_none_or(|selection| {
2538                    if selection.worktree_id == worktree_id {
2539                        selection.entry_id != entry.id
2540                    } else {
2541                        true
2542                    }
2543                }) && entry.is_dir()
2544            },
2545            cx,
2546        );
2547
2548        if let Some(selection) = selection {
2549            self.state.selection = Some(selection);
2550            self.autoscroll(cx);
2551            cx.notify();
2552        }
2553    }
2554
2555    fn select_next_directory(
2556        &mut self,
2557        _: &SelectNextDirectory,
2558        _: &mut Window,
2559        cx: &mut Context<Self>,
2560    ) {
2561        let selection = self.find_visible_entry(
2562            self.state.selection.as_ref(),
2563            false,
2564            |entry, worktree_id| {
2565                self.state.selection.is_none_or(|selection| {
2566                    if selection.worktree_id == worktree_id {
2567                        selection.entry_id != entry.id
2568                    } else {
2569                        true
2570                    }
2571                }) && entry.is_dir()
2572            },
2573            cx,
2574        );
2575
2576        if let Some(selection) = selection {
2577            self.state.selection = Some(selection);
2578            self.autoscroll(cx);
2579            cx.notify();
2580        }
2581    }
2582
2583    fn select_next_git_entry(
2584        &mut self,
2585        _: &SelectNextGitEntry,
2586        window: &mut Window,
2587        cx: &mut Context<Self>,
2588    ) {
2589        let selection = self.find_entry(
2590            self.state.selection.as_ref(),
2591            false,
2592            |entry, worktree_id| {
2593                self.state.selection.is_none_or(|selection| {
2594                    if selection.worktree_id == worktree_id {
2595                        selection.entry_id != entry.id
2596                    } else {
2597                        true
2598                    }
2599                }) && entry.is_file()
2600                    && entry.git_summary.index.modified + entry.git_summary.worktree.modified > 0
2601            },
2602            cx,
2603        );
2604
2605        if let Some(selection) = selection {
2606            self.state.selection = Some(selection);
2607            self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2608            self.update_visible_entries(
2609                Some((selection.worktree_id, selection.entry_id)),
2610                false,
2611                true,
2612                window,
2613                cx,
2614            );
2615            cx.notify();
2616        }
2617    }
2618
2619    fn select_parent(&mut self, _: &SelectParent, window: &mut Window, cx: &mut Context<Self>) {
2620        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2621            if let Some(parent) = entry.path.parent() {
2622                let worktree = worktree.read(cx);
2623                if let Some(parent_entry) = worktree.entry_for_path(parent) {
2624                    self.state.selection = Some(SelectedEntry {
2625                        worktree_id: worktree.id(),
2626                        entry_id: parent_entry.id,
2627                    });
2628                    self.autoscroll(cx);
2629                    cx.notify();
2630                }
2631            }
2632        } else {
2633            self.select_first(&SelectFirst {}, window, cx);
2634        }
2635    }
2636
2637    fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
2638        if let Some(VisibleEntriesForWorktree {
2639            worktree_id,
2640            entries,
2641            ..
2642        }) = self.state.visible_entries.first()
2643            && let Some(entry) = entries.first()
2644        {
2645            let selection = SelectedEntry {
2646                worktree_id: *worktree_id,
2647                entry_id: entry.id,
2648            };
2649            self.state.selection = Some(selection);
2650            if window.modifiers().shift {
2651                self.marked_entries.push(selection);
2652            }
2653            self.autoscroll(cx);
2654            cx.notify();
2655        }
2656    }
2657
2658    fn select_last(&mut self, _: &SelectLast, _: &mut Window, cx: &mut Context<Self>) {
2659        if let Some(VisibleEntriesForWorktree {
2660            worktree_id,
2661            entries,
2662            ..
2663        }) = self.state.visible_entries.last()
2664        {
2665            let worktree = self.project.read(cx).worktree_for_id(*worktree_id, cx);
2666            if let (Some(worktree), Some(entry)) = (worktree, entries.last()) {
2667                let worktree = worktree.read(cx);
2668                if let Some(entry) = worktree.entry_for_id(entry.id) {
2669                    let selection = SelectedEntry {
2670                        worktree_id: *worktree_id,
2671                        entry_id: entry.id,
2672                    };
2673                    self.state.selection = Some(selection);
2674                    self.autoscroll(cx);
2675                    cx.notify();
2676                }
2677            }
2678        }
2679    }
2680
2681    fn autoscroll(&mut self, cx: &mut Context<Self>) {
2682        if let Some((_, _, index)) = self
2683            .state
2684            .selection
2685            .and_then(|s| self.index_for_selection(s))
2686        {
2687            self.scroll_handle.scroll_to_item_with_offset(
2688                index,
2689                ScrollStrategy::Center,
2690                self.sticky_items_count,
2691            );
2692            cx.notify();
2693        }
2694    }
2695
2696    fn cut(&mut self, _: &Cut, _: &mut Window, cx: &mut Context<Self>) {
2697        let entries = self.disjoint_entries(cx);
2698        if !entries.is_empty() {
2699            self.clipboard = Some(ClipboardEntry::Cut(entries));
2700            cx.notify();
2701        }
2702    }
2703
2704    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
2705        let entries = self.disjoint_entries(cx);
2706        if !entries.is_empty() {
2707            self.clipboard = Some(ClipboardEntry::Copied(entries));
2708            cx.notify();
2709        }
2710    }
2711
2712    fn create_paste_path(
2713        &self,
2714        source: &SelectedEntry,
2715        (worktree, target_entry): (Entity<Worktree>, &Entry),
2716        cx: &App,
2717    ) -> Option<(Arc<RelPath>, Option<Range<usize>>)> {
2718        let mut new_path = target_entry.path.to_rel_path_buf();
2719        // If we're pasting into a file, or a directory into itself, go up one level.
2720        if target_entry.is_file() || (target_entry.is_dir() && target_entry.id == source.entry_id) {
2721            new_path.pop();
2722        }
2723        let clipboard_entry_file_name = self
2724            .project
2725            .read(cx)
2726            .path_for_entry(source.entry_id, cx)?
2727            .path
2728            .file_name()?
2729            .to_string();
2730        new_path.push(RelPath::unix(&clipboard_entry_file_name).unwrap());
2731        let extension = new_path.extension().map(|s| s.to_string());
2732        let file_name_without_extension = new_path.file_stem()?.to_string();
2733        let file_name_len = file_name_without_extension.len();
2734        let mut disambiguation_range = None;
2735        let mut ix = 0;
2736        {
2737            let worktree = worktree.read(cx);
2738            while worktree.entry_for_path(&new_path).is_some() {
2739                new_path.pop();
2740
2741                let mut new_file_name = file_name_without_extension.to_string();
2742
2743                let disambiguation = " copy";
2744                let mut disambiguation_len = disambiguation.len();
2745
2746                new_file_name.push_str(disambiguation);
2747
2748                if ix > 0 {
2749                    let extra_disambiguation = format!(" {}", ix);
2750                    disambiguation_len += extra_disambiguation.len();
2751                    new_file_name.push_str(&extra_disambiguation);
2752                }
2753                if let Some(extension) = extension.as_ref() {
2754                    new_file_name.push_str(".");
2755                    new_file_name.push_str(extension);
2756                }
2757
2758                new_path.push(RelPath::unix(&new_file_name).unwrap());
2759
2760                disambiguation_range = Some(file_name_len..(file_name_len + disambiguation_len));
2761                ix += 1;
2762            }
2763        }
2764        Some((new_path.as_rel_path().into(), disambiguation_range))
2765    }
2766
2767    fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
2768        maybe!({
2769            let (worktree, entry) = self.selected_entry_handle(cx)?;
2770            let entry = entry.clone();
2771            let worktree_id = worktree.read(cx).id();
2772            let clipboard_entries = self
2773                .clipboard
2774                .as_ref()
2775                .filter(|clipboard| !clipboard.items().is_empty())?;
2776
2777            enum PasteTask {
2778                Rename(Task<Result<CreatedEntry>>),
2779                Copy(Task<Result<Option<Entry>>>),
2780            }
2781
2782            let mut paste_tasks = Vec::new();
2783            let mut disambiguation_range = None;
2784            let clip_is_cut = clipboard_entries.is_cut();
2785            for clipboard_entry in clipboard_entries.items() {
2786                let (new_path, new_disambiguation_range) =
2787                    self.create_paste_path(clipboard_entry, self.selected_sub_entry(cx)?, cx)?;
2788                let clip_entry_id = clipboard_entry.entry_id;
2789                let task = if clipboard_entries.is_cut() {
2790                    let task = self.project.update(cx, |project, cx| {
2791                        project.rename_entry(clip_entry_id, (worktree_id, new_path).into(), cx)
2792                    });
2793                    PasteTask::Rename(task)
2794                } else {
2795                    let task = self.project.update(cx, |project, cx| {
2796                        project.copy_entry(clip_entry_id, (worktree_id, new_path).into(), cx)
2797                    });
2798                    PasteTask::Copy(task)
2799                };
2800                paste_tasks.push(task);
2801                disambiguation_range = new_disambiguation_range.or(disambiguation_range);
2802            }
2803
2804            let item_count = paste_tasks.len();
2805
2806            cx.spawn_in(window, async move |project_panel, cx| {
2807                let mut last_succeed = None;
2808                for task in paste_tasks {
2809                    match task {
2810                        PasteTask::Rename(task) => {
2811                            if let Some(CreatedEntry::Included(entry)) =
2812                                task.await.notify_async_err(cx)
2813                            {
2814                                last_succeed = Some(entry);
2815                            }
2816                        }
2817                        PasteTask::Copy(task) => {
2818                            if let Some(Some(entry)) = task.await.notify_async_err(cx) {
2819                                last_succeed = Some(entry);
2820                            }
2821                        }
2822                    }
2823                }
2824                // update selection
2825                if let Some(entry) = last_succeed {
2826                    project_panel
2827                        .update_in(cx, |project_panel, window, cx| {
2828                            project_panel.state.selection = Some(SelectedEntry {
2829                                worktree_id,
2830                                entry_id: entry.id,
2831                            });
2832
2833                            if item_count == 1 {
2834                                // open entry if not dir, setting is enabled, and only focus if rename is not pending
2835                                if !entry.is_dir() {
2836                                    let settings = ProjectPanelSettings::get_global(cx);
2837                                    if settings.auto_open.should_open_on_paste() {
2838                                        project_panel.open_entry(
2839                                            entry.id,
2840                                            disambiguation_range.is_none(),
2841                                            false,
2842                                            cx,
2843                                        );
2844                                    }
2845                                }
2846
2847                                // if only one entry was pasted and it was disambiguated, open the rename editor
2848                                if disambiguation_range.is_some() {
2849                                    cx.defer_in(window, |this, window, cx| {
2850                                        this.rename_impl(disambiguation_range, window, cx);
2851                                    });
2852                                }
2853                            }
2854                        })
2855                        .ok();
2856                }
2857
2858                anyhow::Ok(())
2859            })
2860            .detach_and_log_err(cx);
2861
2862            if clip_is_cut {
2863                // Convert the clipboard cut entry to a copy entry after the first paste.
2864                self.clipboard = self.clipboard.take().map(ClipboardEntry::into_copy_entry);
2865            }
2866
2867            self.expand_entry(worktree_id, entry.id, cx);
2868            Some(())
2869        });
2870    }
2871
2872    fn duplicate(&mut self, _: &Duplicate, window: &mut Window, cx: &mut Context<Self>) {
2873        self.copy(&Copy {}, window, cx);
2874        self.paste(&Paste {}, window, cx);
2875    }
2876
2877    fn copy_path(
2878        &mut self,
2879        _: &zed_actions::workspace::CopyPath,
2880        _: &mut Window,
2881        cx: &mut Context<Self>,
2882    ) {
2883        let abs_file_paths = {
2884            let project = self.project.read(cx);
2885            self.effective_entries()
2886                .into_iter()
2887                .filter_map(|entry| {
2888                    let entry_path = project.path_for_entry(entry.entry_id, cx)?.path;
2889                    Some(
2890                        project
2891                            .worktree_for_id(entry.worktree_id, cx)?
2892                            .read(cx)
2893                            .absolutize(&entry_path)
2894                            .to_string_lossy()
2895                            .to_string(),
2896                    )
2897                })
2898                .collect::<Vec<_>>()
2899        };
2900        if !abs_file_paths.is_empty() {
2901            cx.write_to_clipboard(ClipboardItem::new_string(abs_file_paths.join("\n")));
2902        }
2903    }
2904
2905    fn copy_relative_path(
2906        &mut self,
2907        _: &zed_actions::workspace::CopyRelativePath,
2908        _: &mut Window,
2909        cx: &mut Context<Self>,
2910    ) {
2911        let path_style = self.project.read(cx).path_style(cx);
2912        let file_paths = {
2913            let project = self.project.read(cx);
2914            self.effective_entries()
2915                .into_iter()
2916                .filter_map(|entry| {
2917                    Some(
2918                        project
2919                            .path_for_entry(entry.entry_id, cx)?
2920                            .path
2921                            .display(path_style)
2922                            .into_owned(),
2923                    )
2924                })
2925                .collect::<Vec<_>>()
2926        };
2927        if !file_paths.is_empty() {
2928            cx.write_to_clipboard(ClipboardItem::new_string(file_paths.join("\n")));
2929        }
2930    }
2931
2932    fn reveal_in_finder(
2933        &mut self,
2934        _: &RevealInFileManager,
2935        _: &mut Window,
2936        cx: &mut Context<Self>,
2937    ) {
2938        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2939            cx.reveal_path(&worktree.read(cx).absolutize(&entry.path));
2940        }
2941    }
2942
2943    fn remove_from_project(
2944        &mut self,
2945        _: &RemoveFromProject,
2946        _window: &mut Window,
2947        cx: &mut Context<Self>,
2948    ) {
2949        for entry in self.effective_entries().iter() {
2950            let worktree_id = entry.worktree_id;
2951            self.project
2952                .update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
2953        }
2954    }
2955
2956    fn file_abs_paths_to_diff(&self, cx: &Context<Self>) -> Option<(PathBuf, PathBuf)> {
2957        let mut selections_abs_path = self
2958            .marked_entries
2959            .iter()
2960            .filter_map(|entry| {
2961                let project = self.project.read(cx);
2962                let worktree = project.worktree_for_id(entry.worktree_id, cx)?;
2963                let entry = worktree.read(cx).entry_for_id(entry.entry_id)?;
2964                if !entry.is_file() {
2965                    return None;
2966                }
2967                Some(worktree.read(cx).absolutize(&entry.path))
2968            })
2969            .rev();
2970
2971        let last_path = selections_abs_path.next()?;
2972        let previous_to_last = selections_abs_path.next()?;
2973        Some((previous_to_last, last_path))
2974    }
2975
2976    fn compare_marked_files(
2977        &mut self,
2978        _: &CompareMarkedFiles,
2979        window: &mut Window,
2980        cx: &mut Context<Self>,
2981    ) {
2982        let selected_files = self.file_abs_paths_to_diff(cx);
2983        if let Some((file_path1, file_path2)) = selected_files {
2984            self.workspace
2985                .update(cx, |workspace, cx| {
2986                    FileDiffView::open(file_path1, file_path2, workspace, window, cx)
2987                        .detach_and_log_err(cx);
2988                })
2989                .ok();
2990        }
2991    }
2992
2993    fn open_system(&mut self, _: &OpenWithSystem, _: &mut Window, cx: &mut Context<Self>) {
2994        if let Some((worktree, entry)) = self.selected_entry(cx) {
2995            let abs_path = worktree.absolutize(&entry.path);
2996            cx.open_with_system(&abs_path);
2997        }
2998    }
2999
3000    fn open_in_terminal(
3001        &mut self,
3002        _: &OpenInTerminal,
3003        window: &mut Window,
3004        cx: &mut Context<Self>,
3005    ) {
3006        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
3007            let abs_path = match &entry.canonical_path {
3008                Some(canonical_path) => canonical_path.to_path_buf(),
3009                None => worktree.read(cx).absolutize(&entry.path),
3010            };
3011
3012            let working_directory = if entry.is_dir() {
3013                Some(abs_path)
3014            } else {
3015                abs_path.parent().map(|path| path.to_path_buf())
3016            };
3017            if let Some(working_directory) = working_directory {
3018                window.dispatch_action(
3019                    workspace::OpenTerminal { working_directory }.boxed_clone(),
3020                    cx,
3021                )
3022            }
3023        }
3024    }
3025
3026    pub fn new_search_in_directory(
3027        &mut self,
3028        _: &NewSearchInDirectory,
3029        window: &mut Window,
3030        cx: &mut Context<Self>,
3031    ) {
3032        if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
3033            let dir_path = if entry.is_dir() {
3034                entry.path.clone()
3035            } else {
3036                // entry is a file, use its parent directory
3037                match entry.path.parent() {
3038                    Some(parent) => Arc::from(parent),
3039                    None => {
3040                        // File at root, open search with empty filter
3041                        self.workspace
3042                            .update(cx, |workspace, cx| {
3043                                search::ProjectSearchView::new_search_in_directory(
3044                                    workspace,
3045                                    RelPath::empty(),
3046                                    window,
3047                                    cx,
3048                                );
3049                            })
3050                            .ok();
3051                        return;
3052                    }
3053                }
3054            };
3055
3056            let include_root = self.project.read(cx).visible_worktrees(cx).count() > 1;
3057            let dir_path = if include_root {
3058                worktree.read(cx).root_name().join(&dir_path)
3059            } else {
3060                dir_path
3061            };
3062
3063            self.workspace
3064                .update(cx, |workspace, cx| {
3065                    search::ProjectSearchView::new_search_in_directory(
3066                        workspace, &dir_path, window, cx,
3067                    );
3068                })
3069                .ok();
3070        }
3071    }
3072
3073    fn move_entry(
3074        &mut self,
3075        entry_to_move: ProjectEntryId,
3076        destination: ProjectEntryId,
3077        destination_is_file: bool,
3078        cx: &mut Context<Self>,
3079    ) {
3080        if self
3081            .project
3082            .read(cx)
3083            .entry_is_worktree_root(entry_to_move, cx)
3084        {
3085            self.move_worktree_root(entry_to_move, destination, cx)
3086        } else {
3087            self.move_worktree_entry(entry_to_move, destination, destination_is_file, cx)
3088        }
3089    }
3090
3091    fn move_worktree_root(
3092        &mut self,
3093        entry_to_move: ProjectEntryId,
3094        destination: ProjectEntryId,
3095        cx: &mut Context<Self>,
3096    ) {
3097        self.project.update(cx, |project, cx| {
3098            let Some(worktree_to_move) = project.worktree_for_entry(entry_to_move, cx) else {
3099                return;
3100            };
3101            let Some(destination_worktree) = project.worktree_for_entry(destination, cx) else {
3102                return;
3103            };
3104
3105            let worktree_id = worktree_to_move.read(cx).id();
3106            let destination_id = destination_worktree.read(cx).id();
3107
3108            project
3109                .move_worktree(worktree_id, destination_id, cx)
3110                .log_err();
3111        });
3112    }
3113
3114    fn move_worktree_entry(
3115        &mut self,
3116        entry_to_move: ProjectEntryId,
3117        destination_entry: ProjectEntryId,
3118        destination_is_file: bool,
3119        cx: &mut Context<Self>,
3120    ) {
3121        if entry_to_move == destination_entry {
3122            return;
3123        }
3124
3125        let destination_worktree = self.project.update(cx, |project, cx| {
3126            let source_path = project.path_for_entry(entry_to_move, cx)?;
3127            let destination_path = project.path_for_entry(destination_entry, cx)?;
3128            let destination_worktree_id = destination_path.worktree_id;
3129
3130            let mut destination_path = destination_path.path.as_ref();
3131            if destination_is_file {
3132                destination_path = destination_path.parent()?;
3133            }
3134
3135            let mut new_path = destination_path.to_rel_path_buf();
3136            new_path.push(RelPath::unix(source_path.path.file_name()?).unwrap());
3137            if new_path.as_rel_path() != source_path.path.as_ref() {
3138                let task = project.rename_entry(
3139                    entry_to_move,
3140                    (destination_worktree_id, new_path).into(),
3141                    cx,
3142                );
3143                cx.foreground_executor().spawn(task).detach_and_log_err(cx);
3144            }
3145
3146            project.worktree_id_for_entry(destination_entry, cx)
3147        });
3148
3149        if let Some(destination_worktree) = destination_worktree {
3150            self.expand_entry(destination_worktree, destination_entry, cx);
3151        }
3152    }
3153
3154    fn index_for_selection(&self, selection: SelectedEntry) -> Option<(usize, usize, usize)> {
3155        self.index_for_entry(selection.entry_id, selection.worktree_id)
3156    }
3157
3158    fn disjoint_entries(&self, cx: &App) -> BTreeSet<SelectedEntry> {
3159        let marked_entries = self.effective_entries();
3160        let mut sanitized_entries = BTreeSet::new();
3161        if marked_entries.is_empty() {
3162            return sanitized_entries;
3163        }
3164
3165        let project = self.project.read(cx);
3166        let marked_entries_by_worktree: HashMap<WorktreeId, Vec<SelectedEntry>> = marked_entries
3167            .into_iter()
3168            .filter(|entry| !project.entry_is_worktree_root(entry.entry_id, cx))
3169            .fold(HashMap::default(), |mut map, entry| {
3170                map.entry(entry.worktree_id).or_default().push(entry);
3171                map
3172            });
3173
3174        for (worktree_id, marked_entries) in marked_entries_by_worktree {
3175            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
3176                let worktree = worktree.read(cx);
3177                let marked_dir_paths = marked_entries
3178                    .iter()
3179                    .filter_map(|entry| {
3180                        worktree.entry_for_id(entry.entry_id).and_then(|entry| {
3181                            if entry.is_dir() {
3182                                Some(entry.path.as_ref())
3183                            } else {
3184                                None
3185                            }
3186                        })
3187                    })
3188                    .collect::<BTreeSet<_>>();
3189
3190                sanitized_entries.extend(marked_entries.into_iter().filter(|entry| {
3191                    let Some(entry_info) = worktree.entry_for_id(entry.entry_id) else {
3192                        return false;
3193                    };
3194                    let entry_path = entry_info.path.as_ref();
3195                    let inside_marked_dir = marked_dir_paths.iter().any(|&marked_dir_path| {
3196                        entry_path != marked_dir_path && entry_path.starts_with(marked_dir_path)
3197                    });
3198                    !inside_marked_dir
3199                }));
3200            }
3201        }
3202
3203        sanitized_entries
3204    }
3205
3206    fn effective_entries(&self) -> BTreeSet<SelectedEntry> {
3207        if let Some(selection) = self.state.selection {
3208            let selection = SelectedEntry {
3209                entry_id: self.resolve_entry(selection.entry_id),
3210                worktree_id: selection.worktree_id,
3211            };
3212
3213            // Default to using just the selected item when nothing is marked.
3214            if self.marked_entries.is_empty() {
3215                return BTreeSet::from([selection]);
3216            }
3217
3218            // Allow operating on the selected item even when something else is marked,
3219            // making it easier to perform one-off actions without clearing a mark.
3220            if self.marked_entries.len() == 1 && !self.marked_entries.contains(&selection) {
3221                return BTreeSet::from([selection]);
3222            }
3223        }
3224
3225        // Return only marked entries since we've already handled special cases where
3226        // only selection should take precedence. At this point, marked entries may or
3227        // may not include the current selection, which is intentional.
3228        self.marked_entries
3229            .iter()
3230            .map(|entry| SelectedEntry {
3231                entry_id: self.resolve_entry(entry.entry_id),
3232                worktree_id: entry.worktree_id,
3233            })
3234            .collect::<BTreeSet<_>>()
3235    }
3236
3237    /// Finds the currently selected subentry for a given leaf entry id. If a given entry
3238    /// has no ancestors, the project entry ID that's passed in is returned as-is.
3239    fn resolve_entry(&self, id: ProjectEntryId) -> ProjectEntryId {
3240        self.state
3241            .ancestors
3242            .get(&id)
3243            .and_then(|ancestors| ancestors.active_ancestor())
3244            .unwrap_or(id)
3245    }
3246
3247    pub fn selected_entry<'a>(&self, cx: &'a App) -> Option<(&'a Worktree, &'a project::Entry)> {
3248        let (worktree, entry) = self.selected_entry_handle(cx)?;
3249        Some((worktree.read(cx), entry))
3250    }
3251
3252    /// Compared to selected_entry, this function resolves to the currently
3253    /// selected subentry if dir auto-folding is enabled.
3254    fn selected_sub_entry<'a>(
3255        &self,
3256        cx: &'a App,
3257    ) -> Option<(Entity<Worktree>, &'a project::Entry)> {
3258        let (worktree, mut entry) = self.selected_entry_handle(cx)?;
3259
3260        let resolved_id = self.resolve_entry(entry.id);
3261        if resolved_id != entry.id {
3262            let worktree = worktree.read(cx);
3263            entry = worktree.entry_for_id(resolved_id)?;
3264        }
3265        Some((worktree, entry))
3266    }
3267    fn selected_entry_handle<'a>(
3268        &self,
3269        cx: &'a App,
3270    ) -> Option<(Entity<Worktree>, &'a project::Entry)> {
3271        let selection = self.state.selection?;
3272        let project = self.project.read(cx);
3273        let worktree = project.worktree_for_id(selection.worktree_id, cx)?;
3274        let entry = worktree.read(cx).entry_for_id(selection.entry_id)?;
3275        Some((worktree, entry))
3276    }
3277
3278    fn expand_to_selection(&mut self, cx: &mut Context<Self>) -> Option<()> {
3279        let (worktree, entry) = self.selected_entry(cx)?;
3280        let expanded_dir_ids = self
3281            .state
3282            .expanded_dir_ids
3283            .entry(worktree.id())
3284            .or_default();
3285
3286        for path in entry.path.ancestors() {
3287            let Some(entry) = worktree.entry_for_path(path) else {
3288                continue;
3289            };
3290            if entry.is_dir()
3291                && let Err(idx) = expanded_dir_ids.binary_search(&entry.id)
3292            {
3293                expanded_dir_ids.insert(idx, entry.id);
3294            }
3295        }
3296
3297        Some(())
3298    }
3299
3300    fn create_new_git_entry(
3301        parent_entry: &Entry,
3302        git_summary: GitSummary,
3303        new_entry_kind: EntryKind,
3304    ) -> GitEntry {
3305        GitEntry {
3306            entry: Entry {
3307                id: NEW_ENTRY_ID,
3308                kind: new_entry_kind,
3309                path: parent_entry.path.join(RelPath::unix("\0").unwrap()),
3310                inode: 0,
3311                mtime: parent_entry.mtime,
3312                size: parent_entry.size,
3313                is_ignored: parent_entry.is_ignored,
3314                is_hidden: parent_entry.is_hidden,
3315                is_external: false,
3316                is_private: false,
3317                is_always_included: parent_entry.is_always_included,
3318                canonical_path: parent_entry.canonical_path.clone(),
3319                char_bag: parent_entry.char_bag,
3320                is_fifo: parent_entry.is_fifo,
3321            },
3322            git_summary,
3323        }
3324    }
3325
3326    fn update_visible_entries(
3327        &mut self,
3328        new_selected_entry: Option<(WorktreeId, ProjectEntryId)>,
3329        focus_filename_editor: bool,
3330        autoscroll: bool,
3331        window: &mut Window,
3332        cx: &mut Context<Self>,
3333    ) {
3334        let now = Instant::now();
3335        let settings = ProjectPanelSettings::get_global(cx);
3336        let auto_collapse_dirs = settings.auto_fold_dirs;
3337        let hide_gitignore = settings.hide_gitignore;
3338        let sort_mode = settings.sort_mode;
3339        let project = self.project.read(cx);
3340        let repo_snapshots = project.git_store().read(cx).repo_snapshots(cx);
3341
3342        let old_ancestors = self.state.ancestors.clone();
3343        let mut new_state = State::derive(&self.state);
3344        new_state.last_worktree_root_id = project
3345            .visible_worktrees(cx)
3346            .next_back()
3347            .and_then(|worktree| worktree.read(cx).root_entry())
3348            .map(|entry| entry.id);
3349        let mut max_width_item = None;
3350
3351        let visible_worktrees: Vec<_> = project
3352            .visible_worktrees(cx)
3353            .map(|worktree| worktree.read(cx).snapshot())
3354            .collect();
3355        let hide_root = settings.hide_root && visible_worktrees.len() == 1;
3356        let hide_hidden = settings.hide_hidden;
3357
3358        let visible_entries_task = cx.spawn_in(window, async move |this, cx| {
3359            let new_state = cx
3360                .background_spawn(async move {
3361                    for worktree_snapshot in visible_worktrees {
3362                        let worktree_id = worktree_snapshot.id();
3363
3364                        let expanded_dir_ids = match new_state.expanded_dir_ids.entry(worktree_id) {
3365                            hash_map::Entry::Occupied(e) => e.into_mut(),
3366                            hash_map::Entry::Vacant(e) => {
3367                                // The first time a worktree's root entry becomes available,
3368                                // mark that root entry as expanded.
3369                                if let Some(entry) = worktree_snapshot.root_entry() {
3370                                    e.insert(vec![entry.id]).as_slice()
3371                                } else {
3372                                    &[]
3373                                }
3374                            }
3375                        };
3376
3377                        let mut new_entry_parent_id = None;
3378                        let mut new_entry_kind = EntryKind::Dir;
3379                        if let Some(edit_state) = &new_state.edit_state
3380                            && edit_state.worktree_id == worktree_id
3381                            && edit_state.is_new_entry()
3382                        {
3383                            new_entry_parent_id = Some(edit_state.entry_id);
3384                            new_entry_kind = if edit_state.is_dir {
3385                                EntryKind::Dir
3386                            } else {
3387                                EntryKind::File
3388                            };
3389                        }
3390
3391                        let mut visible_worktree_entries = Vec::new();
3392                        let mut entry_iter =
3393                            GitTraversal::new(&repo_snapshots, worktree_snapshot.entries(true, 0));
3394                        let mut auto_folded_ancestors = vec![];
3395                        let worktree_abs_path = worktree_snapshot.abs_path();
3396                        while let Some(entry) = entry_iter.entry() {
3397                            if hide_root && Some(entry.entry) == worktree_snapshot.root_entry() {
3398                                if new_entry_parent_id == Some(entry.id) {
3399                                    visible_worktree_entries.push(Self::create_new_git_entry(
3400                                        entry.entry,
3401                                        entry.git_summary,
3402                                        new_entry_kind,
3403                                    ));
3404                                    new_entry_parent_id = None;
3405                                }
3406                                entry_iter.advance();
3407                                continue;
3408                            }
3409                            if auto_collapse_dirs && entry.kind.is_dir() {
3410                                auto_folded_ancestors.push(entry.id);
3411                                if !new_state.unfolded_dir_ids.contains(&entry.id)
3412                                    && let Some(root_path) = worktree_snapshot.root_entry()
3413                                {
3414                                    let mut child_entries =
3415                                        worktree_snapshot.child_entries(&entry.path);
3416                                    if let Some(child) = child_entries.next()
3417                                        && entry.path != root_path.path
3418                                        && child_entries.next().is_none()
3419                                        && child.kind.is_dir()
3420                                    {
3421                                        entry_iter.advance();
3422
3423                                        continue;
3424                                    }
3425                                }
3426                                let depth = old_ancestors
3427                                    .get(&entry.id)
3428                                    .map(|ancestor| ancestor.current_ancestor_depth)
3429                                    .unwrap_or_default()
3430                                    .min(auto_folded_ancestors.len());
3431                                if let Some(edit_state) = &mut new_state.edit_state
3432                                    && edit_state.entry_id == entry.id
3433                                {
3434                                    edit_state.depth = depth;
3435                                }
3436                                let mut ancestors = std::mem::take(&mut auto_folded_ancestors);
3437                                if ancestors.len() > 1 {
3438                                    ancestors.reverse();
3439                                    new_state.ancestors.insert(
3440                                        entry.id,
3441                                        FoldedAncestors {
3442                                            current_ancestor_depth: depth,
3443                                            ancestors,
3444                                        },
3445                                    );
3446                                }
3447                            }
3448                            auto_folded_ancestors.clear();
3449                            if (!hide_gitignore || !entry.is_ignored)
3450                                && (!hide_hidden || !entry.is_hidden)
3451                            {
3452                                visible_worktree_entries.push(entry.to_owned());
3453                            }
3454                            let precedes_new_entry = if let Some(new_entry_id) = new_entry_parent_id
3455                            {
3456                                entry.id == new_entry_id || {
3457                                    new_state.ancestors.get(&entry.id).is_some_and(|entries| {
3458                                        entries.ancestors.contains(&new_entry_id)
3459                                    })
3460                                }
3461                            } else {
3462                                false
3463                            };
3464                            if precedes_new_entry
3465                                && (!hide_gitignore || !entry.is_ignored)
3466                                && (!hide_hidden || !entry.is_hidden)
3467                            {
3468                                visible_worktree_entries.push(Self::create_new_git_entry(
3469                                    entry.entry,
3470                                    entry.git_summary,
3471                                    new_entry_kind,
3472                                ));
3473                            }
3474
3475                            let (depth, chars) = if Some(entry.entry)
3476                                == worktree_snapshot.root_entry()
3477                            {
3478                                let Some(path_name) = worktree_abs_path.file_name() else {
3479                                    continue;
3480                                };
3481                                let depth = 0;
3482                                (depth, path_name.to_string_lossy().chars().count())
3483                            } else if entry.is_file() {
3484                                let Some(path_name) = entry
3485                                    .path
3486                                    .file_name()
3487                                    .with_context(|| {
3488                                        format!("Non-root entry has no file name: {entry:?}")
3489                                    })
3490                                    .log_err()
3491                                else {
3492                                    continue;
3493                                };
3494                                let depth = entry.path.ancestors().count() - 1;
3495                                (depth, path_name.chars().count())
3496                            } else {
3497                                let path = new_state
3498                                    .ancestors
3499                                    .get(&entry.id)
3500                                    .and_then(|ancestors| {
3501                                        let outermost_ancestor = ancestors.ancestors.last()?;
3502                                        let root_folded_entry = worktree_snapshot
3503                                            .entry_for_id(*outermost_ancestor)?
3504                                            .path
3505                                            .as_ref();
3506                                        entry.path.strip_prefix(root_folded_entry).ok().and_then(
3507                                            |suffix| {
3508                                                Some(
3509                                                    RelPath::unix(root_folded_entry.file_name()?)
3510                                                        .unwrap()
3511                                                        .join(suffix),
3512                                                )
3513                                            },
3514                                        )
3515                                    })
3516                                    .or_else(|| {
3517                                        entry.path.file_name().map(|file_name| {
3518                                            RelPath::unix(file_name).unwrap().into()
3519                                        })
3520                                    })
3521                                    .unwrap_or_else(|| entry.path.clone());
3522                                let depth = path.components().count();
3523                                (depth, path.as_unix_str().chars().count())
3524                            };
3525                            let width_estimate =
3526                                item_width_estimate(depth, chars, entry.canonical_path.is_some());
3527
3528                            match max_width_item.as_mut() {
3529                                Some((id, worktree_id, width)) => {
3530                                    if *width < width_estimate {
3531                                        *id = entry.id;
3532                                        *worktree_id = worktree_snapshot.id();
3533                                        *width = width_estimate;
3534                                    }
3535                                }
3536                                None => {
3537                                    max_width_item =
3538                                        Some((entry.id, worktree_snapshot.id(), width_estimate))
3539                                }
3540                            }
3541
3542                            if expanded_dir_ids.binary_search(&entry.id).is_err()
3543                                && entry_iter.advance_to_sibling()
3544                            {
3545                                continue;
3546                            }
3547                            entry_iter.advance();
3548                        }
3549
3550                        par_sort_worktree_entries_with_mode(
3551                            &mut visible_worktree_entries,
3552                            sort_mode,
3553                        );
3554                        new_state.visible_entries.push(VisibleEntriesForWorktree {
3555                            worktree_id,
3556                            entries: visible_worktree_entries,
3557                            index: OnceCell::new(),
3558                        })
3559                    }
3560                    if let Some((project_entry_id, worktree_id, _)) = max_width_item {
3561                        let mut visited_worktrees_length = 0;
3562                        let index = new_state
3563                            .visible_entries
3564                            .iter()
3565                            .find_map(|visible_entries| {
3566                                if worktree_id == visible_entries.worktree_id {
3567                                    visible_entries
3568                                        .entries
3569                                        .iter()
3570                                        .position(|entry| entry.id == project_entry_id)
3571                                } else {
3572                                    visited_worktrees_length += visible_entries.entries.len();
3573                                    None
3574                                }
3575                            });
3576                        if let Some(index) = index {
3577                            new_state.max_width_item_index = Some(visited_worktrees_length + index);
3578                        }
3579                    }
3580                    new_state
3581                })
3582                .await;
3583            this.update_in(cx, |this, window, cx| {
3584                let current_selection = this.state.selection;
3585                this.state = new_state;
3586                if let Some((worktree_id, entry_id)) = new_selected_entry {
3587                    this.state.selection = Some(SelectedEntry {
3588                        worktree_id,
3589                        entry_id,
3590                    });
3591                } else {
3592                    this.state.selection = current_selection;
3593                }
3594                let elapsed = now.elapsed();
3595                if this.last_reported_update.elapsed() > Duration::from_secs(3600) {
3596                    telemetry::event!(
3597                        "Project Panel Updated",
3598                        elapsed_ms = elapsed.as_millis() as u64,
3599                        worktree_entries = this
3600                            .state
3601                            .visible_entries
3602                            .iter()
3603                            .map(|worktree| worktree.entries.len())
3604                            .sum::<usize>(),
3605                    )
3606                }
3607                if this.update_visible_entries_task.focus_filename_editor {
3608                    this.update_visible_entries_task.focus_filename_editor = false;
3609                    this.filename_editor.update(cx, |editor, cx| {
3610                        window.focus(&editor.focus_handle(cx));
3611                    });
3612                }
3613                if this.update_visible_entries_task.autoscroll {
3614                    this.update_visible_entries_task.autoscroll = false;
3615                    this.autoscroll(cx);
3616                }
3617                cx.notify();
3618            })
3619            .ok();
3620        });
3621
3622        self.update_visible_entries_task = UpdateVisibleEntriesTask {
3623            _visible_entries_task: visible_entries_task,
3624            focus_filename_editor: focus_filename_editor
3625                || self.update_visible_entries_task.focus_filename_editor,
3626            autoscroll: autoscroll || self.update_visible_entries_task.autoscroll,
3627        };
3628    }
3629
3630    fn expand_entry(
3631        &mut self,
3632        worktree_id: WorktreeId,
3633        entry_id: ProjectEntryId,
3634        cx: &mut Context<Self>,
3635    ) {
3636        self.project.update(cx, |project, cx| {
3637            if let Some((worktree, expanded_dir_ids)) = project
3638                .worktree_for_id(worktree_id, cx)
3639                .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
3640            {
3641                project.expand_entry(worktree_id, entry_id, cx);
3642                let worktree = worktree.read(cx);
3643
3644                if let Some(mut entry) = worktree.entry_for_id(entry_id) {
3645                    loop {
3646                        if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
3647                            expanded_dir_ids.insert(ix, entry.id);
3648                        }
3649
3650                        if let Some(parent_entry) =
3651                            entry.path.parent().and_then(|p| worktree.entry_for_path(p))
3652                        {
3653                            entry = parent_entry;
3654                        } else {
3655                            break;
3656                        }
3657                    }
3658                }
3659            }
3660        });
3661    }
3662
3663    fn drop_external_files(
3664        &mut self,
3665        paths: &[PathBuf],
3666        entry_id: ProjectEntryId,
3667        window: &mut Window,
3668        cx: &mut Context<Self>,
3669    ) {
3670        let mut paths: Vec<Arc<Path>> = paths.iter().map(|path| Arc::from(path.clone())).collect();
3671
3672        let open_file_after_drop = paths.len() == 1 && paths[0].is_file();
3673
3674        let Some((target_directory, worktree, fs)) = maybe!({
3675            let project = self.project.read(cx);
3676            let fs = project.fs().clone();
3677            let worktree = project.worktree_for_entry(entry_id, cx)?;
3678            let entry = worktree.read(cx).entry_for_id(entry_id)?;
3679            let path = entry.path.clone();
3680            let target_directory = if entry.is_dir() {
3681                path
3682            } else {
3683                path.parent()?.into()
3684            };
3685            Some((target_directory, worktree, fs))
3686        }) else {
3687            return;
3688        };
3689
3690        let mut paths_to_replace = Vec::new();
3691        for path in &paths {
3692            if let Some(name) = path.file_name()
3693                && let Some(name) = name.to_str()
3694            {
3695                let target_path = target_directory.join(RelPath::unix(name).unwrap());
3696                if worktree.read(cx).entry_for_path(&target_path).is_some() {
3697                    paths_to_replace.push((name.to_string(), path.clone()));
3698                }
3699            }
3700        }
3701
3702        cx.spawn_in(window, async move |this, cx| {
3703            async move {
3704                for (filename, original_path) in &paths_to_replace {
3705                    let prompt_message = format!(
3706                        concat!(
3707                            "A file or folder with name {} ",
3708                            "already exists in the destination folder. ",
3709                            "Do you want to replace it?"
3710                        ),
3711                        filename
3712                    );
3713                    let answer = cx
3714                        .update(|window, cx| {
3715                            window.prompt(
3716                                PromptLevel::Info,
3717                                &prompt_message,
3718                                None,
3719                                &["Replace", "Cancel"],
3720                                cx,
3721                            )
3722                        })?
3723                        .await?;
3724
3725                    if answer == 1
3726                        && let Some(item_idx) = paths.iter().position(|p| p == original_path)
3727                    {
3728                        paths.remove(item_idx);
3729                    }
3730                }
3731
3732                if paths.is_empty() {
3733                    return Ok(());
3734                }
3735
3736                let task = worktree.update(cx, |worktree, cx| {
3737                    worktree.copy_external_entries(target_directory, paths, fs, cx)
3738                })?;
3739
3740                let opened_entries = task
3741                    .await
3742                    .with_context(|| "failed to copy external paths")?;
3743                this.update(cx, |this, cx| {
3744                    if open_file_after_drop && !opened_entries.is_empty() {
3745                        let settings = ProjectPanelSettings::get_global(cx);
3746                        if settings.auto_open.should_open_on_drop() {
3747                            this.open_entry(opened_entries[0], true, false, cx);
3748                        }
3749                    }
3750                })
3751            }
3752            .log_err()
3753            .await
3754        })
3755        .detach();
3756    }
3757
3758    fn refresh_drag_cursor_style(
3759        &self,
3760        modifiers: &Modifiers,
3761        window: &mut Window,
3762        cx: &mut Context<Self>,
3763    ) {
3764        if let Some(existing_cursor) = cx.active_drag_cursor_style() {
3765            let new_cursor = if Self::is_copy_modifier_set(modifiers) {
3766                CursorStyle::DragCopy
3767            } else {
3768                CursorStyle::PointingHand
3769            };
3770            if existing_cursor != new_cursor {
3771                cx.set_active_drag_cursor_style(new_cursor, window);
3772            }
3773        }
3774    }
3775
3776    fn is_copy_modifier_set(modifiers: &Modifiers) -> bool {
3777        cfg!(target_os = "macos") && modifiers.alt
3778            || cfg!(not(target_os = "macos")) && modifiers.control
3779    }
3780
3781    fn drag_onto(
3782        &mut self,
3783        selections: &DraggedSelection,
3784        target_entry_id: ProjectEntryId,
3785        is_file: bool,
3786        window: &mut Window,
3787        cx: &mut Context<Self>,
3788    ) {
3789        if Self::is_copy_modifier_set(&window.modifiers()) {
3790            let _ = maybe!({
3791                let project = self.project.read(cx);
3792                let target_worktree = project.worktree_for_entry(target_entry_id, cx)?;
3793                let worktree_id = target_worktree.read(cx).id();
3794                let target_entry = target_worktree
3795                    .read(cx)
3796                    .entry_for_id(target_entry_id)?
3797                    .clone();
3798
3799                let mut copy_tasks = Vec::new();
3800                let mut disambiguation_range = None;
3801                for selection in selections.items() {
3802                    let (new_path, new_disambiguation_range) = self.create_paste_path(
3803                        selection,
3804                        (target_worktree.clone(), &target_entry),
3805                        cx,
3806                    )?;
3807
3808                    let task = self.project.update(cx, |project, cx| {
3809                        project.copy_entry(selection.entry_id, (worktree_id, new_path).into(), cx)
3810                    });
3811                    copy_tasks.push(task);
3812                    disambiguation_range = new_disambiguation_range.or(disambiguation_range);
3813                }
3814
3815                let item_count = copy_tasks.len();
3816
3817                cx.spawn_in(window, async move |project_panel, cx| {
3818                    let mut last_succeed = None;
3819                    for task in copy_tasks.into_iter() {
3820                        if let Some(Some(entry)) = task.await.log_err() {
3821                            last_succeed = Some(entry.id);
3822                        }
3823                    }
3824                    // update selection
3825                    if let Some(entry_id) = last_succeed {
3826                        project_panel
3827                            .update_in(cx, |project_panel, window, cx| {
3828                                project_panel.state.selection = Some(SelectedEntry {
3829                                    worktree_id,
3830                                    entry_id,
3831                                });
3832
3833                                // if only one entry was dragged and it was disambiguated, open the rename editor
3834                                if item_count == 1 && disambiguation_range.is_some() {
3835                                    project_panel.rename_impl(disambiguation_range, window, cx);
3836                                }
3837                            })
3838                            .ok();
3839                    }
3840                })
3841                .detach();
3842                Some(())
3843            });
3844        } else {
3845            for selection in selections.items() {
3846                self.move_entry(selection.entry_id, target_entry_id, is_file, cx);
3847            }
3848        }
3849    }
3850
3851    fn index_for_entry(
3852        &self,
3853        entry_id: ProjectEntryId,
3854        worktree_id: WorktreeId,
3855    ) -> Option<(usize, usize, usize)> {
3856        let mut total_ix = 0;
3857        for (worktree_ix, visible) in self.state.visible_entries.iter().enumerate() {
3858            if worktree_id != visible.worktree_id {
3859                total_ix += visible.entries.len();
3860                continue;
3861            }
3862
3863            return visible
3864                .entries
3865                .iter()
3866                .enumerate()
3867                .find(|(_, entry)| entry.id == entry_id)
3868                .map(|(ix, _)| (worktree_ix, ix, total_ix + ix));
3869        }
3870        None
3871    }
3872
3873    fn entry_at_index(&self, index: usize) -> Option<(WorktreeId, GitEntryRef<'_>)> {
3874        let mut offset = 0;
3875        for worktree in &self.state.visible_entries {
3876            let current_len = worktree.entries.len();
3877            if index < offset + current_len {
3878                return worktree
3879                    .entries
3880                    .get(index - offset)
3881                    .map(|entry| (worktree.worktree_id, entry.to_ref()));
3882            }
3883            offset += current_len;
3884        }
3885        None
3886    }
3887
3888    fn iter_visible_entries(
3889        &self,
3890        range: Range<usize>,
3891        window: &mut Window,
3892        cx: &mut Context<ProjectPanel>,
3893        mut callback: impl FnMut(
3894            &Entry,
3895            usize,
3896            &HashSet<Arc<RelPath>>,
3897            &mut Window,
3898            &mut Context<ProjectPanel>,
3899        ),
3900    ) {
3901        let mut ix = 0;
3902        for visible in &self.state.visible_entries {
3903            if ix >= range.end {
3904                return;
3905            }
3906
3907            if ix + visible.entries.len() <= range.start {
3908                ix += visible.entries.len();
3909                continue;
3910            }
3911
3912            let end_ix = range.end.min(ix + visible.entries.len());
3913            let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3914            let entries = visible
3915                .index
3916                .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
3917            let base_index = ix + entry_range.start;
3918            for (i, entry) in visible.entries[entry_range].iter().enumerate() {
3919                let global_index = base_index + i;
3920                callback(entry, global_index, entries, window, cx);
3921            }
3922            ix = end_ix;
3923        }
3924    }
3925
3926    fn for_each_visible_entry(
3927        &self,
3928        range: Range<usize>,
3929        window: &mut Window,
3930        cx: &mut Context<ProjectPanel>,
3931        mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut Window, &mut Context<ProjectPanel>),
3932    ) {
3933        let mut ix = 0;
3934        for visible in &self.state.visible_entries {
3935            if ix >= range.end {
3936                return;
3937            }
3938
3939            if ix + visible.entries.len() <= range.start {
3940                ix += visible.entries.len();
3941                continue;
3942            }
3943
3944            let end_ix = range.end.min(ix + visible.entries.len());
3945            let git_status_setting = {
3946                let settings = ProjectPanelSettings::get_global(cx);
3947                settings.git_status
3948            };
3949            if let Some(worktree) = self
3950                .project
3951                .read(cx)
3952                .worktree_for_id(visible.worktree_id, cx)
3953            {
3954                let snapshot = worktree.read(cx).snapshot();
3955                let root_name = snapshot.root_name();
3956
3957                let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3958                let entries = visible
3959                    .index
3960                    .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
3961                for entry in visible.entries[entry_range].iter() {
3962                    let status = git_status_setting
3963                        .then_some(entry.git_summary)
3964                        .unwrap_or_default();
3965
3966                    let mut details = self.details_for_entry(
3967                        entry,
3968                        visible.worktree_id,
3969                        root_name,
3970                        entries,
3971                        status,
3972                        None,
3973                        window,
3974                        cx,
3975                    );
3976
3977                    if let Some(edit_state) = &self.state.edit_state {
3978                        let is_edited_entry = if edit_state.is_new_entry() {
3979                            entry.id == NEW_ENTRY_ID
3980                        } else {
3981                            entry.id == edit_state.entry_id
3982                                || self.state.ancestors.get(&entry.id).is_some_and(
3983                                    |auto_folded_dirs| {
3984                                        auto_folded_dirs.ancestors.contains(&edit_state.entry_id)
3985                                    },
3986                                )
3987                        };
3988
3989                        if is_edited_entry {
3990                            if let Some(processing_filename) = &edit_state.processing_filename {
3991                                details.is_processing = true;
3992                                if let Some(ancestors) = edit_state
3993                                    .leaf_entry_id
3994                                    .and_then(|entry| self.state.ancestors.get(&entry))
3995                                {
3996                                    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;
3997                                    let all_components = ancestors.ancestors.len();
3998
3999                                    let prefix_components = all_components - position;
4000                                    let suffix_components = position.checked_sub(1);
4001                                    let mut previous_components =
4002                                        Path::new(&details.filename).components();
4003                                    let mut new_path = previous_components
4004                                        .by_ref()
4005                                        .take(prefix_components)
4006                                        .collect::<PathBuf>();
4007                                    if let Some(last_component) =
4008                                        processing_filename.components().next_back()
4009                                    {
4010                                        new_path.push(last_component);
4011                                        previous_components.next();
4012                                    }
4013
4014                                    if suffix_components.is_some() {
4015                                        new_path.push(previous_components);
4016                                    }
4017                                    if let Some(str) = new_path.to_str() {
4018                                        details.filename.clear();
4019                                        details.filename.push_str(str);
4020                                    }
4021                                } else {
4022                                    details.filename.clear();
4023                                    details.filename.push_str(processing_filename.as_unix_str());
4024                                }
4025                            } else {
4026                                if edit_state.is_new_entry() {
4027                                    details.filename.clear();
4028                                }
4029                                details.is_editing = true;
4030                            }
4031                        }
4032                    }
4033
4034                    callback(entry.id, details, window, cx);
4035                }
4036            }
4037            ix = end_ix;
4038        }
4039    }
4040
4041    fn find_entry_in_worktree(
4042        &self,
4043        worktree_id: WorktreeId,
4044        reverse_search: bool,
4045        only_visible_entries: bool,
4046        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4047        cx: &mut Context<Self>,
4048    ) -> Option<GitEntry> {
4049        if only_visible_entries {
4050            let entries = self
4051                .state
4052                .visible_entries
4053                .iter()
4054                .find_map(|visible| {
4055                    if worktree_id == visible.worktree_id {
4056                        Some(&visible.entries)
4057                    } else {
4058                        None
4059                    }
4060                })?
4061                .clone();
4062
4063            return utils::ReversibleIterable::new(entries.iter(), reverse_search)
4064                .find(|ele| predicate(ele.to_ref(), worktree_id))
4065                .cloned();
4066        }
4067
4068        let repo_snapshots = self
4069            .project
4070            .read(cx)
4071            .git_store()
4072            .read(cx)
4073            .repo_snapshots(cx);
4074        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4075        worktree.read_with(cx, |tree, _| {
4076            utils::ReversibleIterable::new(
4077                GitTraversal::new(&repo_snapshots, tree.entries(true, 0usize)),
4078                reverse_search,
4079            )
4080            .find_single_ended(|ele| predicate(*ele, worktree_id))
4081            .map(|ele| ele.to_owned())
4082        })
4083    }
4084
4085    fn find_entry(
4086        &self,
4087        start: Option<&SelectedEntry>,
4088        reverse_search: bool,
4089        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4090        cx: &mut Context<Self>,
4091    ) -> Option<SelectedEntry> {
4092        let mut worktree_ids: Vec<_> = self
4093            .state
4094            .visible_entries
4095            .iter()
4096            .map(|worktree| worktree.worktree_id)
4097            .collect();
4098        let repo_snapshots = self
4099            .project
4100            .read(cx)
4101            .git_store()
4102            .read(cx)
4103            .repo_snapshots(cx);
4104
4105        let mut last_found: Option<SelectedEntry> = None;
4106
4107        if let Some(start) = start {
4108            let worktree = self
4109                .project
4110                .read(cx)
4111                .worktree_for_id(start.worktree_id, cx)?
4112                .read(cx);
4113
4114            let search = {
4115                let entry = worktree.entry_for_id(start.entry_id)?;
4116                let root_entry = worktree.root_entry()?;
4117                let tree_id = worktree.id();
4118
4119                let mut first_iter = GitTraversal::new(
4120                    &repo_snapshots,
4121                    worktree.traverse_from_path(true, true, true, entry.path.as_ref()),
4122                );
4123
4124                if reverse_search {
4125                    first_iter.next();
4126                }
4127
4128                let first = first_iter
4129                    .enumerate()
4130                    .take_until(|(count, entry)| entry.entry == root_entry && *count != 0usize)
4131                    .map(|(_, entry)| entry)
4132                    .find(|ele| predicate(*ele, tree_id))
4133                    .map(|ele| ele.to_owned());
4134
4135                let second_iter =
4136                    GitTraversal::new(&repo_snapshots, worktree.entries(true, 0usize));
4137
4138                let second = if reverse_search {
4139                    second_iter
4140                        .take_until(|ele| ele.id == start.entry_id)
4141                        .filter(|ele| predicate(*ele, tree_id))
4142                        .last()
4143                        .map(|ele| ele.to_owned())
4144                } else {
4145                    second_iter
4146                        .take_while(|ele| ele.id != start.entry_id)
4147                        .filter(|ele| predicate(*ele, tree_id))
4148                        .last()
4149                        .map(|ele| ele.to_owned())
4150                };
4151
4152                if reverse_search {
4153                    Some((second, first))
4154                } else {
4155                    Some((first, second))
4156                }
4157            };
4158
4159            if let Some((first, second)) = search {
4160                let first = first.map(|entry| SelectedEntry {
4161                    worktree_id: start.worktree_id,
4162                    entry_id: entry.id,
4163                });
4164
4165                let second = second.map(|entry| SelectedEntry {
4166                    worktree_id: start.worktree_id,
4167                    entry_id: entry.id,
4168                });
4169
4170                if first.is_some() {
4171                    return first;
4172                }
4173                last_found = second;
4174
4175                let idx = worktree_ids
4176                    .iter()
4177                    .enumerate()
4178                    .find(|(_, ele)| **ele == start.worktree_id)
4179                    .map(|(idx, _)| idx);
4180
4181                if let Some(idx) = idx {
4182                    worktree_ids.rotate_left(idx + 1usize);
4183                    worktree_ids.pop();
4184                }
4185            }
4186        }
4187
4188        for tree_id in worktree_ids.into_iter() {
4189            if let Some(found) =
4190                self.find_entry_in_worktree(tree_id, reverse_search, false, &predicate, cx)
4191            {
4192                return Some(SelectedEntry {
4193                    worktree_id: tree_id,
4194                    entry_id: found.id,
4195                });
4196            }
4197        }
4198
4199        last_found
4200    }
4201
4202    fn find_visible_entry(
4203        &self,
4204        start: Option<&SelectedEntry>,
4205        reverse_search: bool,
4206        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4207        cx: &mut Context<Self>,
4208    ) -> Option<SelectedEntry> {
4209        let mut worktree_ids: Vec<_> = self
4210            .state
4211            .visible_entries
4212            .iter()
4213            .map(|worktree| worktree.worktree_id)
4214            .collect();
4215
4216        let mut last_found: Option<SelectedEntry> = None;
4217
4218        if let Some(start) = start {
4219            let entries = self
4220                .state
4221                .visible_entries
4222                .iter()
4223                .find(|worktree| worktree.worktree_id == start.worktree_id)
4224                .map(|worktree| &worktree.entries)?;
4225
4226            let mut start_idx = entries
4227                .iter()
4228                .enumerate()
4229                .find(|(_, ele)| ele.id == start.entry_id)
4230                .map(|(idx, _)| idx)?;
4231
4232            if reverse_search {
4233                start_idx = start_idx.saturating_add(1usize);
4234            }
4235
4236            let (left, right) = entries.split_at_checked(start_idx)?;
4237
4238            let (first_iter, second_iter) = if reverse_search {
4239                (
4240                    utils::ReversibleIterable::new(left.iter(), reverse_search),
4241                    utils::ReversibleIterable::new(right.iter(), reverse_search),
4242                )
4243            } else {
4244                (
4245                    utils::ReversibleIterable::new(right.iter(), reverse_search),
4246                    utils::ReversibleIterable::new(left.iter(), reverse_search),
4247                )
4248            };
4249
4250            let first_search = first_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
4251            let second_search = second_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
4252
4253            if first_search.is_some() {
4254                return first_search.map(|entry| SelectedEntry {
4255                    worktree_id: start.worktree_id,
4256                    entry_id: entry.id,
4257                });
4258            }
4259
4260            last_found = second_search.map(|entry| SelectedEntry {
4261                worktree_id: start.worktree_id,
4262                entry_id: entry.id,
4263            });
4264
4265            let idx = worktree_ids
4266                .iter()
4267                .enumerate()
4268                .find(|(_, ele)| **ele == start.worktree_id)
4269                .map(|(idx, _)| idx);
4270
4271            if let Some(idx) = idx {
4272                worktree_ids.rotate_left(idx + 1usize);
4273                worktree_ids.pop();
4274            }
4275        }
4276
4277        for tree_id in worktree_ids.into_iter() {
4278            if let Some(found) =
4279                self.find_entry_in_worktree(tree_id, reverse_search, true, &predicate, cx)
4280            {
4281                return Some(SelectedEntry {
4282                    worktree_id: tree_id,
4283                    entry_id: found.id,
4284                });
4285            }
4286        }
4287
4288        last_found
4289    }
4290
4291    fn calculate_depth_and_difference(
4292        entry: &Entry,
4293        visible_worktree_entries: &HashSet<Arc<RelPath>>,
4294    ) -> (usize, usize) {
4295        let (depth, difference) = entry
4296            .path
4297            .ancestors()
4298            .skip(1) // Skip the entry itself
4299            .find_map(|ancestor| {
4300                if let Some(parent_entry) = visible_worktree_entries.get(ancestor) {
4301                    let entry_path_components_count = entry.path.components().count();
4302                    let parent_path_components_count = parent_entry.components().count();
4303                    let difference = entry_path_components_count - parent_path_components_count;
4304                    let depth = parent_entry
4305                        .ancestors()
4306                        .skip(1)
4307                        .filter(|ancestor| visible_worktree_entries.contains(*ancestor))
4308                        .count();
4309                    Some((depth + 1, difference))
4310                } else {
4311                    None
4312                }
4313            })
4314            .unwrap_or_else(|| (0, entry.path.components().count()));
4315
4316        (depth, difference)
4317    }
4318
4319    fn highlight_entry_for_external_drag(
4320        &self,
4321        target_entry: &Entry,
4322        target_worktree: &Worktree,
4323    ) -> Option<ProjectEntryId> {
4324        // Always highlight directory or parent directory if it's file
4325        if target_entry.is_dir() {
4326            Some(target_entry.id)
4327        } else {
4328            target_entry
4329                .path
4330                .parent()
4331                .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4332                .map(|parent_entry| parent_entry.id)
4333        }
4334    }
4335
4336    fn highlight_entry_for_selection_drag(
4337        &self,
4338        target_entry: &Entry,
4339        target_worktree: &Worktree,
4340        drag_state: &DraggedSelection,
4341        cx: &Context<Self>,
4342    ) -> Option<ProjectEntryId> {
4343        let target_parent_path = target_entry.path.parent();
4344
4345        // In case of single item drag, we do not highlight existing
4346        // directory which item belongs too
4347        if drag_state.items().count() == 1
4348            && drag_state.active_selection.worktree_id == target_worktree.id()
4349        {
4350            let active_entry_path = self
4351                .project
4352                .read(cx)
4353                .path_for_entry(drag_state.active_selection.entry_id, cx)?;
4354
4355            if let Some(active_parent_path) = active_entry_path.path.parent() {
4356                // Do not highlight active entry parent
4357                if active_parent_path == target_entry.path.as_ref() {
4358                    return None;
4359                }
4360
4361                // Do not highlight active entry sibling files
4362                if Some(active_parent_path) == target_parent_path && target_entry.is_file() {
4363                    return None;
4364                }
4365            }
4366        }
4367
4368        // Always highlight directory or parent directory if it's file
4369        if target_entry.is_dir() {
4370            Some(target_entry.id)
4371        } else {
4372            target_parent_path
4373                .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4374                .map(|parent_entry| parent_entry.id)
4375        }
4376    }
4377
4378    fn should_highlight_background_for_selection_drag(
4379        &self,
4380        drag_state: &DraggedSelection,
4381        last_root_id: ProjectEntryId,
4382        cx: &App,
4383    ) -> bool {
4384        // Always highlight for multiple entries
4385        if drag_state.items().count() > 1 {
4386            return true;
4387        }
4388
4389        // Since root will always have empty relative path
4390        if let Some(entry_path) = self
4391            .project
4392            .read(cx)
4393            .path_for_entry(drag_state.active_selection.entry_id, cx)
4394        {
4395            if let Some(parent_path) = entry_path.path.parent() {
4396                if !parent_path.is_empty() {
4397                    return true;
4398                }
4399            }
4400        }
4401
4402        // If parent is empty, check if different worktree
4403        if let Some(last_root_worktree_id) = self
4404            .project
4405            .read(cx)
4406            .worktree_id_for_entry(last_root_id, cx)
4407        {
4408            if drag_state.active_selection.worktree_id != last_root_worktree_id {
4409                return true;
4410            }
4411        }
4412
4413        false
4414    }
4415
4416    fn render_entry(
4417        &self,
4418        entry_id: ProjectEntryId,
4419        details: EntryDetails,
4420        window: &mut Window,
4421        cx: &mut Context<Self>,
4422    ) -> Stateful<Div> {
4423        const GROUP_NAME: &str = "project_entry";
4424
4425        let kind = details.kind;
4426        let is_sticky = details.sticky.is_some();
4427        let sticky_index = details.sticky.as_ref().map(|this| this.sticky_index);
4428        let settings = ProjectPanelSettings::get_global(cx);
4429        let show_editor = details.is_editing && !details.is_processing;
4430
4431        let selection = SelectedEntry {
4432            worktree_id: details.worktree_id,
4433            entry_id,
4434        };
4435
4436        let is_marked = self.marked_entries.contains(&selection);
4437        let is_active = self
4438            .state
4439            .selection
4440            .is_some_and(|selection| selection.entry_id == entry_id);
4441
4442        let file_name = details.filename.clone();
4443
4444        let mut icon = details.icon.clone();
4445        if settings.file_icons && show_editor && details.kind.is_file() {
4446            let filename = self.filename_editor.read(cx).text(cx);
4447            if filename.len() > 2 {
4448                icon = FileIcons::get_icon(Path::new(&filename), cx);
4449            }
4450        }
4451
4452        let filename_text_color = details.filename_text_color;
4453        let diagnostic_severity = details.diagnostic_severity;
4454        let item_colors = get_item_color(is_sticky, cx);
4455
4456        let canonical_path = details
4457            .canonical_path
4458            .as_ref()
4459            .map(|f| f.to_string_lossy().into_owned());
4460        let path_style = self.project.read(cx).path_style(cx);
4461        let path = details.path.clone();
4462        let path_for_external_paths = path.clone();
4463        let path_for_dragged_selection = path.clone();
4464
4465        let depth = details.depth;
4466        let worktree_id = details.worktree_id;
4467        let dragged_selection = DraggedSelection {
4468            active_selection: SelectedEntry {
4469                worktree_id: selection.worktree_id,
4470                entry_id: self.resolve_entry(selection.entry_id),
4471            },
4472            marked_selections: Arc::from(self.marked_entries.clone()),
4473        };
4474
4475        let bg_color = if is_marked {
4476            item_colors.marked
4477        } else {
4478            item_colors.default
4479        };
4480
4481        let bg_hover_color = if is_marked {
4482            item_colors.marked
4483        } else {
4484            item_colors.hover
4485        };
4486
4487        let validation_color_and_message = if show_editor {
4488            match self
4489                .state
4490                .edit_state
4491                .as_ref()
4492                .map_or(ValidationState::None, |e| e.validation_state.clone())
4493            {
4494                ValidationState::Error(msg) => Some((Color::Error.color(cx), msg)),
4495                ValidationState::Warning(msg) => Some((Color::Warning.color(cx), msg)),
4496                ValidationState::None => None,
4497            }
4498        } else {
4499            None
4500        };
4501
4502        let border_color =
4503            if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4504                match validation_color_and_message {
4505                    Some((color, _)) => color,
4506                    None => item_colors.focused,
4507                }
4508            } else {
4509                bg_color
4510            };
4511
4512        let border_hover_color =
4513            if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4514                match validation_color_and_message {
4515                    Some((color, _)) => color,
4516                    None => item_colors.focused,
4517                }
4518            } else {
4519                bg_hover_color
4520            };
4521
4522        let folded_directory_drag_target = self.folded_directory_drag_target;
4523        let is_highlighted = {
4524            if let Some(highlight_entry_id) =
4525                self.drag_target_entry
4526                    .as_ref()
4527                    .and_then(|drag_target| match drag_target {
4528                        DragTarget::Entry {
4529                            highlight_entry_id, ..
4530                        } => Some(*highlight_entry_id),
4531                        DragTarget::Background => self.state.last_worktree_root_id,
4532                    })
4533            {
4534                // Highlight if same entry or it's children
4535                if entry_id == highlight_entry_id {
4536                    true
4537                } else {
4538                    maybe!({
4539                        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4540                        let highlight_entry = worktree.read(cx).entry_for_id(highlight_entry_id)?;
4541                        Some(path.starts_with(&highlight_entry.path))
4542                    })
4543                    .unwrap_or(false)
4544                }
4545            } else {
4546                false
4547            }
4548        };
4549
4550        let id: ElementId = if is_sticky {
4551            SharedString::from(format!("project_panel_sticky_item_{}", entry_id.to_usize())).into()
4552        } else {
4553            (entry_id.to_proto() as usize).into()
4554        };
4555
4556        div()
4557            .id(id.clone())
4558            .relative()
4559            .group(GROUP_NAME)
4560            .cursor_pointer()
4561            .rounded_none()
4562            .bg(bg_color)
4563            .border_1()
4564            .border_r_2()
4565            .border_color(border_color)
4566            .hover(|style| style.bg(bg_hover_color).border_color(border_hover_color))
4567            .when(is_sticky, |this| {
4568                this.block_mouse_except_scroll()
4569            })
4570            .when(!is_sticky, |this| {
4571                this
4572                .when(is_highlighted && folded_directory_drag_target.is_none(), |this| this.border_color(transparent_white()).bg(item_colors.drag_over))
4573                .when(settings.drag_and_drop, |this| this
4574                .on_drag_move::<ExternalPaths>(cx.listener(
4575                    move |this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
4576                        let is_current_target = this.drag_target_entry.as_ref()
4577                             .and_then(|entry| match entry {
4578                                 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4579                                 DragTarget::Background { .. } => None,
4580                             }) == Some(entry_id);
4581
4582                        if !event.bounds.contains(&event.event.position) {
4583                            // Entry responsible for setting drag target is also responsible to
4584                            // clear it up after drag is out of bounds
4585                            if is_current_target {
4586                                this.drag_target_entry = None;
4587                            }
4588                            return;
4589                        }
4590
4591                        if is_current_target {
4592                            return;
4593                        }
4594
4595                        this.marked_entries.clear();
4596
4597                        let Some((entry_id, highlight_entry_id)) = maybe!({
4598                            let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4599                            let target_entry = target_worktree.entry_for_path(&path_for_external_paths)?;
4600                            let highlight_entry_id = this.highlight_entry_for_external_drag(target_entry, target_worktree)?;
4601                            Some((target_entry.id, highlight_entry_id))
4602                        }) else {
4603                            return;
4604                        };
4605
4606                        this.drag_target_entry = Some(DragTarget::Entry {
4607                            entry_id,
4608                            highlight_entry_id,
4609                        });
4610
4611                    },
4612                ))
4613                .on_drop(cx.listener(
4614                    move |this, external_paths: &ExternalPaths, window, cx| {
4615                        this.drag_target_entry = None;
4616                        this.hover_scroll_task.take();
4617                        this.drop_external_files(external_paths.paths(), entry_id, window, cx);
4618                        cx.stop_propagation();
4619                    },
4620                ))
4621                .on_drag_move::<DraggedSelection>(cx.listener(
4622                    move |this, event: &DragMoveEvent<DraggedSelection>, window, cx| {
4623                        let is_current_target = this.drag_target_entry.as_ref()
4624                             .and_then(|entry| match entry {
4625                                 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4626                                 DragTarget::Background { .. } => None,
4627                             }) == Some(entry_id);
4628
4629                        if !event.bounds.contains(&event.event.position) {
4630                            // Entry responsible for setting drag target is also responsible to
4631                            // clear it up after drag is out of bounds
4632                            if is_current_target {
4633                                this.drag_target_entry = None;
4634                            }
4635                            return;
4636                        }
4637
4638                        if is_current_target {
4639                            return;
4640                        }
4641
4642                        let drag_state = event.drag(cx);
4643
4644                        if drag_state.items().count() == 1 {
4645                            this.marked_entries.clear();
4646                            this.marked_entries.push(drag_state.active_selection);
4647                        }
4648
4649                        let Some((entry_id, highlight_entry_id)) = maybe!({
4650                            let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4651                            let target_entry = target_worktree.entry_for_path(&path_for_dragged_selection)?;
4652                            let highlight_entry_id = this.highlight_entry_for_selection_drag(target_entry, target_worktree, drag_state, cx)?;
4653                            Some((target_entry.id, highlight_entry_id))
4654                        }) else {
4655                            return;
4656                        };
4657
4658                        this.drag_target_entry = Some(DragTarget::Entry {
4659                            entry_id,
4660                            highlight_entry_id,
4661                        });
4662
4663                        this.hover_expand_task.take();
4664
4665                        if !kind.is_dir()
4666                            || this
4667                                .state
4668                                .expanded_dir_ids
4669                                .get(&details.worktree_id)
4670                                .is_some_and(|ids| ids.binary_search(&entry_id).is_ok())
4671                        {
4672                            return;
4673                        }
4674
4675                        let bounds = event.bounds;
4676                        this.hover_expand_task =
4677                            Some(cx.spawn_in(window, async move |this, cx| {
4678                                cx.background_executor()
4679                                    .timer(Duration::from_millis(500))
4680                                    .await;
4681                                this.update_in(cx, |this, window, cx| {
4682                                    this.hover_expand_task.take();
4683                                    if this.drag_target_entry.as_ref().and_then(|entry| match entry {
4684                                        DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4685                                        DragTarget::Background { .. } => None,
4686                                    }) == Some(entry_id)
4687                                        && bounds.contains(&window.mouse_position())
4688                                    {
4689                                        this.expand_entry(worktree_id, entry_id, cx);
4690                                        this.update_visible_entries(
4691                                            Some((worktree_id, entry_id)),
4692                                            false,
4693                                            false,
4694                                            window,
4695                                            cx,
4696                                        );
4697                                        cx.notify();
4698                                    }
4699                                })
4700                                .ok();
4701                            }));
4702                    },
4703                ))
4704                .on_drag(
4705                    dragged_selection,
4706                    {
4707                        let active_component = self.state.ancestors.get(&entry_id).and_then(|ancestors| ancestors.active_component(&details.filename));
4708                        move |selection, click_offset, _window, cx| {
4709                            let filename = active_component.as_ref().unwrap_or_else(|| &details.filename);
4710                            cx.new(|_| DraggedProjectEntryView {
4711                                icon: details.icon.clone(),
4712                                filename: filename.clone(),
4713                                click_offset,
4714                                selection: selection.active_selection,
4715                                selections: selection.marked_selections.clone(),
4716                            })
4717                        }
4718                    }
4719                )
4720                .on_drop(
4721                    cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4722                        this.drag_target_entry = None;
4723                        this.hover_scroll_task.take();
4724                        this.hover_expand_task.take();
4725                        if folded_directory_drag_target.is_some() {
4726                            return;
4727                        }
4728                        this.drag_onto(selections, entry_id, kind.is_file(), window, cx);
4729                    }),
4730                ))
4731            })
4732            .on_mouse_down(
4733                MouseButton::Left,
4734                cx.listener(move |this, _, _, cx| {
4735                    this.mouse_down = true;
4736                    cx.propagate();
4737                }),
4738            )
4739            .on_click(
4740                cx.listener(move |project_panel, event: &gpui::ClickEvent, window, cx| {
4741                    if event.is_right_click() || event.first_focus()
4742                        || show_editor
4743                    {
4744                        return;
4745                    }
4746                    if event.standard_click() {
4747                        project_panel.mouse_down = false;
4748                    }
4749                    cx.stop_propagation();
4750
4751                    if let Some(selection) = project_panel.state.selection.filter(|_| event.modifiers().shift) {
4752                        let current_selection = project_panel.index_for_selection(selection);
4753                        let clicked_entry = SelectedEntry {
4754                            entry_id,
4755                            worktree_id,
4756                        };
4757                        let target_selection = project_panel.index_for_selection(clicked_entry);
4758                        if let Some(((_, _, source_index), (_, _, target_index))) =
4759                            current_selection.zip(target_selection)
4760                        {
4761                            let range_start = source_index.min(target_index);
4762                            let range_end = source_index.max(target_index) + 1;
4763                            let mut new_selections = Vec::new();
4764                            project_panel.for_each_visible_entry(
4765                                range_start..range_end,
4766                                window,
4767                                cx,
4768                                |entry_id, details, _, _| {
4769                                    new_selections.push(SelectedEntry {
4770                                        entry_id,
4771                                        worktree_id: details.worktree_id,
4772                                    });
4773                                },
4774                            );
4775
4776                            for selection in &new_selections {
4777                                if !project_panel.marked_entries.contains(selection) {
4778                                    project_panel.marked_entries.push(*selection);
4779                                }
4780                            }
4781
4782                            project_panel.state.selection = Some(clicked_entry);
4783                            if !project_panel.marked_entries.contains(&clicked_entry) {
4784                                project_panel.marked_entries.push(clicked_entry);
4785                            }
4786                        }
4787                    } else if event.modifiers().secondary() {
4788                        if event.click_count() > 1 {
4789                            project_panel.split_entry(entry_id, false, None, cx);
4790                        } else {
4791                            project_panel.state.selection = Some(selection);
4792                            if let Some(position) = project_panel.marked_entries.iter().position(|e| *e == selection) {
4793                                project_panel.marked_entries.remove(position);
4794                            } else {
4795                                project_panel.marked_entries.push(selection);
4796                            }
4797                        }
4798                    } else if kind.is_dir() {
4799                        project_panel.marked_entries.clear();
4800                        if is_sticky
4801                            && let Some((_, _, index)) = project_panel.index_for_entry(entry_id, worktree_id) {
4802                                project_panel.scroll_handle.scroll_to_item_strict_with_offset(index, ScrollStrategy::Top, sticky_index.unwrap_or(0));
4803                                cx.notify();
4804                                // move down by 1px so that clicked item
4805                                // don't count as sticky anymore
4806                                cx.on_next_frame(window, |_, window, cx| {
4807                                    cx.on_next_frame(window, |this, _, cx| {
4808                                        let mut offset = this.scroll_handle.offset();
4809                                        offset.y += px(1.);
4810                                        this.scroll_handle.set_offset(offset);
4811                                        cx.notify();
4812                                    });
4813                                });
4814                                return;
4815                            }
4816                        if event.modifiers().alt {
4817                            project_panel.toggle_expand_all(entry_id, window, cx);
4818                        } else {
4819                            project_panel.toggle_expanded(entry_id, window, cx);
4820                        }
4821                    } else {
4822                        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
4823                        let click_count = event.click_count();
4824                        let focus_opened_item = click_count > 1;
4825                        let allow_preview = preview_tabs_enabled && click_count == 1;
4826                        project_panel.open_entry(entry_id, focus_opened_item, allow_preview, cx);
4827                    }
4828                }),
4829            )
4830            .child(
4831                ListItem::new(id)
4832                    .indent_level(depth)
4833                    .indent_step_size(px(settings.indent_size))
4834                    .spacing(match settings.entry_spacing {
4835                        ProjectPanelEntrySpacing::Comfortable => ListItemSpacing::Dense,
4836                        ProjectPanelEntrySpacing::Standard => {
4837                            ListItemSpacing::ExtraDense
4838                        }
4839                    })
4840                    .selectable(false)
4841                    .when_some(canonical_path, |this, path| {
4842                        this.end_slot::<AnyElement>(
4843                            div()
4844                                .id("symlink_icon")
4845                                .pr_3()
4846                                .tooltip(move |_window, cx| {
4847                                    Tooltip::with_meta(
4848                                        path.to_string(),
4849                                        None,
4850                                        "Symbolic Link",
4851                                        cx,
4852                                    )
4853                                })
4854                                .child(
4855                                    Icon::new(IconName::ArrowUpRight)
4856                                        .size(IconSize::Indicator)
4857                                        .color(filename_text_color),
4858                                )
4859                                .into_any_element(),
4860                        )
4861                    })
4862                    .child(if let Some(icon) = &icon {
4863                        if let Some((_, decoration_color)) =
4864                            entry_diagnostic_aware_icon_decoration_and_color(diagnostic_severity)
4865                        {
4866                            let is_warning = diagnostic_severity
4867                                .map(|severity| matches!(severity, DiagnosticSeverity::WARNING))
4868                                .unwrap_or(false);
4869                            div().child(
4870                                DecoratedIcon::new(
4871                                    Icon::from_path(icon.clone()).color(Color::Muted),
4872                                    Some(
4873                                        IconDecoration::new(
4874                                            if kind.is_file() {
4875                                                if is_warning {
4876                                                    IconDecorationKind::Triangle
4877                                                } else {
4878                                                    IconDecorationKind::X
4879                                                }
4880                                            } else {
4881                                                IconDecorationKind::Dot
4882                                            },
4883                                            bg_color,
4884                                            cx,
4885                                        )
4886                                        .group_name(Some(GROUP_NAME.into()))
4887                                        .knockout_hover_color(bg_hover_color)
4888                                        .color(decoration_color.color(cx))
4889                                        .position(Point {
4890                                            x: px(-2.),
4891                                            y: px(-2.),
4892                                        }),
4893                                    ),
4894                                )
4895                                .into_any_element(),
4896                            )
4897                        } else {
4898                            h_flex().child(Icon::from_path(icon.to_string()).color(Color::Muted))
4899                        }
4900                    } else if let Some((icon_name, color)) =
4901                        entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
4902                    {
4903                        h_flex()
4904                            .size(IconSize::default().rems())
4905                            .child(Icon::new(icon_name).color(color).size(IconSize::Small))
4906                    } else {
4907                        h_flex()
4908                            .size(IconSize::default().rems())
4909                            .invisible()
4910                            .flex_none()
4911                    })
4912                    .child(
4913                        if let (Some(editor), true) = (Some(&self.filename_editor), show_editor) {
4914                            h_flex().h_6().w_full().child(editor.clone())
4915                        } else {
4916                            h_flex().h_6().map(|mut this| {
4917                                if let Some(folded_ancestors) = self.state.ancestors.get(&entry_id) {
4918                                    let components = Path::new(&file_name)
4919                                        .components()
4920                                        .map(|comp| comp.as_os_str().to_string_lossy().into_owned())
4921                                        .collect::<Vec<_>>();
4922                                    let active_index = folded_ancestors.active_index();
4923                                    let components_len = components.len();
4924                                    let delimiter = SharedString::new(path_style.primary_separator());
4925                                    for (index, component) in components.iter().enumerate() {
4926                                        if index != 0 {
4927                                                let delimiter_target_index = index - 1;
4928                                                let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - delimiter_target_index).cloned();
4929                                                this = this.child(
4930                                                    div()
4931                                                    .when(!is_sticky, |div| {
4932                                                        div
4933                                                            .when(settings.drag_and_drop, |div| div
4934                                                            .on_drop(cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4935                                                            this.hover_scroll_task.take();
4936                                                            this.drag_target_entry = None;
4937                                                            this.folded_directory_drag_target = None;
4938                                                            if let Some(target_entry_id) = target_entry_id {
4939                                                                this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4940                                                            }
4941                                                        }))
4942                                                        .on_drag_move(cx.listener(
4943                                                            move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4944                                                                if event.bounds.contains(&event.event.position) {
4945                                                                    this.folded_directory_drag_target = Some(
4946                                                                        FoldedDirectoryDragTarget {
4947                                                                            entry_id,
4948                                                                            index: delimiter_target_index,
4949                                                                            is_delimiter_target: true,
4950                                                                        }
4951                                                                    );
4952                                                                } else {
4953                                                                    let is_current_target = this.folded_directory_drag_target
4954                                                                        .is_some_and(|target|
4955                                                                            target.entry_id == entry_id &&
4956                                                                            target.index == delimiter_target_index &&
4957                                                                            target.is_delimiter_target
4958                                                                        );
4959                                                                    if is_current_target {
4960                                                                        this.folded_directory_drag_target = None;
4961                                                                    }
4962                                                                }
4963
4964                                                            },
4965                                                        )))
4966                                                    })
4967                                                    .child(
4968                                                        Label::new(delimiter.clone())
4969                                                            .single_line()
4970                                                            .color(filename_text_color)
4971                                                    )
4972                                                );
4973                                        }
4974                                        let id = SharedString::from(format!(
4975                                            "project_panel_path_component_{}_{index}",
4976                                            entry_id.to_usize()
4977                                        ));
4978                                        let label = div()
4979                                            .id(id)
4980                                            .when(!is_sticky,| div| {
4981                                                div
4982                                                .when(index != components_len - 1, |div|{
4983                                                    let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - index).cloned();
4984                                                    div
4985                                                    .when(settings.drag_and_drop, |div| div
4986                                                    .on_drag_move(cx.listener(
4987                                                        move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4988                                                        if event.bounds.contains(&event.event.position) {
4989                                                                this.folded_directory_drag_target = Some(
4990                                                                    FoldedDirectoryDragTarget {
4991                                                                        entry_id,
4992                                                                        index,
4993                                                                        is_delimiter_target: false,
4994                                                                    }
4995                                                                );
4996                                                            } else {
4997                                                                let is_current_target = this.folded_directory_drag_target
4998                                                                    .as_ref()
4999                                                                    .is_some_and(|target|
5000                                                                        target.entry_id == entry_id &&
5001                                                                        target.index == index &&
5002                                                                        !target.is_delimiter_target
5003                                                                    );
5004                                                                if is_current_target {
5005                                                                    this.folded_directory_drag_target = None;
5006                                                                }
5007                                                            }
5008                                                        },
5009                                                    ))
5010                                                    .on_drop(cx.listener(move |this, selections: &DraggedSelection, window,cx| {
5011                                                        this.hover_scroll_task.take();
5012                                                        this.drag_target_entry = None;
5013                                                        this.folded_directory_drag_target = None;
5014                                                        if let Some(target_entry_id) = target_entry_id {
5015                                                            this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
5016                                                        }
5017                                                    }))
5018                                                    .when(folded_directory_drag_target.is_some_and(|target|
5019                                                        target.entry_id == entry_id &&
5020                                                        target.index == index
5021                                                    ), |this| {
5022                                                        this.bg(item_colors.drag_over)
5023                                                    }))
5024                                                })
5025                                            })
5026                                            .on_mouse_down(
5027                                                MouseButton::Left,
5028                                                cx.listener(move |this, _, _, cx| {
5029                                                    if index != active_index
5030                                                        && let Some(folds) =
5031                                                            this.state.ancestors.get_mut(&entry_id)
5032                                                        {
5033                                                            folds.current_ancestor_depth =
5034                                                                components_len - 1 - index;
5035                                                            cx.notify();
5036                                                        }
5037                                                }),
5038                                            )
5039                                            .child(
5040                                                Label::new(component)
5041                                                    .single_line()
5042                                                    .color(filename_text_color)
5043                                                    .when(
5044                                                        index == active_index
5045                                                            && (is_active || is_marked),
5046                                                        |this| this.underline(),
5047                                                    ),
5048                                            );
5049
5050                                        this = this.child(label);
5051                                    }
5052
5053                                    this
5054                                } else {
5055                                    this.child(
5056                                        Label::new(file_name)
5057                                            .single_line()
5058                                            .color(filename_text_color),
5059                                    )
5060                                }
5061                            })
5062                        },
5063                    )
5064                    .on_secondary_mouse_down(cx.listener(
5065                        move |this, event: &MouseDownEvent, window, cx| {
5066                            // Stop propagation to prevent the catch-all context menu for the project
5067                            // panel from being deployed.
5068                            cx.stop_propagation();
5069                            // Some context menu actions apply to all marked entries. If the user
5070                            // right-clicks on an entry that is not marked, they may not realize the
5071                            // action applies to multiple entries. To avoid inadvertent changes, all
5072                            // entries are unmarked.
5073                            if !this.marked_entries.contains(&selection) {
5074                                this.marked_entries.clear();
5075                            }
5076                            this.deploy_context_menu(event.position, entry_id, window, cx);
5077                        },
5078                    ))
5079                    .overflow_x(),
5080            )
5081            .when_some(
5082                validation_color_and_message,
5083                |this, (color, message)| {
5084                    this
5085                    .relative()
5086                    .child(
5087                        deferred(
5088                            div()
5089                            .occlude()
5090                            .absolute()
5091                            .top_full()
5092                            .left(px(-1.)) // Used px over rem so that it doesn't change with font size
5093                            .right(px(-0.5))
5094                            .py_1()
5095                            .px_2()
5096                            .border_1()
5097                            .border_color(color)
5098                            .bg(cx.theme().colors().background)
5099                            .child(
5100                                Label::new(message)
5101                                .color(Color::from(color))
5102                                .size(LabelSize::Small)
5103                            )
5104                        )
5105                    )
5106                }
5107            )
5108    }
5109
5110    fn details_for_entry(
5111        &self,
5112        entry: &Entry,
5113        worktree_id: WorktreeId,
5114        root_name: &RelPath,
5115        entries_paths: &HashSet<Arc<RelPath>>,
5116        git_status: GitSummary,
5117        sticky: Option<StickyDetails>,
5118        _window: &mut Window,
5119        cx: &mut Context<Self>,
5120    ) -> EntryDetails {
5121        let (show_file_icons, show_folder_icons) = {
5122            let settings = ProjectPanelSettings::get_global(cx);
5123            (settings.file_icons, settings.folder_icons)
5124        };
5125
5126        let expanded_entry_ids = self
5127            .state
5128            .expanded_dir_ids
5129            .get(&worktree_id)
5130            .map(Vec::as_slice)
5131            .unwrap_or(&[]);
5132        let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
5133
5134        let icon = match entry.kind {
5135            EntryKind::File => {
5136                if show_file_icons {
5137                    FileIcons::get_icon(entry.path.as_std_path(), cx)
5138                } else {
5139                    None
5140                }
5141            }
5142            _ => {
5143                if show_folder_icons {
5144                    FileIcons::get_folder_icon(is_expanded, entry.path.as_std_path(), cx)
5145                } else {
5146                    FileIcons::get_chevron_icon(is_expanded, cx)
5147                }
5148            }
5149        };
5150
5151        let path_style = self.project.read(cx).path_style(cx);
5152        let (depth, difference) =
5153            ProjectPanel::calculate_depth_and_difference(entry, entries_paths);
5154
5155        let filename = if difference > 1 {
5156            entry
5157                .path
5158                .last_n_components(difference)
5159                .map_or(String::new(), |suffix| {
5160                    suffix.display(path_style).to_string()
5161                })
5162        } else {
5163            entry
5164                .path
5165                .file_name()
5166                .map(|name| name.to_string())
5167                .unwrap_or_else(|| root_name.as_unix_str().to_string())
5168        };
5169
5170        let selection = SelectedEntry {
5171            worktree_id,
5172            entry_id: entry.id,
5173        };
5174        let is_marked = self.marked_entries.contains(&selection);
5175        let is_selected = self.state.selection == Some(selection);
5176
5177        let diagnostic_severity = self
5178            .diagnostics
5179            .get(&(worktree_id, entry.path.clone()))
5180            .cloned();
5181
5182        let filename_text_color =
5183            entry_git_aware_label_color(git_status, entry.is_ignored, is_marked);
5184
5185        let is_cut = self
5186            .clipboard
5187            .as_ref()
5188            .is_some_and(|e| e.is_cut() && e.items().contains(&selection));
5189
5190        EntryDetails {
5191            filename,
5192            icon,
5193            path: entry.path.clone(),
5194            depth,
5195            kind: entry.kind,
5196            is_ignored: entry.is_ignored,
5197            is_expanded,
5198            is_selected,
5199            is_marked,
5200            is_editing: false,
5201            is_processing: false,
5202            is_cut,
5203            sticky,
5204            filename_text_color,
5205            diagnostic_severity,
5206            git_status,
5207            is_private: entry.is_private,
5208            worktree_id,
5209            canonical_path: entry.canonical_path.clone(),
5210        }
5211    }
5212
5213    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
5214        let mut dispatch_context = KeyContext::new_with_defaults();
5215        dispatch_context.add("ProjectPanel");
5216        dispatch_context.add("menu");
5217
5218        let identifier = if self.filename_editor.focus_handle(cx).is_focused(window) {
5219            "editing"
5220        } else {
5221            "not_editing"
5222        };
5223
5224        dispatch_context.add(identifier);
5225        dispatch_context
5226    }
5227
5228    fn reveal_entry(
5229        &mut self,
5230        project: Entity<Project>,
5231        entry_id: ProjectEntryId,
5232        skip_ignored: bool,
5233        window: &mut Window,
5234        cx: &mut Context<Self>,
5235    ) -> Result<()> {
5236        let worktree = project
5237            .read(cx)
5238            .worktree_for_entry(entry_id, cx)
5239            .context("can't reveal a non-existent entry in the project panel")?;
5240        let worktree = worktree.read(cx);
5241        if skip_ignored
5242            && worktree
5243                .entry_for_id(entry_id)
5244                .is_none_or(|entry| entry.is_ignored && !entry.is_always_included)
5245        {
5246            anyhow::bail!("can't reveal an ignored entry in the project panel");
5247        }
5248        let is_active_item_file_diff_view = self
5249            .workspace
5250            .upgrade()
5251            .and_then(|ws| ws.read(cx).active_item(cx))
5252            .map(|item| item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some())
5253            .unwrap_or(false);
5254        if is_active_item_file_diff_view {
5255            return Ok(());
5256        }
5257
5258        let worktree_id = worktree.id();
5259        self.expand_entry(worktree_id, entry_id, cx);
5260        self.update_visible_entries(Some((worktree_id, entry_id)), false, true, window, cx);
5261        self.marked_entries.clear();
5262        self.marked_entries.push(SelectedEntry {
5263            worktree_id,
5264            entry_id,
5265        });
5266        cx.notify();
5267        Ok(())
5268    }
5269
5270    fn find_active_indent_guide(
5271        &self,
5272        indent_guides: &[IndentGuideLayout],
5273        cx: &App,
5274    ) -> Option<usize> {
5275        let (worktree, entry) = self.selected_entry(cx)?;
5276
5277        // Find the parent entry of the indent guide, this will either be the
5278        // expanded folder we have selected, or the parent of the currently
5279        // selected file/collapsed directory
5280        let mut entry = entry;
5281        loop {
5282            let is_expanded_dir = entry.is_dir()
5283                && self
5284                    .state
5285                    .expanded_dir_ids
5286                    .get(&worktree.id())
5287                    .map(|ids| ids.binary_search(&entry.id).is_ok())
5288                    .unwrap_or(false);
5289            if is_expanded_dir {
5290                break;
5291            }
5292            entry = worktree.entry_for_path(&entry.path.parent()?)?;
5293        }
5294
5295        let (active_indent_range, depth) = {
5296            let (worktree_ix, child_offset, ix) = self.index_for_entry(entry.id, worktree.id())?;
5297            let child_paths = &self.state.visible_entries[worktree_ix].entries;
5298            let mut child_count = 0;
5299            let depth = entry.path.ancestors().count();
5300            while let Some(entry) = child_paths.get(child_offset + child_count + 1) {
5301                if entry.path.ancestors().count() <= depth {
5302                    break;
5303                }
5304                child_count += 1;
5305            }
5306
5307            let start = ix + 1;
5308            let end = start + child_count;
5309
5310            let visible_worktree = &self.state.visible_entries[worktree_ix];
5311            let visible_worktree_entries = visible_worktree.index.get_or_init(|| {
5312                visible_worktree
5313                    .entries
5314                    .iter()
5315                    .map(|e| e.path.clone())
5316                    .collect()
5317            });
5318
5319            // Calculate the actual depth of the entry, taking into account that directories can be auto-folded.
5320            let (depth, _) = Self::calculate_depth_and_difference(entry, visible_worktree_entries);
5321            (start..end, depth)
5322        };
5323
5324        let candidates = indent_guides
5325            .iter()
5326            .enumerate()
5327            .filter(|(_, indent_guide)| indent_guide.offset.x == depth);
5328
5329        for (i, indent) in candidates {
5330            // Find matches that are either an exact match, partially on screen, or inside the enclosing indent
5331            if active_indent_range.start <= indent.offset.y + indent.length
5332                && indent.offset.y <= active_indent_range.end
5333            {
5334                return Some(i);
5335            }
5336        }
5337        None
5338    }
5339
5340    fn render_sticky_entries(
5341        &self,
5342        child: StickyProjectPanelCandidate,
5343        window: &mut Window,
5344        cx: &mut Context<Self>,
5345    ) -> SmallVec<[AnyElement; 8]> {
5346        let project = self.project.read(cx);
5347
5348        let Some((worktree_id, entry_ref)) = self.entry_at_index(child.index) else {
5349            return SmallVec::new();
5350        };
5351
5352        let Some(visible) = self
5353            .state
5354            .visible_entries
5355            .iter()
5356            .find(|worktree| worktree.worktree_id == worktree_id)
5357        else {
5358            return SmallVec::new();
5359        };
5360
5361        let Some(worktree) = project.worktree_for_id(worktree_id, cx) else {
5362            return SmallVec::new();
5363        };
5364        let worktree = worktree.read(cx).snapshot();
5365
5366        let paths = visible
5367            .index
5368            .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
5369
5370        let mut sticky_parents = Vec::new();
5371        let mut current_path = entry_ref.path.clone();
5372
5373        'outer: loop {
5374            if let Some(parent_path) = current_path.parent() {
5375                for ancestor_path in parent_path.ancestors() {
5376                    if paths.contains(ancestor_path)
5377                        && let Some(parent_entry) = worktree.entry_for_path(ancestor_path)
5378                    {
5379                        sticky_parents.push(parent_entry.clone());
5380                        current_path = parent_entry.path.clone();
5381                        continue 'outer;
5382                    }
5383                }
5384            }
5385            break 'outer;
5386        }
5387
5388        if sticky_parents.is_empty() {
5389            return SmallVec::new();
5390        }
5391
5392        sticky_parents.reverse();
5393
5394        let panel_settings = ProjectPanelSettings::get_global(cx);
5395        let git_status_enabled = panel_settings.git_status;
5396        let root_name = worktree.root_name();
5397
5398        let git_summaries_by_id = if git_status_enabled {
5399            visible
5400                .entries
5401                .iter()
5402                .map(|e| (e.id, e.git_summary))
5403                .collect::<HashMap<_, _>>()
5404        } else {
5405            Default::default()
5406        };
5407
5408        // already checked if non empty above
5409        let last_item_index = sticky_parents.len() - 1;
5410        sticky_parents
5411            .iter()
5412            .enumerate()
5413            .map(|(index, entry)| {
5414                let git_status = git_summaries_by_id
5415                    .get(&entry.id)
5416                    .copied()
5417                    .unwrap_or_default();
5418                let sticky_details = Some(StickyDetails {
5419                    sticky_index: index,
5420                });
5421                let details = self.details_for_entry(
5422                    entry,
5423                    worktree_id,
5424                    root_name,
5425                    paths,
5426                    git_status,
5427                    sticky_details,
5428                    window,
5429                    cx,
5430                );
5431                self.render_entry(entry.id, details, window, cx)
5432                    .when(index == last_item_index, |this| {
5433                        let shadow_color_top = hsla(0.0, 0.0, 0.0, 0.1);
5434                        let shadow_color_bottom = hsla(0.0, 0.0, 0.0, 0.);
5435                        let sticky_shadow = div()
5436                            .absolute()
5437                            .left_0()
5438                            .bottom_neg_1p5()
5439                            .h_1p5()
5440                            .w_full()
5441                            .bg(linear_gradient(
5442                                0.,
5443                                linear_color_stop(shadow_color_top, 1.),
5444                                linear_color_stop(shadow_color_bottom, 0.),
5445                            ));
5446                        this.child(sticky_shadow)
5447                    })
5448                    .into_any()
5449            })
5450            .collect()
5451    }
5452}
5453
5454#[derive(Clone)]
5455struct StickyProjectPanelCandidate {
5456    index: usize,
5457    depth: usize,
5458}
5459
5460impl StickyCandidate for StickyProjectPanelCandidate {
5461    fn depth(&self) -> usize {
5462        self.depth
5463    }
5464}
5465
5466fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -> usize {
5467    const ICON_SIZE_FACTOR: usize = 2;
5468    let mut item_width = depth * ICON_SIZE_FACTOR + item_text_chars;
5469    if is_symlink {
5470        item_width += ICON_SIZE_FACTOR;
5471    }
5472    item_width
5473}
5474
5475impl Render for ProjectPanel {
5476    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5477        let has_worktree = !self.state.visible_entries.is_empty();
5478        let project = self.project.read(cx);
5479        let panel_settings = ProjectPanelSettings::get_global(cx);
5480        let indent_size = panel_settings.indent_size;
5481        let show_indent_guides = panel_settings.indent_guides.show == ShowIndentGuides::Always;
5482        let show_sticky_entries = {
5483            if panel_settings.sticky_scroll {
5484                let is_scrollable = self.scroll_handle.is_scrollable();
5485                let is_scrolled = self.scroll_handle.offset().y < px(0.);
5486                is_scrollable && is_scrolled
5487            } else {
5488                false
5489            }
5490        };
5491
5492        let is_local = project.is_local();
5493
5494        if has_worktree {
5495            let item_count = self
5496                .state
5497                .visible_entries
5498                .iter()
5499                .map(|worktree| worktree.entries.len())
5500                .sum();
5501
5502            fn handle_drag_move<T: 'static>(
5503                this: &mut ProjectPanel,
5504                e: &DragMoveEvent<T>,
5505                window: &mut Window,
5506                cx: &mut Context<ProjectPanel>,
5507            ) {
5508                if let Some(previous_position) = this.previous_drag_position {
5509                    // Refresh cursor only when an actual drag happens,
5510                    // because modifiers are not updated when the cursor is not moved.
5511                    if e.event.position != previous_position {
5512                        this.refresh_drag_cursor_style(&e.event.modifiers, window, cx);
5513                    }
5514                }
5515                this.previous_drag_position = Some(e.event.position);
5516
5517                if !e.bounds.contains(&e.event.position) {
5518                    this.drag_target_entry = None;
5519                    return;
5520                }
5521                this.hover_scroll_task.take();
5522                let panel_height = e.bounds.size.height;
5523                if panel_height <= px(0.) {
5524                    return;
5525                }
5526
5527                let event_offset = e.event.position.y - e.bounds.origin.y;
5528                // How far along in the project panel is our cursor? (0. is the top of a list, 1. is the bottom)
5529                let hovered_region_offset = event_offset / panel_height;
5530
5531                // We want the scrolling to be a bit faster when the cursor is closer to the edge of a list.
5532                // These pixels offsets were picked arbitrarily.
5533                let vertical_scroll_offset = if hovered_region_offset <= 0.05 {
5534                    8.
5535                } else if hovered_region_offset <= 0.15 {
5536                    5.
5537                } else if hovered_region_offset >= 0.95 {
5538                    -8.
5539                } else if hovered_region_offset >= 0.85 {
5540                    -5.
5541                } else {
5542                    return;
5543                };
5544                let adjustment = point(px(0.), px(vertical_scroll_offset));
5545                this.hover_scroll_task = Some(cx.spawn_in(window, async move |this, cx| {
5546                    loop {
5547                        let should_stop_scrolling = this
5548                            .update(cx, |this, cx| {
5549                                this.hover_scroll_task.as_ref()?;
5550                                let handle = this.scroll_handle.0.borrow_mut();
5551                                let offset = handle.base_handle.offset();
5552
5553                                handle.base_handle.set_offset(offset + adjustment);
5554                                cx.notify();
5555                                Some(())
5556                            })
5557                            .ok()
5558                            .flatten()
5559                            .is_some();
5560                        if should_stop_scrolling {
5561                            return;
5562                        }
5563                        cx.background_executor()
5564                            .timer(Duration::from_millis(16))
5565                            .await;
5566                    }
5567                }));
5568            }
5569            h_flex()
5570                .id("project-panel")
5571                .group("project-panel")
5572                .when(panel_settings.drag_and_drop, |this| {
5573                    this.on_drag_move(cx.listener(handle_drag_move::<ExternalPaths>))
5574                        .on_drag_move(cx.listener(handle_drag_move::<DraggedSelection>))
5575                })
5576                .size_full()
5577                .relative()
5578                .on_modifiers_changed(cx.listener(
5579                    |this, event: &ModifiersChangedEvent, window, cx| {
5580                        this.refresh_drag_cursor_style(&event.modifiers, window, cx);
5581                    },
5582                ))
5583                .key_context(self.dispatch_context(window, cx))
5584                .on_action(cx.listener(Self::scroll_up))
5585                .on_action(cx.listener(Self::scroll_down))
5586                .on_action(cx.listener(Self::scroll_cursor_center))
5587                .on_action(cx.listener(Self::scroll_cursor_top))
5588                .on_action(cx.listener(Self::scroll_cursor_bottom))
5589                .on_action(cx.listener(Self::select_next))
5590                .on_action(cx.listener(Self::select_previous))
5591                .on_action(cx.listener(Self::select_first))
5592                .on_action(cx.listener(Self::select_last))
5593                .on_action(cx.listener(Self::select_parent))
5594                .on_action(cx.listener(Self::select_next_git_entry))
5595                .on_action(cx.listener(Self::select_prev_git_entry))
5596                .on_action(cx.listener(Self::select_next_diagnostic))
5597                .on_action(cx.listener(Self::select_prev_diagnostic))
5598                .on_action(cx.listener(Self::select_next_directory))
5599                .on_action(cx.listener(Self::select_prev_directory))
5600                .on_action(cx.listener(Self::expand_selected_entry))
5601                .on_action(cx.listener(Self::collapse_selected_entry))
5602                .on_action(cx.listener(Self::collapse_all_entries))
5603                .on_action(cx.listener(Self::open))
5604                .on_action(cx.listener(Self::open_permanent))
5605                .on_action(cx.listener(Self::open_split_vertical))
5606                .on_action(cx.listener(Self::open_split_horizontal))
5607                .on_action(cx.listener(Self::confirm))
5608                .on_action(cx.listener(Self::cancel))
5609                .on_action(cx.listener(Self::copy_path))
5610                .on_action(cx.listener(Self::copy_relative_path))
5611                .on_action(cx.listener(Self::new_search_in_directory))
5612                .on_action(cx.listener(Self::unfold_directory))
5613                .on_action(cx.listener(Self::fold_directory))
5614                .on_action(cx.listener(Self::remove_from_project))
5615                .on_action(cx.listener(Self::compare_marked_files))
5616                .when(!project.is_read_only(cx), |el| {
5617                    el.on_action(cx.listener(Self::new_file))
5618                        .on_action(cx.listener(Self::new_directory))
5619                        .on_action(cx.listener(Self::rename))
5620                        .on_action(cx.listener(Self::delete))
5621                        .on_action(cx.listener(Self::cut))
5622                        .on_action(cx.listener(Self::copy))
5623                        .on_action(cx.listener(Self::paste))
5624                        .on_action(cx.listener(Self::duplicate))
5625                        .when(!project.is_remote(), |el| {
5626                            el.on_action(cx.listener(Self::trash))
5627                        })
5628                })
5629                .when(project.is_local(), |el| {
5630                    el.on_action(cx.listener(Self::reveal_in_finder))
5631                        .on_action(cx.listener(Self::open_system))
5632                        .on_action(cx.listener(Self::open_in_terminal))
5633                })
5634                .when(project.is_via_remote_server(), |el| {
5635                    el.on_action(cx.listener(Self::open_in_terminal))
5636                })
5637                .track_focus(&self.focus_handle(cx))
5638                .child(
5639                    v_flex()
5640                        .child(
5641                            uniform_list("entries", item_count, {
5642                                cx.processor(|this, range: Range<usize>, window, cx| {
5643                                    this.rendered_entries_len = range.end - range.start;
5644                                    let mut items = Vec::with_capacity(this.rendered_entries_len);
5645                                    this.for_each_visible_entry(
5646                                        range,
5647                                        window,
5648                                        cx,
5649                                        |id, details, window, cx| {
5650                                            items.push(this.render_entry(id, details, window, cx));
5651                                        },
5652                                    );
5653                                    items
5654                                })
5655                            })
5656                            .when(show_indent_guides, |list| {
5657                                list.with_decoration(
5658                                    ui::indent_guides(
5659                                        px(indent_size),
5660                                        IndentGuideColors::panel(cx),
5661                                    )
5662                                    .with_compute_indents_fn(
5663                                        cx.entity(),
5664                                        |this, range, window, cx| {
5665                                            let mut items =
5666                                                SmallVec::with_capacity(range.end - range.start);
5667                                            this.iter_visible_entries(
5668                                                range,
5669                                                window,
5670                                                cx,
5671                                                |entry, _, entries, _, _| {
5672                                                    let (depth, _) =
5673                                                        Self::calculate_depth_and_difference(
5674                                                            entry, entries,
5675                                                        );
5676                                                    items.push(depth);
5677                                                },
5678                                            );
5679                                            items
5680                                        },
5681                                    )
5682                                    .on_click(cx.listener(
5683                                        |this,
5684                                         active_indent_guide: &IndentGuideLayout,
5685                                         window,
5686                                         cx| {
5687                                            if window.modifiers().secondary() {
5688                                                let ix = active_indent_guide.offset.y;
5689                                                let Some((target_entry, worktree)) = maybe!({
5690                                                    let (worktree_id, entry) =
5691                                                        this.entry_at_index(ix)?;
5692                                                    let worktree = this
5693                                                        .project
5694                                                        .read(cx)
5695                                                        .worktree_for_id(worktree_id, cx)?;
5696                                                    let target_entry = worktree
5697                                                        .read(cx)
5698                                                        .entry_for_path(&entry.path.parent()?)?;
5699                                                    Some((target_entry, worktree))
5700                                                }) else {
5701                                                    return;
5702                                                };
5703
5704                                                this.collapse_entry(
5705                                                    target_entry.clone(),
5706                                                    worktree,
5707                                                    window,
5708                                                    cx,
5709                                                );
5710                                            }
5711                                        },
5712                                    ))
5713                                    .with_render_fn(
5714                                        cx.entity(),
5715                                        move |this, params, _, cx| {
5716                                            const LEFT_OFFSET: Pixels = px(14.);
5717                                            const PADDING_Y: Pixels = px(4.);
5718                                            const HITBOX_OVERDRAW: Pixels = px(3.);
5719
5720                                            let active_indent_guide_index = this
5721                                                .find_active_indent_guide(
5722                                                    &params.indent_guides,
5723                                                    cx,
5724                                                );
5725
5726                                            let indent_size = params.indent_size;
5727                                            let item_height = params.item_height;
5728
5729                                            params
5730                                                .indent_guides
5731                                                .into_iter()
5732                                                .enumerate()
5733                                                .map(|(idx, layout)| {
5734                                                    let offset = if layout.continues_offscreen {
5735                                                        px(0.)
5736                                                    } else {
5737                                                        PADDING_Y
5738                                                    };
5739                                                    let bounds = Bounds::new(
5740                                                        point(
5741                                                            layout.offset.x * indent_size
5742                                                                + LEFT_OFFSET,
5743                                                            layout.offset.y * item_height + offset,
5744                                                        ),
5745                                                        size(
5746                                                            px(1.),
5747                                                            layout.length * item_height
5748                                                                - offset * 2.,
5749                                                        ),
5750                                                    );
5751                                                    ui::RenderedIndentGuide {
5752                                                        bounds,
5753                                                        layout,
5754                                                        is_active: Some(idx)
5755                                                            == active_indent_guide_index,
5756                                                        hitbox: Some(Bounds::new(
5757                                                            point(
5758                                                                bounds.origin.x - HITBOX_OVERDRAW,
5759                                                                bounds.origin.y,
5760                                                            ),
5761                                                            size(
5762                                                                bounds.size.width
5763                                                                    + HITBOX_OVERDRAW * 2.,
5764                                                                bounds.size.height,
5765                                                            ),
5766                                                        )),
5767                                                    }
5768                                                })
5769                                                .collect()
5770                                        },
5771                                    ),
5772                                )
5773                            })
5774                            .when(show_sticky_entries, |list| {
5775                                let sticky_items = ui::sticky_items(
5776                                    cx.entity(),
5777                                    |this, range, window, cx| {
5778                                        let mut items =
5779                                            SmallVec::with_capacity(range.end - range.start);
5780                                        this.iter_visible_entries(
5781                                            range,
5782                                            window,
5783                                            cx,
5784                                            |entry, index, entries, _, _| {
5785                                                let (depth, _) =
5786                                                    Self::calculate_depth_and_difference(
5787                                                        entry, entries,
5788                                                    );
5789                                                let candidate =
5790                                                    StickyProjectPanelCandidate { index, depth };
5791                                                items.push(candidate);
5792                                            },
5793                                        );
5794                                        items
5795                                    },
5796                                    |this, marker_entry, window, cx| {
5797                                        let sticky_entries =
5798                                            this.render_sticky_entries(marker_entry, window, cx);
5799                                        this.sticky_items_count = sticky_entries.len();
5800                                        sticky_entries
5801                                    },
5802                                );
5803                                list.with_decoration(if show_indent_guides {
5804                                    sticky_items.with_decoration(
5805                                        ui::indent_guides(
5806                                            px(indent_size),
5807                                            IndentGuideColors::panel(cx),
5808                                        )
5809                                        .with_render_fn(
5810                                            cx.entity(),
5811                                            move |_, params, _, _| {
5812                                                const LEFT_OFFSET: Pixels = px(14.);
5813
5814                                                let indent_size = params.indent_size;
5815                                                let item_height = params.item_height;
5816
5817                                                params
5818                                                    .indent_guides
5819                                                    .into_iter()
5820                                                    .map(|layout| {
5821                                                        let bounds = Bounds::new(
5822                                                            point(
5823                                                                layout.offset.x * indent_size
5824                                                                    + LEFT_OFFSET,
5825                                                                layout.offset.y * item_height,
5826                                                            ),
5827                                                            size(
5828                                                                px(1.),
5829                                                                layout.length * item_height,
5830                                                            ),
5831                                                        );
5832                                                        ui::RenderedIndentGuide {
5833                                                            bounds,
5834                                                            layout,
5835                                                            is_active: false,
5836                                                            hitbox: None,
5837                                                        }
5838                                                    })
5839                                                    .collect()
5840                                            },
5841                                        ),
5842                                    )
5843                                } else {
5844                                    sticky_items
5845                                })
5846                            })
5847                            .with_sizing_behavior(ListSizingBehavior::Infer)
5848                            .with_horizontal_sizing_behavior(
5849                                ListHorizontalSizingBehavior::Unconstrained,
5850                            )
5851                            .with_width_from_item(self.state.max_width_item_index)
5852                            .track_scroll(&self.scroll_handle),
5853                        )
5854                        .child(
5855                            div()
5856                                .id("project-panel-blank-area")
5857                                .block_mouse_except_scroll()
5858                                .flex_grow()
5859                                .when(
5860                                    self.drag_target_entry.as_ref().is_some_and(
5861                                        |entry| match entry {
5862                                            DragTarget::Background => true,
5863                                            DragTarget::Entry {
5864                                                highlight_entry_id, ..
5865                                            } => self.state.last_worktree_root_id.is_some_and(
5866                                                |root_id| *highlight_entry_id == root_id,
5867                                            ),
5868                                        },
5869                                    ),
5870                                    |div| div.bg(cx.theme().colors().drop_target_background),
5871                                )
5872                                .on_drag_move::<ExternalPaths>(cx.listener(
5873                                    move |this, event: &DragMoveEvent<ExternalPaths>, _, _| {
5874                                        let Some(_last_root_id) = this.state.last_worktree_root_id
5875                                        else {
5876                                            return;
5877                                        };
5878                                        if event.bounds.contains(&event.event.position) {
5879                                            this.drag_target_entry = Some(DragTarget::Background);
5880                                        } else {
5881                                            if this.drag_target_entry.as_ref().is_some_and(|e| {
5882                                                matches!(e, DragTarget::Background)
5883                                            }) {
5884                                                this.drag_target_entry = None;
5885                                            }
5886                                        }
5887                                    },
5888                                ))
5889                                .on_drag_move::<DraggedSelection>(cx.listener(
5890                                    move |this, event: &DragMoveEvent<DraggedSelection>, _, cx| {
5891                                        let Some(last_root_id) = this.state.last_worktree_root_id
5892                                        else {
5893                                            return;
5894                                        };
5895                                        if event.bounds.contains(&event.event.position) {
5896                                            let drag_state = event.drag(cx);
5897                                            if this.should_highlight_background_for_selection_drag(
5898                                                &drag_state,
5899                                                last_root_id,
5900                                                cx,
5901                                            ) {
5902                                                this.drag_target_entry =
5903                                                    Some(DragTarget::Background);
5904                                            }
5905                                        } else {
5906                                            if this.drag_target_entry.as_ref().is_some_and(|e| {
5907                                                matches!(e, DragTarget::Background)
5908                                            }) {
5909                                                this.drag_target_entry = None;
5910                                            }
5911                                        }
5912                                    },
5913                                ))
5914                                .on_drop(cx.listener(
5915                                    move |this, external_paths: &ExternalPaths, window, cx| {
5916                                        this.drag_target_entry = None;
5917                                        this.hover_scroll_task.take();
5918                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5919                                            this.drop_external_files(
5920                                                external_paths.paths(),
5921                                                entry_id,
5922                                                window,
5923                                                cx,
5924                                            );
5925                                        }
5926                                        cx.stop_propagation();
5927                                    },
5928                                ))
5929                                .on_drop(cx.listener(
5930                                    move |this, selections: &DraggedSelection, window, cx| {
5931                                        this.drag_target_entry = None;
5932                                        this.hover_scroll_task.take();
5933                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5934                                            this.drag_onto(selections, entry_id, false, window, cx);
5935                                        }
5936                                        cx.stop_propagation();
5937                                    },
5938                                ))
5939                                .on_click(cx.listener(|this, event, window, cx| {
5940                                    if matches!(event, gpui::ClickEvent::Keyboard(_)) {
5941                                        return;
5942                                    }
5943                                    cx.stop_propagation();
5944                                    this.state.selection = None;
5945                                    this.marked_entries.clear();
5946                                    this.focus_handle(cx).focus(window);
5947                                }))
5948                                .on_mouse_down(
5949                                    MouseButton::Right,
5950                                    cx.listener(move |this, event: &MouseDownEvent, window, cx| {
5951                                        // When deploying the context menu anywhere below the last project entry,
5952                                        // act as if the user clicked the root of the last worktree.
5953                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5954                                            this.deploy_context_menu(
5955                                                event.position,
5956                                                entry_id,
5957                                                window,
5958                                                cx,
5959                                            );
5960                                        }
5961                                    }),
5962                                )
5963                                .when(!project.is_read_only(cx), |el| {
5964                                    el.on_click(cx.listener(
5965                                        |this, event: &gpui::ClickEvent, window, cx| {
5966                                            if event.click_count() > 1
5967                                                && let Some(entry_id) =
5968                                                    this.state.last_worktree_root_id
5969                                            {
5970                                                let project = this.project.read(cx);
5971
5972                                                let worktree_id = if let Some(worktree) =
5973                                                    project.worktree_for_entry(entry_id, cx)
5974                                                {
5975                                                    worktree.read(cx).id()
5976                                                } else {
5977                                                    return;
5978                                                };
5979
5980                                                this.state.selection = Some(SelectedEntry {
5981                                                    worktree_id,
5982                                                    entry_id,
5983                                                });
5984
5985                                                this.new_file(&NewFile, window, cx);
5986                                            }
5987                                        },
5988                                    ))
5989                                }),
5990                        )
5991                        .size_full(),
5992                )
5993                .custom_scrollbars(
5994                    Scrollbars::for_settings::<ProjectPanelSettings>()
5995                        .tracked_scroll_handle(&self.scroll_handle)
5996                        .with_track_along(
5997                            ScrollAxes::Horizontal,
5998                            cx.theme().colors().panel_background,
5999                        )
6000                        .notify_content(),
6001                    window,
6002                    cx,
6003                )
6004                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
6005                    deferred(
6006                        anchored()
6007                            .position(*position)
6008                            .anchor(gpui::Corner::TopLeft)
6009                            .child(menu.clone()),
6010                    )
6011                    .with_priority(3)
6012                }))
6013        } else {
6014            let focus_handle = self.focus_handle(cx);
6015
6016            v_flex()
6017                .id("empty-project_panel")
6018                .p_4()
6019                .size_full()
6020                .items_center()
6021                .justify_center()
6022                .gap_1()
6023                .track_focus(&self.focus_handle(cx))
6024                .child(
6025                    Button::new("open_project", "Open Project")
6026                        .full_width()
6027                        .key_binding(KeyBinding::for_action_in(
6028                            &workspace::Open,
6029                            &focus_handle,
6030                            cx,
6031                        ))
6032                        .on_click(cx.listener(|this, _, window, cx| {
6033                            this.workspace
6034                                .update(cx, |_, cx| {
6035                                    window.dispatch_action(workspace::Open.boxed_clone(), cx);
6036                                })
6037                                .log_err();
6038                        })),
6039                )
6040                .child(
6041                    h_flex()
6042                        .w_1_2()
6043                        .gap_2()
6044                        .child(Divider::horizontal())
6045                        .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
6046                        .child(Divider::horizontal()),
6047                )
6048                .child(
6049                    Button::new("clone_repo", "Clone Repository")
6050                        .full_width()
6051                        .on_click(cx.listener(|this, _, window, cx| {
6052                            this.workspace
6053                                .update(cx, |_, cx| {
6054                                    window.dispatch_action(git::Clone.boxed_clone(), cx);
6055                                })
6056                                .log_err();
6057                        })),
6058                )
6059                .when(is_local, |div| {
6060                    div.when(panel_settings.drag_and_drop, |div| {
6061                        div.drag_over::<ExternalPaths>(|style, _, _, cx| {
6062                            style.bg(cx.theme().colors().drop_target_background)
6063                        })
6064                        .on_drop(cx.listener(
6065                            move |this, external_paths: &ExternalPaths, window, cx| {
6066                                this.drag_target_entry = None;
6067                                this.hover_scroll_task.take();
6068                                if let Some(task) = this
6069                                    .workspace
6070                                    .update(cx, |workspace, cx| {
6071                                        workspace.open_workspace_for_paths(
6072                                            true,
6073                                            external_paths.paths().to_owned(),
6074                                            window,
6075                                            cx,
6076                                        )
6077                                    })
6078                                    .log_err()
6079                                {
6080                                    task.detach_and_log_err(cx);
6081                                }
6082                                cx.stop_propagation();
6083                            },
6084                        ))
6085                    })
6086                })
6087        }
6088    }
6089}
6090
6091impl Render for DraggedProjectEntryView {
6092    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6093        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
6094        h_flex()
6095            .font(ui_font)
6096            .pl(self.click_offset.x + px(12.))
6097            .pt(self.click_offset.y + px(12.))
6098            .child(
6099                div()
6100                    .flex()
6101                    .gap_1()
6102                    .items_center()
6103                    .py_1()
6104                    .px_2()
6105                    .rounded_lg()
6106                    .bg(cx.theme().colors().background)
6107                    .map(|this| {
6108                        if self.selections.len() > 1 && self.selections.contains(&self.selection) {
6109                            this.child(Label::new(format!("{} entries", self.selections.len())))
6110                        } else {
6111                            this.child(if let Some(icon) = &self.icon {
6112                                div().child(Icon::from_path(icon.clone()))
6113                            } else {
6114                                div()
6115                            })
6116                            .child(Label::new(self.filename.clone()))
6117                        }
6118                    }),
6119            )
6120    }
6121}
6122
6123impl EventEmitter<Event> for ProjectPanel {}
6124
6125impl EventEmitter<PanelEvent> for ProjectPanel {}
6126
6127impl Panel for ProjectPanel {
6128    fn position(&self, _: &Window, cx: &App) -> DockPosition {
6129        match ProjectPanelSettings::get_global(cx).dock {
6130            DockSide::Left => DockPosition::Left,
6131            DockSide::Right => DockPosition::Right,
6132        }
6133    }
6134
6135    fn position_is_valid(&self, position: DockPosition) -> bool {
6136        matches!(position, DockPosition::Left | DockPosition::Right)
6137    }
6138
6139    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
6140        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
6141            let dock = match position {
6142                DockPosition::Left | DockPosition::Bottom => DockSide::Left,
6143                DockPosition::Right => DockSide::Right,
6144            };
6145            settings.project_panel.get_or_insert_default().dock = Some(dock);
6146        });
6147    }
6148
6149    fn size(&self, _: &Window, cx: &App) -> Pixels {
6150        self.width
6151            .unwrap_or_else(|| ProjectPanelSettings::get_global(cx).default_width)
6152    }
6153
6154    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
6155        self.width = size;
6156        cx.notify();
6157        cx.defer_in(window, |this, _, cx| {
6158            this.serialize(cx);
6159        });
6160    }
6161
6162    fn icon(&self, _: &Window, cx: &App) -> Option<IconName> {
6163        ProjectPanelSettings::get_global(cx)
6164            .button
6165            .then_some(IconName::FileTree)
6166    }
6167
6168    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
6169        Some("Project Panel")
6170    }
6171
6172    fn toggle_action(&self) -> Box<dyn Action> {
6173        Box::new(ToggleFocus)
6174    }
6175
6176    fn persistent_name() -> &'static str {
6177        "Project Panel"
6178    }
6179
6180    fn panel_key() -> &'static str {
6181        PROJECT_PANEL_KEY
6182    }
6183
6184    fn starts_open(&self, _: &Window, cx: &App) -> bool {
6185        if !ProjectPanelSettings::get_global(cx).starts_open {
6186            return false;
6187        }
6188
6189        let project = &self.project.read(cx);
6190        project.visible_worktrees(cx).any(|tree| {
6191            tree.read(cx)
6192                .root_entry()
6193                .is_some_and(|entry| entry.is_dir())
6194        })
6195    }
6196
6197    fn activation_priority(&self) -> u32 {
6198        0
6199    }
6200}
6201
6202impl Focusable for ProjectPanel {
6203    fn focus_handle(&self, _cx: &App) -> FocusHandle {
6204        self.focus_handle.clone()
6205    }
6206}
6207
6208impl ClipboardEntry {
6209    fn is_cut(&self) -> bool {
6210        matches!(self, Self::Cut { .. })
6211    }
6212
6213    fn items(&self) -> &BTreeSet<SelectedEntry> {
6214        match self {
6215            ClipboardEntry::Copied(entries) | ClipboardEntry::Cut(entries) => entries,
6216        }
6217    }
6218
6219    fn into_copy_entry(self) -> Self {
6220        match self {
6221            ClipboardEntry::Copied(_) => self,
6222            ClipboardEntry::Cut(entries) => ClipboardEntry::Copied(entries),
6223        }
6224    }
6225}
6226
6227#[inline]
6228fn cmp_directories_first(a: &Entry, b: &Entry) -> cmp::Ordering {
6229    util::paths::compare_rel_paths((&a.path, a.is_file()), (&b.path, b.is_file()))
6230}
6231
6232#[inline]
6233fn cmp_mixed(a: &Entry, b: &Entry) -> cmp::Ordering {
6234    util::paths::compare_rel_paths_mixed((&a.path, a.is_file()), (&b.path, b.is_file()))
6235}
6236
6237#[inline]
6238fn cmp_files_first(a: &Entry, b: &Entry) -> cmp::Ordering {
6239    util::paths::compare_rel_paths_files_first((&a.path, a.is_file()), (&b.path, b.is_file()))
6240}
6241
6242#[inline]
6243fn cmp_with_mode(a: &Entry, b: &Entry, mode: &settings::ProjectPanelSortMode) -> cmp::Ordering {
6244    match mode {
6245        settings::ProjectPanelSortMode::DirectoriesFirst => cmp_directories_first(a, b),
6246        settings::ProjectPanelSortMode::Mixed => cmp_mixed(a, b),
6247        settings::ProjectPanelSortMode::FilesFirst => cmp_files_first(a, b),
6248    }
6249}
6250
6251pub fn sort_worktree_entries_with_mode(
6252    entries: &mut [impl AsRef<Entry>],
6253    mode: settings::ProjectPanelSortMode,
6254) {
6255    entries.sort_by(|lhs, rhs| cmp_with_mode(lhs.as_ref(), rhs.as_ref(), &mode));
6256}
6257
6258pub fn par_sort_worktree_entries_with_mode(
6259    entries: &mut Vec<GitEntry>,
6260    mode: settings::ProjectPanelSortMode,
6261) {
6262    entries.par_sort_by(|lhs, rhs| cmp_with_mode(lhs, rhs, &mode));
6263}
6264
6265#[cfg(test)]
6266mod project_panel_tests;