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