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