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