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