1mod project_panel_settings;
2mod utils;
3
4use anyhow::{Context as _, Result};
5use client::{ErrorCode, ErrorExt};
6use collections::{BTreeSet, HashMap, hash_map};
7use command_palette_hooks::CommandPaletteFilter;
8use db::kvp::KEY_VALUE_STORE;
9use editor::{
10 Editor, EditorEvent,
11 items::{
12 entry_diagnostic_aware_icon_decoration_and_color,
13 entry_diagnostic_aware_icon_name_and_color, entry_git_aware_label_color,
14 },
15};
16use file_icons::FileIcons;
17use git::status::GitSummary;
18use git_ui::file_diff_view::FileDiffView;
19use gpui::{
20 Action, AnyElement, App, ArcCow, AsyncWindowContext, Bounds, ClipboardItem, Context,
21 CursorStyle, DismissEvent, Div, DragMoveEvent, Entity, EventEmitter, ExternalPaths,
22 FocusHandle, Focusable, Hsla, InteractiveElement, KeyContext, ListHorizontalSizingBehavior,
23 ListSizingBehavior, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
24 ParentElement, Pixels, Point, PromptLevel, Render, ScrollStrategy, Stateful, Styled,
25 Subscription, Task, UniformListScrollHandle, WeakEntity, Window, actions, anchored, deferred,
26 div, hsla, linear_color_stop, linear_gradient, point, px, size, transparent_white,
27 uniform_list,
28};
29use indexmap::IndexMap;
30use language::DiagnosticSeverity;
31use menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
32use project::{
33 Entry, EntryKind, Fs, GitEntry, GitEntryRef, GitTraversal, Project, ProjectEntryId,
34 ProjectPath, Worktree, WorktreeId,
35 git_store::{GitStoreEvent, git_traversal::ChildEntriesGitIter},
36 project_settings::GoToDiagnosticSeverityFilter,
37 relativize_path,
38};
39use project_panel_settings::ProjectPanelSettings;
40use schemars::JsonSchema;
41use serde::{Deserialize, Serialize};
42use settings::{
43 DockSide, ProjectPanelEntrySpacing, Settings, SettingsStore, ShowDiagnostics, ShowIndentGuides,
44 update_settings_file,
45};
46use smallvec::SmallVec;
47use std::{any::TypeId, time::Instant};
48use std::{
49 cell::OnceCell,
50 cmp,
51 collections::HashSet,
52 ffi::OsStr,
53 ops::Range,
54 path::{Path, PathBuf},
55 sync::Arc,
56 time::Duration,
57};
58use theme::ThemeSettings;
59use ui::{
60 Color, ContextMenu, DecoratedIcon, Divider, Icon, IconDecoration, IconDecorationKind,
61 IndentGuideColors, IndentGuideLayout, KeyBinding, Label, LabelSize, ListItem, ListItemSpacing,
62 ScrollAxes, ScrollableHandle, Scrollbars, StickyCandidate, Tooltip, WithScrollbar, prelude::*,
63 v_flex,
64};
65use util::{ResultExt, TakeUntilExt, TryFutureExt, maybe, paths::compare_paths};
66use workspace::{
67 DraggedSelection, OpenInTerminal, OpenOptions, OpenVisible, PreviewTabsSettings, SelectedEntry,
68 SplitDirection, Workspace,
69 dock::{DockPosition, Panel, PanelEvent},
70 notifications::{DetachAndPromptErr, NotifyTaskExt},
71};
72use worktree::CreatedEntry;
73use zed_actions::workspace::OpenWithSystem;
74
75const PROJECT_PANEL_KEY: &str = "ProjectPanel";
76const NEW_ENTRY_ID: ProjectEntryId = ProjectEntryId::MAX;
77
78struct VisibleEntriesForWorktree {
79 worktree_id: WorktreeId,
80 entries: Vec<GitEntry>,
81 index: OnceCell<HashSet<Arc<Path>>>,
82}
83
84pub struct ProjectPanel {
85 project: Entity<Project>,
86 fs: Arc<dyn Fs>,
87 focus_handle: FocusHandle,
88 scroll_handle: UniformListScrollHandle,
89 // An update loop that keeps incrementing/decrementing scroll offset while there is a dragged entry that's
90 // hovered over the start/end of a list.
91 hover_scroll_task: Option<Task<()>>,
92 visible_entries: Vec<VisibleEntriesForWorktree>,
93 /// Maps from leaf project entry ID to the currently selected ancestor.
94 /// Relevant only for auto-fold dirs, where a single project panel entry may actually consist of several
95 /// project entries (and all non-leaf nodes are guaranteed to be directories).
96 ancestors: HashMap<ProjectEntryId, FoldedAncestors>,
97 folded_directory_drag_target: Option<FoldedDirectoryDragTarget>,
98 last_worktree_root_id: Option<ProjectEntryId>,
99 drag_target_entry: Option<DragTarget>,
100 expanded_dir_ids: HashMap<WorktreeId, Vec<ProjectEntryId>>,
101 unfolded_dir_ids: HashSet<ProjectEntryId>,
102 // Currently selected leaf entry (see auto-folding for a definition of that) in a file tree
103 selection: Option<SelectedEntry>,
104 marked_entries: Vec<SelectedEntry>,
105 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
106 edit_state: Option<EditState>,
107 filename_editor: Entity<Editor>,
108 clipboard: Option<ClipboardEntry>,
109 _dragged_entry_destination: Option<Arc<Path>>,
110 workspace: WeakEntity<Workspace>,
111 width: Option<Pixels>,
112 pending_serialization: Task<Option<()>>,
113 diagnostics: HashMap<(WorktreeId, PathBuf), DiagnosticSeverity>,
114 max_width_item_index: Option<usize>,
115 diagnostic_summary_update: Task<()>,
116 // We keep track of the mouse down state on entries so we don't flash the UI
117 // in case a user clicks to open a file.
118 mouse_down: bool,
119 hover_expand_task: Option<Task<()>>,
120 previous_drag_position: Option<Point<Pixels>>,
121 sticky_items_count: usize,
122 last_reported_update: Instant,
123}
124
125enum DragTarget {
126 /// Dragging on an entry
127 Entry {
128 /// The entry currently under the mouse cursor during a drag operation
129 entry_id: ProjectEntryId,
130 /// Highlight this entry along with all of its children
131 highlight_entry_id: ProjectEntryId,
132 },
133 /// Dragging on background
134 Background,
135}
136
137#[derive(Copy, Clone, Debug)]
138struct FoldedDirectoryDragTarget {
139 entry_id: ProjectEntryId,
140 index: usize,
141 /// Whether we are dragging over the delimiter rather than the component itself.
142 is_delimiter_target: bool,
143}
144
145#[derive(Clone, Debug)]
146enum ValidationState {
147 None,
148 Warning(String),
149 Error(String),
150}
151
152#[derive(Clone, Debug)]
153struct EditState {
154 worktree_id: WorktreeId,
155 entry_id: ProjectEntryId,
156 leaf_entry_id: Option<ProjectEntryId>,
157 is_dir: bool,
158 depth: usize,
159 processing_filename: Option<String>,
160 previously_focused: Option<SelectedEntry>,
161 validation_state: ValidationState,
162}
163
164impl EditState {
165 fn is_new_entry(&self) -> bool {
166 self.leaf_entry_id.is_none()
167 }
168}
169
170#[derive(Clone, Debug)]
171enum ClipboardEntry {
172 Copied(BTreeSet<SelectedEntry>),
173 Cut(BTreeSet<SelectedEntry>),
174}
175
176#[derive(Debug, PartialEq, Eq, Clone)]
177struct EntryDetails {
178 filename: String,
179 icon: Option<SharedString>,
180 path: Arc<Path>,
181 depth: usize,
182 kind: EntryKind,
183 is_ignored: bool,
184 is_expanded: bool,
185 is_selected: bool,
186 is_marked: bool,
187 is_editing: bool,
188 is_processing: bool,
189 is_cut: bool,
190 sticky: Option<StickyDetails>,
191 filename_text_color: Color,
192 diagnostic_severity: Option<DiagnosticSeverity>,
193 git_status: GitSummary,
194 is_private: bool,
195 worktree_id: WorktreeId,
196 canonical_path: Option<Arc<Path>>,
197}
198
199#[derive(Debug, PartialEq, Eq, Clone)]
200struct StickyDetails {
201 sticky_index: usize,
202}
203
204/// Permanently deletes the selected file or directory.
205#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
206#[action(namespace = project_panel)]
207#[serde(deny_unknown_fields)]
208struct Delete {
209 #[serde(default)]
210 pub skip_prompt: bool,
211}
212
213/// Moves the selected file or directory to the system trash.
214#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
215#[action(namespace = project_panel)]
216#[serde(deny_unknown_fields)]
217struct Trash {
218 #[serde(default)]
219 pub skip_prompt: bool,
220}
221
222/// Selects the next entry with diagnostics.
223#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
224#[action(namespace = project_panel)]
225#[serde(deny_unknown_fields)]
226struct SelectNextDiagnostic {
227 #[serde(default)]
228 pub severity: GoToDiagnosticSeverityFilter,
229}
230
231/// Selects the previous entry with diagnostics.
232#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
233#[action(namespace = project_panel)]
234#[serde(deny_unknown_fields)]
235struct SelectPrevDiagnostic {
236 #[serde(default)]
237 pub severity: GoToDiagnosticSeverityFilter,
238}
239
240actions!(
241 project_panel,
242 [
243 /// Expands the selected entry in the project tree.
244 ExpandSelectedEntry,
245 /// Collapses the selected entry in the project tree.
246 CollapseSelectedEntry,
247 /// Collapses all entries in the project tree.
248 CollapseAllEntries,
249 /// Creates a new directory.
250 NewDirectory,
251 /// Creates a new file.
252 NewFile,
253 /// Copies the selected file or directory.
254 Copy,
255 /// Duplicates the selected file or directory.
256 Duplicate,
257 /// Reveals the selected item in the system file manager.
258 RevealInFileManager,
259 /// Removes the selected folder from the project.
260 RemoveFromProject,
261 /// Cuts the selected file or directory.
262 Cut,
263 /// Pastes the previously cut or copied item.
264 Paste,
265 /// Renames the selected file or directory.
266 Rename,
267 /// Opens the selected file in the editor.
268 Open,
269 /// Opens the selected file in a permanent tab.
270 OpenPermanent,
271 /// Opens the selected file in a vertical split.
272 OpenSplitVertical,
273 /// Opens the selected file in a horizontal split.
274 OpenSplitHorizontal,
275 /// Toggles focus on the project panel.
276 ToggleFocus,
277 /// Toggles visibility of git-ignored files.
278 ToggleHideGitIgnore,
279 /// Starts a new search in the selected directory.
280 NewSearchInDirectory,
281 /// Unfolds the selected directory.
282 UnfoldDirectory,
283 /// Folds the selected directory.
284 FoldDirectory,
285 /// Selects the parent directory.
286 SelectParent,
287 /// Selects the next entry with git changes.
288 SelectNextGitEntry,
289 /// Selects the previous entry with git changes.
290 SelectPrevGitEntry,
291 /// Selects the next directory.
292 SelectNextDirectory,
293 /// Selects the previous directory.
294 SelectPrevDirectory,
295 /// Opens a diff view to compare two marked files.
296 CompareMarkedFiles,
297 ]
298);
299
300#[derive(Debug, Default)]
301struct FoldedAncestors {
302 current_ancestor_depth: usize,
303 ancestors: Vec<ProjectEntryId>,
304}
305
306impl FoldedAncestors {
307 fn max_ancestor_depth(&self) -> usize {
308 self.ancestors.len()
309 }
310
311 /// Note: This returns None for last item in ancestors list
312 fn active_ancestor(&self) -> Option<ProjectEntryId> {
313 if self.current_ancestor_depth == 0 {
314 return None;
315 }
316 self.ancestors.get(self.current_ancestor_depth).copied()
317 }
318
319 fn active_index(&self) -> usize {
320 self.max_ancestor_depth()
321 .saturating_sub(1)
322 .saturating_sub(self.current_ancestor_depth)
323 }
324
325 fn active_component(&self, file_name: &str) -> Option<String> {
326 Path::new(file_name)
327 .components()
328 .nth(self.active_index())
329 .map(|comp| comp.as_os_str().to_string_lossy().into_owned())
330 }
331}
332
333pub fn init_settings(cx: &mut App) {
334 ProjectPanelSettings::register(cx);
335}
336
337pub fn init(cx: &mut App) {
338 init_settings(cx);
339
340 cx.observe_new(|workspace: &mut Workspace, _, _| {
341 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
342 workspace.toggle_panel_focus::<ProjectPanel>(window, cx);
343 });
344
345 workspace.register_action(|workspace, _: &ToggleHideGitIgnore, _, cx| {
346 let fs = workspace.app_state().fs.clone();
347 update_settings_file(fs, cx, move |setting, _| {
348 setting.project_panel.get_or_insert_default().hide_gitignore = Some(
349 !setting
350 .project_panel
351 .get_or_insert_default()
352 .hide_gitignore
353 .unwrap_or(false),
354 );
355 })
356 });
357
358 workspace.register_action(|workspace, action: &CollapseAllEntries, window, cx| {
359 if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
360 panel.update(cx, |panel, cx| {
361 panel.collapse_all_entries(action, window, cx);
362 });
363 }
364 });
365
366 workspace.register_action(|workspace, action: &Rename, window, cx| {
367 workspace.open_panel::<ProjectPanel>(window, cx);
368 if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
369 panel.update(cx, |panel, cx| {
370 if let Some(first_marked) = panel.marked_entries.first() {
371 let first_marked = *first_marked;
372 panel.marked_entries.clear();
373 panel.selection = Some(first_marked);
374 }
375 panel.rename(action, window, cx);
376 });
377 }
378 });
379
380 workspace.register_action(|workspace, action: &Duplicate, window, cx| {
381 workspace.open_panel::<ProjectPanel>(window, cx);
382 if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
383 panel.update(cx, |panel, cx| {
384 panel.duplicate(action, window, cx);
385 });
386 }
387 });
388
389 workspace.register_action(|workspace, action: &Delete, window, cx| {
390 if let Some(panel) = workspace.panel::<ProjectPanel>(cx) {
391 panel.update(cx, |panel, cx| panel.delete(action, window, cx));
392 }
393 });
394 })
395 .detach();
396}
397
398#[derive(Debug)]
399pub enum Event {
400 OpenedEntry {
401 entry_id: ProjectEntryId,
402 focus_opened_item: bool,
403 allow_preview: bool,
404 },
405 SplitEntry {
406 entry_id: ProjectEntryId,
407 allow_preview: bool,
408 split_direction: Option<SplitDirection>,
409 },
410 Focus,
411}
412
413#[derive(Serialize, Deserialize)]
414struct SerializedProjectPanel {
415 width: Option<Pixels>,
416}
417
418struct DraggedProjectEntryView {
419 selection: SelectedEntry,
420 icon: Option<SharedString>,
421 filename: String,
422 click_offset: Point<Pixels>,
423 selections: Arc<[SelectedEntry]>,
424}
425
426struct ItemColors {
427 default: Hsla,
428 hover: Hsla,
429 drag_over: Hsla,
430 marked: Hsla,
431 focused: Hsla,
432}
433
434fn get_item_color(is_sticky: bool, cx: &App) -> ItemColors {
435 let colors = cx.theme().colors();
436
437 ItemColors {
438 default: if is_sticky {
439 colors.panel_overlay_background
440 } else {
441 colors.panel_background
442 },
443 hover: if is_sticky {
444 colors.panel_overlay_hover
445 } else {
446 colors.element_hover
447 },
448 marked: colors.element_selected,
449 focused: colors.panel_focused_border,
450 drag_over: colors.drop_target_background,
451 }
452}
453
454impl ProjectPanel {
455 fn new(
456 workspace: &mut Workspace,
457 window: &mut Window,
458 cx: &mut Context<Workspace>,
459 ) -> Entity<Self> {
460 let project = workspace.project().clone();
461 let git_store = project.read(cx).git_store().clone();
462 let project_panel = cx.new(|cx| {
463 let focus_handle = cx.focus_handle();
464 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
465 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
466 this.focus_out(window, cx);
467 })
468 .detach();
469
470 cx.subscribe(&git_store, |this, _, event, cx| match event {
471 GitStoreEvent::RepositoryUpdated(_, _, _)
472 | GitStoreEvent::RepositoryAdded(_)
473 | GitStoreEvent::RepositoryRemoved(_) => {
474 this.update_visible_entries(None, cx);
475 cx.notify();
476 }
477 _ => {}
478 })
479 .detach();
480
481 cx.subscribe(&project, |this, project, event, cx| match event {
482 project::Event::ActiveEntryChanged(Some(entry_id)) => {
483 if ProjectPanelSettings::get_global(cx).auto_reveal_entries {
484 this.reveal_entry(project, *entry_id, true, cx).ok();
485 }
486 }
487 project::Event::ActiveEntryChanged(None) => {
488 let is_active_item_file_diff_view = this
489 .workspace
490 .upgrade()
491 .and_then(|ws| ws.read(cx).active_item(cx))
492 .map(|item| item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some())
493 .unwrap_or(false);
494 if !is_active_item_file_diff_view {
495 this.marked_entries.clear();
496 }
497 }
498 project::Event::RevealInProjectPanel(entry_id) => {
499 if let Some(()) = this.reveal_entry(project, *entry_id, false, cx).log_err() {
500 cx.emit(PanelEvent::Activate);
501 }
502 }
503 project::Event::ActivateProjectPanel => {
504 cx.emit(PanelEvent::Activate);
505 }
506 project::Event::DiskBasedDiagnosticsFinished { .. }
507 | project::Event::DiagnosticsUpdated { .. } => {
508 if ProjectPanelSettings::get_global(cx).show_diagnostics != ShowDiagnostics::Off
509 {
510 this.diagnostic_summary_update = cx.spawn(async move |this, cx| {
511 cx.background_executor()
512 .timer(Duration::from_millis(30))
513 .await;
514 this.update(cx, |this, cx| {
515 this.update_diagnostics(cx);
516 cx.notify();
517 })
518 .log_err();
519 });
520 }
521 }
522 project::Event::WorktreeRemoved(id) => {
523 this.expanded_dir_ids.remove(id);
524 this.update_visible_entries(None, cx);
525 cx.notify();
526 }
527 project::Event::WorktreeUpdatedEntries(_, _)
528 | project::Event::WorktreeAdded(_)
529 | project::Event::WorktreeOrderChanged => {
530 this.update_visible_entries(None, cx);
531 cx.notify();
532 }
533 project::Event::ExpandedAllForEntry(worktree_id, entry_id) => {
534 if let Some((worktree, expanded_dir_ids)) = project
535 .read(cx)
536 .worktree_for_id(*worktree_id, cx)
537 .zip(this.expanded_dir_ids.get_mut(worktree_id))
538 {
539 let worktree = worktree.read(cx);
540
541 let Some(entry) = worktree.entry_for_id(*entry_id) else {
542 return;
543 };
544 let include_ignored_dirs = !entry.is_ignored;
545
546 let mut dirs_to_expand = vec![*entry_id];
547 while let Some(current_id) = dirs_to_expand.pop() {
548 let Some(current_entry) = worktree.entry_for_id(current_id) else {
549 continue;
550 };
551 for child in worktree.child_entries(¤t_entry.path) {
552 if !child.is_dir() || (include_ignored_dirs && child.is_ignored) {
553 continue;
554 }
555
556 dirs_to_expand.push(child.id);
557
558 if let Err(ix) = expanded_dir_ids.binary_search(&child.id) {
559 expanded_dir_ids.insert(ix, child.id);
560 }
561 this.unfolded_dir_ids.insert(child.id);
562 }
563 }
564 this.update_visible_entries(None, cx);
565 cx.notify();
566 }
567 }
568 _ => {}
569 })
570 .detach();
571
572 let trash_action = [TypeId::of::<Trash>()];
573 let is_remote = project.read(cx).is_via_collab();
574
575 if is_remote {
576 CommandPaletteFilter::update_global(cx, |filter, _cx| {
577 filter.hide_action_types(&trash_action);
578 });
579 }
580
581 let filename_editor = cx.new(|cx| Editor::single_line(window, cx));
582
583 cx.subscribe(
584 &filename_editor,
585 |project_panel, _, editor_event, cx| match editor_event {
586 EditorEvent::BufferEdited => {
587 project_panel.populate_validation_error(cx);
588 project_panel.autoscroll(cx);
589 }
590 EditorEvent::SelectionsChanged { .. } => {
591 project_panel.autoscroll(cx);
592 }
593 EditorEvent::Blurred => {
594 if project_panel
595 .edit_state
596 .as_ref()
597 .is_some_and(|state| state.processing_filename.is_none())
598 {
599 project_panel.edit_state = None;
600 project_panel.update_visible_entries(None, cx);
601 cx.notify();
602 }
603 }
604 _ => {}
605 },
606 )
607 .detach();
608
609 cx.observe_global::<FileIcons>(|_, cx| {
610 cx.notify();
611 })
612 .detach();
613
614 let mut project_panel_settings = *ProjectPanelSettings::get_global(cx);
615 cx.observe_global::<SettingsStore>(move |this, cx| {
616 let new_settings = *ProjectPanelSettings::get_global(cx);
617 if project_panel_settings != new_settings {
618 if project_panel_settings.hide_gitignore != new_settings.hide_gitignore {
619 this.update_visible_entries(None, cx);
620 }
621 if project_panel_settings.hide_root != new_settings.hide_root {
622 this.update_visible_entries(None, cx);
623 }
624 if project_panel_settings.sticky_scroll && !new_settings.sticky_scroll {
625 this.sticky_items_count = 0;
626 }
627 project_panel_settings = new_settings;
628 this.update_diagnostics(cx);
629 cx.notify();
630 }
631 })
632 .detach();
633
634 let scroll_handle = UniformListScrollHandle::new();
635 let mut this = Self {
636 project: project.clone(),
637 hover_scroll_task: None,
638 fs: workspace.app_state().fs.clone(),
639 focus_handle,
640 visible_entries: Default::default(),
641 ancestors: Default::default(),
642 folded_directory_drag_target: None,
643 drag_target_entry: None,
644 last_worktree_root_id: Default::default(),
645 expanded_dir_ids: Default::default(),
646 unfolded_dir_ids: Default::default(),
647 selection: None,
648 marked_entries: Default::default(),
649 edit_state: None,
650 context_menu: None,
651 filename_editor,
652 clipboard: None,
653 _dragged_entry_destination: None,
654 workspace: workspace.weak_handle(),
655 width: None,
656 pending_serialization: Task::ready(None),
657 max_width_item_index: None,
658 diagnostics: Default::default(),
659 diagnostic_summary_update: Task::ready(()),
660 scroll_handle,
661 mouse_down: false,
662 hover_expand_task: None,
663 previous_drag_position: None,
664 sticky_items_count: 0,
665 last_reported_update: Instant::now(),
666 };
667 this.update_visible_entries(None, cx);
668
669 this
670 });
671
672 cx.subscribe_in(&project_panel, window, {
673 let project_panel = project_panel.downgrade();
674 move |workspace, _, event, window, cx| match event {
675 &Event::OpenedEntry {
676 entry_id,
677 focus_opened_item,
678 allow_preview,
679 } => {
680 if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx)
681 && let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
682 let file_path = entry.path.clone();
683 let worktree_id = worktree.read(cx).id();
684 let entry_id = entry.id;
685 let is_via_ssh = project.read(cx).is_via_remote_server();
686
687 workspace
688 .open_path_preview(
689 ProjectPath {
690 worktree_id,
691 path: file_path.clone(),
692 },
693 None,
694 focus_opened_item,
695 allow_preview,
696 true,
697 window, cx,
698 )
699 .detach_and_prompt_err("Failed to open file", window, cx, move |e, _, _| {
700 match e.error_code() {
701 ErrorCode::Disconnected => if is_via_ssh {
702 Some("Disconnected from SSH host".to_string())
703 } else {
704 Some("Disconnected from remote project".to_string())
705 },
706 ErrorCode::UnsharedItem => Some(format!(
707 "{} is not shared by the host. This could be because it has been marked as `private`",
708 file_path.display()
709 )),
710 // See note in worktree.rs where this error originates. Returning Some in this case prevents
711 // the error popup from saying "Try Again", which is a red herring in this case
712 ErrorCode::Internal if e.to_string().contains("File is too large to load") => Some(e.to_string()),
713 _ => None,
714 }
715 });
716
717 if let Some(project_panel) = project_panel.upgrade() {
718 // Always select and mark the entry, regardless of whether it is opened or not.
719 project_panel.update(cx, |project_panel, _| {
720 let entry = SelectedEntry { worktree_id, entry_id };
721 project_panel.marked_entries.clear();
722 project_panel.marked_entries.push(entry);
723 project_panel.selection = Some(entry);
724 });
725 if !focus_opened_item {
726 let focus_handle = project_panel.read(cx).focus_handle.clone();
727 window.focus(&focus_handle);
728 }
729 }
730 }
731 }
732 &Event::SplitEntry {
733 entry_id,
734 allow_preview,
735 split_direction,
736 } => {
737 if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx)
738 && let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
739 workspace
740 .split_path_preview(
741 ProjectPath {
742 worktree_id: worktree.read(cx).id(),
743 path: entry.path.clone(),
744 },
745 allow_preview,
746 split_direction,
747 window, cx,
748 )
749 .detach_and_log_err(cx);
750 }
751 }
752
753 _ => {}
754 }
755 })
756 .detach();
757
758 project_panel
759 }
760
761 pub async fn load(
762 workspace: WeakEntity<Workspace>,
763 mut cx: AsyncWindowContext,
764 ) -> Result<Entity<Self>> {
765 let serialized_panel = match workspace
766 .read_with(&cx, |workspace, _| {
767 ProjectPanel::serialization_key(workspace)
768 })
769 .ok()
770 .flatten()
771 {
772 Some(serialization_key) => cx
773 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
774 .await
775 .context("loading project panel")
776 .log_err()
777 .flatten()
778 .map(|panel| serde_json::from_str::<SerializedProjectPanel>(&panel))
779 .transpose()
780 .log_err()
781 .flatten(),
782 None => None,
783 };
784
785 workspace.update_in(&mut cx, |workspace, window, cx| {
786 let panel = ProjectPanel::new(workspace, window, cx);
787 if let Some(serialized_panel) = serialized_panel {
788 panel.update(cx, |panel, cx| {
789 panel.width = serialized_panel.width.map(|px| px.round());
790 cx.notify();
791 });
792 }
793 panel
794 })
795 }
796
797 fn update_diagnostics(&mut self, cx: &mut Context<Self>) {
798 let mut diagnostics: HashMap<(WorktreeId, PathBuf), DiagnosticSeverity> =
799 Default::default();
800 let show_diagnostics_setting = ProjectPanelSettings::get_global(cx).show_diagnostics;
801
802 if show_diagnostics_setting != ShowDiagnostics::Off {
803 self.project
804 .read(cx)
805 .diagnostic_summaries(false, cx)
806 .filter_map(|(path, _, diagnostic_summary)| {
807 if diagnostic_summary.error_count > 0 {
808 Some((path, DiagnosticSeverity::ERROR))
809 } else if show_diagnostics_setting == ShowDiagnostics::All
810 && diagnostic_summary.warning_count > 0
811 {
812 Some((path, DiagnosticSeverity::WARNING))
813 } else {
814 None
815 }
816 })
817 .for_each(|(project_path, diagnostic_severity)| {
818 let mut path_buffer = PathBuf::new();
819 Self::update_strongest_diagnostic_severity(
820 &mut diagnostics,
821 &project_path,
822 path_buffer.clone(),
823 diagnostic_severity,
824 );
825
826 for component in project_path.path.components() {
827 path_buffer.push(component);
828 Self::update_strongest_diagnostic_severity(
829 &mut diagnostics,
830 &project_path,
831 path_buffer.clone(),
832 diagnostic_severity,
833 );
834 }
835 });
836 }
837 self.diagnostics = diagnostics;
838 }
839
840 fn update_strongest_diagnostic_severity(
841 diagnostics: &mut HashMap<(WorktreeId, PathBuf), DiagnosticSeverity>,
842 project_path: &ProjectPath,
843 path_buffer: PathBuf,
844 diagnostic_severity: DiagnosticSeverity,
845 ) {
846 diagnostics
847 .entry((project_path.worktree_id, path_buffer))
848 .and_modify(|strongest_diagnostic_severity| {
849 *strongest_diagnostic_severity =
850 cmp::min(*strongest_diagnostic_severity, diagnostic_severity);
851 })
852 .or_insert(diagnostic_severity);
853 }
854
855 fn serialization_key(workspace: &Workspace) -> Option<String> {
856 workspace
857 .database_id()
858 .map(|id| i64::from(id).to_string())
859 .or(workspace.session_id())
860 .map(|id| format!("{}-{:?}", PROJECT_PANEL_KEY, id))
861 }
862
863 fn serialize(&mut self, cx: &mut Context<Self>) {
864 let Some(serialization_key) = self
865 .workspace
866 .read_with(cx, |workspace, _| {
867 ProjectPanel::serialization_key(workspace)
868 })
869 .ok()
870 .flatten()
871 else {
872 return;
873 };
874 let width = self.width;
875 self.pending_serialization = cx.background_spawn(
876 async move {
877 KEY_VALUE_STORE
878 .write_kvp(
879 serialization_key,
880 serde_json::to_string(&SerializedProjectPanel { width })?,
881 )
882 .await?;
883 anyhow::Ok(())
884 }
885 .log_err(),
886 );
887 }
888
889 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
890 if !self.focus_handle.contains_focused(window, cx) {
891 cx.emit(Event::Focus);
892 }
893 }
894
895 fn focus_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
896 if !self.focus_handle.is_focused(window) {
897 self.confirm(&Confirm, window, cx);
898 }
899 }
900
901 fn deploy_context_menu(
902 &mut self,
903 position: Point<Pixels>,
904 entry_id: ProjectEntryId,
905 window: &mut Window,
906 cx: &mut Context<Self>,
907 ) {
908 let project = self.project.read(cx);
909
910 let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) {
911 id
912 } else {
913 return;
914 };
915
916 self.selection = Some(SelectedEntry {
917 worktree_id,
918 entry_id,
919 });
920
921 if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
922 let auto_fold_dirs = ProjectPanelSettings::get_global(cx).auto_fold_dirs;
923 let worktree = worktree.read(cx);
924 let is_root = Some(entry) == worktree.root_entry();
925 let is_dir = entry.is_dir();
926 let is_foldable = auto_fold_dirs && self.is_foldable(entry, worktree);
927 let is_unfoldable = auto_fold_dirs && self.is_unfoldable(entry, worktree);
928 let is_read_only = project.is_read_only(cx);
929 let is_remote = project.is_via_collab();
930 let is_local = project.is_local();
931
932 let settings = ProjectPanelSettings::get_global(cx);
933 let visible_worktrees_count = project.visible_worktrees(cx).count();
934 let should_hide_rename = is_root
935 && (cfg!(target_os = "windows")
936 || (settings.hide_root && visible_worktrees_count == 1));
937 let should_show_compare = !is_dir && self.file_abs_paths_to_diff(cx).is_some();
938
939 let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
940 menu.context(self.focus_handle.clone()).map(|menu| {
941 if is_read_only {
942 menu.when(is_dir, |menu| {
943 menu.action("Search Inside", Box::new(NewSearchInDirectory))
944 })
945 } else {
946 menu.action("New File", Box::new(NewFile))
947 .action("New Folder", Box::new(NewDirectory))
948 .separator()
949 .when(is_local && cfg!(target_os = "macos"), |menu| {
950 menu.action("Reveal in Finder", Box::new(RevealInFileManager))
951 })
952 .when(is_local && cfg!(not(target_os = "macos")), |menu| {
953 menu.action("Reveal in File Manager", Box::new(RevealInFileManager))
954 })
955 .when(is_local, |menu| {
956 menu.action("Open in Default App", Box::new(OpenWithSystem))
957 })
958 .action("Open in Terminal", Box::new(OpenInTerminal))
959 .when(is_dir, |menu| {
960 menu.separator()
961 .action("Find in Folder…", Box::new(NewSearchInDirectory))
962 })
963 .when(is_unfoldable, |menu| {
964 menu.action("Unfold Directory", Box::new(UnfoldDirectory))
965 })
966 .when(is_foldable, |menu| {
967 menu.action("Fold Directory", Box::new(FoldDirectory))
968 })
969 .when(should_show_compare, |menu| {
970 menu.separator()
971 .action("Compare marked files", Box::new(CompareMarkedFiles))
972 })
973 .separator()
974 .action("Cut", Box::new(Cut))
975 .action("Copy", Box::new(Copy))
976 .action("Duplicate", Box::new(Duplicate))
977 // TODO: Paste should always be visible, cbut disabled when clipboard is empty
978 .action_disabled_when(
979 self.clipboard.as_ref().is_none(),
980 "Paste",
981 Box::new(Paste),
982 )
983 .separator()
984 .action("Copy Path", Box::new(zed_actions::workspace::CopyPath))
985 .action(
986 "Copy Relative Path",
987 Box::new(zed_actions::workspace::CopyRelativePath),
988 )
989 .separator()
990 .when(!should_hide_rename, |menu| {
991 menu.action("Rename", Box::new(Rename))
992 })
993 .when(!is_root & !is_remote, |menu| {
994 menu.action("Trash", Box::new(Trash { skip_prompt: false }))
995 })
996 .when(!is_root, |menu| {
997 menu.action("Delete", Box::new(Delete { skip_prompt: false }))
998 })
999 .when(!is_remote & is_root, |menu| {
1000 menu.separator()
1001 .action(
1002 "Add Folder to Project…",
1003 Box::new(workspace::AddFolderToProject),
1004 )
1005 .action("Remove from Project", Box::new(RemoveFromProject))
1006 })
1007 .when(is_root, |menu| {
1008 menu.separator()
1009 .action("Collapse All", Box::new(CollapseAllEntries))
1010 })
1011 }
1012 })
1013 });
1014
1015 window.focus(&context_menu.focus_handle(cx));
1016 let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
1017 this.context_menu.take();
1018 cx.notify();
1019 });
1020 self.context_menu = Some((context_menu, position, subscription));
1021 }
1022
1023 cx.notify();
1024 }
1025
1026 fn is_unfoldable(&self, entry: &Entry, worktree: &Worktree) -> bool {
1027 if !entry.is_dir() || self.unfolded_dir_ids.contains(&entry.id) {
1028 return false;
1029 }
1030
1031 if let Some(parent_path) = entry.path.parent() {
1032 let snapshot = worktree.snapshot();
1033 let mut child_entries = snapshot.child_entries(parent_path);
1034 if let Some(child) = child_entries.next()
1035 && child_entries.next().is_none()
1036 {
1037 return child.kind.is_dir();
1038 }
1039 };
1040 false
1041 }
1042
1043 fn is_foldable(&self, entry: &Entry, worktree: &Worktree) -> bool {
1044 if entry.is_dir() {
1045 let snapshot = worktree.snapshot();
1046
1047 let mut child_entries = snapshot.child_entries(&entry.path);
1048 if let Some(child) = child_entries.next()
1049 && child_entries.next().is_none()
1050 {
1051 return child.kind.is_dir();
1052 }
1053 }
1054 false
1055 }
1056
1057 fn expand_selected_entry(
1058 &mut self,
1059 _: &ExpandSelectedEntry,
1060 window: &mut Window,
1061 cx: &mut Context<Self>,
1062 ) {
1063 if let Some((worktree, entry)) = self.selected_entry(cx) {
1064 if let Some(folded_ancestors) = self.ancestors.get_mut(&entry.id)
1065 && folded_ancestors.current_ancestor_depth > 0
1066 {
1067 folded_ancestors.current_ancestor_depth -= 1;
1068 cx.notify();
1069 return;
1070 }
1071 if entry.is_dir() {
1072 let worktree_id = worktree.id();
1073 let entry_id = entry.id;
1074 let expanded_dir_ids =
1075 if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
1076 expanded_dir_ids
1077 } else {
1078 return;
1079 };
1080
1081 match expanded_dir_ids.binary_search(&entry_id) {
1082 Ok(_) => self.select_next(&SelectNext, window, cx),
1083 Err(ix) => {
1084 self.project.update(cx, |project, cx| {
1085 project.expand_entry(worktree_id, entry_id, cx);
1086 });
1087
1088 expanded_dir_ids.insert(ix, entry_id);
1089 self.update_visible_entries(None, cx);
1090 cx.notify();
1091 }
1092 }
1093 }
1094 }
1095 }
1096
1097 fn collapse_selected_entry(
1098 &mut self,
1099 _: &CollapseSelectedEntry,
1100 _: &mut Window,
1101 cx: &mut Context<Self>,
1102 ) {
1103 let Some((worktree, entry)) = self.selected_entry_handle(cx) else {
1104 return;
1105 };
1106 self.collapse_entry(entry.clone(), worktree, cx)
1107 }
1108
1109 fn collapse_entry(&mut self, entry: Entry, worktree: Entity<Worktree>, cx: &mut Context<Self>) {
1110 let worktree = worktree.read(cx);
1111 if let Some(folded_ancestors) = self.ancestors.get_mut(&entry.id)
1112 && folded_ancestors.current_ancestor_depth + 1 < folded_ancestors.max_ancestor_depth()
1113 {
1114 folded_ancestors.current_ancestor_depth += 1;
1115 cx.notify();
1116 return;
1117 }
1118 let worktree_id = worktree.id();
1119 let expanded_dir_ids =
1120 if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
1121 expanded_dir_ids
1122 } else {
1123 return;
1124 };
1125
1126 let mut entry = &entry;
1127 loop {
1128 let entry_id = entry.id;
1129 match expanded_dir_ids.binary_search(&entry_id) {
1130 Ok(ix) => {
1131 expanded_dir_ids.remove(ix);
1132 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
1133 cx.notify();
1134 break;
1135 }
1136 Err(_) => {
1137 if let Some(parent_entry) =
1138 entry.path.parent().and_then(|p| worktree.entry_for_path(p))
1139 {
1140 entry = parent_entry;
1141 } else {
1142 break;
1143 }
1144 }
1145 }
1146 }
1147 }
1148
1149 pub fn collapse_all_entries(
1150 &mut self,
1151 _: &CollapseAllEntries,
1152 _: &mut Window,
1153 cx: &mut Context<Self>,
1154 ) {
1155 // By keeping entries for fully collapsed worktrees, we avoid expanding them within update_visible_entries
1156 // (which is it's default behavior when there's no entry for a worktree in expanded_dir_ids).
1157 self.expanded_dir_ids
1158 .retain(|_, expanded_entries| expanded_entries.is_empty());
1159 self.update_visible_entries(None, cx);
1160 cx.notify();
1161 }
1162
1163 fn toggle_expanded(
1164 &mut self,
1165 entry_id: ProjectEntryId,
1166 window: &mut Window,
1167 cx: &mut Context<Self>,
1168 ) {
1169 if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx)
1170 && let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id)
1171 {
1172 self.project.update(cx, |project, cx| {
1173 match expanded_dir_ids.binary_search(&entry_id) {
1174 Ok(ix) => {
1175 expanded_dir_ids.remove(ix);
1176 }
1177 Err(ix) => {
1178 project.expand_entry(worktree_id, entry_id, cx);
1179 expanded_dir_ids.insert(ix, entry_id);
1180 }
1181 }
1182 });
1183 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
1184 window.focus(&self.focus_handle);
1185 cx.notify();
1186 }
1187 }
1188
1189 fn toggle_expand_all(
1190 &mut self,
1191 entry_id: ProjectEntryId,
1192 window: &mut Window,
1193 cx: &mut Context<Self>,
1194 ) {
1195 if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx)
1196 && let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id)
1197 {
1198 match expanded_dir_ids.binary_search(&entry_id) {
1199 Ok(_ix) => {
1200 self.collapse_all_for_entry(worktree_id, entry_id, cx);
1201 }
1202 Err(_ix) => {
1203 self.expand_all_for_entry(worktree_id, entry_id, cx);
1204 }
1205 }
1206 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
1207 window.focus(&self.focus_handle);
1208 cx.notify();
1209 }
1210 }
1211
1212 fn expand_all_for_entry(
1213 &mut self,
1214 worktree_id: WorktreeId,
1215 entry_id: ProjectEntryId,
1216 cx: &mut Context<Self>,
1217 ) {
1218 self.project.update(cx, |project, cx| {
1219 if let Some((worktree, expanded_dir_ids)) = project
1220 .worktree_for_id(worktree_id, cx)
1221 .zip(self.expanded_dir_ids.get_mut(&worktree_id))
1222 {
1223 if let Some(task) = project.expand_all_for_entry(worktree_id, entry_id, cx) {
1224 task.detach();
1225 }
1226
1227 let worktree = worktree.read(cx);
1228
1229 if let Some(mut entry) = worktree.entry_for_id(entry_id) {
1230 loop {
1231 if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
1232 expanded_dir_ids.insert(ix, entry.id);
1233 }
1234
1235 if let Some(parent_entry) =
1236 entry.path.parent().and_then(|p| worktree.entry_for_path(p))
1237 {
1238 entry = parent_entry;
1239 } else {
1240 break;
1241 }
1242 }
1243 }
1244 }
1245 });
1246 }
1247
1248 fn collapse_all_for_entry(
1249 &mut self,
1250 worktree_id: WorktreeId,
1251 entry_id: ProjectEntryId,
1252 cx: &mut Context<Self>,
1253 ) {
1254 self.project.update(cx, |project, cx| {
1255 if let Some((worktree, expanded_dir_ids)) = project
1256 .worktree_for_id(worktree_id, cx)
1257 .zip(self.expanded_dir_ids.get_mut(&worktree_id))
1258 {
1259 let worktree = worktree.read(cx);
1260 let mut dirs_to_collapse = vec![entry_id];
1261 let auto_fold_enabled = ProjectPanelSettings::get_global(cx).auto_fold_dirs;
1262 while let Some(current_id) = dirs_to_collapse.pop() {
1263 let Some(current_entry) = worktree.entry_for_id(current_id) else {
1264 continue;
1265 };
1266 if let Ok(ix) = expanded_dir_ids.binary_search(¤t_id) {
1267 expanded_dir_ids.remove(ix);
1268 }
1269 if auto_fold_enabled {
1270 self.unfolded_dir_ids.remove(¤t_id);
1271 }
1272 for child in worktree.child_entries(¤t_entry.path) {
1273 if child.is_dir() {
1274 dirs_to_collapse.push(child.id);
1275 }
1276 }
1277 }
1278 }
1279 });
1280 }
1281
1282 fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
1283 if let Some(edit_state) = &self.edit_state
1284 && edit_state.processing_filename.is_none()
1285 {
1286 self.filename_editor.update(cx, |editor, cx| {
1287 editor.move_to_beginning_of_line(
1288 &editor::actions::MoveToBeginningOfLine {
1289 stop_at_soft_wraps: false,
1290 stop_at_indent: false,
1291 },
1292 window,
1293 cx,
1294 );
1295 });
1296 return;
1297 }
1298 if let Some(selection) = self.selection {
1299 let (mut worktree_ix, mut entry_ix, _) =
1300 self.index_for_selection(selection).unwrap_or_default();
1301 if entry_ix > 0 {
1302 entry_ix -= 1;
1303 } else if worktree_ix > 0 {
1304 worktree_ix -= 1;
1305 entry_ix = self.visible_entries[worktree_ix].entries.len() - 1;
1306 } else {
1307 return;
1308 }
1309
1310 let VisibleEntriesForWorktree {
1311 worktree_id,
1312 entries,
1313 ..
1314 } = &self.visible_entries[worktree_ix];
1315 let selection = SelectedEntry {
1316 worktree_id: *worktree_id,
1317 entry_id: entries[entry_ix].id,
1318 };
1319 self.selection = Some(selection);
1320 if window.modifiers().shift {
1321 self.marked_entries.push(selection);
1322 }
1323 self.autoscroll(cx);
1324 cx.notify();
1325 } else {
1326 self.select_first(&SelectFirst {}, window, cx);
1327 }
1328 }
1329
1330 fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1331 if let Some(task) = self.confirm_edit(window, cx) {
1332 task.detach_and_notify_err(window, cx);
1333 }
1334 }
1335
1336 fn open(&mut self, _: &Open, window: &mut Window, cx: &mut Context<Self>) {
1337 let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
1338 self.open_internal(true, !preview_tabs_enabled, None, window, cx);
1339 }
1340
1341 fn open_permanent(&mut self, _: &OpenPermanent, window: &mut Window, cx: &mut Context<Self>) {
1342 self.open_internal(false, true, None, window, cx);
1343 }
1344
1345 fn open_split_vertical(
1346 &mut self,
1347 _: &OpenSplitVertical,
1348 window: &mut Window,
1349 cx: &mut Context<Self>,
1350 ) {
1351 self.open_internal(false, true, Some(SplitDirection::vertical(cx)), window, cx);
1352 }
1353
1354 fn open_split_horizontal(
1355 &mut self,
1356 _: &OpenSplitHorizontal,
1357 window: &mut Window,
1358 cx: &mut Context<Self>,
1359 ) {
1360 self.open_internal(
1361 false,
1362 true,
1363 Some(SplitDirection::horizontal(cx)),
1364 window,
1365 cx,
1366 );
1367 }
1368
1369 fn open_internal(
1370 &mut self,
1371 allow_preview: bool,
1372 focus_opened_item: bool,
1373 split_direction: Option<SplitDirection>,
1374 window: &mut Window,
1375 cx: &mut Context<Self>,
1376 ) {
1377 if let Some((_, entry)) = self.selected_entry(cx) {
1378 if entry.is_file() {
1379 if split_direction.is_some() {
1380 self.split_entry(entry.id, allow_preview, split_direction, cx);
1381 } else {
1382 self.open_entry(entry.id, focus_opened_item, allow_preview, cx);
1383 }
1384 cx.notify();
1385 } else {
1386 self.toggle_expanded(entry.id, window, cx);
1387 }
1388 }
1389 }
1390
1391 fn populate_validation_error(&mut self, cx: &mut Context<Self>) {
1392 let edit_state = match self.edit_state.as_mut() {
1393 Some(state) => state,
1394 None => return,
1395 };
1396 let filename = self.filename_editor.read(cx).text(cx);
1397 if !filename.is_empty() {
1398 if let Some(worktree) = self
1399 .project
1400 .read(cx)
1401 .worktree_for_id(edit_state.worktree_id, cx)
1402 && let Some(entry) = worktree.read(cx).entry_for_id(edit_state.entry_id)
1403 {
1404 let mut already_exists = false;
1405 if edit_state.is_new_entry() {
1406 let new_path = entry.path.join(filename.trim_start_matches('/'));
1407 if worktree
1408 .read(cx)
1409 .entry_for_path(new_path.as_path())
1410 .is_some()
1411 {
1412 already_exists = true;
1413 }
1414 } else {
1415 let new_path = if let Some(parent) = entry.path.clone().parent() {
1416 parent.join(&filename)
1417 } else {
1418 filename.clone().into()
1419 };
1420 if let Some(existing) = worktree.read(cx).entry_for_path(new_path.as_path())
1421 && existing.id != entry.id
1422 {
1423 already_exists = true;
1424 }
1425 };
1426 if already_exists {
1427 edit_state.validation_state = ValidationState::Error(format!(
1428 "File or directory '{}' already exists at location. Please choose a different name.",
1429 filename
1430 ));
1431 cx.notify();
1432 return;
1433 }
1434 }
1435 let trimmed_filename = filename.trim();
1436 if trimmed_filename.is_empty() {
1437 edit_state.validation_state =
1438 ValidationState::Error("File or directory name cannot be empty.".to_string());
1439 cx.notify();
1440 return;
1441 }
1442 if trimmed_filename != filename {
1443 edit_state.validation_state = ValidationState::Warning(
1444 "File or directory name contains leading or trailing whitespace.".to_string(),
1445 );
1446 cx.notify();
1447 return;
1448 }
1449 }
1450 edit_state.validation_state = ValidationState::None;
1451 cx.notify();
1452 }
1453
1454 fn confirm_edit(
1455 &mut self,
1456 window: &mut Window,
1457 cx: &mut Context<Self>,
1458 ) -> Option<Task<Result<()>>> {
1459 let edit_state = self.edit_state.as_mut()?;
1460 let worktree_id = edit_state.worktree_id;
1461 let is_new_entry = edit_state.is_new_entry();
1462 let filename = self.filename_editor.read(cx).text(cx);
1463 if filename.trim().is_empty() {
1464 return None;
1465 }
1466 #[cfg(not(target_os = "windows"))]
1467 let filename_indicates_dir = filename.ends_with("/");
1468 // On Windows, path separator could be either `/` or `\`.
1469 #[cfg(target_os = "windows")]
1470 let filename_indicates_dir = filename.ends_with("/") || filename.ends_with("\\");
1471 edit_state.is_dir =
1472 edit_state.is_dir || (edit_state.is_new_entry() && filename_indicates_dir);
1473 let is_dir = edit_state.is_dir;
1474 let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
1475 let entry = worktree.read(cx).entry_for_id(edit_state.entry_id)?.clone();
1476
1477 let edit_task;
1478 let edited_entry_id;
1479 if is_new_entry {
1480 self.selection = Some(SelectedEntry {
1481 worktree_id,
1482 entry_id: NEW_ENTRY_ID,
1483 });
1484 let new_path = entry.path.join(filename.trim_start_matches('/'));
1485 if worktree
1486 .read(cx)
1487 .entry_for_path(new_path.as_path())
1488 .is_some()
1489 {
1490 return None;
1491 }
1492
1493 edited_entry_id = NEW_ENTRY_ID;
1494 edit_task = self.project.update(cx, |project, cx| {
1495 project.create_entry((worktree_id, &new_path), is_dir, cx)
1496 });
1497 } else {
1498 let new_path = if let Some(parent) = entry.path.clone().parent() {
1499 parent.join(&filename)
1500 } else {
1501 filename.clone().into()
1502 };
1503 if let Some(existing) = worktree.read(cx).entry_for_path(new_path.as_path()) {
1504 if existing.id == entry.id {
1505 window.focus(&self.focus_handle);
1506 }
1507 return None;
1508 }
1509 edited_entry_id = entry.id;
1510 edit_task = self.project.update(cx, |project, cx| {
1511 project.rename_entry(entry.id, new_path.as_path(), cx)
1512 });
1513 };
1514
1515 window.focus(&self.focus_handle);
1516 edit_state.processing_filename = Some(filename);
1517 cx.notify();
1518
1519 Some(cx.spawn_in(window, async move |project_panel, cx| {
1520 let new_entry = edit_task.await;
1521 project_panel.update(cx, |project_panel, cx| {
1522 project_panel.edit_state = None;
1523 cx.notify();
1524 })?;
1525
1526 match new_entry {
1527 Err(e) => {
1528 project_panel.update( cx, |project_panel, cx| {
1529 project_panel.marked_entries.clear();
1530 project_panel.update_visible_entries(None, cx);
1531 }).ok();
1532 Err(e)?;
1533 }
1534 Ok(CreatedEntry::Included(new_entry)) => {
1535 project_panel.update( cx, |project_panel, cx| {
1536 if let Some(selection) = &mut project_panel.selection
1537 && selection.entry_id == edited_entry_id {
1538 selection.worktree_id = worktree_id;
1539 selection.entry_id = new_entry.id;
1540 project_panel.marked_entries.clear();
1541 project_panel.expand_to_selection(cx);
1542 }
1543 project_panel.update_visible_entries(None, cx);
1544 if is_new_entry && !is_dir {
1545 project_panel.open_entry(new_entry.id, true, false, cx);
1546 }
1547 cx.notify();
1548 })?;
1549 }
1550 Ok(CreatedEntry::Excluded { abs_path }) => {
1551 if let Some(open_task) = project_panel
1552 .update_in( cx, |project_panel, window, cx| {
1553 project_panel.marked_entries.clear();
1554 project_panel.update_visible_entries(None, cx);
1555
1556 if is_dir {
1557 project_panel.project.update(cx, |_, cx| {
1558 cx.emit(project::Event::Toast {
1559 notification_id: "excluded-directory".into(),
1560 message: format!("Created an excluded directory at {abs_path:?}.\nAlter `file_scan_exclusions` in the settings to show it in the panel")
1561 })
1562 });
1563 None
1564 } else {
1565 project_panel
1566 .workspace
1567 .update(cx, |workspace, cx| {
1568 workspace.open_abs_path(abs_path, OpenOptions { visible: Some(OpenVisible::All), ..Default::default() }, window, cx)
1569 })
1570 .ok()
1571 }
1572 })
1573 .ok()
1574 .flatten()
1575 {
1576 let _ = open_task.await?;
1577 }
1578 }
1579 }
1580 Ok(())
1581 }))
1582 }
1583
1584 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
1585 if cx.stop_active_drag(window) {
1586 self.drag_target_entry.take();
1587 self.hover_expand_task.take();
1588 return;
1589 }
1590
1591 let previous_edit_state = self.edit_state.take();
1592 self.update_visible_entries(None, cx);
1593 self.marked_entries.clear();
1594
1595 if let Some(previously_focused) =
1596 previous_edit_state.and_then(|edit_state| edit_state.previously_focused)
1597 {
1598 self.selection = Some(previously_focused);
1599 self.autoscroll(cx);
1600 }
1601
1602 window.focus(&self.focus_handle);
1603 cx.notify();
1604 }
1605
1606 fn open_entry(
1607 &mut self,
1608 entry_id: ProjectEntryId,
1609 focus_opened_item: bool,
1610 allow_preview: bool,
1611
1612 cx: &mut Context<Self>,
1613 ) {
1614 cx.emit(Event::OpenedEntry {
1615 entry_id,
1616 focus_opened_item,
1617 allow_preview,
1618 });
1619 }
1620
1621 fn split_entry(
1622 &mut self,
1623 entry_id: ProjectEntryId,
1624 allow_preview: bool,
1625 split_direction: Option<SplitDirection>,
1626
1627 cx: &mut Context<Self>,
1628 ) {
1629 cx.emit(Event::SplitEntry {
1630 entry_id,
1631 allow_preview,
1632 split_direction,
1633 });
1634 }
1635
1636 fn new_file(&mut self, _: &NewFile, window: &mut Window, cx: &mut Context<Self>) {
1637 self.add_entry(false, window, cx)
1638 }
1639
1640 fn new_directory(&mut self, _: &NewDirectory, window: &mut Window, cx: &mut Context<Self>) {
1641 self.add_entry(true, window, cx)
1642 }
1643
1644 fn add_entry(&mut self, is_dir: bool, window: &mut Window, cx: &mut Context<Self>) {
1645 let Some((worktree_id, entry_id)) = self
1646 .selection
1647 .map(|entry| (entry.worktree_id, entry.entry_id))
1648 .or_else(|| {
1649 let entry_id = self.last_worktree_root_id?;
1650 let worktree_id = self
1651 .project
1652 .read(cx)
1653 .worktree_for_entry(entry_id, cx)?
1654 .read(cx)
1655 .id();
1656
1657 self.selection = Some(SelectedEntry {
1658 worktree_id,
1659 entry_id,
1660 });
1661
1662 Some((worktree_id, entry_id))
1663 })
1664 else {
1665 return;
1666 };
1667
1668 let directory_id;
1669 let new_entry_id = self.resolve_entry(entry_id);
1670 if let Some((worktree, expanded_dir_ids)) = self
1671 .project
1672 .read(cx)
1673 .worktree_for_id(worktree_id, cx)
1674 .zip(self.expanded_dir_ids.get_mut(&worktree_id))
1675 {
1676 let worktree = worktree.read(cx);
1677 if let Some(mut entry) = worktree.entry_for_id(new_entry_id) {
1678 loop {
1679 if entry.is_dir() {
1680 if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
1681 expanded_dir_ids.insert(ix, entry.id);
1682 }
1683 directory_id = entry.id;
1684 break;
1685 } else {
1686 if let Some(parent_path) = entry.path.parent()
1687 && let Some(parent_entry) = worktree.entry_for_path(parent_path)
1688 {
1689 entry = parent_entry;
1690 continue;
1691 }
1692 return;
1693 }
1694 }
1695 } else {
1696 return;
1697 };
1698 } else {
1699 return;
1700 };
1701
1702 self.marked_entries.clear();
1703 self.edit_state = Some(EditState {
1704 worktree_id,
1705 entry_id: directory_id,
1706 leaf_entry_id: None,
1707 is_dir,
1708 processing_filename: None,
1709 previously_focused: self.selection,
1710 depth: 0,
1711 validation_state: ValidationState::None,
1712 });
1713 self.filename_editor.update(cx, |editor, cx| {
1714 editor.clear(window, cx);
1715 window.focus(&editor.focus_handle(cx));
1716 });
1717 self.update_visible_entries(Some((worktree_id, NEW_ENTRY_ID)), cx);
1718 self.autoscroll(cx);
1719 cx.notify();
1720 }
1721
1722 fn unflatten_entry_id(&self, leaf_entry_id: ProjectEntryId) -> ProjectEntryId {
1723 if let Some(ancestors) = self.ancestors.get(&leaf_entry_id) {
1724 ancestors
1725 .ancestors
1726 .get(ancestors.current_ancestor_depth)
1727 .copied()
1728 .unwrap_or(leaf_entry_id)
1729 } else {
1730 leaf_entry_id
1731 }
1732 }
1733
1734 fn rename_impl(
1735 &mut self,
1736 selection: Option<Range<usize>>,
1737 window: &mut Window,
1738 cx: &mut Context<Self>,
1739 ) {
1740 if let Some(SelectedEntry {
1741 worktree_id,
1742 entry_id,
1743 }) = self.selection
1744 && let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx)
1745 {
1746 let sub_entry_id = self.unflatten_entry_id(entry_id);
1747 if let Some(entry) = worktree.read(cx).entry_for_id(sub_entry_id) {
1748 #[cfg(target_os = "windows")]
1749 if Some(entry) == worktree.read(cx).root_entry() {
1750 return;
1751 }
1752
1753 if Some(entry) == worktree.read(cx).root_entry() {
1754 let settings = ProjectPanelSettings::get_global(cx);
1755 let visible_worktrees_count =
1756 self.project.read(cx).visible_worktrees(cx).count();
1757 if settings.hide_root && visible_worktrees_count == 1 {
1758 return;
1759 }
1760 }
1761
1762 self.edit_state = Some(EditState {
1763 worktree_id,
1764 entry_id: sub_entry_id,
1765 leaf_entry_id: Some(entry_id),
1766 is_dir: entry.is_dir(),
1767 processing_filename: None,
1768 previously_focused: None,
1769 depth: 0,
1770 validation_state: ValidationState::None,
1771 });
1772 let file_name = entry
1773 .path
1774 .file_name()
1775 .map(|s| s.to_string_lossy())
1776 .unwrap_or_default()
1777 .to_string();
1778 let selection = selection.unwrap_or_else(|| {
1779 let file_stem = entry.path.file_stem().map(|s| s.to_string_lossy());
1780 let selection_end =
1781 file_stem.map_or(file_name.len(), |file_stem| file_stem.len());
1782 0..selection_end
1783 });
1784 self.filename_editor.update(cx, |editor, cx| {
1785 editor.set_text(file_name, window, cx);
1786 editor.change_selections(Default::default(), window, cx, |s| {
1787 s.select_ranges([selection])
1788 });
1789 window.focus(&editor.focus_handle(cx));
1790 });
1791 self.update_visible_entries(None, cx);
1792 self.autoscroll(cx);
1793 cx.notify();
1794 }
1795 }
1796 }
1797
1798 fn rename(&mut self, _: &Rename, window: &mut Window, cx: &mut Context<Self>) {
1799 self.rename_impl(None, window, cx);
1800 }
1801
1802 fn trash(&mut self, action: &Trash, window: &mut Window, cx: &mut Context<Self>) {
1803 self.remove(true, action.skip_prompt, window, cx);
1804 }
1805
1806 fn delete(&mut self, action: &Delete, window: &mut Window, cx: &mut Context<Self>) {
1807 self.remove(false, action.skip_prompt, window, cx);
1808 }
1809
1810 fn remove(
1811 &mut self,
1812 trash: bool,
1813 skip_prompt: bool,
1814 window: &mut Window,
1815 cx: &mut Context<ProjectPanel>,
1816 ) {
1817 maybe!({
1818 let items_to_delete = self.disjoint_entries(cx);
1819 if items_to_delete.is_empty() {
1820 return None;
1821 }
1822 let project = self.project.read(cx);
1823
1824 let mut dirty_buffers = 0;
1825 let file_paths = items_to_delete
1826 .iter()
1827 .filter_map(|selection| {
1828 let project_path = project.path_for_entry(selection.entry_id, cx)?;
1829 dirty_buffers +=
1830 project.dirty_buffers(cx).any(|path| path == project_path) as usize;
1831 Some((
1832 selection.entry_id,
1833 project_path
1834 .path
1835 .file_name()?
1836 .to_string_lossy()
1837 .into_owned(),
1838 ))
1839 })
1840 .collect::<Vec<_>>();
1841 if file_paths.is_empty() {
1842 return None;
1843 }
1844 let answer = if !skip_prompt {
1845 let operation = if trash { "Trash" } else { "Delete" };
1846 let prompt = match file_paths.first() {
1847 Some((_, path)) if file_paths.len() == 1 => {
1848 let unsaved_warning = if dirty_buffers > 0 {
1849 "\n\nIt has unsaved changes, which will be lost."
1850 } else {
1851 ""
1852 };
1853
1854 format!("{operation} {path}?{unsaved_warning}")
1855 }
1856 _ => {
1857 const CUTOFF_POINT: usize = 10;
1858 let names = if file_paths.len() > CUTOFF_POINT {
1859 let truncated_path_counts = file_paths.len() - CUTOFF_POINT;
1860 let mut paths = file_paths
1861 .iter()
1862 .map(|(_, path)| path.clone())
1863 .take(CUTOFF_POINT)
1864 .collect::<Vec<_>>();
1865 paths.truncate(CUTOFF_POINT);
1866 if truncated_path_counts == 1 {
1867 paths.push(".. 1 file not shown".into());
1868 } else {
1869 paths.push(format!(".. {} files not shown", truncated_path_counts));
1870 }
1871 paths
1872 } else {
1873 file_paths.iter().map(|(_, path)| path.clone()).collect()
1874 };
1875 let unsaved_warning = if dirty_buffers == 0 {
1876 String::new()
1877 } else if dirty_buffers == 1 {
1878 "\n\n1 of these has unsaved changes, which will be lost.".to_string()
1879 } else {
1880 format!(
1881 "\n\n{dirty_buffers} of these have unsaved changes, which will be lost."
1882 )
1883 };
1884
1885 format!(
1886 "Do you want to {} the following {} files?\n{}{unsaved_warning}",
1887 operation.to_lowercase(),
1888 file_paths.len(),
1889 names.join("\n")
1890 )
1891 }
1892 };
1893 Some(window.prompt(PromptLevel::Info, &prompt, None, &[operation, "Cancel"], cx))
1894 } else {
1895 None
1896 };
1897 let next_selection = self.find_next_selection_after_deletion(items_to_delete, cx);
1898 cx.spawn_in(window, async move |panel, cx| {
1899 if let Some(answer) = answer
1900 && answer.await != Ok(0)
1901 {
1902 return anyhow::Ok(());
1903 }
1904 for (entry_id, _) in file_paths {
1905 panel
1906 .update(cx, |panel, cx| {
1907 panel
1908 .project
1909 .update(cx, |project, cx| project.delete_entry(entry_id, trash, cx))
1910 .context("no such entry")
1911 })??
1912 .await?;
1913 }
1914 panel.update_in(cx, |panel, window, cx| {
1915 if let Some(next_selection) = next_selection {
1916 panel.selection = Some(next_selection);
1917 panel.autoscroll(cx);
1918 } else {
1919 panel.select_last(&SelectLast {}, window, cx);
1920 }
1921 })?;
1922 Ok(())
1923 })
1924 .detach_and_log_err(cx);
1925 Some(())
1926 });
1927 }
1928
1929 fn find_next_selection_after_deletion(
1930 &self,
1931 sanitized_entries: BTreeSet<SelectedEntry>,
1932 cx: &mut Context<Self>,
1933 ) -> Option<SelectedEntry> {
1934 if sanitized_entries.is_empty() {
1935 return None;
1936 }
1937 let project = self.project.read(cx);
1938 let (worktree_id, worktree) = sanitized_entries
1939 .iter()
1940 .map(|entry| entry.worktree_id)
1941 .filter_map(|id| project.worktree_for_id(id, cx).map(|w| (id, w.read(cx))))
1942 .max_by(|(_, a), (_, b)| a.root_name().cmp(b.root_name()))?;
1943 let git_store = project.git_store().read(cx);
1944
1945 let marked_entries_in_worktree = sanitized_entries
1946 .iter()
1947 .filter(|e| e.worktree_id == worktree_id)
1948 .collect::<HashSet<_>>();
1949 let latest_entry = marked_entries_in_worktree
1950 .iter()
1951 .max_by(|a, b| {
1952 match (
1953 worktree.entry_for_id(a.entry_id),
1954 worktree.entry_for_id(b.entry_id),
1955 ) {
1956 (Some(a), Some(b)) => {
1957 compare_paths((&a.path, a.is_file()), (&b.path, b.is_file()))
1958 }
1959 _ => cmp::Ordering::Equal,
1960 }
1961 })
1962 .and_then(|e| worktree.entry_for_id(e.entry_id))?;
1963
1964 let parent_path = latest_entry.path.parent()?;
1965 let parent_entry = worktree.entry_for_path(parent_path)?;
1966
1967 // Remove all siblings that are being deleted except the last marked entry
1968 let repo_snapshots = git_store.repo_snapshots(cx);
1969 let worktree_snapshot = worktree.snapshot();
1970 let hide_gitignore = ProjectPanelSettings::get_global(cx).hide_gitignore;
1971 let mut siblings: Vec<_> =
1972 ChildEntriesGitIter::new(&repo_snapshots, &worktree_snapshot, parent_path)
1973 .filter(|sibling| {
1974 (sibling.id == latest_entry.id)
1975 || (!marked_entries_in_worktree.contains(&&SelectedEntry {
1976 worktree_id,
1977 entry_id: sibling.id,
1978 }) && (!hide_gitignore || !sibling.is_ignored))
1979 })
1980 .map(|entry| entry.to_owned())
1981 .collect();
1982
1983 project::sort_worktree_entries(&mut siblings);
1984 let sibling_entry_index = siblings
1985 .iter()
1986 .position(|sibling| sibling.id == latest_entry.id)?;
1987
1988 if let Some(next_sibling) = sibling_entry_index
1989 .checked_add(1)
1990 .and_then(|i| siblings.get(i))
1991 {
1992 return Some(SelectedEntry {
1993 worktree_id,
1994 entry_id: next_sibling.id,
1995 });
1996 }
1997 if let Some(prev_sibling) = sibling_entry_index
1998 .checked_sub(1)
1999 .and_then(|i| siblings.get(i))
2000 {
2001 return Some(SelectedEntry {
2002 worktree_id,
2003 entry_id: prev_sibling.id,
2004 });
2005 }
2006 // No neighbour sibling found, fall back to parent
2007 Some(SelectedEntry {
2008 worktree_id,
2009 entry_id: parent_entry.id,
2010 })
2011 }
2012
2013 fn unfold_directory(&mut self, _: &UnfoldDirectory, _: &mut Window, cx: &mut Context<Self>) {
2014 if let Some((worktree, entry)) = self.selected_entry(cx) {
2015 self.unfolded_dir_ids.insert(entry.id);
2016
2017 let snapshot = worktree.snapshot();
2018 let mut parent_path = entry.path.parent();
2019 while let Some(path) = parent_path {
2020 if let Some(parent_entry) = worktree.entry_for_path(path) {
2021 let mut children_iter = snapshot.child_entries(path);
2022
2023 if children_iter.by_ref().take(2).count() > 1 {
2024 break;
2025 }
2026
2027 self.unfolded_dir_ids.insert(parent_entry.id);
2028 parent_path = path.parent();
2029 } else {
2030 break;
2031 }
2032 }
2033
2034 self.update_visible_entries(None, cx);
2035 self.autoscroll(cx);
2036 cx.notify();
2037 }
2038 }
2039
2040 fn fold_directory(&mut self, _: &FoldDirectory, _: &mut Window, cx: &mut Context<Self>) {
2041 if let Some((worktree, entry)) = self.selected_entry(cx) {
2042 self.unfolded_dir_ids.remove(&entry.id);
2043
2044 let snapshot = worktree.snapshot();
2045 let mut path = &*entry.path;
2046 loop {
2047 let mut child_entries_iter = snapshot.child_entries(path);
2048 if let Some(child) = child_entries_iter.next() {
2049 if child_entries_iter.next().is_none() && child.is_dir() {
2050 self.unfolded_dir_ids.remove(&child.id);
2051 path = &*child.path;
2052 } else {
2053 break;
2054 }
2055 } else {
2056 break;
2057 }
2058 }
2059
2060 self.update_visible_entries(None, cx);
2061 self.autoscroll(cx);
2062 cx.notify();
2063 }
2064 }
2065
2066 fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2067 if let Some(edit_state) = &self.edit_state
2068 && edit_state.processing_filename.is_none()
2069 {
2070 self.filename_editor.update(cx, |editor, cx| {
2071 editor.move_to_end_of_line(
2072 &editor::actions::MoveToEndOfLine {
2073 stop_at_soft_wraps: false,
2074 },
2075 window,
2076 cx,
2077 );
2078 });
2079 return;
2080 }
2081 if let Some(selection) = self.selection {
2082 let (mut worktree_ix, mut entry_ix, _) =
2083 self.index_for_selection(selection).unwrap_or_default();
2084 if let Some(worktree_entries) =
2085 self.visible_entries.get(worktree_ix).map(|v| &v.entries)
2086 {
2087 if entry_ix + 1 < worktree_entries.len() {
2088 entry_ix += 1;
2089 } else {
2090 worktree_ix += 1;
2091 entry_ix = 0;
2092 }
2093 }
2094
2095 if let Some(VisibleEntriesForWorktree {
2096 worktree_id,
2097 entries,
2098 ..
2099 }) = self.visible_entries.get(worktree_ix)
2100 && let Some(entry) = entries.get(entry_ix)
2101 {
2102 let selection = SelectedEntry {
2103 worktree_id: *worktree_id,
2104 entry_id: entry.id,
2105 };
2106 self.selection = Some(selection);
2107 if window.modifiers().shift {
2108 self.marked_entries.push(selection);
2109 }
2110
2111 self.autoscroll(cx);
2112 cx.notify();
2113 }
2114 } else {
2115 self.select_first(&SelectFirst {}, window, cx);
2116 }
2117 }
2118
2119 fn select_prev_diagnostic(
2120 &mut self,
2121 action: &SelectPrevDiagnostic,
2122 _: &mut Window,
2123 cx: &mut Context<Self>,
2124 ) {
2125 let selection = self.find_entry(
2126 self.selection.as_ref(),
2127 true,
2128 |entry, worktree_id| {
2129 (self.selection.is_none()
2130 || self.selection.is_some_and(|selection| {
2131 if selection.worktree_id == worktree_id {
2132 selection.entry_id != entry.id
2133 } else {
2134 true
2135 }
2136 }))
2137 && entry.is_file()
2138 && self
2139 .diagnostics
2140 .get(&(worktree_id, entry.path.to_path_buf()))
2141 .is_some_and(|severity| action.severity.matches(*severity))
2142 },
2143 cx,
2144 );
2145
2146 if let Some(selection) = selection {
2147 self.selection = Some(selection);
2148 self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2149 self.update_visible_entries(Some((selection.worktree_id, selection.entry_id)), cx);
2150 self.autoscroll(cx);
2151 cx.notify();
2152 }
2153 }
2154
2155 fn select_next_diagnostic(
2156 &mut self,
2157 action: &SelectNextDiagnostic,
2158 _: &mut Window,
2159 cx: &mut Context<Self>,
2160 ) {
2161 let selection = self.find_entry(
2162 self.selection.as_ref(),
2163 false,
2164 |entry, worktree_id| {
2165 (self.selection.is_none()
2166 || self.selection.is_some_and(|selection| {
2167 if selection.worktree_id == worktree_id {
2168 selection.entry_id != entry.id
2169 } else {
2170 true
2171 }
2172 }))
2173 && entry.is_file()
2174 && self
2175 .diagnostics
2176 .get(&(worktree_id, entry.path.to_path_buf()))
2177 .is_some_and(|severity| action.severity.matches(*severity))
2178 },
2179 cx,
2180 );
2181
2182 if let Some(selection) = selection {
2183 self.selection = Some(selection);
2184 self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2185 self.update_visible_entries(Some((selection.worktree_id, selection.entry_id)), cx);
2186 self.autoscroll(cx);
2187 cx.notify();
2188 }
2189 }
2190
2191 fn select_prev_git_entry(
2192 &mut self,
2193 _: &SelectPrevGitEntry,
2194 _: &mut Window,
2195 cx: &mut Context<Self>,
2196 ) {
2197 let selection = self.find_entry(
2198 self.selection.as_ref(),
2199 true,
2200 |entry, worktree_id| {
2201 (self.selection.is_none()
2202 || self.selection.is_some_and(|selection| {
2203 if selection.worktree_id == worktree_id {
2204 selection.entry_id != entry.id
2205 } else {
2206 true
2207 }
2208 }))
2209 && entry.is_file()
2210 && entry.git_summary.index.modified + entry.git_summary.worktree.modified > 0
2211 },
2212 cx,
2213 );
2214
2215 if let Some(selection) = selection {
2216 self.selection = Some(selection);
2217 self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2218 self.update_visible_entries(Some((selection.worktree_id, selection.entry_id)), cx);
2219 self.autoscroll(cx);
2220 cx.notify();
2221 }
2222 }
2223
2224 fn select_prev_directory(
2225 &mut self,
2226 _: &SelectPrevDirectory,
2227 _: &mut Window,
2228 cx: &mut Context<Self>,
2229 ) {
2230 let selection = self.find_visible_entry(
2231 self.selection.as_ref(),
2232 true,
2233 |entry, worktree_id| {
2234 (self.selection.is_none()
2235 || self.selection.is_some_and(|selection| {
2236 if selection.worktree_id == worktree_id {
2237 selection.entry_id != entry.id
2238 } else {
2239 true
2240 }
2241 }))
2242 && entry.is_dir()
2243 },
2244 cx,
2245 );
2246
2247 if let Some(selection) = selection {
2248 self.selection = Some(selection);
2249 self.autoscroll(cx);
2250 cx.notify();
2251 }
2252 }
2253
2254 fn select_next_directory(
2255 &mut self,
2256 _: &SelectNextDirectory,
2257 _: &mut Window,
2258 cx: &mut Context<Self>,
2259 ) {
2260 let selection = self.find_visible_entry(
2261 self.selection.as_ref(),
2262 false,
2263 |entry, worktree_id| {
2264 (self.selection.is_none()
2265 || self.selection.is_some_and(|selection| {
2266 if selection.worktree_id == worktree_id {
2267 selection.entry_id != entry.id
2268 } else {
2269 true
2270 }
2271 }))
2272 && entry.is_dir()
2273 },
2274 cx,
2275 );
2276
2277 if let Some(selection) = selection {
2278 self.selection = Some(selection);
2279 self.autoscroll(cx);
2280 cx.notify();
2281 }
2282 }
2283
2284 fn select_next_git_entry(
2285 &mut self,
2286 _: &SelectNextGitEntry,
2287 _: &mut Window,
2288 cx: &mut Context<Self>,
2289 ) {
2290 let selection = self.find_entry(
2291 self.selection.as_ref(),
2292 false,
2293 |entry, worktree_id| {
2294 (self.selection.is_none()
2295 || self.selection.is_some_and(|selection| {
2296 if selection.worktree_id == worktree_id {
2297 selection.entry_id != entry.id
2298 } else {
2299 true
2300 }
2301 }))
2302 && entry.is_file()
2303 && entry.git_summary.index.modified + entry.git_summary.worktree.modified > 0
2304 },
2305 cx,
2306 );
2307
2308 if let Some(selection) = selection {
2309 self.selection = Some(selection);
2310 self.expand_entry(selection.worktree_id, selection.entry_id, cx);
2311 self.update_visible_entries(Some((selection.worktree_id, selection.entry_id)), cx);
2312 self.autoscroll(cx);
2313 cx.notify();
2314 }
2315 }
2316
2317 fn select_parent(&mut self, _: &SelectParent, window: &mut Window, cx: &mut Context<Self>) {
2318 if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2319 if let Some(parent) = entry.path.parent() {
2320 let worktree = worktree.read(cx);
2321 if let Some(parent_entry) = worktree.entry_for_path(parent) {
2322 self.selection = Some(SelectedEntry {
2323 worktree_id: worktree.id(),
2324 entry_id: parent_entry.id,
2325 });
2326 self.autoscroll(cx);
2327 cx.notify();
2328 }
2329 }
2330 } else {
2331 self.select_first(&SelectFirst {}, window, cx);
2332 }
2333 }
2334
2335 fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
2336 if let Some(VisibleEntriesForWorktree {
2337 worktree_id,
2338 entries,
2339 ..
2340 }) = self.visible_entries.first()
2341 && let Some(entry) = entries.first()
2342 {
2343 let selection = SelectedEntry {
2344 worktree_id: *worktree_id,
2345 entry_id: entry.id,
2346 };
2347 self.selection = Some(selection);
2348 if window.modifiers().shift {
2349 self.marked_entries.push(selection);
2350 }
2351 self.autoscroll(cx);
2352 cx.notify();
2353 }
2354 }
2355
2356 fn select_last(&mut self, _: &SelectLast, _: &mut Window, cx: &mut Context<Self>) {
2357 if let Some(VisibleEntriesForWorktree {
2358 worktree_id,
2359 entries,
2360 ..
2361 }) = self.visible_entries.last()
2362 {
2363 let worktree = self.project.read(cx).worktree_for_id(*worktree_id, cx);
2364 if let (Some(worktree), Some(entry)) = (worktree, entries.last()) {
2365 let worktree = worktree.read(cx);
2366 if let Some(entry) = worktree.entry_for_id(entry.id) {
2367 let selection = SelectedEntry {
2368 worktree_id: *worktree_id,
2369 entry_id: entry.id,
2370 };
2371 self.selection = Some(selection);
2372 self.autoscroll(cx);
2373 cx.notify();
2374 }
2375 }
2376 }
2377 }
2378
2379 fn autoscroll(&mut self, cx: &mut Context<Self>) {
2380 if let Some((_, _, index)) = self.selection.and_then(|s| self.index_for_selection(s)) {
2381 self.scroll_handle.scroll_to_item_with_offset(
2382 index,
2383 ScrollStrategy::Center,
2384 self.sticky_items_count,
2385 );
2386 cx.notify();
2387 }
2388 }
2389
2390 fn cut(&mut self, _: &Cut, _: &mut Window, cx: &mut Context<Self>) {
2391 let entries = self.disjoint_entries(cx);
2392 if !entries.is_empty() {
2393 self.clipboard = Some(ClipboardEntry::Cut(entries));
2394 cx.notify();
2395 }
2396 }
2397
2398 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
2399 let entries = self.disjoint_entries(cx);
2400 if !entries.is_empty() {
2401 self.clipboard = Some(ClipboardEntry::Copied(entries));
2402 cx.notify();
2403 }
2404 }
2405
2406 fn create_paste_path(
2407 &self,
2408 source: &SelectedEntry,
2409 (worktree, target_entry): (Entity<Worktree>, &Entry),
2410 cx: &App,
2411 ) -> Option<(PathBuf, Option<Range<usize>>)> {
2412 let mut new_path = target_entry.path.to_path_buf();
2413 // If we're pasting into a file, or a directory into itself, go up one level.
2414 if target_entry.is_file() || (target_entry.is_dir() && target_entry.id == source.entry_id) {
2415 new_path.pop();
2416 }
2417 let clipboard_entry_file_name = self
2418 .project
2419 .read(cx)
2420 .path_for_entry(source.entry_id, cx)?
2421 .path
2422 .file_name()?
2423 .to_os_string();
2424 new_path.push(&clipboard_entry_file_name);
2425 let extension = new_path.extension().map(|e| e.to_os_string());
2426 let file_name_without_extension = Path::new(&clipboard_entry_file_name).file_stem()?;
2427 let file_name_len = file_name_without_extension.to_string_lossy().len();
2428 let mut disambiguation_range = None;
2429 let mut ix = 0;
2430 {
2431 let worktree = worktree.read(cx);
2432 while worktree.entry_for_path(&new_path).is_some() {
2433 new_path.pop();
2434
2435 let mut new_file_name = file_name_without_extension.to_os_string();
2436
2437 let disambiguation = " copy";
2438 let mut disambiguation_len = disambiguation.len();
2439
2440 new_file_name.push(disambiguation);
2441
2442 if ix > 0 {
2443 let extra_disambiguation = format!(" {}", ix);
2444 disambiguation_len += extra_disambiguation.len();
2445
2446 new_file_name.push(extra_disambiguation);
2447 }
2448 if let Some(extension) = extension.as_ref() {
2449 new_file_name.push(".");
2450 new_file_name.push(extension);
2451 }
2452
2453 new_path.push(new_file_name);
2454 disambiguation_range = Some(file_name_len..(file_name_len + disambiguation_len));
2455 ix += 1;
2456 }
2457 }
2458 Some((new_path, disambiguation_range))
2459 }
2460
2461 fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
2462 maybe!({
2463 let (worktree, entry) = self.selected_entry_handle(cx)?;
2464 let entry = entry.clone();
2465 let worktree_id = worktree.read(cx).id();
2466 let clipboard_entries = self
2467 .clipboard
2468 .as_ref()
2469 .filter(|clipboard| !clipboard.items().is_empty())?;
2470 enum PasteTask {
2471 Rename(Task<Result<CreatedEntry>>),
2472 Copy(Task<Result<Option<Entry>>>),
2473 }
2474 let mut paste_entry_tasks: IndexMap<(ProjectEntryId, bool), PasteTask> =
2475 IndexMap::default();
2476 let mut disambiguation_range = None;
2477 let clip_is_cut = clipboard_entries.is_cut();
2478 for clipboard_entry in clipboard_entries.items() {
2479 let (new_path, new_disambiguation_range) =
2480 self.create_paste_path(clipboard_entry, self.selected_sub_entry(cx)?, cx)?;
2481 let clip_entry_id = clipboard_entry.entry_id;
2482 let is_same_worktree = clipboard_entry.worktree_id == worktree_id;
2483 let relative_worktree_source_path = if !is_same_worktree {
2484 let target_base_path = worktree.read(cx).abs_path();
2485 let clipboard_project_path =
2486 self.project.read(cx).path_for_entry(clip_entry_id, cx)?;
2487 let clipboard_abs_path = self
2488 .project
2489 .read(cx)
2490 .absolute_path(&clipboard_project_path, cx)?;
2491 Some(relativize_path(
2492 &target_base_path,
2493 clipboard_abs_path.as_path(),
2494 ))
2495 } else {
2496 None
2497 };
2498 let task = if clip_is_cut && is_same_worktree {
2499 let task = self.project.update(cx, |project, cx| {
2500 project.rename_entry(clip_entry_id, new_path, cx)
2501 });
2502 PasteTask::Rename(task)
2503 } else {
2504 let entry_id = if is_same_worktree {
2505 clip_entry_id
2506 } else {
2507 entry.id
2508 };
2509 let task = self.project.update(cx, |project, cx| {
2510 project.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
2511 });
2512 PasteTask::Copy(task)
2513 };
2514 let needs_delete = !is_same_worktree && clip_is_cut;
2515 paste_entry_tasks.insert((clip_entry_id, needs_delete), task);
2516 disambiguation_range = new_disambiguation_range.or(disambiguation_range);
2517 }
2518
2519 let item_count = paste_entry_tasks.len();
2520
2521 cx.spawn_in(window, async move |project_panel, cx| {
2522 let mut last_succeed = None;
2523 let mut need_delete_ids = Vec::new();
2524 for ((entry_id, need_delete), task) in paste_entry_tasks.into_iter() {
2525 match task {
2526 PasteTask::Rename(task) => {
2527 if let Some(CreatedEntry::Included(entry)) = task.await.log_err() {
2528 last_succeed = Some(entry);
2529 }
2530 }
2531 PasteTask::Copy(task) => {
2532 if let Some(Some(entry)) = task.await.log_err() {
2533 last_succeed = Some(entry);
2534 if need_delete {
2535 need_delete_ids.push(entry_id);
2536 }
2537 }
2538 }
2539 }
2540 }
2541 // remove entry for cut in difference worktree
2542 for entry_id in need_delete_ids {
2543 project_panel
2544 .update(cx, |project_panel, cx| {
2545 project_panel
2546 .project
2547 .update(cx, |project, cx| project.delete_entry(entry_id, true, cx))
2548 .context("no such entry")
2549 })??
2550 .await?;
2551 }
2552 // update selection
2553 if let Some(entry) = last_succeed {
2554 project_panel
2555 .update_in(cx, |project_panel, window, cx| {
2556 project_panel.selection = Some(SelectedEntry {
2557 worktree_id,
2558 entry_id: entry.id,
2559 });
2560
2561 if item_count == 1 {
2562 // open entry if not dir, and only focus if rename is not pending
2563 if !entry.is_dir() {
2564 project_panel.open_entry(
2565 entry.id,
2566 disambiguation_range.is_none(),
2567 false,
2568 cx,
2569 );
2570 }
2571
2572 // if only one entry was pasted and it was disambiguated, open the rename editor
2573 if disambiguation_range.is_some() {
2574 cx.defer_in(window, |this, window, cx| {
2575 this.rename_impl(disambiguation_range, window, cx);
2576 });
2577 }
2578 }
2579 })
2580 .ok();
2581 }
2582
2583 anyhow::Ok(())
2584 })
2585 .detach_and_log_err(cx);
2586
2587 if clip_is_cut {
2588 // Convert the clipboard cut entry to a copy entry after the first paste.
2589 self.clipboard = self.clipboard.take().map(ClipboardEntry::into_copy_entry);
2590 }
2591
2592 self.expand_entry(worktree_id, entry.id, cx);
2593 Some(())
2594 });
2595 }
2596
2597 fn duplicate(&mut self, _: &Duplicate, window: &mut Window, cx: &mut Context<Self>) {
2598 self.copy(&Copy {}, window, cx);
2599 self.paste(&Paste {}, window, cx);
2600 }
2601
2602 fn copy_path(
2603 &mut self,
2604 _: &zed_actions::workspace::CopyPath,
2605 _: &mut Window,
2606 cx: &mut Context<Self>,
2607 ) {
2608 let abs_file_paths = {
2609 let project = self.project.read(cx);
2610 self.effective_entries()
2611 .into_iter()
2612 .filter_map(|entry| {
2613 let entry_path = project.path_for_entry(entry.entry_id, cx)?.path;
2614 Some(
2615 project
2616 .worktree_for_id(entry.worktree_id, cx)?
2617 .read(cx)
2618 .abs_path()
2619 .join(entry_path)
2620 .to_string_lossy()
2621 .to_string(),
2622 )
2623 })
2624 .collect::<Vec<_>>()
2625 };
2626 if !abs_file_paths.is_empty() {
2627 cx.write_to_clipboard(ClipboardItem::new_string(abs_file_paths.join("\n")));
2628 }
2629 }
2630
2631 fn copy_relative_path(
2632 &mut self,
2633 _: &zed_actions::workspace::CopyRelativePath,
2634 _: &mut Window,
2635 cx: &mut Context<Self>,
2636 ) {
2637 let file_paths = {
2638 let project = self.project.read(cx);
2639 self.effective_entries()
2640 .into_iter()
2641 .filter_map(|entry| {
2642 Some(
2643 project
2644 .path_for_entry(entry.entry_id, cx)?
2645 .path
2646 .to_string_lossy()
2647 .to_string(),
2648 )
2649 })
2650 .collect::<Vec<_>>()
2651 };
2652 if !file_paths.is_empty() {
2653 cx.write_to_clipboard(ClipboardItem::new_string(file_paths.join("\n")));
2654 }
2655 }
2656
2657 fn reveal_in_finder(
2658 &mut self,
2659 _: &RevealInFileManager,
2660 _: &mut Window,
2661 cx: &mut Context<Self>,
2662 ) {
2663 if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2664 cx.reveal_path(&worktree.read(cx).abs_path().join(&entry.path));
2665 }
2666 }
2667
2668 fn remove_from_project(
2669 &mut self,
2670 _: &RemoveFromProject,
2671 _window: &mut Window,
2672 cx: &mut Context<Self>,
2673 ) {
2674 for entry in self.effective_entries().iter() {
2675 let worktree_id = entry.worktree_id;
2676 self.project
2677 .update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
2678 }
2679 }
2680
2681 fn file_abs_paths_to_diff(&self, cx: &Context<Self>) -> Option<(PathBuf, PathBuf)> {
2682 let mut selections_abs_path = self
2683 .marked_entries
2684 .iter()
2685 .filter_map(|entry| {
2686 let project = self.project.read(cx);
2687 let worktree = project.worktree_for_id(entry.worktree_id, cx)?;
2688 let entry = worktree.read(cx).entry_for_id(entry.entry_id)?;
2689 if !entry.is_file() {
2690 return None;
2691 }
2692 worktree.read(cx).absolutize(&entry.path).ok()
2693 })
2694 .rev();
2695
2696 let last_path = selections_abs_path.next()?;
2697 let previous_to_last = selections_abs_path.next()?;
2698 Some((previous_to_last, last_path))
2699 }
2700
2701 fn compare_marked_files(
2702 &mut self,
2703 _: &CompareMarkedFiles,
2704 window: &mut Window,
2705 cx: &mut Context<Self>,
2706 ) {
2707 let selected_files = self.file_abs_paths_to_diff(cx);
2708 if let Some((file_path1, file_path2)) = selected_files {
2709 self.workspace
2710 .update(cx, |workspace, cx| {
2711 FileDiffView::open(file_path1, file_path2, workspace, window, cx)
2712 .detach_and_log_err(cx);
2713 })
2714 .ok();
2715 }
2716 }
2717
2718 fn open_system(&mut self, _: &OpenWithSystem, _: &mut Window, cx: &mut Context<Self>) {
2719 if let Some((worktree, entry)) = self.selected_entry(cx) {
2720 let abs_path = worktree.abs_path().join(&entry.path);
2721 cx.open_with_system(&abs_path);
2722 }
2723 }
2724
2725 fn open_in_terminal(
2726 &mut self,
2727 _: &OpenInTerminal,
2728 window: &mut Window,
2729 cx: &mut Context<Self>,
2730 ) {
2731 if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2732 let abs_path = match &entry.canonical_path {
2733 Some(canonical_path) => Some(canonical_path.to_path_buf()),
2734 None => worktree.read(cx).absolutize(&entry.path).ok(),
2735 };
2736
2737 let working_directory = if entry.is_dir() {
2738 abs_path
2739 } else {
2740 abs_path.and_then(|path| Some(path.parent()?.to_path_buf()))
2741 };
2742 if let Some(working_directory) = working_directory {
2743 window.dispatch_action(
2744 workspace::OpenTerminal { working_directory }.boxed_clone(),
2745 cx,
2746 )
2747 }
2748 }
2749 }
2750
2751 pub fn new_search_in_directory(
2752 &mut self,
2753 _: &NewSearchInDirectory,
2754 window: &mut Window,
2755 cx: &mut Context<Self>,
2756 ) {
2757 if let Some((worktree, entry)) = self.selected_sub_entry(cx) {
2758 let dir_path = if entry.is_dir() {
2759 entry.path.clone()
2760 } else {
2761 // entry is a file, use its parent directory
2762 match entry.path.parent() {
2763 Some(parent) => Arc::from(parent),
2764 None => {
2765 // File at root, open search with empty filter
2766 self.workspace
2767 .update(cx, |workspace, cx| {
2768 search::ProjectSearchView::new_search_in_directory(
2769 workspace,
2770 Path::new(""),
2771 window,
2772 cx,
2773 );
2774 })
2775 .ok();
2776 return;
2777 }
2778 }
2779 };
2780
2781 let include_root = self.project.read(cx).visible_worktrees(cx).count() > 1;
2782 let dir_path = if include_root {
2783 let mut full_path = PathBuf::from(worktree.read(cx).root_name());
2784 full_path.push(&dir_path);
2785 Arc::from(full_path)
2786 } else {
2787 dir_path
2788 };
2789
2790 self.workspace
2791 .update(cx, |workspace, cx| {
2792 search::ProjectSearchView::new_search_in_directory(
2793 workspace, &dir_path, window, cx,
2794 );
2795 })
2796 .ok();
2797 }
2798 }
2799
2800 fn move_entry(
2801 &mut self,
2802 entry_to_move: ProjectEntryId,
2803 destination: ProjectEntryId,
2804 destination_is_file: bool,
2805 cx: &mut Context<Self>,
2806 ) {
2807 if self
2808 .project
2809 .read(cx)
2810 .entry_is_worktree_root(entry_to_move, cx)
2811 {
2812 self.move_worktree_root(entry_to_move, destination, cx)
2813 } else {
2814 self.move_worktree_entry(entry_to_move, destination, destination_is_file, cx)
2815 }
2816 }
2817
2818 fn move_worktree_root(
2819 &mut self,
2820 entry_to_move: ProjectEntryId,
2821 destination: ProjectEntryId,
2822 cx: &mut Context<Self>,
2823 ) {
2824 self.project.update(cx, |project, cx| {
2825 let Some(worktree_to_move) = project.worktree_for_entry(entry_to_move, cx) else {
2826 return;
2827 };
2828 let Some(destination_worktree) = project.worktree_for_entry(destination, cx) else {
2829 return;
2830 };
2831
2832 let worktree_id = worktree_to_move.read(cx).id();
2833 let destination_id = destination_worktree.read(cx).id();
2834
2835 project
2836 .move_worktree(worktree_id, destination_id, cx)
2837 .log_err();
2838 });
2839 }
2840
2841 fn move_worktree_entry(
2842 &mut self,
2843 entry_to_move: ProjectEntryId,
2844 destination: ProjectEntryId,
2845 destination_is_file: bool,
2846 cx: &mut Context<Self>,
2847 ) {
2848 if entry_to_move == destination {
2849 return;
2850 }
2851
2852 let destination_worktree = self.project.update(cx, |project, cx| {
2853 let entry_path = project.path_for_entry(entry_to_move, cx)?;
2854 let destination_entry_path = project.path_for_entry(destination, cx)?.path;
2855
2856 let mut destination_path = destination_entry_path.as_ref();
2857 if destination_is_file {
2858 destination_path = destination_path.parent()?;
2859 }
2860
2861 let mut new_path = destination_path.to_path_buf();
2862 new_path.push(entry_path.path.file_name()?);
2863 if new_path != entry_path.path.as_ref() {
2864 let task = project.rename_entry(entry_to_move, new_path, cx);
2865 cx.foreground_executor().spawn(task).detach_and_log_err(cx);
2866 }
2867
2868 project.worktree_id_for_entry(destination, cx)
2869 });
2870
2871 if let Some(destination_worktree) = destination_worktree {
2872 self.expand_entry(destination_worktree, destination, cx);
2873 }
2874 }
2875
2876 fn index_for_selection(&self, selection: SelectedEntry) -> Option<(usize, usize, usize)> {
2877 self.index_for_entry(selection.entry_id, selection.worktree_id)
2878 }
2879
2880 fn disjoint_entries(&self, cx: &App) -> BTreeSet<SelectedEntry> {
2881 let marked_entries = self.effective_entries();
2882 let mut sanitized_entries = BTreeSet::new();
2883 if marked_entries.is_empty() {
2884 return sanitized_entries;
2885 }
2886
2887 let project = self.project.read(cx);
2888 let marked_entries_by_worktree: HashMap<WorktreeId, Vec<SelectedEntry>> = marked_entries
2889 .into_iter()
2890 .filter(|entry| !project.entry_is_worktree_root(entry.entry_id, cx))
2891 .fold(HashMap::default(), |mut map, entry| {
2892 map.entry(entry.worktree_id).or_default().push(entry);
2893 map
2894 });
2895
2896 for (worktree_id, marked_entries) in marked_entries_by_worktree {
2897 if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
2898 let worktree = worktree.read(cx);
2899 let marked_dir_paths = marked_entries
2900 .iter()
2901 .filter_map(|entry| {
2902 worktree.entry_for_id(entry.entry_id).and_then(|entry| {
2903 if entry.is_dir() {
2904 Some(entry.path.as_ref())
2905 } else {
2906 None
2907 }
2908 })
2909 })
2910 .collect::<BTreeSet<_>>();
2911
2912 sanitized_entries.extend(marked_entries.into_iter().filter(|entry| {
2913 let Some(entry_info) = worktree.entry_for_id(entry.entry_id) else {
2914 return false;
2915 };
2916 let entry_path = entry_info.path.as_ref();
2917 let inside_marked_dir = marked_dir_paths.iter().any(|&marked_dir_path| {
2918 entry_path != marked_dir_path && entry_path.starts_with(marked_dir_path)
2919 });
2920 !inside_marked_dir
2921 }));
2922 }
2923 }
2924
2925 sanitized_entries
2926 }
2927
2928 fn effective_entries(&self) -> BTreeSet<SelectedEntry> {
2929 if let Some(selection) = self.selection {
2930 let selection = SelectedEntry {
2931 entry_id: self.resolve_entry(selection.entry_id),
2932 worktree_id: selection.worktree_id,
2933 };
2934
2935 // Default to using just the selected item when nothing is marked.
2936 if self.marked_entries.is_empty() {
2937 return BTreeSet::from([selection]);
2938 }
2939
2940 // Allow operating on the selected item even when something else is marked,
2941 // making it easier to perform one-off actions without clearing a mark.
2942 if self.marked_entries.len() == 1 && !self.marked_entries.contains(&selection) {
2943 return BTreeSet::from([selection]);
2944 }
2945 }
2946
2947 // Return only marked entries since we've already handled special cases where
2948 // only selection should take precedence. At this point, marked entries may or
2949 // may not include the current selection, which is intentional.
2950 self.marked_entries
2951 .iter()
2952 .map(|entry| SelectedEntry {
2953 entry_id: self.resolve_entry(entry.entry_id),
2954 worktree_id: entry.worktree_id,
2955 })
2956 .collect::<BTreeSet<_>>()
2957 }
2958
2959 /// Finds the currently selected subentry for a given leaf entry id. If a given entry
2960 /// has no ancestors, the project entry ID that's passed in is returned as-is.
2961 fn resolve_entry(&self, id: ProjectEntryId) -> ProjectEntryId {
2962 self.ancestors
2963 .get(&id)
2964 .and_then(|ancestors| ancestors.active_ancestor())
2965 .unwrap_or(id)
2966 }
2967
2968 pub fn selected_entry<'a>(&self, cx: &'a App) -> Option<(&'a Worktree, &'a project::Entry)> {
2969 let (worktree, entry) = self.selected_entry_handle(cx)?;
2970 Some((worktree.read(cx), entry))
2971 }
2972
2973 /// Compared to selected_entry, this function resolves to the currently
2974 /// selected subentry if dir auto-folding is enabled.
2975 fn selected_sub_entry<'a>(
2976 &self,
2977 cx: &'a App,
2978 ) -> Option<(Entity<Worktree>, &'a project::Entry)> {
2979 let (worktree, mut entry) = self.selected_entry_handle(cx)?;
2980
2981 let resolved_id = self.resolve_entry(entry.id);
2982 if resolved_id != entry.id {
2983 let worktree = worktree.read(cx);
2984 entry = worktree.entry_for_id(resolved_id)?;
2985 }
2986 Some((worktree, entry))
2987 }
2988 fn selected_entry_handle<'a>(
2989 &self,
2990 cx: &'a App,
2991 ) -> Option<(Entity<Worktree>, &'a project::Entry)> {
2992 let selection = self.selection?;
2993 let project = self.project.read(cx);
2994 let worktree = project.worktree_for_id(selection.worktree_id, cx)?;
2995 let entry = worktree.read(cx).entry_for_id(selection.entry_id)?;
2996 Some((worktree, entry))
2997 }
2998
2999 fn expand_to_selection(&mut self, cx: &mut Context<Self>) -> Option<()> {
3000 let (worktree, entry) = self.selected_entry(cx)?;
3001 let expanded_dir_ids = self.expanded_dir_ids.entry(worktree.id()).or_default();
3002
3003 for path in entry.path.ancestors() {
3004 let Some(entry) = worktree.entry_for_path(path) else {
3005 continue;
3006 };
3007 if entry.is_dir()
3008 && let Err(idx) = expanded_dir_ids.binary_search(&entry.id)
3009 {
3010 expanded_dir_ids.insert(idx, entry.id);
3011 }
3012 }
3013
3014 Some(())
3015 }
3016
3017 fn create_new_git_entry(
3018 parent_entry: &Entry,
3019 git_summary: GitSummary,
3020 new_entry_kind: EntryKind,
3021 ) -> GitEntry {
3022 GitEntry {
3023 entry: Entry {
3024 id: NEW_ENTRY_ID,
3025 kind: new_entry_kind,
3026 path: parent_entry.path.join("\0").into(),
3027 inode: 0,
3028 mtime: parent_entry.mtime,
3029 size: parent_entry.size,
3030 is_ignored: parent_entry.is_ignored,
3031 is_external: false,
3032 is_private: false,
3033 is_always_included: parent_entry.is_always_included,
3034 canonical_path: parent_entry.canonical_path.clone(),
3035 char_bag: parent_entry.char_bag,
3036 is_fifo: parent_entry.is_fifo,
3037 },
3038 git_summary,
3039 }
3040 }
3041
3042 fn update_visible_entries(
3043 &mut self,
3044 new_selected_entry: Option<(WorktreeId, ProjectEntryId)>,
3045 cx: &mut Context<Self>,
3046 ) {
3047 let now = Instant::now();
3048 let settings = ProjectPanelSettings::get_global(cx);
3049 let auto_collapse_dirs = settings.auto_fold_dirs;
3050 let hide_gitignore = settings.hide_gitignore;
3051 let project = self.project.read(cx);
3052 let repo_snapshots = project.git_store().read(cx).repo_snapshots(cx);
3053 self.last_worktree_root_id = project
3054 .visible_worktrees(cx)
3055 .next_back()
3056 .and_then(|worktree| worktree.read(cx).root_entry())
3057 .map(|entry| entry.id);
3058
3059 let old_ancestors = std::mem::take(&mut self.ancestors);
3060 self.visible_entries.clear();
3061 let mut max_width_item = None;
3062
3063 let visible_worktrees: Vec<_> = project.visible_worktrees(cx).collect();
3064 let hide_root = settings.hide_root && visible_worktrees.len() == 1;
3065 for worktree in visible_worktrees {
3066 let worktree_snapshot = worktree.read(cx).snapshot();
3067 let worktree_id = worktree_snapshot.id();
3068
3069 let expanded_dir_ids = match self.expanded_dir_ids.entry(worktree_id) {
3070 hash_map::Entry::Occupied(e) => e.into_mut(),
3071 hash_map::Entry::Vacant(e) => {
3072 // The first time a worktree's root entry becomes available,
3073 // mark that root entry as expanded.
3074 if let Some(entry) = worktree_snapshot.root_entry() {
3075 e.insert(vec![entry.id]).as_slice()
3076 } else {
3077 &[]
3078 }
3079 }
3080 };
3081
3082 let mut new_entry_parent_id = None;
3083 let mut new_entry_kind = EntryKind::Dir;
3084 if let Some(edit_state) = &self.edit_state
3085 && edit_state.worktree_id == worktree_id
3086 && edit_state.is_new_entry()
3087 {
3088 new_entry_parent_id = Some(edit_state.entry_id);
3089 new_entry_kind = if edit_state.is_dir {
3090 EntryKind::Dir
3091 } else {
3092 EntryKind::File
3093 };
3094 }
3095
3096 let mut visible_worktree_entries = Vec::new();
3097 let mut entry_iter =
3098 GitTraversal::new(&repo_snapshots, worktree_snapshot.entries(true, 0));
3099 let mut auto_folded_ancestors = vec![];
3100 while let Some(entry) = entry_iter.entry() {
3101 if hide_root && Some(entry.entry) == worktree.read(cx).root_entry() {
3102 if new_entry_parent_id == Some(entry.id) {
3103 visible_worktree_entries.push(Self::create_new_git_entry(
3104 entry.entry,
3105 entry.git_summary,
3106 new_entry_kind,
3107 ));
3108 new_entry_parent_id = None;
3109 }
3110 entry_iter.advance();
3111 continue;
3112 }
3113 if auto_collapse_dirs && entry.kind.is_dir() {
3114 auto_folded_ancestors.push(entry.id);
3115 if !self.unfolded_dir_ids.contains(&entry.id)
3116 && let Some(root_path) = worktree_snapshot.root_entry()
3117 {
3118 let mut child_entries = worktree_snapshot.child_entries(&entry.path);
3119 if let Some(child) = child_entries.next()
3120 && entry.path != root_path.path
3121 && child_entries.next().is_none()
3122 && child.kind.is_dir()
3123 {
3124 entry_iter.advance();
3125
3126 continue;
3127 }
3128 }
3129 let depth = old_ancestors
3130 .get(&entry.id)
3131 .map(|ancestor| ancestor.current_ancestor_depth)
3132 .unwrap_or_default()
3133 .min(auto_folded_ancestors.len());
3134 if let Some(edit_state) = &mut self.edit_state
3135 && edit_state.entry_id == entry.id
3136 {
3137 edit_state.depth = depth;
3138 }
3139 let mut ancestors = std::mem::take(&mut auto_folded_ancestors);
3140 if ancestors.len() > 1 {
3141 ancestors.reverse();
3142 self.ancestors.insert(
3143 entry.id,
3144 FoldedAncestors {
3145 current_ancestor_depth: depth,
3146 ancestors,
3147 },
3148 );
3149 }
3150 }
3151 auto_folded_ancestors.clear();
3152 if !hide_gitignore || !entry.is_ignored {
3153 visible_worktree_entries.push(entry.to_owned());
3154 }
3155 let precedes_new_entry = if let Some(new_entry_id) = new_entry_parent_id {
3156 entry.id == new_entry_id || {
3157 self.ancestors
3158 .get(&entry.id)
3159 .is_some_and(|entries| entries.ancestors.contains(&new_entry_id))
3160 }
3161 } else {
3162 false
3163 };
3164 if precedes_new_entry && (!hide_gitignore || !entry.is_ignored) {
3165 visible_worktree_entries.push(Self::create_new_git_entry(
3166 entry.entry,
3167 entry.git_summary,
3168 new_entry_kind,
3169 ));
3170 }
3171 let worktree_abs_path = worktree.read(cx).abs_path();
3172 let (depth, path) = if Some(entry.entry) == worktree.read(cx).root_entry() {
3173 let Some(path_name) = worktree_abs_path.file_name() else {
3174 continue;
3175 };
3176 let path = ArcCow::Borrowed(Path::new(path_name));
3177 let depth = 0;
3178 (depth, path)
3179 } else if entry.is_file() {
3180 let Some(path_name) = entry
3181 .path
3182 .file_name()
3183 .with_context(|| format!("Non-root entry has no file name: {entry:?}"))
3184 .log_err()
3185 else {
3186 continue;
3187 };
3188 let path = ArcCow::Borrowed(Path::new(path_name));
3189 let depth = entry.path.ancestors().count() - 1;
3190 (depth, path)
3191 } else {
3192 let path = self
3193 .ancestors
3194 .get(&entry.id)
3195 .and_then(|ancestors| {
3196 let outermost_ancestor = ancestors.ancestors.last()?;
3197 let root_folded_entry = worktree
3198 .read(cx)
3199 .entry_for_id(*outermost_ancestor)?
3200 .path
3201 .as_ref();
3202 entry
3203 .path
3204 .strip_prefix(root_folded_entry)
3205 .ok()
3206 .and_then(|suffix| {
3207 let full_path = Path::new(root_folded_entry.file_name()?);
3208 Some(ArcCow::Owned(Arc::<Path>::from(full_path.join(suffix))))
3209 })
3210 })
3211 .or_else(|| entry.path.file_name().map(Path::new).map(ArcCow::Borrowed))
3212 .unwrap_or_else(|| ArcCow::Owned(entry.path.clone()));
3213 let depth = path.components().count();
3214 (depth, path)
3215 };
3216 let width_estimate = item_width_estimate(
3217 depth,
3218 path.to_string_lossy().chars().count(),
3219 entry.canonical_path.is_some(),
3220 );
3221
3222 match max_width_item.as_mut() {
3223 Some((id, worktree_id, width)) => {
3224 if *width < width_estimate {
3225 *id = entry.id;
3226 *worktree_id = worktree.read(cx).id();
3227 *width = width_estimate;
3228 }
3229 }
3230 None => {
3231 max_width_item = Some((entry.id, worktree.read(cx).id(), width_estimate))
3232 }
3233 }
3234
3235 if expanded_dir_ids.binary_search(&entry.id).is_err()
3236 && entry_iter.advance_to_sibling()
3237 {
3238 continue;
3239 }
3240 entry_iter.advance();
3241 }
3242
3243 project::sort_worktree_entries(&mut visible_worktree_entries);
3244
3245 self.visible_entries.push(VisibleEntriesForWorktree {
3246 worktree_id,
3247 entries: visible_worktree_entries,
3248 index: OnceCell::new(),
3249 })
3250 }
3251
3252 if let Some((project_entry_id, worktree_id, _)) = max_width_item {
3253 let mut visited_worktrees_length = 0;
3254 let index = self.visible_entries.iter().find_map(|visible_entries| {
3255 if worktree_id == visible_entries.worktree_id {
3256 visible_entries
3257 .entries
3258 .iter()
3259 .position(|entry| entry.id == project_entry_id)
3260 } else {
3261 visited_worktrees_length += visible_entries.entries.len();
3262 None
3263 }
3264 });
3265 if let Some(index) = index {
3266 self.max_width_item_index = Some(visited_worktrees_length + index);
3267 }
3268 }
3269 if let Some((worktree_id, entry_id)) = new_selected_entry {
3270 self.selection = Some(SelectedEntry {
3271 worktree_id,
3272 entry_id,
3273 });
3274 }
3275 let elapsed = now.elapsed();
3276 if self.last_reported_update.elapsed() > Duration::from_secs(3600) {
3277 telemetry::event!(
3278 "Project Panel Updated",
3279 elapsed_ms = elapsed.as_millis() as u64,
3280 worktree_entries = self
3281 .visible_entries
3282 .iter()
3283 .map(|worktree| worktree.entries.len())
3284 .sum::<usize>(),
3285 )
3286 }
3287 }
3288
3289 fn expand_entry(
3290 &mut self,
3291 worktree_id: WorktreeId,
3292 entry_id: ProjectEntryId,
3293 cx: &mut Context<Self>,
3294 ) {
3295 self.project.update(cx, |project, cx| {
3296 if let Some((worktree, expanded_dir_ids)) = project
3297 .worktree_for_id(worktree_id, cx)
3298 .zip(self.expanded_dir_ids.get_mut(&worktree_id))
3299 {
3300 project.expand_entry(worktree_id, entry_id, cx);
3301 let worktree = worktree.read(cx);
3302
3303 if let Some(mut entry) = worktree.entry_for_id(entry_id) {
3304 loop {
3305 if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
3306 expanded_dir_ids.insert(ix, entry.id);
3307 }
3308
3309 if let Some(parent_entry) =
3310 entry.path.parent().and_then(|p| worktree.entry_for_path(p))
3311 {
3312 entry = parent_entry;
3313 } else {
3314 break;
3315 }
3316 }
3317 }
3318 }
3319 });
3320 }
3321
3322 fn drop_external_files(
3323 &mut self,
3324 paths: &[PathBuf],
3325 entry_id: ProjectEntryId,
3326 window: &mut Window,
3327 cx: &mut Context<Self>,
3328 ) {
3329 let mut paths: Vec<Arc<Path>> = paths.iter().map(|path| Arc::from(path.clone())).collect();
3330
3331 let open_file_after_drop = paths.len() == 1 && paths[0].is_file();
3332
3333 let Some((target_directory, worktree, fs)) = maybe!({
3334 let project = self.project.read(cx);
3335 let fs = project.fs().clone();
3336 let worktree = project.worktree_for_entry(entry_id, cx)?;
3337 let entry = worktree.read(cx).entry_for_id(entry_id)?;
3338 let path = entry.path.clone();
3339 let target_directory = if entry.is_dir() {
3340 path.to_path_buf()
3341 } else {
3342 path.parent()?.to_path_buf()
3343 };
3344 Some((target_directory, worktree, fs))
3345 }) else {
3346 return;
3347 };
3348
3349 let mut paths_to_replace = Vec::new();
3350 for path in &paths {
3351 if let Some(name) = path.file_name() {
3352 let mut target_path = target_directory.clone();
3353 target_path.push(name);
3354 if target_path.exists() {
3355 paths_to_replace.push((name.to_string_lossy().to_string(), path.clone()));
3356 }
3357 }
3358 }
3359
3360 cx.spawn_in(window, async move |this, cx| {
3361 async move {
3362 for (filename, original_path) in &paths_to_replace {
3363 let answer = cx.update(|window, cx| {
3364 window
3365 .prompt(
3366 PromptLevel::Info,
3367 format!("A file or folder with name {filename} already exists in the destination folder. Do you want to replace it?").as_str(),
3368 None,
3369 &["Replace", "Cancel"],
3370 cx,
3371 )
3372 })?.await?;
3373
3374 if answer == 1
3375 && let Some(item_idx) = paths.iter().position(|p| p == original_path) {
3376 paths.remove(item_idx);
3377 }
3378 }
3379
3380 if paths.is_empty() {
3381 return Ok(());
3382 }
3383
3384 let task = worktree.update( cx, |worktree, cx| {
3385 worktree.copy_external_entries(target_directory.into(), paths, fs, cx)
3386 })?;
3387
3388 let opened_entries = task.await.with_context(|| "failed to copy external paths")?;
3389 this.update(cx, |this, cx| {
3390 if open_file_after_drop && !opened_entries.is_empty() {
3391 this.open_entry(opened_entries[0], true, false, cx);
3392 }
3393 })
3394 }
3395 .log_err().await
3396 })
3397 .detach();
3398 }
3399
3400 fn refresh_drag_cursor_style(
3401 &self,
3402 modifiers: &Modifiers,
3403 window: &mut Window,
3404 cx: &mut Context<Self>,
3405 ) {
3406 if let Some(existing_cursor) = cx.active_drag_cursor_style() {
3407 let new_cursor = if Self::is_copy_modifier_set(modifiers) {
3408 CursorStyle::DragCopy
3409 } else {
3410 CursorStyle::PointingHand
3411 };
3412 if existing_cursor != new_cursor {
3413 cx.set_active_drag_cursor_style(new_cursor, window);
3414 }
3415 }
3416 }
3417
3418 fn is_copy_modifier_set(modifiers: &Modifiers) -> bool {
3419 cfg!(target_os = "macos") && modifiers.alt
3420 || cfg!(not(target_os = "macos")) && modifiers.control
3421 }
3422
3423 fn drag_onto(
3424 &mut self,
3425 selections: &DraggedSelection,
3426 target_entry_id: ProjectEntryId,
3427 is_file: bool,
3428 window: &mut Window,
3429 cx: &mut Context<Self>,
3430 ) {
3431 if Self::is_copy_modifier_set(&window.modifiers()) {
3432 let _ = maybe!({
3433 let project = self.project.read(cx);
3434 let target_worktree = project.worktree_for_entry(target_entry_id, cx)?;
3435 let worktree_id = target_worktree.read(cx).id();
3436 let target_entry = target_worktree
3437 .read(cx)
3438 .entry_for_id(target_entry_id)?
3439 .clone();
3440
3441 let mut copy_tasks = Vec::new();
3442 let mut disambiguation_range = None;
3443 for selection in selections.items() {
3444 let (new_path, new_disambiguation_range) = self.create_paste_path(
3445 selection,
3446 (target_worktree.clone(), &target_entry),
3447 cx,
3448 )?;
3449
3450 let task = self.project.update(cx, |project, cx| {
3451 project.copy_entry(selection.entry_id, None, new_path, cx)
3452 });
3453 copy_tasks.push(task);
3454 disambiguation_range = new_disambiguation_range.or(disambiguation_range);
3455 }
3456
3457 let item_count = copy_tasks.len();
3458
3459 cx.spawn_in(window, async move |project_panel, cx| {
3460 let mut last_succeed = None;
3461 for task in copy_tasks.into_iter() {
3462 if let Some(Some(entry)) = task.await.log_err() {
3463 last_succeed = Some(entry.id);
3464 }
3465 }
3466 // update selection
3467 if let Some(entry_id) = last_succeed {
3468 project_panel
3469 .update_in(cx, |project_panel, window, cx| {
3470 project_panel.selection = Some(SelectedEntry {
3471 worktree_id,
3472 entry_id,
3473 });
3474
3475 // if only one entry was dragged and it was disambiguated, open the rename editor
3476 if item_count == 1 && disambiguation_range.is_some() {
3477 project_panel.rename_impl(disambiguation_range, window, cx);
3478 }
3479 })
3480 .ok();
3481 }
3482 })
3483 .detach();
3484 Some(())
3485 });
3486 } else {
3487 for selection in selections.items() {
3488 self.move_entry(selection.entry_id, target_entry_id, is_file, cx);
3489 }
3490 }
3491 }
3492
3493 fn index_for_entry(
3494 &self,
3495 entry_id: ProjectEntryId,
3496 worktree_id: WorktreeId,
3497 ) -> Option<(usize, usize, usize)> {
3498 let mut total_ix = 0;
3499 for (worktree_ix, visible) in self.visible_entries.iter().enumerate() {
3500 if worktree_id != visible.worktree_id {
3501 total_ix += visible.entries.len();
3502 continue;
3503 }
3504
3505 return visible
3506 .entries
3507 .iter()
3508 .enumerate()
3509 .find(|(_, entry)| entry.id == entry_id)
3510 .map(|(ix, _)| (worktree_ix, ix, total_ix + ix));
3511 }
3512 None
3513 }
3514
3515 fn entry_at_index(&self, index: usize) -> Option<(WorktreeId, GitEntryRef<'_>)> {
3516 let mut offset = 0;
3517 for worktree in &self.visible_entries {
3518 let current_len = worktree.entries.len();
3519 if index < offset + current_len {
3520 return worktree
3521 .entries
3522 .get(index - offset)
3523 .map(|entry| (worktree.worktree_id, entry.to_ref()));
3524 }
3525 offset += current_len;
3526 }
3527 None
3528 }
3529
3530 fn iter_visible_entries(
3531 &self,
3532 range: Range<usize>,
3533 window: &mut Window,
3534 cx: &mut Context<ProjectPanel>,
3535 mut callback: impl FnMut(
3536 &Entry,
3537 usize,
3538 &HashSet<Arc<Path>>,
3539 &mut Window,
3540 &mut Context<ProjectPanel>,
3541 ),
3542 ) {
3543 let mut ix = 0;
3544 for visible in &self.visible_entries {
3545 if ix >= range.end {
3546 return;
3547 }
3548
3549 if ix + visible.entries.len() <= range.start {
3550 ix += visible.entries.len();
3551 continue;
3552 }
3553
3554 let end_ix = range.end.min(ix + visible.entries.len());
3555 let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3556 let entries = visible
3557 .index
3558 .get_or_init(|| visible.entries.iter().map(|e| (e.path.clone())).collect());
3559 let base_index = ix + entry_range.start;
3560 for (i, entry) in visible.entries[entry_range].iter().enumerate() {
3561 let global_index = base_index + i;
3562 callback(entry, global_index, entries, window, cx);
3563 }
3564 ix = end_ix;
3565 }
3566 }
3567
3568 fn for_each_visible_entry(
3569 &self,
3570 range: Range<usize>,
3571 window: &mut Window,
3572 cx: &mut Context<ProjectPanel>,
3573 mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut Window, &mut Context<ProjectPanel>),
3574 ) {
3575 let mut ix = 0;
3576 for visible in &self.visible_entries {
3577 if ix >= range.end {
3578 return;
3579 }
3580
3581 if ix + visible.entries.len() <= range.start {
3582 ix += visible.entries.len();
3583 continue;
3584 }
3585
3586 let end_ix = range.end.min(ix + visible.entries.len());
3587 let git_status_setting = {
3588 let settings = ProjectPanelSettings::get_global(cx);
3589 settings.git_status
3590 };
3591 if let Some(worktree) = self
3592 .project
3593 .read(cx)
3594 .worktree_for_id(visible.worktree_id, cx)
3595 {
3596 let snapshot = worktree.read(cx).snapshot();
3597 let root_name = OsStr::new(snapshot.root_name());
3598
3599 let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
3600 let entries = visible
3601 .index
3602 .get_or_init(|| visible.entries.iter().map(|e| (e.path.clone())).collect());
3603 for entry in visible.entries[entry_range].iter() {
3604 let status = git_status_setting
3605 .then_some(entry.git_summary)
3606 .unwrap_or_default();
3607
3608 let mut details = self.details_for_entry(
3609 entry,
3610 visible.worktree_id,
3611 root_name,
3612 entries,
3613 status,
3614 None,
3615 window,
3616 cx,
3617 );
3618
3619 if let Some(edit_state) = &self.edit_state {
3620 let is_edited_entry = if edit_state.is_new_entry() {
3621 entry.id == NEW_ENTRY_ID
3622 } else {
3623 entry.id == edit_state.entry_id
3624 || self
3625 .ancestors
3626 .get(&entry.id)
3627 .is_some_and(|auto_folded_dirs| {
3628 auto_folded_dirs.ancestors.contains(&edit_state.entry_id)
3629 })
3630 };
3631
3632 if is_edited_entry {
3633 if let Some(processing_filename) = &edit_state.processing_filename {
3634 details.is_processing = true;
3635 if let Some(ancestors) = edit_state
3636 .leaf_entry_id
3637 .and_then(|entry| self.ancestors.get(&entry))
3638 {
3639 let position = ancestors.ancestors.iter().position(|entry_id| *entry_id == edit_state.entry_id).expect("Edited sub-entry should be an ancestor of selected leaf entry") + 1;
3640 let all_components = ancestors.ancestors.len();
3641
3642 let prefix_components = all_components - position;
3643 let suffix_components = position.checked_sub(1);
3644 let mut previous_components =
3645 Path::new(&details.filename).components();
3646 let mut new_path = previous_components
3647 .by_ref()
3648 .take(prefix_components)
3649 .collect::<PathBuf>();
3650 if let Some(last_component) =
3651 Path::new(processing_filename).components().next_back()
3652 {
3653 new_path.push(last_component);
3654 previous_components.next();
3655 }
3656
3657 if suffix_components.is_some() {
3658 new_path.push(previous_components);
3659 }
3660 if let Some(str) = new_path.to_str() {
3661 details.filename.clear();
3662 details.filename.push_str(str);
3663 }
3664 } else {
3665 details.filename.clear();
3666 details.filename.push_str(processing_filename);
3667 }
3668 } else {
3669 if edit_state.is_new_entry() {
3670 details.filename.clear();
3671 }
3672 details.is_editing = true;
3673 }
3674 }
3675 }
3676
3677 callback(entry.id, details, window, cx);
3678 }
3679 }
3680 ix = end_ix;
3681 }
3682 }
3683
3684 fn find_entry_in_worktree(
3685 &self,
3686 worktree_id: WorktreeId,
3687 reverse_search: bool,
3688 only_visible_entries: bool,
3689 predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
3690 cx: &mut Context<Self>,
3691 ) -> Option<GitEntry> {
3692 if only_visible_entries {
3693 let entries = self
3694 .visible_entries
3695 .iter()
3696 .find_map(|visible| {
3697 if worktree_id == visible.worktree_id {
3698 Some(&visible.entries)
3699 } else {
3700 None
3701 }
3702 })?
3703 .clone();
3704
3705 return utils::ReversibleIterable::new(entries.iter(), reverse_search)
3706 .find(|ele| predicate(ele.to_ref(), worktree_id))
3707 .cloned();
3708 }
3709
3710 let repo_snapshots = self
3711 .project
3712 .read(cx)
3713 .git_store()
3714 .read(cx)
3715 .repo_snapshots(cx);
3716 let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
3717 worktree.read_with(cx, |tree, _| {
3718 utils::ReversibleIterable::new(
3719 GitTraversal::new(&repo_snapshots, tree.entries(true, 0usize)),
3720 reverse_search,
3721 )
3722 .find_single_ended(|ele| predicate(*ele, worktree_id))
3723 .map(|ele| ele.to_owned())
3724 })
3725 }
3726
3727 fn find_entry(
3728 &self,
3729 start: Option<&SelectedEntry>,
3730 reverse_search: bool,
3731 predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
3732 cx: &mut Context<Self>,
3733 ) -> Option<SelectedEntry> {
3734 let mut worktree_ids: Vec<_> = self
3735 .visible_entries
3736 .iter()
3737 .map(|worktree| worktree.worktree_id)
3738 .collect();
3739 let repo_snapshots = self
3740 .project
3741 .read(cx)
3742 .git_store()
3743 .read(cx)
3744 .repo_snapshots(cx);
3745
3746 let mut last_found: Option<SelectedEntry> = None;
3747
3748 if let Some(start) = start {
3749 let worktree = self
3750 .project
3751 .read(cx)
3752 .worktree_for_id(start.worktree_id, cx)?
3753 .read(cx);
3754
3755 let search = {
3756 let entry = worktree.entry_for_id(start.entry_id)?;
3757 let root_entry = worktree.root_entry()?;
3758 let tree_id = worktree.id();
3759
3760 let mut first_iter = GitTraversal::new(
3761 &repo_snapshots,
3762 worktree.traverse_from_path(true, true, true, entry.path.as_ref()),
3763 );
3764
3765 if reverse_search {
3766 first_iter.next();
3767 }
3768
3769 let first = first_iter
3770 .enumerate()
3771 .take_until(|(count, entry)| entry.entry == root_entry && *count != 0usize)
3772 .map(|(_, entry)| entry)
3773 .find(|ele| predicate(*ele, tree_id))
3774 .map(|ele| ele.to_owned());
3775
3776 let second_iter =
3777 GitTraversal::new(&repo_snapshots, worktree.entries(true, 0usize));
3778
3779 let second = if reverse_search {
3780 second_iter
3781 .take_until(|ele| ele.id == start.entry_id)
3782 .filter(|ele| predicate(*ele, tree_id))
3783 .last()
3784 .map(|ele| ele.to_owned())
3785 } else {
3786 second_iter
3787 .take_while(|ele| ele.id != start.entry_id)
3788 .filter(|ele| predicate(*ele, tree_id))
3789 .last()
3790 .map(|ele| ele.to_owned())
3791 };
3792
3793 if reverse_search {
3794 Some((second, first))
3795 } else {
3796 Some((first, second))
3797 }
3798 };
3799
3800 if let Some((first, second)) = search {
3801 let first = first.map(|entry| SelectedEntry {
3802 worktree_id: start.worktree_id,
3803 entry_id: entry.id,
3804 });
3805
3806 let second = second.map(|entry| SelectedEntry {
3807 worktree_id: start.worktree_id,
3808 entry_id: entry.id,
3809 });
3810
3811 if first.is_some() {
3812 return first;
3813 }
3814 last_found = second;
3815
3816 let idx = worktree_ids
3817 .iter()
3818 .enumerate()
3819 .find(|(_, ele)| **ele == start.worktree_id)
3820 .map(|(idx, _)| idx);
3821
3822 if let Some(idx) = idx {
3823 worktree_ids.rotate_left(idx + 1usize);
3824 worktree_ids.pop();
3825 }
3826 }
3827 }
3828
3829 for tree_id in worktree_ids.into_iter() {
3830 if let Some(found) =
3831 self.find_entry_in_worktree(tree_id, reverse_search, false, &predicate, cx)
3832 {
3833 return Some(SelectedEntry {
3834 worktree_id: tree_id,
3835 entry_id: found.id,
3836 });
3837 }
3838 }
3839
3840 last_found
3841 }
3842
3843 fn find_visible_entry(
3844 &self,
3845 start: Option<&SelectedEntry>,
3846 reverse_search: bool,
3847 predicate: impl Fn(GitEntryRef, WorktreeId) -> bool,
3848 cx: &mut Context<Self>,
3849 ) -> Option<SelectedEntry> {
3850 let mut worktree_ids: Vec<_> = self
3851 .visible_entries
3852 .iter()
3853 .map(|worktree| worktree.worktree_id)
3854 .collect();
3855
3856 let mut last_found: Option<SelectedEntry> = None;
3857
3858 if let Some(start) = start {
3859 let entries = self
3860 .visible_entries
3861 .iter()
3862 .find(|worktree| worktree.worktree_id == start.worktree_id)
3863 .map(|worktree| &worktree.entries)?;
3864
3865 let mut start_idx = entries
3866 .iter()
3867 .enumerate()
3868 .find(|(_, ele)| ele.id == start.entry_id)
3869 .map(|(idx, _)| idx)?;
3870
3871 if reverse_search {
3872 start_idx = start_idx.saturating_add(1usize);
3873 }
3874
3875 let (left, right) = entries.split_at_checked(start_idx)?;
3876
3877 let (first_iter, second_iter) = if reverse_search {
3878 (
3879 utils::ReversibleIterable::new(left.iter(), reverse_search),
3880 utils::ReversibleIterable::new(right.iter(), reverse_search),
3881 )
3882 } else {
3883 (
3884 utils::ReversibleIterable::new(right.iter(), reverse_search),
3885 utils::ReversibleIterable::new(left.iter(), reverse_search),
3886 )
3887 };
3888
3889 let first_search = first_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
3890 let second_search = second_iter.find(|ele| predicate(ele.to_ref(), start.worktree_id));
3891
3892 if first_search.is_some() {
3893 return first_search.map(|entry| SelectedEntry {
3894 worktree_id: start.worktree_id,
3895 entry_id: entry.id,
3896 });
3897 }
3898
3899 last_found = second_search.map(|entry| SelectedEntry {
3900 worktree_id: start.worktree_id,
3901 entry_id: entry.id,
3902 });
3903
3904 let idx = worktree_ids
3905 .iter()
3906 .enumerate()
3907 .find(|(_, ele)| **ele == start.worktree_id)
3908 .map(|(idx, _)| idx);
3909
3910 if let Some(idx) = idx {
3911 worktree_ids.rotate_left(idx + 1usize);
3912 worktree_ids.pop();
3913 }
3914 }
3915
3916 for tree_id in worktree_ids.into_iter() {
3917 if let Some(found) =
3918 self.find_entry_in_worktree(tree_id, reverse_search, true, &predicate, cx)
3919 {
3920 return Some(SelectedEntry {
3921 worktree_id: tree_id,
3922 entry_id: found.id,
3923 });
3924 }
3925 }
3926
3927 last_found
3928 }
3929
3930 fn calculate_depth_and_difference(
3931 entry: &Entry,
3932 visible_worktree_entries: &HashSet<Arc<Path>>,
3933 ) -> (usize, usize) {
3934 let (depth, difference) = entry
3935 .path
3936 .ancestors()
3937 .skip(1) // Skip the entry itself
3938 .find_map(|ancestor| {
3939 if let Some(parent_entry) = visible_worktree_entries.get(ancestor) {
3940 let entry_path_components_count = entry.path.components().count();
3941 let parent_path_components_count = parent_entry.components().count();
3942 let difference = entry_path_components_count - parent_path_components_count;
3943 let depth = parent_entry
3944 .ancestors()
3945 .skip(1)
3946 .filter(|ancestor| visible_worktree_entries.contains(*ancestor))
3947 .count();
3948 Some((depth + 1, difference))
3949 } else {
3950 None
3951 }
3952 })
3953 .unwrap_or_else(|| (0, entry.path.components().count()));
3954
3955 (depth, difference)
3956 }
3957
3958 fn highlight_entry_for_external_drag(
3959 &self,
3960 target_entry: &Entry,
3961 target_worktree: &Worktree,
3962 ) -> Option<ProjectEntryId> {
3963 // Always highlight directory or parent directory if it's file
3964 if target_entry.is_dir() {
3965 Some(target_entry.id)
3966 } else {
3967 target_entry
3968 .path
3969 .parent()
3970 .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
3971 .map(|parent_entry| parent_entry.id)
3972 }
3973 }
3974
3975 fn highlight_entry_for_selection_drag(
3976 &self,
3977 target_entry: &Entry,
3978 target_worktree: &Worktree,
3979 drag_state: &DraggedSelection,
3980 cx: &Context<Self>,
3981 ) -> Option<ProjectEntryId> {
3982 let target_parent_path = target_entry.path.parent();
3983
3984 // In case of single item drag, we do not highlight existing
3985 // directory which item belongs too
3986 if drag_state.items().count() == 1
3987 && drag_state.active_selection.worktree_id == target_worktree.id()
3988 {
3989 let active_entry_path = self
3990 .project
3991 .read(cx)
3992 .path_for_entry(drag_state.active_selection.entry_id, cx)?;
3993
3994 if let Some(active_parent_path) = active_entry_path.path.parent() {
3995 // Do not highlight active entry parent
3996 if active_parent_path == target_entry.path.as_ref() {
3997 return None;
3998 }
3999
4000 // Do not highlight active entry sibling files
4001 if Some(active_parent_path) == target_parent_path && target_entry.is_file() {
4002 return None;
4003 }
4004 }
4005 }
4006
4007 // Always highlight directory or parent directory if it's file
4008 if target_entry.is_dir() {
4009 Some(target_entry.id)
4010 } else {
4011 target_parent_path
4012 .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
4013 .map(|parent_entry| parent_entry.id)
4014 }
4015 }
4016
4017 fn should_highlight_background_for_selection_drag(
4018 &self,
4019 drag_state: &DraggedSelection,
4020 last_root_id: ProjectEntryId,
4021 cx: &App,
4022 ) -> bool {
4023 // Always highlight for multiple entries
4024 if drag_state.items().count() > 1 {
4025 return true;
4026 }
4027
4028 // Since root will always have empty relative path
4029 if let Some(entry_path) = self
4030 .project
4031 .read(cx)
4032 .path_for_entry(drag_state.active_selection.entry_id, cx)
4033 {
4034 if let Some(parent_path) = entry_path.path.parent() {
4035 if !parent_path.as_os_str().is_empty() {
4036 return true;
4037 }
4038 }
4039 }
4040
4041 // If parent is empty, check if different worktree
4042 if let Some(last_root_worktree_id) = self
4043 .project
4044 .read(cx)
4045 .worktree_id_for_entry(last_root_id, cx)
4046 {
4047 if drag_state.active_selection.worktree_id != last_root_worktree_id {
4048 return true;
4049 }
4050 }
4051
4052 false
4053 }
4054
4055 fn render_entry(
4056 &self,
4057 entry_id: ProjectEntryId,
4058 details: EntryDetails,
4059 window: &mut Window,
4060 cx: &mut Context<Self>,
4061 ) -> Stateful<Div> {
4062 const GROUP_NAME: &str = "project_entry";
4063
4064 let kind = details.kind;
4065 let is_sticky = details.sticky.is_some();
4066 let sticky_index = details.sticky.as_ref().map(|this| this.sticky_index);
4067 let settings = ProjectPanelSettings::get_global(cx);
4068 let show_editor = details.is_editing && !details.is_processing;
4069
4070 let selection = SelectedEntry {
4071 worktree_id: details.worktree_id,
4072 entry_id,
4073 };
4074
4075 let is_marked = self.marked_entries.contains(&selection);
4076 let is_active = self
4077 .selection
4078 .is_some_and(|selection| selection.entry_id == entry_id);
4079
4080 let file_name = details.filename.clone();
4081
4082 let mut icon = details.icon.clone();
4083 if settings.file_icons && show_editor && details.kind.is_file() {
4084 let filename = self.filename_editor.read(cx).text(cx);
4085 if filename.len() > 2 {
4086 icon = FileIcons::get_icon(Path::new(&filename), cx);
4087 }
4088 }
4089
4090 let filename_text_color = details.filename_text_color;
4091 let diagnostic_severity = details.diagnostic_severity;
4092 let item_colors = get_item_color(is_sticky, cx);
4093
4094 let canonical_path = details
4095 .canonical_path
4096 .as_ref()
4097 .map(|f| f.to_string_lossy().to_string());
4098 let path = details.path.clone();
4099 let path_for_external_paths = path.clone();
4100 let path_for_dragged_selection = path.clone();
4101
4102 let depth = details.depth;
4103 let worktree_id = details.worktree_id;
4104 let dragged_selection = DraggedSelection {
4105 active_selection: SelectedEntry {
4106 worktree_id: selection.worktree_id,
4107 entry_id: self.resolve_entry(selection.entry_id),
4108 },
4109 marked_selections: Arc::from(self.marked_entries.clone()),
4110 };
4111
4112 let bg_color = if is_marked {
4113 item_colors.marked
4114 } else {
4115 item_colors.default
4116 };
4117
4118 let bg_hover_color = if is_marked {
4119 item_colors.marked
4120 } else {
4121 item_colors.hover
4122 };
4123
4124 let validation_color_and_message = if show_editor {
4125 match self
4126 .edit_state
4127 .as_ref()
4128 .map_or(ValidationState::None, |e| e.validation_state.clone())
4129 {
4130 ValidationState::Error(msg) => Some((Color::Error.color(cx), msg)),
4131 ValidationState::Warning(msg) => Some((Color::Warning.color(cx), msg)),
4132 ValidationState::None => None,
4133 }
4134 } else {
4135 None
4136 };
4137
4138 let border_color =
4139 if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4140 match validation_color_and_message {
4141 Some((color, _)) => color,
4142 None => item_colors.focused,
4143 }
4144 } else {
4145 bg_color
4146 };
4147
4148 let border_hover_color =
4149 if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4150 match validation_color_and_message {
4151 Some((color, _)) => color,
4152 None => item_colors.focused,
4153 }
4154 } else {
4155 bg_hover_color
4156 };
4157
4158 let folded_directory_drag_target = self.folded_directory_drag_target;
4159 let is_highlighted = {
4160 if let Some(highlight_entry_id) =
4161 self.drag_target_entry
4162 .as_ref()
4163 .and_then(|drag_target| match drag_target {
4164 DragTarget::Entry {
4165 highlight_entry_id, ..
4166 } => Some(*highlight_entry_id),
4167 DragTarget::Background => self.last_worktree_root_id,
4168 })
4169 {
4170 // Highlight if same entry or it's children
4171 if entry_id == highlight_entry_id {
4172 true
4173 } else {
4174 maybe!({
4175 let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4176 let highlight_entry = worktree.read(cx).entry_for_id(highlight_entry_id)?;
4177 Some(path.starts_with(&highlight_entry.path))
4178 })
4179 .unwrap_or(false)
4180 }
4181 } else {
4182 false
4183 }
4184 };
4185
4186 let id: ElementId = if is_sticky {
4187 SharedString::from(format!("project_panel_sticky_item_{}", entry_id.to_usize())).into()
4188 } else {
4189 (entry_id.to_proto() as usize).into()
4190 };
4191
4192 div()
4193 .id(id.clone())
4194 .relative()
4195 .group(GROUP_NAME)
4196 .cursor_pointer()
4197 .rounded_none()
4198 .bg(bg_color)
4199 .border_1()
4200 .border_r_2()
4201 .border_color(border_color)
4202 .hover(|style| style.bg(bg_hover_color).border_color(border_hover_color))
4203 .when(is_sticky, |this| {
4204 this.block_mouse_except_scroll()
4205 })
4206 .when(!is_sticky, |this| {
4207 this
4208 .when(is_highlighted && folded_directory_drag_target.is_none(), |this| this.border_color(transparent_white()).bg(item_colors.drag_over))
4209 .when(settings.drag_and_drop, |this| this
4210 .on_drag_move::<ExternalPaths>(cx.listener(
4211 move |this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
4212 let is_current_target = this.drag_target_entry.as_ref()
4213 .and_then(|entry| match entry {
4214 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4215 DragTarget::Background { .. } => None,
4216 }) == Some(entry_id);
4217
4218 if !event.bounds.contains(&event.event.position) {
4219 // Entry responsible for setting drag target is also responsible to
4220 // clear it up after drag is out of bounds
4221 if is_current_target {
4222 this.drag_target_entry = None;
4223 }
4224 return;
4225 }
4226
4227 if is_current_target {
4228 return;
4229 }
4230
4231 this.marked_entries.clear();
4232
4233 let Some((entry_id, highlight_entry_id)) = maybe!({
4234 let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4235 let target_entry = target_worktree.entry_for_path(&path_for_external_paths)?;
4236 let highlight_entry_id = this.highlight_entry_for_external_drag(target_entry, target_worktree)?;
4237 Some((target_entry.id, highlight_entry_id))
4238 }) else {
4239 return;
4240 };
4241
4242 this.drag_target_entry = Some(DragTarget::Entry {
4243 entry_id,
4244 highlight_entry_id,
4245 });
4246
4247 },
4248 ))
4249 .on_drop(cx.listener(
4250 move |this, external_paths: &ExternalPaths, window, cx| {
4251 this.drag_target_entry = None;
4252 this.hover_scroll_task.take();
4253 this.drop_external_files(external_paths.paths(), entry_id, window, cx);
4254 cx.stop_propagation();
4255 },
4256 ))
4257 .on_drag_move::<DraggedSelection>(cx.listener(
4258 move |this, event: &DragMoveEvent<DraggedSelection>, window, cx| {
4259 let is_current_target = this.drag_target_entry.as_ref()
4260 .and_then(|entry| match entry {
4261 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4262 DragTarget::Background { .. } => None,
4263 }) == Some(entry_id);
4264
4265 if !event.bounds.contains(&event.event.position) {
4266 // Entry responsible for setting drag target is also responsible to
4267 // clear it up after drag is out of bounds
4268 if is_current_target {
4269 this.drag_target_entry = None;
4270 }
4271 return;
4272 }
4273
4274 if is_current_target {
4275 return;
4276 }
4277
4278 let drag_state = event.drag(cx);
4279
4280 if drag_state.items().count() == 1 {
4281 this.marked_entries.clear();
4282 this.marked_entries.push(drag_state.active_selection);
4283 }
4284
4285 let Some((entry_id, highlight_entry_id)) = maybe!({
4286 let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4287 let target_entry = target_worktree.entry_for_path(&path_for_dragged_selection)?;
4288 let highlight_entry_id = this.highlight_entry_for_selection_drag(target_entry, target_worktree, drag_state, cx)?;
4289 Some((target_entry.id, highlight_entry_id))
4290 }) else {
4291 return;
4292 };
4293
4294 this.drag_target_entry = Some(DragTarget::Entry {
4295 entry_id,
4296 highlight_entry_id,
4297 });
4298
4299 this.hover_expand_task.take();
4300
4301 if !kind.is_dir()
4302 || this
4303 .expanded_dir_ids
4304 .get(&details.worktree_id)
4305 .is_some_and(|ids| ids.binary_search(&entry_id).is_ok())
4306 {
4307 return;
4308 }
4309
4310 let bounds = event.bounds;
4311 this.hover_expand_task =
4312 Some(cx.spawn_in(window, async move |this, cx| {
4313 cx.background_executor()
4314 .timer(Duration::from_millis(500))
4315 .await;
4316 this.update_in(cx, |this, window, cx| {
4317 this.hover_expand_task.take();
4318 if this.drag_target_entry.as_ref().and_then(|entry| match entry {
4319 DragTarget::Entry { entry_id: target_id, .. } => Some(*target_id),
4320 DragTarget::Background { .. } => None,
4321 }) == Some(entry_id)
4322 && bounds.contains(&window.mouse_position())
4323 {
4324 this.expand_entry(worktree_id, entry_id, cx);
4325 this.update_visible_entries(
4326 Some((worktree_id, entry_id)),
4327 cx,
4328 );
4329 cx.notify();
4330 }
4331 })
4332 .ok();
4333 }));
4334 },
4335 ))
4336 .on_drag(
4337 dragged_selection,
4338 {
4339 let active_component = self.ancestors.get(&entry_id).and_then(|ancestors| ancestors.active_component(&details.filename));
4340 move |selection, click_offset, _window, cx| {
4341 let filename = active_component.as_ref().unwrap_or_else(|| &details.filename);
4342 cx.new(|_| DraggedProjectEntryView {
4343 icon: details.icon.clone(),
4344 filename: filename.clone(),
4345 click_offset,
4346 selection: selection.active_selection,
4347 selections: selection.marked_selections.clone(),
4348 })
4349 }
4350 }
4351 )
4352 .on_drop(
4353 cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4354 this.drag_target_entry = None;
4355 this.hover_scroll_task.take();
4356 this.hover_expand_task.take();
4357 if folded_directory_drag_target.is_some() {
4358 return;
4359 }
4360 this.drag_onto(selections, entry_id, kind.is_file(), window, cx);
4361 }),
4362 ))
4363 })
4364 .on_mouse_down(
4365 MouseButton::Left,
4366 cx.listener(move |this, _, _, cx| {
4367 this.mouse_down = true;
4368 cx.propagate();
4369 }),
4370 )
4371 .on_click(
4372 cx.listener(move |project_panel, event: &gpui::ClickEvent, window, cx| {
4373 if event.is_right_click() || event.first_focus()
4374 || show_editor
4375 {
4376 return;
4377 }
4378 if event.standard_click() {
4379 project_panel.mouse_down = false;
4380 }
4381 cx.stop_propagation();
4382
4383 if let Some(selection) = project_panel.selection.filter(|_| event.modifiers().shift) {
4384 let current_selection = project_panel.index_for_selection(selection);
4385 let clicked_entry = SelectedEntry {
4386 entry_id,
4387 worktree_id,
4388 };
4389 let target_selection = project_panel.index_for_selection(clicked_entry);
4390 if let Some(((_, _, source_index), (_, _, target_index))) =
4391 current_selection.zip(target_selection)
4392 {
4393 let range_start = source_index.min(target_index);
4394 let range_end = source_index.max(target_index) + 1;
4395 let mut new_selections = Vec::new();
4396 project_panel.for_each_visible_entry(
4397 range_start..range_end,
4398 window,
4399 cx,
4400 |entry_id, details, _, _| {
4401 new_selections.push(SelectedEntry {
4402 entry_id,
4403 worktree_id: details.worktree_id,
4404 });
4405 },
4406 );
4407
4408 for selection in &new_selections {
4409 if !project_panel.marked_entries.contains(selection) {
4410 project_panel.marked_entries.push(*selection);
4411 }
4412 }
4413
4414 project_panel.selection = Some(clicked_entry);
4415 if !project_panel.marked_entries.contains(&clicked_entry) {
4416 project_panel.marked_entries.push(clicked_entry);
4417 }
4418 }
4419 } else if event.modifiers().secondary() {
4420 if event.click_count() > 1 {
4421 project_panel.split_entry(entry_id, false, None, cx);
4422 } else {
4423 project_panel.selection = Some(selection);
4424 if let Some(position) = project_panel.marked_entries.iter().position(|e| *e == selection) {
4425 project_panel.marked_entries.remove(position);
4426 } else {
4427 project_panel.marked_entries.push(selection);
4428 }
4429 }
4430 } else if kind.is_dir() {
4431 project_panel.marked_entries.clear();
4432 if is_sticky
4433 && let Some((_, _, index)) = project_panel.index_for_entry(entry_id, worktree_id) {
4434 project_panel.scroll_handle.scroll_to_item_with_offset(index, ScrollStrategy::Top, sticky_index.unwrap_or(0));
4435 cx.notify();
4436 // move down by 1px so that clicked item
4437 // don't count as sticky anymore
4438 cx.on_next_frame(window, |_, window, cx| {
4439 cx.on_next_frame(window, |this, _, cx| {
4440 let mut offset = this.scroll_handle.offset();
4441 offset.y += px(1.);
4442 this.scroll_handle.set_offset(offset);
4443 cx.notify();
4444 });
4445 });
4446 return;
4447 }
4448 if event.modifiers().alt {
4449 project_panel.toggle_expand_all(entry_id, window, cx);
4450 } else {
4451 project_panel.toggle_expanded(entry_id, window, cx);
4452 }
4453 } else {
4454 let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
4455 let click_count = event.click_count();
4456 let focus_opened_item = !preview_tabs_enabled || click_count > 1;
4457 let allow_preview = preview_tabs_enabled && click_count == 1;
4458 project_panel.open_entry(entry_id, focus_opened_item, allow_preview, cx);
4459 }
4460 }),
4461 )
4462 .child(
4463 ListItem::new(id)
4464 .indent_level(depth)
4465 .indent_step_size(px(settings.indent_size))
4466 .spacing(match settings.entry_spacing {
4467 ProjectPanelEntrySpacing::Comfortable => ListItemSpacing::Dense,
4468 ProjectPanelEntrySpacing::Standard => {
4469 ListItemSpacing::ExtraDense
4470 }
4471 })
4472 .selectable(false)
4473 .when_some(canonical_path, |this, path| {
4474 this.end_slot::<AnyElement>(
4475 div()
4476 .id("symlink_icon")
4477 .pr_3()
4478 .tooltip(move |window, cx| {
4479 Tooltip::with_meta(
4480 path.to_string(),
4481 None,
4482 "Symbolic Link",
4483 window,
4484 cx,
4485 )
4486 })
4487 .child(
4488 Icon::new(IconName::ArrowUpRight)
4489 .size(IconSize::Indicator)
4490 .color(filename_text_color),
4491 )
4492 .into_any_element(),
4493 )
4494 })
4495 .child(if let Some(icon) = &icon {
4496 if let Some((_, decoration_color)) =
4497 entry_diagnostic_aware_icon_decoration_and_color(diagnostic_severity)
4498 {
4499 let is_warning = diagnostic_severity
4500 .map(|severity| matches!(severity, DiagnosticSeverity::WARNING))
4501 .unwrap_or(false);
4502 div().child(
4503 DecoratedIcon::new(
4504 Icon::from_path(icon.clone()).color(Color::Muted),
4505 Some(
4506 IconDecoration::new(
4507 if kind.is_file() {
4508 if is_warning {
4509 IconDecorationKind::Triangle
4510 } else {
4511 IconDecorationKind::X
4512 }
4513 } else {
4514 IconDecorationKind::Dot
4515 },
4516 bg_color,
4517 cx,
4518 )
4519 .group_name(Some(GROUP_NAME.into()))
4520 .knockout_hover_color(bg_hover_color)
4521 .color(decoration_color.color(cx))
4522 .position(Point {
4523 x: px(-2.),
4524 y: px(-2.),
4525 }),
4526 ),
4527 )
4528 .into_any_element(),
4529 )
4530 } else {
4531 h_flex().child(Icon::from_path(icon.to_string()).color(Color::Muted))
4532 }
4533 } else if let Some((icon_name, color)) =
4534 entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
4535 {
4536 h_flex()
4537 .size(IconSize::default().rems())
4538 .child(Icon::new(icon_name).color(color).size(IconSize::Small))
4539 } else {
4540 h_flex()
4541 .size(IconSize::default().rems())
4542 .invisible()
4543 .flex_none()
4544 })
4545 .child(
4546 if let (Some(editor), true) = (Some(&self.filename_editor), show_editor) {
4547 h_flex().h_6().w_full().child(editor.clone())
4548 } else {
4549 h_flex().h_6().map(|mut this| {
4550 if let Some(folded_ancestors) = self.ancestors.get(&entry_id) {
4551 let components = Path::new(&file_name)
4552 .components()
4553 .map(|comp| comp.as_os_str().to_string_lossy().into_owned())
4554 .collect::<Vec<_>>();
4555 let active_index = folded_ancestors.active_index();
4556 let components_len = components.len();
4557 const DELIMITER: SharedString =
4558 SharedString::new_static(std::path::MAIN_SEPARATOR_STR);
4559 for (index, component) in components.iter().enumerate() {
4560 if index != 0 {
4561 let delimiter_target_index = index - 1;
4562 let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - delimiter_target_index).cloned();
4563 this = this.child(
4564 div()
4565 .when(!is_sticky, |div| {
4566 div
4567 .when(settings.drag_and_drop, |div| div
4568 .on_drop(cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4569 this.hover_scroll_task.take();
4570 this.drag_target_entry = None;
4571 this.folded_directory_drag_target = None;
4572 if let Some(target_entry_id) = target_entry_id {
4573 this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4574 }
4575 }))
4576 .on_drag_move(cx.listener(
4577 move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4578 if event.bounds.contains(&event.event.position) {
4579 this.folded_directory_drag_target = Some(
4580 FoldedDirectoryDragTarget {
4581 entry_id,
4582 index: delimiter_target_index,
4583 is_delimiter_target: true,
4584 }
4585 );
4586 } else {
4587 let is_current_target = this.folded_directory_drag_target
4588 .is_some_and(|target|
4589 target.entry_id == entry_id &&
4590 target.index == delimiter_target_index &&
4591 target.is_delimiter_target
4592 );
4593 if is_current_target {
4594 this.folded_directory_drag_target = None;
4595 }
4596 }
4597
4598 },
4599 )))
4600 })
4601 .child(
4602 Label::new(DELIMITER.clone())
4603 .single_line()
4604 .color(filename_text_color)
4605 )
4606 );
4607 }
4608 let id = SharedString::from(format!(
4609 "project_panel_path_component_{}_{index}",
4610 entry_id.to_usize()
4611 ));
4612 let label = div()
4613 .id(id)
4614 .when(!is_sticky,| div| {
4615 div
4616 .when(index != components_len - 1, |div|{
4617 let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - index).cloned();
4618 div
4619 .when(settings.drag_and_drop, |div| div
4620 .on_drag_move(cx.listener(
4621 move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4622 if event.bounds.contains(&event.event.position) {
4623 this.folded_directory_drag_target = Some(
4624 FoldedDirectoryDragTarget {
4625 entry_id,
4626 index,
4627 is_delimiter_target: false,
4628 }
4629 );
4630 } else {
4631 let is_current_target = this.folded_directory_drag_target
4632 .as_ref()
4633 .is_some_and(|target|
4634 target.entry_id == entry_id &&
4635 target.index == index &&
4636 !target.is_delimiter_target
4637 );
4638 if is_current_target {
4639 this.folded_directory_drag_target = None;
4640 }
4641 }
4642 },
4643 ))
4644 .on_drop(cx.listener(move |this, selections: &DraggedSelection, window,cx| {
4645 this.hover_scroll_task.take();
4646 this.drag_target_entry = None;
4647 this.folded_directory_drag_target = None;
4648 if let Some(target_entry_id) = target_entry_id {
4649 this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4650 }
4651 }))
4652 .when(folded_directory_drag_target.is_some_and(|target|
4653 target.entry_id == entry_id &&
4654 target.index == index
4655 ), |this| {
4656 this.bg(item_colors.drag_over)
4657 }))
4658 })
4659 })
4660 .on_mouse_down(
4661 MouseButton::Left,
4662 cx.listener(move |this, _, _, cx| {
4663 if index != active_index
4664 && let Some(folds) =
4665 this.ancestors.get_mut(&entry_id)
4666 {
4667 folds.current_ancestor_depth =
4668 components_len - 1 - index;
4669 cx.notify();
4670 }
4671 }),
4672 )
4673 .child(
4674 Label::new(component)
4675 .single_line()
4676 .color(filename_text_color)
4677 .when(
4678 index == active_index
4679 && (is_active || is_marked),
4680 |this| this.underline(),
4681 ),
4682 );
4683
4684 this = this.child(label);
4685 }
4686
4687 this
4688 } else {
4689 this.child(
4690 Label::new(file_name)
4691 .single_line()
4692 .color(filename_text_color),
4693 )
4694 }
4695 })
4696 },
4697 )
4698 .on_secondary_mouse_down(cx.listener(
4699 move |this, event: &MouseDownEvent, window, cx| {
4700 // Stop propagation to prevent the catch-all context menu for the project
4701 // panel from being deployed.
4702 cx.stop_propagation();
4703 // Some context menu actions apply to all marked entries. If the user
4704 // right-clicks on an entry that is not marked, they may not realize the
4705 // action applies to multiple entries. To avoid inadvertent changes, all
4706 // entries are unmarked.
4707 if !this.marked_entries.contains(&selection) {
4708 this.marked_entries.clear();
4709 }
4710 this.deploy_context_menu(event.position, entry_id, window, cx);
4711 },
4712 ))
4713 .overflow_x(),
4714 )
4715 .when_some(
4716 validation_color_and_message,
4717 |this, (color, message)| {
4718 this
4719 .relative()
4720 .child(
4721 deferred(
4722 div()
4723 .occlude()
4724 .absolute()
4725 .top_full()
4726 .left(px(-1.)) // Used px over rem so that it doesn't change with font size
4727 .right(px(-0.5))
4728 .py_1()
4729 .px_2()
4730 .border_1()
4731 .border_color(color)
4732 .bg(cx.theme().colors().background)
4733 .child(
4734 Label::new(message)
4735 .color(Color::from(color))
4736 .size(LabelSize::Small)
4737 )
4738 )
4739 )
4740 }
4741 )
4742 }
4743
4744 fn details_for_entry(
4745 &self,
4746 entry: &Entry,
4747 worktree_id: WorktreeId,
4748 root_name: &OsStr,
4749 entries_paths: &HashSet<Arc<Path>>,
4750 git_status: GitSummary,
4751 sticky: Option<StickyDetails>,
4752 _window: &mut Window,
4753 cx: &mut Context<Self>,
4754 ) -> EntryDetails {
4755 let (show_file_icons, show_folder_icons) = {
4756 let settings = ProjectPanelSettings::get_global(cx);
4757 (settings.file_icons, settings.folder_icons)
4758 };
4759
4760 let expanded_entry_ids = self
4761 .expanded_dir_ids
4762 .get(&worktree_id)
4763 .map(Vec::as_slice)
4764 .unwrap_or(&[]);
4765 let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
4766
4767 let icon = match entry.kind {
4768 EntryKind::File => {
4769 if show_file_icons {
4770 FileIcons::get_icon(&entry.path, cx)
4771 } else {
4772 None
4773 }
4774 }
4775 _ => {
4776 if show_folder_icons {
4777 FileIcons::get_folder_icon(is_expanded, &entry.path, cx)
4778 } else {
4779 FileIcons::get_chevron_icon(is_expanded, cx)
4780 }
4781 }
4782 };
4783
4784 let (depth, difference) =
4785 ProjectPanel::calculate_depth_and_difference(entry, entries_paths);
4786
4787 let filename = match difference {
4788 diff if diff > 1 => entry
4789 .path
4790 .iter()
4791 .skip(entry.path.components().count() - diff)
4792 .collect::<PathBuf>()
4793 .to_str()
4794 .unwrap_or_default()
4795 .to_string(),
4796 _ => entry
4797 .path
4798 .file_name()
4799 .map(|name| name.to_string_lossy().into_owned())
4800 .unwrap_or_else(|| root_name.to_string_lossy().to_string()),
4801 };
4802
4803 let selection = SelectedEntry {
4804 worktree_id,
4805 entry_id: entry.id,
4806 };
4807 let is_marked = self.marked_entries.contains(&selection);
4808 let is_selected = self.selection == Some(selection);
4809
4810 let diagnostic_severity = self
4811 .diagnostics
4812 .get(&(worktree_id, entry.path.to_path_buf()))
4813 .cloned();
4814
4815 let filename_text_color =
4816 entry_git_aware_label_color(git_status, entry.is_ignored, is_marked);
4817
4818 let is_cut = self
4819 .clipboard
4820 .as_ref()
4821 .is_some_and(|e| e.is_cut() && e.items().contains(&selection));
4822
4823 EntryDetails {
4824 filename,
4825 icon,
4826 path: entry.path.clone(),
4827 depth,
4828 kind: entry.kind,
4829 is_ignored: entry.is_ignored,
4830 is_expanded,
4831 is_selected,
4832 is_marked,
4833 is_editing: false,
4834 is_processing: false,
4835 is_cut,
4836 sticky,
4837 filename_text_color,
4838 diagnostic_severity,
4839 git_status,
4840 is_private: entry.is_private,
4841 worktree_id,
4842 canonical_path: entry.canonical_path.clone(),
4843 }
4844 }
4845
4846 fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
4847 let mut dispatch_context = KeyContext::new_with_defaults();
4848 dispatch_context.add("ProjectPanel");
4849 dispatch_context.add("menu");
4850
4851 let identifier = if self.filename_editor.focus_handle(cx).is_focused(window) {
4852 "editing"
4853 } else {
4854 "not_editing"
4855 };
4856
4857 dispatch_context.add(identifier);
4858 dispatch_context
4859 }
4860
4861 fn reveal_entry(
4862 &mut self,
4863 project: Entity<Project>,
4864 entry_id: ProjectEntryId,
4865 skip_ignored: bool,
4866 cx: &mut Context<Self>,
4867 ) -> Result<()> {
4868 let worktree = project
4869 .read(cx)
4870 .worktree_for_entry(entry_id, cx)
4871 .context("can't reveal a non-existent entry in the project panel")?;
4872 let worktree = worktree.read(cx);
4873 if skip_ignored
4874 && worktree
4875 .entry_for_id(entry_id)
4876 .is_none_or(|entry| entry.is_ignored && !entry.is_always_included)
4877 {
4878 anyhow::bail!("can't reveal an ignored entry in the project panel");
4879 }
4880 let is_active_item_file_diff_view = self
4881 .workspace
4882 .upgrade()
4883 .and_then(|ws| ws.read(cx).active_item(cx))
4884 .map(|item| item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some())
4885 .unwrap_or(false);
4886 if is_active_item_file_diff_view {
4887 return Ok(());
4888 }
4889
4890 let worktree_id = worktree.id();
4891 self.expand_entry(worktree_id, entry_id, cx);
4892 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
4893 self.marked_entries.clear();
4894 self.marked_entries.push(SelectedEntry {
4895 worktree_id,
4896 entry_id,
4897 });
4898 self.autoscroll(cx);
4899 cx.notify();
4900 Ok(())
4901 }
4902
4903 fn find_active_indent_guide(
4904 &self,
4905 indent_guides: &[IndentGuideLayout],
4906 cx: &App,
4907 ) -> Option<usize> {
4908 let (worktree, entry) = self.selected_entry(cx)?;
4909
4910 // Find the parent entry of the indent guide, this will either be the
4911 // expanded folder we have selected, or the parent of the currently
4912 // selected file/collapsed directory
4913 let mut entry = entry;
4914 loop {
4915 let is_expanded_dir = entry.is_dir()
4916 && self
4917 .expanded_dir_ids
4918 .get(&worktree.id())
4919 .map(|ids| ids.binary_search(&entry.id).is_ok())
4920 .unwrap_or(false);
4921 if is_expanded_dir {
4922 break;
4923 }
4924 entry = worktree.entry_for_path(&entry.path.parent()?)?;
4925 }
4926
4927 let (active_indent_range, depth) = {
4928 let (worktree_ix, child_offset, ix) = self.index_for_entry(entry.id, worktree.id())?;
4929 let child_paths = &self.visible_entries[worktree_ix].entries;
4930 let mut child_count = 0;
4931 let depth = entry.path.ancestors().count();
4932 while let Some(entry) = child_paths.get(child_offset + child_count + 1) {
4933 if entry.path.ancestors().count() <= depth {
4934 break;
4935 }
4936 child_count += 1;
4937 }
4938
4939 let start = ix + 1;
4940 let end = start + child_count;
4941
4942 let visible_worktree = &self.visible_entries[worktree_ix];
4943 let visible_worktree_entries = visible_worktree.index.get_or_init(|| {
4944 visible_worktree
4945 .entries
4946 .iter()
4947 .map(|e| (e.path.clone()))
4948 .collect()
4949 });
4950
4951 // Calculate the actual depth of the entry, taking into account that directories can be auto-folded.
4952 let (depth, _) = Self::calculate_depth_and_difference(entry, visible_worktree_entries);
4953 (start..end, depth)
4954 };
4955
4956 let candidates = indent_guides
4957 .iter()
4958 .enumerate()
4959 .filter(|(_, indent_guide)| indent_guide.offset.x == depth);
4960
4961 for (i, indent) in candidates {
4962 // Find matches that are either an exact match, partially on screen, or inside the enclosing indent
4963 if active_indent_range.start <= indent.offset.y + indent.length
4964 && indent.offset.y <= active_indent_range.end
4965 {
4966 return Some(i);
4967 }
4968 }
4969 None
4970 }
4971
4972 fn render_sticky_entries(
4973 &self,
4974 child: StickyProjectPanelCandidate,
4975 window: &mut Window,
4976 cx: &mut Context<Self>,
4977 ) -> SmallVec<[AnyElement; 8]> {
4978 let project = self.project.read(cx);
4979
4980 let Some((worktree_id, entry_ref)) = self.entry_at_index(child.index) else {
4981 return SmallVec::new();
4982 };
4983
4984 let Some(visible) = self
4985 .visible_entries
4986 .iter()
4987 .find(|worktree| worktree.worktree_id == worktree_id)
4988 else {
4989 return SmallVec::new();
4990 };
4991
4992 let Some(worktree) = project.worktree_for_id(worktree_id, cx) else {
4993 return SmallVec::new();
4994 };
4995 let worktree = worktree.read(cx).snapshot();
4996
4997 let paths = visible
4998 .index
4999 .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
5000
5001 let mut sticky_parents = Vec::new();
5002 let mut current_path = entry_ref.path.clone();
5003
5004 'outer: loop {
5005 if let Some(parent_path) = current_path.parent() {
5006 for ancestor_path in parent_path.ancestors() {
5007 if paths.contains(ancestor_path)
5008 && let Some(parent_entry) = worktree.entry_for_path(ancestor_path)
5009 {
5010 sticky_parents.push(parent_entry.clone());
5011 current_path = parent_entry.path.clone();
5012 continue 'outer;
5013 }
5014 }
5015 }
5016 break 'outer;
5017 }
5018
5019 if sticky_parents.is_empty() {
5020 return SmallVec::new();
5021 }
5022
5023 sticky_parents.reverse();
5024
5025 let panel_settings = ProjectPanelSettings::get_global(cx);
5026 let git_status_enabled = panel_settings.git_status;
5027 let root_name = OsStr::new(worktree.root_name());
5028
5029 let git_summaries_by_id = if git_status_enabled {
5030 visible
5031 .entries
5032 .iter()
5033 .map(|e| (e.id, e.git_summary))
5034 .collect::<HashMap<_, _>>()
5035 } else {
5036 Default::default()
5037 };
5038
5039 // already checked if non empty above
5040 let last_item_index = sticky_parents.len() - 1;
5041 sticky_parents
5042 .iter()
5043 .enumerate()
5044 .map(|(index, entry)| {
5045 let git_status = git_summaries_by_id
5046 .get(&entry.id)
5047 .copied()
5048 .unwrap_or_default();
5049 let sticky_details = Some(StickyDetails {
5050 sticky_index: index,
5051 });
5052 let details = self.details_for_entry(
5053 entry,
5054 worktree_id,
5055 root_name,
5056 paths,
5057 git_status,
5058 sticky_details,
5059 window,
5060 cx,
5061 );
5062 self.render_entry(entry.id, details, window, cx)
5063 .when(index == last_item_index, |this| {
5064 let shadow_color_top = hsla(0.0, 0.0, 0.0, 0.1);
5065 let shadow_color_bottom = hsla(0.0, 0.0, 0.0, 0.);
5066 let sticky_shadow = div()
5067 .absolute()
5068 .left_0()
5069 .bottom_neg_1p5()
5070 .h_1p5()
5071 .w_full()
5072 .bg(linear_gradient(
5073 0.,
5074 linear_color_stop(shadow_color_top, 1.),
5075 linear_color_stop(shadow_color_bottom, 0.),
5076 ));
5077 this.child(sticky_shadow)
5078 })
5079 .into_any()
5080 })
5081 .collect()
5082 }
5083}
5084
5085#[derive(Clone)]
5086struct StickyProjectPanelCandidate {
5087 index: usize,
5088 depth: usize,
5089}
5090
5091impl StickyCandidate for StickyProjectPanelCandidate {
5092 fn depth(&self) -> usize {
5093 self.depth
5094 }
5095}
5096
5097fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -> usize {
5098 const ICON_SIZE_FACTOR: usize = 2;
5099 let mut item_width = depth * ICON_SIZE_FACTOR + item_text_chars;
5100 if is_symlink {
5101 item_width += ICON_SIZE_FACTOR;
5102 }
5103 item_width
5104}
5105
5106impl Render for ProjectPanel {
5107 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5108 let has_worktree = !self.visible_entries.is_empty();
5109 let project = self.project.read(cx);
5110 let panel_settings = ProjectPanelSettings::get_global(cx);
5111 let indent_size = panel_settings.indent_size;
5112 let show_indent_guides = panel_settings.indent_guides.show == ShowIndentGuides::Always;
5113 let show_sticky_entries = {
5114 if panel_settings.sticky_scroll {
5115 let is_scrollable = self.scroll_handle.is_scrollable();
5116 let is_scrolled = self.scroll_handle.offset().y < px(0.);
5117 is_scrollable && is_scrolled
5118 } else {
5119 false
5120 }
5121 };
5122
5123 let is_local = project.is_local();
5124
5125 if has_worktree {
5126 let item_count = self
5127 .visible_entries
5128 .iter()
5129 .map(|worktree| worktree.entries.len())
5130 .sum();
5131
5132 fn handle_drag_move<T: 'static>(
5133 this: &mut ProjectPanel,
5134 e: &DragMoveEvent<T>,
5135 window: &mut Window,
5136 cx: &mut Context<ProjectPanel>,
5137 ) {
5138 if let Some(previous_position) = this.previous_drag_position {
5139 // Refresh cursor only when an actual drag happens,
5140 // because modifiers are not updated when the cursor is not moved.
5141 if e.event.position != previous_position {
5142 this.refresh_drag_cursor_style(&e.event.modifiers, window, cx);
5143 }
5144 }
5145 this.previous_drag_position = Some(e.event.position);
5146
5147 if !e.bounds.contains(&e.event.position) {
5148 this.drag_target_entry = None;
5149 return;
5150 }
5151 this.hover_scroll_task.take();
5152 let panel_height = e.bounds.size.height;
5153 if panel_height <= px(0.) {
5154 return;
5155 }
5156
5157 let event_offset = e.event.position.y - e.bounds.origin.y;
5158 // How far along in the project panel is our cursor? (0. is the top of a list, 1. is the bottom)
5159 let hovered_region_offset = event_offset / panel_height;
5160
5161 // We want the scrolling to be a bit faster when the cursor is closer to the edge of a list.
5162 // These pixels offsets were picked arbitrarily.
5163 let vertical_scroll_offset = if hovered_region_offset <= 0.05 {
5164 8.
5165 } else if hovered_region_offset <= 0.15 {
5166 5.
5167 } else if hovered_region_offset >= 0.95 {
5168 -8.
5169 } else if hovered_region_offset >= 0.85 {
5170 -5.
5171 } else {
5172 return;
5173 };
5174 let adjustment = point(px(0.), px(vertical_scroll_offset));
5175 this.hover_scroll_task = Some(cx.spawn_in(window, async move |this, cx| {
5176 loop {
5177 let should_stop_scrolling = this
5178 .update(cx, |this, cx| {
5179 this.hover_scroll_task.as_ref()?;
5180 let handle = this.scroll_handle.0.borrow_mut();
5181 let offset = handle.base_handle.offset();
5182
5183 handle.base_handle.set_offset(offset + adjustment);
5184 cx.notify();
5185 Some(())
5186 })
5187 .ok()
5188 .flatten()
5189 .is_some();
5190 if should_stop_scrolling {
5191 return;
5192 }
5193 cx.background_executor()
5194 .timer(Duration::from_millis(16))
5195 .await;
5196 }
5197 }));
5198 }
5199 h_flex()
5200 .id("project-panel")
5201 .group("project-panel")
5202 .when(panel_settings.drag_and_drop, |this| {
5203 this.on_drag_move(cx.listener(handle_drag_move::<ExternalPaths>))
5204 .on_drag_move(cx.listener(handle_drag_move::<DraggedSelection>))
5205 })
5206 .size_full()
5207 .relative()
5208 .on_modifiers_changed(cx.listener(
5209 |this, event: &ModifiersChangedEvent, window, cx| {
5210 this.refresh_drag_cursor_style(&event.modifiers, window, cx);
5211 },
5212 ))
5213 .key_context(self.dispatch_context(window, cx))
5214 .on_action(cx.listener(Self::select_next))
5215 .on_action(cx.listener(Self::select_previous))
5216 .on_action(cx.listener(Self::select_first))
5217 .on_action(cx.listener(Self::select_last))
5218 .on_action(cx.listener(Self::select_parent))
5219 .on_action(cx.listener(Self::select_next_git_entry))
5220 .on_action(cx.listener(Self::select_prev_git_entry))
5221 .on_action(cx.listener(Self::select_next_diagnostic))
5222 .on_action(cx.listener(Self::select_prev_diagnostic))
5223 .on_action(cx.listener(Self::select_next_directory))
5224 .on_action(cx.listener(Self::select_prev_directory))
5225 .on_action(cx.listener(Self::expand_selected_entry))
5226 .on_action(cx.listener(Self::collapse_selected_entry))
5227 .on_action(cx.listener(Self::collapse_all_entries))
5228 .on_action(cx.listener(Self::open))
5229 .on_action(cx.listener(Self::open_permanent))
5230 .on_action(cx.listener(Self::open_split_vertical))
5231 .on_action(cx.listener(Self::open_split_horizontal))
5232 .on_action(cx.listener(Self::confirm))
5233 .on_action(cx.listener(Self::cancel))
5234 .on_action(cx.listener(Self::copy_path))
5235 .on_action(cx.listener(Self::copy_relative_path))
5236 .on_action(cx.listener(Self::new_search_in_directory))
5237 .on_action(cx.listener(Self::unfold_directory))
5238 .on_action(cx.listener(Self::fold_directory))
5239 .on_action(cx.listener(Self::remove_from_project))
5240 .on_action(cx.listener(Self::compare_marked_files))
5241 .when(!project.is_read_only(cx), |el| {
5242 el.on_action(cx.listener(Self::new_file))
5243 .on_action(cx.listener(Self::new_directory))
5244 .on_action(cx.listener(Self::rename))
5245 .on_action(cx.listener(Self::delete))
5246 .on_action(cx.listener(Self::trash))
5247 .on_action(cx.listener(Self::cut))
5248 .on_action(cx.listener(Self::copy))
5249 .on_action(cx.listener(Self::paste))
5250 .on_action(cx.listener(Self::duplicate))
5251 .on_click(cx.listener(|this, event: &gpui::ClickEvent, window, cx| {
5252 if event.click_count() > 1
5253 && let Some(entry_id) = this.last_worktree_root_id
5254 {
5255 let project = this.project.read(cx);
5256
5257 let worktree_id = if let Some(worktree) =
5258 project.worktree_for_entry(entry_id, cx)
5259 {
5260 worktree.read(cx).id()
5261 } else {
5262 return;
5263 };
5264
5265 this.selection = Some(SelectedEntry {
5266 worktree_id,
5267 entry_id,
5268 });
5269
5270 this.new_file(&NewFile, window, cx);
5271 }
5272 }))
5273 })
5274 .when(project.is_local(), |el| {
5275 el.on_action(cx.listener(Self::reveal_in_finder))
5276 .on_action(cx.listener(Self::open_system))
5277 .on_action(cx.listener(Self::open_in_terminal))
5278 })
5279 .when(project.is_via_remote_server(), |el| {
5280 el.on_action(cx.listener(Self::open_in_terminal))
5281 })
5282 .track_focus(&self.focus_handle(cx))
5283 .child(
5284 v_flex()
5285 .child(
5286 uniform_list("entries", item_count, {
5287 cx.processor(|this, range: Range<usize>, window, cx| {
5288 let mut items = Vec::with_capacity(range.end - range.start);
5289 this.for_each_visible_entry(
5290 range,
5291 window,
5292 cx,
5293 |id, details, window, cx| {
5294 items.push(this.render_entry(id, details, window, cx));
5295 },
5296 );
5297 items
5298 })
5299 })
5300 .when(show_indent_guides, |list| {
5301 list.with_decoration(
5302 ui::indent_guides(
5303 px(indent_size),
5304 IndentGuideColors::panel(cx),
5305 )
5306 .with_compute_indents_fn(
5307 cx.entity(),
5308 |this, range, window, cx| {
5309 let mut items =
5310 SmallVec::with_capacity(range.end - range.start);
5311 this.iter_visible_entries(
5312 range,
5313 window,
5314 cx,
5315 |entry, _, entries, _, _| {
5316 let (depth, _) =
5317 Self::calculate_depth_and_difference(
5318 entry, entries,
5319 );
5320 items.push(depth);
5321 },
5322 );
5323 items
5324 },
5325 )
5326 .on_click(cx.listener(
5327 |this,
5328 active_indent_guide: &IndentGuideLayout,
5329 window,
5330 cx| {
5331 if window.modifiers().secondary() {
5332 let ix = active_indent_guide.offset.y;
5333 let Some((target_entry, worktree)) = maybe!({
5334 let (worktree_id, entry) =
5335 this.entry_at_index(ix)?;
5336 let worktree = this
5337 .project
5338 .read(cx)
5339 .worktree_for_id(worktree_id, cx)?;
5340 let target_entry = worktree
5341 .read(cx)
5342 .entry_for_path(&entry.path.parent()?)?;
5343 Some((target_entry, worktree))
5344 }) else {
5345 return;
5346 };
5347
5348 this.collapse_entry(
5349 target_entry.clone(),
5350 worktree,
5351 cx,
5352 );
5353 }
5354 },
5355 ))
5356 .with_render_fn(
5357 cx.entity(),
5358 move |this, params, _, cx| {
5359 const LEFT_OFFSET: Pixels = px(14.);
5360 const PADDING_Y: Pixels = px(4.);
5361 const HITBOX_OVERDRAW: Pixels = px(3.);
5362
5363 let active_indent_guide_index = this
5364 .find_active_indent_guide(
5365 ¶ms.indent_guides,
5366 cx,
5367 );
5368
5369 let indent_size = params.indent_size;
5370 let item_height = params.item_height;
5371
5372 params
5373 .indent_guides
5374 .into_iter()
5375 .enumerate()
5376 .map(|(idx, layout)| {
5377 let offset = if layout.continues_offscreen {
5378 px(0.)
5379 } else {
5380 PADDING_Y
5381 };
5382 let bounds = Bounds::new(
5383 point(
5384 layout.offset.x * indent_size
5385 + LEFT_OFFSET,
5386 layout.offset.y * item_height + offset,
5387 ),
5388 size(
5389 px(1.),
5390 layout.length * item_height
5391 - offset * 2.,
5392 ),
5393 );
5394 ui::RenderedIndentGuide {
5395 bounds,
5396 layout,
5397 is_active: Some(idx)
5398 == active_indent_guide_index,
5399 hitbox: Some(Bounds::new(
5400 point(
5401 bounds.origin.x - HITBOX_OVERDRAW,
5402 bounds.origin.y,
5403 ),
5404 size(
5405 bounds.size.width
5406 + HITBOX_OVERDRAW * 2.,
5407 bounds.size.height,
5408 ),
5409 )),
5410 }
5411 })
5412 .collect()
5413 },
5414 ),
5415 )
5416 })
5417 .when(show_sticky_entries, |list| {
5418 let sticky_items = ui::sticky_items(
5419 cx.entity(),
5420 |this, range, window, cx| {
5421 let mut items =
5422 SmallVec::with_capacity(range.end - range.start);
5423 this.iter_visible_entries(
5424 range,
5425 window,
5426 cx,
5427 |entry, index, entries, _, _| {
5428 let (depth, _) =
5429 Self::calculate_depth_and_difference(
5430 entry, entries,
5431 );
5432 let candidate =
5433 StickyProjectPanelCandidate { index, depth };
5434 items.push(candidate);
5435 },
5436 );
5437 items
5438 },
5439 |this, marker_entry, window, cx| {
5440 let sticky_entries =
5441 this.render_sticky_entries(marker_entry, window, cx);
5442 this.sticky_items_count = sticky_entries.len();
5443 sticky_entries
5444 },
5445 );
5446 list.with_decoration(if show_indent_guides {
5447 sticky_items.with_decoration(
5448 ui::indent_guides(
5449 px(indent_size),
5450 IndentGuideColors::panel(cx),
5451 )
5452 .with_render_fn(
5453 cx.entity(),
5454 move |_, params, _, _| {
5455 const LEFT_OFFSET: Pixels = px(14.);
5456
5457 let indent_size = params.indent_size;
5458 let item_height = params.item_height;
5459
5460 params
5461 .indent_guides
5462 .into_iter()
5463 .map(|layout| {
5464 let bounds = Bounds::new(
5465 point(
5466 layout.offset.x * indent_size
5467 + LEFT_OFFSET,
5468 layout.offset.y * item_height,
5469 ),
5470 size(
5471 px(1.),
5472 layout.length * item_height,
5473 ),
5474 );
5475 ui::RenderedIndentGuide {
5476 bounds,
5477 layout,
5478 is_active: false,
5479 hitbox: None,
5480 }
5481 })
5482 .collect()
5483 },
5484 ),
5485 )
5486 } else {
5487 sticky_items
5488 })
5489 })
5490 .with_sizing_behavior(ListSizingBehavior::Infer)
5491 .with_horizontal_sizing_behavior(
5492 ListHorizontalSizingBehavior::Unconstrained,
5493 )
5494 .with_width_from_item(self.max_width_item_index)
5495 .track_scroll(self.scroll_handle.clone()),
5496 )
5497 .child(
5498 div()
5499 .id("project-panel-blank-area")
5500 .block_mouse_except_scroll()
5501 .flex_grow()
5502 .when(
5503 self.drag_target_entry.as_ref().is_some_and(
5504 |entry| match entry {
5505 DragTarget::Background => true,
5506 DragTarget::Entry {
5507 highlight_entry_id, ..
5508 } => {
5509 self.last_worktree_root_id.is_some_and(|root_id| {
5510 *highlight_entry_id == root_id
5511 })
5512 }
5513 },
5514 ),
5515 |div| div.bg(cx.theme().colors().drop_target_background),
5516 )
5517 .on_drag_move::<ExternalPaths>(cx.listener(
5518 move |this, event: &DragMoveEvent<ExternalPaths>, _, _| {
5519 let Some(_last_root_id) = this.last_worktree_root_id else {
5520 return;
5521 };
5522 if event.bounds.contains(&event.event.position) {
5523 this.drag_target_entry = Some(DragTarget::Background);
5524 } else {
5525 if this.drag_target_entry.as_ref().is_some_and(|e| {
5526 matches!(e, DragTarget::Background)
5527 }) {
5528 this.drag_target_entry = None;
5529 }
5530 }
5531 },
5532 ))
5533 .on_drag_move::<DraggedSelection>(cx.listener(
5534 move |this, event: &DragMoveEvent<DraggedSelection>, _, cx| {
5535 let Some(last_root_id) = this.last_worktree_root_id else {
5536 return;
5537 };
5538 if event.bounds.contains(&event.event.position) {
5539 let drag_state = event.drag(cx);
5540 if this.should_highlight_background_for_selection_drag(
5541 &drag_state,
5542 last_root_id,
5543 cx,
5544 ) {
5545 this.drag_target_entry =
5546 Some(DragTarget::Background);
5547 }
5548 } else {
5549 if this.drag_target_entry.as_ref().is_some_and(|e| {
5550 matches!(e, DragTarget::Background)
5551 }) {
5552 this.drag_target_entry = None;
5553 }
5554 }
5555 },
5556 ))
5557 .on_drop(cx.listener(
5558 move |this, external_paths: &ExternalPaths, window, cx| {
5559 this.drag_target_entry = None;
5560 this.hover_scroll_task.take();
5561 if let Some(entry_id) = this.last_worktree_root_id {
5562 this.drop_external_files(
5563 external_paths.paths(),
5564 entry_id,
5565 window,
5566 cx,
5567 );
5568 }
5569 cx.stop_propagation();
5570 },
5571 ))
5572 .on_drop(cx.listener(
5573 move |this, selections: &DraggedSelection, window, cx| {
5574 this.drag_target_entry = None;
5575 this.hover_scroll_task.take();
5576 if let Some(entry_id) = this.last_worktree_root_id {
5577 this.drag_onto(selections, entry_id, false, window, cx);
5578 }
5579 cx.stop_propagation();
5580 },
5581 ))
5582 .on_click(cx.listener(|this, event, _, cx| {
5583 if matches!(event, gpui::ClickEvent::Keyboard(_)) {
5584 return;
5585 }
5586 cx.stop_propagation();
5587 this.selection = None;
5588 this.marked_entries.clear();
5589 }))
5590 .on_mouse_down(
5591 MouseButton::Right,
5592 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
5593 // When deploying the context menu anywhere below the last project entry,
5594 // act as if the user clicked the root of the last worktree.
5595 if let Some(entry_id) = this.last_worktree_root_id {
5596 this.deploy_context_menu(
5597 event.position,
5598 entry_id,
5599 window,
5600 cx,
5601 );
5602 }
5603 }),
5604 ),
5605 )
5606 .size_full(),
5607 )
5608 .custom_scrollbars(
5609 Scrollbars::for_settings::<ProjectPanelSettings>()
5610 .tracked_scroll_handle(self.scroll_handle.clone())
5611 .with_track_along(ScrollAxes::Horizontal)
5612 .notify_content(),
5613 window,
5614 cx,
5615 )
5616 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5617 deferred(
5618 anchored()
5619 .position(*position)
5620 .anchor(gpui::Corner::TopLeft)
5621 .child(menu.clone()),
5622 )
5623 .with_priority(3)
5624 }))
5625 } else {
5626 let focus_handle = self.focus_handle(cx);
5627
5628 v_flex()
5629 .id("empty-project_panel")
5630 .p_4()
5631 .size_full()
5632 .items_center()
5633 .justify_center()
5634 .gap_1()
5635 .track_focus(&self.focus_handle(cx))
5636 .child(
5637 Button::new("open_project", "Open Project")
5638 .full_width()
5639 .key_binding(KeyBinding::for_action_in(
5640 &workspace::Open,
5641 &focus_handle,
5642 window,
5643 cx,
5644 ))
5645 .on_click(cx.listener(|this, _, window, cx| {
5646 this.workspace
5647 .update(cx, |_, cx| {
5648 window.dispatch_action(workspace::Open.boxed_clone(), cx);
5649 })
5650 .log_err();
5651 })),
5652 )
5653 .child(
5654 h_flex()
5655 .w_1_2()
5656 .gap_2()
5657 .child(Divider::horizontal())
5658 .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
5659 .child(Divider::horizontal()),
5660 )
5661 .child(
5662 Button::new("clone_repo", "Clone Repository")
5663 .full_width()
5664 .on_click(cx.listener(|this, _, window, cx| {
5665 this.workspace
5666 .update(cx, |_, cx| {
5667 window.dispatch_action(git::Clone.boxed_clone(), cx);
5668 })
5669 .log_err();
5670 })),
5671 )
5672 .when(is_local, |div| {
5673 div.when(panel_settings.drag_and_drop, |div| {
5674 div.drag_over::<ExternalPaths>(|style, _, _, cx| {
5675 style.bg(cx.theme().colors().drop_target_background)
5676 })
5677 .on_drop(cx.listener(
5678 move |this, external_paths: &ExternalPaths, window, cx| {
5679 this.drag_target_entry = None;
5680 this.hover_scroll_task.take();
5681 if let Some(task) = this
5682 .workspace
5683 .update(cx, |workspace, cx| {
5684 workspace.open_workspace_for_paths(
5685 true,
5686 external_paths.paths().to_owned(),
5687 window,
5688 cx,
5689 )
5690 })
5691 .log_err()
5692 {
5693 task.detach_and_log_err(cx);
5694 }
5695 cx.stop_propagation();
5696 },
5697 ))
5698 })
5699 })
5700 }
5701 }
5702}
5703
5704impl Render for DraggedProjectEntryView {
5705 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5706 let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
5707 h_flex()
5708 .font(ui_font)
5709 .pl(self.click_offset.x + px(12.))
5710 .pt(self.click_offset.y + px(12.))
5711 .child(
5712 div()
5713 .flex()
5714 .gap_1()
5715 .items_center()
5716 .py_1()
5717 .px_2()
5718 .rounded_lg()
5719 .bg(cx.theme().colors().background)
5720 .map(|this| {
5721 if self.selections.len() > 1 && self.selections.contains(&self.selection) {
5722 this.child(Label::new(format!("{} entries", self.selections.len())))
5723 } else {
5724 this.child(if let Some(icon) = &self.icon {
5725 div().child(Icon::from_path(icon.clone()))
5726 } else {
5727 div()
5728 })
5729 .child(Label::new(self.filename.clone()))
5730 }
5731 }),
5732 )
5733 }
5734}
5735
5736impl EventEmitter<Event> for ProjectPanel {}
5737
5738impl EventEmitter<PanelEvent> for ProjectPanel {}
5739
5740impl Panel for ProjectPanel {
5741 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5742 match ProjectPanelSettings::get_global(cx).dock {
5743 DockSide::Left => DockPosition::Left,
5744 DockSide::Right => DockPosition::Right,
5745 }
5746 }
5747
5748 fn position_is_valid(&self, position: DockPosition) -> bool {
5749 matches!(position, DockPosition::Left | DockPosition::Right)
5750 }
5751
5752 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5753 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5754 let dock = match position {
5755 DockPosition::Left | DockPosition::Bottom => DockSide::Left,
5756 DockPosition::Right => DockSide::Right,
5757 };
5758 settings.project_panel.get_or_insert_default().dock = Some(dock);
5759 });
5760 }
5761
5762 fn size(&self, _: &Window, cx: &App) -> Pixels {
5763 self.width
5764 .unwrap_or_else(|| ProjectPanelSettings::get_global(cx).default_width)
5765 }
5766
5767 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
5768 self.width = size;
5769 cx.notify();
5770 cx.defer_in(window, |this, _, cx| {
5771 this.serialize(cx);
5772 });
5773 }
5774
5775 fn icon(&self, _: &Window, cx: &App) -> Option<IconName> {
5776 ProjectPanelSettings::get_global(cx)
5777 .button
5778 .then_some(IconName::FileTree)
5779 }
5780
5781 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5782 Some("Project Panel")
5783 }
5784
5785 fn toggle_action(&self) -> Box<dyn Action> {
5786 Box::new(ToggleFocus)
5787 }
5788
5789 fn persistent_name() -> &'static str {
5790 "Project Panel"
5791 }
5792
5793 fn starts_open(&self, _: &Window, cx: &App) -> bool {
5794 if !ProjectPanelSettings::get_global(cx).starts_open {
5795 return false;
5796 }
5797
5798 let project = &self.project.read(cx);
5799 project.visible_worktrees(cx).any(|tree| {
5800 tree.read(cx)
5801 .root_entry()
5802 .is_some_and(|entry| entry.is_dir())
5803 })
5804 }
5805
5806 fn activation_priority(&self) -> u32 {
5807 0
5808 }
5809}
5810
5811impl Focusable for ProjectPanel {
5812 fn focus_handle(&self, _cx: &App) -> FocusHandle {
5813 self.focus_handle.clone()
5814 }
5815}
5816
5817impl ClipboardEntry {
5818 fn is_cut(&self) -> bool {
5819 matches!(self, Self::Cut { .. })
5820 }
5821
5822 fn items(&self) -> &BTreeSet<SelectedEntry> {
5823 match self {
5824 ClipboardEntry::Copied(entries) | ClipboardEntry::Cut(entries) => entries,
5825 }
5826 }
5827
5828 fn into_copy_entry(self) -> Self {
5829 match self {
5830 ClipboardEntry::Copied(_) => self,
5831 ClipboardEntry::Cut(entries) => ClipboardEntry::Copied(entries),
5832 }
5833 }
5834}
5835
5836#[cfg(test)]
5837mod project_panel_tests;