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