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