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