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 if let Some(parent_entry) = target_entry
3899 .path
3900 .parent()
3901 .and_then(|parent_path| target_worktree.entry_for_path(parent_path))
3902 {
3903 Some(parent_entry.id)
3904 } else {
3905 None
3906 }
3907 }
3908
3909 fn highlight_entry_for_selection_drag(
3910 &self,
3911 target_entry: &Entry,
3912 target_worktree: &Worktree,
3913 drag_state: &DraggedSelection,
3914 cx: &Context<Self>,
3915 ) -> Option<ProjectEntryId> {
3916 let target_parent_path = target_entry.path.parent();
3917
3918 // In case of single item drag, we do not highlight existing
3919 // directory which item belongs too
3920 if drag_state.items().count() == 1 {
3921 let active_entry_path = self
3922 .project
3923 .read(cx)
3924 .path_for_entry(drag_state.active_selection.entry_id, cx)?;
3925
3926 if let Some(active_parent_path) = active_entry_path.path.parent() {
3927 // Do not highlight active entry parent
3928 if active_parent_path == target_entry.path.as_ref() {
3929 return None;
3930 }
3931
3932 // Do not highlight active entry sibling files
3933 if Some(active_parent_path) == target_parent_path && target_entry.is_file() {
3934 return None;
3935 }
3936 }
3937 }
3938
3939 // Always highlight directory or parent directory if it's file
3940 if target_entry.is_dir() {
3941 Some(target_entry.id)
3942 } else if let Some(parent_entry) =
3943 target_parent_path.and_then(|parent_path| target_worktree.entry_for_path(parent_path))
3944 {
3945 Some(parent_entry.id)
3946 } else {
3947 None
3948 }
3949 }
3950
3951 fn render_entry(
3952 &self,
3953 entry_id: ProjectEntryId,
3954 details: EntryDetails,
3955 window: &mut Window,
3956 cx: &mut Context<Self>,
3957 ) -> Stateful<Div> {
3958 const GROUP_NAME: &str = "project_entry";
3959
3960 let kind = details.kind;
3961 let is_sticky = details.sticky.is_some();
3962 let sticky_index = details.sticky.as_ref().map(|this| this.sticky_index);
3963 let settings = ProjectPanelSettings::get_global(cx);
3964 let show_editor = details.is_editing && !details.is_processing;
3965
3966 let selection = SelectedEntry {
3967 worktree_id: details.worktree_id,
3968 entry_id,
3969 };
3970
3971 let is_marked = self.marked_entries.contains(&selection);
3972 let is_active = self
3973 .selection
3974 .is_some_and(|selection| selection.entry_id == entry_id);
3975
3976 let file_name = details.filename.clone();
3977
3978 let mut icon = details.icon.clone();
3979 if settings.file_icons && show_editor && details.kind.is_file() {
3980 let filename = self.filename_editor.read(cx).text(cx);
3981 if filename.len() > 2 {
3982 icon = FileIcons::get_icon(Path::new(&filename), cx);
3983 }
3984 }
3985
3986 let filename_text_color = details.filename_text_color;
3987 let diagnostic_severity = details.diagnostic_severity;
3988 let item_colors = get_item_color(is_sticky, cx);
3989
3990 let canonical_path = details
3991 .canonical_path
3992 .as_ref()
3993 .map(|f| f.to_string_lossy().to_string());
3994 let path = details.path.clone();
3995 let path_for_external_paths = path.clone();
3996 let path_for_dragged_selection = path.clone();
3997
3998 let depth = details.depth;
3999 let worktree_id = details.worktree_id;
4000 let dragged_selection = DraggedSelection {
4001 active_selection: selection,
4002 marked_selections: Arc::from(self.marked_entries.clone()),
4003 };
4004
4005 let bg_color = if is_marked {
4006 item_colors.marked
4007 } else {
4008 item_colors.default
4009 };
4010
4011 let bg_hover_color = if is_marked {
4012 item_colors.marked
4013 } else {
4014 item_colors.hover
4015 };
4016
4017 let validation_color_and_message = if show_editor {
4018 match self
4019 .edit_state
4020 .as_ref()
4021 .map_or(ValidationState::None, |e| e.validation_state.clone())
4022 {
4023 ValidationState::Error(msg) => Some((Color::Error.color(cx), msg)),
4024 ValidationState::Warning(msg) => Some((Color::Warning.color(cx), msg)),
4025 ValidationState::None => None,
4026 }
4027 } else {
4028 None
4029 };
4030
4031 let border_color =
4032 if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4033 match validation_color_and_message {
4034 Some((color, _)) => color,
4035 None => item_colors.focused,
4036 }
4037 } else {
4038 bg_color
4039 };
4040
4041 let border_hover_color =
4042 if !self.mouse_down && is_active && self.focus_handle.contains_focused(window, cx) {
4043 match validation_color_and_message {
4044 Some((color, _)) => color,
4045 None => item_colors.focused,
4046 }
4047 } else {
4048 bg_hover_color
4049 };
4050
4051 let folded_directory_drag_target = self.folded_directory_drag_target;
4052 let is_highlighted = {
4053 if let Some(highlight_entry_id) = self
4054 .drag_target_entry
4055 .as_ref()
4056 .and_then(|drag_target| drag_target.highlight_entry_id)
4057 {
4058 // Highlight if same entry or it's children
4059 if entry_id == highlight_entry_id {
4060 true
4061 } else {
4062 maybe!({
4063 let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
4064 let highlight_entry = worktree.read(cx).entry_for_id(highlight_entry_id)?;
4065 Some(path.starts_with(&highlight_entry.path))
4066 })
4067 .unwrap_or(false)
4068 }
4069 } else {
4070 false
4071 }
4072 };
4073
4074 let id: ElementId = if is_sticky {
4075 SharedString::from(format!("project_panel_sticky_item_{}", entry_id.to_usize())).into()
4076 } else {
4077 (entry_id.to_proto() as usize).into()
4078 };
4079
4080 div()
4081 .id(id.clone())
4082 .relative()
4083 .group(GROUP_NAME)
4084 .cursor_pointer()
4085 .rounded_none()
4086 .bg(bg_color)
4087 .border_1()
4088 .border_r_2()
4089 .border_color(border_color)
4090 .hover(|style| style.bg(bg_hover_color).border_color(border_hover_color))
4091 .when(is_sticky, |this| {
4092 this.block_mouse_except_scroll()
4093 })
4094 .when(!is_sticky, |this| {
4095 this
4096 .when(is_highlighted && folded_directory_drag_target.is_none(), |this| this.border_color(transparent_white()).bg(item_colors.drag_over))
4097 .on_drag_move::<ExternalPaths>(cx.listener(
4098 move |this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
4099 let is_current_target = this.drag_target_entry.as_ref()
4100 .map(|entry| entry.entry_id) == Some(entry_id);
4101
4102 if !event.bounds.contains(&event.event.position) {
4103 // Entry responsible for setting drag target is also responsible to
4104 // clear it up after drag is out of bounds
4105 if is_current_target {
4106 this.drag_target_entry = None;
4107 }
4108 return;
4109 }
4110
4111 if is_current_target {
4112 return;
4113 }
4114
4115 let Some((entry_id, highlight_entry_id)) = maybe!({
4116 let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4117 let target_entry = target_worktree.entry_for_path(&path_for_external_paths)?;
4118 let highlight_entry_id = this.highlight_entry_for_external_drag(target_entry, target_worktree);
4119 Some((target_entry.id, highlight_entry_id))
4120 }) else {
4121 return;
4122 };
4123
4124 this.drag_target_entry = Some(DragTargetEntry {
4125 entry_id,
4126 highlight_entry_id,
4127 });
4128 this.marked_entries.clear();
4129 },
4130 ))
4131 .on_drop(cx.listener(
4132 move |this, external_paths: &ExternalPaths, window, cx| {
4133 this.drag_target_entry = None;
4134 this.hover_scroll_task.take();
4135 this.drop_external_files(external_paths.paths(), entry_id, window, cx);
4136 cx.stop_propagation();
4137 },
4138 ))
4139 .on_drag_move::<DraggedSelection>(cx.listener(
4140 move |this, event: &DragMoveEvent<DraggedSelection>, window, cx| {
4141 let is_current_target = this.drag_target_entry.as_ref()
4142 .map(|entry| entry.entry_id) == Some(entry_id);
4143
4144 if !event.bounds.contains(&event.event.position) {
4145 // Entry responsible for setting drag target is also responsible to
4146 // clear it up after drag is out of bounds
4147 if is_current_target {
4148 this.drag_target_entry = None;
4149 }
4150 return;
4151 }
4152
4153 if is_current_target {
4154 return;
4155 }
4156
4157 let drag_state = event.drag(cx);
4158 let Some((entry_id, highlight_entry_id)) = maybe!({
4159 let target_worktree = this.project.read(cx).worktree_for_id(selection.worktree_id, cx)?.read(cx);
4160 let target_entry = target_worktree.entry_for_path(&path_for_dragged_selection)?;
4161 let highlight_entry_id = this.highlight_entry_for_selection_drag(target_entry, target_worktree, drag_state, cx);
4162 Some((target_entry.id, highlight_entry_id))
4163 }) else {
4164 return;
4165 };
4166
4167 this.drag_target_entry = Some(DragTargetEntry {
4168 entry_id,
4169 highlight_entry_id,
4170 });
4171 if drag_state.items().count() == 1 {
4172 this.marked_entries.clear();
4173 this.marked_entries.push(drag_state.active_selection);
4174 }
4175 this.hover_expand_task.take();
4176
4177 if !kind.is_dir()
4178 || this
4179 .expanded_dir_ids
4180 .get(&details.worktree_id)
4181 .is_some_and(|ids| ids.binary_search(&entry_id).is_ok())
4182 {
4183 return;
4184 }
4185
4186 let bounds = event.bounds;
4187 this.hover_expand_task =
4188 Some(cx.spawn_in(window, async move |this, cx| {
4189 cx.background_executor()
4190 .timer(Duration::from_millis(500))
4191 .await;
4192 this.update_in(cx, |this, window, cx| {
4193 this.hover_expand_task.take();
4194 if this.drag_target_entry.as_ref().map(|entry| entry.entry_id) == Some(entry_id)
4195 && bounds.contains(&window.mouse_position())
4196 {
4197 this.expand_entry(worktree_id, entry_id, cx);
4198 this.update_visible_entries(
4199 Some((worktree_id, entry_id)),
4200 cx,
4201 );
4202 cx.notify();
4203 }
4204 })
4205 .ok();
4206 }));
4207 },
4208 ))
4209 .on_drag(
4210 dragged_selection,
4211 move |selection, click_offset, _window, cx| {
4212 cx.new(|_| DraggedProjectEntryView {
4213 details: details.clone(),
4214 click_offset,
4215 selection: selection.active_selection,
4216 selections: selection.marked_selections.clone(),
4217 })
4218 },
4219 )
4220 .on_drop(
4221 cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4222 this.drag_target_entry = None;
4223 this.hover_scroll_task.take();
4224 this.hover_expand_task.take();
4225 if folded_directory_drag_target.is_some() {
4226 return;
4227 }
4228 this.drag_onto(selections, entry_id, kind.is_file(), window, cx);
4229 }),
4230 )
4231 })
4232 .on_mouse_down(
4233 MouseButton::Left,
4234 cx.listener(move |this, _, _, cx| {
4235 this.mouse_down = true;
4236 cx.propagate();
4237 }),
4238 )
4239 .on_click(
4240 cx.listener(move |project_panel, event: &gpui::ClickEvent, window, cx| {
4241 if event.is_right_click() || event.first_focus()
4242 || show_editor
4243 {
4244 return;
4245 }
4246 if event.standard_click() {
4247 project_panel.mouse_down = false;
4248 }
4249 cx.stop_propagation();
4250
4251 if let Some(selection) = project_panel.selection.filter(|_| event.modifiers().shift) {
4252 let current_selection = project_panel.index_for_selection(selection);
4253 let clicked_entry = SelectedEntry {
4254 entry_id,
4255 worktree_id,
4256 };
4257 let target_selection = project_panel.index_for_selection(clicked_entry);
4258 if let Some(((_, _, source_index), (_, _, target_index))) =
4259 current_selection.zip(target_selection)
4260 {
4261 let range_start = source_index.min(target_index);
4262 let range_end = source_index.max(target_index) + 1;
4263 let mut new_selections = Vec::new();
4264 project_panel.for_each_visible_entry(
4265 range_start..range_end,
4266 window,
4267 cx,
4268 |entry_id, details, _, _| {
4269 new_selections.push(SelectedEntry {
4270 entry_id,
4271 worktree_id: details.worktree_id,
4272 });
4273 },
4274 );
4275
4276 for selection in &new_selections {
4277 if !project_panel.marked_entries.contains(selection) {
4278 project_panel.marked_entries.push(*selection);
4279 }
4280 }
4281
4282 project_panel.selection = Some(clicked_entry);
4283 if !project_panel.marked_entries.contains(&clicked_entry) {
4284 project_panel.marked_entries.push(clicked_entry);
4285 }
4286 }
4287 } else if event.modifiers().secondary() {
4288 if event.click_count() > 1 {
4289 project_panel.split_entry(entry_id, cx);
4290 } else {
4291 project_panel.selection = Some(selection);
4292 if let Some(position) = project_panel.marked_entries.iter().position(|e| *e == selection) {
4293 project_panel.marked_entries.remove(position);
4294 } else {
4295 project_panel.marked_entries.push(selection);
4296 }
4297 }
4298 } else if kind.is_dir() {
4299 project_panel.marked_entries.clear();
4300 if is_sticky
4301 && let Some((_, _, index)) = project_panel.index_for_entry(entry_id, worktree_id) {
4302 project_panel.scroll_handle.scroll_to_item_with_offset(index, ScrollStrategy::Top, sticky_index.unwrap_or(0));
4303 cx.notify();
4304 // move down by 1px so that clicked item
4305 // don't count as sticky anymore
4306 cx.on_next_frame(window, |_, window, cx| {
4307 cx.on_next_frame(window, |this, _, cx| {
4308 let mut offset = this.scroll_handle.offset();
4309 offset.y += px(1.);
4310 this.scroll_handle.set_offset(offset);
4311 cx.notify();
4312 });
4313 });
4314 return;
4315 }
4316 if event.modifiers().alt {
4317 project_panel.toggle_expand_all(entry_id, window, cx);
4318 } else {
4319 project_panel.toggle_expanded(entry_id, window, cx);
4320 }
4321 } else {
4322 let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
4323 let click_count = event.click_count();
4324 let focus_opened_item = !preview_tabs_enabled || click_count > 1;
4325 let allow_preview = preview_tabs_enabled && click_count == 1;
4326 project_panel.open_entry(entry_id, focus_opened_item, allow_preview, cx);
4327 }
4328 }),
4329 )
4330 .child(
4331 ListItem::new(id)
4332 .indent_level(depth)
4333 .indent_step_size(px(settings.indent_size))
4334 .spacing(match settings.entry_spacing {
4335 project_panel_settings::EntrySpacing::Comfortable => ListItemSpacing::Dense,
4336 project_panel_settings::EntrySpacing::Standard => {
4337 ListItemSpacing::ExtraDense
4338 }
4339 })
4340 .selectable(false)
4341 .when_some(canonical_path, |this, path| {
4342 this.end_slot::<AnyElement>(
4343 div()
4344 .id("symlink_icon")
4345 .pr_3()
4346 .tooltip(move |window, cx| {
4347 Tooltip::with_meta(
4348 path.to_string(),
4349 None,
4350 "Symbolic Link",
4351 window,
4352 cx,
4353 )
4354 })
4355 .child(
4356 Icon::new(IconName::ArrowUpRight)
4357 .size(IconSize::Indicator)
4358 .color(filename_text_color),
4359 )
4360 .into_any_element(),
4361 )
4362 })
4363 .child(if let Some(icon) = &icon {
4364 if let Some((_, decoration_color)) =
4365 entry_diagnostic_aware_icon_decoration_and_color(diagnostic_severity)
4366 {
4367 let is_warning = diagnostic_severity
4368 .map(|severity| matches!(severity, DiagnosticSeverity::WARNING))
4369 .unwrap_or(false);
4370 div().child(
4371 DecoratedIcon::new(
4372 Icon::from_path(icon.clone()).color(Color::Muted),
4373 Some(
4374 IconDecoration::new(
4375 if kind.is_file() {
4376 if is_warning {
4377 IconDecorationKind::Triangle
4378 } else {
4379 IconDecorationKind::X
4380 }
4381 } else {
4382 IconDecorationKind::Dot
4383 },
4384 bg_color,
4385 cx,
4386 )
4387 .group_name(Some(GROUP_NAME.into()))
4388 .knockout_hover_color(bg_hover_color)
4389 .color(decoration_color.color(cx))
4390 .position(Point {
4391 x: px(-2.),
4392 y: px(-2.),
4393 }),
4394 ),
4395 )
4396 .into_any_element(),
4397 )
4398 } else {
4399 h_flex().child(Icon::from_path(icon.to_string()).color(Color::Muted))
4400 }
4401 } else if let Some((icon_name, color)) =
4402 entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
4403 {
4404 h_flex()
4405 .size(IconSize::default().rems())
4406 .child(Icon::new(icon_name).color(color).size(IconSize::Small))
4407 } else {
4408 h_flex()
4409 .size(IconSize::default().rems())
4410 .invisible()
4411 .flex_none()
4412 })
4413 .child(
4414 if let (Some(editor), true) = (Some(&self.filename_editor), show_editor) {
4415 h_flex().h_6().w_full().child(editor.clone())
4416 } else {
4417 h_flex().h_6().map(|mut this| {
4418 if let Some(folded_ancestors) = self.ancestors.get(&entry_id) {
4419 let components = Path::new(&file_name)
4420 .components()
4421 .map(|comp| {
4422 comp.as_os_str().to_string_lossy().into_owned()
4423 })
4424 .collect::<Vec<_>>();
4425
4426 let components_len = components.len();
4427 // TODO this can underflow
4428 let active_index = components_len
4429 - 1
4430 - folded_ancestors.current_ancestor_depth;
4431 const DELIMITER: SharedString =
4432 SharedString::new_static(std::path::MAIN_SEPARATOR_STR);
4433 for (index, component) in components.into_iter().enumerate() {
4434 if index != 0 {
4435 let delimiter_target_index = index - 1;
4436 let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - delimiter_target_index).cloned();
4437 this = this.child(
4438 div()
4439 .when(!is_sticky, |div| {
4440 div
4441 .on_drop(cx.listener(move |this, selections: &DraggedSelection, window, cx| {
4442 this.hover_scroll_task.take();
4443 this.drag_target_entry = None;
4444 this.folded_directory_drag_target = None;
4445 if let Some(target_entry_id) = target_entry_id {
4446 this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4447 }
4448 }))
4449 .on_drag_move(cx.listener(
4450 move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4451 if event.bounds.contains(&event.event.position) {
4452 this.folded_directory_drag_target = Some(
4453 FoldedDirectoryDragTarget {
4454 entry_id,
4455 index: delimiter_target_index,
4456 is_delimiter_target: true,
4457 }
4458 );
4459 } else {
4460 let is_current_target = this.folded_directory_drag_target
4461 .is_some_and(|target|
4462 target.entry_id == entry_id &&
4463 target.index == delimiter_target_index &&
4464 target.is_delimiter_target
4465 );
4466 if is_current_target {
4467 this.folded_directory_drag_target = None;
4468 }
4469 }
4470
4471 },
4472 ))
4473 })
4474 .child(
4475 Label::new(DELIMITER.clone())
4476 .single_line()
4477 .color(filename_text_color)
4478 )
4479 );
4480 }
4481 let id = SharedString::from(format!(
4482 "project_panel_path_component_{}_{index}",
4483 entry_id.to_usize()
4484 ));
4485 let label = div()
4486 .id(id)
4487 .when(!is_sticky,| div| {
4488 div
4489 .when(index != components_len - 1, |div|{
4490 let target_entry_id = folded_ancestors.ancestors.get(components_len - 1 - index).cloned();
4491 div
4492 .on_drag_move(cx.listener(
4493 move |this, event: &DragMoveEvent<DraggedSelection>, _, _| {
4494 if event.bounds.contains(&event.event.position) {
4495 this.folded_directory_drag_target = Some(
4496 FoldedDirectoryDragTarget {
4497 entry_id,
4498 index,
4499 is_delimiter_target: false,
4500 }
4501 );
4502 } else {
4503 let is_current_target = this.folded_directory_drag_target
4504 .as_ref()
4505 .is_some_and(|target|
4506 target.entry_id == entry_id &&
4507 target.index == index &&
4508 !target.is_delimiter_target
4509 );
4510 if is_current_target {
4511 this.folded_directory_drag_target = None;
4512 }
4513 }
4514 },
4515 ))
4516 .on_drop(cx.listener(move |this, selections: &DraggedSelection, window,cx| {
4517 this.hover_scroll_task.take();
4518 this.drag_target_entry = None;
4519 this.folded_directory_drag_target = None;
4520 if let Some(target_entry_id) = target_entry_id {
4521 this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
4522 }
4523 }))
4524 .when(folded_directory_drag_target.is_some_and(|target|
4525 target.entry_id == entry_id &&
4526 target.index == index
4527 ), |this| {
4528 this.bg(item_colors.drag_over)
4529 })
4530 })
4531 })
4532 .on_click(cx.listener(move |this, _, _, cx| {
4533 if index != active_index
4534 && let Some(folds) =
4535 this.ancestors.get_mut(&entry_id)
4536 {
4537 folds.current_ancestor_depth =
4538 components_len - 1 - index;
4539 cx.notify();
4540 }
4541 }))
4542 .child(
4543 Label::new(component)
4544 .single_line()
4545 .color(filename_text_color)
4546 .when(
4547 index == active_index
4548 && (is_active || is_marked),
4549 |this| this.underline(),
4550 ),
4551 );
4552
4553 this = this.child(label);
4554 }
4555
4556 this
4557 } else {
4558 this.child(
4559 Label::new(file_name)
4560 .single_line()
4561 .color(filename_text_color),
4562 )
4563 }
4564 })
4565 },
4566 )
4567 .on_secondary_mouse_down(cx.listener(
4568 move |this, event: &MouseDownEvent, window, cx| {
4569 // Stop propagation to prevent the catch-all context menu for the project
4570 // panel from being deployed.
4571 cx.stop_propagation();
4572 // Some context menu actions apply to all marked entries. If the user
4573 // right-clicks on an entry that is not marked, they may not realize the
4574 // action applies to multiple entries. To avoid inadvertent changes, all
4575 // entries are unmarked.
4576 if !this.marked_entries.contains(&selection) {
4577 this.marked_entries.clear();
4578 }
4579 this.deploy_context_menu(event.position, entry_id, window, cx);
4580 },
4581 ))
4582 .overflow_x(),
4583 )
4584 .when_some(
4585 validation_color_and_message,
4586 |this, (color, message)| {
4587 this
4588 .relative()
4589 .child(
4590 deferred(
4591 div()
4592 .occlude()
4593 .absolute()
4594 .top_full()
4595 .left(px(-1.)) // Used px over rem so that it doesn't change with font size
4596 .right(px(-0.5))
4597 .py_1()
4598 .px_2()
4599 .border_1()
4600 .border_color(color)
4601 .bg(cx.theme().colors().background)
4602 .child(
4603 Label::new(message)
4604 .color(Color::from(color))
4605 .size(LabelSize::Small)
4606 )
4607 )
4608 )
4609 }
4610 )
4611 }
4612
4613 fn details_for_entry(
4614 &self,
4615 entry: &Entry,
4616 worktree_id: WorktreeId,
4617 root_name: &OsStr,
4618 entries_paths: &HashSet<Arc<Path>>,
4619 git_status: GitSummary,
4620 sticky: Option<StickyDetails>,
4621 _window: &mut Window,
4622 cx: &mut Context<Self>,
4623 ) -> EntryDetails {
4624 let (show_file_icons, show_folder_icons) = {
4625 let settings = ProjectPanelSettings::get_global(cx);
4626 (settings.file_icons, settings.folder_icons)
4627 };
4628
4629 let expanded_entry_ids = self
4630 .expanded_dir_ids
4631 .get(&worktree_id)
4632 .map(Vec::as_slice)
4633 .unwrap_or(&[]);
4634 let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
4635
4636 let icon = match entry.kind {
4637 EntryKind::File => {
4638 if show_file_icons {
4639 FileIcons::get_icon(&entry.path, cx)
4640 } else {
4641 None
4642 }
4643 }
4644 _ => {
4645 if show_folder_icons {
4646 FileIcons::get_folder_icon(is_expanded, cx)
4647 } else {
4648 FileIcons::get_chevron_icon(is_expanded, cx)
4649 }
4650 }
4651 };
4652
4653 let (depth, difference) =
4654 ProjectPanel::calculate_depth_and_difference(entry, entries_paths);
4655
4656 let filename = match difference {
4657 diff if diff > 1 => entry
4658 .path
4659 .iter()
4660 .skip(entry.path.components().count() - diff)
4661 .collect::<PathBuf>()
4662 .to_str()
4663 .unwrap_or_default()
4664 .to_string(),
4665 _ => entry
4666 .path
4667 .file_name()
4668 .map(|name| name.to_string_lossy().into_owned())
4669 .unwrap_or_else(|| root_name.to_string_lossy().to_string()),
4670 };
4671
4672 let selection = SelectedEntry {
4673 worktree_id,
4674 entry_id: entry.id,
4675 };
4676 let is_marked = self.marked_entries.contains(&selection);
4677 let is_selected = self.selection == Some(selection);
4678
4679 let diagnostic_severity = self
4680 .diagnostics
4681 .get(&(worktree_id, entry.path.to_path_buf()))
4682 .cloned();
4683
4684 let filename_text_color =
4685 entry_git_aware_label_color(git_status, entry.is_ignored, is_marked);
4686
4687 let is_cut = self
4688 .clipboard
4689 .as_ref()
4690 .is_some_and(|e| e.is_cut() && e.items().contains(&selection));
4691
4692 EntryDetails {
4693 filename,
4694 icon,
4695 path: entry.path.clone(),
4696 depth,
4697 kind: entry.kind,
4698 is_ignored: entry.is_ignored,
4699 is_expanded,
4700 is_selected,
4701 is_marked,
4702 is_editing: false,
4703 is_processing: false,
4704 is_cut,
4705 sticky,
4706 filename_text_color,
4707 diagnostic_severity,
4708 git_status,
4709 is_private: entry.is_private,
4710 worktree_id,
4711 canonical_path: entry.canonical_path.clone(),
4712 }
4713 }
4714
4715 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
4716 if !Self::should_show_scrollbar(cx)
4717 || !(self.show_scrollbar || self.vertical_scrollbar_state.is_dragging())
4718 {
4719 return None;
4720 }
4721 Some(
4722 div()
4723 .occlude()
4724 .id("project-panel-vertical-scroll")
4725 .on_mouse_move(cx.listener(|_, _, _, cx| {
4726 cx.notify();
4727 cx.stop_propagation()
4728 }))
4729 .on_hover(|_, _, cx| {
4730 cx.stop_propagation();
4731 })
4732 .on_any_mouse_down(|_, _, cx| {
4733 cx.stop_propagation();
4734 })
4735 .on_mouse_up(
4736 MouseButton::Left,
4737 cx.listener(|this, _, window, cx| {
4738 if !this.vertical_scrollbar_state.is_dragging()
4739 && !this.focus_handle.contains_focused(window, cx)
4740 {
4741 this.hide_scrollbar(window, cx);
4742 cx.notify();
4743 }
4744
4745 cx.stop_propagation();
4746 }),
4747 )
4748 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4749 cx.notify();
4750 }))
4751 .h_full()
4752 .absolute()
4753 .right_1()
4754 .top_1()
4755 .bottom_1()
4756 .w(px(12.))
4757 .cursor_default()
4758 .children(Scrollbar::vertical(
4759 // percentage as f32..end_offset as f32,
4760 self.vertical_scrollbar_state.clone(),
4761 )),
4762 )
4763 }
4764
4765 fn render_horizontal_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
4766 if !Self::should_show_scrollbar(cx)
4767 || !(self.show_scrollbar || self.horizontal_scrollbar_state.is_dragging())
4768 {
4769 return None;
4770 }
4771 Scrollbar::horizontal(self.horizontal_scrollbar_state.clone()).map(|scrollbar| {
4772 div()
4773 .occlude()
4774 .id("project-panel-horizontal-scroll")
4775 .on_mouse_move(cx.listener(|_, _, _, cx| {
4776 cx.notify();
4777 cx.stop_propagation()
4778 }))
4779 .on_hover(|_, _, cx| {
4780 cx.stop_propagation();
4781 })
4782 .on_any_mouse_down(|_, _, cx| {
4783 cx.stop_propagation();
4784 })
4785 .on_mouse_up(
4786 MouseButton::Left,
4787 cx.listener(|this, _, window, cx| {
4788 if !this.horizontal_scrollbar_state.is_dragging()
4789 && !this.focus_handle.contains_focused(window, cx)
4790 {
4791 this.hide_scrollbar(window, cx);
4792 cx.notify();
4793 }
4794
4795 cx.stop_propagation();
4796 }),
4797 )
4798 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4799 cx.notify();
4800 }))
4801 .w_full()
4802 .absolute()
4803 .right_1()
4804 .left_1()
4805 .bottom_1()
4806 .h(px(12.))
4807 .cursor_default()
4808 .child(scrollbar)
4809 })
4810 }
4811
4812 fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
4813 let mut dispatch_context = KeyContext::new_with_defaults();
4814 dispatch_context.add("ProjectPanel");
4815 dispatch_context.add("menu");
4816
4817 let identifier = if self.filename_editor.focus_handle(cx).is_focused(window) {
4818 "editing"
4819 } else {
4820 "not_editing"
4821 };
4822
4823 dispatch_context.add(identifier);
4824 dispatch_context
4825 }
4826
4827 fn should_show_scrollbar(cx: &App) -> bool {
4828 let show = ProjectPanelSettings::get_global(cx)
4829 .scrollbar
4830 .show
4831 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show);
4832 match show {
4833 ShowScrollbar::Auto => true,
4834 ShowScrollbar::System => true,
4835 ShowScrollbar::Always => true,
4836 ShowScrollbar::Never => false,
4837 }
4838 }
4839
4840 fn should_autohide_scrollbar(cx: &App) -> bool {
4841 let show = ProjectPanelSettings::get_global(cx)
4842 .scrollbar
4843 .show
4844 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show);
4845 match show {
4846 ShowScrollbar::Auto => true,
4847 ShowScrollbar::System => cx
4848 .try_global::<ScrollbarAutoHide>()
4849 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
4850 ShowScrollbar::Always => false,
4851 ShowScrollbar::Never => true,
4852 }
4853 }
4854
4855 fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4856 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
4857 if !Self::should_autohide_scrollbar(cx) {
4858 return;
4859 }
4860 self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |panel, cx| {
4861 cx.background_executor()
4862 .timer(SCROLLBAR_SHOW_INTERVAL)
4863 .await;
4864 panel
4865 .update(cx, |panel, cx| {
4866 panel.show_scrollbar = false;
4867 cx.notify();
4868 })
4869 .log_err();
4870 }))
4871 }
4872
4873 fn reveal_entry(
4874 &mut self,
4875 project: Entity<Project>,
4876 entry_id: ProjectEntryId,
4877 skip_ignored: bool,
4878 cx: &mut Context<Self>,
4879 ) -> Result<()> {
4880 let worktree = project
4881 .read(cx)
4882 .worktree_for_entry(entry_id, cx)
4883 .context("can't reveal a non-existent entry in the project panel")?;
4884 let worktree = worktree.read(cx);
4885 if skip_ignored
4886 && worktree
4887 .entry_for_id(entry_id)
4888 .is_none_or(|entry| entry.is_ignored && !entry.is_always_included)
4889 {
4890 anyhow::bail!("can't reveal an ignored entry in the project panel");
4891 }
4892 let is_active_item_file_diff_view = self
4893 .workspace
4894 .upgrade()
4895 .and_then(|ws| ws.read(cx).active_item(cx))
4896 .map(|item| item.act_as_type(TypeId::of::<FileDiffView>(), cx).is_some())
4897 .unwrap_or(false);
4898 if is_active_item_file_diff_view {
4899 return Ok(());
4900 }
4901
4902 let worktree_id = worktree.id();
4903 self.expand_entry(worktree_id, entry_id, cx);
4904 self.update_visible_entries(Some((worktree_id, entry_id)), cx);
4905 self.marked_entries.clear();
4906 self.marked_entries.push(SelectedEntry {
4907 worktree_id,
4908 entry_id,
4909 });
4910 self.autoscroll(cx);
4911 cx.notify();
4912 Ok(())
4913 }
4914
4915 fn find_active_indent_guide(
4916 &self,
4917 indent_guides: &[IndentGuideLayout],
4918 cx: &App,
4919 ) -> Option<usize> {
4920 let (worktree, entry) = self.selected_entry(cx)?;
4921
4922 // Find the parent entry of the indent guide, this will either be the
4923 // expanded folder we have selected, or the parent of the currently
4924 // selected file/collapsed directory
4925 let mut entry = entry;
4926 loop {
4927 let is_expanded_dir = entry.is_dir()
4928 && self
4929 .expanded_dir_ids
4930 .get(&worktree.id())
4931 .map(|ids| ids.binary_search(&entry.id).is_ok())
4932 .unwrap_or(false);
4933 if is_expanded_dir {
4934 break;
4935 }
4936 entry = worktree.entry_for_path(&entry.path.parent()?)?;
4937 }
4938
4939 let (active_indent_range, depth) = {
4940 let (worktree_ix, child_offset, ix) = self.index_for_entry(entry.id, worktree.id())?;
4941 let child_paths = &self.visible_entries[worktree_ix].entries;
4942 let mut child_count = 0;
4943 let depth = entry.path.ancestors().count();
4944 while let Some(entry) = child_paths.get(child_offset + child_count + 1) {
4945 if entry.path.ancestors().count() <= depth {
4946 break;
4947 }
4948 child_count += 1;
4949 }
4950
4951 let start = ix + 1;
4952 let end = start + child_count;
4953
4954 let visible_worktree = &self.visible_entries[worktree_ix];
4955 let visible_worktree_entries = visible_worktree.index.get_or_init(|| {
4956 visible_worktree
4957 .entries
4958 .iter()
4959 .map(|e| (e.path.clone()))
4960 .collect()
4961 });
4962
4963 // Calculate the actual depth of the entry, taking into account that directories can be auto-folded.
4964 let (depth, _) = Self::calculate_depth_and_difference(entry, visible_worktree_entries);
4965 (start..end, depth)
4966 };
4967
4968 let candidates = indent_guides
4969 .iter()
4970 .enumerate()
4971 .filter(|(_, indent_guide)| indent_guide.offset.x == depth);
4972
4973 for (i, indent) in candidates {
4974 // Find matches that are either an exact match, partially on screen, or inside the enclosing indent
4975 if active_indent_range.start <= indent.offset.y + indent.length
4976 && indent.offset.y <= active_indent_range.end
4977 {
4978 return Some(i);
4979 }
4980 }
4981 None
4982 }
4983
4984 fn render_sticky_entries(
4985 &self,
4986 child: StickyProjectPanelCandidate,
4987 window: &mut Window,
4988 cx: &mut Context<Self>,
4989 ) -> SmallVec<[AnyElement; 8]> {
4990 let project = self.project.read(cx);
4991
4992 let Some((worktree_id, entry_ref)) = self.entry_at_index(child.index) else {
4993 return SmallVec::new();
4994 };
4995
4996 let Some(visible) = self
4997 .visible_entries
4998 .iter()
4999 .find(|worktree| worktree.worktree_id == worktree_id)
5000 else {
5001 return SmallVec::new();
5002 };
5003
5004 let Some(worktree) = project.worktree_for_id(worktree_id, cx) else {
5005 return SmallVec::new();
5006 };
5007 let worktree = worktree.read(cx).snapshot();
5008
5009 let paths = visible
5010 .index
5011 .get_or_init(|| visible.entries.iter().map(|e| e.path.clone()).collect());
5012
5013 let mut sticky_parents = Vec::new();
5014 let mut current_path = entry_ref.path.clone();
5015
5016 'outer: loop {
5017 if let Some(parent_path) = current_path.parent() {
5018 for ancestor_path in parent_path.ancestors() {
5019 if paths.contains(ancestor_path)
5020 && let Some(parent_entry) = worktree.entry_for_path(ancestor_path)
5021 {
5022 sticky_parents.push(parent_entry.clone());
5023 current_path = parent_entry.path.clone();
5024 continue 'outer;
5025 }
5026 }
5027 }
5028 break 'outer;
5029 }
5030
5031 if sticky_parents.is_empty() {
5032 return SmallVec::new();
5033 }
5034
5035 sticky_parents.reverse();
5036
5037 let git_status_enabled = ProjectPanelSettings::get_global(cx).git_status;
5038 let root_name = OsStr::new(worktree.root_name());
5039
5040 let git_summaries_by_id = if git_status_enabled {
5041 visible
5042 .entries
5043 .iter()
5044 .map(|e| (e.id, e.git_summary))
5045 .collect::<HashMap<_, _>>()
5046 } else {
5047 Default::default()
5048 };
5049
5050 // already checked if non empty above
5051 let last_item_index = sticky_parents.len() - 1;
5052 sticky_parents
5053 .iter()
5054 .enumerate()
5055 .map(|(index, entry)| {
5056 let git_status = git_summaries_by_id
5057 .get(&entry.id)
5058 .copied()
5059 .unwrap_or_default();
5060 let sticky_details = Some(StickyDetails {
5061 sticky_index: index,
5062 });
5063 let details = self.details_for_entry(
5064 entry,
5065 worktree_id,
5066 root_name,
5067 paths,
5068 git_status,
5069 sticky_details,
5070 window,
5071 cx,
5072 );
5073 self.render_entry(entry.id, details, window, cx)
5074 .when(index == last_item_index, |this| {
5075 let shadow_color_top = hsla(0.0, 0.0, 0.0, 0.1);
5076 let shadow_color_bottom = hsla(0.0, 0.0, 0.0, 0.);
5077 let sticky_shadow = div()
5078 .absolute()
5079 .left_0()
5080 .bottom_neg_1p5()
5081 .h_1p5()
5082 .w_full()
5083 .bg(linear_gradient(
5084 0.,
5085 linear_color_stop(shadow_color_top, 1.),
5086 linear_color_stop(shadow_color_bottom, 0.),
5087 ));
5088 this.child(sticky_shadow)
5089 })
5090 .into_any()
5091 })
5092 .collect()
5093 }
5094}
5095
5096#[derive(Clone)]
5097struct StickyProjectPanelCandidate {
5098 index: usize,
5099 depth: usize,
5100}
5101
5102impl StickyCandidate for StickyProjectPanelCandidate {
5103 fn depth(&self) -> usize {
5104 self.depth
5105 }
5106}
5107
5108fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -> usize {
5109 const ICON_SIZE_FACTOR: usize = 2;
5110 let mut item_width = depth * ICON_SIZE_FACTOR + item_text_chars;
5111 if is_symlink {
5112 item_width += ICON_SIZE_FACTOR;
5113 }
5114 item_width
5115}
5116
5117impl Render for ProjectPanel {
5118 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5119 let has_worktree = !self.visible_entries.is_empty();
5120 let project = self.project.read(cx);
5121 let indent_size = ProjectPanelSettings::get_global(cx).indent_size;
5122 let show_indent_guides =
5123 ProjectPanelSettings::get_global(cx).indent_guides.show == ShowIndentGuides::Always;
5124 let show_sticky_entries = {
5125 if ProjectPanelSettings::get_global(cx).sticky_scroll {
5126 let is_scrollable = self.scroll_handle.is_scrollable();
5127 let is_scrolled = self.scroll_handle.offset().y < px(0.);
5128 is_scrollable && is_scrolled
5129 } else {
5130 false
5131 }
5132 };
5133
5134 let is_local = project.is_local();
5135
5136 if has_worktree {
5137 let item_count = self
5138 .visible_entries
5139 .iter()
5140 .map(|worktree| worktree.entries.len())
5141 .sum();
5142
5143 fn handle_drag_move<T: 'static>(
5144 this: &mut ProjectPanel,
5145 e: &DragMoveEvent<T>,
5146 window: &mut Window,
5147 cx: &mut Context<ProjectPanel>,
5148 ) {
5149 if let Some(previous_position) = this.previous_drag_position {
5150 // Refresh cursor only when an actual drag happens,
5151 // because modifiers are not updated when the cursor is not moved.
5152 if e.event.position != previous_position {
5153 this.refresh_drag_cursor_style(&e.event.modifiers, window, cx);
5154 }
5155 }
5156 this.previous_drag_position = Some(e.event.position);
5157
5158 if !e.bounds.contains(&e.event.position) {
5159 this.drag_target_entry = None;
5160 return;
5161 }
5162 this.hover_scroll_task.take();
5163 let panel_height = e.bounds.size.height;
5164 if panel_height <= px(0.) {
5165 return;
5166 }
5167
5168 let event_offset = e.event.position.y - e.bounds.origin.y;
5169 // How far along in the project panel is our cursor? (0. is the top of a list, 1. is the bottom)
5170 let hovered_region_offset = event_offset / panel_height;
5171
5172 // We want the scrolling to be a bit faster when the cursor is closer to the edge of a list.
5173 // These pixels offsets were picked arbitrarily.
5174 let vertical_scroll_offset = if hovered_region_offset <= 0.05 {
5175 8.
5176 } else if hovered_region_offset <= 0.15 {
5177 5.
5178 } else if hovered_region_offset >= 0.95 {
5179 -8.
5180 } else if hovered_region_offset >= 0.85 {
5181 -5.
5182 } else {
5183 return;
5184 };
5185 let adjustment = point(px(0.), px(vertical_scroll_offset));
5186 this.hover_scroll_task = Some(cx.spawn_in(window, async move |this, cx| {
5187 loop {
5188 let should_stop_scrolling = this
5189 .update(cx, |this, cx| {
5190 this.hover_scroll_task.as_ref()?;
5191 let handle = this.scroll_handle.0.borrow_mut();
5192 let offset = handle.base_handle.offset();
5193
5194 handle.base_handle.set_offset(offset + adjustment);
5195 cx.notify();
5196 Some(())
5197 })
5198 .ok()
5199 .flatten()
5200 .is_some();
5201 if should_stop_scrolling {
5202 return;
5203 }
5204 cx.background_executor()
5205 .timer(Duration::from_millis(16))
5206 .await;
5207 }
5208 }));
5209 }
5210 h_flex()
5211 .id("project-panel")
5212 .group("project-panel")
5213 .on_drag_move(cx.listener(handle_drag_move::<ExternalPaths>))
5214 .on_drag_move(cx.listener(handle_drag_move::<DraggedSelection>))
5215 .size_full()
5216 .relative()
5217 .on_modifiers_changed(cx.listener(
5218 |this, event: &ModifiersChangedEvent, window, cx| {
5219 this.refresh_drag_cursor_style(&event.modifiers, window, cx);
5220 },
5221 ))
5222 .on_hover(cx.listener(|this, hovered, window, cx| {
5223 if *hovered {
5224 this.show_scrollbar = true;
5225 this.hide_scrollbar_task.take();
5226 cx.notify();
5227 } else if !this.focus_handle.contains_focused(window, cx) {
5228 this.hide_scrollbar(window, cx);
5229 }
5230 }))
5231 .on_click(cx.listener(|this, event, _, cx| {
5232 if matches!(event, gpui::ClickEvent::Keyboard(_)) {
5233 return;
5234 }
5235 cx.stop_propagation();
5236 this.selection = None;
5237 this.marked_entries.clear();
5238 }))
5239 .key_context(self.dispatch_context(window, cx))
5240 .on_action(cx.listener(Self::select_next))
5241 .on_action(cx.listener(Self::select_previous))
5242 .on_action(cx.listener(Self::select_first))
5243 .on_action(cx.listener(Self::select_last))
5244 .on_action(cx.listener(Self::select_parent))
5245 .on_action(cx.listener(Self::select_next_git_entry))
5246 .on_action(cx.listener(Self::select_prev_git_entry))
5247 .on_action(cx.listener(Self::select_next_diagnostic))
5248 .on_action(cx.listener(Self::select_prev_diagnostic))
5249 .on_action(cx.listener(Self::select_next_directory))
5250 .on_action(cx.listener(Self::select_prev_directory))
5251 .on_action(cx.listener(Self::expand_selected_entry))
5252 .on_action(cx.listener(Self::collapse_selected_entry))
5253 .on_action(cx.listener(Self::collapse_all_entries))
5254 .on_action(cx.listener(Self::open))
5255 .on_action(cx.listener(Self::open_permanent))
5256 .on_action(cx.listener(Self::confirm))
5257 .on_action(cx.listener(Self::cancel))
5258 .on_action(cx.listener(Self::copy_path))
5259 .on_action(cx.listener(Self::copy_relative_path))
5260 .on_action(cx.listener(Self::new_search_in_directory))
5261 .on_action(cx.listener(Self::unfold_directory))
5262 .on_action(cx.listener(Self::fold_directory))
5263 .on_action(cx.listener(Self::remove_from_project))
5264 .on_action(cx.listener(Self::compare_marked_files))
5265 .when(!project.is_read_only(cx), |el| {
5266 el.on_action(cx.listener(Self::new_file))
5267 .on_action(cx.listener(Self::new_directory))
5268 .on_action(cx.listener(Self::rename))
5269 .on_action(cx.listener(Self::delete))
5270 .on_action(cx.listener(Self::trash))
5271 .on_action(cx.listener(Self::cut))
5272 .on_action(cx.listener(Self::copy))
5273 .on_action(cx.listener(Self::paste))
5274 .on_action(cx.listener(Self::duplicate))
5275 .on_click(cx.listener(|this, event: &gpui::ClickEvent, window, cx| {
5276 if event.click_count() > 1
5277 && let Some(entry_id) = this.last_worktree_root_id
5278 {
5279 let project = this.project.read(cx);
5280
5281 let worktree_id = if let Some(worktree) =
5282 project.worktree_for_entry(entry_id, cx)
5283 {
5284 worktree.read(cx).id()
5285 } else {
5286 return;
5287 };
5288
5289 this.selection = Some(SelectedEntry {
5290 worktree_id,
5291 entry_id,
5292 });
5293
5294 this.new_file(&NewFile, window, cx);
5295 }
5296 }))
5297 })
5298 .when(project.is_local(), |el| {
5299 el.on_action(cx.listener(Self::reveal_in_finder))
5300 .on_action(cx.listener(Self::open_system))
5301 .on_action(cx.listener(Self::open_in_terminal))
5302 })
5303 .when(project.is_via_ssh(), |el| {
5304 el.on_action(cx.listener(Self::open_in_terminal))
5305 })
5306 .on_mouse_down(
5307 MouseButton::Right,
5308 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
5309 // When deploying the context menu anywhere below the last project entry,
5310 // act as if the user clicked the root of the last worktree.
5311 if let Some(entry_id) = this.last_worktree_root_id {
5312 this.deploy_context_menu(event.position, entry_id, window, cx);
5313 }
5314 }),
5315 )
5316 .track_focus(&self.focus_handle(cx))
5317 .child(
5318 uniform_list("entries", item_count, {
5319 cx.processor(|this, range: Range<usize>, window, cx| {
5320 let mut items = Vec::with_capacity(range.end - range.start);
5321 this.for_each_visible_entry(
5322 range,
5323 window,
5324 cx,
5325 |id, details, window, cx| {
5326 items.push(this.render_entry(id, details, window, cx));
5327 },
5328 );
5329 items
5330 })
5331 })
5332 .when(show_indent_guides, |list| {
5333 list.with_decoration(
5334 ui::indent_guides(px(indent_size), IndentGuideColors::panel(cx))
5335 .with_compute_indents_fn(cx.entity(), |this, range, window, cx| {
5336 let mut items =
5337 SmallVec::with_capacity(range.end - range.start);
5338 this.iter_visible_entries(
5339 range,
5340 window,
5341 cx,
5342 |entry, _, entries, _, _| {
5343 let (depth, _) = Self::calculate_depth_and_difference(
5344 entry, entries,
5345 );
5346 items.push(depth);
5347 },
5348 );
5349 items
5350 })
5351 .on_click(cx.listener(
5352 |this, active_indent_guide: &IndentGuideLayout, window, cx| {
5353 if window.modifiers().secondary() {
5354 let ix = active_indent_guide.offset.y;
5355 let Some((target_entry, worktree)) = maybe!({
5356 let (worktree_id, entry) =
5357 this.entry_at_index(ix)?;
5358 let worktree = this
5359 .project
5360 .read(cx)
5361 .worktree_for_id(worktree_id, cx)?;
5362 let target_entry = worktree
5363 .read(cx)
5364 .entry_for_path(&entry.path.parent()?)?;
5365 Some((target_entry, worktree))
5366 }) else {
5367 return;
5368 };
5369
5370 this.collapse_entry(target_entry.clone(), worktree, cx);
5371 }
5372 },
5373 ))
5374 .with_render_fn(cx.entity(), move |this, params, _, cx| {
5375 const LEFT_OFFSET: Pixels = px(14.);
5376 const PADDING_Y: Pixels = px(4.);
5377 const HITBOX_OVERDRAW: Pixels = px(3.);
5378
5379 let active_indent_guide_index =
5380 this.find_active_indent_guide(¶ms.indent_guides, cx);
5381
5382 let indent_size = params.indent_size;
5383 let item_height = params.item_height;
5384
5385 params
5386 .indent_guides
5387 .into_iter()
5388 .enumerate()
5389 .map(|(idx, layout)| {
5390 let offset = if layout.continues_offscreen {
5391 px(0.)
5392 } else {
5393 PADDING_Y
5394 };
5395 let bounds = Bounds::new(
5396 point(
5397 layout.offset.x * indent_size + LEFT_OFFSET,
5398 layout.offset.y * item_height + offset,
5399 ),
5400 size(
5401 px(1.),
5402 layout.length * item_height - offset * 2.,
5403 ),
5404 );
5405 ui::RenderedIndentGuide {
5406 bounds,
5407 layout,
5408 is_active: Some(idx) == active_indent_guide_index,
5409 hitbox: Some(Bounds::new(
5410 point(
5411 bounds.origin.x - HITBOX_OVERDRAW,
5412 bounds.origin.y,
5413 ),
5414 size(
5415 bounds.size.width + HITBOX_OVERDRAW * 2.,
5416 bounds.size.height,
5417 ),
5418 )),
5419 }
5420 })
5421 .collect()
5422 }),
5423 )
5424 })
5425 .when(show_sticky_entries, |list| {
5426 let sticky_items = ui::sticky_items(
5427 cx.entity(),
5428 |this, range, window, cx| {
5429 let mut items = SmallVec::with_capacity(range.end - range.start);
5430 this.iter_visible_entries(
5431 range,
5432 window,
5433 cx,
5434 |entry, index, entries, _, _| {
5435 let (depth, _) =
5436 Self::calculate_depth_and_difference(entry, entries);
5437 let candidate =
5438 StickyProjectPanelCandidate { index, depth };
5439 items.push(candidate);
5440 },
5441 );
5442 items
5443 },
5444 |this, marker_entry, window, cx| {
5445 let sticky_entries =
5446 this.render_sticky_entries(marker_entry, window, cx);
5447 this.sticky_items_count = sticky_entries.len();
5448 sticky_entries
5449 },
5450 );
5451 list.with_decoration(if show_indent_guides {
5452 sticky_items.with_decoration(
5453 ui::indent_guides(px(indent_size), IndentGuideColors::panel(cx))
5454 .with_render_fn(cx.entity(), move |_, params, _, _| {
5455 const LEFT_OFFSET: Pixels = px(14.);
5456
5457 let indent_size = params.indent_size;
5458 let item_height = params.item_height;
5459
5460 params
5461 .indent_guides
5462 .into_iter()
5463 .map(|layout| {
5464 let bounds = Bounds::new(
5465 point(
5466 layout.offset.x * indent_size + LEFT_OFFSET,
5467 layout.offset.y * item_height,
5468 ),
5469 size(px(1.), layout.length * item_height),
5470 );
5471 ui::RenderedIndentGuide {
5472 bounds,
5473 layout,
5474 is_active: false,
5475 hitbox: None,
5476 }
5477 })
5478 .collect()
5479 }),
5480 )
5481 } else {
5482 sticky_items
5483 })
5484 })
5485 .size_full()
5486 .with_sizing_behavior(ListSizingBehavior::Infer)
5487 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
5488 .with_width_from_item(self.max_width_item_index)
5489 .track_scroll(self.scroll_handle.clone()),
5490 )
5491 .children(self.render_vertical_scrollbar(cx))
5492 .when_some(self.render_horizontal_scrollbar(cx), |this, scrollbar| {
5493 this.pb_4().child(scrollbar)
5494 })
5495 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5496 deferred(
5497 anchored()
5498 .position(*position)
5499 .anchor(gpui::Corner::TopLeft)
5500 .child(menu.clone()),
5501 )
5502 .with_priority(3)
5503 }))
5504 } else {
5505 let focus_handle = self.focus_handle(cx);
5506
5507 v_flex()
5508 .id("empty-project_panel")
5509 .p_4()
5510 .size_full()
5511 .items_center()
5512 .justify_center()
5513 .gap_1()
5514 .track_focus(&self.focus_handle(cx))
5515 .child(
5516 Button::new("open_project", "Open Project")
5517 .full_width()
5518 .key_binding(KeyBinding::for_action_in(
5519 &workspace::Open,
5520 &focus_handle,
5521 window,
5522 cx,
5523 ))
5524 .on_click(cx.listener(|this, _, window, cx| {
5525 this.workspace
5526 .update(cx, |_, cx| {
5527 window.dispatch_action(workspace::Open.boxed_clone(), cx);
5528 })
5529 .log_err();
5530 })),
5531 )
5532 .child(
5533 h_flex()
5534 .w_1_2()
5535 .gap_2()
5536 .child(Divider::horizontal())
5537 .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
5538 .child(Divider::horizontal()),
5539 )
5540 .child(
5541 Button::new("clone_repo", "Clone Repository")
5542 .full_width()
5543 .on_click(cx.listener(|this, _, window, cx| {
5544 this.workspace
5545 .update(cx, |_, cx| {
5546 window.dispatch_action(git::Clone.boxed_clone(), cx);
5547 })
5548 .log_err();
5549 })),
5550 )
5551 .when(is_local, |div| {
5552 div.drag_over::<ExternalPaths>(|style, _, _, cx| {
5553 style.bg(cx.theme().colors().drop_target_background)
5554 })
5555 .on_drop(cx.listener(
5556 move |this, external_paths: &ExternalPaths, window, cx| {
5557 this.drag_target_entry = None;
5558 this.hover_scroll_task.take();
5559 if let Some(task) = this
5560 .workspace
5561 .update(cx, |workspace, cx| {
5562 workspace.open_workspace_for_paths(
5563 true,
5564 external_paths.paths().to_owned(),
5565 window,
5566 cx,
5567 )
5568 })
5569 .log_err()
5570 {
5571 task.detach_and_log_err(cx);
5572 }
5573 cx.stop_propagation();
5574 },
5575 ))
5576 })
5577 }
5578 }
5579}
5580
5581impl Render for DraggedProjectEntryView {
5582 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5583 let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
5584 h_flex()
5585 .font(ui_font)
5586 .pl(self.click_offset.x + px(12.))
5587 .pt(self.click_offset.y + px(12.))
5588 .child(
5589 div()
5590 .flex()
5591 .gap_1()
5592 .items_center()
5593 .py_1()
5594 .px_2()
5595 .rounded_lg()
5596 .bg(cx.theme().colors().background)
5597 .map(|this| {
5598 if self.selections.len() > 1 && self.selections.contains(&self.selection) {
5599 this.child(Label::new(format!("{} entries", self.selections.len())))
5600 } else {
5601 this.child(if let Some(icon) = &self.details.icon {
5602 div().child(Icon::from_path(icon.clone()))
5603 } else {
5604 div()
5605 })
5606 .child(Label::new(self.details.filename.clone()))
5607 }
5608 }),
5609 )
5610 }
5611}
5612
5613impl EventEmitter<Event> for ProjectPanel {}
5614
5615impl EventEmitter<PanelEvent> for ProjectPanel {}
5616
5617impl Panel for ProjectPanel {
5618 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5619 match ProjectPanelSettings::get_global(cx).dock {
5620 ProjectPanelDockPosition::Left => DockPosition::Left,
5621 ProjectPanelDockPosition::Right => DockPosition::Right,
5622 }
5623 }
5624
5625 fn position_is_valid(&self, position: DockPosition) -> bool {
5626 matches!(position, DockPosition::Left | DockPosition::Right)
5627 }
5628
5629 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5630 settings::update_settings_file::<ProjectPanelSettings>(
5631 self.fs.clone(),
5632 cx,
5633 move |settings, _| {
5634 let dock = match position {
5635 DockPosition::Left | DockPosition::Bottom => ProjectPanelDockPosition::Left,
5636 DockPosition::Right => ProjectPanelDockPosition::Right,
5637 };
5638 settings.dock = Some(dock);
5639 },
5640 );
5641 }
5642
5643 fn size(&self, _: &Window, cx: &App) -> Pixels {
5644 self.width
5645 .unwrap_or_else(|| ProjectPanelSettings::get_global(cx).default_width)
5646 }
5647
5648 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
5649 self.width = size;
5650 cx.notify();
5651 cx.defer_in(window, |this, _, cx| {
5652 this.serialize(cx);
5653 });
5654 }
5655
5656 fn icon(&self, _: &Window, cx: &App) -> Option<IconName> {
5657 ProjectPanelSettings::get_global(cx)
5658 .button
5659 .then_some(IconName::FileTree)
5660 }
5661
5662 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5663 Some("Project Panel")
5664 }
5665
5666 fn toggle_action(&self) -> Box<dyn Action> {
5667 Box::new(ToggleFocus)
5668 }
5669
5670 fn persistent_name() -> &'static str {
5671 "Project Panel"
5672 }
5673
5674 fn starts_open(&self, _: &Window, cx: &App) -> bool {
5675 if !ProjectPanelSettings::get_global(cx).starts_open {
5676 return false;
5677 }
5678
5679 let project = &self.project.read(cx);
5680 project.visible_worktrees(cx).any(|tree| {
5681 tree.read(cx)
5682 .root_entry()
5683 .is_some_and(|entry| entry.is_dir())
5684 })
5685 }
5686
5687 fn activation_priority(&self) -> u32 {
5688 0
5689 }
5690}
5691
5692impl Focusable for ProjectPanel {
5693 fn focus_handle(&self, _cx: &App) -> FocusHandle {
5694 self.focus_handle.clone()
5695 }
5696}
5697
5698impl ClipboardEntry {
5699 fn is_cut(&self) -> bool {
5700 matches!(self, Self::Cut { .. })
5701 }
5702
5703 fn items(&self) -> &BTreeSet<SelectedEntry> {
5704 match self {
5705 ClipboardEntry::Copied(entries) | ClipboardEntry::Cut(entries) => entries,
5706 }
5707 }
5708
5709 fn into_copy_entry(self) -> Self {
5710 match self {
5711 ClipboardEntry::Copied(_) => self,
5712 ClipboardEntry::Cut(entries) => ClipboardEntry::Copied(entries),
5713 }
5714 }
5715}
5716
5717#[cfg(test)]
5718mod project_panel_tests;