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