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