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