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