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