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