project_panel.rs

   1use context_menu::{ContextMenu, ContextMenuItem};
   2use drag_and_drop::{DragAndDrop, Draggable};
   3use editor::{Cancel, Editor};
   4use futures::stream::StreamExt;
   5use gpui::{
   6    actions,
   7    anyhow::{anyhow, Result},
   8    elements::{
   9        AnchorCorner, ChildView, ContainerStyle, Empty, Flex, Label, MouseEventHandler,
  10        ParentElement, ScrollTarget, Stack, Svg, UniformList, UniformListState,
  11    },
  12    geometry::vector::Vector2F,
  13    keymap_matcher::KeymapContext,
  14    platform::{CursorStyle, MouseButton, PromptLevel},
  15    AnyElement, AppContext, ClipboardItem, Element, Entity, ModelHandle, Task, View, ViewContext,
  16    ViewHandle, WeakViewHandle,
  17};
  18use menu::{Confirm, SelectNext, SelectPrev};
  19use project::{
  20    repository::GitFileStatus, Entry, EntryKind, Project, ProjectEntryId, ProjectPath, Worktree,
  21    WorktreeId,
  22};
  23use settings::Settings;
  24use std::{
  25    cmp::Ordering,
  26    collections::{hash_map, HashMap},
  27    ffi::OsStr,
  28    ops::Range,
  29    path::Path,
  30    sync::Arc,
  31};
  32use theme::ProjectPanelEntry;
  33use unicase::UniCase;
  34use workspace::Workspace;
  35
  36const NEW_ENTRY_ID: ProjectEntryId = ProjectEntryId::MAX;
  37
  38pub struct ProjectPanel {
  39    project: ModelHandle<Project>,
  40    list: UniformListState,
  41    visible_entries: Vec<(WorktreeId, Vec<Entry>)>,
  42    last_worktree_root_id: Option<ProjectEntryId>,
  43    expanded_dir_ids: HashMap<WorktreeId, Vec<ProjectEntryId>>,
  44    selection: Option<Selection>,
  45    edit_state: Option<EditState>,
  46    filename_editor: ViewHandle<Editor>,
  47    clipboard_entry: Option<ClipboardEntry>,
  48    context_menu: ViewHandle<ContextMenu>,
  49    dragged_entry_destination: Option<Arc<Path>>,
  50    workspace: WeakViewHandle<Workspace>,
  51}
  52
  53#[derive(Copy, Clone)]
  54struct Selection {
  55    worktree_id: WorktreeId,
  56    entry_id: ProjectEntryId,
  57}
  58
  59#[derive(Clone, Debug)]
  60struct EditState {
  61    worktree_id: WorktreeId,
  62    entry_id: ProjectEntryId,
  63    is_new_entry: bool,
  64    is_dir: bool,
  65    processing_filename: Option<String>,
  66}
  67
  68#[derive(Copy, Clone)]
  69pub enum ClipboardEntry {
  70    Copied {
  71        worktree_id: WorktreeId,
  72        entry_id: ProjectEntryId,
  73    },
  74    Cut {
  75        worktree_id: WorktreeId,
  76        entry_id: ProjectEntryId,
  77    },
  78}
  79
  80#[derive(Debug, PartialEq, Eq)]
  81pub struct EntryDetails {
  82    filename: String,
  83    path: Arc<Path>,
  84    depth: usize,
  85    kind: EntryKind,
  86    is_ignored: bool,
  87    is_expanded: bool,
  88    is_selected: bool,
  89    is_editing: bool,
  90    is_processing: bool,
  91    is_cut: bool,
  92    git_status: Option<GitFileStatus>,
  93}
  94
  95actions!(
  96    project_panel,
  97    [
  98        ExpandSelectedEntry,
  99        CollapseSelectedEntry,
 100        NewDirectory,
 101        NewFile,
 102        Copy,
 103        CopyPath,
 104        CopyRelativePath,
 105        RevealInFinder,
 106        Cut,
 107        Paste,
 108        Delete,
 109        Rename,
 110        ToggleFocus
 111    ]
 112);
 113
 114pub fn init(cx: &mut AppContext) {
 115    cx.add_action(ProjectPanel::expand_selected_entry);
 116    cx.add_action(ProjectPanel::collapse_selected_entry);
 117    cx.add_action(ProjectPanel::select_prev);
 118    cx.add_action(ProjectPanel::select_next);
 119    cx.add_action(ProjectPanel::new_file);
 120    cx.add_action(ProjectPanel::new_directory);
 121    cx.add_action(ProjectPanel::rename);
 122    cx.add_async_action(ProjectPanel::delete);
 123    cx.add_async_action(ProjectPanel::confirm);
 124    cx.add_action(ProjectPanel::cancel);
 125    cx.add_action(ProjectPanel::cut);
 126    cx.add_action(ProjectPanel::copy);
 127    cx.add_action(ProjectPanel::copy_path);
 128    cx.add_action(ProjectPanel::copy_relative_path);
 129    cx.add_action(ProjectPanel::reveal_in_finder);
 130    cx.add_action(
 131        |this: &mut ProjectPanel, action: &Paste, cx: &mut ViewContext<ProjectPanel>| {
 132            this.paste(action, cx);
 133        },
 134    );
 135}
 136
 137pub enum Event {
 138    OpenedEntry {
 139        entry_id: ProjectEntryId,
 140        focus_opened_item: bool,
 141    },
 142}
 143
 144impl ProjectPanel {
 145    pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> ViewHandle<Self> {
 146        let project = workspace.project().clone();
 147        let project_panel = cx.add_view(|cx: &mut ViewContext<Self>| {
 148            cx.observe(&project, |this, _, cx| {
 149                this.update_visible_entries(None, cx);
 150                cx.notify();
 151            })
 152            .detach();
 153            cx.subscribe(&project, |this, project, event, cx| match event {
 154                project::Event::ActiveEntryChanged(Some(entry_id)) => {
 155                    if let Some(worktree_id) = project.read(cx).worktree_id_for_entry(*entry_id, cx)
 156                    {
 157                        this.expand_entry(worktree_id, *entry_id, cx);
 158                        this.update_visible_entries(Some((worktree_id, *entry_id)), cx);
 159                        this.autoscroll(cx);
 160                        cx.notify();
 161                    }
 162                }
 163                project::Event::WorktreeRemoved(id) => {
 164                    this.expanded_dir_ids.remove(id);
 165                    this.update_visible_entries(None, cx);
 166                    cx.notify();
 167                }
 168                _ => {}
 169            })
 170            .detach();
 171
 172            let filename_editor = cx.add_view(|cx| {
 173                Editor::single_line(
 174                    Some(Arc::new(|theme| {
 175                        let mut style = theme.project_panel.filename_editor.clone();
 176                        style.container.background_color.take();
 177                        style
 178                    })),
 179                    cx,
 180                )
 181            });
 182
 183            cx.subscribe(&filename_editor, |this, _, event, cx| match event {
 184                editor::Event::BufferEdited | editor::Event::SelectionsChanged { .. } => {
 185                    this.autoscroll(cx);
 186                }
 187                _ => {}
 188            })
 189            .detach();
 190            cx.observe_focus(&filename_editor, |this, _, is_focused, cx| {
 191                if !is_focused
 192                    && this
 193                        .edit_state
 194                        .as_ref()
 195                        .map_or(false, |state| state.processing_filename.is_none())
 196                {
 197                    this.edit_state = None;
 198                    this.update_visible_entries(None, cx);
 199                }
 200            })
 201            .detach();
 202
 203            let view_id = cx.view_id();
 204            let mut this = Self {
 205                project: project.clone(),
 206                list: Default::default(),
 207                visible_entries: Default::default(),
 208                last_worktree_root_id: Default::default(),
 209                expanded_dir_ids: Default::default(),
 210                selection: None,
 211                edit_state: None,
 212                filename_editor,
 213                clipboard_entry: None,
 214                context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)),
 215                dragged_entry_destination: None,
 216                workspace: workspace.weak_handle(),
 217            };
 218            this.update_visible_entries(None, cx);
 219            this
 220        });
 221
 222        cx.subscribe(&project_panel, {
 223            let project_panel = project_panel.downgrade();
 224            move |workspace, _, event, cx| match event {
 225                &Event::OpenedEntry {
 226                    entry_id,
 227                    focus_opened_item,
 228                } => {
 229                    if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx) {
 230                        if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
 231                            workspace
 232                                .open_path(
 233                                    ProjectPath {
 234                                        worktree_id: worktree.read(cx).id(),
 235                                        path: entry.path.clone(),
 236                                    },
 237                                    None,
 238                                    focus_opened_item,
 239                                    cx,
 240                                )
 241                                .detach_and_log_err(cx);
 242                            if !focus_opened_item {
 243                                if let Some(project_panel) = project_panel.upgrade(cx) {
 244                                    cx.focus(&project_panel);
 245                                }
 246                            }
 247                        }
 248                    }
 249                }
 250            }
 251        })
 252        .detach();
 253
 254        project_panel
 255    }
 256
 257    fn deploy_context_menu(
 258        &mut self,
 259        position: Vector2F,
 260        entry_id: ProjectEntryId,
 261        cx: &mut ViewContext<Self>,
 262    ) {
 263        let project = self.project.read(cx);
 264
 265        let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) {
 266            id
 267        } else {
 268            return;
 269        };
 270
 271        self.selection = Some(Selection {
 272            worktree_id,
 273            entry_id,
 274        });
 275
 276        let mut menu_entries = Vec::new();
 277        if let Some((worktree, entry)) = self.selected_entry(cx) {
 278            let is_root = Some(entry) == worktree.root_entry();
 279            if !project.is_remote() {
 280                menu_entries.push(ContextMenuItem::action(
 281                    "Add Folder to Project",
 282                    workspace::AddFolderToProject,
 283                ));
 284                if is_root {
 285                    let project = self.project.clone();
 286                    menu_entries.push(ContextMenuItem::handler("Remove from Project", move |cx| {
 287                        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 288                    }));
 289                }
 290            }
 291            menu_entries.push(ContextMenuItem::action("New File", NewFile));
 292            menu_entries.push(ContextMenuItem::action("New Folder", NewDirectory));
 293            menu_entries.push(ContextMenuItem::Separator);
 294            menu_entries.push(ContextMenuItem::action("Cut", Cut));
 295            menu_entries.push(ContextMenuItem::action("Copy", Copy));
 296            menu_entries.push(ContextMenuItem::Separator);
 297            menu_entries.push(ContextMenuItem::action("Copy Path", CopyPath));
 298            menu_entries.push(ContextMenuItem::action(
 299                "Copy Relative Path",
 300                CopyRelativePath,
 301            ));
 302            menu_entries.push(ContextMenuItem::action("Reveal in Finder", RevealInFinder));
 303            if let Some(clipboard_entry) = self.clipboard_entry {
 304                if clipboard_entry.worktree_id() == worktree.id() {
 305                    menu_entries.push(ContextMenuItem::action("Paste", Paste));
 306                }
 307            }
 308            menu_entries.push(ContextMenuItem::Separator);
 309            menu_entries.push(ContextMenuItem::action("Rename", Rename));
 310            if !is_root {
 311                menu_entries.push(ContextMenuItem::action("Delete", Delete));
 312            }
 313        }
 314
 315        self.context_menu.update(cx, |menu, cx| {
 316            menu.show(position, AnchorCorner::TopLeft, menu_entries, cx);
 317        });
 318
 319        cx.notify();
 320    }
 321
 322    fn expand_selected_entry(&mut self, _: &ExpandSelectedEntry, cx: &mut ViewContext<Self>) {
 323        if let Some((worktree, entry)) = self.selected_entry(cx) {
 324            if entry.is_dir() {
 325                let expanded_dir_ids =
 326                    if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree.id()) {
 327                        expanded_dir_ids
 328                    } else {
 329                        return;
 330                    };
 331
 332                match expanded_dir_ids.binary_search(&entry.id) {
 333                    Ok(_) => self.select_next(&SelectNext, cx),
 334                    Err(ix) => {
 335                        expanded_dir_ids.insert(ix, entry.id);
 336                        self.update_visible_entries(None, cx);
 337                        cx.notify();
 338                    }
 339                }
 340            }
 341        }
 342    }
 343
 344    fn collapse_selected_entry(&mut self, _: &CollapseSelectedEntry, cx: &mut ViewContext<Self>) {
 345        if let Some((worktree, mut entry)) = self.selected_entry(cx) {
 346            let expanded_dir_ids =
 347                if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree.id()) {
 348                    expanded_dir_ids
 349                } else {
 350                    return;
 351                };
 352
 353            loop {
 354                match expanded_dir_ids.binary_search(&entry.id) {
 355                    Ok(ix) => {
 356                        expanded_dir_ids.remove(ix);
 357                        self.update_visible_entries(Some((worktree.id(), entry.id)), cx);
 358                        cx.notify();
 359                        break;
 360                    }
 361                    Err(_) => {
 362                        if let Some(parent_entry) =
 363                            entry.path.parent().and_then(|p| worktree.entry_for_path(p))
 364                        {
 365                            entry = parent_entry;
 366                        } else {
 367                            break;
 368                        }
 369                    }
 370                }
 371            }
 372        }
 373    }
 374
 375    fn toggle_expanded(&mut self, entry_id: ProjectEntryId, cx: &mut ViewContext<Self>) {
 376        if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx) {
 377            if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
 378                match expanded_dir_ids.binary_search(&entry_id) {
 379                    Ok(ix) => {
 380                        expanded_dir_ids.remove(ix);
 381                    }
 382                    Err(ix) => {
 383                        expanded_dir_ids.insert(ix, entry_id);
 384                    }
 385                }
 386                self.update_visible_entries(Some((worktree_id, entry_id)), cx);
 387                cx.focus_self();
 388                cx.notify();
 389            }
 390        }
 391    }
 392
 393    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
 394        if let Some(selection) = self.selection {
 395            let (mut worktree_ix, mut entry_ix, _) =
 396                self.index_for_selection(selection).unwrap_or_default();
 397            if entry_ix > 0 {
 398                entry_ix -= 1;
 399            } else if worktree_ix > 0 {
 400                worktree_ix -= 1;
 401                entry_ix = self.visible_entries[worktree_ix].1.len() - 1;
 402            } else {
 403                return;
 404            }
 405
 406            let (worktree_id, worktree_entries) = &self.visible_entries[worktree_ix];
 407            self.selection = Some(Selection {
 408                worktree_id: *worktree_id,
 409                entry_id: worktree_entries[entry_ix].id,
 410            });
 411            self.autoscroll(cx);
 412            cx.notify();
 413        } else {
 414            self.select_first(cx);
 415        }
 416    }
 417
 418    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 419        if let Some(task) = self.confirm_edit(cx) {
 420            Some(task)
 421        } else if let Some((_, entry)) = self.selected_entry(cx) {
 422            if entry.is_file() {
 423                self.open_entry(entry.id, true, cx);
 424            }
 425            None
 426        } else {
 427            None
 428        }
 429    }
 430
 431    fn confirm_edit(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 432        let edit_state = self.edit_state.as_mut()?;
 433        cx.focus_self();
 434
 435        let worktree_id = edit_state.worktree_id;
 436        let is_new_entry = edit_state.is_new_entry;
 437        let is_dir = edit_state.is_dir;
 438        let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
 439        let entry = worktree.read(cx).entry_for_id(edit_state.entry_id)?.clone();
 440        let filename = self.filename_editor.read(cx).text(cx);
 441
 442        let edit_task;
 443        let edited_entry_id;
 444
 445        if is_new_entry {
 446            self.selection = Some(Selection {
 447                worktree_id,
 448                entry_id: NEW_ENTRY_ID,
 449            });
 450            let new_path = entry.path.join(&filename);
 451            edited_entry_id = NEW_ENTRY_ID;
 452            edit_task = self.project.update(cx, |project, cx| {
 453                project.create_entry((worktree_id, new_path), is_dir, cx)
 454            })?;
 455        } else {
 456            let new_path = if let Some(parent) = entry.path.clone().parent() {
 457                parent.join(&filename)
 458            } else {
 459                filename.clone().into()
 460            };
 461            edited_entry_id = entry.id;
 462            edit_task = self.project.update(cx, |project, cx| {
 463                project.rename_entry(entry.id, new_path, cx)
 464            })?;
 465        };
 466
 467        edit_state.processing_filename = Some(filename);
 468        cx.notify();
 469
 470        Some(cx.spawn(|this, mut cx| async move {
 471            let new_entry = edit_task.await;
 472            this.update(&mut cx, |this, cx| {
 473                this.edit_state.take();
 474                cx.notify();
 475            })?;
 476
 477            let new_entry = new_entry?;
 478            this.update(&mut cx, |this, cx| {
 479                if let Some(selection) = &mut this.selection {
 480                    if selection.entry_id == edited_entry_id {
 481                        selection.worktree_id = worktree_id;
 482                        selection.entry_id = new_entry.id;
 483                    }
 484                }
 485                this.update_visible_entries(None, cx);
 486                if is_new_entry && !is_dir {
 487                    this.open_entry(new_entry.id, true, cx);
 488                }
 489                cx.notify();
 490            })?;
 491            Ok(())
 492        }))
 493    }
 494
 495    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 496        self.edit_state = None;
 497        self.update_visible_entries(None, cx);
 498        cx.focus_self();
 499        cx.notify();
 500    }
 501
 502    fn open_entry(
 503        &mut self,
 504        entry_id: ProjectEntryId,
 505        focus_opened_item: bool,
 506        cx: &mut ViewContext<Self>,
 507    ) {
 508        cx.emit(Event::OpenedEntry {
 509            entry_id,
 510            focus_opened_item,
 511        });
 512    }
 513
 514    fn new_file(&mut self, _: &NewFile, cx: &mut ViewContext<Self>) {
 515        self.add_entry(false, cx)
 516    }
 517
 518    fn new_directory(&mut self, _: &NewDirectory, cx: &mut ViewContext<Self>) {
 519        self.add_entry(true, cx)
 520    }
 521
 522    fn add_entry(&mut self, is_dir: bool, cx: &mut ViewContext<Self>) {
 523        if let Some(Selection {
 524            worktree_id,
 525            entry_id,
 526        }) = self.selection
 527        {
 528            let directory_id;
 529            if let Some((worktree, expanded_dir_ids)) = self
 530                .project
 531                .read(cx)
 532                .worktree_for_id(worktree_id, cx)
 533                .zip(self.expanded_dir_ids.get_mut(&worktree_id))
 534            {
 535                let worktree = worktree.read(cx);
 536                if let Some(mut entry) = worktree.entry_for_id(entry_id) {
 537                    loop {
 538                        if entry.is_dir() {
 539                            if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
 540                                expanded_dir_ids.insert(ix, entry.id);
 541                            }
 542                            directory_id = entry.id;
 543                            break;
 544                        } else {
 545                            if let Some(parent_path) = entry.path.parent() {
 546                                if let Some(parent_entry) = worktree.entry_for_path(parent_path) {
 547                                    entry = parent_entry;
 548                                    continue;
 549                                }
 550                            }
 551                            return;
 552                        }
 553                    }
 554                } else {
 555                    return;
 556                };
 557            } else {
 558                return;
 559            };
 560
 561            self.edit_state = Some(EditState {
 562                worktree_id,
 563                entry_id: directory_id,
 564                is_new_entry: true,
 565                is_dir,
 566                processing_filename: None,
 567            });
 568            self.filename_editor
 569                .update(cx, |editor, cx| editor.clear(cx));
 570            cx.focus(&self.filename_editor);
 571            self.update_visible_entries(Some((worktree_id, NEW_ENTRY_ID)), cx);
 572            self.autoscroll(cx);
 573            cx.notify();
 574        }
 575    }
 576
 577    fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) {
 578        if let Some(Selection {
 579            worktree_id,
 580            entry_id,
 581        }) = self.selection
 582        {
 583            if let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx) {
 584                if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
 585                    self.edit_state = Some(EditState {
 586                        worktree_id,
 587                        entry_id,
 588                        is_new_entry: false,
 589                        is_dir: entry.is_dir(),
 590                        processing_filename: None,
 591                    });
 592                    let filename = entry
 593                        .path
 594                        .file_name()
 595                        .map_or(String::new(), |s| s.to_string_lossy().to_string());
 596                    self.filename_editor.update(cx, |editor, cx| {
 597                        editor.set_text(filename, cx);
 598                        editor.select_all(&Default::default(), cx);
 599                    });
 600                    cx.focus(&self.filename_editor);
 601                    self.update_visible_entries(None, cx);
 602                    self.autoscroll(cx);
 603                    cx.notify();
 604                }
 605            }
 606
 607            cx.update_global(|drag_and_drop: &mut DragAndDrop<Workspace>, cx| {
 608                drag_and_drop.cancel_dragging::<ProjectEntryId>(cx);
 609            })
 610        }
 611    }
 612
 613    fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 614        let Selection { entry_id, .. } = self.selection?;
 615        let path = self.project.read(cx).path_for_entry(entry_id, cx)?.path;
 616        let file_name = path.file_name()?;
 617
 618        let mut answer = cx.prompt(
 619            PromptLevel::Info,
 620            &format!("Delete {file_name:?}?"),
 621            &["Delete", "Cancel"],
 622        );
 623        Some(cx.spawn(|this, mut cx| async move {
 624            if answer.next().await != Some(0) {
 625                return Ok(());
 626            }
 627            this.update(&mut cx, |this, cx| {
 628                this.project
 629                    .update(cx, |project, cx| project.delete_entry(entry_id, cx))
 630                    .ok_or_else(|| anyhow!("no such entry"))
 631            })??
 632            .await
 633        }))
 634    }
 635
 636    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
 637        if let Some(selection) = self.selection {
 638            let (mut worktree_ix, mut entry_ix, _) =
 639                self.index_for_selection(selection).unwrap_or_default();
 640            if let Some((_, worktree_entries)) = self.visible_entries.get(worktree_ix) {
 641                if entry_ix + 1 < worktree_entries.len() {
 642                    entry_ix += 1;
 643                } else {
 644                    worktree_ix += 1;
 645                    entry_ix = 0;
 646                }
 647            }
 648
 649            if let Some((worktree_id, worktree_entries)) = self.visible_entries.get(worktree_ix) {
 650                if let Some(entry) = worktree_entries.get(entry_ix) {
 651                    self.selection = Some(Selection {
 652                        worktree_id: *worktree_id,
 653                        entry_id: entry.id,
 654                    });
 655                    self.autoscroll(cx);
 656                    cx.notify();
 657                }
 658            }
 659        } else {
 660            self.select_first(cx);
 661        }
 662    }
 663
 664    fn select_first(&mut self, cx: &mut ViewContext<Self>) {
 665        let worktree = self
 666            .visible_entries
 667            .first()
 668            .and_then(|(worktree_id, _)| self.project.read(cx).worktree_for_id(*worktree_id, cx));
 669        if let Some(worktree) = worktree {
 670            let worktree = worktree.read(cx);
 671            let worktree_id = worktree.id();
 672            if let Some(root_entry) = worktree.root_entry() {
 673                self.selection = Some(Selection {
 674                    worktree_id,
 675                    entry_id: root_entry.id,
 676                });
 677                self.autoscroll(cx);
 678                cx.notify();
 679            }
 680        }
 681    }
 682
 683    fn autoscroll(&mut self, cx: &mut ViewContext<Self>) {
 684        if let Some((_, _, index)) = self.selection.and_then(|s| self.index_for_selection(s)) {
 685            self.list.scroll_to(ScrollTarget::Show(index));
 686            cx.notify();
 687        }
 688    }
 689
 690    fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 691        if let Some((worktree, entry)) = self.selected_entry(cx) {
 692            self.clipboard_entry = Some(ClipboardEntry::Cut {
 693                worktree_id: worktree.id(),
 694                entry_id: entry.id,
 695            });
 696            cx.notify();
 697        }
 698    }
 699
 700    fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 701        if let Some((worktree, entry)) = self.selected_entry(cx) {
 702            self.clipboard_entry = Some(ClipboardEntry::Copied {
 703                worktree_id: worktree.id(),
 704                entry_id: entry.id,
 705            });
 706            cx.notify();
 707        }
 708    }
 709
 710    fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) -> Option<()> {
 711        if let Some((worktree, entry)) = self.selected_entry(cx) {
 712            let clipboard_entry = self.clipboard_entry?;
 713            if clipboard_entry.worktree_id() != worktree.id() {
 714                return None;
 715            }
 716
 717            let clipboard_entry_file_name = self
 718                .project
 719                .read(cx)
 720                .path_for_entry(clipboard_entry.entry_id(), cx)?
 721                .path
 722                .file_name()?
 723                .to_os_string();
 724
 725            let mut new_path = entry.path.to_path_buf();
 726            if entry.is_file() {
 727                new_path.pop();
 728            }
 729
 730            new_path.push(&clipboard_entry_file_name);
 731            let extension = new_path.extension().map(|e| e.to_os_string());
 732            let file_name_without_extension = Path::new(&clipboard_entry_file_name).file_stem()?;
 733            let mut ix = 0;
 734            while worktree.entry_for_path(&new_path).is_some() {
 735                new_path.pop();
 736
 737                let mut new_file_name = file_name_without_extension.to_os_string();
 738                new_file_name.push(" copy");
 739                if ix > 0 {
 740                    new_file_name.push(format!(" {}", ix));
 741                }
 742                if let Some(extension) = extension.as_ref() {
 743                    new_file_name.push(".");
 744                    new_file_name.push(extension);
 745                }
 746
 747                new_path.push(new_file_name);
 748                ix += 1;
 749            }
 750
 751            if clipboard_entry.is_cut() {
 752                if let Some(task) = self.project.update(cx, |project, cx| {
 753                    project.rename_entry(clipboard_entry.entry_id(), new_path, cx)
 754                }) {
 755                    task.detach_and_log_err(cx)
 756                }
 757            } else if let Some(task) = self.project.update(cx, |project, cx| {
 758                project.copy_entry(clipboard_entry.entry_id(), new_path, cx)
 759            }) {
 760                task.detach_and_log_err(cx)
 761            }
 762        }
 763        None
 764    }
 765
 766    fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 767        if let Some((worktree, entry)) = self.selected_entry(cx) {
 768            cx.write_to_clipboard(ClipboardItem::new(
 769                worktree
 770                    .abs_path()
 771                    .join(&entry.path)
 772                    .to_string_lossy()
 773                    .to_string(),
 774            ));
 775        }
 776    }
 777
 778    fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 779        if let Some((_, entry)) = self.selected_entry(cx) {
 780            cx.write_to_clipboard(ClipboardItem::new(entry.path.to_string_lossy().to_string()));
 781        }
 782    }
 783
 784    fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 785        if let Some((worktree, entry)) = self.selected_entry(cx) {
 786            cx.reveal_path(&worktree.abs_path().join(&entry.path));
 787        }
 788    }
 789
 790    fn move_entry(
 791        &mut self,
 792        entry_to_move: ProjectEntryId,
 793        destination: ProjectEntryId,
 794        destination_is_file: bool,
 795        cx: &mut ViewContext<Self>,
 796    ) {
 797        let destination_worktree = self.project.update(cx, |project, cx| {
 798            let entry_path = project.path_for_entry(entry_to_move, cx)?;
 799            let destination_entry_path = project.path_for_entry(destination, cx)?.path.clone();
 800
 801            let mut destination_path = destination_entry_path.as_ref();
 802            if destination_is_file {
 803                destination_path = destination_path.parent()?;
 804            }
 805
 806            let mut new_path = destination_path.to_path_buf();
 807            new_path.push(entry_path.path.file_name()?);
 808            if new_path != entry_path.path.as_ref() {
 809                let task = project.rename_entry(entry_to_move, new_path, cx)?;
 810                cx.foreground().spawn(task).detach_and_log_err(cx);
 811            }
 812
 813            Some(project.worktree_id_for_entry(destination, cx)?)
 814        });
 815
 816        if let Some(destination_worktree) = destination_worktree {
 817            self.expand_entry(destination_worktree, destination, cx);
 818        }
 819    }
 820
 821    fn index_for_selection(&self, selection: Selection) -> Option<(usize, usize, usize)> {
 822        let mut entry_index = 0;
 823        let mut visible_entries_index = 0;
 824        for (worktree_index, (worktree_id, worktree_entries)) in
 825            self.visible_entries.iter().enumerate()
 826        {
 827            if *worktree_id == selection.worktree_id {
 828                for entry in worktree_entries {
 829                    if entry.id == selection.entry_id {
 830                        return Some((worktree_index, entry_index, visible_entries_index));
 831                    } else {
 832                        visible_entries_index += 1;
 833                        entry_index += 1;
 834                    }
 835                }
 836                break;
 837            } else {
 838                visible_entries_index += worktree_entries.len();
 839            }
 840        }
 841        None
 842    }
 843
 844    fn selected_entry<'a>(&self, cx: &'a AppContext) -> Option<(&'a Worktree, &'a project::Entry)> {
 845        let selection = self.selection?;
 846        let project = self.project.read(cx);
 847        let worktree = project.worktree_for_id(selection.worktree_id, cx)?.read(cx);
 848        Some((worktree, worktree.entry_for_id(selection.entry_id)?))
 849    }
 850
 851    fn update_visible_entries(
 852        &mut self,
 853        new_selected_entry: Option<(WorktreeId, ProjectEntryId)>,
 854        cx: &mut ViewContext<Self>,
 855    ) {
 856        let project = self.project.read(cx);
 857        self.last_worktree_root_id = project
 858            .visible_worktrees(cx)
 859            .rev()
 860            .next()
 861            .and_then(|worktree| worktree.read(cx).root_entry())
 862            .map(|entry| entry.id);
 863
 864        self.visible_entries.clear();
 865        for worktree in project.visible_worktrees(cx) {
 866            let snapshot = worktree.read(cx).snapshot();
 867            let worktree_id = snapshot.id();
 868
 869            let expanded_dir_ids = match self.expanded_dir_ids.entry(worktree_id) {
 870                hash_map::Entry::Occupied(e) => e.into_mut(),
 871                hash_map::Entry::Vacant(e) => {
 872                    // The first time a worktree's root entry becomes available,
 873                    // mark that root entry as expanded.
 874                    if let Some(entry) = snapshot.root_entry() {
 875                        e.insert(vec![entry.id]).as_slice()
 876                    } else {
 877                        &[]
 878                    }
 879                }
 880            };
 881
 882            let mut new_entry_parent_id = None;
 883            let mut new_entry_kind = EntryKind::Dir;
 884            if let Some(edit_state) = &self.edit_state {
 885                if edit_state.worktree_id == worktree_id && edit_state.is_new_entry {
 886                    new_entry_parent_id = Some(edit_state.entry_id);
 887                    new_entry_kind = if edit_state.is_dir {
 888                        EntryKind::Dir
 889                    } else {
 890                        EntryKind::File(Default::default())
 891                    };
 892                }
 893            }
 894
 895            let mut visible_worktree_entries = Vec::new();
 896            let mut entry_iter = snapshot.entries(true);
 897
 898            while let Some(entry) = entry_iter.entry() {
 899                visible_worktree_entries.push(entry.clone());
 900                if Some(entry.id) == new_entry_parent_id {
 901                    visible_worktree_entries.push(Entry {
 902                        id: NEW_ENTRY_ID,
 903                        kind: new_entry_kind,
 904                        path: entry.path.join("\0").into(),
 905                        inode: 0,
 906                        mtime: entry.mtime,
 907                        is_symlink: false,
 908                        is_ignored: false,
 909                    });
 910                }
 911                if expanded_dir_ids.binary_search(&entry.id).is_err()
 912                    && entry_iter.advance_to_sibling()
 913                {
 914                    continue;
 915                }
 916                entry_iter.advance();
 917            }
 918            visible_worktree_entries.sort_by(|entry_a, entry_b| {
 919                let mut components_a = entry_a.path.components().peekable();
 920                let mut components_b = entry_b.path.components().peekable();
 921                loop {
 922                    match (components_a.next(), components_b.next()) {
 923                        (Some(component_a), Some(component_b)) => {
 924                            let a_is_file = components_a.peek().is_none() && entry_a.is_file();
 925                            let b_is_file = components_b.peek().is_none() && entry_b.is_file();
 926                            let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
 927                                let name_a =
 928                                    UniCase::new(component_a.as_os_str().to_string_lossy());
 929                                let name_b =
 930                                    UniCase::new(component_b.as_os_str().to_string_lossy());
 931                                name_a.cmp(&name_b)
 932                            });
 933                            if !ordering.is_eq() {
 934                                return ordering;
 935                            }
 936                        }
 937                        (Some(_), None) => break Ordering::Greater,
 938                        (None, Some(_)) => break Ordering::Less,
 939                        (None, None) => break Ordering::Equal,
 940                    }
 941                }
 942            });
 943            self.visible_entries
 944                .push((worktree_id, visible_worktree_entries));
 945        }
 946
 947        if let Some((worktree_id, entry_id)) = new_selected_entry {
 948            self.selection = Some(Selection {
 949                worktree_id,
 950                entry_id,
 951            });
 952        }
 953    }
 954
 955    fn expand_entry(
 956        &mut self,
 957        worktree_id: WorktreeId,
 958        entry_id: ProjectEntryId,
 959        cx: &mut ViewContext<Self>,
 960    ) {
 961        let project = self.project.read(cx);
 962        if let Some((worktree, expanded_dir_ids)) = project
 963            .worktree_for_id(worktree_id, cx)
 964            .zip(self.expanded_dir_ids.get_mut(&worktree_id))
 965        {
 966            let worktree = worktree.read(cx);
 967
 968            if let Some(mut entry) = worktree.entry_for_id(entry_id) {
 969                loop {
 970                    if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
 971                        expanded_dir_ids.insert(ix, entry.id);
 972                    }
 973
 974                    if let Some(parent_entry) =
 975                        entry.path.parent().and_then(|p| worktree.entry_for_path(p))
 976                    {
 977                        entry = parent_entry;
 978                    } else {
 979                        break;
 980                    }
 981                }
 982            }
 983        }
 984    }
 985
 986    fn for_each_visible_entry(
 987        &self,
 988        range: Range<usize>,
 989        cx: &mut ViewContext<ProjectPanel>,
 990        mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut ViewContext<ProjectPanel>),
 991    ) {
 992        let mut ix = 0;
 993        for (worktree_id, visible_worktree_entries) in &self.visible_entries {
 994            if ix >= range.end {
 995                return;
 996            }
 997
 998            if ix + visible_worktree_entries.len() <= range.start {
 999                ix += visible_worktree_entries.len();
1000                continue;
1001            }
1002
1003            let end_ix = range.end.min(ix + visible_worktree_entries.len());
1004            if let Some(worktree) = self.project.read(cx).worktree_for_id(*worktree_id, cx) {
1005                let snapshot = worktree.read(cx).snapshot();
1006                let root_name = OsStr::new(snapshot.root_name());
1007                let expanded_entry_ids = self
1008                    .expanded_dir_ids
1009                    .get(&snapshot.id())
1010                    .map(Vec::as_slice)
1011                    .unwrap_or(&[]);
1012
1013                let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
1014                for entry in &visible_worktree_entries[entry_range] {
1015                    let path = &entry.path;
1016                    let status = snapshot
1017                        .repo_for(path)
1018                        .and_then(|entry| entry.status_for(&snapshot, path));
1019
1020                    let mut details = EntryDetails {
1021                        filename: entry
1022                            .path
1023                            .file_name()
1024                            .unwrap_or(root_name)
1025                            .to_string_lossy()
1026                            .to_string(),
1027                        path: entry.path.clone(),
1028                        depth: entry.path.components().count(),
1029                        kind: entry.kind,
1030                        is_ignored: entry.is_ignored,
1031                        is_expanded: expanded_entry_ids.binary_search(&entry.id).is_ok(),
1032                        is_selected: self.selection.map_or(false, |e| {
1033                            e.worktree_id == snapshot.id() && e.entry_id == entry.id
1034                        }),
1035                        is_editing: false,
1036                        is_processing: false,
1037                        is_cut: self
1038                            .clipboard_entry
1039                            .map_or(false, |e| e.is_cut() && e.entry_id() == entry.id),
1040                        git_status: status,
1041                    };
1042
1043                    if let Some(edit_state) = &self.edit_state {
1044                        let is_edited_entry = if edit_state.is_new_entry {
1045                            entry.id == NEW_ENTRY_ID
1046                        } else {
1047                            entry.id == edit_state.entry_id
1048                        };
1049
1050                        if is_edited_entry {
1051                            if let Some(processing_filename) = &edit_state.processing_filename {
1052                                details.is_processing = true;
1053                                details.filename.clear();
1054                                details.filename.push_str(processing_filename);
1055                            } else {
1056                                if edit_state.is_new_entry {
1057                                    details.filename.clear();
1058                                }
1059                                details.is_editing = true;
1060                            }
1061                        }
1062                    }
1063
1064                    callback(entry.id, details, cx);
1065                }
1066            }
1067            ix = end_ix;
1068        }
1069    }
1070
1071    fn render_entry_visual_element<V: View>(
1072        details: &EntryDetails,
1073        editor: Option<&ViewHandle<Editor>>,
1074        padding: f32,
1075        row_container_style: ContainerStyle,
1076        style: &ProjectPanelEntry,
1077        cx: &mut ViewContext<V>,
1078    ) -> AnyElement<V> {
1079        let kind = details.kind;
1080        let show_editor = details.is_editing && !details.is_processing;
1081
1082        // Prepare colors for git statuses
1083        let editor_theme = &cx.global::<Settings>().theme.editor;
1084        let mut filename_text_style = style.text.clone();
1085        filename_text_style.color = details
1086            .git_status
1087            .as_ref()
1088            .map(|status| match status {
1089                GitFileStatus::Added => editor_theme.diff.inserted,
1090                GitFileStatus::Modified => editor_theme.diff.modified,
1091                GitFileStatus::Conflict => editor_theme.diff.deleted,
1092            })
1093            .unwrap_or(style.text.color);
1094
1095        Flex::row()
1096            .with_child(
1097                if kind == EntryKind::Dir {
1098                    if details.is_expanded {
1099                        Svg::new("icons/chevron_down_8.svg").with_color(style.icon_color)
1100                    } else {
1101                        Svg::new("icons/chevron_right_8.svg").with_color(style.icon_color)
1102                    }
1103                    .constrained()
1104                } else {
1105                    Empty::new().constrained()
1106                }
1107                .with_max_width(style.icon_size)
1108                .with_max_height(style.icon_size)
1109                .aligned()
1110                .constrained()
1111                .with_width(style.icon_size),
1112            )
1113            .with_child(if show_editor && editor.is_some() {
1114                ChildView::new(editor.as_ref().unwrap(), cx)
1115                    .contained()
1116                    .with_margin_left(style.icon_spacing)
1117                    .aligned()
1118                    .left()
1119                    .flex(1.0, true)
1120                    .into_any()
1121            } else {
1122                Label::new(details.filename.clone(), filename_text_style)
1123                    .contained()
1124                    .with_margin_left(style.icon_spacing)
1125                    .aligned()
1126                    .left()
1127                    .into_any()
1128            })
1129            .constrained()
1130            .with_height(style.height)
1131            .contained()
1132            .with_style(row_container_style)
1133            .with_padding_left(padding)
1134            .into_any_named("project panel entry visual element")
1135    }
1136
1137    fn render_entry(
1138        entry_id: ProjectEntryId,
1139        details: EntryDetails,
1140        editor: &ViewHandle<Editor>,
1141        dragged_entry_destination: &mut Option<Arc<Path>>,
1142        theme: &theme::ProjectPanel,
1143        cx: &mut ViewContext<Self>,
1144    ) -> AnyElement<Self> {
1145        let kind = details.kind;
1146        let path = details.path.clone();
1147        let padding = theme.container.padding.left + details.depth as f32 * theme.indent_width;
1148
1149        let entry_style = if details.is_cut {
1150            &theme.cut_entry
1151        } else if details.is_ignored {
1152            &theme.ignored_entry
1153        } else {
1154            &theme.entry
1155        };
1156
1157        let show_editor = details.is_editing && !details.is_processing;
1158
1159        MouseEventHandler::<Self, _>::new(entry_id.to_usize(), cx, |state, cx| {
1160            let mut style = entry_style.style_for(state, details.is_selected).clone();
1161
1162            if cx
1163                .global::<DragAndDrop<Workspace>>()
1164                .currently_dragged::<ProjectEntryId>(cx.window_id())
1165                .is_some()
1166                && dragged_entry_destination
1167                    .as_ref()
1168                    .filter(|destination| details.path.starts_with(destination))
1169                    .is_some()
1170            {
1171                style = entry_style.active.clone().unwrap();
1172            }
1173
1174            let row_container_style = if show_editor {
1175                theme.filename_editor.container
1176            } else {
1177                style.container
1178            };
1179
1180            Self::render_entry_visual_element(
1181                &details,
1182                Some(editor),
1183                padding,
1184                row_container_style,
1185                &style,
1186                cx,
1187            )
1188        })
1189        .on_click(MouseButton::Left, move |event, this, cx| {
1190            if !show_editor {
1191                if kind == EntryKind::Dir {
1192                    this.toggle_expanded(entry_id, cx);
1193                } else {
1194                    this.open_entry(entry_id, event.click_count > 1, cx);
1195                }
1196            }
1197        })
1198        .on_down(MouseButton::Right, move |event, this, cx| {
1199            this.deploy_context_menu(event.position, entry_id, cx);
1200        })
1201        .on_up(MouseButton::Left, move |_, this, cx| {
1202            if let Some((_, dragged_entry)) = cx
1203                .global::<DragAndDrop<Workspace>>()
1204                .currently_dragged::<ProjectEntryId>(cx.window_id())
1205            {
1206                this.move_entry(
1207                    *dragged_entry,
1208                    entry_id,
1209                    matches!(details.kind, EntryKind::File(_)),
1210                    cx,
1211                );
1212            }
1213        })
1214        .on_move(move |_, this, cx| {
1215            if cx
1216                .global::<DragAndDrop<Workspace>>()
1217                .currently_dragged::<ProjectEntryId>(cx.window_id())
1218                .is_some()
1219            {
1220                this.dragged_entry_destination = if matches!(kind, EntryKind::File(_)) {
1221                    path.parent().map(|parent| Arc::from(parent))
1222                } else {
1223                    Some(path.clone())
1224                };
1225            }
1226        })
1227        .as_draggable(entry_id, {
1228            let row_container_style = theme.dragged_entry.container;
1229
1230            move |_, cx: &mut ViewContext<Workspace>| {
1231                let theme = cx.global::<Settings>().theme.clone();
1232                Self::render_entry_visual_element(
1233                    &details,
1234                    None,
1235                    padding,
1236                    row_container_style,
1237                    &theme.project_panel.dragged_entry,
1238                    cx,
1239                )
1240            }
1241        })
1242        .with_cursor_style(CursorStyle::PointingHand)
1243        .into_any_named("project panel entry")
1244    }
1245}
1246
1247impl View for ProjectPanel {
1248    fn ui_name() -> &'static str {
1249        "ProjectPanel"
1250    }
1251
1252    fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> gpui::AnyElement<Self> {
1253        enum ProjectPanel {}
1254        let theme = &cx.global::<Settings>().theme.project_panel;
1255        let mut container_style = theme.container;
1256        let padding = std::mem::take(&mut container_style.padding);
1257        let last_worktree_root_id = self.last_worktree_root_id;
1258
1259        let has_worktree = self.visible_entries.len() != 0;
1260
1261        if has_worktree {
1262            Stack::new()
1263                .with_child(
1264                    MouseEventHandler::<ProjectPanel, _>::new(0, cx, |_, cx| {
1265                        UniformList::new(
1266                            self.list.clone(),
1267                            self.visible_entries
1268                                .iter()
1269                                .map(|(_, worktree_entries)| worktree_entries.len())
1270                                .sum(),
1271                            cx,
1272                            move |this, range, items, cx| {
1273                                let theme = cx.global::<Settings>().theme.clone();
1274                                let mut dragged_entry_destination =
1275                                    this.dragged_entry_destination.clone();
1276                                this.for_each_visible_entry(range, cx, |id, details, cx| {
1277                                    items.push(Self::render_entry(
1278                                        id,
1279                                        details,
1280                                        &this.filename_editor,
1281                                        &mut dragged_entry_destination,
1282                                        &theme.project_panel,
1283                                        cx,
1284                                    ));
1285                                });
1286                                this.dragged_entry_destination = dragged_entry_destination;
1287                            },
1288                        )
1289                        .with_padding_top(padding.top)
1290                        .with_padding_bottom(padding.bottom)
1291                        .contained()
1292                        .with_style(container_style)
1293                        .expanded()
1294                    })
1295                    .on_down(MouseButton::Right, move |event, this, cx| {
1296                        // When deploying the context menu anywhere below the last project entry,
1297                        // act as if the user clicked the root of the last worktree.
1298                        if let Some(entry_id) = last_worktree_root_id {
1299                            this.deploy_context_menu(event.position, entry_id, cx);
1300                        }
1301                    }),
1302                )
1303                .with_child(ChildView::new(&self.context_menu, cx))
1304                .into_any_named("project panel")
1305        } else {
1306            Flex::column()
1307                .with_child(
1308                    MouseEventHandler::<Self, _>::new(2, cx, {
1309                        let button_style = theme.open_project_button.clone();
1310                        let context_menu_item_style =
1311                            cx.global::<Settings>().theme.context_menu.item.clone();
1312                        move |state, cx| {
1313                            let button_style = button_style.style_for(state, false).clone();
1314                            let context_menu_item =
1315                                context_menu_item_style.style_for(state, true).clone();
1316
1317                            theme::ui::keystroke_label(
1318                                "Open a project",
1319                                &button_style,
1320                                &context_menu_item.keystroke,
1321                                Box::new(workspace::Open),
1322                                cx,
1323                            )
1324                        }
1325                    })
1326                    .on_click(MouseButton::Left, move |_, this, cx| {
1327                        if let Some(workspace) = this.workspace.upgrade(cx) {
1328                            workspace.update(cx, |workspace, cx| {
1329                                if let Some(task) = workspace.open(&Default::default(), cx) {
1330                                    task.detach_and_log_err(cx);
1331                                }
1332                            })
1333                        }
1334                    })
1335                    .with_cursor_style(CursorStyle::PointingHand),
1336                )
1337                .contained()
1338                .with_style(container_style)
1339                .into_any_named("empty project panel")
1340        }
1341    }
1342
1343    fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
1344        Self::reset_to_default_keymap_context(keymap);
1345        keymap.add_identifier("menu");
1346    }
1347}
1348
1349impl Entity for ProjectPanel {
1350    type Event = Event;
1351}
1352
1353impl workspace::sidebar::SidebarItem for ProjectPanel {
1354    fn should_show_badge(&self, _: &AppContext) -> bool {
1355        false
1356    }
1357}
1358
1359impl ClipboardEntry {
1360    fn is_cut(&self) -> bool {
1361        matches!(self, Self::Cut { .. })
1362    }
1363
1364    fn entry_id(&self) -> ProjectEntryId {
1365        match self {
1366            ClipboardEntry::Copied { entry_id, .. } | ClipboardEntry::Cut { entry_id, .. } => {
1367                *entry_id
1368            }
1369        }
1370    }
1371
1372    fn worktree_id(&self) -> WorktreeId {
1373        match self {
1374            ClipboardEntry::Copied { worktree_id, .. }
1375            | ClipboardEntry::Cut { worktree_id, .. } => *worktree_id,
1376        }
1377    }
1378}
1379
1380#[cfg(test)]
1381mod tests {
1382    use super::*;
1383    use gpui::{TestAppContext, ViewHandle};
1384    use project::FakeFs;
1385    use serde_json::json;
1386    use std::{collections::HashSet, path::Path};
1387
1388    #[gpui::test]
1389    async fn test_visible_list(cx: &mut gpui::TestAppContext) {
1390        cx.foreground().forbid_parking();
1391        cx.update(|cx| {
1392            let settings = Settings::test(cx);
1393            cx.set_global(settings);
1394        });
1395
1396        let fs = FakeFs::new(cx.background());
1397        fs.insert_tree(
1398            "/root1",
1399            json!({
1400                ".dockerignore": "",
1401                ".git": {
1402                    "HEAD": "",
1403                },
1404                "a": {
1405                    "0": { "q": "", "r": "", "s": "" },
1406                    "1": { "t": "", "u": "" },
1407                    "2": { "v": "", "w": "", "x": "", "y": "" },
1408                },
1409                "b": {
1410                    "3": { "Q": "" },
1411                    "4": { "R": "", "S": "", "T": "", "U": "" },
1412                },
1413                "C": {
1414                    "5": {},
1415                    "6": { "V": "", "W": "" },
1416                    "7": { "X": "" },
1417                    "8": { "Y": {}, "Z": "" }
1418                }
1419            }),
1420        )
1421        .await;
1422        fs.insert_tree(
1423            "/root2",
1424            json!({
1425                "d": {
1426                    "9": ""
1427                },
1428                "e": {}
1429            }),
1430        )
1431        .await;
1432
1433        let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
1434        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1435        let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1436        assert_eq!(
1437            visible_entries_as_strings(&panel, 0..50, cx),
1438            &[
1439                "v root1",
1440                "    > .git",
1441                "    > a",
1442                "    > b",
1443                "    > C",
1444                "      .dockerignore",
1445                "v root2",
1446                "    > d",
1447                "    > e",
1448            ]
1449        );
1450
1451        toggle_expand_dir(&panel, "root1/b", cx);
1452        assert_eq!(
1453            visible_entries_as_strings(&panel, 0..50, cx),
1454            &[
1455                "v root1",
1456                "    > .git",
1457                "    > a",
1458                "    v b  <== selected",
1459                "        > 3",
1460                "        > 4",
1461                "    > C",
1462                "      .dockerignore",
1463                "v root2",
1464                "    > d",
1465                "    > e",
1466            ]
1467        );
1468
1469        assert_eq!(
1470            visible_entries_as_strings(&panel, 6..9, cx),
1471            &[
1472                //
1473                "    > C",
1474                "      .dockerignore",
1475                "v root2",
1476            ]
1477        );
1478    }
1479
1480    #[gpui::test(iterations = 30)]
1481    async fn test_editing_files(cx: &mut gpui::TestAppContext) {
1482        cx.foreground().forbid_parking();
1483        cx.update(|cx| {
1484            let settings = Settings::test(cx);
1485            cx.set_global(settings);
1486        });
1487
1488        let fs = FakeFs::new(cx.background());
1489        fs.insert_tree(
1490            "/root1",
1491            json!({
1492                ".dockerignore": "",
1493                ".git": {
1494                    "HEAD": "",
1495                },
1496                "a": {
1497                    "0": { "q": "", "r": "", "s": "" },
1498                    "1": { "t": "", "u": "" },
1499                    "2": { "v": "", "w": "", "x": "", "y": "" },
1500                },
1501                "b": {
1502                    "3": { "Q": "" },
1503                    "4": { "R": "", "S": "", "T": "", "U": "" },
1504                },
1505                "C": {
1506                    "5": {},
1507                    "6": { "V": "", "W": "" },
1508                    "7": { "X": "" },
1509                    "8": { "Y": {}, "Z": "" }
1510                }
1511            }),
1512        )
1513        .await;
1514        fs.insert_tree(
1515            "/root2",
1516            json!({
1517                "d": {
1518                    "9": ""
1519                },
1520                "e": {}
1521            }),
1522        )
1523        .await;
1524
1525        let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
1526        let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1527        let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1528
1529        select_path(&panel, "root1", cx);
1530        assert_eq!(
1531            visible_entries_as_strings(&panel, 0..10, cx),
1532            &[
1533                "v root1  <== selected",
1534                "    > .git",
1535                "    > a",
1536                "    > b",
1537                "    > C",
1538                "      .dockerignore",
1539                "v root2",
1540                "    > d",
1541                "    > e",
1542            ]
1543        );
1544
1545        // Add a file with the root folder selected. The filename editor is placed
1546        // before the first file in the root folder.
1547        panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
1548        cx.read_window(window_id, |cx| {
1549            let panel = panel.read(cx);
1550            assert!(panel.filename_editor.is_focused(cx));
1551        });
1552        assert_eq!(
1553            visible_entries_as_strings(&panel, 0..10, cx),
1554            &[
1555                "v root1",
1556                "    > .git",
1557                "    > a",
1558                "    > b",
1559                "    > C",
1560                "      [EDITOR: '']  <== selected",
1561                "      .dockerignore",
1562                "v root2",
1563                "    > d",
1564                "    > e",
1565            ]
1566        );
1567
1568        let confirm = panel.update(cx, |panel, cx| {
1569            panel
1570                .filename_editor
1571                .update(cx, |editor, cx| editor.set_text("the-new-filename", cx));
1572            panel.confirm(&Confirm, cx).unwrap()
1573        });
1574        assert_eq!(
1575            visible_entries_as_strings(&panel, 0..10, cx),
1576            &[
1577                "v root1",
1578                "    > .git",
1579                "    > a",
1580                "    > b",
1581                "    > C",
1582                "      [PROCESSING: 'the-new-filename']  <== selected",
1583                "      .dockerignore",
1584                "v root2",
1585                "    > d",
1586                "    > e",
1587            ]
1588        );
1589
1590        confirm.await.unwrap();
1591        assert_eq!(
1592            visible_entries_as_strings(&panel, 0..10, cx),
1593            &[
1594                "v root1",
1595                "    > .git",
1596                "    > a",
1597                "    > b",
1598                "    > C",
1599                "      .dockerignore",
1600                "      the-new-filename  <== selected",
1601                "v root2",
1602                "    > d",
1603                "    > e",
1604            ]
1605        );
1606
1607        select_path(&panel, "root1/b", cx);
1608        panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
1609        assert_eq!(
1610            visible_entries_as_strings(&panel, 0..10, cx),
1611            &[
1612                "v root1",
1613                "    > .git",
1614                "    > a",
1615                "    v b",
1616                "        > 3",
1617                "        > 4",
1618                "          [EDITOR: '']  <== selected",
1619                "    > C",
1620                "      .dockerignore",
1621                "      the-new-filename",
1622            ]
1623        );
1624
1625        panel
1626            .update(cx, |panel, cx| {
1627                panel
1628                    .filename_editor
1629                    .update(cx, |editor, cx| editor.set_text("another-filename", cx));
1630                panel.confirm(&Confirm, cx).unwrap()
1631            })
1632            .await
1633            .unwrap();
1634        assert_eq!(
1635            visible_entries_as_strings(&panel, 0..10, cx),
1636            &[
1637                "v root1",
1638                "    > .git",
1639                "    > a",
1640                "    v b",
1641                "        > 3",
1642                "        > 4",
1643                "          another-filename  <== selected",
1644                "    > C",
1645                "      .dockerignore",
1646                "      the-new-filename",
1647            ]
1648        );
1649
1650        select_path(&panel, "root1/b/another-filename", cx);
1651        panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
1652        assert_eq!(
1653            visible_entries_as_strings(&panel, 0..10, cx),
1654            &[
1655                "v root1",
1656                "    > .git",
1657                "    > a",
1658                "    v b",
1659                "        > 3",
1660                "        > 4",
1661                "          [EDITOR: 'another-filename']  <== selected",
1662                "    > C",
1663                "      .dockerignore",
1664                "      the-new-filename",
1665            ]
1666        );
1667
1668        let confirm = panel.update(cx, |panel, cx| {
1669            panel
1670                .filename_editor
1671                .update(cx, |editor, cx| editor.set_text("a-different-filename", cx));
1672            panel.confirm(&Confirm, cx).unwrap()
1673        });
1674        assert_eq!(
1675            visible_entries_as_strings(&panel, 0..10, cx),
1676            &[
1677                "v root1",
1678                "    > .git",
1679                "    > a",
1680                "    v b",
1681                "        > 3",
1682                "        > 4",
1683                "          [PROCESSING: 'a-different-filename']  <== selected",
1684                "    > C",
1685                "      .dockerignore",
1686                "      the-new-filename",
1687            ]
1688        );
1689
1690        confirm.await.unwrap();
1691        assert_eq!(
1692            visible_entries_as_strings(&panel, 0..10, cx),
1693            &[
1694                "v root1",
1695                "    > .git",
1696                "    > a",
1697                "    v b",
1698                "        > 3",
1699                "        > 4",
1700                "          a-different-filename  <== selected",
1701                "    > C",
1702                "      .dockerignore",
1703                "      the-new-filename",
1704            ]
1705        );
1706
1707        panel.update(cx, |panel, cx| panel.new_directory(&NewDirectory, cx));
1708        assert_eq!(
1709            visible_entries_as_strings(&panel, 0..10, cx),
1710            &[
1711                "v root1",
1712                "    > .git",
1713                "    > a",
1714                "    v b",
1715                "        > [EDITOR: '']  <== selected",
1716                "        > 3",
1717                "        > 4",
1718                "          a-different-filename",
1719                "    > C",
1720                "      .dockerignore",
1721            ]
1722        );
1723
1724        let confirm = panel.update(cx, |panel, cx| {
1725            panel
1726                .filename_editor
1727                .update(cx, |editor, cx| editor.set_text("new-dir", cx));
1728            panel.confirm(&Confirm, cx).unwrap()
1729        });
1730        panel.update(cx, |panel, cx| panel.select_next(&Default::default(), cx));
1731        assert_eq!(
1732            visible_entries_as_strings(&panel, 0..10, cx),
1733            &[
1734                "v root1",
1735                "    > .git",
1736                "    > a",
1737                "    v b",
1738                "        > [PROCESSING: 'new-dir']",
1739                "        > 3  <== selected",
1740                "        > 4",
1741                "          a-different-filename",
1742                "    > C",
1743                "      .dockerignore",
1744            ]
1745        );
1746
1747        confirm.await.unwrap();
1748        assert_eq!(
1749            visible_entries_as_strings(&panel, 0..10, cx),
1750            &[
1751                "v root1",
1752                "    > .git",
1753                "    > a",
1754                "    v b",
1755                "        > 3  <== selected",
1756                "        > 4",
1757                "        > new-dir",
1758                "          a-different-filename",
1759                "    > C",
1760                "      .dockerignore",
1761            ]
1762        );
1763
1764        panel.update(cx, |panel, cx| panel.rename(&Default::default(), cx));
1765        assert_eq!(
1766            visible_entries_as_strings(&panel, 0..10, cx),
1767            &[
1768                "v root1",
1769                "    > .git",
1770                "    > a",
1771                "    v b",
1772                "        > [EDITOR: '3']  <== selected",
1773                "        > 4",
1774                "        > new-dir",
1775                "          a-different-filename",
1776                "    > C",
1777                "      .dockerignore",
1778            ]
1779        );
1780
1781        // Dismiss the rename editor when it loses focus.
1782        workspace.update(cx, |_, cx| cx.focus_self());
1783        assert_eq!(
1784            visible_entries_as_strings(&panel, 0..10, cx),
1785            &[
1786                "v root1",
1787                "    > .git",
1788                "    > a",
1789                "    v b",
1790                "        > 3  <== selected",
1791                "        > 4",
1792                "        > new-dir",
1793                "          a-different-filename",
1794                "    > C",
1795                "      .dockerignore",
1796            ]
1797        );
1798    }
1799
1800    #[gpui::test]
1801    async fn test_copy_paste(cx: &mut gpui::TestAppContext) {
1802        cx.foreground().forbid_parking();
1803        cx.update(|cx| {
1804            let settings = Settings::test(cx);
1805            cx.set_global(settings);
1806        });
1807
1808        let fs = FakeFs::new(cx.background());
1809        fs.insert_tree(
1810            "/root1",
1811            json!({
1812                "one.two.txt": "",
1813                "one.txt": ""
1814            }),
1815        )
1816        .await;
1817
1818        let project = Project::test(fs.clone(), ["/root1".as_ref()], cx).await;
1819        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1820        let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1821
1822        panel.update(cx, |panel, cx| {
1823            panel.select_next(&Default::default(), cx);
1824            panel.select_next(&Default::default(), cx);
1825        });
1826
1827        assert_eq!(
1828            visible_entries_as_strings(&panel, 0..50, cx),
1829            &[
1830                //
1831                "v root1",
1832                "      one.two.txt  <== selected",
1833                "      one.txt",
1834            ]
1835        );
1836
1837        // Regression test - file name is created correctly when
1838        // the copied file's name contains multiple dots.
1839        panel.update(cx, |panel, cx| {
1840            panel.copy(&Default::default(), cx);
1841            panel.paste(&Default::default(), cx);
1842        });
1843        cx.foreground().run_until_parked();
1844
1845        assert_eq!(
1846            visible_entries_as_strings(&panel, 0..50, cx),
1847            &[
1848                //
1849                "v root1",
1850                "      one.two copy.txt",
1851                "      one.two.txt  <== selected",
1852                "      one.txt",
1853            ]
1854        );
1855
1856        panel.update(cx, |panel, cx| {
1857            panel.paste(&Default::default(), cx);
1858        });
1859        cx.foreground().run_until_parked();
1860
1861        assert_eq!(
1862            visible_entries_as_strings(&panel, 0..50, cx),
1863            &[
1864                //
1865                "v root1",
1866                "      one.two copy 1.txt",
1867                "      one.two copy.txt",
1868                "      one.two.txt  <== selected",
1869                "      one.txt",
1870            ]
1871        );
1872    }
1873
1874    fn toggle_expand_dir(
1875        panel: &ViewHandle<ProjectPanel>,
1876        path: impl AsRef<Path>,
1877        cx: &mut TestAppContext,
1878    ) {
1879        let path = path.as_ref();
1880        panel.update(cx, |panel, cx| {
1881            for worktree in panel.project.read(cx).worktrees(cx).collect::<Vec<_>>() {
1882                let worktree = worktree.read(cx);
1883                if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
1884                    let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
1885                    panel.toggle_expanded(entry_id, cx);
1886                    return;
1887                }
1888            }
1889            panic!("no worktree for path {:?}", path);
1890        });
1891    }
1892
1893    fn select_path(
1894        panel: &ViewHandle<ProjectPanel>,
1895        path: impl AsRef<Path>,
1896        cx: &mut TestAppContext,
1897    ) {
1898        let path = path.as_ref();
1899        panel.update(cx, |panel, cx| {
1900            for worktree in panel.project.read(cx).worktrees(cx).collect::<Vec<_>>() {
1901                let worktree = worktree.read(cx);
1902                if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
1903                    let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
1904                    panel.selection = Some(Selection {
1905                        worktree_id: worktree.id(),
1906                        entry_id,
1907                    });
1908                    return;
1909                }
1910            }
1911            panic!("no worktree for path {:?}", path);
1912        });
1913    }
1914
1915    fn visible_entries_as_strings(
1916        panel: &ViewHandle<ProjectPanel>,
1917        range: Range<usize>,
1918        cx: &mut TestAppContext,
1919    ) -> Vec<String> {
1920        let mut result = Vec::new();
1921        let mut project_entries = HashSet::new();
1922        let mut has_editor = false;
1923
1924        panel.update(cx, |panel, cx| {
1925            panel.for_each_visible_entry(range, cx, |project_entry, details, _| {
1926                if details.is_editing {
1927                    assert!(!has_editor, "duplicate editor entry");
1928                    has_editor = true;
1929                } else {
1930                    assert!(
1931                        project_entries.insert(project_entry),
1932                        "duplicate project entry {:?} {:?}",
1933                        project_entry,
1934                        details
1935                    );
1936                }
1937
1938                let indent = "    ".repeat(details.depth);
1939                let icon = if matches!(details.kind, EntryKind::Dir | EntryKind::PendingDir) {
1940                    if details.is_expanded {
1941                        "v "
1942                    } else {
1943                        "> "
1944                    }
1945                } else {
1946                    "  "
1947                };
1948                let name = if details.is_editing {
1949                    format!("[EDITOR: '{}']", details.filename)
1950                } else if details.is_processing {
1951                    format!("[PROCESSING: '{}']", details.filename)
1952                } else {
1953                    details.filename.clone()
1954                };
1955                let selected = if details.is_selected {
1956                    "  <== selected"
1957                } else {
1958                    ""
1959                };
1960                result.push(format!("{indent}{icon}{name}{selected}"));
1961            });
1962        });
1963
1964        result
1965    }
1966}