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