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