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