From e3808fc7c2a02578626ebf200e012fbca46d1937 Mon Sep 17 00:00:00 2001 From: Muu Date: Wed, 11 Nov 2026 01:01:09 +0800 Subject: [PATCH] feat(project): resolve navigation into attached dependency projects (#2448) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings › Project Structure › Dependencies lists other projects this one depends on (and, in a workspace, the roots each member depends on). Dependency projects join the content roots, so the index, Project view and run see them, and navigation resolves across them: nav_resolve_module maps an import path to a file in the file's navigation roots, and nav_index_definitions answers bare-name lookups filtered to those roots inside the index (so own-root matches can't evict dependency matches). navigation_roots is memoized for 1 s, and hand-written member_dependencies keys with the other path separator match on Windows. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- crates/ide-core/src/settings.rs | 5 + crates/ide-host/src/ops/nav.rs | 64 ++- crates/ide-host/src/project.rs | 107 ++++- crates/ide-index/src/lib.rs | 13 + crates/ide-index/src/matching.rs | 15 + crates/ide-index/src/tests.rs | 21 + e2e/settings.spec.ts | 4 +- scripts/dev-session.ts | 3 +- src-tauri/src/commands/mod.rs | 2 + src-tauri/src/commands/nav.rs | 26 ++ src/bindings.ts | 17 + src/editor/lsp/navigation.ts | 164 +++++++- src/editor/lsp/syntaxFallback.test.ts | 138 +++++++ src/editor/lsp/syntaxFallback.ts | 15 + src/features/project-tree/index.ts | 4 +- src/features/run/contextRun.ts | 4 +- .../settings/__tests__/dialog.test.tsx | 13 +- .../__tests__/projectDependencies.test.ts | 47 +++ .../languages/ProjectStructurePage.tsx | 366 +++++++++++------- src/features/settings/model/staging.ts | 10 +- src/features/settings/pages/languages.tsx | 1 + src/platform/languageSettings.ts | 22 ++ src/platform/locales/text/en.json | 25 +- src/platform/locales/text/zh.json | 25 +- 24 files changed, 935 insertions(+), 176 deletions(-) create mode 100644 src/features/settings/__tests__/projectDependencies.test.ts diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index bea1a1f2a..38716097d 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1273,6 +1273,11 @@ pub struct ProjectStructureSettings { pub unmarked: Vec, /// Content roots besides the project folder (absolute paths), shown and searched with it. pub content_roots: Vec, + /// Other projects (absolute paths) this project depends on; indexed and navigable like content roots. + pub dependencies: Vec, + /// Per-workspace-member dependencies: member root (IPC path) → the roots it depends on. + /// A member not listed here (or with an empty list) navigates only into itself. + pub member_dependencies: BTreeMap>, /// "Exclude files": `;`-separated name patterns (`*.log;tmp*`) excluded at any depth. pub exclude_files: String, /// Project compiler output directory (relative to project root or absolute; empty = default). diff --git a/crates/ide-host/src/ops/nav.rs b/crates/ide-host/src/ops/nav.rs index 2621446fd..c8ead1c7b 100644 --- a/crates/ide-host/src/ops/nav.rs +++ b/crates/ide-host/src/ops/nav.rs @@ -8,7 +8,7 @@ use ide_language::{FileReference, WebReference}; use ide_workspace::file_refs::{self, PathCompletion}; use serde::{Deserialize, Serialize}; use specta::Type; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// A web reference no language server resolves and where it points: `class="card"` → /// `.card` selectors, `id` → `#id` selectors, `href="#top"` → the element, `var(--x)` → @@ -112,6 +112,62 @@ pub async fn web_goto(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeRes .await } +/// The file a Python import path names: `a.b.c` is `a/b/c.py(i)` or `a/b/c/__init__.py(i)` +/// in the project or one of its content roots (an attached dependency project included); +/// `.x` names it relative to `from`'s directory. Neither the language server (it analyses a +/// single root) nor the definition index resolves a package segment, so ⌘B on the `a.b` of +/// `from a.b import x` needs this. +pub async fn nav_resolve_module(host: &Host, window: &str, name: String, from: IpcPath) -> IdeResult> { + let project = host.project(window)?; + blocking(move || { + let dots = name.len() - name.trim_start_matches('.').len(); + let parts: Vec<&str> = name.split('.').filter(|s| !s.is_empty()).collect(); + if parts.is_empty() { + return Ok(None); + } + let rel = parts.iter().collect::(); + let bases: Vec = if dots > 0 { + let dir = PathBuf::from(from); + let dir = dir.parent().map(Path::to_path_buf).unwrap_or(dir); + let base = (0..dots.saturating_sub(1)).fold(dir, |p, _| p.parent().map(Path::to_path_buf).unwrap_or(p)); + vec![base] + } else { + crate::project::navigation_roots(&project, &from) + }; + for base in bases { + let dir = base.join(&rel); + for candidate in + [dir.with_extension("py"), dir.with_extension("pyi"), dir.join("__init__.py"), dir.join("__init__.pyi")] + { + if candidate.is_file() { + return Ok(Some(IpcPath::from(candidate))); + } + } + } + Ok(None) + }) + .await +} + +/// Index definitions named `name` within the roots `from` may navigate into (its own root +/// plus its configured dependencies — see `navigation_roots`): the cross-root answer when +/// the language server cannot resolve an import into an attached dependency project. +pub async fn nav_index_definitions( + host: &Host, + window: &str, + name: String, + from: IpcPath, +) -> IdeResult> { + let project = host.project(window)?; + blocking(move || { + let roots = crate::project::navigation_roots(&project, &from); + // Filter inside the index: a cap applied before the root filter can fill with + // own-root matches and evict the dependency roots entirely. + Ok(project.index.symbols_named_within(&name, None, &roots, 500)) + }) + .await +} + /// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). pub async fn fs_resolve_reference( host: &Host, @@ -181,6 +237,12 @@ pub(crate) fn register(d: &mut Dispatcher) { d.add("remove_recent", |c| async move { remove_recent(&c.host, &c.window, c.arg("path")?) }); d.add("recent_files", |c| async move { recent_files(&c.host, &c.window) }); d.add("web_goto", |c| async move { web_goto(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?).await }); + d.add("nav_resolve_module", |c| async move { + nav_resolve_module(&c.host, &c.window, c.arg("name")?, c.arg("from")?).await + }); + d.add("nav_index_definitions", |c| async move { + nav_index_definitions(&c.host, &c.window, c.arg("name")?, c.arg("from")?).await + }); d.add("fs_resolve_reference", |c| async move { fs_resolve_reference(&c.host, &c.window, c.arg("from")?, c.arg("value")?).await }); diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 2e5197e8d..869cf9291 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -13,9 +13,11 @@ use ide_vfs::Watcher; use ide_workspace::documents::DocumentObserver; use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoots, SettingsStore, SourceFolder}; use parking_lot::{Mutex, RwLock}; +use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; /// Everything bound to one open project folder. pub struct Project { @@ -1197,9 +1199,81 @@ fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cac extra_content_roots(settings, root, build_cache) } +/// The roots a file may navigate into: its own root (the workspace member containing it, or +/// the project root) plus that root's configured dependencies. A workspace member depends +/// only on the roots picked per member in Settings › Project Structure › Dependencies — +/// being attached to the workspace never makes its code navigable by itself. +/// Cached navigation roots per (project, file), with the instant they were computed. +type NavigationRootsCache = HashMap<(PathBuf, PathBuf), (Instant, Vec)>; + +pub(crate) fn navigation_roots(project: &Project, from: &Path) -> Vec { + // Hover probes and import-segment clicks repeat these lookups for the same file, + // and each uncached call re-reads the workspace file: memoize briefly. The short + // TTL keeps settings and workspace edits near-immediate. + static CACHE: Mutex> = Mutex::new(None); + const TTL: Duration = Duration::from_secs(1); + const CAP: usize = 256; + let key = (project.root.clone(), from.to_path_buf()); + if let Some((at, roots)) = CACHE.lock().as_ref().and_then(|m| m.get(&key)) + && at.elapsed() < TTL + { + return roots.clone(); + } + let roots = navigation_roots_uncached(project, from); + if let Some(map) = CACHE.lock().as_mut() { + if map.len() >= CAP { + map.retain(|_, (at, _)| at.elapsed() < TTL); + } + map.insert(key, (Instant::now(), roots.clone())); + } + roots +} + +fn navigation_roots_uncached(project: &Project, from: &Path) -> Vec { + let settings = project.settings.effective(); + let workspace = ide_workspace::workspace::Workspace::load(&project.root).ok().flatten(); + let own = workspace + .as_ref() + .and_then(|w| w.projects.iter().filter(|p| from.starts_with(p)).max_by_key(|p| p.components().count()).cloned()) + .unwrap_or_else(|| project.root.clone()); + let mut roots = vec![own.clone()]; + let own_key = ide_core::ipc_path::to_ipc(&own); + if let Some(deps) = member_dependencies_for(&settings.project_structure.member_dependencies, &own_key) { + for dep in deps { + let dep = PathBuf::from(dep.trim()); + if dep.is_absolute() && dep.is_dir() && !roots.contains(&dep) { + roots.push(dep); + } + } + } + if workspace.is_none() { + for root in content_roots(&settings, &project.root, &project.build_cache_dir()) { + if !roots.contains(&root) { + roots.push(root); + } + } + } + roots +} + +/// The dependency roots configured for `own`, keyed by IPC path. The settings UI writes +/// keys as it received the member paths (IPC form); a hand-edited settings.toml may not, +/// so compare normalized rather than only by exact match. +fn member_dependencies_for<'a>(map: &'a BTreeMap>, own_key: &str) -> Option<&'a Vec> { + if let Some(deps) = map.get(own_key) { + return Some(deps); + } + map.iter().find(|(key, _)| ide_core::ipc_path::to_ipc(&PathBuf::from(key)) == own_key).map(|(_, deps)| deps) +} + fn extra_content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec { let mut out: Vec = Vec::new(); - let user = settings.project_structure.content_roots.iter().map(|r| PathBuf::from(r.trim())); + let user = settings + .project_structure + .content_roots + .iter() + .chain(settings.project_structure.dependencies.iter()) + .map(|r| PathBuf::from(r.trim())); for p in user.chain(ide_build::gradle_external_roots(root, build_cache, &settings.languages.java.gradle)) { if p.is_absolute() && p.is_dir() && !p.starts_with(root) && !out.contains(&p) { out.push(p); @@ -1811,3 +1885,34 @@ mod composer_tests { assert!(!changed(&[])); } } + +#[cfg(test)] +mod content_roots_tests { + use super::content_roots; + + #[test] + #[cfg(windows)] + fn member_dependencies_match_hand_written_keys() { + let mut map = std::collections::BTreeMap::new(); + map.insert("B:\\proj\\member".to_string(), vec!["B:/dep".to_string()]); + let deps = super::member_dependencies_for(&map, "B:/proj/member"); + assert_eq!(deps.map(Vec::as_slice), Some(["B:/dep".to_string()].as_slice())); + } + + #[test] + fn dependency_projects_join_the_content_roots() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("app"); + let shared = tmp.path().join("shared"); + let dep = tmp.path().join("lib"); + for dir in [&root, &shared, &dep] { + std::fs::create_dir_all(dir).unwrap(); + } + let mut settings = ide_core::settings::Settings::default(); + settings.project_structure.content_roots = vec![shared.to_string_lossy().into_owned()]; + settings.project_structure.dependencies = + vec![dep.to_string_lossy().into_owned(), root.to_string_lossy().into_owned()]; + let roots = content_roots(&settings, &root, &tmp.path().join("build")); + assert_eq!(roots, vec![shared, dep]); + } +} diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index 03082fed3..3a5c2aa23 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -319,6 +319,19 @@ impl ProjectIndex { matching::symbols_named(&self.shared.data.read(), name, kind, limit) } + /// Symbols named exactly `name` (of `kind`, if given) whose file is inside one of `roots` + /// (the project root plus its configured dependency roots): answers bounded by the cap + /// never evict matches from a root because another root filled it first. + pub fn symbols_named_within( + &self, + name: &str, + kind: Option, + roots: &[PathBuf], + limit: usize, + ) -> Vec { + matching::symbols_named_within(&self.shared.data.read(), name, kind, roots, limit) + } + /// Incrementally re-indexes changed paths (called from the vfs watcher). /// Cheap: the work is queued for the indexing thread. pub fn update(&self, changed: &[PathBuf], removed: &[PathBuf]) { diff --git a/crates/ide-index/src/matching.rs b/crates/ide-index/src/matching.rs index 6f5d27418..de2f2cbf4 100644 --- a/crates/ide-index/src/matching.rs +++ b/crates/ide-index/src/matching.rs @@ -526,11 +526,26 @@ pub(crate) fn find_symbols_until( /// Symbols named exactly `name` (and of `kind`, when given), by path then position. pub(crate) fn symbols_named(data: &IndexData, name: &str, kind: Option, limit: usize) -> Vec { + symbols_named_within(data, name, kind, &[], limit) +} + +/// Symbols named exactly `name` (and of `kind`, when given) whose file is inside one of +/// `roots` (empty = every indexed file), by path then position. Filtering while walking +/// entries keeps symbols outside the roots from materialising or filling the cap. +pub(crate) fn symbols_named_within( + data: &IndexData, + name: &str, + kind: Option, + roots: &[PathBuf], + limit: usize, +) -> Vec { let mask = char_mask(name); + let within = |e: &FileEntry| roots.is_empty() || roots.iter().any(|root| e.path.starts_with(root)); let mut out: Vec = data .files .iter() .flatten() + .filter(|e| within(e)) .flat_map(|e| { e.symbols.iter().filter(|s| s.mask == mask && &*s.name == name && kind.is_none_or(|k| s.kind == k)).map( move |s| SymbolMatch { diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index 63952f15c..46e5dd247 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -528,6 +528,27 @@ fn css_selectors_are_found_by_exact_name() { assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty()); } +#[test] +fn symbols_named_within_keeps_out_of_root_matches_from_evicting_a_root() { + let f = Fixture::new(&[ + ("a/w.rs", "struct Decoder;\nstruct Decoder;\n"), + ("b/x.rs", "struct Decoder;\nstruct Decoder;\nstruct Decoder;\n"), + ("dep/b.rs", "struct Decoder;\n"), + ]); + let idx = f.open(); + let own = f.root.join("a"); + let dep = f.root.join("dep"); + // Unfiltered, the cap fills in rel-path order — own root, then the out-of-root + // content root b/ — so dep/ is evicted before the caller's root filter runs. + let unfiltered = idx.symbols_named("Decoder", None, 3); + let unfiltered: Vec<&str> = unfiltered.iter().map(|m| m.rel_path.as_ref()).collect(); + assert_eq!(unfiltered, vec!["a/w.rs", "a/w.rs", "b/x.rs"]); + let found: Vec = + idx.symbols_named_within("Decoder", None, &[own, dep], 3).into_iter().map(|m| m.rel_path).collect(); + assert_eq!(found, vec!["a/w.rs".to_string(), "a/w.rs".to_string(), "dep/b.rs".to_string()]); + assert!(idx.symbols_named_within("Decoder", None, &[f.root.join("none")], 3).is_empty()); +} + #[test] fn content_roots_and_excludes_change_without_reopening() { let fx = Fixture::new(&[("src/main.rs", "fn alpha() {}\n"), ("src/gen/out.rs", "fn generated() {}\n")]); diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index 21161dd54..bdb4260fb 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -53,8 +53,8 @@ test("Project Structure keeps edits across repeated shortcuts and applies them", await page.keyboard.press("Meta+;"); await expect(dialog.getByLabel("Compiler output", { exact: true })).toHaveValue("out/classes"); await dialog.getByRole("button", { name: "Modules", exact: true }).click(); - await dialog.getByRole("tab", { name: "Dependencies", exact: true }).click(); - await expect(dialog.getByRole("button", { name: "Add Library", exact: true })).toBeDisabled(); + await dialog.getByRole("button", { name: "Dependencies", exact: true }).click(); + await expect(dialog.getByRole("group", { name: "The project depends on these projects" })).toBeVisible(); await dialog.getByRole("button", { name: "Artifacts", exact: true }).click(); await expect(dialog.getByRole("button", { name: "JAR", exact: true })).toBeDisabled(); await page.keyboard.press("Escape"); diff --git a/scripts/dev-session.ts b/scripts/dev-session.ts index 5adbdfa7f..ce3dd5c99 100644 --- a/scripts/dev-session.ts +++ b/scripts/dev-session.ts @@ -68,7 +68,8 @@ export async function claimSession( }); return { server }; } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE") throw error; + const code = (error as NodeJS.ErrnoException).code; + if (code !== "EADDRINUSE" && code !== "EACCES") throw error; const existing = await readSession(port); if (existing?.worktree === session.worktree && existing.identifier === session.identifier) { return { existing }; diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 34f8d4b88..6ee481991 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -218,6 +218,8 @@ pub fn builder() -> tauri_specta::Builder { nav::recent_files, nav::remove_recent, nav::web_goto, + nav::nav_resolve_module, + nav::nav_index_definitions, nav::fs_resolve_reference, nav::path_completions, nav::web_unresolved_references, diff --git a/src-tauri/src/commands/nav.rs b/src-tauri/src/commands/nav.rs index 910d602d2..68478efeb 100644 --- a/src-tauri/src/commands/nav.rs +++ b/src-tauri/src/commands/nav.rs @@ -89,6 +89,32 @@ pub async fn web_goto(window: Window, state: State<'_, AppState>, doc: DocId, po ide_host::ops::nav::web_goto(&state.host, window.label(), doc, pos).await } +/// The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when +/// no project or content root has it. +#[tauri::command] +#[specta::specta] +pub async fn nav_resolve_module( + window: Window, + state: State<'_, AppState>, + name: String, + from: IpcPath, +) -> IdeResult> { + ide_host::ops::nav::nav_resolve_module(&state.host, window.label(), name, from).await +} + +/// Index definitions named `name` within the roots `from` may navigate into (its own root +/// plus its configured dependencies). +#[tauri::command] +#[specta::specta] +pub async fn nav_index_definitions( + window: Window, + state: State<'_, AppState>, + name: String, + from: IpcPath, +) -> IdeResult> { + ide_host::ops::nav::nav_index_definitions(&state.host, window.label(), name, from).await +} + /// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). #[tauri::command] #[specta::specta] diff --git a/src/bindings.ts b/src/bindings.ts index cbaa74d7e..94432bc3f 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -388,6 +388,16 @@ export const commands = { reference: WebReference, targets: Location[], } | null, IdeError>(__TAURI_INVOKE("web_goto", { doc, pos })), + /** + * The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when + * no project or content root has it. + */ + navResolveModule: (name: string, from: IpcPath) => typedError(__TAURI_INVOKE("nav_resolve_module", { name, from })), + /** + * Index definitions named `name` within the roots `from` may navigate into (its own root + * plus its configured dependencies). + */ + navIndexDefinitions: (name: string, from: IpcPath) => typedError(__TAURI_INVOKE("nav_index_definitions", { name, from })), /** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */ fsResolveReference: (from: IpcPath, value: string) => typedError(__TAURI_INVOKE("fs_resolve_reference", { from, value })), /** Files and folders that continue `prefix`, a path being typed in `from`. */ @@ -7153,6 +7163,13 @@ export type ProjectStructureSettings = { unmarked?: string[], /** Content roots besides the project folder (absolute paths), shown and searched with it. */ contentRoots?: string[], + /** Other projects (absolute paths) this project depends on; indexed and navigable like content roots. */ + dependencies?: string[], + /** + * Per-workspace-member dependencies: member root (IPC path) → the roots it depends on. + * A member not listed here (or with an empty list) navigates only into itself. + */ + memberDependencies?: { [key in string]: string[] }, /** "Exclude files": `;`-separated name patterns (`*.log;tmp*`) excluded at any depth. */ excludeFiles?: string, /** Project compiler output directory (relative to project root or absolute; empty = default). */ diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index 966ba6e70..564fcb16a 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -48,10 +48,11 @@ import { basename, relativePath, useProject } from "@/platform/project"; import { editorService } from "@/workbench/contributions"; import { fileIconName } from "@/ui"; import { NO_SERVER, debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp"; -import { offsetToPos, rangeToOffsets } from "./positions"; +import { offsetToPos, rangeContains, rangeToOffsets } from "./positions"; import { SYNTAX_NOTE, declarationFallback, + indexDefinitions, isSelfTarget, localHighlights, type DeclarationTarget, @@ -314,6 +315,16 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) let locs: DeclarationTarget[]; let fromSyntax = false; const declaration = kind === "definition" || kind === "declaration"; + // A segment of an import path names a file — possibly in a dependency project, which + // neither the single-root server nor the name index resolves. + const moduleName = declaration ? importModuleName(view, doc, offset) : null; + if (moduleName) { + const module = await moduleFile(doc, moduleName).catch(() => null); + if (module) { + await navigateTo(module); + return; + } + } let serverDown = false; let streamed: ReturnType | null = null; try { @@ -347,7 +358,8 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) return; serverDown = isUnavailable(e); // Dumb mode: the server is not ready / failing — answer from the syntax tree. - const fb = await gotoFallback(view, doc, pos); + // An import path is not a name to look up: only its file matters. + const fb = moduleName ? null : await gotoFallback(view, doc, pos); if (superseded()) return; if (!fb) { reportLspError(view, e, true); @@ -371,6 +383,31 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) ) return; if (superseded()) return; + // The server only resolves what it sees: answer from the project index, which also + // covers attached dependency projects (an unresolved import into them). Never for a + // module path: a segment is not a symbol name. + if (declaration && !fromSyntax && !moduleName) { + const name = nameAt(view, offset); + const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : []; + if (targets.length) { + if (isSelfTarget(targets, doc.path, pos)) { + if (!(await executeAction("find.showUsages"))) showHint(view, "No usages found"); + return; + } + if (targets.length === 1) { + await navigateTo(targets[0]!); + return; + } + openPopup({ + kind: "list", + anchor: caretAnchor(view, offset), + title: chooserTitle(kind, name, targets.length), + items: await locationItems(targets), + pin: pinToFind(name ?? "", targets), + }); + return; + } + } // The server only checks this file's syntax: say why instead of just "not found". const reason = serverDown ? null : outsideProjectReason(doc.path); showHint( @@ -385,6 +422,45 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) } // IDEA: ⌘B on a declaration shows its usages. if (kind === "definition" && isSelfTarget(locs, doc.path, pos)) { + // An imported name is not the declaration it means: when the server points at the import + // itself (it analyses one root and cannot see the dependency project), the import names + // the module the declaration lives in. Prefer that module — the bare name alone matches + // unrelated declarations of the same name in other roots. + const modulePath = importedModulePath(view, offset); + const name = modulePath ? importedDeclarationName(view, offset) : null; + let others: DeclarationTarget[] = []; + if (name && modulePath) { + // An imported name can be a submodule itself (`from a import b` → a/b.py). + const submodule = await moduleFile(doc, joinModulePath(modulePath, name)).catch(() => null); + if (submodule) { + others = [submodule]; + } else { + const file = await moduleFile(doc, modulePath).catch(() => null); + if (file) { + const defs = await indexDefinitions(doc.path, name).catch(() => []); + others = defs.filter((t) => t.path === file.path); + if (!others.length) others = [file]; + } + } + } + if (!others.length && name) { + const targets = await indexDefinitions(doc.path, name).catch(() => []); + others = targets.filter((t) => !(t.path === doc.path && rangeContains(t.range, pos))); + } + if (others.length === 1) { + await navigateTo(others[0]!); + return; + } + if (others.length > 1) { + openPopup({ + kind: "list", + anchor: caretAnchor(view, offset), + title: chooserTitle(kind, name, others.length), + items: await locationItems(others), + pin: pinToFind(name ?? "", others), + }); + return; + } if (!(await executeAction("find.showUsages")) && !superseded()) showHint(view, "No usages found"); return; } @@ -495,6 +571,76 @@ async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos): } } +/** + * The module path up to the caret's segment — `a.b` for `a.b.c` with the caret on `b`, with + * the leading dots of a relative import — or null when the caret is not on a module path + * (an imported name is not a path). Read from the line text: a segment names a file whether + * or not a syntax tree is available. + */ +function importModuleName(view: EditorView, doc: EditorDocContext, offset: number): string | null { + if (doc.virtual) return null; + const line = view.state.doc.lineAt(offset); + const col = offset - line.from; + const prefixTo = (path: string, at: number) => { + const cut = Math.min(Math.max(0, col - at), path.length); + let end = cut; + while (end < path.length && path[end] !== ".") end++; + return path.slice(0, end); + }; + const from = /^\s*from\s+(\.*[\w.]*)\s+import\b/.exec(line.text); + if (from?.[1]) { + const at = line.text.indexOf(from[1], from.index); + if (col >= at && col <= at + from[1].length) return prefixTo(from[1], at) || null; + } + const plain = /^\s*import\s+([\w.]+)/.exec(line.text); + if (plain?.[1]) { + const at = line.text.indexOf(plain[1], plain.index); + if (col >= at && col <= at + plain[1].length) return prefixTo(plain[1], at) || null; + } + return null; +} + +/** The file a dotted module path names, in the roots the document may navigate into. */ +async function moduleFile(doc: EditorDocContext, name: string): Promise { + const path = await lspRequest(() => commands.navResolveModule(name, doc.path)).catch(() => null); + return path ? { path, range: { start: { line: 0, col: 0 }, end: { line: 0, col: 0 } } } : null; +} + +/** + * The full module path an import binds names from — `a.b` of `from a.b import c` (with the + * relative dots), or the dotted path of a plain `import`. Reads through a parenthesised + * `from … import (…)` so a caret on a listed name finds its module. Null off an import. + */ +function importedModulePath(view: EditorView, offset: number): string | null { + const doc = view.state.doc; + let line = doc.lineAt(offset); + for (let hops = 0; ; hops++) { + const from = /^\s*from\s+(\.*[\w.]*)\s+import\b/.exec(line.text); + if (from?.[1]) return from[1]; + const plain = /^\s*import\s+([\w.]+)(?:\s+as\s+\w+)?\s*(?:#.*)?$/.exec(line.text); + if (plain?.[1]) return plain[1]; + if (line.number === 1 || hops > 20) return null; + const prev = doc.line(line.number - 1); + // A listed name continues an import above; anything else does not. + if (!/[,(]\s*$/.test(prev.text) || !/^[\w*,\s()]*$/.test(line.text)) return null; + line = prev; + } +} + +/** The name an import binds at the caret — the original when the caret is on its alias. */ +function importedDeclarationName(view: EditorView, offset: number): string | null { + const word = navigationWord(view, offset); + if (!word) return null; + const text = view.state.sliceDoc(word.from, word.to); + const alias = new RegExp(`(\\w+)\\s+as\\s+${text}\\b`).exec(view.state.doc.lineAt(offset).text); + return alias?.[1] ?? text; +} + +/** `from . import x` joins as `.x`; `from a.b import c` as `a.b.c`. */ +function joinModulePath(module: string, name: string): string { + return module.endsWith(".") ? `${module}${name}` : `${module}.${name}`; +} + // --------------------------------------------------------------------------- // ⌘-hover link + ⌘-click @@ -562,14 +708,28 @@ async function probeNavigation( let navigable = !!contributedAt(view.state, CONTRIBUTED_DEFINITION, offset); if (!navigable && doc) { const pos = offsetToPos(view.state.doc, offset); + let fromSyntax = false; try { navigable = (await requestNavigation(view, offset, "definition")).length > 0; } catch (e) { if (!isUnavailable(e)) throw e; navigable = !!(await gotoFallback(view, doc, pos))?.length; + fromSyntax = true; } if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual) navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length; + // The index answers across dependency roots too (unresolved imports), but a module path + // segment is a file rather than a name. + if (!navigable && !fromSyntax) { + const moduleName = importModuleName(view, doc, offset); + if (moduleName) navigable = !!(await moduleFile(doc, moduleName).catch(() => null)); + else { + const word = navigationWord(view, offset); + const name = word ? view.state.sliceDoc(word.from, word.to) : null; + const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : []; + navigable = targets.length > 0; + } + } } if (!navigable) return null; return { info: null }; diff --git a/src/editor/lsp/syntaxFallback.test.ts b/src/editor/lsp/syntaxFallback.test.ts index 1ebba79d0..32b30cec5 100644 --- a/src/editor/lsp/syntaxFallback.test.ts +++ b/src/editor/lsp/syntaxFallback.test.ts @@ -22,6 +22,8 @@ const cmd = { syntaxIdentifiers: vi.fn((): R => ok([])), syntaxErrors: vi.fn((): R => ok({ errors: [], truncated: false })), findSymbols: vi.fn((): R => ok([])), + navIndexDefinitions: vi.fn((): R => ok([])), + navResolveModule: vi.fn((): R => ok(null)), applyWorkspaceEdit: vi.fn((): R => ok(null)), }; @@ -342,6 +344,142 @@ describe("navigation wiring", () => { expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to"); }); + it("answers from the index when the server cannot resolve an import into a dependency project", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("ParallelDims", "class", "/deps/engine/model.py")])); + const view = editor("from torchtitan.distributed import ParallelDims;\n", "python", 35, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/deps/engine/model.py", { + selection: { line: 3, col: 4 }, + focus: true, + }); + }); + + it("opens the file a package segment of an import path names", async () => { + cmd.navResolveModule.mockReturnValueOnce(ok("/deps/torchtitan/__init__.py")); + cmd.navResolveModule.mockReturnValueOnce(ok("/deps/torchtitan/tools/logging.py")); + const view = editor("from torchtitan.tools.logging import logger;\n", "python", 6, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(cmd.navResolveModule).toHaveBeenCalledWith("torchtitan", "/p/a.py"); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/__init__.py", { + selection: { line: 0, col: 0 }, + focus: true, + }); + openFile.mockClear(); + const deeper = editor("from torchtitan.tools.logging import logger;\n", "python", 24, "/p/a.py"); + await gotoTargets(deeper, "definition"); + expect(cmd.navResolveModule).toHaveBeenLastCalledWith("torchtitan.tools.logging", "/p/a.py"); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/tools/logging.py", { + selection: { line: 0, col: 0 }, + focus: true, + }); + }); + + it("never looks a module path segment up as a symbol name", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + const view = editor("from torchtitan.tools.logging import logger;\n", "python", 17, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(cmd.navResolveModule).toHaveBeenCalledWith("torchtitan.tools", "/p/a.py"); + expect(cmd.navIndexDefinitions).not.toHaveBeenCalled(); + expect(openFile).not.toHaveBeenCalled(); + expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to"); + }); + + it("still looks the imported name up, not the module path", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("logger", "variable", "/deps/torchtitan/tools/logging.py")])); + const view = editor("from torchtitan.tools.logging import logger;\n", "python", 39, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(cmd.navResolveModule).not.toHaveBeenCalled(); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/tools/logging.py", { + selection: { line: 3, col: 4 }, + focus: true, + }); + }); + + it("looks past a server answer that points at the import itself", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([{ path: "/p/a.py", range: r(0, 37, 43) }])); + cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("logger", "variable", "/deps/torchtitan/tools/logging.py")])); + const view = editor("from torchtitan.tools.logging import logger;\n", "python", 39, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/tools/logging.py", { + selection: { line: 3, col: 4 }, + focus: true, + }); + expect(executeAction).not.toHaveBeenCalledWith("find.showUsages"); + }); + + it("narrows a plain import with a trailing comment the same way", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([{ path: "/p/a.py", range: r(0, 32, 39) }])); + cmd.navResolveModule + .mockImplementationOnce(() => ok(null)) // the segment click did not resolve: the answer came from the server + .mockImplementationOnce(() => ok(null)) // the name is not a submodule of the module + .mockImplementationOnce(() => ok("/deps/torchtitan/models/common/decoder.py")); + cmd.navIndexDefinitions.mockReturnValueOnce( + ok([sym("Decoder", "class", "/deps/torchtitan/models/common/decoder.py")]), + ); + const view = editor("import torchtitan.models.common.decoder # Decoder\n", "python", 36, "/p/a.py"); + await gotoTargets(view, "definition"); + // The plain import's name is the module segment itself: the index has no exact + // "decoder" symbol, so the narrowed answer is the module file. + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/models/common/decoder.py", { + selection: { line: 0, col: 0 }, + focus: true, + }); + expect(executeAction).not.toHaveBeenCalledWith("find.showUsages"); + }); + + it("narrows a self-pointed import answer to the module the import names", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([{ path: "/p/a.py", range: r(0, 45, 52) }])); + cmd.navResolveModule + .mockImplementationOnce(() => ok(null)) // the name is not a submodule of the module + .mockImplementationOnce(() => ok("/deps/torchtitan/models/common/decoder.py")); + cmd.navIndexDefinitions.mockReturnValueOnce( + ok([ + sym("Decoder", "class", "/deps/torchtitan/models/common/decoder.py"), + sym("Decoder", "class", "/deps/torchtitan/models/flux/autoencoder.py"), + ]), + ); + const view = editor("from torchtitan.models.common.decoder import Decoder\n", "python", 47, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/models/common/decoder.py", { + selection: { line: 3, col: 4 }, + focus: true, + }); + expect(executeAction).not.toHaveBeenCalledWith("find.showUsages"); + }); + + it("jumps to the file when an imported name is a submodule", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([{ path: "/p/a.py", range: r(0, 30, 37) }])); + cmd.navResolveModule.mockImplementationOnce(() => ok("/deps/torchtitan/models/decoder/__init__.py")); + const view = editor("from torchtitan.models import decoder\n", "python", 35, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/models/decoder/__init__.py", { + selection: { line: 0, col: 0 }, + focus: true, + }); + expect(cmd.navIndexDefinitions).not.toHaveBeenCalled(); + }); + + it("narrows a listed name of a parenthesised import to its module", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([{ path: "/p/a.py", range: r(1, 2, 9) }])); + cmd.navResolveModule + .mockImplementationOnce(() => ok(null)) + .mockImplementationOnce(() => ok("/deps/torchtitan/models/common/decoder.py")); + cmd.navIndexDefinitions.mockReturnValueOnce( + ok([ + sym("Decoder", "class", "/deps/torchtitan/models/common/decoder.py"), + sym("Decoder", "class", "/deps/torchtitan/models/flux/autoencoder.py"), + ]), + ); + const view = editor("from torchtitan.models.common.decoder import (\n Decoder,\n)\n", "python", 52, "/p/a.py"); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/deps/torchtitan/models/common/decoder.py", { + selection: { line: 3, col: 4 }, + focus: true, + }); + }); + it("says why when the server only checks the file's syntax", async () => { const { setFileDiagnostics } = await import("./diagnostics"); setFileDiagnostics("/p/a.ts", "jdtls", [ diff --git a/src/editor/lsp/syntaxFallback.ts b/src/editor/lsp/syntaxFallback.ts index 0740f9a25..03fbe5881 100644 --- a/src/editor/lsp/syntaxFallback.ts +++ b/src/editor/lsp/syntaxFallback.ts @@ -131,6 +131,21 @@ export function localTargets(path: string, symbol: LocalSymbol): { targets: Decl const SYMBOL_LIMIT = 500; +/** + * Index definitions named `name` — what the project index knows beyond the language + * server's scope: only the roots `path` may navigate into (its own root plus its + * configured dependencies; see Project Structure › Dependencies). No local-variable + * heuristics: an empty server answer stays authoritative about the code it analyses. + */ +export async function indexDefinitions(path: string, name: string): Promise { + const matches = await call(commands.navIndexDefinitions(name, path)); + const symbols = filterSymbols(matches, name, "other").filter((s) => compatibleFiles(path, s.path)); + return rankTargets( + symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })), + path, + ); +} + /** * Go to Declaration without a language server: a certain local definition, * otherwise project index symbols with exactly that name (filtered by the diff --git a/src/features/project-tree/index.ts b/src/features/project-tree/index.ts index 721dff766..7bcd304e3 100644 --- a/src/features/project-tree/index.ts +++ b/src/features/project-tree/index.ts @@ -2,7 +2,7 @@ import { onEditorEvent, openEditorPaths } from "@/editor/api"; import { commands, isTauri, onIdeEvent } from "@/platform/ipc"; import { useBuildModel } from "@/platform/buildModel"; -import { validateProjectStructure, type RootFolder } from "@/platform/languageSettings"; +import { effectiveContentRoots, validateProjectStructure, type RootFolder } from "@/platform/languageSettings"; import { useProject } from "@/platform/project"; import { initProjectRoots, useProjectRoots } from "@/platform/projectRoots"; import { folderIconName } from "@/ui"; @@ -115,7 +115,7 @@ export function activate(): () => void { const syncContentRoots = () => { const { project, settings } = useProject.getState(); const own = project && (!project.workspace || project.workspace.projects[0] === project.root); - const paths = own ? validateProjectStructure(settings?.projectStructure).contentRoots : []; + const paths = own ? effectiveContentRoots(validateProjectStructure(settings?.projectStructure)) : []; // The Build tool window's model (one load per build change), not a load of our own. const build = useBuildModel.getState(); const gradleBuilds = build.root === project?.root ? (build.model?.gradle ?? []) : []; diff --git a/src/features/run/contextRun.ts b/src/features/run/contextRun.ts index 9d9215fb9..18fb5ac92 100644 --- a/src/features/run/contextRun.ts +++ b/src/features/run/contextRun.ts @@ -8,7 +8,7 @@ import { activeEditor } from "@/editor/api"; import { executeAction, getAction } from "@/platform/actions"; import { call, commands, isTauri, type RunConfig } from "@/platform/ipc"; import { useProject } from "@/platform/project"; -import { validateProjectStructure } from "@/platform/languageSettings"; +import { effectiveContentRoots, validateProjectStructure } from "@/platform/languageSettings"; import { useBuildModel } from "@/platform/buildModel"; import { isVirtualUri } from "@/platform/virtualDocs"; import { showContextMenu, type MenuItem } from "@/ui"; @@ -48,7 +48,7 @@ async function ensureConfigs() { /** The focused editor's file, text and caret line. */ /** Project folders outside its root: Project Structure content roots and Gradle modules (as of the last sync). */ export function projectContentRoots(): string[] { - const own = validateProjectStructure(useProject.getState().settings?.projectStructure).contentRoots; + const own = effectiveContentRoots(validateProjectStructure(useProject.getState().settings?.projectStructure)); // The build model keeps the folders of modules outside the project absolute. const gradle = (useBuildModel.getState().model?.gradle ?? []) .flatMap((g) => g.projects) diff --git a/src/features/settings/__tests__/dialog.test.tsx b/src/features/settings/__tests__/dialog.test.tsx index 36b1a2152..4e8f2d85b 100644 --- a/src/features/settings/__tests__/dialog.test.tsx +++ b/src/features/settings/__tests__/dialog.test.tsx @@ -655,7 +655,11 @@ describe("Settings dialog", () => { expect(within(nav).getByRole("button", { name: "Modules" })).toHaveAttribute("aria-current", "page"); expect(within(psDialog).getByRole("tab", { name: "Sources" })).toBeInTheDocument(); expect(within(psDialog).getByRole("tab", { name: "Paths" })).toBeInTheDocument(); - expect(within(psDialog).getByRole("tab", { name: "Dependencies" })).toBeInTheDocument(); + await act(async () => { + fireEvent.click(within(nav).getByRole("button", { name: "Dependencies" })); + }); + expect(within(nav).getByRole("button", { name: "Dependencies" })).toHaveAttribute("aria-current", "page"); + expect(within(psDialog).getByRole("group", { name: "The project depends on these projects" })).toBeInTheDocument(); }); it("preserves pending Project Structure edits when its shortcut is invoked again", async () => { @@ -675,9 +679,10 @@ describe("Settings dialog", () => { await act(async () => executeAction("file.projectStructure", "modules")); fireEvent.click(screen.getByRole("tab", { name: "Paths" })); expect(screen.getByLabelText("Test output path")).toBeDisabled(); - fireEvent.click(screen.getByRole("tab", { name: "Dependencies" })); - expect(screen.getByRole("button", { name: "Add Library" })).toBeDisabled(); - expect(screen.getByRole("button", { name: "Add Module Dependency" })).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Dependencies" })); + // Project dependencies are supported: the checklist is live, no disabled placeholder. + expect(screen.getByRole("group", { name: "The project depends on these projects" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Add Project…" })).toBeEnabled(); fireEvent.click(screen.getByRole("button", { name: "Artifacts" })); expect(screen.getByRole("button", { name: "JAR" })).toBeDisabled(); expect(screen.getByRole("button", { name: "WAR" })).toBeDisabled(); diff --git a/src/features/settings/__tests__/projectDependencies.test.ts b/src/features/settings/__tests__/projectDependencies.test.ts new file mode 100644 index 000000000..446840e0b --- /dev/null +++ b/src/features/settings/__tests__/projectDependencies.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_PROJECT_STRUCTURE, effectiveContentRoots } from "@/platform/languageSettings"; +import { DEFAULT_SETTINGS, validateSettings } from "../model/schema"; +import { dependencyCandidates } from "../languages/ProjectStructurePage"; + +describe("project dependencies", () => { + it("validates stored dependencies like content roots", () => { + const s = validateSettings({ projectStructure: { dependencies: ["/deps/lib", "/deps/lib", ""] } }); + expect(s.projectStructure.dependencies).toEqual(["/deps/lib"]); + expect(DEFAULT_SETTINGS.projectStructure.dependencies).toEqual([]); + expect(DEFAULT_SETTINGS.projectStructure.memberDependencies).toEqual({}); + }); + + it("keeps per-root dependencies and drops empty ones", () => { + const s = validateSettings({ + projectStructure: { + memberDependencies: { "/w/app": ["/w/lib", "/w/lib", ""], "/w/lib": [], "": ["/w/app"] }, + }, + }); + expect(s.projectStructure.memberDependencies).toEqual({ "/w/app": ["/w/lib"] }); + }); + + it("merges dependencies into the effective content roots", () => { + expect( + effectiveContentRoots({ + ...DEFAULT_PROJECT_STRUCTURE, + contentRoots: ["/shared"], + dependencies: ["/deps/lib", "/shared"], + }), + ).toEqual(["/shared", "/deps/lib"]); + }); + + it("builds the checklist of one root", () => { + const rows = dependencyCandidates("/p/root", ["/deps/lib"], { + recents: [ + { path: "/w/other", name: "Other" }, + { path: "/p/root", name: "Root" }, + { path: "/p/root/sub", name: "Sub" }, + { path: "/deps/lib", name: "lib" }, + ], + }); + expect(rows).toEqual([ + { path: "/deps/lib", name: "lib", checked: true, disabled: false }, + { path: "/w/other", name: "Other", checked: false, disabled: false }, + ]); + }); +}); diff --git a/src/features/settings/languages/ProjectStructurePage.tsx b/src/features/settings/languages/ProjectStructurePage.tsx index db7a8ec87..d92bb91d6 100644 --- a/src/features/settings/languages/ProjectStructurePage.tsx +++ b/src/features/settings/languages/ProjectStructurePage.tsx @@ -25,7 +25,7 @@ import { import { SettingsFormContext } from "@/workbench/contributions"; import { call, commands, isTauri, nextRequestId, type FileEntry } from "@/platform/ipc"; import { mergeLibraryGroups } from "@/platform/libraries"; -import type { BuildModel, LibraryGroup, WebArtifact } from "@/bindings"; +import type { BuildModel, LibraryGroup, RecentProject, WebArtifact } from "@/bindings"; import { relativePath, useProject } from "@/platform/project"; import { PageContext, useSettingsFormFor } from "../components/context"; import { @@ -54,7 +54,6 @@ import { type FacetConfigValid, type FolderListKey, type FolderRole, - type ModuleDependencyValid, type ModuleStructureValid, type ProjectLibraryValid, type ProjectStructureValid, @@ -67,7 +66,14 @@ import { SdkField, tildify, useDetected, useProjectSetting } from "./components" import styles from "./Sdk.module.css"; import { tx } from "@/platform/i18n"; -export type ProjectStructureSectionId = "project" | "modules" | "libraries" | "facets" | "artifacts" | "sdks"; +export type ProjectStructureSectionId = + | "project" + | "modules" + | "dependencies" + | "libraries" + | "facets" + | "artifacts" + | "sdks"; interface DirNode { path: string; @@ -97,6 +103,7 @@ const ROLES: Array<{ role: FolderRole; label: string; title: string; kind: Folde const SECTION_TABS: Array<{ id: ProjectStructureSectionId; label: string; icon: IconName }> = [ { id: "project", label: "Project", icon: "folder" }, { id: "modules", label: "Modules", icon: "module" }, + { id: "dependencies", label: "Dependencies", icon: "build-dependencies" }, { id: "libraries", label: "Libraries", icon: "folder-library" }, { id: "facets", label: "Facets", icon: "file-config" }, { id: "artifacts", label: "Artifacts", icon: "file-archive" }, @@ -157,6 +164,10 @@ function useStructure(): [ProjectStructureValid, (next: ProjectStructureValid) = const [excluded, setExcluded] = useProjectSetting("projectStructure.excluded"); const [unmarked, setUnmarked] = useProjectSetting("projectStructure.unmarked"); const [contentRoots] = useProjectSetting("projectStructure.contentRoots"); + const [dependencies] = useProjectSetting("projectStructure.dependencies"); + const [memberDependencies] = useProjectSetting | undefined>( + "projectStructure.memberDependencies", + ); const [excludeFiles] = useProjectSetting("projectStructure.excludeFiles"); const [compilerOutput] = useProjectSetting("projectStructure.compilerOutput"); const [modules] = useProjectSetting | undefined>("projectStructure.modules"); @@ -174,6 +185,8 @@ function useStructure(): [ProjectStructureValid, (next: ProjectStructureValid) = excluded: excluded ?? [], unmarked: unmarked ?? [], contentRoots: contentRoots ?? [], + dependencies: dependencies ?? [], + memberDependencies: memberDependencies ?? {}, excludeFiles: excludeFiles ?? "", compilerOutput: compilerOutput ?? "", modules: modules ?? {}, @@ -189,6 +202,8 @@ function useStructure(): [ProjectStructureValid, (next: ProjectStructureValid) = excluded, unmarked, contentRoots, + dependencies, + memberDependencies, excludeFiles, compilerOutput, modules, @@ -581,6 +596,212 @@ interface DiscoveredModule { buildTool: "maven" | "gradle" | "custom"; } +/** One row of the Project Structure › Dependencies checklist. */ +export interface DependencyCandidate { + path: string; + name: string; + checked: boolean; + disabled: boolean; +} + +/** + * Rows of the "project dependencies" checklist of a single root (the project folder, or a + * workspace member): the configured dependencies first, then recent projects as candidates. + */ +export function dependencyCandidates( + root: string | null, + dependencies: readonly string[], + options: { recents?: ReadonlyArray<{ path: string; name: string }> } = {}, +): DependencyCandidate[] { + const out: DependencyCandidate[] = []; + const listed = new Set(); + const nameOf = (p: string) => p.slice(p.lastIndexOf("/") + 1).replace(/[\\/]+$/, "") || p; + const attachable = (p: string) => !!root && p !== root && !p.startsWith(`${root}/`); + for (const p of dependencies) { + if (listed.has(p) || !attachable(p)) continue; + listed.add(p); + out.push({ path: p, name: nameOf(p), checked: true, disabled: false }); + } + for (const r of options.recents ?? []) { + if (listed.has(r.path) || !attachable(r.path)) continue; + listed.add(r.path); + out.push({ path: r.path, name: r.name || nameOf(r.path), checked: false, disabled: false }); + } + return out; +} + +/** Settings › Project Structure › Modules › Dependencies. */ +function ModuleDependenciesTab() { + const workspaceProjects = useProject((s) => s.project?.workspace?.projects ?? null); + // A workspace: every member is an equal root that picks the roots it depends on. + return workspaceProjects ? : ; +} + +/** The dependency checklist of a standalone project (no workspace). */ +function ProjectDependencies() { + const root = useProject((s) => s.project?.root ?? null); + const [deps, setDeps] = useProjectSetting("projectStructure.dependencies"); + const [recents, setRecents] = useState([]); + + useEffect(() => { + let live = true; + void commands + .recentProjects() + .then((rs) => live && setRecents(rs)) + .catch(() => {}); + return () => { + live = false; + }; + }, []); + + const list = deps ?? []; + const candidates = useMemo(() => dependencyCandidates(root, deps ?? [], { recents }), [root, deps, recents]); + + const toggle = (path: string, checked: boolean) => + setDeps(checked ? [...list, path] : list.filter((x) => x !== path)); + const add = async () => { + const picked = await choosePath({ + directory: true, + title: "Add Project Dependency", + defaultPath: root ?? undefined, + }); + if (!picked || !root || picked === root || inside(root, picked) || list.includes(picked)) return; + setDeps([...list, picked]); + }; + + return ( +
+
+ + Dependency projects are indexed and navigable together with this project: Go to Declaration, Find Usages and + the Project view include them. + +
+
+ {candidates.length === 0 && ( +
+ No candidate projects. Recently opened projects appear here. +
+ )} + {candidates.map((c) => ( +
+ toggle(c.path, checked)} + aria-label={tx`The project depends on ${c.name}`} + /> + + {tildify(c.path)} + +
+ ))} +
+
+ +
+
+ ); +} + +/** The per-root dependency checklist of a workspace: all members are equal roots. */ +function MemberDependencies({ members }: { members: readonly string[] }) { + const [memberDeps, setMemberDeps] = useProjectSetting | undefined>( + "projectStructure.memberDependencies", + ); + const [selected, setSelected] = useState(0); + const active = members[Math.min(selected, members.length - 1)] ?? ""; + const activeName = active.slice(active.lastIndexOf("/") + 1); + const deps = useMemo(() => memberDeps?.[active] ?? [], [memberDeps, active]); + const others = useMemo(() => { + const nameOf = (p: string) => p.slice(p.lastIndexOf("/") + 1); + const extra = deps.filter((d) => !members.includes(d)).map((path) => ({ path, name: nameOf(path) })); + return members + .filter((m) => m !== active) + .map((path) => ({ path, name: nameOf(path) })) + .concat(extra); + }, [members, active, deps]); + const roots = useMemo( + () => members.map((path) => ({ path, name: path.slice(path.lastIndexOf("/") + 1) })), + [members], + ); + const setDeps = (next: string[]) => setMemberDeps({ ...(memberDeps ?? {}), [active]: next }); + const toggle = (path: string, checked: boolean) => + setDeps(checked ? [...deps, path] : deps.filter((x) => x !== path)); + const add = async () => { + const picked = await choosePath({ + directory: true, + title: "Add Project Dependency", + defaultPath: active, + }); + if (!picked || picked === active || inside(active, picked) || deps.includes(picked)) return; + setDeps([...deps, picked]); + }; + + return ( +
+
+ + Every root is equal: pick a root on the left, then check the roots it depends on. Go to Declaration in it + resolves only into its own code and its dependencies. + +
+
+
+
+ {roots.map((m, i) => ( + + ))} +
+
+
+
+
+ {others.length === 0 && ( +
+ No other roots. +
+ )} + {others.map((c) => ( +
+ toggle(c.path, checked)} + aria-label={tx`The root depends on ${c.name}`} + /> + + {tildify(c.path)} + +
+ ))} +
+
+ +
+
+
+
+
+ ); +} + function ModulesSection() { const root = useProject((s) => s.project?.root ?? null); const projectName = useProject((s) => s.project?.name ?? ""); @@ -588,10 +809,8 @@ function ModulesSection() { const [modulesMap, setModulesMap] = useProjectSetting | undefined>( "projectStructure.modules", ); - const [libraries] = useProjectSetting("projectStructure.libraries"); const [selectedModule, setSelectedModule] = useState("."); - const [subTab, setSubTab] = useState<"sources" | "paths" | "dependencies">("sources"); - const [selectedDepIdx, setSelectedDepIdx] = useState(-1); + const [subTab, setSubTab] = useState<"sources" | "paths">("sources"); const [moduleError, setModuleError] = useState(false); const outId = useId(); const testOutId = useId(); @@ -664,27 +883,6 @@ function ModulesSection() { setSelectedModule("."); }; - const addLibraryDependency = () => { - const firstLib = libraries?.[0]?.name ?? "project-lib"; - const dep: ModuleDependencyValid = { kind: "library", target: firstLib, scope: "compile", exported: false }; - updateModuleCfg({ dependencies: [...currentModuleCfg.dependencies, dep] }); - setSelectedDepIdx(currentModuleCfg.dependencies.length); - }; - - const addModuleDependency = () => { - const otherMod = modules.find((m) => m.key !== activeKey)?.key ?? "shared"; - const dep: ModuleDependencyValid = { kind: "module", target: otherMod, scope: "compile", exported: false }; - updateModuleCfg({ dependencies: [...currentModuleCfg.dependencies, dep] }); - setSelectedDepIdx(currentModuleCfg.dependencies.length); - }; - - const removeDependency = () => { - if (selectedDepIdx < 0 || selectedDepIdx >= currentModuleCfg.dependencies.length) return; - const next = currentModuleCfg.dependencies.filter((_, idx) => idx !== selectedDepIdx); - updateModuleCfg({ dependencies: next }); - setSelectedDepIdx(-1); - }; - const activeMod = modules.find((m) => m.key === activeKey) ?? modules[0]; return ( @@ -751,15 +949,6 @@ function ModulesSection() { > Paths - {subTab === "sources" && } @@ -868,108 +1057,6 @@ function ModulesSection() { )} - - {subTab === "dependencies" && ( -
-
- Custom module dependencies are not supported yet. Configure dependencies in Maven or Gradle. -
-
-
- - - -
-
- - - - - - - - - - - {currentModuleCfg.dependencies.length === 0 && ( - - - - )} - {currentModuleCfg.dependencies.map((dep, idx) => ( - setSelectedDepIdx(idx)} - > - - - - - - ))} - -
- Export - - Dependency - - Kind - - Scope -
- No custom module dependencies configured. -
- { - const next = [...currentModuleCfg.dependencies]; - next[idx] = { ...dep, exported }; - updateModuleCfg({ dependencies: next }); - }} - aria-label="Export dependency" - /> - - { - const next = [...currentModuleCfg.dependencies]; - next[idx] = { ...dep, target: e.target.value }; - updateModuleCfg({ dependencies: next }); - }} - /> - - - {dep.kind === "module" ? Module : Library} - - -
-
-
-
- )} @@ -1857,6 +1944,7 @@ const NAV_GROUPS: Array<{ items: [ { id: "project", label: "Project", icon: "folder" }, { id: "modules", label: "Modules", icon: "module" }, + { id: "dependencies", label: "Dependencies", icon: "build-dependencies" }, { id: "libraries", label: "Libraries", icon: "folder-library" }, { id: "facets", label: "Facets", icon: "file-config" }, { id: "artifacts", label: "Artifacts", icon: "file-archive" }, @@ -1979,6 +2067,7 @@ function ProjectStructureDialogInner() {
{section === "project" && } {section === "modules" && } + {section === "dependencies" && } {section === "libraries" && } {section === "facets" && } {section === "artifacts" && } @@ -2014,6 +2103,7 @@ export function ProjectStructurePage({ initialSection = "modules" }: { initialSe
{section === "project" && } {section === "modules" && } + {section === "dependencies" && } {section === "libraries" && } {section === "facets" && } {section === "artifacts" && } diff --git a/src/features/settings/model/staging.ts b/src/features/settings/model/staging.ts index 312beb8af..33e7f95f1 100644 --- a/src/features/settings/model/staging.ts +++ b/src/features/settings/model/staging.ts @@ -26,11 +26,19 @@ interface ExternalChange { apply(): Promise; } -export type ProjectStructureSection = "project" | "modules" | "libraries" | "facets" | "artifacts" | "sdks"; +export type ProjectStructureSection = + | "project" + | "modules" + | "dependencies" + | "libraries" + | "facets" + | "artifacts" + | "sdks"; const PROJECT_STRUCTURE_SECTIONS: readonly ProjectStructureSection[] = [ "project", "modules", + "dependencies", "libraries", "facets", "artifacts", diff --git a/src/features/settings/pages/languages.tsx b/src/features/settings/pages/languages.tsx index fc1c9df7c..f157a0027 100644 --- a/src/features/settings/pages/languages.tsx +++ b/src/features/settings/pages/languages.tsx @@ -69,6 +69,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [ "project sdk", "language level", "modules", + "dependencies", "libraries", "facets", "artifacts", diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index fc4d859b6..8efe63786 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -204,6 +204,10 @@ export interface ProjectStructureValid { unmarked: string[]; /** Content roots besides the project folder (absolute paths). */ contentRoots: string[]; + /** Other projects (absolute paths) this project depends on; indexed and navigable with it. */ + dependencies: string[]; + /** Per-workspace-member dependencies: member path → the roots it depends on. */ + memberDependencies: Record; /** "Exclude files": `;`-separated name patterns. */ excludeFiles: string; /** Project compiler output directory; empty = default. */ @@ -271,6 +275,8 @@ export const DEFAULT_PROJECT_STRUCTURE: ProjectStructureValid = { excluded: [], unmarked: [], contentRoots: [], + dependencies: [], + memberDependencies: {}, excludeFiles: "", compilerOutput: "", modules: {}, @@ -554,6 +560,17 @@ export function validateProjectStructure(raw: unknown): ProjectStructureValid { contentRoots: Array.isArray(p.contentRoots) ? [...new Set(p.contentRoots.filter((x): x is string => typeof x === "string" && !!x.trim()))] : [], + dependencies: Array.isArray(p.dependencies) + ? [...new Set(p.dependencies.filter((x): x is string => typeof x === "string" && !!x.trim()))] + : [], + memberDependencies: Object.fromEntries( + Object.entries(obj(p.memberDependencies)) + .map(([member, deps]) => [ + member, + Array.isArray(deps) ? [...new Set(deps.filter((x): x is string => typeof x === "string" && !!x.trim()))] : [], + ]) + .filter(([member, deps]) => !!member && (deps as string[]).length > 0), + ), excludeFiles: typeof p.excludeFiles === "string" ? p.excludeFiles : "", compilerOutput: text(p.compilerOutput, ""), modules: validateModulesMap(p.modules), @@ -563,6 +580,11 @@ export function validateProjectStructure(raw: unknown): ProjectStructureValid { }; } +/** Content roots plus dependency projects, deduplicated (what the Project view, index and run see). */ +export function effectiveContentRoots(ps: ProjectStructureValid): string[] { + return [...new Set([...ps.contentRoots, ...ps.dependencies])]; +} + /** Root kinds, as in IDEA's Project Structure (`ide-workspace::roots::RootKind`). */ export type FolderRole = "source" | "test" | "resources" | "testResources" | "excluded"; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 47ef38b21..5f139b4a3 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -274,16 +274,7 @@ "Output path": "Output path", "Test output path": "Test output path", "Select Test Output Directory": "Select Test Output Directory", - "Add Library": "Add Library", - "Add Module Dependency": "Add Module Dependency", - "Remove dependency": "Remove dependency", - "Export": "Export", - "Dependency": "Dependency", - "No custom module dependencies configured.": "No custom module dependencies configured.", - "Export dependency": "Export dependency", - "Dependency target": "Dependency target", "Library": "Library", - "Dependency scope": "Dependency scope", "Select Classes Directory": "Select Classes Directory", "Select Library JAR": "Select Library JAR", "Add JAR or Directory…": "Add JAR or Directory…", @@ -339,7 +330,6 @@ "Platform Settings": "Platform Settings", "Project Structure sections": "Project Structure sections", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.", - "Custom module dependencies are not supported yet. Configure dependencies in Maven or Gradle.": "Custom module dependencies are not supported yet. Configure dependencies in Maven or Gradle.", "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.", "Add Module Overrides": "Add Module Overrides", "Select a module directory inside the project.": "Select a module directory inside the project.", @@ -877,5 +867,18 @@ "Couldn't fork the task": "Couldn't fork the task", "Fork": "Fork", "Fork Conversation from Here": "Fork Conversation from Here", - "Rainbow indent guides": "Rainbow indent guides" + "Rainbow indent guides": "Rainbow indent guides", + "Project Dependencies": "Project Dependencies", + "The project depends on these projects": "The project depends on these projects", + "The project depends on {name}": "The project depends on {name}", + "Dependency projects are indexed and navigable together with this project: Go to Declaration, Find Usages and the Project view include them.": "Dependency projects are indexed and navigable together with this project: Go to Declaration, Find Usages and the Project view include them.", + "No candidate projects. Recently opened projects appear here.": "No candidate projects. Recently opened projects appear here.", + "Roots": "Roots", + "Dependencies of {name}": "Dependencies of {name}", + "The root depends on these projects": "The root depends on these projects", + "The root depends on {name}": "The root depends on {name}", + "No other roots.": "No other roots.", + "Add Project…": "Add Project…", + "Add Project Dependency": "Add Project Dependency", + "Every root is equal: pick a root on the left, then check the roots it depends on. Go to Declaration in it resolves only into its own code and its dependencies.": "Every root is equal: pick a root on the left, then check the roots it depends on. Go to Declaration in it resolves only into its own code and its dependencies." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 55894ef3d..4e8b35b15 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1825,16 +1825,7 @@ "Output path": "输出路径", "Test output path": "测试输出路径", "Select Test Output Directory": "选择测试输出目录", - "Add Library": "添加库", - "Add Module Dependency": "添加模块依赖", - "Remove dependency": "移除依赖", - "Export": "导出", - "Dependency": "依赖项", - "No custom module dependencies configured.": "尚未配置自定义模块依赖。", - "Export dependency": "导出依赖", - "Dependency target": "依赖目标", "Library": "库", - "Dependency scope": "依赖范围", "Select Classes Directory": "选择类目录", "Select Library JAR": "选择库 JAR", "Add JAR or Directory…": "添加 JAR 或目录…", @@ -6693,7 +6684,6 @@ "Cannot copy the value": "无法复制该值", "The check could not run: {reason}": "检查无法运行:{reason}", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暂不支持自定义测试输出路径。测试输出由 Maven 和 Gradle 管理。", - "Custom module dependencies are not supported yet. Configure dependencies in Maven or Gradle.": "暂不支持自定义模块依赖。请在 Maven 或 Gradle 中配置依赖。", "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "暂不支持自定义制品打包。请构建和部署 Maven 或 Gradle 定义的制品。", "Add Module Overrides": "添加模块覆盖设置", "Select a module directory inside the project.": "请选择项目内的模块目录。", @@ -7212,5 +7202,18 @@ "Imported '{name}' (based on {parent}): {applied} actions.": "已导入 '{name}'(基于 {parent}):{applied} 个操作。", "Not available in OpenIDEA ({length}): {join}.": "OpenIDEA 中不可用({length}):{join}。", "Skipped {skippedShortcuts} unsupported shortcuts.": "已跳过 {skippedShortcuts} 个不支持的快捷键。", - "Import IntelliJ IDEA Keymap…": "导入 IntelliJ IDEA 键盘映射…" + "Import IntelliJ IDEA Keymap…": "导入 IntelliJ IDEA 键盘映射…", + "Project Dependencies": "项目依赖项", + "The project depends on these projects": "项目取决于这些项目", + "The project depends on {name}": "项目取决于 {name}", + "Dependency projects are indexed and navigable together with this project: Go to Declaration, Find Usages and the Project view include them.": "依赖项目将与本项目一起建立索引并参与导航:“转到声明”、查找用法和项目视图都会包含它们。", + "No candidate projects. Recently opened projects appear here.": "暂无候选项目。最近打开的项目会显示在这里。", + "Add Project…": "添加项目…", + "Roots": "根", + "Dependencies of {name}": "{name} 的依赖项", + "The root depends on these projects": "该根取决于这些项目", + "The root depends on {name}": "该根取决于 {name}", + "No other roots.": "没有其他根。", + "Add Project Dependency": "添加项目依赖", + "Every root is equal: pick a root on the left, then check the roots it depends on. Go to Declaration in it resolves only into its own code and its dependencies.": "所有根地位相同:先在左侧选择一个根,再勾选它依赖的根。该根中的“转到声明”只会解析它自身及其依赖中的代码。" }