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