diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index b7c9139a5..a5b4e5698 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -15,6 +15,7 @@ use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress}; use ide_core::settings::Settings; use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit}; use std::path::Path; +use std::sync::Arc; fn join_err(e: tokio::task::JoinError) -> IdeError { IdeError::internal(e.to_string()) @@ -330,21 +331,61 @@ pub async fn build_sync( // holds for Gradle: it reuses its cached classpath on restart, so a // dependency added to `build.gradle` stays unresolved until told to sync. let lsp = project.lsp.clone(); + let documents = project.documents.clone(); tokio::spawn(async move { if profiles_changed { // jdtls takes the profiles from its Maven settings (see `ide_sdk::maven_profiles`). lsp.reconfigure().await; } + let first = updates.first().cloned(); for file in updates { let uri = ide_lsp::path_to_uri_string(&file); if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await { tracing::debug!("java/projectConfigurationsUpdate: {e}"); } } + let changed = { + let lsp = lsp.clone(); + tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default() + }; + if let Some(file) = first + && let Err(e) = lsp.java_refresh_archives(&file, &changed).await + { + tracing::debug!("openidea.java.refreshArchives: {e}"); + } + refresh_library_classes(&lsp, &documents).await; }); Ok(model) } +/// Open library classes whose jar was replaced in place (a SNAPSHOT installed +/// again keeps its path) show the new contents, like a reopened one. +async fn refresh_library_classes(lsp: &Arc, documents: &Arc) { + let changed = { + let (lsp, documents) = (lsp.clone(), documents.clone()); + tokio::task::spawn_blocking(move || { + documents + .open_documents() + .into_iter() + .filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?))) + .filter(|(_, uri)| lsp.library_class_changed(uri)) + .collect::>() + }) + .await + .unwrap_or_default() + }; + for (doc, uri) in changed { + match lsp.virtual_document(&uri).await { + Ok(vd) => { + if let Err(e) = documents.replace_virtual(doc, &vd.text, &vd.encoding, vd.has_bom) { + tracing::debug!("refreshing {uri}: {e}"); + } + } + Err(e) => tracing::debug!("refreshing {uri}: {e}"), + } + } +} + /// The POM declaring `dependency` for the Maven module `pom` (project-relative): the /// module's own, else its nearest parent in the project; its path, text and declaration. fn declaring_pom( @@ -1051,7 +1092,6 @@ mod maven_completion_tests { use ide_build::maven::completion::PomCompletionKind; use ide_core::CancellationToken; use ide_workspace::dependencies::DependencyVersionSource; - use std::sync::Arc; /// Cache answers the test plants before completing, so the op's Central /// lookups hit the session cache and the network is never reached. diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index a3beb2d5d..918c83298 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -809,6 +809,21 @@ impl LspManager { .map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e)) } + /// Asks jdtls to re-read library archives replaced in place (`openidea.java.refreshArchives`): + /// a SNAPSHOT installed again keeps its path, and JDT would keep showing the classes it read + /// from the old archive. Best-effort: skipped while jdtls is not already running. + pub async fn java_refresh_archives(&self, path: &Path, archives: &[PathBuf]) -> IdeResult<()> { + let java = LanguageId::new("java"); + let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else { + return Ok(()); + }; + if server.running().is_none() { + return Ok(()); + } + let archives = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect(); + self.jdtls_command(path, "openidea.java.refreshArchives", archives).await.map(|_| ()) + } + /// Pause autobuild before resolving the launch classpath. That query takes the /// Java project's workspace scheduling rule, draining the interrupted autobuild. /// Keep this guard until Maven outputs have been copied out of JDT's reach. diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 8d4f76592..bf5b43843 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -241,6 +241,9 @@ pub struct LspManager { virtual_origins: Mutex>, /// Contents fetched for virtual URIs. virtual_docs: Mutex>, + /// Modification time of the archive behind a cached library class, so a jar + /// replaced in place (a SNAPSHOT installed again) is read again. + virtual_stamps: Mutex>, injections: injections::State, /// Open notebooks by path. Locked before `docs` when both are. notebooks: Mutex>, @@ -508,6 +511,7 @@ impl LspManager { go_mod_checked: Mutex::new(HashSet::new()), virtual_origins: Mutex::new(HashMap::new()), virtual_docs: Mutex::new(HashMap::new()), + virtual_stamps: Mutex::new(HashMap::new()), injections: injections::State::default(), notebooks: Mutex::new(HashMap::new()), }) @@ -3202,14 +3206,44 @@ impl LspManager { Ok(found) } + /// Whether the archive behind a cached library class changed since it was read. + /// Stats the archive: call from a blocking worker. + pub fn library_class_changed(&self, uri: &str) -> bool { + let Some(stamp) = self.virtual_stamps.lock().get(uri).copied() else { return false }; + virtual_doc::archive_modified(uri) != Some(stamp) + } + + /// Archives behind cached library classes that changed since they were read. + /// Stats each archive: call from a blocking worker. + pub fn changed_library_archives(&self) -> Vec { + let uris: Vec = self.virtual_stamps.lock().keys().cloned().collect(); + let mut archives: Vec = uris + .iter() + .filter(|uri| self.library_class_changed(uri)) + .filter_map(|uri| virtual_doc::archive(uri)) + .collect(); + archives.sort(); + archives.dedup(); + archives + } + /// Contents of a virtual document, from the server that owns `uri`: /// `workspace/textDocumentContent` (LSP 3.18) when the server serves the /// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry /// is read from its archive, a `jar:` class shown as its library source /// (see [`library_source`]) or else decompiled by the server. Cached. pub async fn virtual_document(&self, uri: &str) -> IdeResult { - if let Some(d) = self.virtual_docs.lock().get(uri) { - return Ok(d.clone()); + let cached = self.virtual_docs.lock().get(uri).cloned(); + if let Some(d) = cached { + let stamp = self.virtual_stamps.lock().get(uri).copied(); + let current = { + let uri = uri.to_owned(); + tokio::task::spawn_blocking(move || virtual_doc::archive_modified(&uri)).await.ok().flatten() + }; + if stamp.is_none() || stamp == current { + return Ok(d); + } + self.virtual_docs.lock().remove(uri); } let scheme = virtual_doc::scheme(uri).to_owned(); let jar_class = scheme == "jar" && library_source::parse(uri).is_some_and(|e| e.entry.ends_with(".class")); @@ -3353,11 +3387,18 @@ impl LspManager { if let Some(server) = server { self.virtual_origins.lock().entry(uri.to_owned()).or_insert(server); } + let stamp = virtual_doc::archive_modified(uri); let mut cache = self.virtual_docs.lock(); + let mut stamps = self.virtual_stamps.lock(); if cache.len() >= VIRTUAL_CACHE_LIMIT { cache.clear(); + stamps.clear(); } cache.insert(uri.to_owned(), doc.clone()); + match stamp { + Some(stamp) => stamps.insert(uri.to_owned(), stamp), + None => stamps.remove(uri), + }; doc } diff --git a/crates/ide-lsp/src/virtual_doc.rs b/crates/ide-lsp/src/virtual_doc.rs index 077c33fc2..a14306bfc 100644 --- a/crates/ide-lsp/src/virtual_doc.rs +++ b/crates/ide-lsp/src/virtual_doc.rs @@ -172,6 +172,20 @@ pub fn description(uri: &str) -> Option { } } +/// The archive a `jar:` or `jdt:` library class comes from. +pub(crate) fn archive(uri: &str) -> Option { + match scheme(uri) { + "jar" => Some(crate::library_source::parse(uri)?.jar), + "jdt" => description(uri).filter(|p| p.ends_with(".jar") || p.ends_with(".jmod")).map(Into::into), + _ => None, + } +} + +/// Modification time of the archive a `jar:` or `jdt:` library class comes from. +pub(crate) fn archive_modified(uri: &str) -> Option { + std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok() +} + /// Check both the package and actual archive, so duplicate type names never pick another jar. pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, name: &str) -> bool { let segs = segments(uri); @@ -304,6 +318,29 @@ mod tests { assert_eq!(description("foo://x/y"), None); } + #[test] + fn finds_the_archive_behind_a_library_class() { + assert_eq!(archive(JDT), Some("/Users/me/.m2/repository/spring-boot-4.1.1.jar".into())); + assert_eq!( + archive("jdt://contents/java.base/java.lang/String.class?=p/%5C/jdk%5C/lib%5C/jrt-fs.jar%60java.base=x"), + None + ); + assert_eq!(archive("jdt://contents/a.jar/p/C.class"), None); + assert_eq!(archive("file:///a/C.java"), None); + + let dir = tempfile::tempdir().unwrap(); + let jar = dir.path().join("lib-1.0-SNAPSHOT.jar"); + std::fs::write(&jar, b"PK").unwrap(); + let uri = format!("jar:file://{}!/p/C.class", jar.display()); + assert_eq!(archive(&uri), Some(jar.clone())); + let before = archive_modified(&uri).unwrap(); + let file = std::fs::File::options().write(true).open(&jar).unwrap(); + file.set_modified(before + std::time::Duration::from_secs(5)).unwrap(); + assert_ne!(archive_modified(&uri), Some(before)); + std::fs::remove_file(&jar).unwrap(); + assert_eq!(archive_modified(&uri), None); + } + #[test] fn detects_generated_code() { assert!(is_decompiled( diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 54170b624..bb1953c76 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1547,7 +1547,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.13.0", + "1.14.0", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index 2418c45c4..649ffb4df 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA Java usages Bundle-SymbolicName: ai.openidea.usages;singleton:=true -Bundle-Version: 1.13.0 +Bundle-Version: 1.14.0 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core, org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime, diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index c2924301e..9adce4c03 100644 Binary files a/java/java-usages/openidea-java-usages.jar and b/java/java-usages/openidea-java-usages.jar differ diff --git a/java/java-usages/plugin.xml b/java/java-usages/plugin.xml index 54819bc98..cb1138eff 100644 --- a/java/java-usages/plugin.xml +++ b/java/java-usages/plugin.xml @@ -17,6 +17,9 @@ + + + diff --git a/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java b/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java new file mode 100644 index 000000000..496f9c99c --- /dev/null +++ b/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java @@ -0,0 +1,68 @@ +package ai.openidea.archives; + +import java.lang.reflect.Field; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.IJavaModel; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; + +/** + * Re-reads library archives replaced in place (a SNAPSHOT installed again keeps its path). The + * arguments are the archives' file system paths. Their package fragment roots are closed, which + * drops the class files read from the old archive, and jdtls' decompiled sources (cached by class + * handle, which a replaced archive keeps) are dropped, so the classes are read again. + */ +public final class RefreshArchivesCommand implements IDelegateCommandHandler { + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); + model.refreshExternalArchives(null, monitor); + Set archives = new HashSet<>(); + for (Object argument : arguments) { + if (argument instanceof String path) archives.add(Path.fromOSString(path)); + } + int closed = 0; + if (archives.isEmpty()) return closed; + clearDecompilerCache(); + for (IJavaProject project : model.getJavaProjects()) { + for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) { + if (monitor.isCanceled()) throw new OperationCanceledException(); + if (root.isArchive() && root.isExternal() && archives.contains(root.getPath()) && root.isOpen()) { + root.close(); + closed++; + } + } + } + return closed; + } + + /** jdtls keeps decompiled sources in a static per-decompiler LRU with no API to drop them. */ + private static void clearDecompilerCache() { + try { + Class impl = IDelegateCommandHandler.class.getClassLoader() + .loadClass("org.eclipse.jdt.ls.core.internal.decompiler.DecompilerImpl"); + Field field = impl.getDeclaredField("decompilerCache"); + field.setAccessible(true); + if (field.get(null) instanceof Map caches) { + synchronized (caches) { + for (Object cache : caches.values()) { + if (cache instanceof Map map) map.clear(); + } + } + } + } catch (ReflectiveOperationException | RuntimeException e) { + JavaLanguageServerPlugin.logException("Clearing decompiled sources", e); + } + } +} diff --git a/src/editor/core/librarySources.ts b/src/editor/core/librarySources.ts index 410618107..93bf8f5f8 100644 --- a/src/editor/core/librarySources.ts +++ b/src/editor/core/librarySources.ts @@ -1,10 +1,10 @@ import { useEffect, useState } from "react"; import { create } from "zustand"; import { registerActions } from "@/platform/actions"; -import { call, commands, isCancelled, nextRequestId, type RequestId } from "@/platform/ipc"; +import { call, commands, isCancelled, nextRequestId, onIdeEvent, type RequestId } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { useProject } from "@/platform/project"; -import { invalidateVirtualDocument } from "@/platform/virtualDocs"; +import { invalidateVirtualDocument, invalidateVirtualDocuments } from "@/platform/virtualDocs"; import { maybeEditorService, notifications } from "@/workbench/contributions"; interface SourceState { @@ -82,6 +82,9 @@ export function registerLibrarySourcesActions(): () => void { const offProject = useProject.subscribe((state, previous) => { if (state.project !== previous.project) clear(); }); + // A reload may have replaced a library jar in place (a SNAPSHOT installed again): reopened + // classes fetch their contents again (the backend refreshes the open ones). + const offRoots = onIdeEvent("projectRootsChanged", () => invalidateVirtualDocuments()); const offActions = registerActions([ { id: "editor.downloadSources", @@ -118,6 +121,7 @@ export function registerLibrarySourcesActions(): () => void { return () => { offActions(); offProject(); + offRoots(); clear(); }; } diff --git a/src/platform/virtualDocs.ts b/src/platform/virtualDocs.ts index f602785c0..57b4aac68 100644 --- a/src/platform/virtualDocs.ts +++ b/src/platform/virtualDocs.ts @@ -73,6 +73,11 @@ export function invalidateVirtualDocument(uri: string): void { cache.delete(uri); } +/** Forgets every cached document: a build tool reload may have replaced library jars in place. */ +export function invalidateVirtualDocuments(): void { + cache.clear(); +} + /** Contents of a virtual document (cached; failures are retried on the next call). */ export function virtualDocument(uri: string): Promise { let p = cache.get(uri);