project_panel.rs

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