1mod project_panel_settings;
2
3use context_menu::{ContextMenu, ContextMenuItem};
4use db::kvp::KEY_VALUE_STORE;
5use drag_and_drop::{DragAndDrop, Draggable};
6use editor::{Cancel, Editor};
7use futures::stream::StreamExt;
8use gpui::{
9 actions,
10 anyhow::{self, anyhow, Result},
11 elements::{
12 AnchorCorner, ChildView, ContainerStyle, Empty, Flex, Label, MouseEventHandler,
13 ParentElement, ScrollTarget, Stack, Svg, UniformList, UniformListState,
14 },
15 geometry::vector::Vector2F,
16 keymap_matcher::KeymapContext,
17 platform::{CursorStyle, MouseButton, PromptLevel},
18 Action, AnyElement, AppContext, AsyncAppContext, ClipboardItem, Element, Entity, ModelHandle,
19 Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
20};
21use menu::{Confirm, SelectNext, SelectPrev};
22use project::{
23 repository::GitFileStatus, Entry, EntryKind, Fs, Project, ProjectEntryId, ProjectPath,
24 Worktree, WorktreeId,
25};
26use project_panel_settings::{ProjectPanelDockPosition, ProjectPanelSettings};
27use serde::{Deserialize, Serialize};
28use settings::SettingsStore;
29use std::{
30 cmp::Ordering,
31 collections::{hash_map, HashMap},
32 ffi::OsStr,
33 ops::Range,
34 path::Path,
35 sync::Arc,
36};
37use theme::ProjectPanelEntry;
38use unicase::UniCase;
39use util::{ResultExt, TryFutureExt};
40use workspace::{
41 dock::{DockPosition, Panel},
42 Workspace,
43};
44
45const PROJECT_PANEL_KEY: &'static str = "ProjectPanel";
46const NEW_ENTRY_ID: ProjectEntryId = ProjectEntryId::MAX;
47
48pub struct ProjectPanel {
49 project: ModelHandle<Project>,
50 fs: Arc<dyn Fs>,
51 list: UniformListState,
52 visible_entries: Vec<(WorktreeId, Vec<Entry>)>,
53 last_worktree_root_id: Option<ProjectEntryId>,
54 expanded_dir_ids: HashMap<WorktreeId, Vec<ProjectEntryId>>,
55 selection: Option<Selection>,
56 edit_state: Option<EditState>,
57 filename_editor: ViewHandle<Editor>,
58 clipboard_entry: Option<ClipboardEntry>,
59 context_menu: ViewHandle<ContextMenu>,
60 dragged_entry_destination: Option<Arc<Path>>,
61 workspace: WeakViewHandle<Workspace>,
62 has_focus: bool,
63 width: Option<f32>,
64 pending_serialization: Task<Option<()>>,
65}
66
67#[derive(Copy, Clone, Debug)]
68struct Selection {
69 worktree_id: WorktreeId,
70 entry_id: ProjectEntryId,
71}
72
73#[derive(Clone, Debug)]
74struct EditState {
75 worktree_id: WorktreeId,
76 entry_id: ProjectEntryId,
77 is_new_entry: bool,
78 is_dir: bool,
79 processing_filename: Option<String>,
80}
81
82#[derive(Copy, Clone)]
83pub enum ClipboardEntry {
84 Copied {
85 worktree_id: WorktreeId,
86 entry_id: ProjectEntryId,
87 },
88 Cut {
89 worktree_id: WorktreeId,
90 entry_id: ProjectEntryId,
91 },
92}
93
94#[derive(Debug, PartialEq, Eq)]
95pub struct EntryDetails {
96 filename: String,
97 path: Arc<Path>,
98 depth: usize,
99 kind: EntryKind,
100 is_ignored: bool,
101 is_expanded: bool,
102 is_selected: bool,
103 is_editing: bool,
104 is_processing: bool,
105 is_cut: bool,
106 git_status: Option<GitFileStatus>,
107}
108
109actions!(
110 project_panel,
111 [
112 ExpandSelectedEntry,
113 CollapseSelectedEntry,
114 NewDirectory,
115 NewFile,
116 Copy,
117 CopyPath,
118 CopyRelativePath,
119 RevealInFinder,
120 Cut,
121 Paste,
122 Delete,
123 Rename,
124 ToggleFocus
125 ]
126);
127
128pub fn init_settings(cx: &mut AppContext) {
129 settings::register::<ProjectPanelSettings>(cx);
130}
131
132pub fn init(cx: &mut AppContext) {
133 init_settings(cx);
134 cx.add_action(ProjectPanel::expand_selected_entry);
135 cx.add_action(ProjectPanel::collapse_selected_entry);
136 cx.add_action(ProjectPanel::select_prev);
137 cx.add_action(ProjectPanel::select_next);
138 cx.add_action(ProjectPanel::new_file);
139 cx.add_action(ProjectPanel::new_directory);
140 cx.add_action(ProjectPanel::rename);
141 cx.add_async_action(ProjectPanel::delete);
142 cx.add_async_action(ProjectPanel::confirm);
143 cx.add_action(ProjectPanel::cancel);
144 cx.add_action(ProjectPanel::cut);
145 cx.add_action(ProjectPanel::copy);
146 cx.add_action(ProjectPanel::copy_path);
147 cx.add_action(ProjectPanel::copy_relative_path);
148 cx.add_action(ProjectPanel::reveal_in_finder);
149 cx.add_action(
150 |this: &mut ProjectPanel, action: &Paste, cx: &mut ViewContext<ProjectPanel>| {
151 this.paste(action, cx);
152 },
153 );
154}
155
156#[derive(Debug)]
157pub enum Event {
158 OpenedEntry {
159 entry_id: ProjectEntryId,
160 focus_opened_item: bool,
161 },
162 DockPositionChanged,
163 Focus,
164}
165
166#[derive(Serialize, Deserialize)]
167struct SerializedProjectPanel {
168 width: Option<f32>,
169}
170
171impl ProjectPanel {
172 fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> ViewHandle<Self> {
173 let project = workspace.project().clone();
174 let project_panel = cx.add_view(|cx: &mut ViewContext<Self>| {
175 cx.observe(&project, |this, _, cx| {
176 this.update_visible_entries(None, cx);
177 cx.notify();
178 })
179 .detach();
180 cx.subscribe(&project, |this, project, event, cx| match event {
181 project::Event::ActiveEntryChanged(Some(entry_id)) => {
182 if let Some(worktree_id) = project.read(cx).worktree_id_for_entry(*entry_id, cx)
183 {
184 this.expand_entry(worktree_id, *entry_id, cx);
185 this.update_visible_entries(Some((worktree_id, *entry_id)), cx);
186 this.autoscroll(cx);
187 cx.notify();
188 }
189 }
190 project::Event::WorktreeRemoved(id) => {
191 this.expanded_dir_ids.remove(id);
192 this.update_visible_entries(None, cx);
193 cx.notify();
194 }
195 _ => {}
196 })
197 .detach();
198
199 let filename_editor = cx.add_view(|cx| {
200 Editor::single_line(
201 Some(Arc::new(|theme| {
202 let mut style = theme.project_panel.filename_editor.clone();
203 style.container.background_color.take();
204 style
205 })),
206 cx,
207 )
208 });
209
210 cx.subscribe(&filename_editor, |this, _, event, cx| match event {
211 editor::Event::BufferEdited | editor::Event::SelectionsChanged { .. } => {
212 this.autoscroll(cx);
213 }
214 _ => {}
215 })
216 .detach();
217 cx.observe_focus(&filename_editor, |this, _, is_focused, cx| {
218 if !is_focused
219 && this
220 .edit_state
221 .as_ref()
222 .map_or(false, |state| state.processing_filename.is_none())
223 {
224 this.edit_state = None;
225 this.update_visible_entries(None, cx);
226 }
227 })
228 .detach();
229
230 let view_id = cx.view_id();
231 let mut this = Self {
232 project: project.clone(),
233 fs: workspace.app_state().fs.clone(),
234 list: Default::default(),
235 visible_entries: Default::default(),
236 last_worktree_root_id: Default::default(),
237 expanded_dir_ids: Default::default(),
238 selection: None,
239 edit_state: None,
240 filename_editor,
241 clipboard_entry: None,
242 context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)),
243 dragged_entry_destination: None,
244 workspace: workspace.weak_handle(),
245 has_focus: false,
246 width: None,
247 pending_serialization: Task::ready(None),
248 };
249 this.update_visible_entries(None, cx);
250
251 // Update the dock position when the setting changes.
252 let mut old_dock_position = this.position(cx);
253 cx.observe_global::<SettingsStore, _>(move |this, cx| {
254 let new_dock_position = this.position(cx);
255 if new_dock_position != old_dock_position {
256 old_dock_position = new_dock_position;
257 cx.emit(Event::DockPositionChanged);
258 }
259 })
260 .detach();
261
262 this
263 });
264
265 cx.subscribe(&project_panel, {
266 let project_panel = project_panel.downgrade();
267 move |workspace, _, event, cx| match event {
268 &Event::OpenedEntry {
269 entry_id,
270 focus_opened_item,
271 } => {
272 if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx) {
273 if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
274 workspace
275 .open_path(
276 ProjectPath {
277 worktree_id: worktree.read(cx).id(),
278 path: entry.path.clone(),
279 },
280 None,
281 focus_opened_item,
282 cx,
283 )
284 .detach_and_log_err(cx);
285 if !focus_opened_item {
286 if let Some(project_panel) = project_panel.upgrade(cx) {
287 cx.focus(&project_panel);
288 }
289 }
290 }
291 }
292 }
293 _ => {}
294 }
295 })
296 .detach();
297
298 project_panel
299 }
300
301 pub fn load(
302 workspace: WeakViewHandle<Workspace>,
303 cx: AsyncAppContext,
304 ) -> Task<Result<ViewHandle<Self>>> {
305 cx.spawn(|mut cx| async move {
306 let serialized_panel = if let Some(panel) = cx
307 .background()
308 .spawn(async move { KEY_VALUE_STORE.read_kvp(PROJECT_PANEL_KEY) })
309 .await
310 .log_err()
311 .flatten()
312 {
313 Some(serde_json::from_str::<SerializedProjectPanel>(&panel)?)
314 } else {
315 None
316 };
317 workspace.update(&mut cx, |workspace, cx| {
318 let panel = ProjectPanel::new(workspace, cx);
319 if let Some(serialized_panel) = serialized_panel {
320 panel.update(cx, |panel, cx| {
321 panel.width = serialized_panel.width;
322 cx.notify();
323 });
324 }
325 panel
326 })
327 })
328 }
329
330 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
331 let width = self.width;
332 self.pending_serialization = cx.background().spawn(
333 async move {
334 KEY_VALUE_STORE
335 .write_kvp(
336 PROJECT_PANEL_KEY.into(),
337 serde_json::to_string(&SerializedProjectPanel { width })?,
338 )
339 .await?;
340 anyhow::Ok(())
341 }
342 .log_err(),
343 );
344 }
345
346 fn deploy_context_menu(
347 &mut self,
348 position: Vector2F,
349 entry_id: ProjectEntryId,
350 cx: &mut ViewContext<Self>,
351 ) {
352 let project = self.project.read(cx);
353
354 let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) {
355 id
356 } else {
357 return;
358 };
359
360 self.selection = Some(Selection {
361 worktree_id,
362 entry_id,
363 });
364
365 let mut menu_entries = Vec::new();
366 if let Some((worktree, entry)) = self.selected_entry(cx) {
367 let is_root = Some(entry) == worktree.root_entry();
368 if !project.is_remote() {
369 menu_entries.push(ContextMenuItem::action(
370 "Add Folder to Project",
371 workspace::AddFolderToProject,
372 ));
373 if is_root {
374 let project = self.project.clone();
375 menu_entries.push(ContextMenuItem::handler("Remove from Project", move |cx| {
376 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
377 }));
378 }
379 }
380 menu_entries.push(ContextMenuItem::action("New File", NewFile));
381 menu_entries.push(ContextMenuItem::action("New Folder", NewDirectory));
382 menu_entries.push(ContextMenuItem::Separator);
383 menu_entries.push(ContextMenuItem::action("Cut", Cut));
384 menu_entries.push(ContextMenuItem::action("Copy", Copy));
385 menu_entries.push(ContextMenuItem::Separator);
386 menu_entries.push(ContextMenuItem::action("Copy Path", CopyPath));
387 menu_entries.push(ContextMenuItem::action(
388 "Copy Relative Path",
389 CopyRelativePath,
390 ));
391 menu_entries.push(ContextMenuItem::action("Reveal in Finder", RevealInFinder));
392 if let Some(clipboard_entry) = self.clipboard_entry {
393 if clipboard_entry.worktree_id() == worktree.id() {
394 menu_entries.push(ContextMenuItem::action("Paste", Paste));
395 }
396 }
397 menu_entries.push(ContextMenuItem::Separator);
398 menu_entries.push(ContextMenuItem::action("Rename", Rename));
399 if !is_root {
400 menu_entries.push(ContextMenuItem::action("Delete", Delete));
401 }
402 }
403
404 self.context_menu.update(cx, |menu, cx| {
405 menu.show(position, AnchorCorner::TopLeft, menu_entries, cx);
406 });
407
408 cx.notify();
409 }
410
411 fn expand_selected_entry(&mut self, _: &ExpandSelectedEntry, cx: &mut ViewContext<Self>) {
412 if let Some((worktree, entry)) = self.selected_entry(cx) {
413 if entry.is_dir() {
414 let worktree_id = worktree.id();
415 let entry_id = entry.id;
416 let expanded_dir_ids =
417 if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
418 expanded_dir_ids
419 } else {
420 return;
421 };
422
423 match expanded_dir_ids.binary_search(&entry_id) {
424 Ok(_) => self.select_next(&SelectNext, cx),
425 Err(ix) => {
426 self.project.update(cx, |project, cx| {
427 project.expand_entry(worktree_id, entry_id, cx);
428 });
429
430 expanded_dir_ids.insert(ix, entry_id);
431 self.update_visible_entries(None, cx);
432 cx.notify();
433 }
434 }
435 }
436 }
437 }
438
439 fn collapse_selected_entry(&mut self, _: &CollapseSelectedEntry, cx: &mut ViewContext<Self>) {
440 if let Some((worktree, mut entry)) = self.selected_entry(cx) {
441 let worktree_id = worktree.id();
442 let expanded_dir_ids =
443 if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
444 expanded_dir_ids
445 } else {
446 return;
447 };
448
449 loop {
450 let entry_id = entry.id;
451 match expanded_dir_ids.binary_search(&entry_id) {
452 Ok(ix) => {
453 expanded_dir_ids.remove(ix);
454 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
455 cx.notify();
456 break;
457 }
458 Err(_) => {
459 if let Some(parent_entry) =
460 entry.path.parent().and_then(|p| worktree.entry_for_path(p))
461 {
462 entry = parent_entry;
463 } else {
464 break;
465 }
466 }
467 }
468 }
469 }
470 }
471
472 fn toggle_expanded(&mut self, entry_id: ProjectEntryId, cx: &mut ViewContext<Self>) {
473 if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx) {
474 if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
475 self.project.update(cx, |project, cx| {
476 match expanded_dir_ids.binary_search(&entry_id) {
477 Ok(ix) => {
478 expanded_dir_ids.remove(ix);
479 }
480 Err(ix) => {
481 project.expand_entry(worktree_id, entry_id, cx);
482 expanded_dir_ids.insert(ix, entry_id);
483 }
484 }
485 });
486 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
487 cx.focus_self();
488 cx.notify();
489 }
490 }
491 }
492
493 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
494 if let Some(selection) = self.selection {
495 let (mut worktree_ix, mut entry_ix, _) =
496 self.index_for_selection(selection).unwrap_or_default();
497 if entry_ix > 0 {
498 entry_ix -= 1;
499 } else if worktree_ix > 0 {
500 worktree_ix -= 1;
501 entry_ix = self.visible_entries[worktree_ix].1.len() - 1;
502 } else {
503 return;
504 }
505
506 let (worktree_id, worktree_entries) = &self.visible_entries[worktree_ix];
507 self.selection = Some(Selection {
508 worktree_id: *worktree_id,
509 entry_id: worktree_entries[entry_ix].id,
510 });
511 self.autoscroll(cx);
512 cx.notify();
513 } else {
514 self.select_first(cx);
515 }
516 }
517
518 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
519 if let Some(task) = self.confirm_edit(cx) {
520 Some(task)
521 } else if let Some((_, entry)) = self.selected_entry(cx) {
522 if entry.is_file() {
523 self.open_entry(entry.id, true, cx);
524 }
525 None
526 } else {
527 None
528 }
529 }
530
531 fn confirm_edit(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
532 let edit_state = self.edit_state.as_mut()?;
533 cx.focus_self();
534
535 let worktree_id = edit_state.worktree_id;
536 let is_new_entry = edit_state.is_new_entry;
537 let is_dir = edit_state.is_dir;
538 let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
539 let entry = worktree.read(cx).entry_for_id(edit_state.entry_id)?.clone();
540 let filename = self.filename_editor.read(cx).text(cx);
541
542 let path_already_exists = |path| worktree.read(cx).entry_for_path(path).is_some();
543 let edit_task;
544 let edited_entry_id;
545 if is_new_entry {
546 self.selection = Some(Selection {
547 worktree_id,
548 entry_id: NEW_ENTRY_ID,
549 });
550 let new_path = entry.path.join(&filename.trim_start_matches("/"));
551 if path_already_exists(new_path.as_path()) {
552 return None;
553 }
554
555 edited_entry_id = NEW_ENTRY_ID;
556 edit_task = self.project.update(cx, |project, cx| {
557 project.create_entry((worktree_id, &new_path), is_dir, cx)
558 })?;
559 } else {
560 let new_path = if let Some(parent) = entry.path.clone().parent() {
561 parent.join(&filename)
562 } else {
563 filename.clone().into()
564 };
565 if path_already_exists(new_path.as_path()) {
566 return None;
567 }
568
569 edited_entry_id = entry.id;
570 edit_task = self.project.update(cx, |project, cx| {
571 project.rename_entry(entry.id, new_path.as_path(), cx)
572 })?;
573 };
574
575 edit_state.processing_filename = Some(filename);
576 cx.notify();
577
578 Some(cx.spawn(|this, mut cx| async move {
579 let new_entry = edit_task.await;
580 this.update(&mut cx, |this, cx| {
581 this.edit_state.take();
582 cx.notify();
583 })?;
584
585 let new_entry = new_entry?;
586 this.update(&mut cx, |this, cx| {
587 if let Some(selection) = &mut this.selection {
588 if selection.entry_id == edited_entry_id {
589 selection.worktree_id = worktree_id;
590 selection.entry_id = new_entry.id;
591 this.expand_to_selection(cx);
592 }
593 }
594 this.update_visible_entries(None, cx);
595 if is_new_entry && !is_dir {
596 this.open_entry(new_entry.id, true, cx);
597 }
598 cx.notify();
599 })?;
600 Ok(())
601 }))
602 }
603
604 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
605 self.edit_state = None;
606 self.update_visible_entries(None, cx);
607 cx.focus_self();
608 cx.notify();
609 }
610
611 fn open_entry(
612 &mut self,
613 entry_id: ProjectEntryId,
614 focus_opened_item: bool,
615 cx: &mut ViewContext<Self>,
616 ) {
617 cx.emit(Event::OpenedEntry {
618 entry_id,
619 focus_opened_item,
620 });
621 }
622
623 fn new_file(&mut self, _: &NewFile, cx: &mut ViewContext<Self>) {
624 self.add_entry(false, cx)
625 }
626
627 fn new_directory(&mut self, _: &NewDirectory, cx: &mut ViewContext<Self>) {
628 self.add_entry(true, cx)
629 }
630
631 fn add_entry(&mut self, is_dir: bool, cx: &mut ViewContext<Self>) {
632 if let Some(Selection {
633 worktree_id,
634 entry_id,
635 }) = self.selection
636 {
637 let directory_id;
638 if let Some((worktree, expanded_dir_ids)) = self
639 .project
640 .read(cx)
641 .worktree_for_id(worktree_id, cx)
642 .zip(self.expanded_dir_ids.get_mut(&worktree_id))
643 {
644 let worktree = worktree.read(cx);
645 if let Some(mut entry) = worktree.entry_for_id(entry_id) {
646 loop {
647 if entry.is_dir() {
648 if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
649 expanded_dir_ids.insert(ix, entry.id);
650 }
651 directory_id = entry.id;
652 break;
653 } else {
654 if let Some(parent_path) = entry.path.parent() {
655 if let Some(parent_entry) = worktree.entry_for_path(parent_path) {
656 entry = parent_entry;
657 continue;
658 }
659 }
660 return;
661 }
662 }
663 } else {
664 return;
665 };
666 } else {
667 return;
668 };
669
670 self.edit_state = Some(EditState {
671 worktree_id,
672 entry_id: directory_id,
673 is_new_entry: true,
674 is_dir,
675 processing_filename: None,
676 });
677 self.filename_editor
678 .update(cx, |editor, cx| editor.clear(cx));
679 cx.focus(&self.filename_editor);
680 self.update_visible_entries(Some((worktree_id, NEW_ENTRY_ID)), cx);
681 self.autoscroll(cx);
682 cx.notify();
683 }
684 }
685
686 fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) {
687 if let Some(Selection {
688 worktree_id,
689 entry_id,
690 }) = self.selection
691 {
692 if let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx) {
693 if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
694 self.edit_state = Some(EditState {
695 worktree_id,
696 entry_id,
697 is_new_entry: false,
698 is_dir: entry.is_dir(),
699 processing_filename: None,
700 });
701 let filename = entry
702 .path
703 .file_name()
704 .map_or(String::new(), |s| s.to_string_lossy().to_string());
705 self.filename_editor.update(cx, |editor, cx| {
706 editor.set_text(filename, cx);
707 editor.select_all(&Default::default(), cx);
708 });
709 cx.focus(&self.filename_editor);
710 self.update_visible_entries(None, cx);
711 self.autoscroll(cx);
712 cx.notify();
713 }
714 }
715
716 cx.update_global(|drag_and_drop: &mut DragAndDrop<Workspace>, cx| {
717 drag_and_drop.cancel_dragging::<ProjectEntryId>(cx);
718 })
719 }
720 }
721
722 fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
723 let Selection { entry_id, .. } = self.selection?;
724 let path = self.project.read(cx).path_for_entry(entry_id, cx)?.path;
725 let file_name = path.file_name()?;
726
727 let mut answer = cx.prompt(
728 PromptLevel::Info,
729 &format!("Delete {file_name:?}?"),
730 &["Delete", "Cancel"],
731 );
732 Some(cx.spawn(|this, mut cx| async move {
733 if answer.next().await != Some(0) {
734 return Ok(());
735 }
736 this.update(&mut cx, |this, cx| {
737 this.project
738 .update(cx, |project, cx| project.delete_entry(entry_id, cx))
739 .ok_or_else(|| anyhow!("no such entry"))
740 })??
741 .await
742 }))
743 }
744
745 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
746 if let Some(selection) = self.selection {
747 let (mut worktree_ix, mut entry_ix, _) =
748 self.index_for_selection(selection).unwrap_or_default();
749 if let Some((_, worktree_entries)) = self.visible_entries.get(worktree_ix) {
750 if entry_ix + 1 < worktree_entries.len() {
751 entry_ix += 1;
752 } else {
753 worktree_ix += 1;
754 entry_ix = 0;
755 }
756 }
757
758 if let Some((worktree_id, worktree_entries)) = self.visible_entries.get(worktree_ix) {
759 if let Some(entry) = worktree_entries.get(entry_ix) {
760 self.selection = Some(Selection {
761 worktree_id: *worktree_id,
762 entry_id: entry.id,
763 });
764 self.autoscroll(cx);
765 cx.notify();
766 }
767 }
768 } else {
769 self.select_first(cx);
770 }
771 }
772
773 fn select_first(&mut self, cx: &mut ViewContext<Self>) {
774 let worktree = self
775 .visible_entries
776 .first()
777 .and_then(|(worktree_id, _)| self.project.read(cx).worktree_for_id(*worktree_id, cx));
778 if let Some(worktree) = worktree {
779 let worktree = worktree.read(cx);
780 let worktree_id = worktree.id();
781 if let Some(root_entry) = worktree.root_entry() {
782 self.selection = Some(Selection {
783 worktree_id,
784 entry_id: root_entry.id,
785 });
786 self.autoscroll(cx);
787 cx.notify();
788 }
789 }
790 }
791
792 fn autoscroll(&mut self, cx: &mut ViewContext<Self>) {
793 if let Some((_, _, index)) = self.selection.and_then(|s| self.index_for_selection(s)) {
794 self.list.scroll_to(ScrollTarget::Show(index));
795 cx.notify();
796 }
797 }
798
799 fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
800 if let Some((worktree, entry)) = self.selected_entry(cx) {
801 self.clipboard_entry = Some(ClipboardEntry::Cut {
802 worktree_id: worktree.id(),
803 entry_id: entry.id,
804 });
805 cx.notify();
806 }
807 }
808
809 fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
810 if let Some((worktree, entry)) = self.selected_entry(cx) {
811 self.clipboard_entry = Some(ClipboardEntry::Copied {
812 worktree_id: worktree.id(),
813 entry_id: entry.id,
814 });
815 cx.notify();
816 }
817 }
818
819 fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) -> Option<()> {
820 if let Some((worktree, entry)) = self.selected_entry(cx) {
821 let clipboard_entry = self.clipboard_entry?;
822 if clipboard_entry.worktree_id() != worktree.id() {
823 return None;
824 }
825
826 let clipboard_entry_file_name = self
827 .project
828 .read(cx)
829 .path_for_entry(clipboard_entry.entry_id(), cx)?
830 .path
831 .file_name()?
832 .to_os_string();
833
834 let mut new_path = entry.path.to_path_buf();
835 if entry.is_file() {
836 new_path.pop();
837 }
838
839 new_path.push(&clipboard_entry_file_name);
840 let extension = new_path.extension().map(|e| e.to_os_string());
841 let file_name_without_extension = Path::new(&clipboard_entry_file_name).file_stem()?;
842 let mut ix = 0;
843 while worktree.entry_for_path(&new_path).is_some() {
844 new_path.pop();
845
846 let mut new_file_name = file_name_without_extension.to_os_string();
847 new_file_name.push(" copy");
848 if ix > 0 {
849 new_file_name.push(format!(" {}", ix));
850 }
851 if let Some(extension) = extension.as_ref() {
852 new_file_name.push(".");
853 new_file_name.push(extension);
854 }
855
856 new_path.push(new_file_name);
857 ix += 1;
858 }
859
860 if clipboard_entry.is_cut() {
861 if let Some(task) = self.project.update(cx, |project, cx| {
862 project.rename_entry(clipboard_entry.entry_id(), new_path, cx)
863 }) {
864 task.detach_and_log_err(cx)
865 }
866 } else if let Some(task) = self.project.update(cx, |project, cx| {
867 project.copy_entry(clipboard_entry.entry_id(), new_path, cx)
868 }) {
869 task.detach_and_log_err(cx)
870 }
871 }
872 None
873 }
874
875 fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
876 if let Some((worktree, entry)) = self.selected_entry(cx) {
877 cx.write_to_clipboard(ClipboardItem::new(
878 worktree
879 .abs_path()
880 .join(&entry.path)
881 .to_string_lossy()
882 .to_string(),
883 ));
884 }
885 }
886
887 fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
888 if let Some((_, entry)) = self.selected_entry(cx) {
889 cx.write_to_clipboard(ClipboardItem::new(entry.path.to_string_lossy().to_string()));
890 }
891 }
892
893 fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
894 if let Some((worktree, entry)) = self.selected_entry(cx) {
895 cx.reveal_path(&worktree.abs_path().join(&entry.path));
896 }
897 }
898
899 fn move_entry(
900 &mut self,
901 entry_to_move: ProjectEntryId,
902 destination: ProjectEntryId,
903 destination_is_file: bool,
904 cx: &mut ViewContext<Self>,
905 ) {
906 let destination_worktree = self.project.update(cx, |project, cx| {
907 let entry_path = project.path_for_entry(entry_to_move, cx)?;
908 let destination_entry_path = project.path_for_entry(destination, cx)?.path.clone();
909
910 let mut destination_path = destination_entry_path.as_ref();
911 if destination_is_file {
912 destination_path = destination_path.parent()?;
913 }
914
915 let mut new_path = destination_path.to_path_buf();
916 new_path.push(entry_path.path.file_name()?);
917 if new_path != entry_path.path.as_ref() {
918 let task = project.rename_entry(entry_to_move, new_path, cx)?;
919 cx.foreground().spawn(task).detach_and_log_err(cx);
920 }
921
922 Some(project.worktree_id_for_entry(destination, cx)?)
923 });
924
925 if let Some(destination_worktree) = destination_worktree {
926 self.expand_entry(destination_worktree, destination, cx);
927 }
928 }
929
930 fn index_for_selection(&self, selection: Selection) -> Option<(usize, usize, usize)> {
931 let mut entry_index = 0;
932 let mut visible_entries_index = 0;
933 for (worktree_index, (worktree_id, worktree_entries)) in
934 self.visible_entries.iter().enumerate()
935 {
936 if *worktree_id == selection.worktree_id {
937 for entry in worktree_entries {
938 if entry.id == selection.entry_id {
939 return Some((worktree_index, entry_index, visible_entries_index));
940 } else {
941 visible_entries_index += 1;
942 entry_index += 1;
943 }
944 }
945 break;
946 } else {
947 visible_entries_index += worktree_entries.len();
948 }
949 }
950 None
951 }
952
953 fn selected_entry<'a>(&self, cx: &'a AppContext) -> Option<(&'a Worktree, &'a project::Entry)> {
954 let (worktree, entry) = self.selected_entry_handle(cx)?;
955 Some((worktree.read(cx), entry))
956 }
957
958 fn selected_entry_handle<'a>(
959 &self,
960 cx: &'a AppContext,
961 ) -> Option<(ModelHandle<Worktree>, &'a project::Entry)> {
962 let selection = self.selection?;
963 let project = self.project.read(cx);
964 let worktree = project.worktree_for_id(selection.worktree_id, cx)?;
965 let entry = worktree.read(cx).entry_for_id(selection.entry_id)?;
966 Some((worktree, entry))
967 }
968
969 fn expand_to_selection(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
970 let (worktree, entry) = self.selected_entry(cx)?;
971 let expanded_dir_ids = self.expanded_dir_ids.entry(worktree.id()).or_default();
972
973 for path in entry.path.ancestors() {
974 let Some(entry) = worktree.entry_for_path(path) else {
975 continue;
976 };
977 if entry.is_dir() {
978 if let Err(idx) = expanded_dir_ids.binary_search(&entry.id) {
979 expanded_dir_ids.insert(idx, entry.id);
980 }
981 }
982 }
983
984 Some(())
985 }
986
987 fn update_visible_entries(
988 &mut self,
989 new_selected_entry: Option<(WorktreeId, ProjectEntryId)>,
990 cx: &mut ViewContext<Self>,
991 ) {
992 let project = self.project.read(cx);
993 self.last_worktree_root_id = project
994 .visible_worktrees(cx)
995 .rev()
996 .next()
997 .and_then(|worktree| worktree.read(cx).root_entry())
998 .map(|entry| entry.id);
999
1000 self.visible_entries.clear();
1001 for worktree in project.visible_worktrees(cx) {
1002 let snapshot = worktree.read(cx).snapshot();
1003 let worktree_id = snapshot.id();
1004
1005 let expanded_dir_ids = match self.expanded_dir_ids.entry(worktree_id) {
1006 hash_map::Entry::Occupied(e) => e.into_mut(),
1007 hash_map::Entry::Vacant(e) => {
1008 // The first time a worktree's root entry becomes available,
1009 // mark that root entry as expanded.
1010 if let Some(entry) = snapshot.root_entry() {
1011 e.insert(vec![entry.id]).as_slice()
1012 } else {
1013 &[]
1014 }
1015 }
1016 };
1017
1018 let mut new_entry_parent_id = None;
1019 let mut new_entry_kind = EntryKind::Dir;
1020 if let Some(edit_state) = &self.edit_state {
1021 if edit_state.worktree_id == worktree_id && edit_state.is_new_entry {
1022 new_entry_parent_id = Some(edit_state.entry_id);
1023 new_entry_kind = if edit_state.is_dir {
1024 EntryKind::Dir
1025 } else {
1026 EntryKind::File(Default::default())
1027 };
1028 }
1029 }
1030
1031 let mut visible_worktree_entries = Vec::new();
1032 let mut entry_iter = snapshot.entries(true);
1033
1034 while let Some(entry) = entry_iter.entry() {
1035 visible_worktree_entries.push(entry.clone());
1036 if Some(entry.id) == new_entry_parent_id {
1037 visible_worktree_entries.push(Entry {
1038 id: NEW_ENTRY_ID,
1039 kind: new_entry_kind,
1040 path: entry.path.join("\0").into(),
1041 inode: 0,
1042 mtime: entry.mtime,
1043 is_symlink: false,
1044 is_ignored: false,
1045 is_external: false,
1046 git_status: entry.git_status,
1047 });
1048 }
1049 if expanded_dir_ids.binary_search(&entry.id).is_err()
1050 && entry_iter.advance_to_sibling()
1051 {
1052 continue;
1053 }
1054 entry_iter.advance();
1055 }
1056
1057 snapshot.propagate_git_statuses(&mut visible_worktree_entries);
1058
1059 visible_worktree_entries.sort_by(|entry_a, entry_b| {
1060 let mut components_a = entry_a.path.components().peekable();
1061 let mut components_b = entry_b.path.components().peekable();
1062 loop {
1063 match (components_a.next(), components_b.next()) {
1064 (Some(component_a), Some(component_b)) => {
1065 let a_is_file = components_a.peek().is_none() && entry_a.is_file();
1066 let b_is_file = components_b.peek().is_none() && entry_b.is_file();
1067 let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
1068 let name_a =
1069 UniCase::new(component_a.as_os_str().to_string_lossy());
1070 let name_b =
1071 UniCase::new(component_b.as_os_str().to_string_lossy());
1072 name_a.cmp(&name_b)
1073 });
1074 if !ordering.is_eq() {
1075 return ordering;
1076 }
1077 }
1078 (Some(_), None) => break Ordering::Greater,
1079 (None, Some(_)) => break Ordering::Less,
1080 (None, None) => break Ordering::Equal,
1081 }
1082 }
1083 });
1084 self.visible_entries
1085 .push((worktree_id, visible_worktree_entries));
1086 }
1087
1088 if let Some((worktree_id, entry_id)) = new_selected_entry {
1089 self.selection = Some(Selection {
1090 worktree_id,
1091 entry_id,
1092 });
1093 }
1094 }
1095
1096 fn expand_entry(
1097 &mut self,
1098 worktree_id: WorktreeId,
1099 entry_id: ProjectEntryId,
1100 cx: &mut ViewContext<Self>,
1101 ) {
1102 self.project.update(cx, |project, cx| {
1103 if let Some((worktree, expanded_dir_ids)) = project
1104 .worktree_for_id(worktree_id, cx)
1105 .zip(self.expanded_dir_ids.get_mut(&worktree_id))
1106 {
1107 project.expand_entry(worktree_id, entry_id, cx);
1108 let worktree = worktree.read(cx);
1109
1110 if let Some(mut entry) = worktree.entry_for_id(entry_id) {
1111 loop {
1112 if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
1113 expanded_dir_ids.insert(ix, entry.id);
1114 }
1115
1116 if let Some(parent_entry) =
1117 entry.path.parent().and_then(|p| worktree.entry_for_path(p))
1118 {
1119 entry = parent_entry;
1120 } else {
1121 break;
1122 }
1123 }
1124 }
1125 }
1126 });
1127 }
1128
1129 fn for_each_visible_entry(
1130 &self,
1131 range: Range<usize>,
1132 cx: &mut ViewContext<ProjectPanel>,
1133 mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut ViewContext<ProjectPanel>),
1134 ) {
1135 let mut ix = 0;
1136 for (worktree_id, visible_worktree_entries) in &self.visible_entries {
1137 if ix >= range.end {
1138 return;
1139 }
1140
1141 if ix + visible_worktree_entries.len() <= range.start {
1142 ix += visible_worktree_entries.len();
1143 continue;
1144 }
1145
1146 let end_ix = range.end.min(ix + visible_worktree_entries.len());
1147 let git_status_setting = settings::get::<ProjectPanelSettings>(cx).git_status;
1148 if let Some(worktree) = self.project.read(cx).worktree_for_id(*worktree_id, cx) {
1149 let snapshot = worktree.read(cx).snapshot();
1150 let root_name = OsStr::new(snapshot.root_name());
1151 let expanded_entry_ids = self
1152 .expanded_dir_ids
1153 .get(&snapshot.id())
1154 .map(Vec::as_slice)
1155 .unwrap_or(&[]);
1156
1157 let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
1158 for entry in visible_worktree_entries[entry_range].iter() {
1159 let status = git_status_setting.then(|| entry.git_status).flatten();
1160
1161 let mut details = EntryDetails {
1162 filename: entry
1163 .path
1164 .file_name()
1165 .unwrap_or(root_name)
1166 .to_string_lossy()
1167 .to_string(),
1168 path: entry.path.clone(),
1169 depth: entry.path.components().count(),
1170 kind: entry.kind,
1171 is_ignored: entry.is_ignored,
1172 is_expanded: expanded_entry_ids.binary_search(&entry.id).is_ok(),
1173 is_selected: self.selection.map_or(false, |e| {
1174 e.worktree_id == snapshot.id() && e.entry_id == entry.id
1175 }),
1176 is_editing: false,
1177 is_processing: false,
1178 is_cut: self
1179 .clipboard_entry
1180 .map_or(false, |e| e.is_cut() && e.entry_id() == entry.id),
1181 git_status: status,
1182 };
1183
1184 if let Some(edit_state) = &self.edit_state {
1185 let is_edited_entry = if edit_state.is_new_entry {
1186 entry.id == NEW_ENTRY_ID
1187 } else {
1188 entry.id == edit_state.entry_id
1189 };
1190
1191 if is_edited_entry {
1192 if let Some(processing_filename) = &edit_state.processing_filename {
1193 details.is_processing = true;
1194 details.filename.clear();
1195 details.filename.push_str(processing_filename);
1196 } else {
1197 if edit_state.is_new_entry {
1198 details.filename.clear();
1199 }
1200 details.is_editing = true;
1201 }
1202 }
1203 }
1204
1205 callback(entry.id, details, cx);
1206 }
1207 }
1208 ix = end_ix;
1209 }
1210 }
1211
1212 fn render_entry_visual_element<V: View>(
1213 details: &EntryDetails,
1214 editor: Option<&ViewHandle<Editor>>,
1215 padding: f32,
1216 row_container_style: ContainerStyle,
1217 style: &ProjectPanelEntry,
1218 cx: &mut ViewContext<V>,
1219 ) -> AnyElement<V> {
1220 let kind = details.kind;
1221 let show_editor = details.is_editing && !details.is_processing;
1222
1223 let mut filename_text_style = style.text.clone();
1224 filename_text_style.color = details
1225 .git_status
1226 .as_ref()
1227 .map(|status| match status {
1228 GitFileStatus::Added => style.status.git.inserted,
1229 GitFileStatus::Modified => style.status.git.modified,
1230 GitFileStatus::Conflict => style.status.git.conflict,
1231 })
1232 .unwrap_or(style.text.color);
1233
1234 Flex::row()
1235 .with_child(
1236 if kind.is_dir() {
1237 if details.is_expanded {
1238 Svg::new("icons/chevron_down_8.svg").with_color(style.icon_color)
1239 } else {
1240 Svg::new("icons/chevron_right_8.svg").with_color(style.icon_color)
1241 }
1242 .constrained()
1243 } else {
1244 Empty::new().constrained()
1245 }
1246 .with_max_width(style.icon_size)
1247 .with_max_height(style.icon_size)
1248 .aligned()
1249 .constrained()
1250 .with_width(style.icon_size),
1251 )
1252 .with_child(if show_editor && editor.is_some() {
1253 ChildView::new(editor.as_ref().unwrap(), cx)
1254 .contained()
1255 .with_margin_left(style.icon_spacing)
1256 .aligned()
1257 .left()
1258 .flex(1.0, true)
1259 .into_any()
1260 } else {
1261 Label::new(details.filename.clone(), filename_text_style)
1262 .contained()
1263 .with_margin_left(style.icon_spacing)
1264 .aligned()
1265 .left()
1266 .into_any()
1267 })
1268 .constrained()
1269 .with_height(style.height)
1270 .contained()
1271 .with_style(row_container_style)
1272 .with_padding_left(padding)
1273 .into_any_named("project panel entry visual element")
1274 }
1275
1276 fn render_entry(
1277 entry_id: ProjectEntryId,
1278 details: EntryDetails,
1279 editor: &ViewHandle<Editor>,
1280 dragged_entry_destination: &mut Option<Arc<Path>>,
1281 theme: &theme::ProjectPanel,
1282 cx: &mut ViewContext<Self>,
1283 ) -> AnyElement<Self> {
1284 let kind = details.kind;
1285 let path = details.path.clone();
1286 let padding = theme.container.padding.left + details.depth as f32 * theme.indent_width;
1287
1288 let entry_style = if details.is_cut {
1289 &theme.cut_entry
1290 } else if details.is_ignored {
1291 &theme.ignored_entry
1292 } else {
1293 &theme.entry
1294 };
1295
1296 let show_editor = details.is_editing && !details.is_processing;
1297
1298 MouseEventHandler::<Self, _>::new(entry_id.to_usize(), cx, |state, cx| {
1299 let mut style = entry_style
1300 .in_state(details.is_selected)
1301 .style_for(state)
1302 .clone();
1303
1304 if cx
1305 .global::<DragAndDrop<Workspace>>()
1306 .currently_dragged::<ProjectEntryId>(cx.window_id())
1307 .is_some()
1308 && dragged_entry_destination
1309 .as_ref()
1310 .filter(|destination| details.path.starts_with(destination))
1311 .is_some()
1312 {
1313 style = entry_style.active_state().default.clone();
1314 }
1315
1316 let row_container_style = if show_editor {
1317 theme.filename_editor.container
1318 } else {
1319 style.container
1320 };
1321
1322 Self::render_entry_visual_element(
1323 &details,
1324 Some(editor),
1325 padding,
1326 row_container_style,
1327 &style,
1328 cx,
1329 )
1330 })
1331 .on_click(MouseButton::Left, move |event, this, cx| {
1332 if !show_editor {
1333 if kind.is_dir() {
1334 this.toggle_expanded(entry_id, cx);
1335 } else {
1336 this.open_entry(entry_id, event.click_count > 1, cx);
1337 }
1338 }
1339 })
1340 .on_down(MouseButton::Right, move |event, this, cx| {
1341 this.deploy_context_menu(event.position, entry_id, cx);
1342 })
1343 .on_up(MouseButton::Left, move |_, this, cx| {
1344 if let Some((_, dragged_entry)) = cx
1345 .global::<DragAndDrop<Workspace>>()
1346 .currently_dragged::<ProjectEntryId>(cx.window_id())
1347 {
1348 this.move_entry(
1349 *dragged_entry,
1350 entry_id,
1351 matches!(details.kind, EntryKind::File(_)),
1352 cx,
1353 );
1354 }
1355 })
1356 .on_move(move |_, this, cx| {
1357 if cx
1358 .global::<DragAndDrop<Workspace>>()
1359 .currently_dragged::<ProjectEntryId>(cx.window_id())
1360 .is_some()
1361 {
1362 this.dragged_entry_destination = if matches!(kind, EntryKind::File(_)) {
1363 path.parent().map(|parent| Arc::from(parent))
1364 } else {
1365 Some(path.clone())
1366 };
1367 }
1368 })
1369 .as_draggable(entry_id, {
1370 let row_container_style = theme.dragged_entry.container;
1371
1372 move |_, cx: &mut ViewContext<Workspace>| {
1373 let theme = theme::current(cx).clone();
1374 Self::render_entry_visual_element(
1375 &details,
1376 None,
1377 padding,
1378 row_container_style,
1379 &theme.project_panel.dragged_entry,
1380 cx,
1381 )
1382 }
1383 })
1384 .with_cursor_style(CursorStyle::PointingHand)
1385 .into_any_named("project panel entry")
1386 }
1387}
1388
1389impl View for ProjectPanel {
1390 fn ui_name() -> &'static str {
1391 "ProjectPanel"
1392 }
1393
1394 fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> gpui::AnyElement<Self> {
1395 enum ProjectPanel {}
1396 let theme = &theme::current(cx).project_panel;
1397 let mut container_style = theme.container;
1398 let padding = std::mem::take(&mut container_style.padding);
1399 let last_worktree_root_id = self.last_worktree_root_id;
1400
1401 let has_worktree = self.visible_entries.len() != 0;
1402
1403 if has_worktree {
1404 Stack::new()
1405 .with_child(
1406 MouseEventHandler::<ProjectPanel, _>::new(0, cx, |_, cx| {
1407 UniformList::new(
1408 self.list.clone(),
1409 self.visible_entries
1410 .iter()
1411 .map(|(_, worktree_entries)| worktree_entries.len())
1412 .sum(),
1413 cx,
1414 move |this, range, items, cx| {
1415 let theme = theme::current(cx).clone();
1416 let mut dragged_entry_destination =
1417 this.dragged_entry_destination.clone();
1418 this.for_each_visible_entry(range, cx, |id, details, cx| {
1419 items.push(Self::render_entry(
1420 id,
1421 details,
1422 &this.filename_editor,
1423 &mut dragged_entry_destination,
1424 &theme.project_panel,
1425 cx,
1426 ));
1427 });
1428 this.dragged_entry_destination = dragged_entry_destination;
1429 },
1430 )
1431 .with_padding_top(padding.top)
1432 .with_padding_bottom(padding.bottom)
1433 .contained()
1434 .with_style(container_style)
1435 .expanded()
1436 })
1437 .on_down(MouseButton::Right, move |event, this, cx| {
1438 // When deploying the context menu anywhere below the last project entry,
1439 // act as if the user clicked the root of the last worktree.
1440 if let Some(entry_id) = last_worktree_root_id {
1441 this.deploy_context_menu(event.position, entry_id, cx);
1442 }
1443 }),
1444 )
1445 .with_child(ChildView::new(&self.context_menu, cx))
1446 .into_any_named("project panel")
1447 } else {
1448 Flex::column()
1449 .with_child(
1450 MouseEventHandler::<Self, _>::new(2, cx, {
1451 let button_style = theme.open_project_button.clone();
1452 let context_menu_item_style = theme::current(cx).context_menu.item.clone();
1453 move |state, cx| {
1454 let button_style = button_style.style_for(state).clone();
1455 let context_menu_item = context_menu_item_style
1456 .active_state()
1457 .style_for(state)
1458 .clone();
1459
1460 theme::ui::keystroke_label(
1461 "Open a project",
1462 &button_style,
1463 &context_menu_item.keystroke,
1464 Box::new(workspace::Open),
1465 cx,
1466 )
1467 }
1468 })
1469 .on_click(MouseButton::Left, move |_, this, cx| {
1470 if let Some(workspace) = this.workspace.upgrade(cx) {
1471 workspace.update(cx, |workspace, cx| {
1472 if let Some(task) = workspace.open(&Default::default(), cx) {
1473 task.detach_and_log_err(cx);
1474 }
1475 })
1476 }
1477 })
1478 .with_cursor_style(CursorStyle::PointingHand),
1479 )
1480 .contained()
1481 .with_style(container_style)
1482 .into_any_named("empty project panel")
1483 }
1484 }
1485
1486 fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
1487 Self::reset_to_default_keymap_context(keymap);
1488 keymap.add_identifier("menu");
1489 }
1490
1491 fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {
1492 if !self.has_focus {
1493 self.has_focus = true;
1494 cx.emit(Event::Focus);
1495 }
1496 }
1497
1498 fn focus_out(&mut self, _: gpui::AnyViewHandle, _: &mut ViewContext<Self>) {
1499 self.has_focus = false;
1500 }
1501}
1502
1503impl Entity for ProjectPanel {
1504 type Event = Event;
1505}
1506
1507impl workspace::dock::Panel for ProjectPanel {
1508 fn position(&self, cx: &WindowContext) -> DockPosition {
1509 match settings::get::<ProjectPanelSettings>(cx).dock {
1510 ProjectPanelDockPosition::Left => DockPosition::Left,
1511 ProjectPanelDockPosition::Right => DockPosition::Right,
1512 }
1513 }
1514
1515 fn position_is_valid(&self, position: DockPosition) -> bool {
1516 matches!(position, DockPosition::Left | DockPosition::Right)
1517 }
1518
1519 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1520 settings::update_settings_file::<ProjectPanelSettings>(
1521 self.fs.clone(),
1522 cx,
1523 move |settings| {
1524 let dock = match position {
1525 DockPosition::Left | DockPosition::Bottom => ProjectPanelDockPosition::Left,
1526 DockPosition::Right => ProjectPanelDockPosition::Right,
1527 };
1528 settings.dock = Some(dock);
1529 },
1530 );
1531 }
1532
1533 fn size(&self, cx: &WindowContext) -> f32 {
1534 self.width
1535 .unwrap_or_else(|| settings::get::<ProjectPanelSettings>(cx).default_width)
1536 }
1537
1538 fn set_size(&mut self, size: f32, cx: &mut ViewContext<Self>) {
1539 self.width = Some(size);
1540 self.serialize(cx);
1541 cx.notify();
1542 }
1543
1544 fn should_zoom_in_on_event(_: &Self::Event) -> bool {
1545 false
1546 }
1547
1548 fn should_zoom_out_on_event(_: &Self::Event) -> bool {
1549 false
1550 }
1551
1552 fn is_zoomed(&self, _: &WindowContext) -> bool {
1553 false
1554 }
1555
1556 fn set_zoomed(&mut self, _: bool, _: &mut ViewContext<Self>) {}
1557
1558 fn set_active(&mut self, _: bool, _: &mut ViewContext<Self>) {}
1559
1560 fn icon_path(&self) -> &'static str {
1561 "icons/folder_tree_16.svg"
1562 }
1563
1564 fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
1565 ("Project Panel".into(), Some(Box::new(ToggleFocus)))
1566 }
1567
1568 fn should_change_position_on_event(event: &Self::Event) -> bool {
1569 matches!(event, Event::DockPositionChanged)
1570 }
1571
1572 fn should_activate_on_event(_: &Self::Event) -> bool {
1573 false
1574 }
1575
1576 fn should_close_on_event(_: &Self::Event) -> bool {
1577 false
1578 }
1579
1580 fn has_focus(&self, _: &WindowContext) -> bool {
1581 self.has_focus
1582 }
1583
1584 fn is_focus_event(event: &Self::Event) -> bool {
1585 matches!(event, Event::Focus)
1586 }
1587}
1588
1589impl ClipboardEntry {
1590 fn is_cut(&self) -> bool {
1591 matches!(self, Self::Cut { .. })
1592 }
1593
1594 fn entry_id(&self) -> ProjectEntryId {
1595 match self {
1596 ClipboardEntry::Copied { entry_id, .. } | ClipboardEntry::Cut { entry_id, .. } => {
1597 *entry_id
1598 }
1599 }
1600 }
1601
1602 fn worktree_id(&self) -> WorktreeId {
1603 match self {
1604 ClipboardEntry::Copied { worktree_id, .. }
1605 | ClipboardEntry::Cut { worktree_id, .. } => *worktree_id,
1606 }
1607 }
1608}
1609
1610#[cfg(test)]
1611mod tests {
1612 use super::*;
1613 use gpui::{TestAppContext, ViewHandle};
1614 use pretty_assertions::assert_eq;
1615 use project::FakeFs;
1616 use serde_json::json;
1617 use settings::SettingsStore;
1618 use std::{collections::HashSet, path::Path};
1619 use workspace::{pane, AppState};
1620
1621 #[gpui::test]
1622 async fn test_visible_list(cx: &mut gpui::TestAppContext) {
1623 init_test(cx);
1624
1625 let fs = FakeFs::new(cx.background());
1626 fs.insert_tree(
1627 "/root1",
1628 json!({
1629 ".dockerignore": "",
1630 ".git": {
1631 "HEAD": "",
1632 },
1633 "a": {
1634 "0": { "q": "", "r": "", "s": "" },
1635 "1": { "t": "", "u": "" },
1636 "2": { "v": "", "w": "", "x": "", "y": "" },
1637 },
1638 "b": {
1639 "3": { "Q": "" },
1640 "4": { "R": "", "S": "", "T": "", "U": "" },
1641 },
1642 "C": {
1643 "5": {},
1644 "6": { "V": "", "W": "" },
1645 "7": { "X": "" },
1646 "8": { "Y": {}, "Z": "" }
1647 }
1648 }),
1649 )
1650 .await;
1651 fs.insert_tree(
1652 "/root2",
1653 json!({
1654 "d": {
1655 "9": ""
1656 },
1657 "e": {}
1658 }),
1659 )
1660 .await;
1661
1662 let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
1663 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1664 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1665 assert_eq!(
1666 visible_entries_as_strings(&panel, 0..50, cx),
1667 &[
1668 "v root1",
1669 " > .git",
1670 " > a",
1671 " > b",
1672 " > C",
1673 " .dockerignore",
1674 "v root2",
1675 " > d",
1676 " > e",
1677 ]
1678 );
1679
1680 toggle_expand_dir(&panel, "root1/b", cx);
1681 assert_eq!(
1682 visible_entries_as_strings(&panel, 0..50, cx),
1683 &[
1684 "v root1",
1685 " > .git",
1686 " > a",
1687 " v b <== selected",
1688 " > 3",
1689 " > 4",
1690 " > C",
1691 " .dockerignore",
1692 "v root2",
1693 " > d",
1694 " > e",
1695 ]
1696 );
1697
1698 assert_eq!(
1699 visible_entries_as_strings(&panel, 6..9, cx),
1700 &[
1701 //
1702 " > C",
1703 " .dockerignore",
1704 "v root2",
1705 ]
1706 );
1707 }
1708
1709 #[gpui::test(iterations = 30)]
1710 async fn test_editing_files(cx: &mut gpui::TestAppContext) {
1711 init_test(cx);
1712
1713 let fs = FakeFs::new(cx.background());
1714 fs.insert_tree(
1715 "/root1",
1716 json!({
1717 ".dockerignore": "",
1718 ".git": {
1719 "HEAD": "",
1720 },
1721 "a": {
1722 "0": { "q": "", "r": "", "s": "" },
1723 "1": { "t": "", "u": "" },
1724 "2": { "v": "", "w": "", "x": "", "y": "" },
1725 },
1726 "b": {
1727 "3": { "Q": "" },
1728 "4": { "R": "", "S": "", "T": "", "U": "" },
1729 },
1730 "C": {
1731 "5": {},
1732 "6": { "V": "", "W": "" },
1733 "7": { "X": "" },
1734 "8": { "Y": {}, "Z": "" }
1735 }
1736 }),
1737 )
1738 .await;
1739 fs.insert_tree(
1740 "/root2",
1741 json!({
1742 "d": {
1743 "9": ""
1744 },
1745 "e": {}
1746 }),
1747 )
1748 .await;
1749
1750 let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
1751 let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1752 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
1753
1754 select_path(&panel, "root1", cx);
1755 assert_eq!(
1756 visible_entries_as_strings(&panel, 0..10, cx),
1757 &[
1758 "v root1 <== selected",
1759 " > .git",
1760 " > a",
1761 " > b",
1762 " > C",
1763 " .dockerignore",
1764 "v root2",
1765 " > d",
1766 " > e",
1767 ]
1768 );
1769
1770 // Add a file with the root folder selected. The filename editor is placed
1771 // before the first file in the root folder.
1772 panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
1773 cx.read_window(window_id, |cx| {
1774 let panel = panel.read(cx);
1775 assert!(panel.filename_editor.is_focused(cx));
1776 });
1777 assert_eq!(
1778 visible_entries_as_strings(&panel, 0..10, cx),
1779 &[
1780 "v root1",
1781 " > .git",
1782 " > a",
1783 " > b",
1784 " > C",
1785 " [EDITOR: ''] <== selected",
1786 " .dockerignore",
1787 "v root2",
1788 " > d",
1789 " > e",
1790 ]
1791 );
1792
1793 let confirm = panel.update(cx, |panel, cx| {
1794 panel
1795 .filename_editor
1796 .update(cx, |editor, cx| editor.set_text("the-new-filename", cx));
1797 panel.confirm(&Confirm, cx).unwrap()
1798 });
1799 assert_eq!(
1800 visible_entries_as_strings(&panel, 0..10, cx),
1801 &[
1802 "v root1",
1803 " > .git",
1804 " > a",
1805 " > b",
1806 " > C",
1807 " [PROCESSING: 'the-new-filename'] <== selected",
1808 " .dockerignore",
1809 "v root2",
1810 " > d",
1811 " > e",
1812 ]
1813 );
1814
1815 confirm.await.unwrap();
1816 assert_eq!(
1817 visible_entries_as_strings(&panel, 0..10, cx),
1818 &[
1819 "v root1",
1820 " > .git",
1821 " > a",
1822 " > b",
1823 " > C",
1824 " .dockerignore",
1825 " the-new-filename <== selected",
1826 "v root2",
1827 " > d",
1828 " > e",
1829 ]
1830 );
1831
1832 select_path(&panel, "root1/b", cx);
1833 panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
1834 assert_eq!(
1835 visible_entries_as_strings(&panel, 0..10, cx),
1836 &[
1837 "v root1",
1838 " > .git",
1839 " > a",
1840 " v b",
1841 " > 3",
1842 " > 4",
1843 " [EDITOR: ''] <== selected",
1844 " > C",
1845 " .dockerignore",
1846 " the-new-filename",
1847 ]
1848 );
1849
1850 panel
1851 .update(cx, |panel, cx| {
1852 panel
1853 .filename_editor
1854 .update(cx, |editor, cx| editor.set_text("another-filename", cx));
1855 panel.confirm(&Confirm, cx).unwrap()
1856 })
1857 .await
1858 .unwrap();
1859 assert_eq!(
1860 visible_entries_as_strings(&panel, 0..10, cx),
1861 &[
1862 "v root1",
1863 " > .git",
1864 " > a",
1865 " v b",
1866 " > 3",
1867 " > 4",
1868 " another-filename <== selected",
1869 " > C",
1870 " .dockerignore",
1871 " the-new-filename",
1872 ]
1873 );
1874
1875 select_path(&panel, "root1/b/another-filename", cx);
1876 panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
1877 assert_eq!(
1878 visible_entries_as_strings(&panel, 0..10, cx),
1879 &[
1880 "v root1",
1881 " > .git",
1882 " > a",
1883 " v b",
1884 " > 3",
1885 " > 4",
1886 " [EDITOR: 'another-filename'] <== selected",
1887 " > C",
1888 " .dockerignore",
1889 " the-new-filename",
1890 ]
1891 );
1892
1893 let confirm = panel.update(cx, |panel, cx| {
1894 panel
1895 .filename_editor
1896 .update(cx, |editor, cx| editor.set_text("a-different-filename", cx));
1897 panel.confirm(&Confirm, cx).unwrap()
1898 });
1899 assert_eq!(
1900 visible_entries_as_strings(&panel, 0..10, cx),
1901 &[
1902 "v root1",
1903 " > .git",
1904 " > a",
1905 " v b",
1906 " > 3",
1907 " > 4",
1908 " [PROCESSING: 'a-different-filename'] <== selected",
1909 " > C",
1910 " .dockerignore",
1911 " the-new-filename",
1912 ]
1913 );
1914
1915 confirm.await.unwrap();
1916 assert_eq!(
1917 visible_entries_as_strings(&panel, 0..10, cx),
1918 &[
1919 "v root1",
1920 " > .git",
1921 " > a",
1922 " v b",
1923 " > 3",
1924 " > 4",
1925 " a-different-filename <== selected",
1926 " > C",
1927 " .dockerignore",
1928 " the-new-filename",
1929 ]
1930 );
1931
1932 panel.update(cx, |panel, cx| panel.new_directory(&NewDirectory, cx));
1933 assert_eq!(
1934 visible_entries_as_strings(&panel, 0..10, cx),
1935 &[
1936 "v root1",
1937 " > .git",
1938 " > a",
1939 " v b",
1940 " > [EDITOR: ''] <== selected",
1941 " > 3",
1942 " > 4",
1943 " a-different-filename",
1944 " > C",
1945 " .dockerignore",
1946 ]
1947 );
1948
1949 let confirm = panel.update(cx, |panel, cx| {
1950 panel
1951 .filename_editor
1952 .update(cx, |editor, cx| editor.set_text("new-dir", cx));
1953 panel.confirm(&Confirm, cx).unwrap()
1954 });
1955 panel.update(cx, |panel, cx| panel.select_next(&Default::default(), cx));
1956 assert_eq!(
1957 visible_entries_as_strings(&panel, 0..10, cx),
1958 &[
1959 "v root1",
1960 " > .git",
1961 " > a",
1962 " v b",
1963 " > [PROCESSING: 'new-dir']",
1964 " > 3 <== selected",
1965 " > 4",
1966 " a-different-filename",
1967 " > C",
1968 " .dockerignore",
1969 ]
1970 );
1971
1972 confirm.await.unwrap();
1973 assert_eq!(
1974 visible_entries_as_strings(&panel, 0..10, cx),
1975 &[
1976 "v root1",
1977 " > .git",
1978 " > a",
1979 " v b",
1980 " > 3 <== selected",
1981 " > 4",
1982 " > new-dir",
1983 " a-different-filename",
1984 " > C",
1985 " .dockerignore",
1986 ]
1987 );
1988
1989 panel.update(cx, |panel, cx| panel.rename(&Default::default(), cx));
1990 assert_eq!(
1991 visible_entries_as_strings(&panel, 0..10, cx),
1992 &[
1993 "v root1",
1994 " > .git",
1995 " > a",
1996 " v b",
1997 " > [EDITOR: '3'] <== selected",
1998 " > 4",
1999 " > new-dir",
2000 " a-different-filename",
2001 " > C",
2002 " .dockerignore",
2003 ]
2004 );
2005
2006 // Dismiss the rename editor when it loses focus.
2007 workspace.update(cx, |_, cx| cx.focus_self());
2008 assert_eq!(
2009 visible_entries_as_strings(&panel, 0..10, cx),
2010 &[
2011 "v root1",
2012 " > .git",
2013 " > a",
2014 " v b",
2015 " > 3 <== selected",
2016 " > 4",
2017 " > new-dir",
2018 " a-different-filename",
2019 " > C",
2020 " .dockerignore",
2021 ]
2022 );
2023 }
2024
2025 #[gpui::test(iterations = 30)]
2026 async fn test_adding_directories_via_file(cx: &mut gpui::TestAppContext) {
2027 init_test(cx);
2028
2029 let fs = FakeFs::new(cx.background());
2030 fs.insert_tree(
2031 "/root1",
2032 json!({
2033 ".dockerignore": "",
2034 ".git": {
2035 "HEAD": "",
2036 },
2037 "a": {
2038 "0": { "q": "", "r": "", "s": "" },
2039 "1": { "t": "", "u": "" },
2040 "2": { "v": "", "w": "", "x": "", "y": "" },
2041 },
2042 "b": {
2043 "3": { "Q": "" },
2044 "4": { "R": "", "S": "", "T": "", "U": "" },
2045 },
2046 "C": {
2047 "5": {},
2048 "6": { "V": "", "W": "" },
2049 "7": { "X": "" },
2050 "8": { "Y": {}, "Z": "" }
2051 }
2052 }),
2053 )
2054 .await;
2055 fs.insert_tree(
2056 "/root2",
2057 json!({
2058 "d": {
2059 "9": ""
2060 },
2061 "e": {}
2062 }),
2063 )
2064 .await;
2065
2066 let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
2067 let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2068 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
2069
2070 select_path(&panel, "root1", cx);
2071 assert_eq!(
2072 visible_entries_as_strings(&panel, 0..10, cx),
2073 &[
2074 "v root1 <== selected",
2075 " > .git",
2076 " > a",
2077 " > b",
2078 " > C",
2079 " .dockerignore",
2080 "v root2",
2081 " > d",
2082 " > e",
2083 ]
2084 );
2085
2086 // Add a file with the root folder selected. The filename editor is placed
2087 // before the first file in the root folder.
2088 panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
2089 cx.read_window(window_id, |cx| {
2090 let panel = panel.read(cx);
2091 assert!(panel.filename_editor.is_focused(cx));
2092 });
2093 assert_eq!(
2094 visible_entries_as_strings(&panel, 0..10, cx),
2095 &[
2096 "v root1",
2097 " > .git",
2098 " > a",
2099 " > b",
2100 " > C",
2101 " [EDITOR: ''] <== selected",
2102 " .dockerignore",
2103 "v root2",
2104 " > d",
2105 " > e",
2106 ]
2107 );
2108
2109 let confirm = panel.update(cx, |panel, cx| {
2110 panel.filename_editor.update(cx, |editor, cx| {
2111 editor.set_text("/bdir1/dir2/the-new-filename", cx)
2112 });
2113 panel.confirm(&Confirm, cx).unwrap()
2114 });
2115
2116 assert_eq!(
2117 visible_entries_as_strings(&panel, 0..10, cx),
2118 &[
2119 "v root1",
2120 " > .git",
2121 " > a",
2122 " > b",
2123 " > C",
2124 " [PROCESSING: '/bdir1/dir2/the-new-filename'] <== selected",
2125 " .dockerignore",
2126 "v root2",
2127 " > d",
2128 " > e",
2129 ]
2130 );
2131
2132 confirm.await.unwrap();
2133 assert_eq!(
2134 visible_entries_as_strings(&panel, 0..13, cx),
2135 &[
2136 "v root1",
2137 " > .git",
2138 " > a",
2139 " > b",
2140 " v bdir1",
2141 " v dir2",
2142 " the-new-filename <== selected",
2143 " > C",
2144 " .dockerignore",
2145 "v root2",
2146 " > d",
2147 " > e",
2148 ]
2149 );
2150 }
2151
2152 #[gpui::test]
2153 async fn test_copy_paste(cx: &mut gpui::TestAppContext) {
2154 init_test(cx);
2155
2156 let fs = FakeFs::new(cx.background());
2157 fs.insert_tree(
2158 "/root1",
2159 json!({
2160 "one.two.txt": "",
2161 "one.txt": ""
2162 }),
2163 )
2164 .await;
2165
2166 let project = Project::test(fs.clone(), ["/root1".as_ref()], cx).await;
2167 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2168 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
2169
2170 panel.update(cx, |panel, cx| {
2171 panel.select_next(&Default::default(), cx);
2172 panel.select_next(&Default::default(), cx);
2173 });
2174
2175 assert_eq!(
2176 visible_entries_as_strings(&panel, 0..50, cx),
2177 &[
2178 //
2179 "v root1",
2180 " one.two.txt <== selected",
2181 " one.txt",
2182 ]
2183 );
2184
2185 // Regression test - file name is created correctly when
2186 // the copied file's name contains multiple dots.
2187 panel.update(cx, |panel, cx| {
2188 panel.copy(&Default::default(), cx);
2189 panel.paste(&Default::default(), cx);
2190 });
2191 cx.foreground().run_until_parked();
2192
2193 assert_eq!(
2194 visible_entries_as_strings(&panel, 0..50, cx),
2195 &[
2196 //
2197 "v root1",
2198 " one.two copy.txt",
2199 " one.two.txt <== selected",
2200 " one.txt",
2201 ]
2202 );
2203
2204 panel.update(cx, |panel, cx| {
2205 panel.paste(&Default::default(), cx);
2206 });
2207 cx.foreground().run_until_parked();
2208
2209 assert_eq!(
2210 visible_entries_as_strings(&panel, 0..50, cx),
2211 &[
2212 //
2213 "v root1",
2214 " one.two copy 1.txt",
2215 " one.two copy.txt",
2216 " one.two.txt <== selected",
2217 " one.txt",
2218 ]
2219 );
2220 }
2221
2222 #[gpui::test]
2223 async fn test_remove_opened_file(cx: &mut gpui::TestAppContext) {
2224 init_test_with_editor(cx);
2225
2226 let fs = FakeFs::new(cx.background());
2227 fs.insert_tree(
2228 "/src",
2229 json!({
2230 "test": {
2231 "first.rs": "// First Rust file",
2232 "second.rs": "// Second Rust file",
2233 "third.rs": "// Third Rust file",
2234 }
2235 }),
2236 )
2237 .await;
2238
2239 let project = Project::test(fs.clone(), ["/src".as_ref()], cx).await;
2240 let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2241 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
2242
2243 toggle_expand_dir(&panel, "src/test", cx);
2244 select_path(&panel, "src/test/first.rs", cx);
2245 panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
2246 cx.foreground().run_until_parked();
2247 assert_eq!(
2248 visible_entries_as_strings(&panel, 0..10, cx),
2249 &[
2250 "v src",
2251 " v test",
2252 " first.rs <== selected",
2253 " second.rs",
2254 " third.rs"
2255 ]
2256 );
2257 ensure_single_file_is_opened(window_id, &workspace, "test/first.rs", cx);
2258
2259 submit_deletion(window_id, &panel, cx);
2260 assert_eq!(
2261 visible_entries_as_strings(&panel, 0..10, cx),
2262 &[
2263 "v src",
2264 " v test",
2265 " second.rs",
2266 " third.rs"
2267 ],
2268 "Project panel should have no deleted file, no other file is selected in it"
2269 );
2270 ensure_no_open_items_and_panes(window_id, &workspace, cx);
2271
2272 select_path(&panel, "src/test/second.rs", cx);
2273 panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
2274 cx.foreground().run_until_parked();
2275 assert_eq!(
2276 visible_entries_as_strings(&panel, 0..10, cx),
2277 &[
2278 "v src",
2279 " v test",
2280 " second.rs <== selected",
2281 " third.rs"
2282 ]
2283 );
2284 ensure_single_file_is_opened(window_id, &workspace, "test/second.rs", cx);
2285
2286 cx.update_window(window_id, |cx| {
2287 let active_items = workspace
2288 .read(cx)
2289 .panes()
2290 .iter()
2291 .filter_map(|pane| pane.read(cx).active_item())
2292 .collect::<Vec<_>>();
2293 assert_eq!(active_items.len(), 1);
2294 let open_editor = active_items
2295 .into_iter()
2296 .next()
2297 .unwrap()
2298 .downcast::<Editor>()
2299 .expect("Open item should be an editor");
2300 open_editor.update(cx, |editor, cx| editor.set_text("Another text!", cx));
2301 });
2302 submit_deletion(window_id, &panel, cx);
2303 assert_eq!(
2304 visible_entries_as_strings(&panel, 0..10, cx),
2305 &["v src", " v test", " third.rs"],
2306 "Project panel should have no deleted file, with one last file remaining"
2307 );
2308 ensure_no_open_items_and_panes(window_id, &workspace, cx);
2309 }
2310
2311 #[gpui::test]
2312 async fn test_create_duplicate_items(cx: &mut gpui::TestAppContext) {
2313 init_test_with_editor(cx);
2314
2315 let fs = FakeFs::new(cx.background());
2316 fs.insert_tree(
2317 "/src",
2318 json!({
2319 "test": {
2320 "first.rs": "// First Rust file",
2321 "second.rs": "// Second Rust file",
2322 "third.rs": "// Third Rust file",
2323 }
2324 }),
2325 )
2326 .await;
2327
2328 let project = Project::test(fs.clone(), ["/src".as_ref()], cx).await;
2329 let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2330 let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
2331
2332 select_path(&panel, "src/", cx);
2333 panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
2334 cx.foreground().run_until_parked();
2335 assert_eq!(
2336 visible_entries_as_strings(&panel, 0..10, cx),
2337 &["v src <== selected", " > test"]
2338 );
2339 panel.update(cx, |panel, cx| panel.new_directory(&NewDirectory, cx));
2340 cx.read_window(window_id, |cx| {
2341 let panel = panel.read(cx);
2342 assert!(panel.filename_editor.is_focused(cx));
2343 });
2344 assert_eq!(
2345 visible_entries_as_strings(&panel, 0..10, cx),
2346 &["v src", " > [EDITOR: ''] <== selected", " > test"]
2347 );
2348 panel.update(cx, |panel, cx| {
2349 panel
2350 .filename_editor
2351 .update(cx, |editor, cx| editor.set_text("test", cx));
2352 assert!(
2353 panel.confirm(&Confirm, cx).is_none(),
2354 "Should not allow to confirm on conflicting new directory name"
2355 )
2356 });
2357 assert_eq!(
2358 visible_entries_as_strings(&panel, 0..10, cx),
2359 &["v src", " > test"],
2360 "File list should be unchanged after failed folder create confirmation"
2361 );
2362
2363 select_path(&panel, "src/test/", cx);
2364 panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
2365 cx.foreground().run_until_parked();
2366 assert_eq!(
2367 visible_entries_as_strings(&panel, 0..10, cx),
2368 &["v src", " > test <== selected"]
2369 );
2370 panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
2371 cx.read_window(window_id, |cx| {
2372 let panel = panel.read(cx);
2373 assert!(panel.filename_editor.is_focused(cx));
2374 });
2375 assert_eq!(
2376 visible_entries_as_strings(&panel, 0..10, cx),
2377 &[
2378 "v src",
2379 " v test",
2380 " [EDITOR: ''] <== selected",
2381 " first.rs",
2382 " second.rs",
2383 " third.rs"
2384 ]
2385 );
2386 panel.update(cx, |panel, cx| {
2387 panel
2388 .filename_editor
2389 .update(cx, |editor, cx| editor.set_text("first.rs", cx));
2390 assert!(
2391 panel.confirm(&Confirm, cx).is_none(),
2392 "Should not allow to confirm on conflicting new file name"
2393 )
2394 });
2395 assert_eq!(
2396 visible_entries_as_strings(&panel, 0..10, cx),
2397 &[
2398 "v src",
2399 " v test",
2400 " first.rs",
2401 " second.rs",
2402 " third.rs"
2403 ],
2404 "File list should be unchanged after failed file create confirmation"
2405 );
2406
2407 select_path(&panel, "src/test/first.rs", cx);
2408 panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
2409 cx.foreground().run_until_parked();
2410 assert_eq!(
2411 visible_entries_as_strings(&panel, 0..10, cx),
2412 &[
2413 "v src",
2414 " v test",
2415 " first.rs <== selected",
2416 " second.rs",
2417 " third.rs"
2418 ],
2419 );
2420 panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
2421 cx.read_window(window_id, |cx| {
2422 let panel = panel.read(cx);
2423 assert!(panel.filename_editor.is_focused(cx));
2424 });
2425 assert_eq!(
2426 visible_entries_as_strings(&panel, 0..10, cx),
2427 &[
2428 "v src",
2429 " v test",
2430 " [EDITOR: 'first.rs'] <== selected",
2431 " second.rs",
2432 " third.rs"
2433 ]
2434 );
2435 panel.update(cx, |panel, cx| {
2436 panel
2437 .filename_editor
2438 .update(cx, |editor, cx| editor.set_text("second.rs", cx));
2439 assert!(
2440 panel.confirm(&Confirm, cx).is_none(),
2441 "Should not allow to confirm on conflicting file rename"
2442 )
2443 });
2444 assert_eq!(
2445 visible_entries_as_strings(&panel, 0..10, cx),
2446 &[
2447 "v src",
2448 " v test",
2449 " first.rs <== selected",
2450 " second.rs",
2451 " third.rs"
2452 ],
2453 "File list should be unchanged after failed rename confirmation"
2454 );
2455 }
2456
2457 fn toggle_expand_dir(
2458 panel: &ViewHandle<ProjectPanel>,
2459 path: impl AsRef<Path>,
2460 cx: &mut TestAppContext,
2461 ) {
2462 let path = path.as_ref();
2463 panel.update(cx, |panel, cx| {
2464 for worktree in panel.project.read(cx).worktrees(cx).collect::<Vec<_>>() {
2465 let worktree = worktree.read(cx);
2466 if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
2467 let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
2468 panel.toggle_expanded(entry_id, cx);
2469 return;
2470 }
2471 }
2472 panic!("no worktree for path {:?}", path);
2473 });
2474 }
2475
2476 fn select_path(
2477 panel: &ViewHandle<ProjectPanel>,
2478 path: impl AsRef<Path>,
2479 cx: &mut TestAppContext,
2480 ) {
2481 let path = path.as_ref();
2482 panel.update(cx, |panel, cx| {
2483 for worktree in panel.project.read(cx).worktrees(cx).collect::<Vec<_>>() {
2484 let worktree = worktree.read(cx);
2485 if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
2486 let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
2487 panel.selection = Some(Selection {
2488 worktree_id: worktree.id(),
2489 entry_id,
2490 });
2491 return;
2492 }
2493 }
2494 panic!("no worktree for path {:?}", path);
2495 });
2496 }
2497
2498 fn visible_entries_as_strings(
2499 panel: &ViewHandle<ProjectPanel>,
2500 range: Range<usize>,
2501 cx: &mut TestAppContext,
2502 ) -> Vec<String> {
2503 let mut result = Vec::new();
2504 let mut project_entries = HashSet::new();
2505 let mut has_editor = false;
2506
2507 panel.update(cx, |panel, cx| {
2508 panel.for_each_visible_entry(range, cx, |project_entry, details, _| {
2509 if details.is_editing {
2510 assert!(!has_editor, "duplicate editor entry");
2511 has_editor = true;
2512 } else {
2513 assert!(
2514 project_entries.insert(project_entry),
2515 "duplicate project entry {:?} {:?}",
2516 project_entry,
2517 details
2518 );
2519 }
2520
2521 let indent = " ".repeat(details.depth);
2522 let icon = if details.kind.is_dir() {
2523 if details.is_expanded {
2524 "v "
2525 } else {
2526 "> "
2527 }
2528 } else {
2529 " "
2530 };
2531 let name = if details.is_editing {
2532 format!("[EDITOR: '{}']", details.filename)
2533 } else if details.is_processing {
2534 format!("[PROCESSING: '{}']", details.filename)
2535 } else {
2536 details.filename.clone()
2537 };
2538 let selected = if details.is_selected {
2539 " <== selected"
2540 } else {
2541 ""
2542 };
2543 result.push(format!("{indent}{icon}{name}{selected}"));
2544 });
2545 });
2546
2547 result
2548 }
2549
2550 fn init_test(cx: &mut TestAppContext) {
2551 cx.foreground().forbid_parking();
2552 cx.update(|cx| {
2553 cx.set_global(SettingsStore::test(cx));
2554 init_settings(cx);
2555 theme::init((), cx);
2556 language::init(cx);
2557 editor::init_settings(cx);
2558 crate::init(cx);
2559 workspace::init_settings(cx);
2560 Project::init_settings(cx);
2561 });
2562 }
2563
2564 fn init_test_with_editor(cx: &mut TestAppContext) {
2565 cx.foreground().forbid_parking();
2566 cx.update(|cx| {
2567 let app_state = AppState::test(cx);
2568 theme::init((), cx);
2569 init_settings(cx);
2570 language::init(cx);
2571 editor::init(cx);
2572 pane::init(cx);
2573 crate::init(cx);
2574 workspace::init(app_state.clone(), cx);
2575 Project::init_settings(cx);
2576 });
2577 }
2578
2579 fn ensure_single_file_is_opened(
2580 window_id: usize,
2581 workspace: &ViewHandle<Workspace>,
2582 expected_path: &str,
2583 cx: &mut TestAppContext,
2584 ) {
2585 cx.read_window(window_id, |cx| {
2586 let workspace = workspace.read(cx);
2587 let worktrees = workspace.worktrees(cx).collect::<Vec<_>>();
2588 assert_eq!(worktrees.len(), 1);
2589 let worktree_id = WorktreeId::from_usize(worktrees[0].id());
2590
2591 let open_project_paths = workspace
2592 .panes()
2593 .iter()
2594 .filter_map(|pane| pane.read(cx).active_item()?.project_path(cx))
2595 .collect::<Vec<_>>();
2596 assert_eq!(
2597 open_project_paths,
2598 vec![ProjectPath {
2599 worktree_id,
2600 path: Arc::from(Path::new(expected_path))
2601 }],
2602 "Should have opened file, selected in project panel"
2603 );
2604 });
2605 }
2606
2607 fn submit_deletion(
2608 window_id: usize,
2609 panel: &ViewHandle<ProjectPanel>,
2610 cx: &mut TestAppContext,
2611 ) {
2612 assert!(
2613 !cx.has_pending_prompt(window_id),
2614 "Should have no prompts before the deletion"
2615 );
2616 panel.update(cx, |panel, cx| {
2617 panel
2618 .delete(&Delete, cx)
2619 .expect("Deletion start")
2620 .detach_and_log_err(cx);
2621 });
2622 assert!(
2623 cx.has_pending_prompt(window_id),
2624 "Should have a prompt after the deletion"
2625 );
2626 cx.simulate_prompt_answer(window_id, 0);
2627 assert!(
2628 !cx.has_pending_prompt(window_id),
2629 "Should have no prompts after prompt was replied to"
2630 );
2631 cx.foreground().run_until_parked();
2632 }
2633
2634 fn ensure_no_open_items_and_panes(
2635 window_id: usize,
2636 workspace: &ViewHandle<Workspace>,
2637 cx: &mut TestAppContext,
2638 ) {
2639 assert!(
2640 !cx.has_pending_prompt(window_id),
2641 "Should have no prompts after deletion operation closes the file"
2642 );
2643 cx.read_window(window_id, |cx| {
2644 let open_project_paths = workspace
2645 .read(cx)
2646 .panes()
2647 .iter()
2648 .filter_map(|pane| pane.read(cx).active_item()?.project_path(cx))
2649 .collect::<Vec<_>>();
2650 assert!(
2651 open_project_paths.is_empty(),
2652 "Deleted file's buffer should be closed, but got open files: {open_project_paths:?}"
2653 );
2654 });
2655 }
2656}