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 in &visible_worktree_entries[entry_range] {
1015 let path = &entry.path;
1016 let status = (entry.path.parent().is_some() && !entry.is_ignored)
1017 .then(|| {
1018 snapshot
1019 .repo_for(path)
1020 .and_then(|entry| entry.status_for_path(&snapshot, path))
1021 })
1022 .flatten();
1023
1024 let mut details = EntryDetails {
1025 filename: entry
1026 .path
1027 .file_name()
1028 .unwrap_or(root_name)
1029 .to_string_lossy()
1030 .to_string(),
1031 path: entry.path.clone(),
1032 depth: entry.path.components().count(),
1033 kind: entry.kind,
1034 is_ignored: entry.is_ignored,
1035 is_expanded: expanded_entry_ids.binary_search(&entry.id).is_ok(),
1036 is_selected: self.selection.map_or(false, |e| {
1037 e.worktree_id == snapshot.id() && e.entry_id == entry.id
1038 }),
1039 is_editing: false,
1040 is_processing: false,
1041 is_cut: self
1042 .clipboard_entry
1043 .map_or(false, |e| e.is_cut() && e.entry_id() == entry.id),
1044 git_status: status,
1045 };
1046
1047 if let Some(edit_state) = &self.edit_state {
1048 let is_edited_entry = if edit_state.is_new_entry {
1049 entry.id == NEW_ENTRY_ID
1050 } else {
1051 entry.id == edit_state.entry_id
1052 };
1053
1054 if is_edited_entry {
1055 if let Some(processing_filename) = &edit_state.processing_filename {
1056 details.is_processing = true;
1057 details.filename.clear();
1058 details.filename.push_str(processing_filename);
1059 } else {
1060 if edit_state.is_new_entry {
1061 details.filename.clear();
1062 }
1063 details.is_editing = true;
1064 }
1065 }
1066 }
1067
1068 callback(entry.id, details, cx);
1069 }
1070 }
1071 ix = end_ix;
1072 }
1073 }
1074
1075 fn render_entry_visual_element<V: View>(
1076 details: &EntryDetails,
1077 editor: Option<&ViewHandle<Editor>>,
1078 padding: f32,
1079 row_container_style: ContainerStyle,
1080 style: &ProjectPanelEntry,
1081 cx: &mut ViewContext<V>,
1082 ) -> AnyElement<V> {
1083 let kind = details.kind;
1084 let show_editor = details.is_editing && !details.is_processing;
1085
1086 Flex::row()
1087 .with_child(
1088 if kind == EntryKind::Dir {
1089 if details.is_expanded {
1090 Svg::new("icons/chevron_down_8.svg").with_color(style.icon_color)
1091 } else {
1092 Svg::new("icons/chevron_right_8.svg").with_color(style.icon_color)
1093 }
1094 .constrained()
1095 } else {
1096 Empty::new().constrained()
1097 }
1098 .with_max_width(style.icon_size)
1099 .with_max_height(style.icon_size)
1100 .aligned()
1101 .constrained()
1102 .with_width(style.icon_size),
1103 )
1104 .with_child(if show_editor && editor.is_some() {
1105 ChildView::new(editor.as_ref().unwrap(), cx)
1106 .contained()
1107 .with_margin_left(style.icon_spacing)
1108 .aligned()
1109 .left()
1110 .flex(1.0, true)
1111 .into_any()
1112 } else {
1113 ComponentHost::new(FileName::new(
1114 details.filename.clone(),
1115 details.git_status,
1116 FileName::style(style.text.clone(), &cx.global::<Settings>().theme),
1117 ))
1118 .contained()
1119 .with_margin_left(style.icon_spacing)
1120 .aligned()
1121 .left()
1122 .into_any()
1123 })
1124 .constrained()
1125 .with_height(style.height)
1126 .contained()
1127 .with_style(row_container_style)
1128 .with_padding_left(padding)
1129 .into_any_named("project panel entry visual element")
1130 }
1131
1132 fn render_entry(
1133 entry_id: ProjectEntryId,
1134 details: EntryDetails,
1135 editor: &ViewHandle<Editor>,
1136 dragged_entry_destination: &mut Option<Arc<Path>>,
1137 theme: &theme::ProjectPanel,
1138 cx: &mut ViewContext<Self>,
1139 ) -> AnyElement<Self> {
1140 let kind = details.kind;
1141 let path = details.path.clone();
1142 let padding = theme.container.padding.left + details.depth as f32 * theme.indent_width;
1143
1144 let entry_style = if details.is_cut {
1145 &theme.cut_entry
1146 } else if details.is_ignored {
1147 &theme.ignored_entry
1148 } else {
1149 &theme.entry
1150 };
1151
1152 let show_editor = details.is_editing && !details.is_processing;
1153
1154 MouseEventHandler::<Self, _>::new(entry_id.to_usize(), cx, |state, cx| {
1155 let mut style = entry_style.style_for(state, details.is_selected).clone();
1156
1157 if cx
1158 .global::<DragAndDrop<Workspace>>()
1159 .currently_dragged::<ProjectEntryId>(cx.window_id())
1160 .is_some()
1161 && dragged_entry_destination
1162 .as_ref()
1163 .filter(|destination| details.path.starts_with(destination))
1164 .is_some()
1165 {
1166 style = entry_style.active.clone().unwrap();
1167 }
1168
1169 let row_container_style = if show_editor {
1170 theme.filename_editor.container
1171 } else {
1172 style.container
1173 };
1174
1175 Self::render_entry_visual_element(
1176 &details,
1177 Some(editor),
1178 padding,
1179 row_container_style,
1180 &style,
1181 cx,
1182 )
1183 })
1184 .on_click(MouseButton::Left, move |event, this, cx| {
1185 if !show_editor {
1186 if kind == EntryKind::Dir {
1187 this.toggle_expanded(entry_id, cx);
1188 } else {
1189 this.open_entry(entry_id, event.click_count > 1, cx);
1190 }
1191 }
1192 })
1193 .on_down(MouseButton::Right, move |event, this, cx| {
1194 this.deploy_context_menu(event.position, entry_id, cx);
1195 })
1196 .on_up(MouseButton::Left, move |_, this, cx| {
1197 if let Some((_, dragged_entry)) = cx
1198 .global::<DragAndDrop<Workspace>>()
1199 .currently_dragged::<ProjectEntryId>(cx.window_id())
1200 {
1201 this.move_entry(
1202 *dragged_entry,
1203 entry_id,
1204 matches!(details.kind, EntryKind::File(_)),
1205 cx,
1206 );
1207 }
1208 })
1209 .on_move(move |_, this, cx| {
1210 if cx
1211 .global::<DragAndDrop<Workspace>>()
1212 .currently_dragged::<ProjectEntryId>(cx.window_id())
1213 .is_some()
1214 {
1215 this.dragged_entry_destination = if matches!(kind, EntryKind::File(_)) {
1216 path.parent().map(|parent| Arc::from(parent))
1217 } else {
1218 Some(path.clone())
1219 };
1220 }
1221 })
1222 .as_draggable(entry_id, {
1223 let row_container_style = theme.dragged_entry.container;
1224
1225 move |_, cx: &mut ViewContext<Workspace>| {
1226 let theme = cx.global::<Settings>().theme.clone();
1227 Self::render_entry_visual_element(
1228 &details,
1229 None,
1230 padding,
1231 row_container_style,
1232 &theme.project_panel.dragged_entry,
1233 cx,
1234 )
1235 }
1236 })
1237 .with_cursor_style(CursorStyle::PointingHand)
1238 .into_any_named("project panel entry")
1239 }
1240}
1241
1242impl View for ProjectPanel {
1243 fn ui_name() -> &'static str {
1244 "ProjectPanel"
1245 }
1246
1247 fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> gpui::AnyElement<Self> {
1248 enum ProjectPanel {}
1249 let theme = &cx.global::<Settings>().theme.project_panel;
1250 let mut container_style = theme.container;
1251 let padding = std::mem::take(&mut container_style.padding);
1252 let last_worktree_root_id = self.last_worktree_root_id;
1253
1254 let has_worktree = self.visible_entries.len() != 0;
1255
1256 if has_worktree {
1257 Stack::new()
1258 .with_child(
1259 MouseEventHandler::<ProjectPanel, _>::new(0, cx, |_, cx| {
1260 UniformList::new(
1261 self.list.clone(),
1262 self.visible_entries
1263 .iter()
1264 .map(|(_, worktree_entries)| worktree_entries.len())
1265 .sum(),
1266 cx,
1267 move |this, range, items, cx| {
1268 let theme = cx.global::<Settings>().theme.clone();
1269 let mut dragged_entry_destination =
1270 this.dragged_entry_destination.clone();
1271 this.for_each_visible_entry(range, cx, |id, details, cx| {
1272 items.push(Self::render_entry(
1273 id,
1274 details,
1275 &this.filename_editor,
1276 &mut dragged_entry_destination,
1277 &theme.project_panel,
1278 cx,
1279 ));
1280 });
1281 this.dragged_entry_destination = dragged_entry_destination;
1282 },
1283 )
1284 .with_padding_top(padding.top)
1285 .with_padding_bottom(padding.bottom)
1286 .contained()
1287 .with_style(container_style)
1288 .expanded()
1289 })
1290 .on_down(MouseButton::Right, move |event, this, cx| {
1291 // When deploying the context menu anywhere below the last project entry,
1292 // act as if the user clicked the root of the last worktree.
1293 if let Some(entry_id) = last_worktree_root_id {
1294 this.deploy_context_menu(event.position, entry_id, cx);
1295 }
1296 }),
1297 )
1298 .with_child(ChildView::new(&self.context_menu, cx))
1299 .into_any_named("project panel")
1300 } else {
1301 Flex::column()
1302 .with_child(
1303 MouseEventHandler::<Self, _>::new(2, cx, {
1304 let button_style = theme.open_project_button.clone();
1305 let context_menu_item_style =
1306 cx.global::<Settings>().theme.context_menu.item.clone();
1307 move |state, cx| {
1308 let button_style = button_style.style_for(state, false).clone();
1309 let context_menu_item =
1310 context_menu_item_style.style_for(state, true).clone();
1311
1312 theme::ui::keystroke_label(
1313 "Open a project",
1314 &button_style,
1315 &context_menu_item.keystroke,
1316 Box::new(workspace::Open),
1317 cx,
1318 )
1319 }
1320 })
1321 .on_click(MouseButton::Left, move |_, this, cx| {
1322 if let Some(workspace) = this.workspace.upgrade(cx) {
1323 workspace.update(cx, |workspace, cx| {
1324 if let Some(task) = workspace.open(&Default::default(), cx) {
1325 task.detach_and_log_err(cx);
1326 }
1327 })
1328 }
1329 })
1330 .with_cursor_style(CursorStyle::PointingHand),
1331 )
1332 .contained()
1333 .with_style(container_style)
1334 .into_any_named("empty project panel")
1335 }
1336 }
1337
1338 fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
1339 Self::reset_to_default_keymap_context(keymap);
1340 keymap.add_identifier("menu");
1341 }
1342}
1343
1344impl Entity for ProjectPanel {
1345 type Event = Event;
1346}
1347
1348impl workspace::sidebar::SidebarItem for ProjectPanel {
1349 fn should_show_badge(&self, _: &AppContext) -> bool {
1350 false
1351 }
1352}
1353
1354impl ClipboardEntry {
1355 fn is_cut(&self) -> bool {
1356 matches!(self, Self::Cut { .. })
1357 }
1358
1359 fn entry_id(&self) -> ProjectEntryId {
1360 match self {
1361 ClipboardEntry::Copied { entry_id, .. } | ClipboardEntry::Cut { entry_id, .. } => {
1362 *entry_id
1363 }
1364 }
1365 }
1366
1367 fn worktree_id(&self) -> WorktreeId {
1368 match self {
1369 ClipboardEntry::Copied { worktree_id, .. }
1370 | ClipboardEntry::Cut { worktree_id, .. } => *worktree_id,
1371 }
1372 }
1373}
1374
1375#[cfg(test)]
1376mod tests {
1377 use super::*;
1378 use gpui::{TestAppContext, ViewHandle};
1379 use project::FakeFs;
1380 use serde_json::json;
1381 use std::{collections::HashSet, path::Path};
1382
1383 #[gpui::test]
1384 async fn test_visible_list(cx: &mut gpui::TestAppContext) {
1385 cx.foreground().forbid_parking();
1386 cx.update(|cx| {
1387 let settings = Settings::test(cx);
1388 cx.set_global(settings);
1389 });
1390
1391 let fs = FakeFs::new(cx.background());
1392 fs.insert_tree(
1393 "/root1",
1394 json!({
1395 ".dockerignore": "",
1396 ".git": {
1397 "HEAD": "",
1398 },
1399 "a": {
1400 "0": { "q": "", "r": "", "s": "" },
1401 "1": { "t": "", "u": "" },
1402 "2": { "v": "", "w": "", "x": "", "y": "" },
1403 },
1404 "b": {
1405 "3": { "Q": "" },
1406 "4": { "R": "", "S": "", "T": "", "U": "" },
1407 },
1408 "C": {
1409 "5": {},
1410 "6": { "V": "", "W": "" },
1411 "7": { "X": "" },
1412 "8": { "Y": {}, "Z": "" }
1413 }
1414 }),
1415 )
1416 .await;
1417 fs.insert_tree(
1418 "/root2",
1419 json!({
1420 "d": {
1421 "9": ""
1422 },
1423 "e": {}
1424 }),
1425 )
1426 .await;
1427
1428 let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
1429 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1430 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1431 assert_eq!(
1432 visible_entries_as_strings(&panel, 0..50, cx),
1433 &[
1434 "v root1",
1435 " > .git",
1436 " > a",
1437 " > b",
1438 " > C",
1439 " .dockerignore",
1440 "v root2",
1441 " > d",
1442 " > e",
1443 ]
1444 );
1445
1446 toggle_expand_dir(&panel, "root1/b", cx);
1447 assert_eq!(
1448 visible_entries_as_strings(&panel, 0..50, cx),
1449 &[
1450 "v root1",
1451 " > .git",
1452 " > a",
1453 " v b <== selected",
1454 " > 3",
1455 " > 4",
1456 " > C",
1457 " .dockerignore",
1458 "v root2",
1459 " > d",
1460 " > e",
1461 ]
1462 );
1463
1464 assert_eq!(
1465 visible_entries_as_strings(&panel, 6..9, cx),
1466 &[
1467 //
1468 " > C",
1469 " .dockerignore",
1470 "v root2",
1471 ]
1472 );
1473 }
1474
1475 #[gpui::test(iterations = 30)]
1476 async fn test_editing_files(cx: &mut gpui::TestAppContext) {
1477 cx.foreground().forbid_parking();
1478 cx.update(|cx| {
1479 let settings = Settings::test(cx);
1480 cx.set_global(settings);
1481 });
1482
1483 let fs = FakeFs::new(cx.background());
1484 fs.insert_tree(
1485 "/root1",
1486 json!({
1487 ".dockerignore": "",
1488 ".git": {
1489 "HEAD": "",
1490 },
1491 "a": {
1492 "0": { "q": "", "r": "", "s": "" },
1493 "1": { "t": "", "u": "" },
1494 "2": { "v": "", "w": "", "x": "", "y": "" },
1495 },
1496 "b": {
1497 "3": { "Q": "" },
1498 "4": { "R": "", "S": "", "T": "", "U": "" },
1499 },
1500 "C": {
1501 "5": {},
1502 "6": { "V": "", "W": "" },
1503 "7": { "X": "" },
1504 "8": { "Y": {}, "Z": "" }
1505 }
1506 }),
1507 )
1508 .await;
1509 fs.insert_tree(
1510 "/root2",
1511 json!({
1512 "d": {
1513 "9": ""
1514 },
1515 "e": {}
1516 }),
1517 )
1518 .await;
1519
1520 let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
1521 let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1522 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1523
1524 select_path(&panel, "root1", cx);
1525 assert_eq!(
1526 visible_entries_as_strings(&panel, 0..10, cx),
1527 &[
1528 "v root1 <== selected",
1529 " > .git",
1530 " > a",
1531 " > b",
1532 " > C",
1533 " .dockerignore",
1534 "v root2",
1535 " > d",
1536 " > e",
1537 ]
1538 );
1539
1540 // Add a file with the root folder selected. The filename editor is placed
1541 // before the first file in the root folder.
1542 panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
1543 cx.read_window(window_id, |cx| {
1544 let panel = panel.read(cx);
1545 assert!(panel.filename_editor.is_focused(cx));
1546 });
1547 assert_eq!(
1548 visible_entries_as_strings(&panel, 0..10, cx),
1549 &[
1550 "v root1",
1551 " > .git",
1552 " > a",
1553 " > b",
1554 " > C",
1555 " [EDITOR: ''] <== selected",
1556 " .dockerignore",
1557 "v root2",
1558 " > d",
1559 " > e",
1560 ]
1561 );
1562
1563 let confirm = panel.update(cx, |panel, cx| {
1564 panel
1565 .filename_editor
1566 .update(cx, |editor, cx| editor.set_text("the-new-filename", cx));
1567 panel.confirm(&Confirm, cx).unwrap()
1568 });
1569 assert_eq!(
1570 visible_entries_as_strings(&panel, 0..10, cx),
1571 &[
1572 "v root1",
1573 " > .git",
1574 " > a",
1575 " > b",
1576 " > C",
1577 " [PROCESSING: 'the-new-filename'] <== selected",
1578 " .dockerignore",
1579 "v root2",
1580 " > d",
1581 " > e",
1582 ]
1583 );
1584
1585 confirm.await.unwrap();
1586 assert_eq!(
1587 visible_entries_as_strings(&panel, 0..10, cx),
1588 &[
1589 "v root1",
1590 " > .git",
1591 " > a",
1592 " > b",
1593 " > C",
1594 " .dockerignore",
1595 " the-new-filename <== selected",
1596 "v root2",
1597 " > d",
1598 " > e",
1599 ]
1600 );
1601
1602 select_path(&panel, "root1/b", cx);
1603 panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
1604 assert_eq!(
1605 visible_entries_as_strings(&panel, 0..10, cx),
1606 &[
1607 "v root1",
1608 " > .git",
1609 " > a",
1610 " v b",
1611 " > 3",
1612 " > 4",
1613 " [EDITOR: ''] <== selected",
1614 " > C",
1615 " .dockerignore",
1616 " the-new-filename",
1617 ]
1618 );
1619
1620 panel
1621 .update(cx, |panel, cx| {
1622 panel
1623 .filename_editor
1624 .update(cx, |editor, cx| editor.set_text("another-filename", cx));
1625 panel.confirm(&Confirm, cx).unwrap()
1626 })
1627 .await
1628 .unwrap();
1629 assert_eq!(
1630 visible_entries_as_strings(&panel, 0..10, cx),
1631 &[
1632 "v root1",
1633 " > .git",
1634 " > a",
1635 " v b",
1636 " > 3",
1637 " > 4",
1638 " another-filename <== selected",
1639 " > C",
1640 " .dockerignore",
1641 " the-new-filename",
1642 ]
1643 );
1644
1645 select_path(&panel, "root1/b/another-filename", cx);
1646 panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
1647 assert_eq!(
1648 visible_entries_as_strings(&panel, 0..10, cx),
1649 &[
1650 "v root1",
1651 " > .git",
1652 " > a",
1653 " v b",
1654 " > 3",
1655 " > 4",
1656 " [EDITOR: 'another-filename'] <== selected",
1657 " > C",
1658 " .dockerignore",
1659 " the-new-filename",
1660 ]
1661 );
1662
1663 let confirm = panel.update(cx, |panel, cx| {
1664 panel
1665 .filename_editor
1666 .update(cx, |editor, cx| editor.set_text("a-different-filename", cx));
1667 panel.confirm(&Confirm, cx).unwrap()
1668 });
1669 assert_eq!(
1670 visible_entries_as_strings(&panel, 0..10, cx),
1671 &[
1672 "v root1",
1673 " > .git",
1674 " > a",
1675 " v b",
1676 " > 3",
1677 " > 4",
1678 " [PROCESSING: 'a-different-filename'] <== selected",
1679 " > C",
1680 " .dockerignore",
1681 " the-new-filename",
1682 ]
1683 );
1684
1685 confirm.await.unwrap();
1686 assert_eq!(
1687 visible_entries_as_strings(&panel, 0..10, cx),
1688 &[
1689 "v root1",
1690 " > .git",
1691 " > a",
1692 " v b",
1693 " > 3",
1694 " > 4",
1695 " a-different-filename <== selected",
1696 " > C",
1697 " .dockerignore",
1698 " the-new-filename",
1699 ]
1700 );
1701
1702 panel.update(cx, |panel, cx| panel.new_directory(&NewDirectory, cx));
1703 assert_eq!(
1704 visible_entries_as_strings(&panel, 0..10, cx),
1705 &[
1706 "v root1",
1707 " > .git",
1708 " > a",
1709 " v b",
1710 " > [EDITOR: ''] <== selected",
1711 " > 3",
1712 " > 4",
1713 " a-different-filename",
1714 " > C",
1715 " .dockerignore",
1716 ]
1717 );
1718
1719 let confirm = panel.update(cx, |panel, cx| {
1720 panel
1721 .filename_editor
1722 .update(cx, |editor, cx| editor.set_text("new-dir", cx));
1723 panel.confirm(&Confirm, cx).unwrap()
1724 });
1725 panel.update(cx, |panel, cx| panel.select_next(&Default::default(), cx));
1726 assert_eq!(
1727 visible_entries_as_strings(&panel, 0..10, cx),
1728 &[
1729 "v root1",
1730 " > .git",
1731 " > a",
1732 " v b",
1733 " > [PROCESSING: 'new-dir']",
1734 " > 3 <== selected",
1735 " > 4",
1736 " a-different-filename",
1737 " > C",
1738 " .dockerignore",
1739 ]
1740 );
1741
1742 confirm.await.unwrap();
1743 assert_eq!(
1744 visible_entries_as_strings(&panel, 0..10, cx),
1745 &[
1746 "v root1",
1747 " > .git",
1748 " > a",
1749 " v b",
1750 " > 3 <== selected",
1751 " > 4",
1752 " > new-dir",
1753 " a-different-filename",
1754 " > C",
1755 " .dockerignore",
1756 ]
1757 );
1758
1759 panel.update(cx, |panel, cx| panel.rename(&Default::default(), cx));
1760 assert_eq!(
1761 visible_entries_as_strings(&panel, 0..10, cx),
1762 &[
1763 "v root1",
1764 " > .git",
1765 " > a",
1766 " v b",
1767 " > [EDITOR: '3'] <== selected",
1768 " > 4",
1769 " > new-dir",
1770 " a-different-filename",
1771 " > C",
1772 " .dockerignore",
1773 ]
1774 );
1775
1776 // Dismiss the rename editor when it loses focus.
1777 workspace.update(cx, |_, cx| cx.focus_self());
1778 assert_eq!(
1779 visible_entries_as_strings(&panel, 0..10, cx),
1780 &[
1781 "v root1",
1782 " > .git",
1783 " > a",
1784 " v b",
1785 " > 3 <== selected",
1786 " > 4",
1787 " > new-dir",
1788 " a-different-filename",
1789 " > C",
1790 " .dockerignore",
1791 ]
1792 );
1793 }
1794
1795 #[gpui::test]
1796 async fn test_copy_paste(cx: &mut gpui::TestAppContext) {
1797 cx.foreground().forbid_parking();
1798 cx.update(|cx| {
1799 let settings = Settings::test(cx);
1800 cx.set_global(settings);
1801 });
1802
1803 let fs = FakeFs::new(cx.background());
1804 fs.insert_tree(
1805 "/root1",
1806 json!({
1807 "one.two.txt": "",
1808 "one.txt": ""
1809 }),
1810 )
1811 .await;
1812
1813 let project = Project::test(fs.clone(), ["/root1".as_ref()], cx).await;
1814 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1815 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1816
1817 panel.update(cx, |panel, cx| {
1818 panel.select_next(&Default::default(), cx);
1819 panel.select_next(&Default::default(), cx);
1820 });
1821
1822 assert_eq!(
1823 visible_entries_as_strings(&panel, 0..50, cx),
1824 &[
1825 //
1826 "v root1",
1827 " one.two.txt <== selected",
1828 " one.txt",
1829 ]
1830 );
1831
1832 // Regression test - file name is created correctly when
1833 // the copied file's name contains multiple dots.
1834 panel.update(cx, |panel, cx| {
1835 panel.copy(&Default::default(), cx);
1836 panel.paste(&Default::default(), cx);
1837 });
1838 cx.foreground().run_until_parked();
1839
1840 assert_eq!(
1841 visible_entries_as_strings(&panel, 0..50, cx),
1842 &[
1843 //
1844 "v root1",
1845 " one.two copy.txt",
1846 " one.two.txt <== selected",
1847 " one.txt",
1848 ]
1849 );
1850
1851 panel.update(cx, |panel, cx| {
1852 panel.paste(&Default::default(), cx);
1853 });
1854 cx.foreground().run_until_parked();
1855
1856 assert_eq!(
1857 visible_entries_as_strings(&panel, 0..50, cx),
1858 &[
1859 //
1860 "v root1",
1861 " one.two copy 1.txt",
1862 " one.two copy.txt",
1863 " one.two.txt <== selected",
1864 " one.txt",
1865 ]
1866 );
1867 }
1868
1869 fn toggle_expand_dir(
1870 panel: &ViewHandle<ProjectPanel>,
1871 path: impl AsRef<Path>,
1872 cx: &mut TestAppContext,
1873 ) {
1874 let path = path.as_ref();
1875 panel.update(cx, |panel, cx| {
1876 for worktree in panel.project.read(cx).worktrees(cx).collect::<Vec<_>>() {
1877 let worktree = worktree.read(cx);
1878 if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
1879 let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
1880 panel.toggle_expanded(entry_id, cx);
1881 return;
1882 }
1883 }
1884 panic!("no worktree for path {:?}", path);
1885 });
1886 }
1887
1888 fn select_path(
1889 panel: &ViewHandle<ProjectPanel>,
1890 path: impl AsRef<Path>,
1891 cx: &mut TestAppContext,
1892 ) {
1893 let path = path.as_ref();
1894 panel.update(cx, |panel, cx| {
1895 for worktree in panel.project.read(cx).worktrees(cx).collect::<Vec<_>>() {
1896 let worktree = worktree.read(cx);
1897 if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
1898 let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
1899 panel.selection = Some(Selection {
1900 worktree_id: worktree.id(),
1901 entry_id,
1902 });
1903 return;
1904 }
1905 }
1906 panic!("no worktree for path {:?}", path);
1907 });
1908 }
1909
1910 fn visible_entries_as_strings(
1911 panel: &ViewHandle<ProjectPanel>,
1912 range: Range<usize>,
1913 cx: &mut TestAppContext,
1914 ) -> Vec<String> {
1915 let mut result = Vec::new();
1916 let mut project_entries = HashSet::new();
1917 let mut has_editor = false;
1918
1919 panel.update(cx, |panel, cx| {
1920 panel.for_each_visible_entry(range, cx, |project_entry, details, _| {
1921 if details.is_editing {
1922 assert!(!has_editor, "duplicate editor entry");
1923 has_editor = true;
1924 } else {
1925 assert!(
1926 project_entries.insert(project_entry),
1927 "duplicate project entry {:?} {:?}",
1928 project_entry,
1929 details
1930 );
1931 }
1932
1933 let indent = " ".repeat(details.depth);
1934 let icon = if matches!(details.kind, EntryKind::Dir | EntryKind::PendingDir) {
1935 if details.is_expanded {
1936 "v "
1937 } else {
1938 "> "
1939 }
1940 } else {
1941 " "
1942 };
1943 let name = if details.is_editing {
1944 format!("[EDITOR: '{}']", details.filename)
1945 } else if details.is_processing {
1946 format!("[PROCESSING: '{}']", details.filename)
1947 } else {
1948 details.filename.clone()
1949 };
1950 let selected = if details.is_selected {
1951 " <== selected"
1952 } else {
1953 ""
1954 };
1955 result.push(format!("{indent}{icon}{name}{selected}"));
1956 });
1957 });
1958
1959 result
1960 }
1961}