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