project_panel.rs

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