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