-
Notifications
You must be signed in to change notification settings - Fork 441
/
extension.ts
1261 lines (1151 loc) · 50.8 KB
/
extension.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
import * as chokidar from 'chokidar';
import * as fs from 'fs';
import * as fse from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import * as semver from 'semver';
import { CodeActionContext, commands, CompletionItem, ConfigurationTarget, Diagnostic, env, EventEmitter, ExtensionContext, extensions, IndentAction, InputBoxOptions, languages, Location, MarkdownString, QuickPickItemKind, Range, RelativePattern, SnippetString, SnippetTextEdit, TextDocument, TextEditorRevealType, UIKind, Uri, ViewColumn, window, workspace, WorkspaceConfiguration, WorkspaceEdit } from 'vscode';
import { CancellationToken, CodeActionParams, CodeActionRequest, CodeActionResolveRequest, Command, CompletionRequest, DidChangeConfigurationNotification, ExecuteCommandParams, ExecuteCommandRequest, LanguageClientOptions, RevealOutputChannelOn } from 'vscode-languageclient';
import { LanguageClient } from 'vscode-languageclient/node';
import { apiManager } from './apiManager';
import { ClientErrorHandler } from './clientErrorHandler';
import { Commands, CommandTitle } from './commands';
import { ClientStatus, ExtensionAPI, TraceEvent } from './extension.api';
import * as fileEventHandler from './fileEventHandler';
import { getSharedIndexCache, HEAP_DUMP_LOCATION, prepareExecutable, removeEquinoxFragmentOnDarwinX64, startedFromSources } from './javaServerStarter';
import { initializeLogFile, logger } from './log';
import { cleanupLombokCache } from "./lombokSupport";
import { markdownPreviewProvider } from "./markdownPreviewProvider";
import { OutputInfoCollector } from './outputInfoCollector';
import { collectJavaExtensions, getBundlesToReload, getShortcuts, IJavaShortcut, isContributedPartUpdated } from './plugin';
import { fixJdtSchemeHoverLinks, registerClientProviders } from './providerDispatcher';
import * as requirements from './requirements';
import { languageStatusBarProvider } from './runtimeStatusBarProvider';
import { serverStatusBarProvider, ShortcutQuickPickItem } from './serverStatusBarProvider';
import { ACTIVE_BUILD_TOOL_STATE, cleanWorkspaceFileName, getJavaServerMode, handleTextDocumentChanges, getImportMode, onConfigurationChange, ServerMode, ImportMode } from './settings';
import { snippetCompletionProvider } from './snippetCompletionProvider';
import { JavaClassEditorProvider } from './javaClassEditor';
import { StandardLanguageClient } from './standardLanguageClient';
import { SyntaxLanguageClient } from './syntaxLanguageClient';
import { convertToGlob, deleteClientLog, deleteDirectory, ensureExists, getBuildFilePatterns, getExclusionGlob, getInclusionPatternsFromNegatedExclusion, getJavaConfig, getJavaConfiguration, hasBuildToolConflicts, resolveActualCause, getVersion } from './utils';
import glob = require('glob');
import { Telemetry } from './telemetry';
import { getMessage } from './errorUtils';
import { activationProgressNotification } from "./serverTaskPresenter";
import { loadSupportedJreNames } from './jdkUtils';
import { BuildFileSelector, PICKED_BUILD_FILES, cleanupWorkspaceState } from './buildFilesSelector';
import { pasteFile } from './pasteAction';
import { ServerStatusKind } from './serverStatus';
import { TelemetryService } from '@redhat-developer/vscode-redhat-telemetry/lib/node';
const syntaxClient: SyntaxLanguageClient = new SyntaxLanguageClient();
const standardClient: StandardLanguageClient = new StandardLanguageClient();
const jdtEventEmitter = new EventEmitter<Uri>();
const extensionName = 'Language Support for Java';
let storagePath: string;
let clientLogFile: string;
/**
* Shows a message about the server crashing due to an out of memory issue
*/
async function showOOMMessage(): Promise<void> {
const CONFIGURE = 'Increase Memory ..';
const result = await window.showErrorMessage('The Java Language Server encountered an OutOfMemory error. Some language features may not work due to limited memory. ',
CONFIGURE);
if (result === CONFIGURE) {
let jvmArgs: string = getJavaConfiguration().get('jdt.ls.vmargs');
const results = MAX_HEAP_SIZE_EXTRACTOR.exec(jvmArgs);
if (results && results[0]) {
const maxMemArg: string = results[0];
const maxMemValue: number = Number(results[1]);
const newMaxMemArg: string = maxMemArg.replace(maxMemValue.toString(), (maxMemValue * 2).toString());
jvmArgs = jvmArgs.replace(maxMemArg, newMaxMemArg);
await workspace.getConfiguration().update("java.jdt.ls.vmargs", jvmArgs, ConfigurationTarget.Workspace);
}
}
}
function getMaxMemFromConfiguration(includeUnit?: boolean): string | undefined {
const jvmArgs: string = getJavaConfiguration().get('jdt.ls.vmargs');
const results = includeUnit ? MAX_HEAP_SIZE_EXTRACTOR_WITH_UNIT.exec(jvmArgs)
: MAX_HEAP_SIZE_EXTRACTOR.exec(jvmArgs);
return results && results[0] ? results[1] : undefined;
}
const HEAP_DUMP_FOLDER_EXTRACTOR = new RegExp(`${HEAP_DUMP_LOCATION}(?:'([^']+)'|"([^"]+)"|([^\\s]+))`);
const MAX_HEAP_SIZE_EXTRACTOR = new RegExp(`-Xmx([0-9]+)[kKmMgG]`);
const MAX_HEAP_SIZE_EXTRACTOR_WITH_UNIT = new RegExp(`-Xmx([0-9]+[kKmMgG])`);
/**
* Returns the heap dump folder defined in the user's preferences, or undefined if the user does not set the heap dump folder
*
* @returns the heap dump folder defined in the user's preferences, or undefined if the user does not set the heap dump folder
*/
function getHeapDumpFolderFromSettings(): string {
const jvmArgs: string = getJavaConfiguration().get('jdt.ls.vmargs');
const results = HEAP_DUMP_FOLDER_EXTRACTOR.exec(jvmArgs);
if (!results || !results[0]) {
return undefined;
}
return results[1] || results[2] || results[3];
}
const REPLACE_JDT_LINKS_PATTERN: RegExp = /(\[(?:[^\]])+\]\()(jdt:\/\/(?:(?:(?:\\\))|([^)]))+))\)/g;
/**
* Replace `jdt://` links in the documentation with links that execute the VS Code command required to open the referenced file.
*
* Extracted from {@link fixJdtSchemeHoverLinks} for use in completion item documentation.
*
* @param oldDocumentation the documentation to fix the links in
* @returns the documentation with fixed links
*/
export function fixJdtLinksInDocumentation(oldDocumentation: MarkdownString): MarkdownString {
const newContent: string = oldDocumentation.value.replace(REPLACE_JDT_LINKS_PATTERN, (_substring, group1, group2) => {
const uri = `command:${Commands.OPEN_FILE}?${encodeURI(JSON.stringify([encodeURIComponent(group2)]))}`;
return `${group1}${uri})`;
});
const mdString = new MarkdownString(newContent);
mdString.isTrusted = true;
return mdString;
}
export async function activate(context: ExtensionContext): Promise<ExtensionAPI> {
await loadSupportedJreNames(context);
context.subscriptions.push(commands.registerCommand(Commands.FILESEXPLORER_ONPASTE, async () => {
const originalClipboard = await env.clipboard.readText();
// Hack in order to get path to selected folder if applicable (see https://github.com/microsoft/vscode/issues/3553#issuecomment-1098562676)
await commands.executeCommand('copyFilePath');
const folder = await env.clipboard.readText();
await env.clipboard.writeText(originalClipboard);
pasteFile(folder);
}));
context.subscriptions.push(markdownPreviewProvider);
context.subscriptions.push(commands.registerCommand(Commands.TEMPLATE_VARIABLES, async () => {
markdownPreviewProvider.show(context.asAbsolutePath(path.join('document', `${Commands.TEMPLATE_VARIABLES}.md`)), 'Predefined Variables', "", context);
}));
context.subscriptions.push(commands.registerCommand(Commands.NOT_COVERED_EXECUTION, async () => {
markdownPreviewProvider.show(context.asAbsolutePath(path.join('document', `_java.notCoveredExecution.md`)), 'Not Covered Maven Plugin Execution', "", context);
}));
storagePath = context.storagePath;
context.subscriptions.push(commands.registerCommand(Commands.METADATA_FILES_GENERATION, async () => {
markdownPreviewProvider.show(context.asAbsolutePath(path.join('document', `_java.metadataFilesGeneration.md`)), 'Metadata Files Generation', "", context);
}));
context.subscriptions.push(commands.registerCommand(Commands.LEARN_MORE_ABOUT_CLEAN_UPS, async () => {
markdownPreviewProvider.show(context.asAbsolutePath(path.join('document', `${Commands.LEARN_MORE_ABOUT_CLEAN_UPS}.md`)), 'Java Clean Ups', "java-clean-ups", context);
}));
if (!storagePath) {
storagePath = getTempWorkspace();
}
const workspacePath = path.resolve(`${storagePath}/jdt_ws`);
clientLogFile = path.join(storagePath, 'client.log');
const cleanWorkspaceExists = fs.existsSync(path.join(workspacePath, cleanWorkspaceFileName));
if (cleanWorkspaceExists) {
deleteClientLog(storagePath);
}
initializeLogFile(clientLogFile);
Telemetry.startTelemetry(context);
enableJavadocSymbols();
registerOutOfMemoryDetection(storagePath);
cleanJavaWorkspaceStorage();
if (!startedFromSources()) { // Dev mode: version may not match package.json, deleting the in-use folder
cleanOldGlobalStorage(context);
}
// https://github.com/redhat-developer/vscode-java/issues/3484
if (process.platform === 'darwin' && process.arch === 'x64') {
try {
if (semver.lt(os.release(), '20.0.0')) {
removeEquinoxFragmentOnDarwinX64(context);
}
} catch (error) {
// do nothing
}
}
return requirements.resolveRequirements(context).catch(error => {
// show error
window.showErrorMessage(error.message, error.label).then((selection) => {
if (error.label && error.label === selection && error.command) {
commands.executeCommand(error.command, error.commandParam);
}
});
// rethrow to disrupt the chain.
throw error;
}).then(async (requirements) => {
const triggerFiles = await getTriggerFiles();
return new Promise<ExtensionAPI>(async (resolve) => {
const syntaxServerWorkspacePath = path.resolve(`${storagePath}/ss_ws`);
let serverMode = getJavaServerMode();
const isWorkspaceTrusted = (workspace as any).isTrusted; // TODO: use workspace.isTrusted directly when other clients catch up to adopt 1.56.0
if (isWorkspaceTrusted !== undefined && !isWorkspaceTrusted) { // keep compatibility for old engines < 1.56.0
serverMode = ServerMode.lightWeight;
}
commands.executeCommand('setContext', 'java:serverMode', serverMode);
const isDebugModeByClientPort = !!process.env['SYNTAXLS_CLIENT_PORT'] || !!process.env['JDTLS_CLIENT_PORT'];
const requireSyntaxServer = (serverMode !== ServerMode.standard) && (!isDebugModeByClientPort || !!process.env['SYNTAXLS_CLIENT_PORT']);
let requireStandardServer = (serverMode !== ServerMode.lightWeight) && (!isDebugModeByClientPort || !!process.env['JDTLS_CLIENT_PORT']);
let initFailureReported: boolean = false;
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for java
documentSelector: [
{ scheme: 'file', language: 'java' },
{ scheme: 'jdt', language: 'java' },
{ scheme: 'untitled', language: 'java' }
],
synchronize: {
configurationSection: ['java', 'editor.insertSpaces', 'editor.tabSize', "files.associations"],
},
initializationOptions: {
bundles: collectJavaExtensions(extensions.all),
workspaceFolders: workspace.workspaceFolders ? workspace.workspaceFolders.map(f => f.uri.toString()) : null,
settings: { java: await getJavaConfig(requirements.java_home) },
extendedClientCapabilities: {
classFileContentsSupport: true,
overrideMethodsPromptSupport: true,
hashCodeEqualsPromptSupport: true,
advancedOrganizeImportsSupport: true,
generateToStringPromptSupport: true,
advancedGenerateAccessorsSupport: true,
generateConstructorsPromptSupport: true,
generateDelegateMethodsPromptSupport: true,
advancedExtractRefactoringSupport: true,
inferSelectionSupport: ["extractMethod", "extractVariable", "extractField"],
moveRefactoringSupport: true,
clientHoverProvider: true,
clientDocumentSymbolProvider: true,
gradleChecksumWrapperPromptSupport: true,
advancedIntroduceParameterRefactoringSupport: true,
actionableRuntimeNotificationSupport: true,
onCompletionItemSelectedCommand: "editor.action.triggerParameterHints",
extractInterfaceSupport: true,
advancedUpgradeGradleSupport: true,
executeClientCommandSupport: true,
snippetEditSupport: true,
},
triggerFiles,
},
middleware: {
workspace: {
didChangeConfiguration: async () => {
await standardClient.getClient().sendNotification(DidChangeConfigurationNotification.type, {
settings: {
java: await getJavaConfig(requirements.java_home),
}
});
}
},
resolveCompletionItem: async (item, token, next): Promise<CompletionItem> => {
const completionItem = await next(item, token);
if (completionItem.documentation instanceof MarkdownString) {
completionItem.documentation = fixJdtLinksInDocumentation(completionItem.documentation);
}
return completionItem;
},
// https://github.com/redhat-developer/vscode-java/issues/2130
// include all diagnostics for the current line in the CodeActionContext params for the performance reason
provideCodeActions: async (document, range, context, token, next) => {
const client: LanguageClient = standardClient.getClient();
const params: CodeActionParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range),
context: await client.code2ProtocolConverter.asCodeActionContext(context)
};
const showAt = getJavaConfiguration().get<string>("quickfix.showAt");
if (showAt === 'line' && range.start.line === range.end.line && range.start.character === range.end.character) {
const textLine = document.lineAt(params.range.start.line);
if (textLine !== null) {
const diagnostics = client.diagnostics.get(document.uri);
const allDiagnostics: Diagnostic[] = [];
for (const diagnostic of diagnostics) {
if (textLine.range.intersection(diagnostic.range)) {
const newLen = allDiagnostics.push(diagnostic);
if (newLen > 1000) {
break;
}
}
}
const codeActionContext: CodeActionContext = {
diagnostics: allDiagnostics,
only: context.only,
triggerKind: context.triggerKind,
};
params.context = await client.code2ProtocolConverter.asCodeActionContext(codeActionContext);
}
}
return client.sendRequest(CodeActionRequest.type, params, token).then(async (values) => {
if (values === null) {
return undefined;
}
const result = [];
for (const item of values) {
if (Command.is(item)) {
result.push(client.protocol2CodeConverter.asCommand(item));
}
else {
result.push(await client.protocol2CodeConverter.asCodeAction(item));
}
}
return result;
}, (error) => {
return client.handleFailedRequest(CodeActionRequest.type, token, error, []);
});
},
resolveCodeAction: async (item, token, next) => {
const client: LanguageClient = standardClient.getClient();
const documentUris = [];
const snippetEdits = [];
return client.sendRequest(CodeActionResolveRequest.type, client.code2ProtocolConverter.asCodeActionSync(item), token).then(async (result) => {
if (token.isCancellationRequested) {
return item;
}
const docChanges = result.edit !== undefined ? result.edit.documentChanges : undefined;
if (docChanges !== undefined) {
for (const docChange of docChanges) {
if ("textDocument" in docChange) {
for (const edit of docChange.edits) {
if ("snippet" in edit) {
documentUris.push(Uri.parse(docChange.textDocument.uri).toString());
snippetEdits.push(new SnippetTextEdit(client.protocol2CodeConverter.asRange((edit as any).range), new SnippetString((edit as any).snippet.value)));
}
}
}
}
const codeAction = await client.protocol2CodeConverter.asCodeAction(result, token);
const docEdits = codeAction.edit !== undefined? codeAction.edit.entries() : [];
for (const docEdit of docEdits) {
const uri = docEdit[0];
if (documentUris.includes(uri.toString())) {
const editList = [];
for (const edit of docEdit[1]) {
let isSnippet = false;
snippetEdits.forEach((snippet, index) => {
if (edit.range.isEqual(snippet.range) && documentUris[index] === uri.toString()) {
editList.push(snippet);
isSnippet = true;
}
});
if (!isSnippet) {
editList.push(edit);
}
}
codeAction.edit.set(uri, null);
codeAction.edit.set(uri, editList);
}
}
return codeAction;
}
return await client.protocol2CodeConverter.asCodeAction(result, token);
}, (error) => {
return client.handleFailedRequest(CodeActionResolveRequest.type, token, error, item);
});
},
provideReferences: async(document, position, options, token, next): Promise<Location[]> => {
// Override includeDeclaration from VS Code by allowing it to be configured
options.includeDeclaration = getJavaConfiguration().get('references.includeDeclarations');
return await next(document, position, options, token);
}
},
revealOutputChannelOn: RevealOutputChannelOn.Never,
errorHandler: new ClientErrorHandler(extensionName),
initializationFailedHandler: error => {
logger.error(`Failed to initialize ${extensionName} due to ${error && error.toString()}`);
if ((error.toString().includes('Connection') && error.toString().includes('disposed')) || error.toString().includes('Internal error')) {
if (!initFailureReported) {
apiManager.fireTraceEvent({
name: "java.client.error.initialization",
properties: {
message: error && error.toString(),
data: resolveActualCause(error?.data),
},
});
}
initFailureReported = true;
return false;
} else {
return true;
}
},
outputChannel: requireStandardServer ? new OutputInfoCollector(extensionName) : undefined,
outputChannelName: extensionName
};
apiManager.initialize(requirements, serverMode);
registerCodeCompletionTelemetryListener();
resolve(apiManager.getApiInstance());
// the promise is resolved
// no need to pass `resolve` into any code past this point,
// since `resolve` is a no-op from now on
const serverOptions = prepareExecutable(requirements, syntaxServerWorkspacePath, context, true);
if (requireSyntaxServer) {
if (process.env['SYNTAXLS_CLIENT_PORT']) {
syntaxClient.initialize(requirements, clientOptions);
} else {
syntaxClient.initialize(requirements, clientOptions, serverOptions);
}
syntaxClient.start().then(() => {
syntaxClient.registerSyntaxClientActions(serverOptions);
});
serverStatusBarProvider.showLightWeightStatus();
}
context.subscriptions.push(commands.registerCommand(Commands.EXECUTE_WORKSPACE_COMMAND, (command, ...rest) => {
const api: ExtensionAPI = apiManager.getApiInstance();
if (api.serverMode === ServerMode.lightWeight) {
console.warn(`The command: ${command} is not supported in LightWeight mode. See: https://github.com/redhat-developer/vscode-java/issues/1480`);
return;
}
let token: CancellationToken;
let commandArgs: any[] = rest;
if (rest && rest.length && CancellationToken.is(rest[rest.length - 1])) {
token = rest[rest.length - 1];
commandArgs = rest.slice(0, rest.length - 1);
}
const params: ExecuteCommandParams = {
command,
arguments: commandArgs
};
if (token) {
return standardClient.getClient().sendRequest(ExecuteCommandRequest.type, params, token);
} else {
return standardClient.getClient().sendRequest(ExecuteCommandRequest.type, params);
}
}));
if (cleanWorkspaceExists) {
const data = {};
try {
cleanupLombokCache(context);
cleanupWorkspaceState(context);
deleteDirectory(workspacePath);
deleteDirectory(syntaxServerWorkspacePath);
} catch (error) {
data['error'] = getMessage(error);
window.showErrorMessage(`Failed to delete ${workspacePath}: ${error}`);
}
await Telemetry.sendTelemetry(Commands.CLEAN_WORKSPACE, data);
}
// Register commands here to make it available even when the language client fails
context.subscriptions.push(commands.registerCommand(Commands.OPEN_STATUS_SHORTCUT, async (status: string) => {
const items: ShortcutQuickPickItem[] = [];
if (status === ServerStatusKind.error || status === ServerStatusKind.warning) {
commands.executeCommand("workbench.panel.markers.view.focus");
} else {
commands.executeCommand(Commands.SHOW_SERVER_TASK_STATUS, true);
}
items.push(...getShortcuts().map((shortcut: IJavaShortcut) => {
return {
label: shortcut.title,
command: shortcut.command,
args: shortcut.arguments,
};
}));
const choice = await window.showQuickPick(items);
if (!choice) {
return;
}
apiManager.fireTraceEvent({
name: "triggerShortcutCommand",
properties: {
message: choice.command,
},
});
if (choice.command) {
commands.executeCommand(choice.command, ...(choice.args || []));
}
}));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_SERVER_LOG, (column: ViewColumn) => openServerLogFile(storagePath, column)));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_SERVER_STDOUT_LOG, (column: ViewColumn) => openRollingServerLogFile(storagePath, '.out-jdt.ls', column)));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_SERVER_STDERR_LOG, (column: ViewColumn) => openRollingServerLogFile(storagePath, '.error-jdt.ls', column)));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_CLIENT_LOG, (column: ViewColumn) => openClientLogFile(clientLogFile, column)));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_LOGS, () => openLogs()));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_FORMATTER, async () => openFormatter(context.extensionPath)));
context.subscriptions.push(commands.registerCommand(Commands.OPEN_FILE, async (uri: string) => {
const parsedUri = Uri.parse(uri);
const editor = await window.showTextDocument(parsedUri);
// Reveal the document at the specified line, if possible (e.g. jumping to a specific javadoc method).
if (editor && parsedUri.scheme === 'jdt' && parsedUri.fragment) {
const line = parseInt(parsedUri.fragment);
if (isNaN(line) || line < 1 || line > editor.document.lineCount) {
return;
}
const range = editor.document.lineAt(line -1).range;
editor.revealRange(range, TextEditorRevealType.AtTop);
}
}));
context.subscriptions.push(commands.registerCommand(Commands.CLEAN_WORKSPACE, (force?: boolean) => cleanWorkspace(workspacePath, force)));
context.subscriptions.push(commands.registerCommand(Commands.CLEAN_SHARED_INDEXES, () => cleanSharedIndexes(context)));
context.subscriptions.push(commands.registerCommand(Commands.GET_WORKSPACE_PATH, () => workspacePath));
context.subscriptions.push(commands.registerCommand(Commands.REFRESH_BUNDLES_COMMAND, () => {
return getBundlesToReload();
}));
context.subscriptions.push(onConfigurationChange(workspacePath, context));
registerRestartJavaLanguageServerCommand(context);
/**
* Command to switch the server mode. Currently it only supports switch from lightweight to standard.
* @param force force to switch server mode without asking
*/
commands.registerCommand(Commands.SWITCH_SERVER_MODE, async (switchTo: ServerMode, force: boolean = false) => {
const isWorkspaceTrusted = (workspace as any).isTrusted;
if (isWorkspaceTrusted !== undefined && !isWorkspaceTrusted) { // keep compatibility for old engines < 1.56.0
const button = "Manage Workspace Trust";
const choice = await window.showInformationMessage("For security concern, Java language server cannot be switched to Standard mode in untrusted workspaces.", button);
if (choice === button) {
commands.executeCommand("workbench.trust.manage");
}
return;
}
const clientStatus: ClientStatus = standardClient.getClientStatus();
if (clientStatus === ClientStatus.starting || clientStatus === ClientStatus.started) {
return;
}
const api: ExtensionAPI = apiManager.getApiInstance();
if (!force && (api.serverMode === switchTo || api.serverMode === ServerMode.standard)) {
return;
}
let choice: string;
if (force) {
choice = "Yes";
} else {
choice = await window.showInformationMessage("Are you sure you want to switch the Java language server to Standard mode?", "Yes", "No");
}
if (choice === "Yes") {
await startStandardServer(context, requirements, clientOptions, workspacePath, true /* triggeredByCommand */);
}
});
context.subscriptions.push(commands.registerCommand(Commands.CHANGE_JAVA_SEARCH_SCOPE, async () => {
const selection = await window.showQuickPick(["all", "main"], {
canPickMany: false,
placeHolder: `Current: ${workspace.getConfiguration().get("java.search.scope")}`,
});
if(selection) {
workspace.getConfiguration().update("java.search.scope", selection, false);
}
}));
context.subscriptions.push(snippetCompletionProvider.initialize());
context.subscriptions.push(serverStatusBarProvider);
context.subscriptions.push(languageStatusBarProvider);
const classEditorProviderRegistration = window.registerCustomEditorProvider(JavaClassEditorProvider.viewType, new JavaClassEditorProvider(context));
context.subscriptions.push(classEditorProviderRegistration);
registerClientProviders(context, { contentProviderEvent: jdtEventEmitter.event });
apiManager.getApiInstance().onDidServerModeChange((event: ServerMode) => {
if (event === ServerMode.standard) {
syntaxClient.stop();
fileEventHandler.setServerStatus(true);
languageStatusBarProvider.initialize(context);
}
commands.executeCommand('setContext', 'java:serverMode', event);
});
if (serverMode === ServerMode.hybrid && !await fse.pathExists(path.join(workspacePath, ".metadata", ".plugins"))) {
const config = getJavaConfiguration();
const importOnStartupSection: string = "project.importOnFirstTimeStartup";
const importOnStartup = config.get(importOnStartupSection);
if (importOnStartup === "disabled" ||
env.uiKind === UIKind.Web && env.appName.includes("Visual Studio Code")) {
apiManager.getApiInstance().serverMode = ServerMode.lightWeight;
apiManager.fireDidServerModeChange(ServerMode.lightWeight);
requireStandardServer = false;
} else if (importOnStartup === "interactive" && await workspaceContainsBuildFiles()) {
apiManager.getApiInstance().serverMode = ServerMode.lightWeight;
apiManager.fireDidServerModeChange(ServerMode.lightWeight);
requireStandardServer = await promptUserForStandardServer(config);
} else {
requireStandardServer = true;
}
}
if (requireStandardServer) {
await startStandardServer(context, requirements, clientOptions, workspacePath);
}
const onDidGrantWorkspaceTrust = (workspace as any).onDidGrantWorkspaceTrust;
if (onDidGrantWorkspaceTrust !== undefined) { // keep compatibility for old engines < 1.56.0
context.subscriptions.push(onDidGrantWorkspaceTrust(() => {
if (getJavaServerMode() !== ServerMode.lightWeight) {
// See the issue https://github.com/redhat-developer/vscode-java/issues/1994
// Need to recollect the Java bundles before starting standard mode.
let pollingCount: number = 0;
// Poll every ~100ms (timeout after 1s) and check whether contributing javaExtensions have changed.
const intervalId = setInterval(() => {
const existingJavaExtensions = clientOptions.initializationOptions.bundles;
clientOptions.initializationOptions.bundles = collectJavaExtensions(extensions.all);
if (++pollingCount >= 10 || isContributedPartUpdated(existingJavaExtensions, clientOptions.initializationOptions.bundles)) {
clearInterval(intervalId);
commands.executeCommand(Commands.SWITCH_SERVER_MODE, ServerMode.standard, true);
return;
}
}, 100);
}
}));
}
context.subscriptions.push(workspace.onDidChangeTextDocument(event => handleTextDocumentChanges(event.document, event.contentChanges)));
});
});
}
async function startStandardServer(context: ExtensionContext, requirements: requirements.RequirementsData, clientOptions: LanguageClientOptions, workspacePath: string, triggeredByCommand: boolean = false) {
if (standardClient.getClientStatus() !== ClientStatus.uninitialized) {
return;
}
const selector: BuildFileSelector = new BuildFileSelector(context, []);
const importMode: ImportMode = await getImportMode(context, selector);
if (importMode === ImportMode.automatic) {
if (!await ensureNoBuildToolConflicts(context, clientOptions)) {
return;
}
} else {
const buildFiles: string[] = [];
if (importMode === ImportMode.manual) {
const cache = context.workspaceState.get<string[]>(PICKED_BUILD_FILES);
if (cache === undefined || cache.length === 0 && triggeredByCommand) {
buildFiles.push(...await selector.selectBuildFiles() || []);
} else {
buildFiles.push(...cache);
}
}
if (buildFiles.length === 0) {
commands.executeCommand('setContext', 'java:serverMode', ServerMode.lightWeight);
serverStatusBarProvider.showNotImportedStatus();
return;
}
clientOptions.initializationOptions.projectConfigurations = buildFiles;
}
if (apiManager.getApiInstance().serverMode === ServerMode.lightWeight) {
// Before standard server is ready, we are in hybrid.
apiManager.getApiInstance().serverMode = ServerMode.hybrid;
apiManager.fireDidServerModeChange(ServerMode.hybrid);
}
await standardClient.initialize(context, requirements, clientOptions, workspacePath, jdtEventEmitter);
standardClient.start().then(async () => {
standardClient.registerLanguageClientActions(context, await fse.pathExists(path.join(workspacePath, ".metadata", ".plugins")), jdtEventEmitter);
});
serverStatusBarProvider.setBusy("Activating...");
}
async function workspaceContainsBuildFiles(): Promise<boolean> {
// Since the VS Code API does not support put negated exclusion pattern in findFiles(), we need to first parse the
// negated exclusion to inclusion and do the search. (If negated exclusion pattern is set by user)
const inclusionPatterns: string[] = getBuildFilePatterns();
const inclusionPatternsFromNegatedExclusion: string[] = getInclusionPatternsFromNegatedExclusion();
if (inclusionPatterns.length > 0 && inclusionPatternsFromNegatedExclusion.length > 0 &&
(await workspace.findFiles(convertToGlob(inclusionPatterns, inclusionPatternsFromNegatedExclusion), null, 1 /* maxResults */)).length > 0) {
return true;
}
// Nothing found in negated exclusion pattern, do a normal search then.
const inclusionGlob: string = convertToGlob(inclusionPatterns);
const exclusionGlob: string = getExclusionGlob();
if (inclusionGlob && (await workspace.findFiles(inclusionGlob, exclusionGlob, 1 /* maxResults */)).length > 0) {
return true;
}
return false;
}
async function ensureNoBuildToolConflicts(context: ExtensionContext, clientOptions: LanguageClientOptions): Promise<boolean> {
const isMavenEnabled: boolean = getJavaConfiguration().get<boolean>("import.maven.enabled");
const isGradleEnabled: boolean = getJavaConfiguration().get<boolean>("import.gradle.enabled");
if (isMavenEnabled && isGradleEnabled) {
let activeBuildTool: string | undefined = context.workspaceState.get(ACTIVE_BUILD_TOOL_STATE);
if (!activeBuildTool) {
if (!await hasBuildToolConflicts()) {
return true;
}
activeBuildTool = await window.showInformationMessage("Build tool conflicts are detected in workspace. Which one would you like to use?", "Use Maven", "Use Gradle");
}
if (!activeBuildTool) {
return false; // user cancels
} else if (activeBuildTool.toLocaleLowerCase().includes("maven")) {
// Here we do not persist it in the settings to avoid generating/updating files in user's workspace
// Later if user want to change the active build tool, just directly set the related settings.
clientOptions.initializationOptions.settings.java.import.gradle.enabled = false;
context.workspaceState.update(ACTIVE_BUILD_TOOL_STATE, "maven");
} else if (activeBuildTool.toLocaleLowerCase().includes("gradle")) {
clientOptions.initializationOptions.settings.java.import.maven.enabled = false;
context.workspaceState.update(ACTIVE_BUILD_TOOL_STATE, "gradle");
} else {
throw new Error(`Unknown build tool: ${activeBuildTool}`); // unreachable
}
}
return true;
}
async function promptUserForStandardServer(config: WorkspaceConfiguration): Promise<boolean> {
const choice: string = await window.showInformationMessage("The workspace contains Java projects. Would you like to import them?", "Yes", "Always", "Later");
switch (choice) {
case "Always":
await config.update("project.importOnFirstTimeStartup", "automatic", ConfigurationTarget.Global);
return true;
case "Yes":
return true;
case "Later":
default:
const importHintSection: string = "project.importHint";
const dontShowAgain: string = "Don't Show Again";
const showHint: boolean = config.get(importHintSection);
if (showHint && standardClient.getClientStatus() === ClientStatus.uninitialized) {
const showRocketEmoji: boolean = process.platform === "win32" || process.platform === "darwin";
const message: string = `Java Language Server is running in LightWeight mode. Click the ${showRocketEmoji ? '🚀' : 'Rocket'} icon in the status bar if you want to import the projects later.`;
window.showInformationMessage(message, dontShowAgain)
.then(selection => {
if (selection && selection === dontShowAgain) {
config.update(importHintSection, false, ConfigurationTarget.Global);
}
});
}
return false;
}
}
export function deactivate(): Promise<void[]> {
return Promise.all<void>([
standardClient.stop(),
syntaxClient.stop(),
]);
}
export async function getActiveLanguageClient(): Promise<LanguageClient | undefined> {
let languageClient: LanguageClient;
const api: ExtensionAPI = apiManager.getApiInstance();
if (api.serverMode === ServerMode.standard) {
languageClient = standardClient.getClient();
} else {
languageClient = syntaxClient.getClient();
}
if (!languageClient) {
return undefined;
}
if (languageClient.needsStart()) {
await languageClient.start();
}
return languageClient;
}
function enableJavadocSymbols() {
// Let's enable Javadoc symbols autocompletion, shamelessly copied from MIT licensed code at
// https://github.com/Microsoft/vscode/blob/9d611d4dfd5a4a101b5201b8c9e21af97f06e7a7/extensions/typescript/src/typescriptMain.ts#L186
languages.setLanguageConfiguration('java', {
indentationRules: {
// ^(.*\*/)?\s*\}.*$
decreaseIndentPattern: /^(.*\*\/)?\s*\}.*$/,
// ^.*\{[^}"']*$
increaseIndentPattern: /^.*\{[^}"']*$/
},
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
onEnterRules: [
{
// e.g. /** | */ or /* | */
beforeText: /^\s*\/\*\*?(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: IndentAction.IndentOutdent, appendText: ' * ' }
},
{
// e.g. /** ...|
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: IndentAction.None, appendText: ' * ' }
},
{
// e.g. * ...|
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: IndentAction.None, appendText: '* ' }
},
{
// e.g. */|
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
},
{
// e.g. *-----*/|
beforeText: /^(\t|(\ \ ))*\ \*[^/]*\*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
},
{
// e.g. /// ...| (Markdown javadoc)
beforeText: /^\s*\/\/\/(.*)?$/,
action: { indentAction: IndentAction.None, appendText: '/// ' }
}
]
});
}
export function getTempWorkspace() {
return path.resolve(os.tmpdir(), `vscodesws_${makeRandomHexString(5)}`);
}
function makeRandomHexString(length) {
const chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
let result = '';
for (let i = 0; i < length; i++) {
const idx = Math.floor(chars.length * Math.random());
result += chars[idx];
}
return result;
}
async function cleanWorkspace(workspacePath, force?: boolean) {
if (!force) {
const doIt = 'Reload and delete';
const selection = await window.showWarningMessage('Are you sure you want to clean the Java language server workspace?', 'Cancel', doIt);
if (selection !== doIt) {
return;
}
}
ensureExists(workspacePath);
const file = path.join(workspacePath, cleanWorkspaceFileName);
fs.closeSync(fs.openSync(file, 'w'));
commands.executeCommand(Commands.RELOAD_WINDOW);
}
async function cleanSharedIndexes(context: ExtensionContext) {
const sharedIndexLocation: string = getSharedIndexCache(context);
if (sharedIndexLocation && fs.existsSync(sharedIndexLocation)) {
const doIt = 'Clean and Reload';
const ans = await window.showWarningMessage('The shared indexes might be in use by other workspaces, do you want to clear it? New indexes will be built after reloading.',
doIt, "Cancel");
if (ans === doIt) {
deleteDirectory(sharedIndexLocation);
commands.executeCommand(Commands.RELOAD_WINDOW);
}
}
}
function openServerLogFile(storagePath, column: ViewColumn = ViewColumn.Active): Thenable<boolean> {
const workspacePath = getWorkspacePath(storagePath);
const serverLogFile = path.join(workspacePath, '.metadata', '.log');
return openLogFile(serverLogFile, 'Could not open Java Language Server log file', column);
}
function getWorkspacePath(storagePath: any) {
return path.join(storagePath, apiManager.getApiInstance().serverMode === ServerMode.lightWeight ? 'ss_ws' : 'jdt_ws');
}
function openRollingServerLogFile(storagePath, filename, column: ViewColumn = ViewColumn.Active): Thenable<boolean> {
return new Promise((resolve) => {
const workspacePath = getWorkspacePath(storagePath);
const dirname = path.join(workspacePath, '.metadata');
// find out the newest one
glob(`${filename}-*`, { cwd: dirname }, (err, files) => {
if (!err && files.length > 0) {
files.sort();
const logFile = path.join(dirname, files[files.length - 1]);
openLogFile(logFile, `Could not open Java Language Server log file ${filename}`, column).then((result) => resolve(result));
} else {
resolve(false);
}
});
});
}
function openClientLogFile(logFile: string, column: ViewColumn = ViewColumn.Active): Thenable<boolean> {
return new Promise((resolve) => {
const filename = path.basename(logFile);
const dirname = path.dirname(logFile);
// find out the newest one
glob(`${filename}.*`, { cwd: dirname }, (err, files) => {
if (!err && files.length > 0) {
files.sort((a, b) => {
const dateA = a.slice(11, 21), dateB = b.slice(11, 21);
if (dateA === dateB) {
if (a.length > 22 && b.length > 22) {
const extA = a.slice(22), extB = b.slice(22);
return parseInt(extA) - parseInt(extB);
} else {
return a.length - b.length;
}
} else {
return dateA < dateB ? -1 : 1;
}
});
logFile = path.join(dirname, files[files.length - 1]);
}
openLogFile(logFile, 'Could not open Java extension log file', column).then((result) => resolve(result));
});
});
}
async function openLogs() {
await commands.executeCommand(Commands.OPEN_CLIENT_LOG, ViewColumn.One);
await commands.executeCommand(Commands.OPEN_SERVER_LOG, ViewColumn.One);
await commands.executeCommand(Commands.OPEN_SERVER_STDOUT_LOG, ViewColumn.One);
await commands.executeCommand(Commands.OPEN_SERVER_STDERR_LOG, ViewColumn.One);
const client = await getActiveLanguageClient();
client?.outputChannel.show(true);
}
function openLogFile(logFile, openingFailureWarning: string, column: ViewColumn = ViewColumn.Active): Thenable<boolean> {
if (!fs.existsSync(logFile)) {
return window.showWarningMessage('No log file available').then(() => false);
}
return workspace.openTextDocument(logFile)
.then(doc => {
if (!doc) {
return false;
}
return window.showTextDocument(doc, { viewColumn: column, preview: false })
.then(editor => !!editor);
}, () => false)
.then(didOpen => {
if (!didOpen) {
window.showWarningMessage(openingFailureWarning);
}
return didOpen;
});
}
async function openFormatter(extensionPath) {
const defaultFormatter = path.join(extensionPath, 'formatters', 'eclipse-formatter.xml');
const formatterUrl: string = getJavaConfiguration().get('format.settings.url');
if (formatterUrl && formatterUrl.length > 0) {
if (isRemote(formatterUrl)) {
return commands.executeCommand(Commands.OPEN_BROWSER, Uri.parse(formatterUrl));
} else {
const document = getPath(formatterUrl);
if (document && fs.existsSync(document)) {
return openDocument(extensionPath, document, defaultFormatter, null);
}
}
}
const global = workspace.workspaceFolders === undefined;
const fileName = formatterUrl || 'eclipse-formatter.xml';
let file;
let relativePath;
if (!global) {
file = path.join(workspace.workspaceFolders[0].uri.fsPath, fileName);
relativePath = fileName;
} else {
const root = path.join(extensionPath, '..', 'redhat.java');
ensureExists(root);
file = path.join(root, fileName);
}
if (!fs.existsSync(file)) {
addFormatter(extensionPath, file, defaultFormatter, relativePath);
} else {
if (formatterUrl) {
getJavaConfiguration().update('format.settings.url', (relativePath !== null ? relativePath : file), global);
openDocument(extensionPath, file, file, defaultFormatter);
} else {
addFormatter(extensionPath, file, defaultFormatter, relativePath);
}
}
}
function getPath(f) {
if (workspace.workspaceFolders && !path.isAbsolute(f)) {
workspace.workspaceFolders.forEach(wf => {
const file = path.resolve(wf.uri.path, f);
if (fs.existsSync(file)) {
return file;
}
});
} else {
return path.resolve(f);
}
return null;
}
function openDocument(extensionPath, formatterUrl, defaultFormatter, relativePath) {
return workspace.openTextDocument(formatterUrl)
.then(doc => {
if (!doc) {
addFormatter(extensionPath, formatterUrl, defaultFormatter, relativePath);