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                                    continue;
3489                                };
3490                                let depth = 0;
3491                                (depth, path_name.to_string_lossy().chars().count())
3492                            } else if entry.is_file() {
3493                                let Some(path_name) = entry
3494                                    .path
3495                                    .file_name()
3496                                    .with_context(|| {
3497                                        format!("Non-root entry has no file name: {entry:?}")
3498                                    })
3499                                    .log_err()
3500                                else {
3501                                    continue;
3502                                };
3503                                let depth = entry.path.ancestors().count() - 1;
3504                                (depth, path_name.chars().count())
3505                            } else {
3506                                let path = new_state
3507                                    .ancestors
3508                                    .get(&entry.id)
3509                                    .and_then(|ancestors| {
3510                                        let outermost_ancestor = ancestors.ancestors.last()?;
3511                                        let root_folded_entry = worktree_snapshot
3512                                            .entry_for_id(*outermost_ancestor)?
3513                                            .path
3514                                            .as_ref();
3515                                        entry.path.strip_prefix(root_folded_entry).ok().and_then(
3516                                            |suffix| {
3517                                                Some(
3518                                                    RelPath::unix(root_folded_entry.file_name()?)
3519                                                        .unwrap()
3520                                                        .join(suffix),
3521                                                )
3522                                            },
3523                                        )
3524                                    })
3525                                    .or_else(|| {
3526                                        entry.path.file_name().map(|file_name| {
3527                                            RelPath::unix(file_name).unwrap().into()
3528                                        })
3529                                    })
3530                                    .unwrap_or_else(|| entry.path.clone());
3531                                let depth = path.components().count();
3532                                (depth, path.as_unix_str().chars().count())
3533                            };
3534                            let width_estimate =
3535                                item_width_estimate(depth, chars, entry.canonical_path.is_some());
3536
3537                            match max_width_item.as_mut() {
3538                                Some((id, worktree_id, width)) => {
3539                                    if *width < width_estimate {
3540                                        *id = entry.id;
3541                                        *worktree_id = worktree_snapshot.id();
3542                                        *width = width_estimate;
3543                                    }
3544                                }
3545                                None => {
3546                                    max_width_item =
3547                                        Some((entry.id, worktree_snapshot.id(), width_estimate))
3548                                }
3549                            }
3550
3551                            if expanded_dir_ids.binary_search(&entry.id).is_err()
3552                                && entry_iter.advance_to_sibling()
3553                            {
3554                                continue;
3555                            }
3556                            entry_iter.advance();
3557                        }
3558
3559                        par_sort_worktree_entries_with_mode(
3560                            &mut visible_worktree_entries,
3561                            sort_mode,
3562                        );
3563                        new_state.visible_entries.push(VisibleEntriesForWorktree {
3564                            worktree_id,
3565                            entries: visible_worktree_entries,
3566                            index: OnceCell::new(),
3567                        })
3568                    }
3569                    if let Some((project_entry_id, worktree_id, _)) = max_width_item {
3570                        let mut visited_worktrees_length = 0;
3571                        let index = new_state
3572                            .visible_entries
3573                            .iter()
3574                            .find_map(|visible_entries| {
3575                                if worktree_id == visible_entries.worktree_id {
3576                                    visible_entries
3577                                        .entries
3578                                        .iter()
3579                                        .position(|entry| entry.id == project_entry_id)
3580                                } else {
3581                                    visited_worktrees_length += visible_entries.entries.len();
3582                                    None
3583                                }
3584                            });
3585                        if let Some(index) = index {
3586                            new_state.max_width_item_index = Some(visited_worktrees_length + index);
3587                        }
3588                    }
3589                    new_state
3590                })
3591                .await;
3592            this.update_in(cx, |this, window, cx| {
3593                let current_selection = this.state.selection;
3594                this.state = new_state;
3595                if let Some((worktree_id, entry_id)) = new_selected_entry {
3596                    this.state.selection = Some(SelectedEntry {
3597                        worktree_id,
3598                        entry_id,
3599                    });
3600                } else {
3601                    this.state.selection = current_selection;
3602                }
3603                let elapsed = now.elapsed();
3604                if this.last_reported_update.elapsed() > Duration::from_secs(3600) {
3605                    telemetry::event!(
3606                        "Project Panel Updated",
3607                        elapsed_ms = elapsed.as_millis() as u64,
3608                        worktree_entries = this
3609                            .state
3610                            .visible_entries
3611                            .iter()
3612                            .map(|worktree| worktree.entries.len())
3613                            .sum::<usize>(),
3614                    )
3615                }
3616                if this.update_visible_entries_task.focus_filename_editor {
3617                    this.update_visible_entries_task.focus_filename_editor = false;
3618                    this.filename_editor.update(cx, |editor, cx| {
3619                        window.focus(&editor.focus_handle(cx));
3620                    });
3621                }
3622                if this.update_visible_entries_task.autoscroll {
3623                    this.update_visible_entries_task.autoscroll = false;
3624                    this.autoscroll(cx);
3625                }
3626                cx.notify();
3627            })
3628            .ok();
3629        });
3630
3631        self.update_visible_entries_task = UpdateVisibleEntriesTask {
3632            _visible_entries_task: visible_entries_task,
3633            focus_filename_editor: focus_filename_editor
3634                || self.update_visible_entries_task.focus_filename_editor,
3635            autoscroll: autoscroll || self.update_visible_entries_task.autoscroll,
3636        };
3637    }
3638
3639    fn expand_entry(
3640        &mut self,
3641        worktree_id: WorktreeId,
3642        entry_id: ProjectEntryId,
3643        cx: &mut Context<Self>,
3644    ) {
3645        self.project.update(cx, |project, cx| {
3646            if let Some((worktree, expanded_dir_ids)) = project
3647                .worktree_for_id(worktree_id, cx)
3648                .zip(self.state.expanded_dir_ids.get_mut(&worktree_id))
3649            {
3650                project.expand_entry(worktree_id, entry_id, cx);
3651                let worktree = worktree.read(cx);
3652
3653                if let Some(mut entry) = worktree.entry_for_id(entry_id) {
3654                    loop {
3655                        if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
3656                            expanded_dir_ids.insert(ix, entry.id);
3657                        }
3658
3659                        if let Some(parent_entry) =
3660                            entry.path.parent().and_then(|p| worktree.entry_for_path(p))
3661                        {
3662                            entry = parent_entry;
3663                        } else {
3664                            break;
3665                        }
3666                    }
3667                }
3668            }
3669        });
3670    }
3671
3672    fn drop_external_files(
3673        &mut self,
3674        paths: &[PathBuf],
3675        entry_id: ProjectEntryId,
3676        window: &mut Window,
3677        cx: &mut Context<Self>,
3678    ) {
3679        let mut paths: Vec<Arc<Path>> = paths.iter().map(|path| Arc::from(path.clone())).collect();
3680
3681        let open_file_after_drop = paths.len() == 1 && paths[0].is_file();
3682
3683        let Some((target_directory, worktree, fs)) = maybe!({
3684            let project = self.project.read(cx);
3685            let fs = project.fs().clone();
3686            let worktree = project.worktree_for_entry(entry_id, cx)?;
3687            let entry = worktree.read(cx).entry_for_id(entry_id)?;
3688            let path = entry.path.clone();
3689            let target_directory = if entry.is_dir() {
3690                path
3691            } else {
3692                path.parent()?.into()
3693            };
3694            Some((target_directory, worktree, fs))
3695        }) else {
3696            return;
3697        };
3698
3699        let mut paths_to_replace = Vec::new();
3700        for path in &paths {
3701            if let Some(name) = path.file_name()
3702                && let Some(name) = name.to_str()
3703            {
3704                let target_path = target_directory.join(RelPath::unix(name).unwrap());
3705                if worktree.read(cx).entry_for_path(&target_path).is_some() {
3706                    paths_to_replace.push((name.to_string(), path.clone()));
3707                }
3708            }
3709        }
3710
3711        cx.spawn_in(window, async move |this, cx| {
3712            async move {
3713                for (filename, original_path) in &paths_to_replace {
3714                    let prompt_message = format!(
3715                        concat!(
3716                            "A file or folder with name {} ",
3717                            "already exists in the destination folder. ",
3718                            "Do you want to replace it?"
3719                        ),
3720                        filename
3721                    );
3722                    let answer = cx
3723                        .update(|window, cx| {
3724                            window.prompt(
3725                                PromptLevel::Info,
3726                                &prompt_message,
3727                                None,
3728                                &["Replace", "Cancel"],
3729                                cx,
3730                            )
3731                        })?
3732                        .await?;
3733
3734                    if answer == 1
3735                        && let Some(item_idx) = paths.iter().position(|p| p == original_path)
3736                    {
3737                        paths.remove(item_idx);
3738                    }
3739                }
3740
3741                if paths.is_empty() {
3742                    return Ok(());
3743                }
3744
3745                let task = worktree.update(cx, |worktree, cx| {
3746                    worktree.copy_external_entries(target_directory, paths, fs, cx)
3747                })?;
3748
3749                let opened_entries = task
3750                    .await
3751                    .with_context(|| "failed to copy external paths")?;
3752                this.update(cx, |this, cx| {
3753                    if open_file_after_drop && !opened_entries.is_empty() {
3754                        let settings = ProjectPanelSettings::get_global(cx);
3755                        if settings.auto_open.should_open_on_drop() {
3756                            this.open_entry(opened_entries[0], true, false, cx);
3757                        }
3758                    }
3759                })
3760            }
3761            .log_err()
3762            .await
3763        })
3764        .detach();
3765    }
3766
3767    fn refresh_drag_cursor_style(
3768        &self,
3769        modifiers: &Modifiers,
3770        window: &mut Window,
3771        cx: &mut Context<Self>,
3772    ) {
3773        if let Some(existing_cursor) = cx.active_drag_cursor_style() {
3774            let new_cursor = if Self::is_copy_modifier_set(modifiers) {
3775                CursorStyle::DragCopy
3776            } else {
3777                CursorStyle::PointingHand
3778            };
3779            if existing_cursor != new_cursor {
3780                cx.set_active_drag_cursor_style(new_cursor, window);
3781            }
3782        }
3783    }
3784
3785    fn is_copy_modifier_set(modifiers: &Modifiers) -> bool {
3786        cfg!(target_os = "macos") && modifiers.alt
3787            || cfg!(not(target_os = "macos")) && modifiers.control
3788    }
3789
3790    fn drag_onto(
3791        &mut self,
3792        selections: &DraggedSelection,
3793        target_entry_id: ProjectEntryId,
3794        is_file: bool,
3795        window: &mut Window,
3796        cx: &mut Context<Self>,
3797    ) {
3798        if Self::is_copy_modifier_set(&window.modifiers()) {
3799            let _ = maybe!({
3800                let project = self.project.read(cx);
3801                let target_worktree = project.worktree_for_entry(target_entry_id, cx)?;
3802                let worktree_id = target_worktree.read(cx).id();
3803                let target_entry = target_worktree
3804                    .read(cx)
3805                    .entry_for_id(target_entry_id)?
3806                    .clone();
3807
3808                let mut copy_tasks = Vec::new();
3809                let mut disambiguation_range = None;
3810                for selection in selections.items() {
3811                    let (new_path, new_disambiguation_range) = self.create_paste_path(
3812                        selection,
3813                        (target_worktree.clone(), &target_entry),
3814                        cx,
3815                    )?;
3816
3817                    let task = self.project.update(cx, |project, cx| {
3818                        project.copy_entry(selection.entry_id, (worktree_id, new_path).into(), cx)
3819                    });
3820                    copy_tasks.push(task);
3821                    disambiguation_range = new_disambiguation_range.or(disambiguation_range);
3822                }
3823
3824                let item_count = copy_tasks.len();
3825
3826                cx.spawn_in(window, async move |project_panel, cx| {
3827                    let mut last_succeed = None;
3828                    for task in copy_tasks.into_iter() {
3829                        if let Some(Some(entry)) = task.await.log_err() {
3830                            last_succeed = Some(entry.id);
3831                        }
3832                    }
3833                    // update selection
3834                    if let Some(entry_id) = last_succeed {
3835                        project_panel
3836                            .update_in(cx, |project_panel, window, cx| {
3837                                project_panel.state.selection = Some(SelectedEntry {
3838                                    worktree_id,
3839                                    entry_id,
3840                                });
3841
3842                                // if only one entry was dragged and it was disambiguated, open the rename editor
3843                                if item_count == 1 && disambiguation_range.is_some() {
3844                                    project_panel.rename_impl(disambiguation_range, window, cx);
3845                                }
3846                            })
3847                            .ok();
3848                    }
3849                })
3850                .detach();
3851                Some(())
3852            });
3853        } else {
3854            for selection in selections.items() {
3855                self.move_entry(selection.entry_id, target_entry_id, is_file, cx);
3856            }
3857        }
3858    }
3859
3860    fn index_for_entry(
3861        &self,
3862        entry_id: ProjectEntryId,
3863        worktree_id: WorktreeId,
3864    ) -> Option<(usize, usize, usize)> {
3865        let mut total_ix = 0;
3866        for (worktree_ix, visible) in self.state.visible_entries.iter().enumerate() {
3867            if worktree_id != visible.worktree_id {
3868                total_ix += visible.entries.len();
3869                continue;
3870            }
3871
3872            return visible
3873                .entries
3874                .iter()
3875                .enumerate()
3876                .find(|(_, entry)| entry.id == entry_id)
3877                .map(|(ix, _)| (worktree_ix, ix, total_ix + ix));
3878        }
3879        None
3880    }
3881
3882    fn entry_at_index(&self, index: usize) -> Option<(WorktreeId, GitEntryRef<'_>)> {
3883        let mut offset = 0;
3884        for worktree in &self.state.visible_entries {
3885            let current_len = worktree.entries.len();
3886            if index < offset + current_len {
3887                return worktree
3888                    .entries
3889                    .get(index - offset)
3890                    .map(|entry| (worktree.worktree_id, entry.to_ref()));
3891            }
3892            offset += current_len;
3893        }
3894        None
3895    }
3896
3897    fn iter_visible_entries(
3898        &self,
3899        range: Range<usize>,
3900        window: &mut Window,
3901        cx: &mut Context<ProjectPanel>,
3902        mut callback: impl FnMut(
3903            &Entry,
3904            usize,
3905            &HashSet<Arc<RelPath>>,
3906            &mut Window,
3907            &mut Context<ProjectPanel>,
3908        ),
3909    ) {
3910        let mut ix = 0;
3911        for visible in &self.state.visible_entries {
3912            if ix >= range.end {
3913                return;
3914            }
3915
3916            if ix + visible.entries.len() <= range.start {
3917                ix += visible.entries.len();
3918                continue;
3919            }
3920
3921            let end_ix = range.end.min(ix + visible.entries.len());
3922            let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3923            let entries = visible
3924                .index
3925                .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
3926            let base_index = ix + entry_range.start;
3927            for (i, entry) in visible.entries[entry_range].iter().enumerate() {
3928                let global_index = base_index + i;
3929                callback(entry, global_index, entries, window, cx);
3930            }
3931            ix = end_ix;
3932        }
3933    }
3934
3935    fn for_each_visible_entry(
3936        &self,
3937        range: Range<usize>,
3938        window: &mut Window,
3939        cx: &mut Context<ProjectPanel>,
3940        mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut Window, &mut Context<ProjectPanel>),
3941    ) {
3942        let mut ix = 0;
3943        for visible in &self.state.visible_entries {
3944            if ix >= range.end {
3945                return;
3946            }
3947
3948            if ix + visible.entries.len() <= range.start {
3949                ix += visible.entries.len();
3950                continue;
3951            }
3952
3953            let end_ix = range.end.min(ix + visible.entries.len());
3954            let git_status_setting = {
3955                let settings = ProjectPanelSettings::get_global(cx);
3956                settings.git_status
3957            };
3958            if let Some(worktree) = self
3959                .project
3960                .read(cx)
3961                .worktree_for_id(visible.worktree_id, cx)
3962            {
3963                let snapshot = worktree.read(cx).snapshot();
3964                let root_name = snapshot.root_name();
3965
3966                let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3967                let entries = visible
3968                    .index
3969                    .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
3970                for entry in visible.entries[entry_range].iter() {
3971                    let status = git_status_setting
3972                        .then_some(entry.git_summary)
3973                        .unwrap_or_default();
3974
3975                    let mut details = self.details_for_entry(
3976                        entry,
3977                        visible.worktree_id,
3978                        root_name,
3979                        entries,
3980                        status,
3981                        None,
3982                        window,
3983                        cx,
3984                    );
3985
3986                    if let Some(edit_state) = &self.state.edit_state {
3987                        let is_edited_entry = if edit_state.is_new_entry() {
3988                            entry.id == NEW_ENTRY_ID
3989                        } else {
3990                            entry.id == edit_state.entry_id
3991                                || self.state.ancestors.get(&entry.id).is_some_and(
3992                                    |auto_folded_dirs| {
3993                                        auto_folded_dirs.ancestors.contains(&edit_state.entry_id)
3994                                    },
3995                                )
3996                        };
3997
3998                        if is_edited_entry {
3999                            if let Some(processing_filename) = &edit_state.processing_filename {
4000                                details.is_processing = true;
4001                                if let Some(ancestors) = edit_state
4002                                    .leaf_entry_id
4003                                    .and_then(|entry| self.state.ancestors.get(&entry))
4004                                {
4005                                    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;
4006                                    let all_components = ancestors.ancestors.len();
4007
4008                                    let prefix_components = all_components - position;
4009                                    let suffix_components = position.checked_sub(1);
4010                                    let mut previous_components =
4011                                        Path::new(&details.filename).components();
4012                                    let mut new_path = previous_components
4013                                        .by_ref()
4014                                        .take(prefix_components)
4015                                        .collect::<PathBuf>();
4016                                    if let Some(last_component) =
4017                                        processing_filename.components().next_back()
4018                                    {
4019                                        new_path.push(last_component);
4020                                        previous_components.next();
4021                                    }
4022
4023                                    if suffix_components.is_some() {
4024                                        new_path.push(previous_components);
4025                                    }
4026                                    if let Some(str) = new_path.to_str() {
4027                                        details.filename.clear();
4028                                        details.filename.push_str(str);
4029                                    }
4030                                } else {
4031                                    details.filename.clear();
4032                                    details.filename.push_str(processing_filename.as_unix_str());
4033                                }
4034                            } else {
4035                                if edit_state.is_new_entry() {
4036                                    details.filename.clear();
4037                                }
4038                                details.is_editing = true;
4039                            }
4040                        }
4041                    }
4042
4043                    callback(entry.id, details, window, cx);
4044                }
4045            }
4046            ix = end_ix;
4047        }
4048    }
4049
4050    fn find_entry_in_worktree(
4051        &self,
4052        worktree_id: WorktreeId,
4053        reverse_search: bool,
4054        only_visible_entries: bool,
4055        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4056        cx: &mut Context<Self>,
4057    ) -> Option<GitEntry> {
4058        if only_visible_entries {
4059            let entries = self
4060                .state
4061                .visible_entries
4062                .iter()
4063                .find_map(|visible| {
4064                    if worktree_id == visible.worktree_id {
4065                        Some(&visible.entries)
4066                    } else {
4067                        None
4068                    }
4069                })?
4070                .clone();
4071
4072            return utils::ReversibleIterable::new(entries.iter(), reverse_search)
4073                .find(|ele| predicate(ele.to_ref(), worktree_id))
4074                .cloned();
4075        }
4076
4077        let repo_snapshots = self
4078            .project
4079            .read(cx)
4080            .git_store()
4081            .read(cx)
4082            .repo_snapshots(cx);
4083        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4084        worktree.read_with(cx, |tree, _| {
4085            utils::ReversibleIterable::new(
4086                GitTraversal::new(&repo_snapshots, tree.entries(true, 0usize)),
4087                reverse_search,
4088            )
4089            .find_single_ended(|ele| predicate(*ele, worktree_id))
4090            .map(|ele| ele.to_owned())
4091        })
4092    }
4093
4094    fn find_entry(
4095        &self,
4096        start: Option<&SelectedEntry>,
4097        reverse_search: bool,
4098        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4099        cx: &mut Context<Self>,
4100    ) -> Option<SelectedEntry> {
4101        let mut worktree_ids: Vec<_> = self
4102            .state
4103            .visible_entries
4104            .iter()
4105            .map(|worktree| worktree.worktree_id)
4106            .collect();
4107        let repo_snapshots = self
4108            .project
4109            .read(cx)
4110            .git_store()
4111            .read(cx)
4112            .repo_snapshots(cx);
4113
4114        let mut last_found: Option<SelectedEntry> = None;
4115
4116        if let Some(start) = start {
4117            let worktree = self
4118                .project
4119                .read(cx)
4120                .worktree_for_id(start.worktree_id, cx)?
4121                .read(cx);
4122
4123            let search = {
4124                let entry = worktree.entry_for_id(start.entry_id)?;
4125                let root_entry = worktree.root_entry()?;
4126                let tree_id = worktree.id();
4127
4128                let mut first_iter = GitTraversal::new(
4129                    &repo_snapshots,
4130                    worktree.traverse_from_path(true, true, true, entry.path.as_ref()),
4131                );
4132
4133                if reverse_search {
4134                    first_iter.next();
4135                }
4136
4137                let first = first_iter
4138                    .enumerate()
4139                    .take_until(|(count, entry)| entry.entry == root_entry && *count != 0usize)
4140                    .map(|(_, entry)| entry)
4141                    .find(|ele| predicate(*ele, tree_id))
4142                    .map(|ele| ele.to_owned());
4143
4144                let second_iter =
4145                    GitTraversal::new(&repo_snapshots, worktree.entries(true, 0usize));
4146
4147                let second = if reverse_search {
4148                    second_iter
4149                        .take_until(|ele| ele.id == start.entry_id)
4150                        .filter(|ele| predicate(*ele, tree_id))
4151                        .last()
4152                        .map(|ele| ele.to_owned())
4153                } else {
4154                    second_iter
4155                        .take_while(|ele| ele.id != start.entry_id)
4156                        .filter(|ele| predicate(*ele, tree_id))
4157                        .last()
4158                        .map(|ele| ele.to_owned())
4159                };
4160
4161                if reverse_search {
4162                    Some((second, first))
4163                } else {
4164                    Some((first, second))
4165                }
4166            };
4167
4168            if let Some((first, second)) = search {
4169                let first = first.map(|entry| SelectedEntry {
4170                    worktree_id: start.worktree_id,
4171                    entry_id: entry.id,
4172                });
4173
4174                let second = second.map(|entry| SelectedEntry {
4175                    worktree_id: start.worktree_id,
4176                    entry_id: entry.id,
4177                });
4178
4179                if first.is_some() {
4180                    return first;
4181                }
4182                last_found = second;
4183
4184                let idx = worktree_ids
4185                    .iter()
4186                    .enumerate()
4187                    .find(|(_, ele)| **ele == start.worktree_id)
4188                    .map(|(idx, _)| idx);
4189
4190                if let Some(idx) = idx {
4191                    worktree_ids.rotate_left(idx + 1usize);
4192                    worktree_ids.pop();
4193                }
4194            }
4195        }
4196
4197        for tree_id in worktree_ids.into_iter() {
4198            if let Some(found) =
4199                self.find_entry_in_worktree(tree_id, reverse_search, false, &predicate, cx)
4200            {
4201                return Some(SelectedEntry {
4202                    worktree_id: tree_id,
4203                    entry_id: found.id,
4204                });
4205            }
4206        }
4207
4208        last_found
4209    }
4210
4211    fn find_visible_entry(
4212        &self,
4213        start: Option<&SelectedEntry>,
4214        reverse_search: bool,
4215        predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
4216        cx: &mut Context<Self>,
4217    ) -> Option<SelectedEntry> {
4218        let mut worktree_ids: Vec<_> = self
4219            .state
4220            .visible_entries
4221            .iter()
4222            .map(|worktree| worktree.worktree_id)
4223            .collect();
4224
4225        let mut last_found: Option<SelectedEntry> = None;
4226
4227        if let Some(start) = start {
4228            let entries = self
4229                .state
4230                .visible_entries
4231                .iter()
4232                .find(|worktree| worktree.worktree_id == start.worktree_id)
4233                .map(|worktree| &worktree.entries)?;
4234
4235            let mut start_idx = entries
4236                .iter()
4237                .enumerate()
4238                .find(|(_, ele)| ele.id == start.entry_id)
4239                .map(|(idx, _)| idx)?;
4240
4241            if reverse_search {
4242                start_idx = start_idx.saturating_add(1usize);
4243            }
4244
4245            let (left, right) = entries.split_at_checked(start_idx)?;
4246
4247            let (first_iter, second_iter) = if reverse_search {
4248                (
4249                    utils::ReversibleIterable::new(left.iter(), reverse_search),
4250                    utils::ReversibleIterable::new(right.iter(), reverse_search),
4251                )
4252            } else {
4253                (
4254                    utils::ReversibleIterable::new(right.iter(), reverse_search),
4255                    utils::ReversibleIterable::new(left.iter(), reverse_search),
4256                )
4257            };
4258
4259            let first_search = first_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
4260            let second_search = second_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
4261
4262            if first_search.is_some() {
4263                return first_search.map(|entry| SelectedEntry {
4264                    worktree_id: start.worktree_id,
4265                    entry_id: entry.id,
4266                });
4267            }
4268
4269            last_found = second_search.map(|entry| SelectedEntry {
4270                worktree_id: start.worktree_id,
4271                entry_id: entry.id,
4272            });
4273
4274            let idx = worktree_ids
4275                .iter()
4276                .enumerate()
4277                .find(|(_, ele)| **ele == start.worktree_id)
4278                .map(|(idx, _)| idx);
4279
4280            if let Some(idx) = idx {
4281                worktree_ids.rotate_left(idx + 1usize);
4282                worktree_ids.pop();
4283            }
4284        }
4285
4286        for tree_id in worktree_ids.into_iter() {
4287            if let Some(found) =
4288                self.find_entry_in_worktree(tree_id, reverse_search, true, &predicate, cx)
4289            {
4290                return Some(SelectedEntry {
4291                    worktree_id: tree_id,
4292                    entry_id: found.id,
4293                });
4294            }
4295        }
4296
4297        last_found
4298    }
4299
4300    fn calculate_depth_and_difference(
4301        entry: &Entry,
4302        visible_worktree_entries: &HashSet<Arc<RelPath>>,
4303    ) -> (usize, usize) {
4304        let (depth, difference) = entry
4305            .path
4306            .ancestors()
4307            .skip(1) // Skip the entry itself
4308            .find_map(|ancestor| {
4309                if let Some(parent_entry) = visible_worktree_entries.get(ancestor) {
4310                    let entry_path_components_count = entry.path.components().count();
4311                    let parent_path_components_count = parent_entry.components().count();
4312                    let difference = entry_path_components_count - parent_path_components_count;
4313                    let depth = parent_entry
4314                        .ancestors()
4315                        .skip(1)
4316                        .filter(|ancestor| visible_worktree_entries.contains(*ancestor))
4317                        .count();
4318                    Some((depth + 1, difference))
4319                } else {
4320                    None
4321                }
4322            })
4323            .unwrap_or_else(|| (0, entry.path.components().count()));
4324
4325        (depth, difference)
4326    }
4327
4328    fn highlight_entry_for_external_drag(
4329        &self,
4330        target_entry: &Entry,
4331        target_worktree: &Worktree,
4332    ) -> Option<ProjectEntryId> {
4333        // Always highlight directory or parent directory if it's file
4334        if target_entry.is_dir() {
4335            Some(target_entry.id)
4336        } else {
4337            target_entry
4338                .path
4339                .parent()
4340                .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4341                .map(|parent_entry| parent_entry.id)
4342        }
4343    }
4344
4345    fn highlight_entry_for_selection_drag(
4346        &self,
4347        target_entry: &Entry,
4348        target_worktree: &Worktree,
4349        drag_state: &DraggedSelection,
4350        cx: &Context<Self>,
4351    ) -> Option<ProjectEntryId> {
4352        let target_parent_path = target_entry.path.parent();
4353
4354        // In case of single item drag, we do not highlight existing
4355        // directory which item belongs too
4356        if drag_state.items().count() == 1
4357            && drag_state.active_selection.worktree_id == target_worktree.id()
4358        {
4359            let active_entry_path = self
4360                .project
4361                .read(cx)
4362                .path_for_entry(drag_state.active_selection.entry_id, cx)?;
4363
4364            if let Some(active_parent_path) = active_entry_path.path.parent() {
4365                // Do not highlight active entry parent
4366                if active_parent_path == target_entry.path.as_ref() {
4367                    return None;
4368                }
4369
4370                // Do not highlight active entry sibling files
4371                if Some(active_parent_path) == target_parent_path && target_entry.is_file() {
4372                    return None;
4373                }
4374            }
4375        }
4376
4377        // Always highlight directory or parent directory if it's file
4378        if target_entry.is_dir() {
4379            Some(target_entry.id)
4380        } else {
4381            target_parent_path
4382                .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4383                .map(|parent_entry| parent_entry.id)
4384        }
4385    }
4386
4387    fn should_highlight_background_for_selection_drag(
4388        &self,
4389        drag_state: &DraggedSelection,
4390        last_root_id: ProjectEntryId,
4391        cx: &App,
4392    ) -> bool {
4393        // Always highlight for multiple entries
4394        if drag_state.items().count() > 1 {
4395            return true;
4396        }
4397
4398        // Since root will always have empty relative path
4399        if let Some(entry_path) = self
4400            .project
4401            .read(cx)
4402            .path_for_entry(drag_state.active_selection.entry_id, cx)
4403        {
4404            if let Some(parent_path) = entry_path.path.parent() {
4405                if !parent_path.is_empty() {
4406                    return true;
4407                }
4408            }
4409        }
4410
4411        // If parent is empty, check if different worktree
4412        if let Some(last_root_worktree_id) = self
4413            .project
4414            .read(cx)
4415            .worktree_id_for_entry(last_root_id, cx)
4416        {
4417            if drag_state.active_selection.worktree_id != last_root_worktree_id {
4418                return true;
4419            }
4420        }
4421
4422        false
4423    }
4424
4425    fn render_entry(
4426        &self,
4427        entry_id: ProjectEntryId,
4428        details: EntryDetails,
4429        window: &mut Window,
4430        cx: &mut Context<Self>,
4431    ) -> Stateful<Div> {
4432        const GROUP_NAME: &str = "project_entry";
4433
4434        let kind = details.kind;
4435        let is_sticky = details.sticky.is_some();
4436        let sticky_index = details.sticky.as_ref().map(|this| this.sticky_index);
4437        let settings = ProjectPanelSettings::get_global(cx);
4438        let show_editor = details.is_editing && !details.is_processing;
4439
4440        let selection = SelectedEntry {
4441            worktree_id: details.worktree_id,
4442            entry_id,
4443        };
4444
4445        let is_marked = self.marked_entries.contains(&selection);
4446        let is_active = self
4447            .state
4448            .selection
4449            .is_some_and(|selection| selection.entry_id == entry_id);
4450
4451        let file_name = details.filename.clone();
4452
4453        let mut icon = details.icon.clone();
4454        if settings.file_icons && show_editor && details.kind.is_file() {
4455            let filename = self.filename_editor.read(cx).text(cx);
4456            if filename.len() > 2 {
4457                icon = FileIcons::get_icon(Path::new(&filename), cx);
4458            }
4459        }
4460
4461        let filename_text_color = details.filename_text_color;
4462        let diagnostic_severity = details.diagnostic_severity;
4463        let item_colors = get_item_color(is_sticky, cx);
4464
4465        let canonical_path = details
4466            .canonical_path
4467            .as_ref()
4468            .map(|f| f.to_string_lossy().into_owned());
4469        let path_style = self.project.read(cx).path_style(cx);
4470        let path = details.path.clone();
4471        let path_for_external_paths = path.clone();
4472        let path_for_dragged_selection = path.clone();
4473
4474        let depth = details.depth;
4475        let worktree_id = details.worktree_id;
4476        let dragged_selection = DraggedSelection {
4477            active_selection: SelectedEntry {
4478                worktree_id: selection.worktree_id,
4479                entry_id: self.resolve_entry(selection.entry_id),
4480            },
4481            marked_selections: Arc::from(self.marked_entries.clone()),
4482        };
4483
4484        let bg_color = if is_marked {
4485            item_colors.marked
4486        } else {
4487            item_colors.default
4488        };
4489
4490        let bg_hover_color = if is_marked {
4491            item_colors.marked
4492        } else {
4493            item_colors.hover
4494        };
4495
4496        let validation_color_and_message = if show_editor {
4497            match self
4498                .state
4499                .edit_state
4500                .as_ref()
4501                .map_or(ValidationState::None, |e| e.validation_state.clone())
4502            {
4503                ValidationState::Error(msg) => Some((Color::Error.color(cx), msg)),
4504                ValidationState::Warning(msg) => Some((Color::Warning.color(cx), msg)),
4505                ValidationState::None => None,
4506            }
4507        } else {
4508            None
4509        };
4510
4511        let border_color =
4512            if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4513                match validation_color_and_message {
4514                    Some((color, _)) => color,
4515                    None => item_colors.focused,
4516                }
4517            } else {
4518                bg_color
4519            };
4520
4521        let border_hover_color =
4522            if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4523                match validation_color_and_message {
4524                    Some((color, _)) => color,
4525                    None => item_colors.focused,
4526                }
4527            } else {
4528                bg_hover_color
4529            };
4530
4531        let folded_directory_drag_target = self.folded_directory_drag_target;
4532        let is_highlighted = {
4533            if let Some(highlight_entry_id) =
4534                self.drag_target_entry
4535                    .as_ref()
4536                    .and_then(|drag_target| match drag_target {
4537                        DragTarget::Entry {
4538                            highlight_entry_id, ..
4539                        } => Some(*highlight_entry_id),
4540                        DragTarget::Background => self.state.last_worktree_root_id,
4541                    })
4542            {
4543                // Highlight if same entry or it's children
4544                if entry_id == highlight_entry_id {
4545                    true
4546                } else {
4547                    maybe!({
4548                        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4549                        let highlight_entry = worktree.read(cx).entry_for_id(highlight_entry_id)?;
4550                        Some(path.starts_with(&highlight_entry.path))
4551                    })
4552                    .unwrap_or(false)
4553                }
4554            } else {
4555                false
4556            }
4557        };
4558
4559        let id: ElementId = if is_sticky {
4560            SharedString::from(format!("project_panel_sticky_item_{}", entry_id.to_usize())).into()
4561        } else {
4562            (entry_id.to_proto() as usize).into()
4563        };
4564
4565        div()
4566            .id(id.clone())
4567            .relative()
4568            .group(GROUP_NAME)
4569            .cursor_pointer()
4570            .rounded_none()
4571            .bg(bg_color)
4572            .border_1()
4573            .border_r_2()
4574            .border_color(border_color)
4575            .hover(|style| style.bg(bg_hover_color).border_color(border_hover_color))
4576            .when(is_sticky, |this| {
4577                this.block_mouse_except_scroll()
4578            })
4579            .when(!is_sticky, |this| {
4580                this
4581                .when(is_highlighted && folded_directory_drag_target.is_none(), |this| this.border_color(transparent_white()).bg(item_colors.drag_over))
4582                .when(settings.drag_and_drop, |this| this
4583                .on_drag_move::<ExternalPaths>(cx.listener(
4584                    move |this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
4585                        let is_current_target = this.drag_target_entry.as_ref()
4586                             .and_then(|entry| match entry {
4587                                 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4588                                 DragTarget::Background { .. } => None,
4589                             }) == Some(entry_id);
4590
4591                        if !event.bounds.contains(&event.event.position) {
4592                            // Entry responsible for setting drag target is also responsible to
4593                            // clear it up after drag is out of bounds
4594                            if is_current_target {
4595                                this.drag_target_entry = None;
4596                            }
4597                            return;
4598                        }
4599
4600                        if is_current_target {
4601                            return;
4602                        }
4603
4604                        this.marked_entries.clear();
4605
4606                        let Some((entry_id, highlight_entry_id)) = maybe!({
4607                            let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4608                            let target_entry = target_worktree.entry_for_path(&path_for_external_paths)?;
4609                            let highlight_entry_id = this.highlight_entry_for_external_drag(target_entry, target_worktree)?;
4610                            Some((target_entry.id, highlight_entry_id))
4611                        }) else {
4612                            return;
4613                        };
4614
4615                        this.drag_target_entry = Some(DragTarget::Entry {
4616                            entry_id,
4617                            highlight_entry_id,
4618                        });
4619
4620                    },
4621                ))
4622                .on_drop(cx.listener(
4623                    move |this, external_paths: &ExternalPaths, window, cx| {
4624                        this.drag_target_entry = None;
4625                        this.hover_scroll_task.take();
4626                        this.drop_external_files(external_paths.paths(), entry_id, window, cx);
4627                        cx.stop_propagation();
4628                    },
4629                ))
4630                .on_drag_move::<DraggedSelection>(cx.listener(
4631                    move |this, event: &DragMoveEvent<DraggedSelection>, window, cx| {
4632                        let is_current_target = this.drag_target_entry.as_ref()
4633                             .and_then(|entry| match entry {
4634                                 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4635                                 DragTarget::Background { .. } => None,
4636                             }) == Some(entry_id);
4637
4638                        if !event.bounds.contains(&event.event.position) {
4639                            // Entry responsible for setting drag target is also responsible to
4640                            // clear it up after drag is out of bounds
4641                            if is_current_target {
4642                                this.drag_target_entry = None;
4643                            }
4644                            return;
4645                        }
4646
4647                        if is_current_target {
4648                            return;
4649                        }
4650
4651                        let drag_state = event.drag(cx);
4652
4653                        if drag_state.items().count() == 1 {
4654                            this.marked_entries.clear();
4655                            this.marked_entries.push(drag_state.active_selection);
4656                        }
4657
4658                        let Some((entry_id, highlight_entry_id)) = maybe!({
4659                            let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4660                            let target_entry = target_worktree.entry_for_path(&path_for_dragged_selection)?;
4661                            let highlight_entry_id = this.highlight_entry_for_selection_drag(target_entry, target_worktree, drag_state, cx)?;
4662                            Some((target_entry.id, highlight_entry_id))
4663                        }) else {
4664                            return;
4665                        };
4666
4667                        this.drag_target_entry = Some(DragTarget::Entry {
4668                            entry_id,
4669                            highlight_entry_id,
4670                        });
4671
4672                        this.hover_expand_task.take();
4673
4674                        if !kind.is_dir()
4675                            || this
4676                                .state
4677                                .expanded_dir_ids
4678                                .get(&details.worktree_id)
4679                                .is_some_and(|ids| ids.binary_search(&entry_id).is_ok())
4680                        {
4681                            return;
4682                        }
4683
4684                        let bounds = event.bounds;
4685                        this.hover_expand_task =
4686                            Some(cx.spawn_in(window, async move |this, cx| {
4687                                cx.background_executor()
4688                                    .timer(Duration::from_millis(500))
4689                                    .await;
4690                                this.update_in(cx, |this, window, cx| {
4691                                    this.hover_expand_task.take();
4692                                    if this.drag_target_entry.as_ref().and_then(|entry| match entry {
4693                                        DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4694                                        DragTarget::Background { .. } => None,
4695                                    }) == Some(entry_id)
4696                                        && bounds.contains(&window.mouse_position())
4697                                    {
4698                                        this.expand_entry(worktree_id, entry_id, cx);
4699                                        this.update_visible_entries(
4700                                            Some((worktree_id, entry_id)),
4701                                            false,
4702                                            false,
4703                                            window,
4704                                            cx,
4705                                        );
4706                                        cx.notify();
4707                                    }
4708                                })
4709                                .ok();
4710                            }));
4711                    },
4712                ))
4713                .on_drag(
4714                    dragged_selection,
4715                    {
4716                        let active_component = self.state.ancestors.get(&entry_id).and_then(|ancestors| ancestors.active_component(&details.filename));
4717                        move |selection, click_offset, _window, cx| {
4718                            let filename = active_component.as_ref().unwrap_or_else(|| &details.filename);
4719                            cx.new(|_| DraggedProjectEntryView {
4720                                icon: details.icon.clone(),
4721                                filename: filename.clone(),
4722                                click_offset,
4723                                selection: selection.active_selection,
4724                                selections: selection.marked_selections.clone(),
4725                            })
4726                        }
4727                    }
4728                )
4729                .on_drop(
4730                    cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4731                        this.drag_target_entry = None;
4732                        this.hover_scroll_task.take();
4733                        this.hover_expand_task.take();
4734                        if folded_directory_drag_target.is_some() {
4735                            return;
4736                        }
4737                        this.drag_onto(selections, entry_id, kind.is_file(), window, cx);
4738                    }),
4739                ))
4740            })
4741            .on_mouse_down(
4742                MouseButton::Left,
4743                cx.listener(move |this, _, _, cx| {
4744                    this.mouse_down = true;
4745                    cx.propagate();
4746                }),
4747            )
4748            .on_click(
4749                cx.listener(move |project_panel, event: &gpui::ClickEvent, window, cx| {
4750                    if event.is_right_click() || event.first_focus()
4751                        || show_editor
4752                    {
4753                        return;
4754                    }
4755                    if event.standard_click() {
4756                        project_panel.mouse_down = false;
4757                    }
4758                    cx.stop_propagation();
4759
4760                    if let Some(selection) = project_panel.state.selection.filter(|_| event.modifiers().shift) {
4761                        let current_selection = project_panel.index_for_selection(selection);
4762                        let clicked_entry = SelectedEntry {
4763                            entry_id,
4764                            worktree_id,
4765                        };
4766                        let target_selection = project_panel.index_for_selection(clicked_entry);
4767                        if let Some(((_, _, source_index), (_, _, target_index))) =
4768                            current_selection.zip(target_selection)
4769                        {
4770                            let range_start = source_index.min(target_index);
4771                            let range_end = source_index.max(target_index) + 1;
4772                            let mut new_selections = Vec::new();
4773                            project_panel.for_each_visible_entry(
4774                                range_start..range_end,
4775                                window,
4776                                cx,
4777                                |entry_id, details, _, _| {
4778                                    new_selections.push(SelectedEntry {
4779                                        entry_id,
4780                                        worktree_id: details.worktree_id,
4781                                    });
4782                                },
4783                            );
4784
4785                            for selection in &new_selections {
4786                                if !project_panel.marked_entries.contains(selection) {
4787                                    project_panel.marked_entries.push(*selection);
4788                                }
4789                            }
4790
4791                            project_panel.state.selection = Some(clicked_entry);
4792                            if !project_panel.marked_entries.contains(&clicked_entry) {
4793                                project_panel.marked_entries.push(clicked_entry);
4794                            }
4795                        }
4796                    } else if event.modifiers().secondary() {
4797                        if event.click_count() > 1 {
4798                            project_panel.split_entry(entry_id, false, None, cx);
4799                        } else {
4800                            project_panel.state.selection = Some(selection);
4801                            if let Some(position) = project_panel.marked_entries.iter().position(|e| *e == selection) {
4802                                project_panel.marked_entries.remove(position);
4803                            } else {
4804                                project_panel.marked_entries.push(selection);
4805                            }
4806                        }
4807                    } else if kind.is_dir() {
4808                        project_panel.marked_entries.clear();
4809                        if is_sticky
4810                            && let Some((_, _, index)) = project_panel.index_for_entry(entry_id, worktree_id) {
4811                                project_panel.scroll_handle.scroll_to_item_strict_with_offset(index, ScrollStrategy::Top, sticky_index.unwrap_or(0));
4812                                cx.notify();
4813                                // move down by 1px so that clicked item
4814                                // don't count as sticky anymore
4815                                cx.on_next_frame(window, |_, window, cx| {
4816                                    cx.on_next_frame(window, |this, _, cx| {
4817                                        let mut offset = this.scroll_handle.offset();
4818                                        offset.y += px(1.);
4819                                        this.scroll_handle.set_offset(offset);
4820                                        cx.notify();
4821                                    });
4822                                });
4823                                return;
4824                            }
4825                        if event.modifiers().alt {
4826                            project_panel.toggle_expand_all(entry_id, window, cx);
4827                        } else {
4828                            project_panel.toggle_expanded(entry_id, window, cx);
4829                        }
4830                    } else {
4831                        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enable_preview_from_project_panel;
4832                        let click_count = event.click_count();
4833                        let focus_opened_item = click_count > 1;
4834                        let allow_preview = preview_tabs_enabled && click_count == 1;
4835                        project_panel.open_entry(entry_id, focus_opened_item, allow_preview, cx);
4836                    }
4837                }),
4838            )
4839            .child(
4840                ListItem::new(id)
4841                    .indent_level(depth)
4842                    .indent_step_size(px(settings.indent_size))
4843                    .spacing(match settings.entry_spacing {
4844                        ProjectPanelEntrySpacing::Comfortable => ListItemSpacing::Dense,
4845                        ProjectPanelEntrySpacing::Standard => {
4846                            ListItemSpacing::ExtraDense
4847                        }
4848                    })
4849                    .selectable(false)
4850                    .when_some(canonical_path, |this, path| {
4851                        this.end_slot::<AnyElement>(
4852                            div()
4853                                .id("symlink_icon")
4854                                .pr_3()
4855                                .tooltip(move |_window, cx| {
4856                                    Tooltip::with_meta(
4857                                        path.to_string(),
4858                                        None,
4859                                        "Symbolic Link",
4860                                        cx,
4861                                    )
4862                                })
4863                                .child(
4864                                    Icon::new(IconName::ArrowUpRight)
4865                                        .size(IconSize::Indicator)
4866                                        .color(filename_text_color),
4867                                )
4868                                .into_any_element(),
4869                        )
4870                    })
4871                    .child(if let Some(icon) = &icon {
4872                        if let Some((_, decoration_color)) =
4873                            entry_diagnostic_aware_icon_decoration_and_color(diagnostic_severity)
4874                        {
4875                            let is_warning = diagnostic_severity
4876                                .map(|severity| matches!(severity, DiagnosticSeverity::WARNING))
4877                                .unwrap_or(false);
4878                            div().child(
4879                                DecoratedIcon::new(
4880                                    Icon::from_path(icon.clone()).color(Color::Muted),
4881                                    Some(
4882                                        IconDecoration::new(
4883                                            if kind.is_file() {
4884                                                if is_warning {
4885                                                    IconDecorationKind::Triangle
4886                                                } else {
4887                                                    IconDecorationKind::X
4888                                                }
4889                                            } else {
4890                                                IconDecorationKind::Dot
4891                                            },
4892                                            bg_color,
4893                                            cx,
4894                                        )
4895                                        .group_name(Some(GROUP_NAME.into()))
4896                                        .knockout_hover_color(bg_hover_color)
4897                                        .color(decoration_color.color(cx))
4898                                        .position(Point {
4899                                            x: px(-2.),
4900                                            y: px(-2.),
4901                                        }),
4902                                    ),
4903                                )
4904                                .into_any_element(),
4905                            )
4906                        } else {
4907                            h_flex().child(Icon::from_path(icon.to_string()).color(Color::Muted))
4908                        }
4909                    } else if let Some((icon_name, color)) =
4910                        entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
4911                    {
4912                        h_flex()
4913                            .size(IconSize::default().rems())
4914                            .child(Icon::new(icon_name).color(color).size(IconSize::Small))
4915                    } else {
4916                        h_flex()
4917                            .size(IconSize::default().rems())
4918                            .invisible()
4919                            .flex_none()
4920                    })
4921                    .child(
4922                        if let (Some(editor), true) = (Some(&self.filename_editor), show_editor) {
4923                            h_flex().h_6().w_full().child(editor.clone())
4924                        } else {
4925                            h_flex().h_6().map(|mut this| {
4926                                if let Some(folded_ancestors) = self.state.ancestors.get(&entry_id) {
4927                                    let components = Path::new(&file_name)
4928                                        .components()
4929                                        .map(|comp| comp.as_os_str().to_string_lossy().into_owned())
4930                                        .collect::<Vec<_>>();
4931                                    let active_index = folded_ancestors.active_index();
4932                                    let components_len = components.len();
4933                                    let delimiter = SharedString::new(path_style.primary_separator());
4934                                    for (index, component) in components.iter().enumerate() {
4935                                        if index != 0 {
4936                                                let delimiter_target_index = index - 1;
4937                                                let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - delimiter_target_index).cloned();
4938                                                this = this.child(
4939                                                    div()
4940                                                    .when(!is_sticky, |div| {
4941                                                        div
4942                                                            .when(settings.drag_and_drop, |div| div
4943                                                            .on_drop(cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4944                                                            this.hover_scroll_task.take();
4945                                                            this.drag_target_entry = None;
4946                                                            this.folded_directory_drag_target = None;
4947                                                            if let Some(target_entry_id) = target_entry_id {
4948                                                                this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4949                                                            }
4950                                                        }))
4951                                                        .on_drag_move(cx.listener(
4952                                                            move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4953                                                                if event.bounds.contains(&event.event.position) {
4954                                                                    this.folded_directory_drag_target = Some(
4955                                                                        FoldedDirectoryDragTarget {
4956                                                                            entry_id,
4957                                                                            index: delimiter_target_index,
4958                                                                            is_delimiter_target: true,
4959                                                                        }
4960                                                                    );
4961                                                                } else {
4962                                                                    let is_current_target = this.folded_directory_drag_target
4963                                                                        .is_some_and(|target|
4964                                                                            target.entry_id == entry_id &&
4965                                                                            target.index == delimiter_target_index &&
4966                                                                            target.is_delimiter_target
4967                                                                        );
4968                                                                    if is_current_target {
4969                                                                        this.folded_directory_drag_target = None;
4970                                                                    }
4971                                                                }
4972
4973                                                            },
4974                                                        )))
4975                                                    })
4976                                                    .child(
4977                                                        Label::new(delimiter.clone())
4978                                                            .single_line()
4979                                                            .color(filename_text_color)
4980                                                    )
4981                                                );
4982                                        }
4983                                        let id = SharedString::from(format!(
4984                                            "project_panel_path_component_{}_{index}",
4985                                            entry_id.to_usize()
4986                                        ));
4987                                        let label = div()
4988                                            .id(id)
4989                                            .when(!is_sticky,| div| {
4990                                                div
4991                                                .when(index != components_len - 1, |div|{
4992                                                    let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - index).cloned();
4993                                                    div
4994                                                    .when(settings.drag_and_drop, |div| div
4995                                                    .on_drag_move(cx.listener(
4996                                                        move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4997                                                        if event.bounds.contains(&event.event.position) {
4998                                                                this.folded_directory_drag_target = Some(
4999                                                                    FoldedDirectoryDragTarget {
5000                                                                        entry_id,
5001                                                                        index,
5002                                                                        is_delimiter_target: false,
5003                                                                    }
5004                                                                );
5005                                                            } else {
5006                                                                let is_current_target = this.folded_directory_drag_target
5007                                                                    .as_ref()
5008                                                                    .is_some_and(|target|
5009                                                                        target.entry_id == entry_id &&
5010                                                                        target.index == index &&
5011                                                                        !target.is_delimiter_target
5012                                                                    );
5013                                                                if is_current_target {
5014                                                                    this.folded_directory_drag_target = None;
5015                                                                }
5016                                                            }
5017                                                        },
5018                                                    ))
5019                                                    .on_drop(cx.listener(move |this, selections: &DraggedSelection, window,cx| {
5020                                                        this.hover_scroll_task.take();
5021                                                        this.drag_target_entry = None;
5022                                                        this.folded_directory_drag_target = None;
5023                                                        if let Some(target_entry_id) = target_entry_id {
5024                                                            this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
5025                                                        }
5026                                                    }))
5027                                                    .when(folded_directory_drag_target.is_some_and(|target|
5028                                                        target.entry_id == entry_id &&
5029                                                        target.index == index
5030                                                    ), |this| {
5031                                                        this.bg(item_colors.drag_over)
5032                                                    }))
5033                                                })
5034                                            })
5035                                            .on_mouse_down(
5036                                                MouseButton::Left,
5037                                                cx.listener(move |this, _, _, cx| {
5038                                                    if index != active_index
5039                                                        && let Some(folds) =
5040                                                            this.state.ancestors.get_mut(&entry_id)
5041                                                        {
5042                                                            folds.current_ancestor_depth =
5043                                                                components_len - 1 - index;
5044                                                            cx.notify();
5045                                                        }
5046                                                }),
5047                                            )
5048                                            .child(
5049                                                Label::new(component)
5050                                                    .single_line()
5051                                                    .color(filename_text_color)
5052                                                    .when(
5053                                                        index == active_index
5054                                                            && (is_active || is_marked),
5055                                                        |this| this.underline(),
5056                                                    ),
5057                                            );
5058
5059                                        this = this.child(label);
5060                                    }
5061
5062                                    this
5063                                } else {
5064                                    this.child(
5065                                        Label::new(file_name)
5066                                            .single_line()
5067                                            .color(filename_text_color),
5068                                    )
5069                                }
5070                            })
5071                        },
5072                    )
5073                    .on_secondary_mouse_down(cx.listener(
5074                        move |this, event: &MouseDownEvent, window, cx| {
5075                            // Stop propagation to prevent the catch-all context menu for the project
5076                            // panel from being deployed.
5077                            cx.stop_propagation();
5078                            // Some context menu actions apply to all marked entries. If the user
5079                            // right-clicks on an entry that is not marked, they may not realize the
5080                            // action applies to multiple entries. To avoid inadvertent changes, all
5081                            // entries are unmarked.
5082                            if !this.marked_entries.contains(&selection) {
5083                                this.marked_entries.clear();
5084                            }
5085                            this.deploy_context_menu(event.position, entry_id, window, cx);
5086                        },
5087                    ))
5088                    .overflow_x(),
5089            )
5090            .when_some(
5091                validation_color_and_message,
5092                |this, (color, message)| {
5093                    this
5094                    .relative()
5095                    .child(
5096                        deferred(
5097                            div()
5098                            .occlude()
5099                            .absolute()
5100                            .top_full()
5101                            .left(px(-1.)) // Used px over rem so that it doesn't change with font size
5102                            .right(px(-0.5))
5103                            .py_1()
5104                            .px_2()
5105                            .border_1()
5106                            .border_color(color)
5107                            .bg(cx.theme().colors().background)
5108                            .child(
5109                                Label::new(message)
5110                                .color(Color::from(color))
5111                                .size(LabelSize::Small)
5112                            )
5113                        )
5114                    )
5115                }
5116            )
5117    }
5118
5119    fn details_for_entry(
5120        &self,
5121        entry: &Entry,
5122        worktree_id: WorktreeId,
5123        root_name: &RelPath,
5124        entries_paths: &HashSet<Arc<RelPath>>,
5125        git_status: GitSummary,
5126        sticky: Option<StickyDetails>,
5127        _window: &mut Window,
5128        cx: &mut Context<Self>,
5129    ) -> EntryDetails {
5130        let (show_file_icons, show_folder_icons) = {
5131            let settings = ProjectPanelSettings::get_global(cx);
5132            (settings.file_icons, settings.folder_icons)
5133        };
5134
5135        let expanded_entry_ids = self
5136            .state
5137            .expanded_dir_ids
5138            .get(&worktree_id)
5139            .map(Vec::as_slice)
5140            .unwrap_or(&[]);
5141        let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
5142
5143        let icon = match entry.kind {
5144            EntryKind::File => {
5145                if show_file_icons {
5146                    FileIcons::get_icon(entry.path.as_std_path(), cx)
5147                } else {
5148                    None
5149                }
5150            }
5151            _ => {
5152                if show_folder_icons {
5153                    FileIcons::get_folder_icon(is_expanded, entry.path.as_std_path(), cx)
5154                } else {
5155                    FileIcons::get_chevron_icon(is_expanded, cx)
5156                }
5157            }
5158        };
5159
5160        let path_style = self.project.read(cx).path_style(cx);
5161        let (depth, difference) =
5162            ProjectPanel::calculate_depth_and_difference(entry, entries_paths);
5163
5164        let filename = if difference > 1 {
5165            entry
5166                .path
5167                .last_n_components(difference)
5168                .map_or(String::new(), |suffix| {
5169                    suffix.display(path_style).to_string()
5170                })
5171        } else {
5172            entry
5173                .path
5174                .file_name()
5175                .map(|name| name.to_string())
5176                .unwrap_or_else(|| root_name.as_unix_str().to_string())
5177        };
5178
5179        let selection = SelectedEntry {
5180            worktree_id,
5181            entry_id: entry.id,
5182        };
5183        let is_marked = self.marked_entries.contains(&selection);
5184        let is_selected = self.state.selection == Some(selection);
5185
5186        let diagnostic_severity = self
5187            .diagnostics
5188            .get(&(worktree_id, entry.path.clone()))
5189            .cloned();
5190
5191        let filename_text_color =
5192            entry_git_aware_label_color(git_status, entry.is_ignored, is_marked);
5193
5194        let is_cut = self
5195            .clipboard
5196            .as_ref()
5197            .is_some_and(|e| e.is_cut() && e.items().contains(&selection));
5198
5199        EntryDetails {
5200            filename,
5201            icon,
5202            path: entry.path.clone(),
5203            depth,
5204            kind: entry.kind,
5205            is_ignored: entry.is_ignored,
5206            is_expanded,
5207            is_selected,
5208            is_marked,
5209            is_editing: false,
5210            is_processing: false,
5211            is_cut,
5212            sticky,
5213            filename_text_color,
5214            diagnostic_severity,
5215            git_status,
5216            is_private: entry.is_private,
5217            worktree_id,
5218            canonical_path: entry.canonical_path.clone(),
5219        }
5220    }
5221
5222    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
5223        let mut dispatch_context = KeyContext::new_with_defaults();
5224        dispatch_context.add("ProjectPanel");
5225        dispatch_context.add("menu");
5226
5227        let identifier = if self.filename_editor.focus_handle(cx).is_focused(window) {
5228            "editing"
5229        } else {
5230            "not_editing"
5231        };
5232
5233        dispatch_context.add(identifier);
5234        dispatch_context
5235    }
5236
5237    fn reveal_entry(
5238        &mut self,
5239        project: Entity<Project>,
5240        entry_id: ProjectEntryId,
5241        skip_ignored: bool,
5242        window: &mut Window,
5243        cx: &mut Context<Self>,
5244    ) -> Result<()> {
5245        let worktree = project
5246            .read(cx)
5247            .worktree_for_entry(entry_id, cx)
5248            .context("can't reveal a non-existent entry in the project panel")?;
5249        let worktree = worktree.read(cx);
5250        if skip_ignored
5251            && worktree
5252                .entry_for_id(entry_id)
5253                .is_none_or(|entry| entry.is_ignored && !entry.is_always_included)
5254        {
5255            anyhow::bail!("can't reveal an ignored entry in the project panel");
5256        }
5257        let is_active_item_file_diff_view = self
5258            .workspace
5259            .upgrade()
5260            .and_then(|ws| ws.read(cx).active_item(cx))
5261            .map(|item| item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some())
5262            .unwrap_or(false);
5263        if is_active_item_file_diff_view {
5264            return Ok(());
5265        }
5266
5267        let worktree_id = worktree.id();
5268        self.expand_entry(worktree_id, entry_id, cx);
5269        self.update_visible_entries(Some((worktree_id, entry_id)), false, true, window, cx);
5270        self.marked_entries.clear();
5271        self.marked_entries.push(SelectedEntry {
5272            worktree_id,
5273            entry_id,
5274        });
5275        cx.notify();
5276        Ok(())
5277    }
5278
5279    fn find_active_indent_guide(
5280        &self,
5281        indent_guides: &[IndentGuideLayout],
5282        cx: &App,
5283    ) -> Option<usize> {
5284        let (worktree, entry) = self.selected_entry(cx)?;
5285
5286        // Find the parent entry of the indent guide, this will either be the
5287        // expanded folder we have selected, or the parent of the currently
5288        // selected file/collapsed directory
5289        let mut entry = entry;
5290        loop {
5291            let is_expanded_dir = entry.is_dir()
5292                && self
5293                    .state
5294                    .expanded_dir_ids
5295                    .get(&worktree.id())
5296                    .map(|ids| ids.binary_search(&entry.id).is_ok())
5297                    .unwrap_or(false);
5298            if is_expanded_dir {
5299                break;
5300            }
5301            entry = worktree.entry_for_path(&entry.path.parent()?)?;
5302        }
5303
5304        let (active_indent_range, depth) = {
5305            let (worktree_ix, child_offset, ix) = self.index_for_entry(entry.id, worktree.id())?;
5306            let child_paths = &self.state.visible_entries[worktree_ix].entries;
5307            let mut child_count = 0;
5308            let depth = entry.path.ancestors().count();
5309            while let Some(entry) = child_paths.get(child_offset + child_count + 1) {
5310                if entry.path.ancestors().count() <= depth {
5311                    break;
5312                }
5313                child_count += 1;
5314            }
5315
5316            let start = ix + 1;
5317            let end = start + child_count;
5318
5319            let visible_worktree = &self.state.visible_entries[worktree_ix];
5320            let visible_worktree_entries = visible_worktree.index.get_or_init(|| {
5321                visible_worktree
5322                    .entries
5323                    .iter()
5324                    .map(|e| e.path.clone())
5325                    .collect()
5326            });
5327
5328            // Calculate the actual depth of the entry, taking into account that directories can be auto-folded.
5329            let (depth, _) = Self::calculate_depth_and_difference(entry, visible_worktree_entries);
5330            (start..end, depth)
5331        };
5332
5333        let candidates = indent_guides
5334            .iter()
5335            .enumerate()
5336            .filter(|(_, indent_guide)| indent_guide.offset.x == depth);
5337
5338        for (i, indent) in candidates {
5339            // Find matches that are either an exact match, partially on screen, or inside the enclosing indent
5340            if active_indent_range.start <= indent.offset.y + indent.length
5341                && indent.offset.y <= active_indent_range.end
5342            {
5343                return Some(i);
5344            }
5345        }
5346        None
5347    }
5348
5349    fn render_sticky_entries(
5350        &self,
5351        child: StickyProjectPanelCandidate,
5352        window: &mut Window,
5353        cx: &mut Context<Self>,
5354    ) -> SmallVec<[AnyElement; 8]> {
5355        let project = self.project.read(cx);
5356
5357        let Some((worktree_id, entry_ref)) = self.entry_at_index(child.index) else {
5358            return SmallVec::new();
5359        };
5360
5361        let Some(visible) = self
5362            .state
5363            .visible_entries
5364            .iter()
5365            .find(|worktree| worktree.worktree_id == worktree_id)
5366        else {
5367            return SmallVec::new();
5368        };
5369
5370        let Some(worktree) = project.worktree_for_id(worktree_id, cx) else {
5371            return SmallVec::new();
5372        };
5373        let worktree = worktree.read(cx).snapshot();
5374
5375        let paths = visible
5376            .index
5377            .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
5378
5379        let mut sticky_parents = Vec::new();
5380        let mut current_path = entry_ref.path.clone();
5381
5382        'outer: loop {
5383            if let Some(parent_path) = current_path.parent() {
5384                for ancestor_path in parent_path.ancestors() {
5385                    if paths.contains(ancestor_path)
5386                        && let Some(parent_entry) = worktree.entry_for_path(ancestor_path)
5387                    {
5388                        sticky_parents.push(parent_entry.clone());
5389                        current_path = parent_entry.path.clone();
5390                        continue 'outer;
5391                    }
5392                }
5393            }
5394            break 'outer;
5395        }
5396
5397        if sticky_parents.is_empty() {
5398            return SmallVec::new();
5399        }
5400
5401        sticky_parents.reverse();
5402
5403        let panel_settings = ProjectPanelSettings::get_global(cx);
5404        let git_status_enabled = panel_settings.git_status;
5405        let root_name = worktree.root_name();
5406
5407        let git_summaries_by_id = if git_status_enabled {
5408            visible
5409                .entries
5410                .iter()
5411                .map(|e| (e.id, e.git_summary))
5412                .collect::<HashMap<_, _>>()
5413        } else {
5414            Default::default()
5415        };
5416
5417        // already checked if non empty above
5418        let last_item_index = sticky_parents.len() - 1;
5419        sticky_parents
5420            .iter()
5421            .enumerate()
5422            .map(|(index, entry)| {
5423                let git_status = git_summaries_by_id
5424                    .get(&entry.id)
5425                    .copied()
5426                    .unwrap_or_default();
5427                let sticky_details = Some(StickyDetails {
5428                    sticky_index: index,
5429                });
5430                let details = self.details_for_entry(
5431                    entry,
5432                    worktree_id,
5433                    root_name,
5434                    paths,
5435                    git_status,
5436                    sticky_details,
5437                    window,
5438                    cx,
5439                );
5440                self.render_entry(entry.id, details, window, cx)
5441                    .when(index == last_item_index, |this| {
5442                        let shadow_color_top = hsla(0.0, 0.0, 0.0, 0.1);
5443                        let shadow_color_bottom = hsla(0.0, 0.0, 0.0, 0.);
5444                        let sticky_shadow = div()
5445                            .absolute()
5446                            .left_0()
5447                            .bottom_neg_1p5()
5448                            .h_1p5()
5449                            .w_full()
5450                            .bg(linear_gradient(
5451                                0.,
5452                                linear_color_stop(shadow_color_top, 1.),
5453                                linear_color_stop(shadow_color_bottom, 0.),
5454                            ));
5455                        this.child(sticky_shadow)
5456                    })
5457                    .into_any()
5458            })
5459            .collect()
5460    }
5461}
5462
5463#[derive(Clone)]
5464struct StickyProjectPanelCandidate {
5465    index: usize,
5466    depth: usize,
5467}
5468
5469impl StickyCandidate for StickyProjectPanelCandidate {
5470    fn depth(&self) -> usize {
5471        self.depth
5472    }
5473}
5474
5475fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -> usize {
5476    const ICON_SIZE_FACTOR: usize = 2;
5477    let mut item_width = depth * ICON_SIZE_FACTOR + item_text_chars;
5478    if is_symlink {
5479        item_width += ICON_SIZE_FACTOR;
5480    }
5481    item_width
5482}
5483
5484impl Render for ProjectPanel {
5485    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5486        let has_worktree = !self.state.visible_entries.is_empty();
5487        let project = self.project.read(cx);
5488        let panel_settings = ProjectPanelSettings::get_global(cx);
5489        let indent_size = panel_settings.indent_size;
5490        let show_indent_guides = panel_settings.indent_guides.show == ShowIndentGuides::Always;
5491        let show_sticky_entries = {
5492            if panel_settings.sticky_scroll {
5493                let is_scrollable = self.scroll_handle.is_scrollable();
5494                let is_scrolled = self.scroll_handle.offset().y < px(0.);
5495                is_scrollable && is_scrolled
5496            } else {
5497                false
5498            }
5499        };
5500
5501        let is_local = project.is_local();
5502
5503        if has_worktree {
5504            let item_count = self
5505                .state
5506                .visible_entries
5507                .iter()
5508                .map(|worktree| worktree.entries.len())
5509                .sum();
5510
5511            fn handle_drag_move<T: 'static>(
5512                this: &mut ProjectPanel,
5513                e: &DragMoveEvent<T>,
5514                window: &mut Window,
5515                cx: &mut Context<ProjectPanel>,
5516            ) {
5517                if let Some(previous_position) = this.previous_drag_position {
5518                    // Refresh cursor only when an actual drag happens,
5519                    // because modifiers are not updated when the cursor is not moved.
5520                    if e.event.position != previous_position {
5521                        this.refresh_drag_cursor_style(&e.event.modifiers, window, cx);
5522                    }
5523                }
5524                this.previous_drag_position = Some(e.event.position);
5525
5526                if !e.bounds.contains(&e.event.position) {
5527                    this.drag_target_entry = None;
5528                    return;
5529                }
5530                this.hover_scroll_task.take();
5531                let panel_height = e.bounds.size.height;
5532                if panel_height <= px(0.) {
5533                    return;
5534                }
5535
5536                let event_offset = e.event.position.y - e.bounds.origin.y;
5537                // How far along in the project panel is our cursor? (0. is the top of a list, 1. is the bottom)
5538                let hovered_region_offset = event_offset / panel_height;
5539
5540                // We want the scrolling to be a bit faster when the cursor is closer to the edge of a list.
5541                // These pixels offsets were picked arbitrarily.
5542                let vertical_scroll_offset = if hovered_region_offset <= 0.05 {
5543                    8.
5544                } else if hovered_region_offset <= 0.15 {
5545                    5.
5546                } else if hovered_region_offset >= 0.95 {
5547                    -8.
5548                } else if hovered_region_offset >= 0.85 {
5549                    -5.
5550                } else {
5551                    return;
5552                };
5553                let adjustment = point(px(0.), px(vertical_scroll_offset));
5554                this.hover_scroll_task = Some(cx.spawn_in(window, async move |this, cx| {
5555                    loop {
5556                        let should_stop_scrolling = this
5557                            .update(cx, |this, cx| {
5558                                this.hover_scroll_task.as_ref()?;
5559                                let handle = this.scroll_handle.0.borrow_mut();
5560                                let offset = handle.base_handle.offset();
5561
5562                                handle.base_handle.set_offset(offset + adjustment);
5563                                cx.notify();
5564                                Some(())
5565                            })
5566                            .ok()
5567                            .flatten()
5568                            .is_some();
5569                        if should_stop_scrolling {
5570                            return;
5571                        }
5572                        cx.background_executor()
5573                            .timer(Duration::from_millis(16))
5574                            .await;
5575                    }
5576                }));
5577            }
5578            h_flex()
5579                .id("project-panel")
5580                .group("project-panel")
5581                .when(panel_settings.drag_and_drop, |this| {
5582                    this.on_drag_move(cx.listener(handle_drag_move::<ExternalPaths>))
5583                        .on_drag_move(cx.listener(handle_drag_move::<DraggedSelection>))
5584                })
5585                .size_full()
5586                .relative()
5587                .on_modifiers_changed(cx.listener(
5588                    |this, event: &ModifiersChangedEvent, window, cx| {
5589                        this.refresh_drag_cursor_style(&event.modifiers, window, cx);
5590                    },
5591                ))
5592                .key_context(self.dispatch_context(window, cx))
5593                .on_action(cx.listener(Self::scroll_up))
5594                .on_action(cx.listener(Self::scroll_down))
5595                .on_action(cx.listener(Self::scroll_cursor_center))
5596                .on_action(cx.listener(Self::scroll_cursor_top))
5597                .on_action(cx.listener(Self::scroll_cursor_bottom))
5598                .on_action(cx.listener(Self::select_next))
5599                .on_action(cx.listener(Self::select_previous))
5600                .on_action(cx.listener(Self::select_first))
5601                .on_action(cx.listener(Self::select_last))
5602                .on_action(cx.listener(Self::select_parent))
5603                .on_action(cx.listener(Self::select_next_git_entry))
5604                .on_action(cx.listener(Self::select_prev_git_entry))
5605                .on_action(cx.listener(Self::select_next_diagnostic))
5606                .on_action(cx.listener(Self::select_prev_diagnostic))
5607                .on_action(cx.listener(Self::select_next_directory))
5608                .on_action(cx.listener(Self::select_prev_directory))
5609                .on_action(cx.listener(Self::expand_selected_entry))
5610                .on_action(cx.listener(Self::collapse_selected_entry))
5611                .on_action(cx.listener(Self::collapse_all_entries))
5612                .on_action(cx.listener(Self::open))
5613                .on_action(cx.listener(Self::open_permanent))
5614                .on_action(cx.listener(Self::open_split_vertical))
5615                .on_action(cx.listener(Self::open_split_horizontal))
5616                .on_action(cx.listener(Self::confirm))
5617                .on_action(cx.listener(Self::cancel))
5618                .on_action(cx.listener(Self::copy_path))
5619                .on_action(cx.listener(Self::copy_relative_path))
5620                .on_action(cx.listener(Self::new_search_in_directory))
5621                .on_action(cx.listener(Self::unfold_directory))
5622                .on_action(cx.listener(Self::fold_directory))
5623                .on_action(cx.listener(Self::remove_from_project))
5624                .on_action(cx.listener(Self::compare_marked_files))
5625                .when(!project.is_read_only(cx), |el| {
5626                    el.on_action(cx.listener(Self::new_file))
5627                        .on_action(cx.listener(Self::new_directory))
5628                        .on_action(cx.listener(Self::rename))
5629                        .on_action(cx.listener(Self::delete))
5630                        .on_action(cx.listener(Self::cut))
5631                        .on_action(cx.listener(Self::copy))
5632                        .on_action(cx.listener(Self::paste))
5633                        .on_action(cx.listener(Self::duplicate))
5634                        .when(!project.is_remote(), |el| {
5635                            el.on_action(cx.listener(Self::trash))
5636                        })
5637                })
5638                .when(project.is_local(), |el| {
5639                    el.on_action(cx.listener(Self::reveal_in_finder))
5640                        .on_action(cx.listener(Self::open_system))
5641                        .on_action(cx.listener(Self::open_in_terminal))
5642                })
5643                .when(project.is_via_remote_server(), |el| {
5644                    el.on_action(cx.listener(Self::open_in_terminal))
5645                })
5646                .track_focus(&self.focus_handle(cx))
5647                .child(
5648                    v_flex()
5649                        .child(
5650                            uniform_list("entries", item_count, {
5651                                cx.processor(|this, range: Range<usize>, window, cx| {
5652                                    this.rendered_entries_len = range.end - range.start;
5653                                    let mut items = Vec::with_capacity(this.rendered_entries_len);
5654                                    this.for_each_visible_entry(
5655                                        range,
5656                                        window,
5657                                        cx,
5658                                        |id, details, window, cx| {
5659                                            items.push(this.render_entry(id, details, window, cx));
5660                                        },
5661                                    );
5662                                    items
5663                                })
5664                            })
5665                            .when(show_indent_guides, |list| {
5666                                list.with_decoration(
5667                                    ui::indent_guides(
5668                                        px(indent_size),
5669                                        IndentGuideColors::panel(cx),
5670                                    )
5671                                    .with_compute_indents_fn(
5672                                        cx.entity(),
5673                                        |this, range, window, cx| {
5674                                            let mut items =
5675                                                SmallVec::with_capacity(range.end - range.start);
5676                                            this.iter_visible_entries(
5677                                                range,
5678                                                window,
5679                                                cx,
5680                                                |entry, _, entries, _, _| {
5681                                                    let (depth, _) =
5682                                                        Self::calculate_depth_and_difference(
5683                                                            entry, entries,
5684                                                        );
5685                                                    items.push(depth);
5686                                                },
5687                                            );
5688                                            items
5689                                        },
5690                                    )
5691                                    .on_click(cx.listener(
5692                                        |this,
5693                                         active_indent_guide: &IndentGuideLayout,
5694                                         window,
5695                                         cx| {
5696                                            if window.modifiers().secondary() {
5697                                                let ix = active_indent_guide.offset.y;
5698                                                let Some((target_entry, worktree)) = maybe!({
5699                                                    let (worktree_id, entry) =
5700                                                        this.entry_at_index(ix)?;
5701                                                    let worktree = this
5702                                                        .project
5703                                                        .read(cx)
5704                                                        .worktree_for_id(worktree_id, cx)?;
5705                                                    let target_entry = worktree
5706                                                        .read(cx)
5707                                                        .entry_for_path(&entry.path.parent()?)?;
5708                                                    Some((target_entry, worktree))
5709                                                }) else {
5710                                                    return;
5711                                                };
5712
5713                                                this.collapse_entry(
5714                                                    target_entry.clone(),
5715                                                    worktree,
5716                                                    window,
5717                                                    cx,
5718                                                );
5719                                            }
5720                                        },
5721                                    ))
5722                                    .with_render_fn(
5723                                        cx.entity(),
5724                                        move |this, params, _, cx| {
5725                                            const LEFT_OFFSET: Pixels = px(14.);
5726                                            const PADDING_Y: Pixels = px(4.);
5727                                            const HITBOX_OVERDRAW: Pixels = px(3.);
5728
5729                                            let active_indent_guide_index = this
5730                                                .find_active_indent_guide(
5731                                                    &params.indent_guides,
5732                                                    cx,
5733                                                );
5734
5735                                            let indent_size = params.indent_size;
5736                                            let item_height = params.item_height;
5737
5738                                            params
5739                                                .indent_guides
5740                                                .into_iter()
5741                                                .enumerate()
5742                                                .map(|(idx, layout)| {
5743                                                    let offset = if layout.continues_offscreen {
5744                                                        px(0.)
5745                                                    } else {
5746                                                        PADDING_Y
5747                                                    };
5748                                                    let bounds = Bounds::new(
5749                                                        point(
5750                                                            layout.offset.x * indent_size
5751                                                                + LEFT_OFFSET,
5752                                                            layout.offset.y * item_height + offset,
5753                                                        ),
5754                                                        size(
5755                                                            px(1.),
5756                                                            layout.length * item_height
5757                                                                - offset * 2.,
5758                                                        ),
5759                                                    );
5760                                                    ui::RenderedIndentGuide {
5761                                                        bounds,
5762                                                        layout,
5763                                                        is_active: Some(idx)
5764                                                            == active_indent_guide_index,
5765                                                        hitbox: Some(Bounds::new(
5766                                                            point(
5767                                                                bounds.origin.x - HITBOX_OVERDRAW,
5768                                                                bounds.origin.y,
5769                                                            ),
5770                                                            size(
5771                                                                bounds.size.width
5772                                                                    + HITBOX_OVERDRAW * 2.,
5773                                                                bounds.size.height,
5774                                                            ),
5775                                                        )),
5776                                                    }
5777                                                })
5778                                                .collect()
5779                                        },
5780                                    ),
5781                                )
5782                            })
5783                            .when(show_sticky_entries, |list| {
5784                                let sticky_items = ui::sticky_items(
5785                                    cx.entity(),
5786                                    |this, range, window, cx| {
5787                                        let mut items =
5788                                            SmallVec::with_capacity(range.end - range.start);
5789                                        this.iter_visible_entries(
5790                                            range,
5791                                            window,
5792                                            cx,
5793                                            |entry, index, entries, _, _| {
5794                                                let (depth, _) =
5795                                                    Self::calculate_depth_and_difference(
5796                                                        entry, entries,
5797                                                    );
5798                                                let candidate =
5799                                                    StickyProjectPanelCandidate { index, depth };
5800                                                items.push(candidate);
5801                                            },
5802                                        );
5803                                        items
5804                                    },
5805                                    |this, marker_entry, window, cx| {
5806                                        let sticky_entries =
5807                                            this.render_sticky_entries(marker_entry, window, cx);
5808                                        this.sticky_items_count = sticky_entries.len();
5809                                        sticky_entries
5810                                    },
5811                                );
5812                                list.with_decoration(if show_indent_guides {
5813                                    sticky_items.with_decoration(
5814                                        ui::indent_guides(
5815                                            px(indent_size),
5816                                            IndentGuideColors::panel(cx),
5817                                        )
5818                                        .with_render_fn(
5819                                            cx.entity(),
5820                                            move |_, params, _, _| {
5821                                                const LEFT_OFFSET: Pixels = px(14.);
5822
5823                                                let indent_size = params.indent_size;
5824                                                let item_height = params.item_height;
5825
5826                                                params
5827                                                    .indent_guides
5828                                                    .into_iter()
5829                                                    .map(|layout| {
5830                                                        let bounds = Bounds::new(
5831                                                            point(
5832                                                                layout.offset.x * indent_size
5833                                                                    + LEFT_OFFSET,
5834                                                                layout.offset.y * item_height,
5835                                                            ),
5836                                                            size(
5837                                                                px(1.),
5838                                                                layout.length * item_height,
5839                                                            ),
5840                                                        );
5841                                                        ui::RenderedIndentGuide {
5842                                                            bounds,
5843                                                            layout,
5844                                                            is_active: false,
5845                                                            hitbox: None,
5846                                                        }
5847                                                    })
5848                                                    .collect()
5849                                            },
5850                                        ),
5851                                    )
5852                                } else {
5853                                    sticky_items
5854                                })
5855                            })
5856                            .with_sizing_behavior(ListSizingBehavior::Infer)
5857                            .with_horizontal_sizing_behavior(
5858                                ListHorizontalSizingBehavior::Unconstrained,
5859                            )
5860                            .with_width_from_item(self.state.max_width_item_index)
5861                            .track_scroll(&self.scroll_handle),
5862                        )
5863                        .child(
5864                            div()
5865                                .id("project-panel-blank-area")
5866                                .block_mouse_except_scroll()
5867                                .flex_grow()
5868                                .when(
5869                                    self.drag_target_entry.as_ref().is_some_and(
5870                                        |entry| match entry {
5871                                            DragTarget::Background => true,
5872                                            DragTarget::Entry {
5873                                                highlight_entry_id, ..
5874                                            } => self.state.last_worktree_root_id.is_some_and(
5875                                                |root_id| *highlight_entry_id == root_id,
5876                                            ),
5877                                        },
5878                                    ),
5879                                    |div| div.bg(cx.theme().colors().drop_target_background),
5880                                )
5881                                .on_drag_move::<ExternalPaths>(cx.listener(
5882                                    move |this, event: &DragMoveEvent<ExternalPaths>, _, _| {
5883                                        let Some(_last_root_id) = this.state.last_worktree_root_id
5884                                        else {
5885                                            return;
5886                                        };
5887                                        if event.bounds.contains(&event.event.position) {
5888                                            this.drag_target_entry = Some(DragTarget::Background);
5889                                        } else {
5890                                            if this.drag_target_entry.as_ref().is_some_and(|e| {
5891                                                matches!(e, DragTarget::Background)
5892                                            }) {
5893                                                this.drag_target_entry = None;
5894                                            }
5895                                        }
5896                                    },
5897                                ))
5898                                .on_drag_move::<DraggedSelection>(cx.listener(
5899                                    move |this, event: &DragMoveEvent<DraggedSelection>, _, cx| {
5900                                        let Some(last_root_id) = this.state.last_worktree_root_id
5901                                        else {
5902                                            return;
5903                                        };
5904                                        if event.bounds.contains(&event.event.position) {
5905                                            let drag_state = event.drag(cx);
5906                                            if this.should_highlight_background_for_selection_drag(
5907                                                &drag_state,
5908                                                last_root_id,
5909                                                cx,
5910                                            ) {
5911                                                this.drag_target_entry =
5912                                                    Some(DragTarget::Background);
5913                                            }
5914                                        } else {
5915                                            if this.drag_target_entry.as_ref().is_some_and(|e| {
5916                                                matches!(e, DragTarget::Background)
5917                                            }) {
5918                                                this.drag_target_entry = None;
5919                                            }
5920                                        }
5921                                    },
5922                                ))
5923                                .on_drop(cx.listener(
5924                                    move |this, external_paths: &ExternalPaths, window, cx| {
5925                                        this.drag_target_entry = None;
5926                                        this.hover_scroll_task.take();
5927                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5928                                            this.drop_external_files(
5929                                                external_paths.paths(),
5930                                                entry_id,
5931                                                window,
5932                                                cx,
5933                                            );
5934                                        }
5935                                        cx.stop_propagation();
5936                                    },
5937                                ))
5938                                .on_drop(cx.listener(
5939                                    move |this, selections: &DraggedSelection, window, cx| {
5940                                        this.drag_target_entry = None;
5941                                        this.hover_scroll_task.take();
5942                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5943                                            this.drag_onto(selections, entry_id, false, window, cx);
5944                                        }
5945                                        cx.stop_propagation();
5946                                    },
5947                                ))
5948                                .on_click(cx.listener(|this, event, window, cx| {
5949                                    if matches!(event, gpui::ClickEvent::Keyboard(_)) {
5950                                        return;
5951                                    }
5952                                    cx.stop_propagation();
5953                                    this.state.selection = None;
5954                                    this.marked_entries.clear();
5955                                    this.focus_handle(cx).focus(window);
5956                                }))
5957                                .on_mouse_down(
5958                                    MouseButton::Right,
5959                                    cx.listener(move |this, event: &MouseDownEvent, window, cx| {
5960                                        // When deploying the context menu anywhere below the last project entry,
5961                                        // act as if the user clicked the root of the last worktree.
5962                                        if let Some(entry_id) = this.state.last_worktree_root_id {
5963                                            this.deploy_context_menu(
5964                                                event.position,
5965                                                entry_id,
5966                                                window,
5967                                                cx,
5968                                            );
5969                                        }
5970                                    }),
5971                                )
5972                                .when(!project.is_read_only(cx), |el| {
5973                                    el.on_click(cx.listener(
5974                                        |this, event: &gpui::ClickEvent, window, cx| {
5975                                            if event.click_count() > 1
5976                                                && let Some(entry_id) =
5977                                                    this.state.last_worktree_root_id
5978                                            {
5979                                                let project = this.project.read(cx);
5980
5981                                                let worktree_id = if let Some(worktree) =
5982                                                    project.worktree_for_entry(entry_id, cx)
5983                                                {
5984                                                    worktree.read(cx).id()
5985                                                } else {
5986                                                    return;
5987                                                };
5988
5989                                                this.state.selection = Some(SelectedEntry {
5990                                                    worktree_id,
5991                                                    entry_id,
5992                                                });
5993
5994                                                this.new_file(&NewFile, window, cx);
5995                                            }
5996                                        },
5997                                    ))
5998                                }),
5999                        )
6000                        .size_full(),
6001                )
6002                .custom_scrollbars(
6003                    Scrollbars::for_settings::<ProjectPanelSettings>()
6004                        .tracked_scroll_handle(&self.scroll_handle)
6005                        .with_track_along(
6006                            ScrollAxes::Horizontal,
6007                            cx.theme().colors().panel_background,
6008                        )
6009                        .notify_content(),
6010                    window,
6011                    cx,
6012                )
6013                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
6014                    deferred(
6015                        anchored()
6016                            .position(*position)
6017                            .anchor(gpui::Corner::TopLeft)
6018                            .child(menu.clone()),
6019                    )
6020                    .with_priority(3)
6021                }))
6022        } else {
6023            let focus_handle = self.focus_handle(cx);
6024
6025            v_flex()
6026                .id("empty-project_panel")
6027                .p_4()
6028                .size_full()
6029                .items_center()
6030                .justify_center()
6031                .gap_1()
6032                .track_focus(&self.focus_handle(cx))
6033                .child(
6034                    Button::new("open_project", "Open Project")
6035                        .full_width()
6036                        .key_binding(KeyBinding::for_action_in(
6037                            &workspace::Open,
6038                            &focus_handle,
6039                            cx,
6040                        ))
6041                        .on_click(cx.listener(|this, _, window, cx| {
6042                            this.workspace
6043                                .update(cx, |_, cx| {
6044                                    window.dispatch_action(workspace::Open.boxed_clone(), cx);
6045                                })
6046                                .log_err();
6047                        })),
6048                )
6049                .child(
6050                    h_flex()
6051                        .w_1_2()
6052                        .gap_2()
6053                        .child(Divider::horizontal())
6054                        .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
6055                        .child(Divider::horizontal()),
6056                )
6057                .child(
6058                    Button::new("clone_repo", "Clone Repository")
6059                        .full_width()
6060                        .on_click(cx.listener(|this, _, window, cx| {
6061                            this.workspace
6062                                .update(cx, |_, cx| {
6063                                    window.dispatch_action(git::Clone.boxed_clone(), cx);
6064                                })
6065                                .log_err();
6066                        })),
6067                )
6068                .when(is_local, |div| {
6069                    div.when(panel_settings.drag_and_drop, |div| {
6070                        div.drag_over::<ExternalPaths>(|style, _, _, cx| {
6071                            style.bg(cx.theme().colors().drop_target_background)
6072                        })
6073                        .on_drop(cx.listener(
6074                            move |this, external_paths: &ExternalPaths, window, cx| {
6075                                this.drag_target_entry = None;
6076                                this.hover_scroll_task.take();
6077                                if let Some(task) = this
6078                                    .workspace
6079                                    .update(cx, |workspace, cx| {
6080                                        workspace.open_workspace_for_paths(
6081                                            true,
6082                                            external_paths.paths().to_owned(),
6083                                            window,
6084                                            cx,
6085                                        )
6086                                    })
6087                                    .log_err()
6088                                {
6089                                    task.detach_and_log_err(cx);
6090                                }
6091                                cx.stop_propagation();
6092                            },
6093                        ))
6094                    })
6095                })
6096        }
6097    }
6098}
6099
6100impl Render for DraggedProjectEntryView {
6101    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6102        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
6103        h_flex()
6104            .font(ui_font)
6105            .pl(self.click_offset.x + px(12.))
6106            .pt(self.click_offset.y + px(12.))
6107            .child(
6108                div()
6109                    .flex()
6110                    .gap_1()
6111                    .items_center()
6112                    .py_1()
6113                    .px_2()
6114                    .rounded_lg()
6115                    .bg(cx.theme().colors().background)
6116                    .map(|this| {
6117                        if self.selections.len() > 1 && self.selections.contains(&self.selection) {
6118                            this.child(Label::new(format!("{} entries", self.selections.len())))
6119                        } else {
6120                            this.child(if let Some(icon) = &self.icon {
6121                                div().child(Icon::from_path(icon.clone()))
6122                            } else {
6123                                div()
6124                            })
6125                            .child(Label::new(self.filename.clone()))
6126                        }
6127                    }),
6128            )
6129    }
6130}
6131
6132impl EventEmitter<Event> for ProjectPanel {}
6133
6134impl EventEmitter<PanelEvent> for ProjectPanel {}
6135
6136impl Panel for ProjectPanel {
6137    fn position(&self, _: &Window, cx: &App) -> DockPosition {
6138        match ProjectPanelSettings::get_global(cx).dock {
6139            DockSide::Left => DockPosition::Left,
6140            DockSide::Right => DockPosition::Right,
6141        }
6142    }
6143
6144    fn position_is_valid(&self, position: DockPosition) -> bool {
6145        matches!(position, DockPosition::Left | DockPosition::Right)
6146    }
6147
6148    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
6149        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
6150            let dock = match position {
6151                DockPosition::Left | DockPosition::Bottom => DockSide::Left,
6152                DockPosition::Right => DockSide::Right,
6153            };
6154            settings.project_panel.get_or_insert_default().dock = Some(dock);
6155        });
6156    }
6157
6158    fn size(&self, _: &Window, cx: &App) -> Pixels {
6159        self.width
6160            .unwrap_or_else(|| ProjectPanelSettings::get_global(cx).default_width)
6161    }
6162
6163    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
6164        self.width = size;
6165        cx.notify();
6166        cx.defer_in(window, |this, _, cx| {
6167            this.serialize(cx);
6168        });
6169    }
6170
6171    fn icon(&self, _: &Window, cx: &App) -> Option<IconName> {
6172        ProjectPanelSettings::get_global(cx)
6173            .button
6174            .then_some(IconName::FileTree)
6175    }
6176
6177    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
6178        Some("Project Panel")
6179    }
6180
6181    fn toggle_action(&self) -> Box<dyn Action> {
6182        Box::new(ToggleFocus)
6183    }
6184
6185    fn persistent_name() -> &'static str {
6186        "Project Panel"
6187    }
6188
6189    fn panel_key() -> &'static str {
6190        PROJECT_PANEL_KEY
6191    }
6192
6193    fn starts_open(&self, _: &Window, cx: &App) -> bool {
6194        if !ProjectPanelSettings::get_global(cx).starts_open {
6195            return false;
6196        }
6197
6198        let project = &self.project.read(cx);
6199        project.visible_worktrees(cx).any(|tree| {
6200            tree.read(cx)
6201                .root_entry()
6202                .is_some_and(|entry| entry.is_dir())
6203        })
6204    }
6205
6206    fn activation_priority(&self) -> u32 {
6207        0
6208    }
6209}
6210
6211impl Focusable for ProjectPanel {
6212    fn focus_handle(&self, _cx: &App) -> FocusHandle {
6213        self.focus_handle.clone()
6214    }
6215}
6216
6217impl ClipboardEntry {
6218    fn is_cut(&self) -> bool {
6219        matches!(self, Self::Cut { .. })
6220    }
6221
6222    fn items(&self) -> &BTreeSet<SelectedEntry> {
6223        match self {
6224            ClipboardEntry::Copied(entries) | ClipboardEntry::Cut(entries) => entries,
6225        }
6226    }
6227
6228    fn into_copy_entry(self) -> Self {
6229        match self {
6230            ClipboardEntry::Copied(_) => self,
6231            ClipboardEntry::Cut(entries) => ClipboardEntry::Copied(entries),
6232        }
6233    }
6234}
6235
6236#[inline]
6237fn cmp_directories_first(a: &Entry, b: &Entry) -> cmp::Ordering {
6238    util::paths::compare_rel_paths((&a.path, a.is_file()), (&b.path, b.is_file()))
6239}
6240
6241#[inline]
6242fn cmp_mixed(a: &Entry, b: &Entry) -> cmp::Ordering {
6243    util::paths::compare_rel_paths_mixed((&a.path, a.is_file()), (&b.path, b.is_file()))
6244}
6245
6246#[inline]
6247fn cmp_files_first(a: &Entry, b: &Entry) -> cmp::Ordering {
6248    util::paths::compare_rel_paths_files_first((&a.path, a.is_file()), (&b.path, b.is_file()))
6249}
6250
6251#[inline]
6252fn cmp_with_mode(a: &Entry, b: &Entry, mode: &settings::ProjectPanelSortMode) -> cmp::Ordering {
6253    match mode {
6254        settings::ProjectPanelSortMode::DirectoriesFirst => cmp_directories_first(a, b),
6255        settings::ProjectPanelSortMode::Mixed => cmp_mixed(a, b),
6256        settings::ProjectPanelSortMode::FilesFirst => cmp_files_first(a, b),
6257    }
6258}
6259
6260pub fn sort_worktree_entries_with_mode(
6261    entries: &mut [impl AsRef<Entry>],
6262    mode: settings::ProjectPanelSortMode,
6263) {
6264    entries.sort_by(|lhs, rhs| cmp_with_mode(lhs.as_ref(), rhs.as_ref(), &mode));
6265}
6266
6267pub fn par_sort_worktree_entries_with_mode(
6268    entries: &mut Vec<GitEntry>,
6269    mode: settings::ProjectPanelSortMode,
6270) {
6271    entries.par_sort_by(|lhs, rhs| cmp_with_mode(lhs, rhs, &mode));
6272}
6273
6274#[cfg(test)]
6275mod project_panel_tests;