-
Notifications
You must be signed in to change notification settings - Fork 39.7k
Expand file tree
/
Copy pathdeveloperActions.ts
More file actions
1006 lines (843 loc) · 37.7 KB
/
developerActions.ts
File metadata and controls
1006 lines (843 loc) · 37.7 KB
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.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import './media/actions.css';
import { localize, localize2 } from '../../../nls.js';
import { IKeybindingService } from '../../../platform/keybinding/common/keybinding.js';
import { DomEmitter } from '../../../base/browser/event.js';
import { Color } from '../../../base/common/color.js';
import { Emitter, Event } from '../../../base/common/event.js';
import { IDisposable, toDisposable, dispose, DisposableStore, setDisposableTracker, DisposableTracker, DisposableInfo } from '../../../base/common/lifecycle.js';
import { getDomNodePagePosition, append, $, getActiveDocument, onDidRegisterWindow, getWindows } from '../../../base/browser/dom.js';
import { createCSSRule, createStyleSheet } from '../../../base/browser/domStylesheets.js';
import { IConfigurationService } from '../../../platform/configuration/common/configuration.js';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from '../../../platform/contextkey/common/contextkey.js';
import { Context } from '../../../platform/contextkey/browser/contextKeyService.js';
import { StandardKeyboardEvent } from '../../../base/browser/keyboardEvent.js';
import { RunOnceScheduler } from '../../../base/common/async.js';
import { ILayoutService } from '../../../platform/layout/browser/layoutService.js';
import { Registry } from '../../../platform/registry/common/platform.js';
import { registerAction2, Action2, MenuRegistry } from '../../../platform/actions/common/actions.js';
import { IStorageService, StorageScope, StorageTarget } from '../../../platform/storage/common/storage.js';
import { clamp } from '../../../base/common/numbers.js';
import { KeyCode } from '../../../base/common/keyCodes.js';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from '../../../platform/configuration/common/configurationRegistry.js';
import { ILogService } from '../../../platform/log/common/log.js';
import { IWorkingCopyService } from '../../services/workingCopy/common/workingCopyService.js';
import { ServicesAccessor } from '../../../platform/instantiation/common/instantiation.js';
import { Categories } from '../../../platform/action/common/actionCommonCategories.js';
import { IWorkingCopyBackupService } from '../../services/workingCopy/common/workingCopyBackup.js';
import { ResolutionResult, ResultKind } from '../../../platform/keybinding/common/keybindingResolver.js';
import { IDialogService } from '../../../platform/dialogs/common/dialogs.js';
import { IOutputService } from '../../services/output/common/output.js';
import { windowLogId } from '../../services/log/common/logConstants.js';
import { ByteSize } from '../../../platform/files/common/files.js';
import { IQuickInputService, IQuickPickItem } from '../../../platform/quickinput/common/quickInput.js';
import { IUserDataProfileService } from '../../services/userDataProfile/common/userDataProfile.js';
import { IEditorService } from '../../services/editor/common/editorService.js';
import product from '../../../platform/product/common/product.js';
import { CommandsRegistry } from '../../../platform/commands/common/commands.js';
import { IEnvironmentService } from '../../../platform/environment/common/environment.js';
import { IProductService } from '../../../platform/product/common/productService.js';
import { IDefaultAccountService } from '../../services/accounts/common/defaultAccount.js';
import { IAuthenticationService } from '../../services/authentication/common/authentication.js';
import { IAuthenticationAccessService } from '../../services/authentication/browser/authenticationAccessService.js';
import { IPolicyService } from '../../../platform/policy/common/policy.js';
class InspectContextKeysAction extends Action2 {
constructor() {
super({
id: 'workbench.action.inspectContextKeys',
title: localize2('inspect context keys', 'Inspect Context Keys'),
category: Categories.Developer,
f1: true
});
}
run(accessor: ServicesAccessor): void {
const contextKeyService = accessor.get(IContextKeyService);
const disposables = new DisposableStore();
const stylesheet = createStyleSheet(undefined, undefined, disposables);
createCSSRule('*', 'cursor: crosshair !important;', stylesheet);
const hoverFeedback = document.createElement('div');
const activeDocument = getActiveDocument();
activeDocument.body.appendChild(hoverFeedback);
disposables.add(toDisposable(() => hoverFeedback.remove()));
hoverFeedback.style.position = 'absolute';
hoverFeedback.style.pointerEvents = 'none';
hoverFeedback.style.backgroundColor = 'rgba(255, 0, 0, 0.5)';
hoverFeedback.style.zIndex = '1000';
const onMouseMove = disposables.add(new DomEmitter(activeDocument, 'mousemove', true));
disposables.add(onMouseMove.event(e => {
const target = e.target as HTMLElement;
const position = getDomNodePagePosition(target);
hoverFeedback.style.top = `${position.top}px`;
hoverFeedback.style.left = `${position.left}px`;
hoverFeedback.style.width = `${position.width}px`;
hoverFeedback.style.height = `${position.height}px`;
}));
const onMouseDown = disposables.add(new DomEmitter(activeDocument, 'mousedown', true));
Event.once(onMouseDown.event)(e => { e.preventDefault(); e.stopPropagation(); }, null, disposables);
const onMouseUp = disposables.add(new DomEmitter(activeDocument, 'mouseup', true));
Event.once(onMouseUp.event)(e => {
e.preventDefault();
e.stopPropagation();
const context = contextKeyService.getContext(e.target as HTMLElement) as Context;
console.log(context.collectAllValues());
dispose(disposables);
}, null, disposables);
}
}
interface IScreencastKeyboardOptions {
readonly showKeys?: boolean;
readonly showKeybindings?: boolean;
readonly showCommands?: boolean;
readonly showCommandGroups?: boolean;
readonly showSingleEditorCursorMoves?: boolean;
}
class ToggleScreencastModeAction extends Action2 {
static disposable: IDisposable | undefined;
constructor() {
super({
id: 'workbench.action.toggleScreencastMode',
title: localize2('toggle screencast mode', 'Toggle Screencast Mode'),
category: Categories.Developer,
f1: true
});
}
run(accessor: ServicesAccessor): void {
if (ToggleScreencastModeAction.disposable) {
ToggleScreencastModeAction.disposable.dispose();
ToggleScreencastModeAction.disposable = undefined;
return;
}
const layoutService = accessor.get(ILayoutService);
const configurationService = accessor.get(IConfigurationService);
const keybindingService = accessor.get(IKeybindingService);
const disposables = new DisposableStore();
const container = layoutService.activeContainer;
const mouseMarker = append(container, $('.screencast-mouse'));
disposables.add(toDisposable(() => mouseMarker.remove()));
const keyboardMarker = append(container, $('.screencast-keyboard'));
disposables.add(toDisposable(() => keyboardMarker.remove()));
const onMouseDown = disposables.add(new Emitter<MouseEvent>());
const onMouseUp = disposables.add(new Emitter<MouseEvent>());
const onMouseMove = disposables.add(new Emitter<MouseEvent>());
function registerContainerListeners(container: HTMLElement, disposables: DisposableStore): void {
disposables.add(disposables.add(new DomEmitter(container, 'mousedown', true)).event(e => onMouseDown.fire(e)));
disposables.add(disposables.add(new DomEmitter(container, 'mouseup', true)).event(e => onMouseUp.fire(e)));
disposables.add(disposables.add(new DomEmitter(container, 'mousemove', true)).event(e => onMouseMove.fire(e)));
}
for (const { window, disposables } of getWindows()) {
registerContainerListeners(layoutService.getContainer(window), disposables);
}
disposables.add(onDidRegisterWindow(({ window, disposables }) => registerContainerListeners(layoutService.getContainer(window), disposables)));
disposables.add(layoutService.onDidChangeActiveContainer(() => {
layoutService.activeContainer.appendChild(mouseMarker);
layoutService.activeContainer.appendChild(keyboardMarker);
}));
const updateMouseIndicatorColor = () => {
mouseMarker.style.borderColor = Color.fromHex(configurationService.getValue<string>('screencastMode.mouseIndicatorColor')).toString();
};
let mouseIndicatorSize: number;
const updateMouseIndicatorSize = () => {
mouseIndicatorSize = clamp(configurationService.getValue<number>('screencastMode.mouseIndicatorSize') || 20, 20, 100);
mouseMarker.style.height = `${mouseIndicatorSize}px`;
mouseMarker.style.width = `${mouseIndicatorSize}px`;
};
updateMouseIndicatorColor();
updateMouseIndicatorSize();
disposables.add(onMouseDown.event(e => {
mouseMarker.style.top = `${e.clientY - mouseIndicatorSize / 2}px`;
mouseMarker.style.left = `${e.clientX - mouseIndicatorSize / 2}px`;
mouseMarker.style.display = 'block';
mouseMarker.style.transform = `scale(${1})`;
mouseMarker.style.transition = 'transform 0.1s';
const mouseMoveListener = onMouseMove.event(e => {
mouseMarker.style.top = `${e.clientY - mouseIndicatorSize / 2}px`;
mouseMarker.style.left = `${e.clientX - mouseIndicatorSize / 2}px`;
mouseMarker.style.transform = `scale(${.8})`;
});
Event.once(onMouseUp.event)(() => {
mouseMarker.style.display = 'none';
mouseMoveListener.dispose();
});
}));
const updateKeyboardFontSize = () => {
keyboardMarker.style.fontSize = `${clamp(configurationService.getValue<number>('screencastMode.fontSize') || 56, 20, 100)}px`;
};
const updateKeyboardMarker = () => {
keyboardMarker.style.bottom = `${clamp(configurationService.getValue<number>('screencastMode.verticalOffset') || 0, 0, 90)}%`;
};
let keyboardMarkerTimeout!: number;
const updateKeyboardMarkerTimeout = () => {
keyboardMarkerTimeout = clamp(configurationService.getValue<number>('screencastMode.keyboardOverlayTimeout') || 800, 500, 5000);
};
updateKeyboardFontSize();
updateKeyboardMarker();
updateKeyboardMarkerTimeout();
disposables.add(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('screencastMode.verticalOffset')) {
updateKeyboardMarker();
}
if (e.affectsConfiguration('screencastMode.fontSize')) {
updateKeyboardFontSize();
}
if (e.affectsConfiguration('screencastMode.keyboardOverlayTimeout')) {
updateKeyboardMarkerTimeout();
}
if (e.affectsConfiguration('screencastMode.mouseIndicatorColor')) {
updateMouseIndicatorColor();
}
if (e.affectsConfiguration('screencastMode.mouseIndicatorSize')) {
updateMouseIndicatorSize();
}
}));
const onKeyDown = disposables.add(new Emitter<KeyboardEvent>());
const onCompositionStart = disposables.add(new Emitter<CompositionEvent>());
const onCompositionUpdate = disposables.add(new Emitter<CompositionEvent>());
const onCompositionEnd = disposables.add(new Emitter<CompositionEvent>());
function registerWindowListeners(window: Window, disposables: DisposableStore): void {
disposables.add(disposables.add(new DomEmitter(window, 'keydown', true)).event(e => onKeyDown.fire(e)));
disposables.add(disposables.add(new DomEmitter(window, 'compositionstart', true)).event(e => onCompositionStart.fire(e)));
disposables.add(disposables.add(new DomEmitter(window, 'compositionupdate', true)).event(e => onCompositionUpdate.fire(e)));
disposables.add(disposables.add(new DomEmitter(window, 'compositionend', true)).event(e => onCompositionEnd.fire(e)));
}
for (const { window, disposables } of getWindows()) {
registerWindowListeners(window, disposables);
}
disposables.add(onDidRegisterWindow(({ window, disposables }) => registerWindowListeners(window, disposables)));
let length = 0;
let composing: Element | undefined = undefined;
let imeBackSpace = false;
const clearKeyboardScheduler = new RunOnceScheduler(() => {
keyboardMarker.textContent = '';
composing = undefined;
length = 0;
}, keyboardMarkerTimeout);
disposables.add(onCompositionStart.event(e => {
imeBackSpace = true;
}));
disposables.add(onCompositionUpdate.event(e => {
if (e.data && imeBackSpace) {
if (length > 20) {
keyboardMarker.innerText = '';
length = 0;
}
composing = composing ?? append(keyboardMarker, $('span.key'));
composing.textContent = e.data;
} else if (imeBackSpace) {
keyboardMarker.innerText = '';
append(keyboardMarker, $('span.key', {}, `Backspace`));
}
clearKeyboardScheduler.schedule();
}));
disposables.add(onCompositionEnd.event(e => {
composing = undefined;
length++;
}));
disposables.add(onKeyDown.event(e => {
if (e.key === 'Process' || /[\uac00-\ud787\u3131-\u314e\u314f-\u3163\u3041-\u3094\u30a1-\u30f4\u30fc\u3005\u3006\u3024\u4e00-\u9fa5]/u.test(e.key)) {
if (e.code === 'Backspace') {
imeBackSpace = true;
} else if (!e.code.includes('Key')) {
composing = undefined;
imeBackSpace = false;
} else {
imeBackSpace = true;
}
clearKeyboardScheduler.schedule();
return;
}
if (e.isComposing) {
return;
}
const options = configurationService.getValue<IScreencastKeyboardOptions>('screencastMode.keyboardOptions');
const event = new StandardKeyboardEvent(e);
const shortcut = keybindingService.softDispatch(event, event.target);
// Hide the single arrow key pressed
if (shortcut.kind === ResultKind.KbFound && shortcut.commandId && !(options.showSingleEditorCursorMoves ?? true) && (
['cursorLeft', 'cursorRight', 'cursorUp', 'cursorDown'].includes(shortcut.commandId))
) {
return;
}
if (
event.ctrlKey || event.altKey || event.metaKey || event.shiftKey
|| length > 20
|| event.keyCode === KeyCode.Backspace || event.keyCode === KeyCode.Escape
|| event.keyCode === KeyCode.UpArrow || event.keyCode === KeyCode.DownArrow
|| event.keyCode === KeyCode.LeftArrow || event.keyCode === KeyCode.RightArrow
) {
keyboardMarker.innerText = '';
length = 0;
}
const keybinding = keybindingService.resolveKeyboardEvent(event);
const commandDetails = (this._isKbFound(shortcut) && shortcut.commandId) ? this.getCommandDetails(shortcut.commandId) : undefined;
let commandAndGroupLabel = commandDetails?.title;
let keyLabel: string | undefined | null = keybinding.getLabel();
if (commandDetails) {
if ((options.showCommandGroups ?? false) && commandDetails.category) {
commandAndGroupLabel = `${commandDetails.category}: ${commandAndGroupLabel} `;
}
if (this._isKbFound(shortcut) && shortcut.commandId) {
const keybindings = keybindingService.lookupKeybindings(shortcut.commandId)
.filter(k => k.getLabel()?.endsWith(keyLabel ?? ''));
if (keybindings.length > 0) {
keyLabel = keybindings[keybindings.length - 1].getLabel();
}
}
}
if ((options.showCommands ?? true) && commandAndGroupLabel) {
append(keyboardMarker, $('span.title', {}, `${commandAndGroupLabel} `));
}
if ((options.showKeys ?? true) || ((options.showKeybindings ?? true) && this._isKbFound(shortcut))) {
// Fix label for arrow keys
keyLabel = keyLabel?.replace('UpArrow', '↑')
?.replace('DownArrow', '↓')
?.replace('LeftArrow', '←')
?.replace('RightArrow', '→');
append(keyboardMarker, $('span.key', {}, keyLabel ?? ''));
}
length++;
clearKeyboardScheduler.schedule();
}));
ToggleScreencastModeAction.disposable = disposables;
}
private _isKbFound(resolutionResult: ResolutionResult): resolutionResult is { kind: ResultKind.KbFound; commandId: string | null; commandArgs: unknown; isBubble: boolean } {
return resolutionResult.kind === ResultKind.KbFound;
}
private getCommandDetails(commandId: string): { title: string; category?: string } | undefined {
const fromMenuRegistry = MenuRegistry.getCommand(commandId);
if (fromMenuRegistry) {
return {
title: typeof fromMenuRegistry.title === 'string' ? fromMenuRegistry.title : fromMenuRegistry.title.value,
category: fromMenuRegistry.category ? (typeof fromMenuRegistry.category === 'string' ? fromMenuRegistry.category : fromMenuRegistry.category.value) : undefined
};
}
const fromCommandsRegistry = CommandsRegistry.getCommand(commandId);
if (fromCommandsRegistry?.metadata?.description) {
return { title: typeof fromCommandsRegistry.metadata.description === 'string' ? fromCommandsRegistry.metadata.description : fromCommandsRegistry.metadata.description.value };
}
return undefined;
}
}
class LogStorageAction extends Action2 {
constructor() {
super({
id: 'workbench.action.logStorage',
title: localize2({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, "Log Storage Database Contents"),
category: Categories.Developer,
f1: true
});
}
run(accessor: ServicesAccessor): void {
const storageService = accessor.get(IStorageService);
const dialogService = accessor.get(IDialogService);
storageService.log();
dialogService.info(localize('storageLogDialogMessage', "The storage database contents have been logged to the developer tools."), localize('storageLogDialogDetails', "Open developer tools from the menu and select the Console tab."));
}
}
class LogWorkingCopiesAction extends Action2 {
constructor() {
super({
id: 'workbench.action.logWorkingCopies',
title: localize2({ key: 'logWorkingCopies', comment: ['A developer only action to log the working copies that exist.'] }, "Log Working Copies"),
category: Categories.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const workingCopyService = accessor.get(IWorkingCopyService);
const workingCopyBackupService = accessor.get(IWorkingCopyBackupService);
const logService = accessor.get(ILogService);
const outputService = accessor.get(IOutputService);
const backups = await workingCopyBackupService.getBackups();
const msg = [
``,
`[Working Copies]`,
...(workingCopyService.workingCopies.length > 0) ?
workingCopyService.workingCopies.map(workingCopy => `${workingCopy.isDirty() ? '● ' : ''}${workingCopy.resource.toString(true)} (typeId: ${workingCopy.typeId || '<no typeId>'})`) :
['<none>'],
``,
`[Backups]`,
...(backups.length > 0) ?
backups.map(backup => `${backup.resource.toString(true)} (typeId: ${backup.typeId || '<no typeId>'})`) :
['<none>'],
];
logService.info(msg.join('\n'));
outputService.showChannel(windowLogId, true);
}
}
class RemoveLargeStorageEntriesAction extends Action2 {
private static SIZE_THRESHOLD = 1024 * 16; // 16kb
constructor() {
super({
id: 'workbench.action.removeLargeStorageDatabaseEntries',
title: localize2('removeLargeStorageDatabaseEntries', 'Remove Large Storage Database Entries...'),
category: Categories.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const storageService = accessor.get(IStorageService);
const quickInputService = accessor.get(IQuickInputService);
const userDataProfileService = accessor.get(IUserDataProfileService);
const dialogService = accessor.get(IDialogService);
const environmentService = accessor.get(IEnvironmentService);
interface IStorageItem extends IQuickPickItem {
readonly key: string;
readonly scope: StorageScope;
readonly target: StorageTarget;
readonly size: number;
}
const items: IStorageItem[] = [];
for (const scope of [StorageScope.APPLICATION, StorageScope.PROFILE, StorageScope.WORKSPACE]) {
if (scope === StorageScope.PROFILE && userDataProfileService.currentProfile.isDefault) {
continue; // avoid duplicates
}
for (const target of [StorageTarget.MACHINE, StorageTarget.USER]) {
for (const key of storageService.keys(scope, target)) {
const value = storageService.get(key, scope);
if (value && (!environmentService.isBuilt /* show all keys in dev */ || value.length > RemoveLargeStorageEntriesAction.SIZE_THRESHOLD)) {
items.push({
key,
scope,
target,
size: value.length,
label: key,
description: ByteSize.formatSize(value.length),
detail: localize('largeStorageItemDetail', "Scope: {0}, Target: {1}", scope === StorageScope.APPLICATION ? localize('global', "Global") : scope === StorageScope.PROFILE ? localize('profile', "Profile") : localize('workspace', "Workspace"), target === StorageTarget.MACHINE ? localize('machine', "Machine") : localize('user', "User")),
});
}
}
}
}
items.sort((itemA, itemB) => itemB.size - itemA.size);
const selectedItems = await new Promise<readonly IStorageItem[]>(resolve => {
const disposables = new DisposableStore();
const picker = disposables.add(quickInputService.createQuickPick<IStorageItem>());
picker.items = items;
picker.canSelectMany = true;
picker.ok = false;
picker.customButton = true;
picker.hideCheckAll = true;
picker.customLabel = localize('removeLargeStorageEntriesPickerButton', "Remove");
picker.placeholder = localize('removeLargeStorageEntriesPickerPlaceholder', "Select large entries to remove from storage");
if (items.length === 0) {
picker.description = localize('removeLargeStorageEntriesPickerDescriptionNoEntries', "There are no large storage entries to remove.");
}
picker.show();
disposables.add(picker.onDidCustom(() => {
resolve(picker.selectedItems);
picker.hide();
}));
disposables.add(picker.onDidHide(() => disposables.dispose()));
});
if (selectedItems.length === 0) {
return;
}
const { confirmed } = await dialogService.confirm({
type: 'warning',
message: localize('removeLargeStorageEntriesConfirmRemove', "Do you want to remove the selected storage entries from the database?"),
detail: localize('removeLargeStorageEntriesConfirmRemoveDetail', "{0}\n\nThis action is irreversible and may result in data loss!", selectedItems.map(item => item.label).join('\n')),
primaryButton: localize({ key: 'removeLargeStorageEntriesButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Remove")
});
if (!confirmed) {
return;
}
const scopesToOptimize = new Set<StorageScope>();
for (const item of selectedItems) {
storageService.remove(item.key, item.scope);
scopesToOptimize.add(item.scope);
}
for (const scope of scopesToOptimize) {
await storageService.optimize(scope);
}
}
}
let tracker: DisposableTracker | undefined = undefined;
let trackedDisposables = new Set<IDisposable>();
const DisposablesSnapshotStateContext = new RawContextKey<'started' | 'pending' | 'stopped'>('dirtyWorkingCopies', 'stopped');
class StartTrackDisposables extends Action2 {
constructor() {
super({
id: 'workbench.action.startTrackDisposables',
title: localize2('startTrackDisposables', 'Start Tracking Disposables'),
category: Categories.Developer,
f1: true,
precondition: ContextKeyExpr.and(DisposablesSnapshotStateContext.isEqualTo('pending').negate(), DisposablesSnapshotStateContext.isEqualTo('started').negate())
});
}
run(accessor: ServicesAccessor): void {
const disposablesSnapshotStateContext = DisposablesSnapshotStateContext.bindTo(accessor.get(IContextKeyService));
disposablesSnapshotStateContext.set('started');
trackedDisposables.clear();
tracker = new DisposableTracker();
setDisposableTracker(tracker);
}
}
class SnapshotTrackedDisposables extends Action2 {
constructor() {
super({
id: 'workbench.action.snapshotTrackedDisposables',
title: localize2('snapshotTrackedDisposables', 'Snapshot Tracked Disposables'),
category: Categories.Developer,
f1: true,
precondition: DisposablesSnapshotStateContext.isEqualTo('started')
});
}
run(accessor: ServicesAccessor): void {
const disposablesSnapshotStateContext = DisposablesSnapshotStateContext.bindTo(accessor.get(IContextKeyService));
disposablesSnapshotStateContext.set('pending');
trackedDisposables = new Set(tracker?.computeLeakingDisposables(1000)?.leaks.map(disposable => disposable.value));
}
}
class StopTrackDisposables extends Action2 {
constructor() {
super({
id: 'workbench.action.stopTrackDisposables',
title: localize2('stopTrackDisposables', 'Stop Tracking Disposables'),
category: Categories.Developer,
f1: true,
precondition: DisposablesSnapshotStateContext.isEqualTo('pending')
});
}
run(accessor: ServicesAccessor): void {
const editorService = accessor.get(IEditorService);
const disposablesSnapshotStateContext = DisposablesSnapshotStateContext.bindTo(accessor.get(IContextKeyService));
disposablesSnapshotStateContext.set('stopped');
if (tracker) {
const disposableLeaks = new Set<DisposableInfo>();
for (const disposable of new Set(tracker.computeLeakingDisposables(1000)?.leaks) ?? []) {
if (trackedDisposables.has(disposable.value)) {
disposableLeaks.add(disposable);
}
}
const leaks = tracker.computeLeakingDisposables(1000, Array.from(disposableLeaks));
if (leaks) {
editorService.openEditor({ resource: undefined, contents: leaks.details });
}
}
setDisposableTracker(null);
tracker = undefined;
trackedDisposables.clear();
}
}
class PolicyDiagnosticsAction extends Action2 {
constructor() {
super({
id: 'workbench.action.showPolicyDiagnostics',
title: localize2('policyDiagnostics', 'Policy Diagnostics'),
category: Categories.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const editorService = accessor.get(IEditorService);
const configurationService = accessor.get(IConfigurationService);
const productService = accessor.get(IProductService);
const defaultAccountService = accessor.get(IDefaultAccountService);
const authenticationService = accessor.get(IAuthenticationService);
const authenticationAccessService = accessor.get(IAuthenticationAccessService);
const policyService = accessor.get(IPolicyService);
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
let content = '# VS Code Policy Diagnostics\n\n';
content += '*WARNING: This file may contain sensitive information.*\n\n';
content += '## System Information\n\n';
content += '| Property | Value |\n';
content += '|----------|-------|\n';
content += `| Generated | ${new Date().toISOString()} |\n`;
content += `| Product | ${productService.nameLong} ${productService.version} |\n`;
content += `| Commit | ${productService.commit || 'n/a'} |\n\n`;
// Account information
content += '## Account Information\n\n';
try {
const account = await defaultAccountService.getDefaultAccount();
const sensitiveKeys = ['sessionId', 'analytics_tracking_id'];
if (account) {
// Try to get username/display info from the authentication session
let username = 'Unknown';
let accountLabel = 'Unknown';
try {
const providerIds = authenticationService.getProviderIds();
for (const providerId of providerIds) {
const sessions = await authenticationService.getSessions(providerId);
const matchingSession = sessions.find(session => session.id === account.sessionId);
if (matchingSession) {
username = matchingSession.account.id;
accountLabel = matchingSession.account.label;
break;
}
}
} catch (error) {
// Fallback to just session info
}
content += '### Default Account Summary\n\n';
content += `**Account ID/Username**: ${username}\n\n`;
content += `**Account Label**: ${accountLabel}\n\n`;
content += '### Detailed Account Properties\n\n';
content += '| Property | Value |\n';
content += '|----------|-------|\n';
// Iterate through all properties of the account object
for (const [key, value] of Object.entries(account)) {
if (value !== undefined && value !== null) {
let displayValue: string;
// Mask sensitive information
if (sensitiveKeys.includes(key)) {
displayValue = '***';
} else if (typeof value === 'object') {
displayValue = JSON.stringify(value);
} else {
displayValue = String(value);
}
content += `| ${key} | ${displayValue} |\n`;
}
}
content += '\n';
} else {
content += '*No default account configured*\n\n';
}
} catch (error) {
content += `*Error retrieving account information: ${error}*\n\n`;
}
content += '## Policy-Controlled Settings\n\n';
const policyConfigurations = configurationRegistry.getPolicyConfigurations();
const configurationProperties = configurationRegistry.getConfigurationProperties();
const excludedProperties = configurationRegistry.getExcludedConfigurationProperties();
if (policyConfigurations.size > 0) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const appliedPolicy: Array<{ name: string; key: string; property: any; inspection: any }> = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const notAppliedPolicy: Array<{ name: string; key: string; property: any; inspection: any }> = [];
for (const [policyName, settingKey] of policyConfigurations) {
const property = configurationProperties[settingKey] ?? excludedProperties[settingKey];
if (property) {
const inspectValue = configurationService.inspect(settingKey);
const settingInfo = {
name: policyName,
key: settingKey,
property,
inspection: inspectValue
};
if (inspectValue.policyValue !== undefined) {
appliedPolicy.push(settingInfo);
} else {
notAppliedPolicy.push(settingInfo);
}
}
}
// Try to detect where the policy came from
const policySourceMemo = new Map<string, string>();
const getPolicySource = (policyName: string): string => {
if (policySourceMemo.has(policyName)) {
return policySourceMemo.get(policyName)!;
}
try {
const policyServiceConstructorName = policyService.constructor.name;
if (policyServiceConstructorName === 'MultiplexPolicyService') {
// eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
const multiplexService = policyService as any;
if (multiplexService.policyServices) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const componentServices = multiplexService.policyServices as ReadonlyArray<any>;
for (const service of componentServices) {
if (service.getPolicyValue && service.getPolicyValue(policyName) !== undefined) {
policySourceMemo.set(policyName, service.constructor.name);
return service.constructor.name;
}
}
}
}
return '';
} catch {
return 'Unknown';
}
};
content += '### Applied Policy\n\n';
appliedPolicy.sort((a, b) => getPolicySource(a.name).localeCompare(getPolicySource(b.name)) || a.name.localeCompare(b.name));
if (appliedPolicy.length > 0) {
content += '| Setting Key | Policy Name | Policy Source | Default Value | Current Value | Policy Value |\n';
content += '|-------------|-------------|---------------|---------------|---------------|-------------|\n';
for (const setting of appliedPolicy) {
const defaultValue = JSON.stringify(setting.property.default);
const currentValue = JSON.stringify(setting.inspection.value);
const policyValue = JSON.stringify(setting.inspection.policyValue);
const policySource = getPolicySource(setting.name);
content += `| ${setting.key} | ${setting.name} | ${policySource} | \`${defaultValue}\` | \`${currentValue}\` | \`${policyValue}\` |\n`;
}
content += '\n';
} else {
content += '*No settings are currently controlled by policies*\n\n';
}
content += '### Non-applied Policy\n\n';
if (notAppliedPolicy.length > 0) {
content += '| Setting Key | Policy Name \n';
content += '|-------------|-------------|\n';
for (const setting of notAppliedPolicy) {
content += `| ${setting.key} | ${setting.name}|\n`;
}
content += '\n';
} else {
content += '*All policy-controllable settings are currently being enforced*\n\n';
}
} else {
content += '*No policy-controlled settings found*\n\n';
}
// Authentication diagnostics
content += '## Authentication Information\n\n';
try {
const providerIds = authenticationService.getProviderIds();
if (providerIds.length > 0) {
content += '### Authentication Providers\n\n';
content += '| Provider ID | Sessions | Accounts |\n';
content += '|-------------|----------|----------|\n';
for (const providerId of providerIds) {
try {
const sessions = await authenticationService.getSessions(providerId);
const accounts = sessions.map(session => session.account);
const uniqueAccounts = Array.from(new Set(accounts.map(account => account.label)));
content += `| ${providerId} | ${sessions.length} | ${uniqueAccounts.join(', ') || 'None'} |\n`;
} catch (error) {
content += `| ${providerId} | Error | ${error} |\n`;
}
}
content += '\n';
// Detailed session information
content += '### Detailed Session Information\n\n';
for (const providerId of providerIds) {
try {
const sessions = await authenticationService.getSessions(providerId);
if (sessions.length > 0) {
content += `#### ${providerId}\n\n`;
content += '| Account | Scopes | Extensions with Access |\n';
content += '|---------|--------|------------------------|\n';
for (const session of sessions) {
const accountName = session.account.label;
const scopes = session.scopes.join(', ') || 'Default';
// Get extensions with access to this account
try {
const allowedExtensions = authenticationAccessService.readAllowedExtensions(providerId, accountName);
const extensionNames = allowedExtensions
.filter(ext => ext.allowed !== false)
.map(ext => `${ext.name}${ext.trusted ? ' (trusted)' : ''}`)
.join(', ') || 'None';
content += `| ${accountName} | ${scopes} | ${extensionNames} |\n`;
} catch (error) {
content += `| ${accountName} | ${scopes} | Error: ${error} |\n`;
}
}
content += '\n';
}
} catch (error) {
content += `#### ${providerId}\n*Error retrieving sessions: ${error}*\n\n`;
}
}
} else {
content += '*No authentication providers found*\n\n';
}
} catch (error) {
content += `*Error retrieving authentication information: ${error}*\n\n`;
}
await editorService.openEditor({
resource: undefined,
contents: content,
languageId: 'markdown',
options: { pinned: true, }
});
}
}
// --- Actions Registration
registerAction2(InspectContextKeysAction);
registerAction2(ToggleScreencastModeAction);
registerAction2(LogStorageAction);
registerAction2(LogWorkingCopiesAction);
registerAction2(RemoveLargeStorageEntriesAction);
registerAction2(PolicyDiagnosticsAction);
if (!product.commit) {
registerAction2(StartTrackDisposables);
registerAction2(SnapshotTrackedDisposables);
registerAction2(StopTrackDisposables);
}
// --- Configuration
// Screen Cast Mode
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
configurationRegistry.registerConfiguration({
id: 'screencastMode',
order: 9,
title: localize('screencastModeConfigurationTitle', "Screencast Mode"),
type: 'object',
properties: {
'screencastMode.verticalOffset': {
type: 'number',
default: 20,
minimum: 0,
maximum: 90,
description: localize('screencastMode.location.verticalPosition', "Controls the vertical offset of the screencast mode overlay from the bottom as a percentage of the workbench height.")
},
'screencastMode.fontSize': {
type: 'number',
default: 56,
minimum: 20,
maximum: 100,
description: localize('screencastMode.fontSize', "Controls the font size (in pixels) of the screencast mode keyboard.")
},
'screencastMode.keyboardOptions': {
type: 'object',
description: localize('screencastMode.keyboardOptions.description', "Options for customizing the keyboard overlay in screencast mode."),
properties: {
'showKeys': {
type: 'boolean',
default: true,
description: localize('screencastMode.keyboardOptions.showKeys', "Show raw keys.")
},
'showKeybindings': {
type: 'boolean',
default: true,
description: localize('screencastMode.keyboardOptions.showKeybindings', "Show keyboard shortcuts.")
},
'showCommands': {
type: 'boolean',
default: true,
description: localize('screencastMode.keyboardOptions.showCommands', "Show command names.")
},
'showCommandGroups': {
type: 'boolean',
default: false,
description: localize('screencastMode.keyboardOptions.showCommandGroups', "Show command group names, when commands are also shown.")
},
'showSingleEditorCursorMoves': {
type: 'boolean',
default: true,
description: localize('screencastMode.keyboardOptions.showSingleEditorCursorMoves', "Show single editor cursor move commands.")
}
},
default: {
'showKeys': true,
'showKeybindings': true,
'showCommands': true,
'showCommandGroups': false,
'showSingleEditorCursorMoves': true
},
additionalProperties: false
},
'screencastMode.keyboardOverlayTimeout': {
type: 'number',
default: 800,
minimum: 500,
maximum: 5000,
description: localize('screencastMode.keyboardOverlayTimeout', "Controls how long (in milliseconds) the keyboard overlay is shown in screencast mode.")
},
'screencastMode.mouseIndicatorColor': {
type: 'string',
format: 'color-hex',
default: '#FF0000',
description: localize('screencastMode.mouseIndicatorColor', "Controls the color in hex (#RGB, #RGBA, #RRGGBB or #RRGGBBAA) of the mouse indicator in screencast mode.")
},
'screencastMode.mouseIndicatorSize': {
type: 'number',
default: 20,