-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
extension.ts
1385 lines (1237 loc) · 60.2 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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import * as path from 'path';
import * as vscode from 'vscode';
import * as os from 'os';
import * as fs from 'fs';
import * as util from '../common';
import * as telemetry from '../telemetry';
import { TreeNode, NodeType } from './referencesModel';
import { UI, getUI } from './ui';
import { Client, openFileVersions } from './client';
import { ClientCollection } from './clientCollection';
import { CppSettings, OtherSettings } from './settings';
import { PersistentWorkspaceState, PersistentState } from './persistentState';
import { getLanguageConfig } from './languageConfig';
import { getCustomConfigProviders } from './customProviders';
import { PlatformInformation } from '../platform';
import { Range } from 'vscode-languageclient';
import { ChildProcess, spawn } from 'child_process';
import { getTargetBuildInfo, BuildInfo } from '../githubAPI';
import { PackageVersion } from '../packageVersion';
import { getTemporaryCommandRegistrarInstance } from '../commands';
import * as rd from 'readline';
import * as yauzl from 'yauzl';
import { Readable, Writable } from 'stream';
import * as nls from 'vscode-nls';
import { CppBuildTaskProvider } from './cppBuildTaskProvider';
import * as which from 'which';
import { IExperimentationService } from 'tas-client';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
export const cppBuildTaskProvider: CppBuildTaskProvider = new CppBuildTaskProvider();
let prevCrashFile: string;
let clients: ClientCollection;
let activeDocument: string;
let ui: UI;
const disposables: vscode.Disposable[] = [];
let languageConfigurations: vscode.Disposable[] = [];
let intervalTimer: NodeJS.Timer;
let insiderUpdateEnabled: boolean = false;
let insiderUpdateTimer: NodeJS.Timer;
const insiderUpdateTimerInterval: number = 1000 * 60 * 60;
let realActivationOccurred: boolean = false;
let tempCommands: vscode.Disposable[] = [];
let activatedPreviously: PersistentWorkspaceState<boolean>;
let buildInfoCache: BuildInfo | undefined;
const cppInstallVsixStr: string = 'C/C++: Install vsix -- ';
let taskProvider: vscode.Disposable;
let codeActionProvider: vscode.Disposable;
export const intelliSenseDisabledError: string = "Do not activate the extension when IntelliSense is disabled.";
type VcpkgDatabase = { [key: string]: string[] }; // Stored as <header file entry> -> [<port name>]
let vcpkgDbPromise: Promise<VcpkgDatabase>;
function initVcpkgDatabase(): Promise<VcpkgDatabase> {
return new Promise((resolve, reject) => {
yauzl.open(util.getExtensionFilePath('VCPkgHeadersDatabase.zip'), { lazyEntries: true }, (err?: Error, zipfile?: yauzl.ZipFile) => {
// Resolves with an empty database instead of rejecting on failure.
const database: VcpkgDatabase = {};
if (err || !zipfile) {
resolve(database);
return;
}
// Waits until the input file is closed before resolving.
zipfile.on('close', () => {
resolve(database);
});
zipfile.on('entry', entry => {
if (entry.fileName !== 'VCPkgHeadersDatabase.txt') {
zipfile.readEntry();
return;
}
zipfile.openReadStream(entry, (err?: Error, stream?: Readable) => {
if (err || !stream) {
zipfile.close();
return;
}
const reader: rd.ReadLine = rd.createInterface(stream);
reader.on('line', (lineText: string) => {
const portFilePair: string[] = lineText.split(':');
if (portFilePair.length !== 2) {
return;
}
const portName: string = portFilePair[0];
const relativeHeader: string = portFilePair[1];
if (!database[relativeHeader]) {
database[relativeHeader] = [];
}
database[relativeHeader].push(portName);
});
reader.on('close', () => {
// We found the one file we wanted.
// It's OK to close instead of progressing through more files in the zip.
zipfile.close();
});
});
});
zipfile.readEntry();
});
});
}
function getVcpkgHelpAction(): vscode.CodeAction {
const dummy: any[] = [{}]; // To distinguish between entry from CodeActions and the command palette
return {
command: { title: 'vcpkgOnlineHelpSuggested', command: 'C_Cpp.VcpkgOnlineHelpSuggested', arguments: dummy },
title: localize("learn.how.to.install.a.library", "Learn how to install a library for this header with vcpkg"),
kind: vscode.CodeActionKind.QuickFix
};
}
function getVcpkgClipboardInstallAction(port: string): vscode.CodeAction {
return {
command: { title: 'vcpkgClipboardInstallSuggested', command: 'C_Cpp.VcpkgClipboardInstallSuggested', arguments: [[port]] },
title: localize("copy.vcpkg.command", "Copy vcpkg command to install '{0}' to the clipboard", port),
kind: vscode.CodeActionKind.QuickFix
};
}
async function lookupIncludeInVcpkg(document: vscode.TextDocument, line: number): Promise<string[]> {
const matches: RegExpMatchArray | null = document.lineAt(line).text.match(/#include\s*[<"](?<includeFile>[^>"]*)[>"]/);
if (!matches || !matches.length || !matches.groups) {
return [];
}
const missingHeader: string = matches.groups['includeFile'].replace(/\//g, '\\');
let portsWithHeader: string[] | undefined;
const vcpkgDb: VcpkgDatabase = await vcpkgDbPromise;
if (vcpkgDb) {
portsWithHeader = vcpkgDb[missingHeader];
}
return portsWithHeader ? portsWithHeader : [];
}
function isMissingIncludeDiagnostic(diagnostic: vscode.Diagnostic): boolean {
const missingIncludeCode: number = 1696;
if (diagnostic.code === null || diagnostic.code === undefined || !diagnostic.source) {
return false;
}
return diagnostic.code === missingIncludeCode && diagnostic.source === 'C/C++';
}
/**
* activate: set up the extension for language services
*/
export async function activate(activationEventOccurred: boolean): Promise<void> {
if (realActivationOccurred) {
return; // Occurs if multiple delayed commands occur before the real commands are registered.
}
// Activate immediately if an activation event occurred in the previous workspace session.
// If onActivationEvent doesn't occur, it won't auto-activate next time.
activatedPreviously = new PersistentWorkspaceState("activatedPreviously", false);
if (activatedPreviously.Value) {
activatedPreviously.Value = false;
realActivation();
}
if (tempCommands.length === 0) { // Only needs to be added once.
tempCommands.push(vscode.workspace.onDidOpenTextDocument(onDidOpenTextDocument));
}
// handle "workspaceContains:/.vscode/c_cpp_properties.json" activation event.
let cppPropertiesExists: boolean = false;
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
for (let i: number = 0; i < vscode.workspace.workspaceFolders.length; ++i) {
const config: string = path.join(vscode.workspace.workspaceFolders[i].uri.fsPath, ".vscode/c_cpp_properties.json");
if (await util.checkFileExists(config)) {
cppPropertiesExists = true;
const doc: vscode.TextDocument = await vscode.workspace.openTextDocument(config);
vscode.languages.setTextDocumentLanguage(doc, "jsonc");
}
}
}
// Check if an activation event has already occurred.
if (activationEventOccurred) {
onActivationEvent();
return;
}
taskProvider = vscode.tasks.registerTaskProvider(CppBuildTaskProvider.CppBuildScriptType, cppBuildTaskProvider);
vscode.tasks.onDidStartTask(event => {
getActiveClient().PauseCodeAnalysis();
if (event.execution.task.definition.type === CppBuildTaskProvider.CppBuildScriptType
|| event.execution.task.name.startsWith(CppBuildTaskProvider.CppBuildSourceStr)) {
telemetry.logLanguageServerEvent('buildTaskStarted');
}
});
vscode.tasks.onDidEndTask(event => {
getActiveClient().ResumeCodeAnalysis();
if (event.execution.task.definition.type === CppBuildTaskProvider.CppBuildScriptType
|| event.execution.task.name.startsWith(CppBuildTaskProvider.CppBuildSourceStr)) {
telemetry.logLanguageServerEvent('buildTaskFinished');
if (event.execution.task.scope !== vscode.TaskScope.Global && event.execution.task.scope !== vscode.TaskScope.Workspace) {
const folder: vscode.WorkspaceFolder | undefined = event.execution.task.scope;
if (folder) {
const settings: CppSettings = new CppSettings(folder.uri);
if (settings.codeAnalysisRunOnBuild && settings.clangTidyEnabled) {
clients.getClientFor(folder.uri).handleRunCodeAnalysisOnAllFiles();
}
return;
}
}
const settings: CppSettings = new CppSettings();
if (settings.codeAnalysisRunOnBuild && settings.clangTidyEnabled) {
clients.ActiveClient.handleRunCodeAnalysisOnAllFiles();
}
}
});
const selector: vscode.DocumentSelector = [
{ scheme: 'file', language: 'c' },
{ scheme: 'file', language: 'cpp' },
{ scheme: 'file', language: 'cuda-cpp' }
];
codeActionProvider = vscode.languages.registerCodeActionsProvider(selector, {
provideCodeActions: async (document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): Promise<vscode.CodeAction[]> => {
if (!await clients.ActiveClient.getVcpkgEnabled()) {
return [];
}
// Generate vcpkg install/help commands if the incoming doc/range is a missing include error
if (!context.diagnostics.some(isMissingIncludeDiagnostic)) {
return [];
}
telemetry.logLanguageServerEvent('codeActionsProvided', { "source": "vcpkg" });
if (!await clients.ActiveClient.getVcpkgInstalled()) {
return [getVcpkgHelpAction()];
}
const ports: string[] = await lookupIncludeInVcpkg(document, range.start.line);
const actions: vscode.CodeAction[] = ports.map<vscode.CodeAction>(getVcpkgClipboardInstallAction);
return actions;
}
});
if (cppPropertiesExists) {
onActivationEvent();
return;
}
// handle "onLanguage:c", "onLanguage:cpp" and "onLanguage:cuda-cpp" activation events.
if (vscode.workspace.textDocuments !== undefined && vscode.workspace.textDocuments.length > 0) {
for (let i: number = 0; i < vscode.workspace.textDocuments.length; ++i) {
const document: vscode.TextDocument = vscode.workspace.textDocuments[i];
if (document.uri.scheme === "file") {
if (document.languageId === "c" || document.languageId === "cpp" || document.languageId === "cuda-cpp") {
onActivationEvent();
return;
}
}
}
}
}
function onDidOpenTextDocument(document: vscode.TextDocument): void {
if (document.languageId === "c" || document.languageId === "cpp" || document.languageId === "cuda-cpp") {
onActivationEvent();
}
}
function onActivationEvent(): void {
if (tempCommands.length === 0) {
return;
}
// Cancel all the temp commands that just look for activations.
tempCommands.forEach((command) => {
command.dispose();
});
tempCommands = [];
if (!realActivationOccurred) {
realActivation();
}
activatedPreviously.Value = true;
}
function sendActivationTelemetry(): void {
const activateEvent: { [key: string]: string } = {};
// Don't log telemetry for machineId if it's a special value used by the dev host: someValue.machineid
if (vscode.env.machineId !== "someValue.machineId") {
const machineIdPersistentState: PersistentState<string | undefined> = new PersistentState<string | undefined>("CPP.machineId", undefined);
if (!machineIdPersistentState.Value) {
activateEvent["newMachineId"] = vscode.env.machineId;
} else if (machineIdPersistentState.Value !== vscode.env.machineId) {
activateEvent["newMachineId"] = vscode.env.machineId;
activateEvent["oldMachineId"] = machineIdPersistentState.Value;
}
machineIdPersistentState.Value = vscode.env.machineId;
}
if (vscode.env.uiKind === vscode.UIKind.Web) {
activateEvent["WebUI"] = "1";
}
telemetry.logLanguageServerEvent("Activate", activateEvent);
}
function realActivation(): void {
if (new CppSettings((vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) ? vscode.workspace.workspaceFolders[0]?.uri : undefined).intelliSenseEngine === "Disabled") {
throw new Error(intelliSenseDisabledError);
} else {
console.log("activating extension");
sendActivationTelemetry();
const checkForConflictingExtensions: PersistentState<boolean> = new PersistentState<boolean>("CPP." + util.packageJson.version + ".checkForConflictingExtensions", true);
if (checkForConflictingExtensions.Value) {
checkForConflictingExtensions.Value = false;
const clangCommandAdapterActive: boolean = vscode.extensions.all.some((extension: vscode.Extension<any>, index: number, array: Readonly<vscode.Extension<any>[]>): boolean =>
extension.isActive && extension.id === "mitaki28.vscode-clang");
if (clangCommandAdapterActive) {
telemetry.logLanguageServerEvent("conflictingExtension");
}
}
}
realActivationOccurred = true;
console.log("starting language server");
clients = new ClientCollection();
ui = getUI();
// Log cold start.
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (activeEditor) {
clients.timeTelemetryCollector.setFirstFile(activeEditor.document.uri);
}
// There may have already been registered CustomConfigurationProviders.
// Request for configurations from those providers.
clients.forEach(client => {
getCustomConfigProviders().forEach(provider => client.onRegisterCustomConfigurationProvider(provider));
});
disposables.push(vscode.workspace.onDidChangeConfiguration(onDidChangeSettings));
disposables.push(vscode.window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor));
ui.activeDocumentChanged(); // Handle already active documents (for non-cpp files that we don't register didOpen).
disposables.push(vscode.window.onDidChangeTextEditorSelection(onDidChangeTextEditorSelection));
disposables.push(vscode.window.onDidChangeVisibleTextEditors(onDidChangeVisibleTextEditors));
updateLanguageConfigurations();
reportMacCrashes();
const settings: CppSettings = new CppSettings();
vcpkgDbPromise = initVcpkgDatabase();
PlatformInformation.GetPlatformInformation().then(async info => {
// Skip Insiders processing for 32-bit Linux.
if (info.platform !== "linux" || info.architecture === "x64" || info.architecture === "arm" || info.architecture === "arm64") {
// Skip Insiders processing for unsupported VS Code versions.
const experimentationService: IExperimentationService | undefined = await telemetry.getExperimentationService();
// If we can't get to the experimentation service, don't suggest Insiders.
if (experimentationService !== undefined) {
const allowInsiders: boolean | undefined = await experimentationService.getTreatmentVariableAsync<boolean>("vscode", "allowInsiders");
// If we can't get the minimum supported VS Code version for Insiders, don't suggest Insiders.
if (allowInsiders) {
insiderUpdateEnabled = true;
if (settings.updateChannel === 'Default') {
const userVersion: PackageVersion = new PackageVersion(util.packageJson.version);
if (userVersion.suffix === "insiders") {
checkAndApplyUpdate(settings.updateChannel, false);
} else {
suggestInsidersChannel();
}
} else if (settings.updateChannel === 'Insiders') {
insiderUpdateTimer = global.setInterval(checkAndApplyUpdateOnTimer, insiderUpdateTimerInterval);
checkAndApplyUpdate(settings.updateChannel, false);
}
}
}
}
});
clients.ActiveClient.notifyWhenLanguageClientReady(() => {
intervalTimer = global.setInterval(onInterval, 2500);
});
}
export function updateLanguageConfigurations(): void {
languageConfigurations.forEach(d => d.dispose());
languageConfigurations = [];
languageConfigurations.push(vscode.languages.setLanguageConfiguration('c', getLanguageConfig('c')));
languageConfigurations.push(vscode.languages.setLanguageConfiguration('cpp', getLanguageConfig('cpp')));
languageConfigurations.push(vscode.languages.setLanguageConfiguration('cuda-cpp', getLanguageConfig('cuda-cpp')));
}
/**
* workspace events
*/
function onDidChangeSettings(event: vscode.ConfigurationChangeEvent): void {
const activeClient: Client = clients.ActiveClient;
const changedActiveClientSettings: { [key: string]: string } = activeClient.onDidChangeSettings(event, true);
clients.forEach(client => {
if (client !== activeClient) {
client.onDidChangeSettings(event, false);
}
});
if (insiderUpdateEnabled) {
const newUpdateChannel: string = changedActiveClientSettings['updateChannel'];
if (newUpdateChannel) {
if (newUpdateChannel === 'Default') {
clearInterval(insiderUpdateTimer);
} else if (newUpdateChannel === 'Insiders') {
insiderUpdateTimer = global.setInterval(checkAndApplyUpdateOnTimer, insiderUpdateTimerInterval);
}
checkAndApplyUpdate(newUpdateChannel, true);
}
}
}
export function onDidChangeActiveTextEditor(editor?: vscode.TextEditor): void {
/* need to notify the affected client(s) */
console.assert(clients !== undefined, "client should be available before active editor is changed");
if (clients === undefined) {
return;
}
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!editor || !activeEditor || activeEditor.document.uri.scheme !== "file" || (activeEditor.document.languageId !== "c" && activeEditor.document.languageId !== "cpp" && activeEditor.document.languageId !== "cuda-cpp")) {
activeDocument = "";
} else {
activeDocument = editor.document.uri.toString();
clients.activeDocumentChanged(editor.document);
clients.ActiveClient.selectionChanged(Range.create(editor.selection.start, editor.selection.end));
}
ui.activeDocumentChanged();
}
function onDidChangeTextEditorSelection(event: vscode.TextEditorSelectionChangeEvent): void {
/* need to notify the affected client(s) */
if (!event.textEditor || !vscode.window.activeTextEditor || event.textEditor.document.uri !== vscode.window.activeTextEditor.document.uri ||
event.textEditor.document.uri.scheme !== "file" ||
(event.textEditor.document.languageId !== "cpp" && event.textEditor.document.languageId !== "c")) {
return;
}
if (activeDocument !== event.textEditor.document.uri.toString()) {
// For some unknown reason we don't reliably get onDidChangeActiveTextEditor callbacks.
activeDocument = event.textEditor.document.uri.toString();
clients.activeDocumentChanged(event.textEditor.document);
ui.activeDocumentChanged();
}
clients.ActiveClient.selectionChanged(Range.create(event.selections[0].start, event.selections[0].end));
}
export function processDelayedDidOpen(document: vscode.TextDocument): boolean {
const client: Client = clients.getClientFor(document.uri);
if (client) {
// Log warm start.
if (clients.checkOwnership(client, document)) {
if (!client.TrackedDocuments.has(document)) {
// If not yet tracked, process as a newly opened file. (didOpen is sent to server in client.takeOwnership()).
clients.timeTelemetryCollector.setDidOpenTime(document.uri);
client.TrackedDocuments.add(document);
const finishDidOpen = (doc: vscode.TextDocument) => {
client.provideCustomConfiguration(doc.uri, undefined);
client.notifyWhenLanguageClientReady(() => {
client.takeOwnership(doc);
client.onDidOpenTextDocument(doc);
});
};
let languageChanged: boolean = false;
// Work around vscode treating ".C" or ".H" as c, by adding this file name to file associations as cpp
if ((document.uri.path.endsWith(".C") || document.uri.path.endsWith(".H")) && document.languageId === "c") {
const cppSettings: CppSettings = new CppSettings();
if (cppSettings.autoAddFileAssociations) {
const fileName: string = path.basename(document.uri.fsPath);
const mappingString: string = fileName + "@" + document.uri.fsPath;
client.addFileAssociations(mappingString, "cpp");
client.sendDidChangeSettings({ files: { associations: new OtherSettings().filesAssociations }});
vscode.languages.setTextDocumentLanguage(document, "cpp").then((newDoc: vscode.TextDocument) => {
finishDidOpen(newDoc);
});
languageChanged = true;
}
}
if (!languageChanged) {
finishDidOpen(document);
}
return true;
}
}
}
return false;
}
function onDidChangeVisibleTextEditors(editors: vscode.TextEditor[]): void {
// Process delayed didOpen for any visible editors we haven't seen before
editors.forEach(editor => {
if ((editor.document.uri.scheme === "file") && (editor.document.languageId === "c" || editor.document.languageId === "cpp" || editor.document.languageId === "cuda-cpp")) {
if (!processDelayedDidOpen(editor.document)) {
const client: Client = clients.getClientFor(editor.document.uri);
client.onDidChangeVisibleTextEditor(editor);
}
}
});
}
function onInterval(): void {
// TODO: do we need to pump messages to all clients? depends on what we do with the icons, I suppose.
clients.ActiveClient.onInterval();
}
/**
* Install a VSIX package. This helper function will exist until VSCode offers a command to do so.
* @param updateChannel The user's updateChannel setting.
*/
async function installVsix(vsixLocation: string): Promise<void> {
const userVersion: PackageVersion = new PackageVersion(vscode.version);
// 1.33.0 introduces workbench.extensions.installExtension. 1.32.3 was immediately prior.
const lastVersionWithoutInstallExtensionCommand: PackageVersion = new PackageVersion('1.32.3');
if (userVersion.isVsCodeVersionGreaterThan(lastVersionWithoutInstallExtensionCommand)) {
return vscode.commands.executeCommand('workbench.extensions.installExtension', vscode.Uri.file(vsixLocation));
}
// Get the path to the VSCode command -- replace logic later when VSCode allows calling of
// workbench.extensions.action.installVSIX from TypeScript w/o instead popping up a file dialog
return PlatformInformation.GetPlatformInformation().then((platformInfo) => {
const getVsCodeScriptPath = (platformInfo: any): string => {
if (platformInfo.platform === 'win32') {
const vsCodeBinName: string = path.basename(process.execPath);
let cmdFile: string; // Windows VS Code Insiders/Exploration breaks VS Code naming conventions
if (vsCodeBinName === 'Code - Insiders.exe') {
cmdFile = 'code-insiders.cmd';
} else if (vsCodeBinName === 'Code - Exploration.exe') {
cmdFile = 'code-exploration.cmd';
} else {
cmdFile = 'code.cmd';
}
const vsCodeExeDir: string = path.dirname(process.execPath);
return path.join(vsCodeExeDir, 'bin', cmdFile);
} else if (platformInfo.platform === 'darwin') {
return path.join(process.execPath, '..', '..', '..', '..', '..',
'Resources', 'app', 'bin', 'code');
} else {
const vsCodeBinName: string = path.basename(process.execPath);
return which.sync(vsCodeBinName);
}
};
let vsCodeScriptPath: string;
try {
vsCodeScriptPath = getVsCodeScriptPath(platformInfo);
} catch (err) {
return Promise.reject(new Error('Failed to find VS Code script'));
}
// 1.28.0 changes the CLI for making installations. 1.27.2 was immediately prior.
const oldVersion: PackageVersion = new PackageVersion('1.27.2');
if (userVersion.isVsCodeVersionGreaterThan(oldVersion)) {
return new Promise<void>((resolve, reject) => {
let process: ChildProcess;
try {
process = spawn(vsCodeScriptPath, ['--install-extension', vsixLocation, '--force']);
// Timeout the process if no response is sent back. Ensures this Promise resolves/rejects
const timer: NodeJS.Timer = global.setTimeout(() => {
process.kill();
reject(new Error('Failed to receive response from VS Code script process for installation within 30s.'));
}, 30000);
process.on('exit', (code: number) => {
clearInterval(timer);
if (code !== 0) {
reject(new Error(`VS Code script exited with error code ${code}`));
} else {
resolve();
}
});
if (process.pid === undefined) {
throw new Error();
}
} catch (error) {
reject(new Error('Failed to launch VS Code script process for installation'));
return;
}
});
}
return new Promise<void>((resolve, reject) => {
let process: ChildProcess;
try {
process = spawn(vsCodeScriptPath, ['--install-extension', vsixLocation]);
if (process.pid === undefined) {
throw new Error();
}
} catch (error) {
reject(new Error('Failed to launch VS Code script process for installation'));
return;
}
// Timeout the process if no response is sent back. Ensures this Promise resolves/rejects
const timer: NodeJS.Timer = global.setTimeout(() => {
process.kill();
reject(new Error('Failed to receive response from VS Code script process for installation within 30s.'));
}, 30000);
// If downgrading, the VS Code CLI will prompt whether the user is sure they would like to downgrade.
// Respond to this by writing 0 to stdin (the option to override and install the VSIX package)
let sentOverride: boolean = false;
const stdout: Readable | null = process.stdout;
if (!stdout) {
reject(new Error("Failed to communicate with VS Code script process for installation"));
return;
}
stdout.on('data', () => {
if (sentOverride) {
return;
}
const stdin: Writable | null = process.stdin;
if (!stdin) {
reject(new Error("Failed to communicate with VS Code script process for installation"));
return;
}
stdin.write('0\n');
sentOverride = true;
clearInterval(timer);
resolve();
});
});
});
}
async function suggestInsidersChannel(): Promise<void> {
if (util.isCodespaces()) {
// Do not prompt users of Codespaces to join Insiders.
return;
}
const suggestInsiders: PersistentState<boolean> = new PersistentState<boolean>("CPP.suggestInsiders", true);
if (!suggestInsiders.Value) {
return;
}
const suggestInsidersCount: PersistentState<number> = new PersistentState<number>("CPP.suggestInsidersCount", 0);
if (suggestInsidersCount.Value < 10) {
suggestInsidersCount.Value = suggestInsidersCount.Value + 1;
return;
}
let buildInfo: BuildInfo | undefined;
try {
buildInfo = await getTargetBuildInfo("Insiders", false);
} catch (errJS) {
const error: Error = errJS as Error;
console.log(`${cppInstallVsixStr}${error.message}`);
if (error.message.indexOf('/') !== -1 || error.message.indexOf('\\') !== -1) {
error.message = "Potential PII hidden";
}
telemetry.logLanguageServerEvent('suggestInsiders', { 'error': error.message, 'success': 'false' });
}
if (!buildInfo) {
return; // No need to update.
}
const message: string = localize('insiders.available', "Insiders version {0} is available. Would you like to switch to the Insiders channel and install this update?", buildInfo.name);
const yes: string = localize("yes.button", "Yes");
const askLater: string = localize("ask.me.later.button", "Ask Me Later");
const dontShowAgain: string = localize("dont.show.again.button", "Don't Show Again");
vscode.window.showInformationMessage(message, yes, askLater, dontShowAgain).then((selection) => {
switch (selection) {
case yes:
// Cache buildInfo.
buildInfoCache = buildInfo;
// It will call onDidChangeSettings.
vscode.workspace.getConfiguration("C_Cpp").update("updateChannel", "Insiders", vscode.ConfigurationTarget.Global);
break;
case dontShowAgain:
suggestInsiders.Value = false;
break;
case askLater:
break;
default:
break;
}
});
}
async function applyUpdate(buildInfo: BuildInfo): Promise<void> {
let tempVSIX: any;
try {
tempVSIX = await util.createTempFileWithPostfix('.vsix');
// Try to download VSIX
const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration();
const originalProxySupport: string | undefined = config.inspect<string>('http.proxySupport')?.globalValue;
while (true) { // Might need to try again with a different http.proxySupport setting.
try {
await util.downloadFileToDestination(buildInfo.downloadUrl, tempVSIX.name);
} catch {
// Try again with the proxySupport to "off".
if (originalProxySupport !== config.inspect<string>('http.proxySupport')?.globalValue) {
config.update('http.proxySupport', originalProxySupport, true); // Reset the http.proxySupport.
throw new Error('Failed to download VSIX package with proxySupport off'); // Changing the proxySupport didn't help.
}
if (config.get('http.proxySupport') !== "off" && originalProxySupport !== "off") {
config.update('http.proxySupport', "off", true);
continue;
}
throw new Error('Failed to download VSIX package');
}
if (originalProxySupport !== config.inspect<string>('http.proxySupport')?.globalValue) {
config.update('http.proxySupport', originalProxySupport, true); // Reset the http.proxySupport.
telemetry.logLanguageServerEvent('installVsix', { 'error': "Success with proxySupport off", 'success': 'true' });
}
break;
}
// Install VSIX
try {
await installVsix(tempVSIX.name);
} catch (error) {
throw new Error('Failed to install VSIX package');
}
// Installation successful
clearInterval(insiderUpdateTimer);
const message: string = localize("extension.updated",
"The C/C++ Extension has been updated to version {0}. Please reload the window for the changes to take effect.",
buildInfo.name);
util.promptReloadWindow(message);
telemetry.logLanguageServerEvent('installVsix', { 'success': 'true' });
} catch (errJS) {
const error: Error = errJS as Error;
console.error(`${cppInstallVsixStr}${error.message}`);
if (error.message.indexOf('/') !== -1 || error.message.indexOf('\\') !== -1) {
error.message = "Potential PII hidden";
}
telemetry.logLanguageServerEvent('installVsix', { 'error': error.message, 'success': 'false' });
}
// Delete temp VSIX file
if (tempVSIX) {
tempVSIX.removeCallback();
}
}
async function checkAndApplyUpdateOnTimer(): Promise<void> {
return checkAndApplyUpdate('Insiders', false);
}
/**
* Query package.json and the GitHub API to determine whether the user should update, if so then install the update.
* The update can be an upgrade or downgrade depending on the the updateChannel setting.
* @param updateChannel The user's updateChannel setting.
* @param isFromSettingsChange True if the invocation is the result of a settings change.
*/
async function checkAndApplyUpdate(updateChannel: string, isFromSettingsChange: boolean): Promise<void> {
// If we have buildInfo cache, we should use it.
let buildInfo: BuildInfo | undefined = buildInfoCache;
// clear buildInfo cache.
buildInfoCache = undefined;
if (!buildInfo) {
try {
buildInfo = await getTargetBuildInfo(updateChannel, isFromSettingsChange);
} catch (errJS) {
const error: Error = errJS as Error;
telemetry.logLanguageServerEvent('installVsix', { 'error': error.message, 'success': 'false' });
}
}
if (!buildInfo) {
return; // No need to update.
}
await applyUpdate(buildInfo);
}
/**
* registered commands
*/
let commandsRegistered: boolean = false;
export function registerCommands(): void {
if (commandsRegistered) {
return;
}
commandsRegistered = true;
getTemporaryCommandRegistrarInstance().clearTempCommands();
disposables.push(vscode.commands.registerCommand('C_Cpp.SwitchHeaderSource', onSwitchHeaderSource));
disposables.push(vscode.commands.registerCommand('C_Cpp.ResetDatabase', onResetDatabase));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationSelect', onSelectConfiguration));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationProviderSelect', onSelectConfigurationProvider));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditJSON', onEditConfigurationJSON));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditUI', onEditConfigurationUI));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEdit', onEditConfiguration));
disposables.push(vscode.commands.registerCommand('C_Cpp.AddToIncludePath', onAddToIncludePath));
disposables.push(vscode.commands.registerCommand('C_Cpp.EnableErrorSquiggles', onEnableSquiggles));
disposables.push(vscode.commands.registerCommand('C_Cpp.DisableErrorSquiggles', onDisableSquiggles));
disposables.push(vscode.commands.registerCommand('C_Cpp.ToggleIncludeFallback', onToggleIncludeFallback));
disposables.push(vscode.commands.registerCommand('C_Cpp.ToggleDimInactiveRegions', onToggleDimInactiveRegions));
disposables.push(vscode.commands.registerCommand('C_Cpp.PauseParsing', onPauseParsing));
disposables.push(vscode.commands.registerCommand('C_Cpp.ResumeParsing', onResumeParsing));
disposables.push(vscode.commands.registerCommand('C_Cpp.PauseCodeAnalysis', onPauseCodeAnalysis));
disposables.push(vscode.commands.registerCommand('C_Cpp.ResumeCodeAnalysis', onResumeCodeAnalysis));
disposables.push(vscode.commands.registerCommand('C_Cpp.CancelCodeAnalysis', onCancelCodeAnalysis));
disposables.push(vscode.commands.registerCommand('C_Cpp.ShowParsingCommands', onShowParsingCommands));
disposables.push(vscode.commands.registerCommand('C_Cpp.ShowCodeAnalysisCommands', onShowCodeAnalysisCommands));
disposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferencesProgress', onShowReferencesProgress));
disposables.push(vscode.commands.registerCommand('C_Cpp.TakeSurvey', onTakeSurvey));
disposables.push(vscode.commands.registerCommand('C_Cpp.LogDiagnostics', onLogDiagnostics));
disposables.push(vscode.commands.registerCommand('C_Cpp.RescanWorkspace', onRescanWorkspace));
disposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferenceItem', onShowRefCommand));
disposables.push(vscode.commands.registerCommand('C_Cpp.referencesViewGroupByType', onToggleRefGroupView));
disposables.push(vscode.commands.registerCommand('C_Cpp.referencesViewUngroupByType', onToggleRefGroupView));
disposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgClipboardInstallSuggested', onVcpkgClipboardInstallSuggested));
disposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgOnlineHelpSuggested', onVcpkgOnlineHelpSuggested));
disposables.push(vscode.commands.registerCommand('C_Cpp.GenerateEditorConfig', onGenerateEditorConfig));
disposables.push(vscode.commands.registerCommand('C_Cpp.GoToNextDirectiveInGroup', onGoToNextDirectiveInGroup));
disposables.push(vscode.commands.registerCommand('C_Cpp.GoToPrevDirectiveInGroup', onGoToPrevDirectiveInGroup));
disposables.push(vscode.commands.registerCommand('C_Cpp.CheckForCompiler', onCheckForCompiler));
disposables.push(vscode.commands.registerCommand('C_Cpp.RunCodeAnalysisOnActiveFile', onRunCodeAnalysisOnActiveFile));
disposables.push(vscode.commands.registerCommand('C_Cpp.RunCodeAnalysisOnOpenFiles', onRunCodeAnalysisOnOpenFiles));
disposables.push(vscode.commands.registerCommand('C_Cpp.RunCodeAnalysisOnAllFiles', onRunCodeAnalysisOnAllFiles));
disposables.push(vscode.commands.registerCommand('C_Cpp.ClearCodeAnalysisSquiggles', onClearCodeAnalysisSquiggles));
disposables.push(vscode.commands.registerCommand('cpptools.activeConfigName', onGetActiveConfigName));
disposables.push(vscode.commands.registerCommand('cpptools.activeConfigCustomVariable', onGetActiveConfigCustomVariable));
disposables.push(vscode.commands.registerCommand('cpptools.setActiveConfigName', onSetActiveConfigName));
disposables.push(vscode.commands.registerCommand('C_Cpp.RestartIntelliSenseForFile', onRestartIntelliSenseForFile));
getTemporaryCommandRegistrarInstance().executeDelayedCommands();
}
function onRestartIntelliSenseForFile(): void {
onActivationEvent();
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!activeEditor || !activeEditor.document || activeEditor.document.uri.scheme !== "file" ||
(activeEditor.document.languageId !== "c" && activeEditor.document.languageId !== "cpp" && activeEditor.document.languageId !== "cuda-cpp")) {
return;
}
clients.ActiveClient.restartIntelliSenseForFile(activeEditor.document);
}
async function onSwitchHeaderSource(): Promise<void> {
onActivationEvent();
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!activeEditor || !activeEditor.document) {
return;
}
if (activeEditor.document.languageId !== "c" && activeEditor.document.languageId !== "cpp" && activeEditor.document.languageId !== "cuda-cpp") {
return;
}
let rootPath: string = clients.ActiveClient.RootPath;
const fileName: string = activeEditor.document.fileName;
if (!rootPath) {
rootPath = path.dirname(fileName); // When switching without a folder open.
}
let targetFileName: string = await clients.ActiveClient.requestSwitchHeaderSource(rootPath, fileName);
// If the targetFileName has a path that is a symlink target of a workspace folder,
// then replace the RootRealPath with the RootPath (the symlink path).
let targetFileNameReplaced: boolean = false;
clients.forEach(client => {
if (!targetFileNameReplaced && client.RootRealPath && client.RootPath !== client.RootRealPath
&& targetFileName.indexOf(client.RootRealPath) === 0) {
targetFileName = client.RootPath + targetFileName.substr(client.RootRealPath.length);
targetFileNameReplaced = true;
}
});
const document: vscode.TextDocument = await vscode.workspace.openTextDocument(targetFileName);
let foundEditor: boolean = false;
// If the document is already visible in another column, open it there.
vscode.window.visibleTextEditors.forEach((editor, index, array) => {
if (editor.document === document && !foundEditor) {
foundEditor = true;
vscode.window.showTextDocument(document, editor.viewColumn);
}
});
if (!foundEditor) {
vscode.window.showTextDocument(document);
}
}
/**
* Allow the user to select a workspace when multiple workspaces exist and get the corresponding Client back.
* The resulting client is used to handle some command that was previously invoked.
*/
async function selectClient(): Promise<Client> {
if (clients.Count === 1) {
return clients.ActiveClient;
} else {
const key: string = await ui.showWorkspaces(clients.Names);
if (key !== "") {
const client: Client | undefined = clients.get(key);
if (client) {
return client;
} else {
console.assert("client not found");
}
}
throw new Error(localize("client.not.found", "client not found"));
}
}
function onResetDatabase(): void {
onActivationEvent();
clients.ActiveClient.resetDatabase();
}
function onSelectConfiguration(): void {
onActivationEvent();
if (!isFolderOpen()) {
vscode.window.showInformationMessage(localize("configuration.select.first", 'Open a folder first to select a configuration'));
} else {
// This only applies to the active client. You cannot change the configuration for
// a client that is not active since that client's UI will not be visible.
clients.ActiveClient.handleConfigurationSelectCommand();
}
}
function onSelectConfigurationProvider(): void {
onActivationEvent();
if (!isFolderOpen()) {
vscode.window.showInformationMessage(localize("configuration.provider.select.first", 'Open a folder first to select a configuration provider'));
} else {
selectClient().then(client => client.handleConfigurationProviderSelectCommand(), rejected => {});
}
}
function onEditConfigurationJSON(viewColumn: vscode.ViewColumn = vscode.ViewColumn.Active): void {
onActivationEvent();
telemetry.logLanguageServerEvent("SettingsCommand", { "palette": "json" }, undefined);
if (!isFolderOpen()) {
vscode.window.showInformationMessage(localize('edit.configurations.open.first', 'Open a folder first to edit configurations'));
} else {
selectClient().then(client => client.handleConfigurationEditJSONCommand(viewColumn), rejected => {});
}
}
function onEditConfigurationUI(viewColumn: vscode.ViewColumn = vscode.ViewColumn.Active): void {
onActivationEvent();
telemetry.logLanguageServerEvent("SettingsCommand", { "palette": "ui" }, undefined);
if (!isFolderOpen()) {
vscode.window.showInformationMessage(localize('edit.configurations.open.first', 'Open a folder first to edit configurations'));
} else {
selectClient().then(client => client.handleConfigurationEditUICommand(viewColumn), rejected => {});
}
}
function onEditConfiguration(viewColumn: vscode.ViewColumn = vscode.ViewColumn.Active): void {
onActivationEvent();
if (!isFolderOpen()) {
vscode.window.showInformationMessage(localize('edit.configurations.open.first', 'Open a folder first to edit configurations'));
} else {
selectClient().then(client => client.handleConfigurationEditCommand(viewColumn), rejected => {});
}
}
function onGenerateEditorConfig(): void {
onActivationEvent();
if (!isFolderOpen()) {
const settings: CppSettings = new CppSettings();
settings.generateEditorConfig();
} else {
selectClient().then(client => {
const settings: CppSettings = new CppSettings(client.RootUri);
settings.generateEditorConfig();
});
}
}
function onGoToNextDirectiveInGroup(): void {
onActivationEvent();
const client: Client = getActiveClient();
client.handleGoToDirectiveInGroup(true);
}
function onGoToPrevDirectiveInGroup(): void {
onActivationEvent();
const client: Client = getActiveClient();
client.handleGoToDirectiveInGroup(false);
}
function onCheckForCompiler(): void {
onActivationEvent();
const client: Client = getActiveClient();
client.handleCheckForCompiler();
}
async function onRunCodeAnalysisOnActiveFile(): Promise<void> {
onActivationEvent();