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