project_panel.rs

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