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