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