diff --git a/crates/ide-index/src/filter.rs b/crates/ide-index/src/filter.rs index 79019e0d0..76d0bb556 100644 --- a/crates/ide-index/src/filter.rs +++ b/crates/ide-index/src/filter.rs @@ -241,6 +241,15 @@ impl PathFilter { (!rel.is_empty()).then_some(rel) } + /// Recent Files' stored form: the store key for a project file, the absolute + /// path for one outside it (a scratch file). Loading joins it to the root, + /// which leaves an absolute path as it is. + pub(crate) fn recent_key(&self, path: &Path) -> Option { + self.store_key(path).or_else(|| { + (path.is_absolute() && !path.starts_with(&self.root)).then(|| path.to_str().map(str::to_owned))? + }) + } + fn excluded_rel(&self, rel: &str) -> bool { self.excludes.is_match(rel) } diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index c60531436..4459c9f37 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -400,15 +400,10 @@ impl ProjectIndex { /// Boost for "recent files" ranking. /// Records a recently opened file; a virtual document's URI (library - /// class) is kept verbatim, like IDEA lists library classes in Recent Files. + /// class) is kept verbatim, and a file outside the project (a scratch file) + /// by its absolute path. pub fn mark_recent(&self, path: &Path) { - let path = match path.to_str() { - Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(), - _ => match self.normalize(path) { - Some(p) => p, - None => return, - }, - }; + let Some(path) = self.recent_key(path) else { return }; { let mut r = self.shared.recent.lock(); r.retain(|p| p != &path); @@ -420,13 +415,7 @@ impl ProjectIndex { /// Drops a file from Recent Files (Delete in the ⌘E popup). pub fn remove_recent(&self, path: &Path) { - let path = match path.to_str() { - Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(), - _ => match self.normalize(path) { - Some(p) => p, - None => return, - }, - }; + let Some(path) = self.recent_key(path) else { return }; { let mut r = self.shared.recent.lock(); let before = r.len(); @@ -473,6 +462,20 @@ impl ProjectIndex { &self.root } + /// How Recent Files stores `path`: a virtual URI verbatim, a project file normalized, + /// and an existing file outside the root canonicalized. Excluded files under the root + /// are left out. + fn recent_key(&self, path: &Path) -> Option { + if path.to_str().is_some_and(ide_core::text::is_virtual_uri) { + return Some(path.to_owned()); + } + if let Some(p) = self.normalize(path) { + return Some(p); + } + let p = dunce::canonicalize(path).ok().filter(|p| p.is_file())?; + (!p.starts_with(&self.root)).then_some(p) + } + /// Absolute path inside the root (or a content root), or `None` for paths outside the project. fn normalize(&self, path: &Path) -> Option { let filter = self.shared.filter(); diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index abd658439..72f9bb9d6 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -251,6 +251,26 @@ fn recent_files_skip_deleted_files_but_keep_virtual_documents() { assert_eq!(idx.recent_files(), vec![virt]); } +#[test] +fn recent_files_keep_files_outside_the_project() { + let fx = sample(); + let scratches = tempfile::tempdir().unwrap(); + let scratch = dunce::canonicalize(scratches.path()).unwrap().join("generated-requests.http"); + std::fs::write(&scratch, "GET http://localhost\n").unwrap(); + let app = fx.root.join("web/app.py"); + { + let idx = fx.open(); + idx.mark_recent(&app); + idx.mark_recent(&scratch); + assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()]); + assert!(idx.wait_idle(WAIT)); + } + let idx = fx.open(); + assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()], "persisted by absolute path"); + idx.remove_recent(&scratch); + assert_eq!(idx.recent_files(), vec![app]); +} + #[test] fn persistence_skips_unchanged_files_on_reopen() { let fx = sample(); diff --git a/crates/ide-index/src/worker.rs b/crates/ide-index/src/worker.rs index e67cf8a93..accd68efe 100644 --- a/crates/ide-index/src/worker.rs +++ b/crates/ide-index/src/worker.rs @@ -591,7 +591,7 @@ impl Shared { let update_elapsed = update_started.elapsed(); let snapshot_started = Instant::now(); if let Some(store) = &self.store { - let recent: Vec = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect(); + let recent: Vec = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect(); let d = self.data.read(); let snapshot_started = Instant::now(); if let Err(e) = store.save_snapshot(&d, &filter, guard) { @@ -976,7 +976,7 @@ impl Shared { } } if save_recent && let Some(store) = &self.store { - let rels: Vec = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect(); + let rels: Vec = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect(); if let Err(e) = store.save_recent(&rels) { tracing::warn!("index cache: saving recent files failed: {e}"); } diff --git a/src/features/search/__tests__/recent.test.ts b/src/features/search/__tests__/recent.test.ts index d3163f84b..be41803a4 100644 --- a/src/features/search/__tests__/recent.test.ts +++ b/src/features/search/__tests__/recent.test.ts @@ -132,6 +132,23 @@ describe("recent files switcher", () => { ).toEqual(["README.md"]); }); + it("shows a scratch file under its root's label", () => { + const labelled = [{ path: "/data/scratches", label: "Scratches" }]; + const items = filterRecentFiles( + ["/data/scratches/api/generated-requests.http", "/p/src/Main.kt", "/elsewhere/a.txt"], + "", + { + root: "/p", + labelled, + }, + ); + expect(items.map((f) => [f.rel, f.dir])).toEqual([ + ["Scratches/api/generated-requests.http", "Scratches/api"], + ["src/Main.kt", "src"], + ["/elsewhere/a.txt", "/elsewhere"], + ]); + }); + it("preselects the previous file when the current one is first", () => { const items = filterRecentFiles(paths, "", { root: "/p" }); expect(initialFileIndex(items, "/p/src/Main.kt", "")).toBe(1); diff --git a/src/features/search/recent/RecentPopups.tsx b/src/features/search/recent/RecentPopups.tsx index 5a8094648..31a83028c 100644 --- a/src/features/search/recent/RecentPopups.tsx +++ b/src/features/search/recent/RecentPopups.tsx @@ -25,6 +25,7 @@ import { maybeEditorService, toolWindowService, useContributions, + useProjectViewRoots, useFileDecoration, type OpenEditorTab, type ToolWindowContribution, @@ -91,6 +92,14 @@ function RecentFilesDialog() { const step = useRecentPopup((s) => s.step); const edited = useTracking((s) => s.edited); const root = useProject((s) => s.project?.root ?? null); + const viewRoots = useProjectViewRoots((s) => s.roots); + const labelled = useMemo( + () => + [...viewRoots.values()].flatMap((r) => + r.scope === "scratches" && r.path ? [{ path: r.path, label: r.label }] : [], + ), + [viewRoots], + ); const toolWindows = useContributions((s) => s.toolWindows); const [paths, setPaths] = useState(null); // Switcher: the open editor tabs (files and others), when the editor service lists them. @@ -135,13 +144,13 @@ function RecentFilesDialog() { const files = useMemo( () => tabs - ? switcherItems(paths ?? [], tabs, query, root).filter((f) => !removed.has(f.path)) + ? switcherItems(paths ?? [], tabs, query, root, labelled).filter((f) => !removed.has(f.path)) : filterRecentFiles( (paths ?? []).filter((p) => !removed.has(p)), query, - { root, edited, editedOnly }, + { root, labelled, edited, editedOnly }, ), - [paths, tabs, removed, query, root, edited, editedOnly], + [paths, tabs, removed, query, root, labelled, edited, editedOnly], ); const fileRows = useMemo(() => files.map((f) => ({ ...f, key: f.path })), [files]); const tools = useMemo(() => switcherToolWindows(toolWindows.values(), !!root, query), [toolWindows, root, query]); diff --git a/src/features/search/recent/model.ts b/src/features/search/recent/model.ts index a07208baf..e83abcdf0 100644 --- a/src/features/search/recent/model.ts +++ b/src/features/search/recent/model.ts @@ -18,10 +18,27 @@ export interface RecentFileItem { editor?: { input: EditorInput; icon: string }; } +/** A folder outside the project shown by its label (the Scratches root): `Scratches/requests.http`. */ +export interface LabelledRoot { + path: string; + label: string; +} + +function displayPath(path: string, root: string | null, labelled: readonly LabelledRoot[] = []): string { + if (root && path.startsWith(root + "/")) return path.slice(root.length + 1); + const outside = labelled.find((r) => path.startsWith(r.path + "/")); + return outside ? `${outside.label}/${path.slice(outside.path.length + 1)}` : path; +} + export function filterRecentFiles( paths: readonly string[], query: string, - opts: { root: string | null; edited?: ReadonlySet; editedOnly?: boolean }, + opts: { + root: string | null; + labelled?: readonly LabelledRoot[]; + edited?: ReadonlySet; + editedOnly?: boolean; + }, ): RecentFileItem[] { const out: RecentFileItem[] = []; const seen = new Set(); @@ -29,7 +46,7 @@ export function filterRecentFiles( if (seen.has(path)) continue; seen.add(path); if (opts.editedOnly && !opts.edited?.has(path)) continue; - const rel = opts.root && path.startsWith(opts.root + "/") ? path.slice(opts.root.length + 1) : path; + const rel = displayPath(path, opts.root, opts.labelled); const name = basename(rel); let indices: number[] = []; if (query.trim()) { @@ -70,6 +87,7 @@ export function switcherItems( tabs: readonly OpenEditorTab[], query: string, root: string | null, + labelled: readonly LabelledRoot[] = [], ): RecentFileItem[] { const fileTabs = new Map(tabs.filter(isFileTab).map((t) => [t.input.path!, t])); const ordered = [ @@ -83,7 +101,7 @@ export function switcherItems( const out: RecentFileItem[] = []; for (const t of ordered) { if (isFileTab(t)) { - out.push(...filterRecentFiles([t.input.path!], query, { root })); + out.push(...filterRecentFiles([t.input.path!], query, { root, labelled })); continue; } let indices: number[] = [];