From c79b31f64b83d8e319b878a0441044360a9acbd2 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 10:13:14 +0100 Subject: [PATCH] Extract Workspace/OpenProjects synchronization into own file --- .../java/lsp/server/protocol/Server.java | 405 +--------------- .../server/protocol/WorkspaceProjects.java | 445 ++++++++++++++++++ 2 files changed, 463 insertions(+), 387 deletions(-) create mode 100644 java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/WorkspaceProjects.java diff --git a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/Server.java b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/Server.java index 966226eec9e9..2632f74ad6e2 100644 --- a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/Server.java +++ b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/Server.java @@ -26,20 +26,14 @@ import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; -import java.util.concurrent.CancellationException; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; @@ -52,7 +46,6 @@ import java.util.concurrent.CompletionException; import java.util.stream.Collectors; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.eclipse.lsp4j.CallHierarchyRegistrationOptions; import org.eclipse.lsp4j.CodeActionKind; @@ -63,7 +56,6 @@ import org.eclipse.lsp4j.FoldingRangeProviderOptions; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.InitializeResult; -import org.eclipse.lsp4j.InlayHintRegistrationOptions; import org.eclipse.lsp4j.MessageActionItem; import org.eclipse.lsp4j.MessageParams; import org.eclipse.lsp4j.MessageType; @@ -114,11 +106,7 @@ import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; -import org.netbeans.api.project.ProjectInformation; -import org.netbeans.api.project.ProjectUtils; import static org.netbeans.api.project.ProjectUtils.parentOf; -import org.netbeans.api.project.Sources; -import org.netbeans.api.project.ui.OpenProjects; import org.netbeans.modules.java.lsp.server.LspGsonSetup; import org.netbeans.modules.java.lsp.server.LspServerState; import org.netbeans.modules.java.lsp.server.LspSession; @@ -139,13 +127,9 @@ import org.netbeans.modules.parsing.spi.indexing.CustomIndexerFactory; import org.netbeans.modules.parsing.spi.indexing.Indexable; import org.netbeans.modules.progress.spi.InternalHandle; -import org.netbeans.spi.project.ActionProgress; -import org.netbeans.spi.project.ActionProvider; import org.openide.LifecycleManager; import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileUtil; import org.openide.util.Lookup; -import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.util.Pair; import org.openide.util.RequestProcessor; @@ -159,12 +143,16 @@ * @author lahvac */ public final class Server { - private static final Logger LOG = Logger.getLogger(Server.class.getName()); + static final Logger LOG = Logger.getLogger(Server.class.getName()); + /** * Special logger that logs LSP in/out messages. */ - private static final Logger LSP_LOG = Logger.getLogger("org.netbeans.modules.java.lsp.server.lsptrace"); // NOI18N - private static final LspServerTelemetryManager LSP_SERVER_TELEMETRY = new LspServerTelemetryManager(); + static final Logger LSP_LOG = Logger.getLogger("org.netbeans.modules.java.lsp.server.lsptrace"); // NOI18N + static final LspServerTelemetryManager LSP_SERVER_TELEMETRY = new LspServerTelemetryManager(); + // change to a greater throughput if the initialization waits on more processes than just (serialized) project open. + static final RequestProcessor SERVER_INIT_RP = new RequestProcessor(LanguageServerImpl.class.getName()); + private static final ErrorsNotifier ERR_NOTIFIER = new ErrorsNotifier(); private Server() { @@ -408,10 +396,6 @@ public static class LanguageServerImpl implements LanguageServer, LanguageClient private static final String NETBEANS_PROJECT_JDKHOME = "project.jdkhome"; private static final String NETBEANS_JAVA_HINTS = "hints"; - // change to a greater throughput if the initialization waits on more processes than just (serialized) project open. - private static final RequestProcessor SERVER_INIT_RP = new RequestProcessor(LanguageServerImpl.class.getName()); - - private static final Logger LOG = Logger.getLogger(LanguageServerImpl.class.getName()); private NbCodeClientWrapper client; private final TextDocumentServiceImpl textDocumentService = new TextDocumentServiceImpl(this); private final WorkspaceServiceImpl workspaceService = new WorkspaceServiceImpl(this); @@ -424,49 +408,15 @@ public static class LanguageServerImpl implements LanguageServer, LanguageClient private final LspTreeViewServiceImpl treeService = new LspTreeViewServiceImpl(sessionLookup); private final LspInputServiceImpl inputService = new LspInputServiceImpl(); - - /** - * Projects that are or were opened. After projects open, their CompletableFutures - * remain here to signal no further priming build is required. - */ - // @GuardedBy(this) - private final Map> beingOpened = new HashMap<>(); - - /** - * Projects opened based on files. This registry avoids duplicate questions if - * more files are opened at the same time; the project question is displayed just for the - * first time. - */ - // @GuardedBy(this) - private final Map> openingFileOwners = new HashMap<>(); - - /** - * Holds projects opened in the LSP workspace; these projects serve as root points for - * other projects opened behind the scenes. The value is initially uncompleted, but - * is replaced by a completed future at any time the set of workspace projects change. - */ - private volatile CompletableFuture workspaceProjects = new CompletableFuture<>(); - - /** - * All projects opened by this LSP server. The collection is replaced every time - * the set of opened projects change, collections are never modified. - */ - private volatile Collection openedProjects = Collections.emptyList(); - - /** - * Workspace folders (nonproject) accepted by the user; we do not ask for opening projects - * underneath these folders. - */ - // @GuardedBy(this) - private final List acceptedWorkspaceFolders = new ArrayList<>(); - private final OpenedDocuments openedDocuments = new OpenedDocuments(); private final LspSession lspSession; private boolean shutdownReqReceived = false; + private final WorkspaceProjects workspaceProjects; LanguageServerImpl(LspSession session) { this.lspSession = session; + this.workspaceProjects = new WorkspaceProjects(workspaceService, () -> client); } private Lookup getSessionLookup() { @@ -491,331 +441,16 @@ Lookup getSessionOnlyLookup() { */ @Override public CompletableFuture asyncOpenSelectedProjects(List projectCandidates, boolean addWorkspace) { - if (projectCandidates == null || projectCandidates.isEmpty()) { - return CompletableFuture.completedFuture(new Project[0]); - } - CompletableFuture f = new CompletableFuture<>(); - LOG.log(Level.FINER, "Asked to open project(s): {0}", Arrays.asList(projectCandidates)); - LOG.log(Level.FINER, "Caller:", new Throwable()); - SERVER_INIT_RP.post(() -> { - asyncOpenSelectedProjects0(f, projectCandidates, addWorkspace, false); - }); - return f; - } - - @NbBundle.Messages({ - "PROMPT_AskOpenProjectForFile=File {0} belongs to project {1}. To enable all features, the project should be opened" - + " and initialized by the Language Server. Do you want to proceed ?", - "PROMPT_AskOpenProject=To enable all features of project {0}, it should be opened" - + " and initialized by the Language Server. Do you want to proceed ?", - "PROMPT_AskOpenProjectForFile_Yes=Open and initialize", - "PROMPT_AskOpenProjectForFile_No=No", - "PROMPT_AskOpenProjectForFile_Unnamed=(unnamed)" - }) + return workspaceProjects.asyncOpenSelectedProjects(projectCandidates, addWorkspace); + } + @Override public CompletableFuture asyncOpenFileOwner(FileObject file) { - Project prj = FileOwnerQuery.getOwner(file); - if (prj == null) { - return CompletableFuture.completedFuture(null); - } - // first wait on the initial workspace open/init. - return workspaceProjects.thenCompose((wprj) -> { - CompletableFuture f = new CompletableFuture<>(); - CompletableFuture g = f.thenApply(arr -> arr.length > 0 ? arr[0] : null); - Collection prjs = Arrays.asList(wprj); - - boolean openImmediately = false; - synchronized (this) { - if (openedProjects.contains(prj)) { - // shortcut - return CompletableFuture.completedFuture(prj); - } - CompletableFuture h = beingOpened.get(prj); - if (h != null) { - // already being really opened - return h.thenApply((unused) -> prj); - } - // the project is already being asked for; otherwise leave - // a trace + flag so the project is not asked again. - CompletableFuture p = openingFileOwners.putIfAbsent(prj, g); - if (p != null) { - return p; - } - // if any of the parent projects is among the opened ones, - // then we are permitted - for (Project check : projectPath(prj, false)) { - if (prjs.contains(check)) { - openImmediately = true; - break; - } - } - if (!openImmediately) { - FileObject pdir = prj.getProjectDirectory(); - // accept projects in folders which were not recognized as project parts. - for (FileObject wf : acceptedWorkspaceFolders) { - if (wf.equals(pdir) || FileUtil.isParentOf(wf, pdir)) { - openImmediately = true; - } - } - } - } - if (openImmediately) { - // open without asking - SERVER_INIT_RP.post(() -> { - asyncOpenSelectedProjects0(f, Collections.singletonList(file), false, false); - }); - } else { - ProjectInformation pi = ProjectUtils.getInformation(prj); - String dispName = pi != null ? pi.getDisplayName() : Bundle.PROMPT_AskOpenProjectForFile_Unnamed(); - final MessageActionItem yes = new MessageActionItem(Bundle.PROMPT_AskOpenProjectForFile_Yes()); - ShowMessageRequestParams smrp = new ShowMessageRequestParams(Arrays.asList( - yes, - new MessageActionItem(Bundle.PROMPT_AskOpenProjectForFile_No()) - )); - if (prj.getProjectDirectory() == file) { - smrp.setMessage(Bundle.PROMPT_AskOpenProject(dispName)); - } else { - smrp.setMessage(Bundle.PROMPT_AskOpenProjectForFile(file.getNameExt(), dispName)); - } - smrp.setType(MessageType.Info); - - client.showMessageRequest(smrp).thenAccept(ai -> { - if (!yes.equals(ai)) { - f.completeExceptionally(new CancellationException()); - return; - } - SERVER_INIT_RP.post(() -> { - asyncOpenSelectedProjects0(f, Collections.singletonList(file), false, false); - }); - }); - } - return f.thenApply(arr -> arr.length > 0 ? arr[0] : null); - }); + return workspaceProjects.asyncOpenFileOwner(file); } public List getAcceptedWorkspaceFolders() { - return acceptedWorkspaceFolders; - } - - /** - * For diagnostic purposes - */ - private AtomicInteger openRequestId = new AtomicInteger(1); - - private void asyncOpenSelectedProjects0(CompletableFuture f, List projectCandidates, boolean asWorkspaceProjects, boolean validParents) { - List projects = new ArrayList<>(); - List nonProjects = new ArrayList<>(); - List haveProjects = new ArrayList<>(); - - Project[] candidateMapping = new Project[projectCandidates.size()]; - try { - int index = 0; - if (projectCandidates != null) { - for (FileObject candidate : projectCandidates) { - Project prj = FileOwnerQuery.getOwner(candidate); - LOG.log(Level.FINER, "Opening {0} for candidate {1}, directory is {2}", new Object[] { prj, candidate, prj == null ? null : prj.getProjectDirectory() }); - if (prj != null) { - candidateMapping[index] = prj; - projects.add(prj); - haveProjects.add(prj.getProjectDirectory()); - } else if (validParents && candidate.isFolder()) { - nonProjects.add(candidate); - } - index++; - } - - synchronized (this) { - boolean nwp = asWorkspaceProjects; - for (FileObject pd : haveProjects) { - for (FileObject wf : new ArrayList<>(acceptedWorkspaceFolders)) { - if (wf.equals(pd) || FileUtil.isParentOf(pd, wf)) { - LOG.log(Level.FINE, "Nonproject workspace folder turned to project: {0}", projectCandidates.get(0)); - acceptedWorkspaceFolders.remove(wf); - // we should call asyncOpenSelectedProjects1 twice, once to add to workspace, once to not add - - // but it should only happen with single-file open = just one project. - if (projectCandidates.size() == 1) { - nwp = true; - } - } - } - } - A: for (FileObject np : nonProjects) { - for (FileObject c : acceptedWorkspaceFolders) { - if (c.equals(np) || FileUtil.isParentOf(c, np)) { - continue A; - } - } - LOG.log(Level.FINE, "Not recognized as a project, but accepting as workspace : {0}", np); - acceptedWorkspaceFolders.add(np); - } - asWorkspaceProjects = nwp; - } - } - Project[] previouslyOpened; - try { - previouslyOpened = OpenProjects.getDefault().openProjects().get(); - if (previouslyOpened.length > 0) { - Level level = Level.FINEST; - assert (level = Level.CONFIG) != null; - for (Project p : previouslyOpened) { - LOG.log(level, "Previously opened project at {0}", p.getProjectDirectory()); - } - } - } catch (InterruptedException | ExecutionException ex) { - throw new IllegalStateException(ex); - - } - asyncOpenSelectedProjects1(f, previouslyOpened, candidateMapping, projects, asWorkspaceProjects); - } catch (RuntimeException ex) { - f.completeExceptionally(ex); - } - } - - CompletableFuture[] primeProjects(Collection projects, int id, Map> local) { - List toOpen = new ArrayList<>(); - List> primingBuilds = new ArrayList<>(); - - synchronized (this) { - LOG.log(Level.FINER, "{0}: Opening project(s): {1}", new Object[]{ id, Arrays.asList(projects) }); - for (Project p : projects) { - CompletableFuture pending = beingOpened.get(p); - if (pending != null) { - primingBuilds.add(pending); - } else { - toOpen.add(p); - local.put(p, new CompletableFuture()); - } - } - beingOpened.putAll(local); - } - - LOG.log(Level.FINER, id + ": Opening projects: {0}", Arrays.asList(toOpen)); - - // before the projects are officialy 'opened', try to prime the projects - for (Project p : toOpen) { - ActionProvider pap = p.getLookup().lookup(ActionProvider.class); - if (pap == null) { - LOG.log(Level.FINER, "{0}: No action provider at all !", id); - continue; - } - if (!Arrays.asList(pap.getSupportedActions()).contains(ActionProvider.COMMAND_PRIME)) { - LOG.log(Level.FINER, "{0}: No action provider gives PRIME", id); - // this may take some while; so better call outside of any locks. - continue; - } - LOG.log(Level.FINER, "{0}: Found Priming action: {1}", new Object[]{id, p}); - if (pap.isActionEnabled(ActionProvider.COMMAND_PRIME, Lookup.EMPTY)) { - final CompletableFuture primeF = new CompletableFuture<>(); - LOG.log(Level.FINER, "{0}: Found enabled Priming build for: {1}", new Object[]{id, p}); - ActionProgress progress = new ActionProgress() { - @Override - protected void started() {} - - @Override - public void finished(boolean success) { - LOG.log(Level.FINER, id + ": Priming build completed for project " + p); - primeF.complete(null); - } - }; - primingBuilds.add(primeF); - - pap.invokeAction(ActionProvider.COMMAND_PRIME, Lookups.fixed(progress)); - } - } - return primingBuilds.toArray(new CompletableFuture[0]); - } - - private void asyncOpenSelectedProjects1(CompletableFuture f, Project[] previouslyOpened, Project[] candidateMapping, List initialProjects, boolean addToWorkspace) { - long t = System.currentTimeMillis(); - int id = this.openRequestId.getAndIncrement(); - Map> local = new HashMap<>(); - - CompletableFuture[] primingBuilds = primeProjects(initialProjects, id, local); - - AtomicReference>> subprojectProcessor = new AtomicReference(); - Set processedProjects = new HashSet<>(); - AtomicInteger level = new AtomicInteger(1); - subprojectProcessor.set((projects) -> { - Set additionalProjects = new LinkedHashSet<>(); - for (Project prj : projects) { - Set containedProjects = ProjectUtils.getContainedProjects(prj, true); - if (containedProjects != null) { - LOG.log(Level.FINE, "Project {0} reports contained projects: {1}", new Object[] { prj, containedProjects }); - additionalProjects.addAll(containedProjects); - } - } - additionalProjects.removeAll(processedProjects); - additionalProjects.removeAll(projects); - - processedProjects.addAll(projects); - - LOG.log(Level.FINE, "Processing subprojects, level {0}: {1}", new Object[] { level.getAndIncrement(), additionalProjects }); - - if (additionalProjects.isEmpty()) { - OpenProjects.getDefault().open(processedProjects.toArray(new Project[processedProjects.size()]), false); - try { - LOG.log(Level.FINER, "{0}: Calling openProjects() for : {1}", new Object[]{id, Arrays.asList(processedProjects)}); - OpenProjects.getDefault().openProjects().get(); - } catch (InterruptedException | ExecutionException ex) { - throw new IllegalStateException(ex); - } - for (Project prj : processedProjects) { - //init source groups/FileOwnerQuery: - ProjectUtils.getSources(prj).getSourceGroups(Sources.TYPE_GENERIC); - final CompletableFuture prjF = local.get(prj); - if (prjF != null) { - prjF.complete(null); - } - } - Set projectSet = new HashSet<>(Arrays.asList(OpenProjects.getDefault().getOpenProjects())); - projectSet.retainAll(openedProjects); - projectSet.addAll(processedProjects); - - Project[] prjsRequested = projects.toArray(new Project[processedProjects.size()]); - Project[] prjs = projects.toArray(new Project[processedProjects.size()]); - LOG.log(Level.FINER, "{0}: Finished opening projects: {1}", new Object[]{id, Arrays.asList(processedProjects)}); - synchronized (this) { - openedProjects = projectSet; - if (addToWorkspace) { - Set ns = new HashSet<>(processedProjects); - List current = Arrays.asList(workspaceProjects.getNow(new Project[0])); - int s = current.size(); - ns.addAll(current); - LOG.log(Level.FINER, "Current is: {0}, ns: {1}", new Object[] { current, ns }); - if (s != ns.size()) { - prjs = ns.toArray(new Project[ns.size()]); - workspaceProjects.complete(prjs); - workspaceProjects = CompletableFuture.completedFuture(prjs); - } - } - for (Project p : prjs) { - // override flag in opening cache, no further questions asked. - openingFileOwners.put(p, f.thenApply(unused -> p)); - } - } - f.complete(candidateMapping); - List workspaceClientFolders = workspaceService.getClientWorkspaceFolders(); - LSP_SERVER_TELEMETRY.sendWorkspaceInfo(client, workspaceClientFolders, openedProjects, System.currentTimeMillis() - t); - LOG.log(Level.INFO, "{0} projects opened in {1}ms", new Object[] { prjsRequested.length, (System.currentTimeMillis() - t) }); - } else { - LOG.log(Level.FINER, "{0}: Collecting projects to prime from: {1}", new Object[]{id, Arrays.asList(additionalProjects)}); - CompletableFuture[] nextPrimingBuilds = primeProjects(additionalProjects, id, local); - CompletableFuture.allOf(nextPrimingBuilds).thenRun(() -> { - subprojectProcessor.get().accept(additionalProjects); - }).exceptionally(e -> { - f.completeExceptionally(e); - return null; - }); - } - }); - - // Wait for all priming builds, even those already pending, to finish: - CompletableFuture.allOf(primingBuilds).thenRun(() -> { - subprojectProcessor.get().accept(initialProjects); - }).exceptionally(e -> { - f.completeExceptionally(e); - return null; - }); + return workspaceProjects.getAcceptedWorkspaceFolders(); } private JavaSource checkJavaSupport() { @@ -832,7 +467,7 @@ private JavaSource checkJavaSupport() { @Override public CompletableFuture openedProjects() { - return workspaceProjects; + return workspaceProjects.getWorkspaceProjects(); } @Override @@ -982,7 +617,7 @@ public CompletableFuture initialize(InitializeParams init) { //TODO: use getRootPath()? } } - CompletableFuture possibleWaitedPrjs = workspaceProjects; + CompletableFuture possibleWaitedPrjs = workspaceProjects.getWorkspaceProjects(); // this Future will receive candidates, some of them possibly null. Cannot complete directly the existing `workspaceProjects` wit the returned candidates, // as this could return nulls to clients that do not expect any. CompletableFuture prjs = new CompletableFuture(); @@ -1012,7 +647,7 @@ public CompletableFuture initialize(InitializeParams init) { if (!cancel.get()) { projectCandidates.addAll(additionalCandidates); } - asyncOpenSelectedProjects0(prjs, projectCandidates, true, true); + workspaceProjects.asyncOpenSelectedProjects0(prjs, projectCandidates, true, true); }); // chain showIndexingComplete message after initial project open. @@ -1059,7 +694,7 @@ private void initializeOptions() { workspaceService.updateMavenUserSettingsPreferences(newMavenUserSettingsPath); }); - getWorkspaceProjects().thenAccept(projects -> { + workspaceProjects.getWorkspaceProjects().thenAccept(projects -> { List defaultConfigs = List.of(NETBEANS_JAVA_HINTS, NETBEANS_PROJECT_JDKHOME); List projectConfigs = List.of(NETBEANS_FORMAT, NETBEANS_JAVA_IMPORTS); @@ -1106,10 +741,6 @@ private void initializeOptions() { }); } - public CompletableFuture getWorkspaceProjects() { - return workspaceProjects; - } - public InitializeResult finishInitialization(InitializeResult res) { OperationContext c = OperationContext.find(sessionLookup); // discard the progress token as it is going to be invalid anyway. Further pending diff --git a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/WorkspaceProjects.java b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/WorkspaceProjects.java new file mode 100644 index 000000000000..feacdf404607 --- /dev/null +++ b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/WorkspaceProjects.java @@ -0,0 +1,445 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.java.lsp.server.protocol; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import org.eclipse.lsp4j.MessageActionItem; +import org.eclipse.lsp4j.MessageType; +import org.eclipse.lsp4j.ShowMessageRequestParams; +import org.eclipse.lsp4j.services.LanguageClient; +import org.netbeans.api.project.FileOwnerQuery; +import org.netbeans.api.project.Project; +import org.netbeans.api.project.ProjectInformation; +import org.netbeans.api.project.ProjectUtils; +import org.netbeans.api.project.Sources; +import org.netbeans.api.project.ui.OpenProjects; +import static org.netbeans.modules.java.lsp.server.protocol.Server.projectPath; +import org.netbeans.spi.project.ActionProgress; +import org.netbeans.spi.project.ActionProvider; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.Lookup; +import org.openide.util.NbBundle; +import org.openide.util.lookup.Lookups; + +/** Synchronizes workspace with list of opened projects. + * + * @see OpenProjects + */ +final class WorkspaceProjects { + private final WorkspaceServiceImpl workspaceService; + private final Supplier lazyClient; + + WorkspaceProjects(WorkspaceServiceImpl workspaceService, Supplier lazyClient) { + this.workspaceService = workspaceService; + this.lazyClient = lazyClient; + } + + /** + * For diagnostic purposes + */ + private final AtomicInteger openRequestId = new AtomicInteger(1); + + /** + * Workspace folders (nonproject) accepted by the user; we do not ask for + * opening projects underneath these folders. + */ + // @GuardedBy(this) + private final List acceptedWorkspaceFolders = new ArrayList<>(); + + /** + * All projects opened by this LSP server. The collection is replaced every + * time the set of opened projects change, collections are never modified. + */ + private volatile Collection openedProjects = Collections.emptyList(); + + /** + * Holds projects opened in the LSP workspace; these projects serve as root + * points for other projects opened behind the scenes. The value is + * initially uncompleted, but is replaced by a completed future at + * any time the set of workspace projects change. + */ + private volatile CompletableFuture workspaceProjects = new CompletableFuture<>(); + + /** + * Projects opened based on files. This registry avoids duplicate questions + * if more files are opened at the same time; the project question is + * displayed just for the first time. + */ + // @GuardedBy(this) + private final Map> openingFileOwners = new HashMap<>(); + + /** + * Projects that are or were opened. After projects open, their + * CompletableFutures remain here to signal no further priming build is + * required. + */ + // @GuardedBy(this) + private final Map> beingOpened = new HashMap<>(); + + /** + * Open projects that own the `projectCandidates` files asynchronously. + * Returns immediately, results or errors are reported through the Future. + * + * @param projectCandidates files whose projects should be opened. + * @return future that yields the opened project instances. + */ + CompletableFuture asyncOpenSelectedProjects(List projectCandidates, boolean addWorkspace) { + if (projectCandidates == null || projectCandidates.isEmpty()) { + return CompletableFuture.completedFuture(new Project[0]); + } + CompletableFuture f = new CompletableFuture<>(); + Server.LOG.log(Level.FINER, "Asked to open project(s): {0}", Arrays.asList(projectCandidates)); + Server.LOG.log(Level.FINER, "Caller:", new Throwable()); + Server.SERVER_INIT_RP.post(() -> { + asyncOpenSelectedProjects0(f, projectCandidates, addWorkspace, false); + }); + return f; + } + + @NbBundle.Messages({ + "PROMPT_AskOpenProjectForFile=File {0} belongs to project {1}. To enable all features, the project should be opened" + + " and initialized by the Language Server. Do you want to proceed ?", + "PROMPT_AskOpenProject=To enable all features of project {0}, it should be opened" + + " and initialized by the Language Server. Do you want to proceed ?", + "PROMPT_AskOpenProjectForFile_Yes=Open and initialize", + "PROMPT_AskOpenProjectForFile_No=No", + "PROMPT_AskOpenProjectForFile_Unnamed=(unnamed)" + }) + CompletableFuture asyncOpenFileOwner(FileObject file) { + Project prj = FileOwnerQuery.getOwner(file); + if (prj == null) { + return CompletableFuture.completedFuture(null); + } + // first wait on the initial workspace open/init. + return workspaceProjects.thenCompose((wprj) -> { + CompletableFuture f = new CompletableFuture<>(); + CompletableFuture g = f.thenApply(arr -> arr.length > 0 ? arr[0] : null); + Collection prjs = Arrays.asList(wprj); + + boolean openImmediately = false; + synchronized (this) { + if (openedProjects.contains(prj)) { + // shortcut + return CompletableFuture.completedFuture(prj); + } + CompletableFuture h = beingOpened.get(prj); + if (h != null) { + // already being really opened + return h.thenApply((unused) -> prj); + } + // the project is already being asked for; otherwise leave + // a trace + flag so the project is not asked again. + CompletableFuture p = openingFileOwners.putIfAbsent(prj, g); + if (p != null) { + return p; + } + // if any of the parent projects is among the opened ones, + // then we are permitted + for (Project check : projectPath(prj, false)) { + if (prjs.contains(check)) { + openImmediately = true; + break; + } + } + if (!openImmediately) { + FileObject pdir = prj.getProjectDirectory(); + // accept projects in folders which were not recognized as project parts. + for (FileObject wf : acceptedWorkspaceFolders) { + if (wf.equals(pdir) || FileUtil.isParentOf(wf, pdir)) { + openImmediately = true; + } + } + } + } + if (openImmediately) { + // open without asking + Server.SERVER_INIT_RP.post(() -> { + asyncOpenSelectedProjects0(f, Collections.singletonList(file), false, false); + }); + } else { + ProjectInformation pi = ProjectUtils.getInformation(prj); + String dispName = pi != null ? pi.getDisplayName() : Bundle.PROMPT_AskOpenProjectForFile_Unnamed(); + final MessageActionItem yes = new MessageActionItem(Bundle.PROMPT_AskOpenProjectForFile_Yes()); + ShowMessageRequestParams smrp = new ShowMessageRequestParams(Arrays.asList( + yes, + new MessageActionItem(Bundle.PROMPT_AskOpenProjectForFile_No()) + )); + if (prj.getProjectDirectory() == file) { + smrp.setMessage(Bundle.PROMPT_AskOpenProject(dispName)); + } else { + smrp.setMessage(Bundle.PROMPT_AskOpenProjectForFile(file.getNameExt(), dispName)); + } + smrp.setType(MessageType.Info); + + getClient().showMessageRequest(smrp).thenAccept(ai -> { + if (!yes.equals(ai)) { + f.completeExceptionally(new CancellationException()); + return; + } + Server.SERVER_INIT_RP.post(() -> { + asyncOpenSelectedProjects0(f, Collections.singletonList(file), false, false); + }); + }); + } + return f.thenApply(arr -> arr.length > 0 ? arr[0] : null); + }); + } + + public List getAcceptedWorkspaceFolders() { + return acceptedWorkspaceFolders; + } + + void asyncOpenSelectedProjects0(CompletableFuture f, List projectCandidates, boolean asWorkspaceProjects, boolean validParents) { + List projects = new ArrayList<>(); + List nonProjects = new ArrayList<>(); + List haveProjects = new ArrayList<>(); + Project[] candidateMapping = new Project[projectCandidates.size()]; + try { + int index = 0; + if (projectCandidates != null) { + for (FileObject candidate : projectCandidates) { + Project prj = FileOwnerQuery.getOwner(candidate); + Server.LOG.log(Level.FINER, "Opening {0} for candidate {1}, directory is {2}", new Object[]{prj, candidate, prj == null ? null : prj.getProjectDirectory()}); + if (prj != null) { + candidateMapping[index] = prj; + projects.add(prj); + haveProjects.add(prj.getProjectDirectory()); + } else if (validParents && candidate.isFolder()) { + nonProjects.add(candidate); + } + index++; + } + synchronized (this) { + boolean nwp = asWorkspaceProjects; + for (FileObject pd : haveProjects) { + for (FileObject wf : new ArrayList<>(acceptedWorkspaceFolders)) { + if (wf.equals(pd) || FileUtil.isParentOf(pd, wf)) { + Server.LOG.log(Level.FINE, "Nonproject workspace folder turned to project: {0}", projectCandidates.get(0)); + acceptedWorkspaceFolders.remove(wf); + // we should call asyncOpenSelectedProjects1 twice, once to add to workspace, once to not add - + // but it should only happen with single-file open = just one project. + if (projectCandidates.size() == 1) { + nwp = true; + } + } + } + } + A: + for (FileObject np : nonProjects) { + for (FileObject c : acceptedWorkspaceFolders) { + if (c.equals(np) || FileUtil.isParentOf(c, np)) { + continue A; + } + } + Server.LOG.log(Level.FINE, "Not recognized as a project, but accepting as workspace : {0}", np); + acceptedWorkspaceFolders.add(np); + } + asWorkspaceProjects = nwp; + } + } + Project[] previouslyOpened; + try { + previouslyOpened = OpenProjects.getDefault().openProjects().get(); + if (previouslyOpened.length > 0) { + Level level = Level.FINEST; + assert (level = Level.CONFIG) != null; + for (Project p : previouslyOpened) { + Server.LOG.log(level, "Previously opened project at {0}", p.getProjectDirectory()); + } + } + } catch (InterruptedException | ExecutionException ex) { + throw new IllegalStateException(ex); + } + asyncOpenSelectedProjects1(f, previouslyOpened, candidateMapping, projects, asWorkspaceProjects); + } catch (RuntimeException ex) { + f.completeExceptionally(ex); + } + } + + private void asyncOpenSelectedProjects1(CompletableFuture f, Project[] previouslyOpened, Project[] candidateMapping, List initialProjects, boolean addToWorkspace) { + long t = System.currentTimeMillis(); + int id = openRequestId.getAndIncrement(); + Map> local = new HashMap<>(); + CompletableFuture[] primingBuilds = primeProjects(initialProjects, id, local); + AtomicReference>> subprojectProcessor = new AtomicReference(); + Set processedProjects = new HashSet<>(); + AtomicInteger level = new AtomicInteger(1); + subprojectProcessor.set((projects) -> { + Set additionalProjects = new LinkedHashSet<>(); + for (Project prj : projects) { + Set containedProjects = ProjectUtils.getContainedProjects(prj, true); + if (containedProjects != null) { + Server.LOG.log(Level.FINE, "Project {0} reports contained projects: {1}", new Object[] { prj, containedProjects }); + additionalProjects.addAll(containedProjects); + } + } + additionalProjects.removeAll(processedProjects); + additionalProjects.removeAll(projects); + + processedProjects.addAll(projects); + + Server.LOG.log(Level.FINE, "Processing subprojects, level {0}: {1}", new Object[] { level.getAndIncrement(), additionalProjects }); + + if (additionalProjects.isEmpty()) { + OpenProjects.getDefault().open(processedProjects.toArray(new Project[processedProjects.size()]), false); + try { + Server.LOG.log(Level.FINER, "{0}: Calling openProjects() for : {1}", new Object[]{id, Arrays.asList(processedProjects)}); + OpenProjects.getDefault().openProjects().get(); + } catch (InterruptedException | ExecutionException ex) { + throw new IllegalStateException(ex); + } + for (Project prj : processedProjects) { + //init source groups/FileOwnerQuery: + ProjectUtils.getSources(prj).getSourceGroups(Sources.TYPE_GENERIC); + final CompletableFuture prjF = local.get(prj); + if (prjF != null) { + prjF.complete(null); + } + } + Set projectSet = new HashSet<>(Arrays.asList(OpenProjects.getDefault().getOpenProjects())); + projectSet.retainAll(openedProjects); + projectSet.addAll(processedProjects); + + Project[] prjsRequested = projects.toArray(new Project[processedProjects.size()]); + Project[] prjs = projects.toArray(new Project[processedProjects.size()]); + Server.LOG.log(Level.FINER, "{0}: Finished opening projects: {1}", new Object[]{id, Arrays.asList(processedProjects)}); + synchronized (this) { + openedProjects = projectSet; + if (addToWorkspace) { + Set ns = new HashSet<>(processedProjects); + List current = Arrays.asList(workspaceProjects.getNow(new Project[0])); + int s = current.size(); + ns.addAll(current); + Server.LOG.log(Level.FINER, "Current is: {0}, ns: {1}", new Object[] { current, ns }); + if (s != ns.size()) { + prjs = ns.toArray(new Project[ns.size()]); + workspaceProjects.complete(prjs); + workspaceProjects = CompletableFuture.completedFuture(prjs); + } + } + for (Project p : prjs) { + // override flag in opening cache, no further questions asked. + openingFileOwners.put(p, f.thenApply(unused -> p)); + } + } + f.complete(candidateMapping); + List workspaceClientFolders = workspaceService.getClientWorkspaceFolders(); + Server.LSP_SERVER_TELEMETRY.sendWorkspaceInfo(getClient(), workspaceClientFolders, openedProjects, System.currentTimeMillis() - t); + Server.LOG.log(Level.INFO, "{0} projects opened in {1}ms", new Object[] { prjsRequested.length, (System.currentTimeMillis() - t) }); + } else { + Server.LOG.log(Level.FINER, "{0}: Collecting projects to prime from: {1}", new Object[]{id, Arrays.asList(additionalProjects)}); + CompletableFuture[] nextPrimingBuilds = primeProjects(additionalProjects, id, local); + CompletableFuture.allOf(nextPrimingBuilds).thenRun(() -> { + subprojectProcessor.get().accept(additionalProjects); + }).exceptionally(e -> { + f.completeExceptionally(e); + return null; + }); + } + }); // Wait for all priming builds, even those already pending, to finish: + CompletableFuture.allOf(primingBuilds).thenRun(() -> { + subprojectProcessor.get().accept(initialProjects); + }).exceptionally(e -> { + f.completeExceptionally(e); + return null; + }); + } + + CompletableFuture[] primeProjects(Collection projects, int id, Map> local) { + List toOpen = new ArrayList<>(); + List> primingBuilds = new ArrayList<>(); + + synchronized (this) { + Server.LOG.log(Level.FINER, "{0}: Opening project(s): {1}", new Object[]{id, Arrays.asList(projects)}); + for (Project p : projects) { + CompletableFuture pending = beingOpened.get(p); + if (pending != null) { + primingBuilds.add(pending); + } else { + toOpen.add(p); + local.put(p, new CompletableFuture()); + } + } + beingOpened.putAll(local); + } + + Server.LOG.log(Level.FINER, id + ": Opening projects: {0}", Arrays.asList(toOpen)); + + // before the projects are officialy 'opened', try to prime the projects + for (Project p : toOpen) { + ActionProvider pap = p.getLookup().lookup(ActionProvider.class); + if (pap == null) { + Server.LOG.log(Level.FINER, "{0}: No action provider at all !", id); + continue; + } + if (!Arrays.asList(pap.getSupportedActions()).contains(ActionProvider.COMMAND_PRIME)) { + Server.LOG.log(Level.FINER, "{0}: No action provider gives PRIME", id); + // this may take some while; so better call outside of any locks. + continue; + } + Server.LOG.log(Level.FINER, "{0}: Found Priming action: {1}", new Object[]{id, p}); + if (pap.isActionEnabled(ActionProvider.COMMAND_PRIME, Lookup.EMPTY)) { + final CompletableFuture primeF = new CompletableFuture<>(); + Server.LOG.log(Level.FINER, "{0}: Found enabled Priming build for: {1}", new Object[]{id, p}); + ActionProgress progress = new ActionProgress() { + @Override + protected void started() { + } + + @Override + public void finished(boolean success) { + Server.LOG.log(Level.FINER, id + ": Priming build completed for project " + p); + primeF.complete(null); + } + }; + primingBuilds.add(primeF); + + pap.invokeAction(ActionProvider.COMMAND_PRIME, Lookups.fixed(progress)); + } + } + return primingBuilds.toArray(new CompletableFuture[0]); + } + + CompletableFuture getWorkspaceProjects() { + return workspaceProjects; + } + + private LanguageClient getClient() { + return lazyClient.get(); + } + +}