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