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