-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathindex.ts
332 lines (303 loc) · 11.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import { findRuntimes, getRuntime, IJavaRuntime } from "jdk-utils";
import * as _ from "lodash";
import * as path from "path";
import * as vscode from "vscode";
import { getExtensionContext, getNonce } from "../utils";
import { getProjectNameFromUri, getProjectType } from "../utils/jdt";
import { ProjectType } from "../utils/webview";
import { JavaRuntimeEntry, ProjectRuntimeEntry } from "./types";
import { sourceLevelDisplayName } from "./utils/misc";
import { REQUIRED_JDK_VERSION, resolveRequirements } from "./utils/upstreamApi";
let javaRuntimeView: vscode.WebviewPanel | undefined;
let javaHomes: IJavaRuntime[];
export async function javaRuntimeCmdHandler(context: vscode.ExtensionContext, _operationId: string) {
if (javaRuntimeView) {
javaRuntimeView.reveal();
return;
}
javaRuntimeView = vscode.window.createWebviewPanel("java.runtime", "Configure Java Runtime", {
viewColumn: vscode.ViewColumn.One,
}, {
enableScripts: true,
enableCommandUris: true,
retainContextWhenHidden: true
});
await initializeJavaRuntimeView(context, javaRuntimeView, onDidDisposeWebviewPanel);
}
function onDidDisposeWebviewPanel() {
javaRuntimeView = undefined;
}
async function initializeJavaRuntimeView(context: vscode.ExtensionContext, webviewPanel: vscode.WebviewPanel, onDisposeCallback: () => void) {
webviewPanel.iconPath = {
light: vscode.Uri.file(path.join(context.extensionPath, "caption.light.svg")),
dark: vscode.Uri.file(path.join(context.extensionPath, "caption.dark.svg"))
};
webviewPanel.webview.html = getHtmlForWebview(webviewPanel, context.asAbsolutePath("./out/assets/java-runtime/index.js"));
context.subscriptions.push(webviewPanel.onDidDispose(onDisposeCallback));
context.subscriptions.push(webviewPanel.webview.onDidReceiveMessage(async (e) => {
switch (e.command) {
case "onWillListRuntimes": {
findJavaRuntimeEntries().then(data => {
showJavaRuntimeEntries(data);
});
break;
}
case "updateJavaHome": {
const { javaHome } = e;
await vscode.workspace.getConfiguration("java").update("home", javaHome, vscode.ConfigurationTarget.Global);
break;
}
case "updateRuntimePath": {
const { sourceLevel, runtimePath } = e;
const runtimes = vscode.workspace.getConfiguration("java").get<any[]>("configuration.runtimes") || [];
const target = runtimes.find(r => r.name === sourceLevel);
if (target) {
target.path = runtimePath;
} else {
runtimes.push({
name: sourceLevel,
path: runtimePath
});
}
await vscode.workspace.getConfiguration("java").update("configuration.runtimes", runtimes, vscode.ConfigurationTarget.Global);
findJavaRuntimeEntries().then(data => {
showJavaRuntimeEntries(data);
});
break;
}
case "setDefaultRuntime": {
const { runtimePath, majorVersion } = e;
const sourceLevel = sourceLevelDisplayName(majorVersion);
const runtimes = vscode.workspace.getConfiguration("java").get<any[]>("configuration.runtimes") || [];
for (const r of runtimes) {
delete r.default;
}
let targetRuntime = runtimes.find(r => r.path === runtimePath);
if (targetRuntime) {
targetRuntime.default = true;
} else {
targetRuntime = runtimes.find(r => r.name === sourceLevel);
if (targetRuntime) {
targetRuntime.path = runtimePath;
targetRuntime.default = true;
} else {
runtimes.push({
name: sourceLevel,
path: runtimePath,
default: true
});
}
}
await vscode.workspace.getConfiguration("java").update("configuration.runtimes", runtimes, vscode.ConfigurationTarget.Global);
findJavaRuntimeEntries().then(data => {
showJavaRuntimeEntries(data);
});
break;
}
case "openBuildScript": {
const { scriptFile, rootUri } = e;
const rootPath = vscode.Uri.parse(rootUri).fsPath;
const fullPath = path.join(rootPath, scriptFile);
vscode.commands.executeCommand("vscode.open", vscode.Uri.file(fullPath));
break;
}
case "onWillBrowseForJDK": {
const javaHomeUri: vscode.Uri[] | undefined = await vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectMany: false,
canSelectFolders: true,
title: "Specify Java runtime to launch Language Server"
});
if (javaHomeUri) {
const javaHome = javaHomeUri[0].fsPath;
if (await getRuntime(javaHome)) {
await vscode.workspace.getConfiguration("java").update("jdt.ls.java.home", javaHome, vscode.ConfigurationTarget.Global);
} else {
await vscode.window.showWarningMessage(`${javaHome} is not a valid Java runtime home directory.`);
}
}
break;
}
case "onWillRunCommandFromWebview": {
const { wrappedArgs } = e;
vscode.commands.executeCommand("java.webview.runCommand", wrappedArgs);
break;
}
default:
break;
}
}));
function showJavaRuntimeEntries(args: any) {
webviewPanel.webview.postMessage({
command: "showJavaRuntimeEntries",
args: args,
});
}
// refresh webview with latest source levels when classpath (project info) changes
const javaExt = vscode.extensions.getExtension("redhat.java");
if (javaExt?.isActive && javaExt?.exports?.onDidClasspathUpdate) {
const onDidClasspathUpdate: vscode.Event<vscode.Uri> = javaExt.exports.onDidClasspathUpdate;
const listener = onDidClasspathUpdate((_e: vscode.Uri) => {
findJavaRuntimeEntries().then(data => {
showJavaRuntimeEntries(data);
});
});
context.subscriptions.push(webviewPanel.onDidDispose(() => listener.dispose()));
}
}
function getHtmlForWebview(webviewPanel: vscode.WebviewPanel, scriptPath: string) {
const scriptPathOnDisk = vscode.Uri.file(scriptPath);
const scriptUri = webviewPanel.webview.asWebviewUri(scriptPathOnDisk);
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>Configure Java Runtime</title>
</head>
<body>
<script nonce="${nonce}" src="${scriptUri}" type="module"></script>
<div id="content"></div>
</body>
</html>`;
}
export class JavaRuntimeViewSerializer implements vscode.WebviewPanelSerializer {
async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, _state: any) {
if (javaRuntimeView) {
javaRuntimeView.reveal();
webviewPanel.dispose();
return;
}
javaRuntimeView = webviewPanel;
initializeJavaRuntimeView(getExtensionContext(), webviewPanel, onDidDisposeWebviewPanel);
}
}
export async function validateJavaRuntime() {
// TODO:
// option a) should check Java LS exported API for java_home
// * option b) use the same way to check java_home as vscode-java
try {
const runtime = await resolveRequirements();
if (runtime.tooling_jre_version >= REQUIRED_JDK_VERSION && runtime.tooling_jre) {
return true;
}
} catch (error) {
}
return false;
}
export async function findJavaRuntimeEntries(): Promise<{
javaRuntimes?: JavaRuntimeEntry[],
projectRuntimes?: ProjectRuntimeEntry[],
javaDotHome?: string;
javaHomeError?: string;
}> {
if (!javaHomes) {
const runtimes: IJavaRuntime[] = await findRuntimes({ checkJavac: true, withVersion: true });
javaHomes = runtimes.filter(r => r.hasJavac);
}
const javaRuntimes: JavaRuntimeEntry[] = javaHomes.map(elem => ({
name: elem.homedir,
fspath: elem.homedir,
majorVersion: elem.version?.major || 0,
type: "from jdk-utils"
})).sort((a, b) => b.majorVersion - a.majorVersion);
let javaDotHome;
let javaHomeError;
try {
const runtime = await resolveRequirements();
javaDotHome = runtime.tooling_jre;
const javaVersion = runtime.tooling_jre_version;
if (!javaVersion || javaVersion < REQUIRED_JDK_VERSION) {
javaHomeError = `Java ${REQUIRED_JDK_VERSION} or more recent is required by the Java language support (redhat.java) extension. Preferred JDK "${javaDotHome}" (version ${javaVersion}) doesn't meet the requirement. Please specify or install a recent JDK.`;
}
} catch (error) {
javaHomeError = (error as Error).message;
}
let projectRuntimes = await getProjectRuntimesFromPM();
if (_.isEmpty(projectRuntimes)) {
projectRuntimes = await getProjectRuntimesFromLS();
}
return {
javaRuntimes,
projectRuntimes,
javaDotHome,
javaHomeError
};
}
async function getProjectRuntimesFromPM(): Promise<ProjectRuntimeEntry[]> {
const ret: ProjectRuntimeEntry[] = [];
const projectManagerExt = vscode.extensions.getExtension("vscjava.vscode-java-dependency");
if (vscode.workspace.workspaceFolders && projectManagerExt && projectManagerExt.isActive) {
let projects: any[] = [];
for (const wf of vscode.workspace.workspaceFolders) {
try {
projects = await vscode.commands.executeCommand("java.execute.workspaceCommand", "java.project.list", wf.uri.toString()) || [];
} catch (error) {
console.error(error);
}
for (const project of projects) {
const runtimeSpec = await getRuntimeSpec(project.uri);
const projectType: ProjectType = getProjectType(vscode.Uri.parse(project.uri).fsPath, runtimeSpec.natureIds);
ret.push({
name: project.displayName || project.name,
rootPath: project.uri,
projectType,
...runtimeSpec
});
}
}
}
return ret;
}
async function getProjectRuntimesFromLS(): Promise<ProjectRuntimeEntry[]> {
const ret: ProjectRuntimeEntry[] = [];
const javaExt = vscode.extensions.getExtension("redhat.java");
if (javaExt && javaExt.isActive) {
let projects: string[] = [];
try {
projects = await vscode.commands.executeCommand("java.execute.workspaceCommand", "java.project.getAll") || [];
} catch (error) {
// LS not ready
}
for (const projectRoot of projects) {
const runtimeSpec = await getRuntimeSpec(projectRoot);
const projectType: ProjectType = await getProjectType(vscode.Uri.parse(projectRoot).fsPath, runtimeSpec.natureIds);
ret.push({
name: getProjectNameFromUri(projectRoot),
rootPath: projectRoot,
projectType: projectType,
...runtimeSpec
});
}
}
return ret;
}
async function getRuntimeSpec(projectRootUri: string) {
let natureIds;
let runtimePath;
let sourceLevel;
const javaExt = vscode.extensions.getExtension("redhat.java");
if (javaExt && javaExt.isActive) {
const NATURE_IDS = "org.eclipse.jdt.ls.core.natureIds";
const SOURCE_LEVEL_KEY = "org.eclipse.jdt.core.compiler.source";
const VM_INSTALL_PATH = "org.eclipse.jdt.ls.core.vm.location";
try {
const settings: any = await javaExt.exports.getProjectSettings(projectRootUri, [NATURE_IDS, SOURCE_LEVEL_KEY, VM_INSTALL_PATH]);
natureIds = settings[NATURE_IDS];
runtimePath = settings[VM_INSTALL_PATH];
sourceLevel = settings[SOURCE_LEVEL_KEY];
} catch (error) {
console.warn(error);
}
}
return {
natureIds,
runtimePath,
sourceLevel
};
}