-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
editorOverrideService.ts
659 lines (579 loc) · 28 KB
/
editorOverrideService.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as glob from 'vs/base/common/glob';
import { distinct, firstOrDefault, flatten, insert } from 'vs/base/common/arrays';
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { basename, extname, isEqual } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { EditorActivation, EditorOverride, IEditorOptions } from 'vs/platform/editor/common/editor';
import { EditorResourceAccessor, IEditorInput, IEditorInputWithOptions, IEditorInputWithOptionsAndGroup, SideBySideEditor } from 'vs/workbench/common/editor';
import { IEditorGroup, IEditorGroupsService, preferredSideBySideGroupDirection } from 'vs/workbench/services/editor/common/editorGroupsService';
import { Schemas } from 'vs/base/common/network';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { ContributedEditorInfo, ContributedEditorPriority, ContributionPointOptions, DEFAULT_EDITOR_ASSOCIATION, DiffEditorInputFactoryFunction, EditorAssociation, EditorAssociations, EditorInputFactoryFunction, editorsAssociationsSettingId, globMatchesResource, IEditorOverrideService, priorityToRank } from 'vs/workbench/services/editor/common/editorOverrideService';
import { IKeyMods, IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { localize } from 'vs/nls';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { ILogService } from 'vs/platform/log/common/log';
interface IContributedEditorInput extends IEditorInput {
viewType?: string;
}
interface ContributionPoint {
globPattern: string | glob.IRelativePattern,
editorInfo: ContributedEditorInfo,
options?: ContributionPointOptions,
createEditorInput: EditorInputFactoryFunction
createDiffEditorInput?: DiffEditorInputFactoryFunction
}
type ContributionPoints = Array<ContributionPoint>;
export class EditorOverrideService extends Disposable implements IEditorOverrideService {
readonly _serviceBrand: undefined;
// Constants
private static readonly configureDefaultID = 'promptOpenWith.configureDefault';
private static readonly overrideCacheStorageID = 'editorOverrideService.cache';
private static readonly conflictingDefaultsStorageID = 'editorOverrideService.conflictingDefaults';
// Data Stores
private _contributionPoints: Map<string | glob.IRelativePattern, ContributionPoints> = new Map<string | glob.IRelativePattern, ContributionPoints>();
private cache: Set<string> | undefined;
constructor(
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@INotificationService private readonly notificationService: INotificationService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IStorageService private readonly storageService: IStorageService,
@IExtensionService private readonly extensionService: IExtensionService,
@IHostService private readonly hostService: IHostService,
@ILogService private readonly logService: ILogService,
) {
super();
// Read in the cache on statup
this.cache = new Set<string>(JSON.parse(this.storageService.get(EditorOverrideService.overrideCacheStorageID, StorageScope.GLOBAL, JSON.stringify([]))));
this.storageService.remove(EditorOverrideService.overrideCacheStorageID, StorageScope.GLOBAL);
this.convertOldAssociationFormat();
this._register(this.storageService.onWillSaveState(() => {
// We want to store the glob patterns we would activate on, this allows us to know if we need to await the ext host on startup for opening a resource
this.cacheContributionPoints();
}));
// When extensions have registered we no longer need the cache
this.extensionService.onDidRegisterExtensions(() => {
this.cache = undefined;
});
// When the setting changes we want to ensure that it is properly converted
this._register(this.configurationService.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration(editorsAssociationsSettingId)) {
this.convertOldAssociationFormat();
}
}));
}
async resolveEditorOverride(editor: IEditorInput, options: IEditorOptions | undefined, group: IEditorGroup): Promise<IEditorInputWithOptionsAndGroup | undefined> {
// If it was an override before we await for the extensions to activate and then proceed with overriding or else they won't be registered
if (this.cache && editor.resource && this.resourceMatchesCache(editor.resource)) {
await this.extensionService.whenInstalledExtensionsRegistered();
}
if (options?.override === EditorOverride.DISABLED) {
throw new Error(`Calling resolve editor override when override is explicitly disabled!`);
}
// Always ensure inputs have populated resource fields
const resource = EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
if (!resource) {
return { editor, options, group };
}
let override = typeof options?.override === 'string' ? options.override : undefined;
// If the editor passed in already has a type and the user didn't explicitly override the editor choice, use the editor type.
override = override ?? (editor as IContributedEditorInput).viewType;
if (options?.override === EditorOverride.PICK) {
const picked = await this.doPickEditorOverride(editor, options, group);
// If the picker was cancelled we will stop resolving the override
if (!picked) {
return;
}
// Deconstruct the return picked options and overrides if the user selected something
override = picked[0].override as string | undefined;
options = picked[0];
group = picked[1] ?? group;
}
// Resolved the override as much as possible, now find a given contribution
const { contributionPoint, conflictingDefault } = this.getContributionPoint(resource, override);
const selectedContribution = contributionPoint;
if (!selectedContribution) {
return { editor, options, group };
}
const handlesDiff = typeof selectedContribution.options?.canHandleDiff === 'function' ? selectedContribution.options.canHandleDiff() : selectedContribution.options?.canHandleDiff;
if (editor instanceof DiffEditorInput && handlesDiff === false) {
return { editor, options, group };
}
// If it's the currently active editor we shouldn't do anything
if (selectedContribution.editorInfo.describes(editor)) {
return;
}
const input = await this.doOverrideEditorInput(resource, editor, options, group, selectedContribution);
if (conflictingDefault && input) {
// Show the conflicting default dialog
await this.doHandleConflictingDefaults(resource, selectedContribution.editorInfo.label, input.editor, input.options ?? options, group);
}
// Add the group as we might've changed it with the quickpick
if (input) {
this.sendOverrideTelemetry(input.editor);
return { ...input, group };
}
return input;
}
registerContributionPoint(
globPattern: string | glob.IRelativePattern,
editorInfo: ContributedEditorInfo,
options: ContributionPointOptions,
createEditorInput: EditorInputFactoryFunction,
createDiffEditorInput?: DiffEditorInputFactoryFunction
): IDisposable {
let contributionPoint = this._contributionPoints.get(globPattern);
if (contributionPoint === undefined) {
contributionPoint = [];
this._contributionPoints.set(globPattern, contributionPoint);
}
const remove = insert(contributionPoint, {
globPattern,
editorInfo,
options,
createEditorInput,
createDiffEditorInput
});
return toDisposable(() => remove());
}
hasContributionPoint(glob: string): boolean {
return this._contributionPoints.has(glob);
}
getAssociationsForResource(resource: URI): EditorAssociations {
const associations = this.getAllUserAssociations();
const matchingAssociations = associations.filter(association => association.filenamePattern && globMatchesResource(association.filenamePattern, resource));
const allContributions: ContributionPoints = this._allContributions;
// Ensure that the settings are valid contribution points
return matchingAssociations.filter(association => allContributions.find(c => c.editorInfo.id === association.viewType));
}
private convertOldAssociationFormat(): void {
this.hostService.hadLastFocus().then(hadLastFocus => {
if (!hadLastFocus) {
return;
}
const rawAssociations = this.configurationService.getValue<EditorAssociations | { [fileNamePattern: string]: string }>(editorsAssociationsSettingId) || {};
// If it's not an array, then it's the new format
if (!Array.isArray(rawAssociations)) {
return;
}
let newSettingObject = Object.create(null);
// Make the correctly formatted object from the array and then set that object
for (const association of rawAssociations) {
if (association.filenamePattern) {
newSettingObject[association.filenamePattern] = association.viewType;
}
}
this.logService.info(`Migrating ${editorsAssociationsSettingId}`);
this.configurationService.updateValue(editorsAssociationsSettingId, newSettingObject);
});
}
private getAllUserAssociations(): EditorAssociations {
let rawAssociations = this.configurationService.getValue<EditorAssociations | { [fileNamePattern: string]: string }>(editorsAssociationsSettingId) || {};
// If it's an array then it is old format
if (Array.isArray(rawAssociations)) {
// Make the correctly formatted object
const newValue = Object.create(null);
for (const association of rawAssociations) {
if (association.filenamePattern) {
newValue[association.filenamePattern] = association.viewType;
}
}
rawAssociations = newValue;
}
let associations = [];
for (const [key, value] of Object.entries(rawAssociations)) {
const association: EditorAssociation = {
filenamePattern: key,
viewType: value
};
associations.push(association);
}
return associations;
}
/**
* Returns all contributions as an array. Possible to contain duplicates
*/
private get _allContributions(): ContributionPoints {
return flatten(Array.from(this._contributionPoints.values()));
}
updateUserAssociations(globPattern: string, editorID: string): void {
const newAssociation: EditorAssociation = { viewType: editorID, filenamePattern: globPattern };
const currentAssociations = this.getAllUserAssociations();
const newSettingObject = Object.create(null);
// Form the new setting object including the newest associations
for (const association of [...currentAssociations, newAssociation]) {
if (association.filenamePattern) {
newSettingObject[association.filenamePattern] = association.viewType;
}
}
this.configurationService.updateValue(editorsAssociationsSettingId, newSettingObject);
}
private findMatchingContributions(resource: URI): ContributionPoint[] {
// The user setting should be respected even if the editor doesn't specify that resource in package.json
const userSettings = this.getAssociationsForResource(resource);
let contributions: ContributionPoint[] = [];
// Then all glob patterns
for (const [key, contributionPoints] of this._contributionPoints) {
for (const contributionPoint of contributionPoints) {
const foundInSettings = userSettings.find(setting => setting.viewType === contributionPoint.editorInfo.id);
if (foundInSettings || globMatchesResource(key, resource)) {
contributions.push(contributionPoint);
}
}
}
// Return the contributions sorted by their priority
return contributions.sort((a, b) => priorityToRank(b.editorInfo.priority) - priorityToRank(a.editorInfo.priority));
}
public getEditorIds(resource: URI): string[] {
const contributionPoints = this.findMatchingContributions(resource);
return contributionPoints.map(contribution => contribution.editorInfo.id);
}
/**
* Given a resource and an override selects the best possible contribution point
* @returns The contribution point and whether there was another default which conflicted with it
*/
private getContributionPoint(resource: URI, override: string | undefined): { contributionPoint: ContributionPoint | undefined, conflictingDefault: boolean } {
const findMatchingContribPoint = (contributionPoints: ContributionPoints, viewType: string) => {
return contributionPoints.find((contribPoint) => {
if (contribPoint.options && contribPoint.options.canSupportResource !== undefined) {
return contribPoint.editorInfo.id === viewType && contribPoint.options.canSupportResource(resource);
}
return contribPoint.editorInfo.id === viewType;
});
};
if (override) {
// Specific overried passed in doesn't have to match the reosurce, it can be anything
const contributionPoints = this._allContributions;
return {
contributionPoint: findMatchingContribPoint(contributionPoints, override),
conflictingDefault: false
};
}
let contributionPoints = this.findMatchingContributions(resource);
const associationsFromSetting = this.getAssociationsForResource(resource);
// We only want built-in+ if no user defined setting is found, else we won't override
const possibleContributionPoints = contributionPoints.filter(contribPoint => priorityToRank(contribPoint.editorInfo.priority) >= priorityToRank(ContributedEditorPriority.builtin) && contribPoint.editorInfo.id !== DEFAULT_EDITOR_ASSOCIATION.id);
// If the contribution is exclusive we use that, else use the user setting, else use the built-in+ contribution
const selectedViewType = possibleContributionPoints[0]?.editorInfo.priority === ContributedEditorPriority.exclusive ?
possibleContributionPoints[0]?.editorInfo.id :
associationsFromSetting[0]?.viewType || possibleContributionPoints[0]?.editorInfo.id;
let conflictingDefault = false;
if (associationsFromSetting.length === 0 && possibleContributionPoints.length > 1) {
conflictingDefault = true;
}
return {
contributionPoint: findMatchingContribPoint(contributionPoints, selectedViewType),
conflictingDefault
};
}
private async doOverrideEditorInput(resource: URI, editor: IEditorInput, options: IEditorOptions | undefined, group: IEditorGroup, selectedContribution: ContributionPoint): Promise<IEditorInputWithOptions | undefined> {
// If no activation option is provided, populate it.
if (options && typeof options.activation === 'undefined') {
options = { ...options, activation: options.preserveFocus ? EditorActivation.RESTORE : undefined };
}
// If it's a diff editor we trigger the create diff editor input
if (editor instanceof DiffEditorInput) {
if (!selectedContribution.createDiffEditorInput) {
return;
}
const inputWithOptions = selectedContribution.createDiffEditorInput(editor, options, group);
return inputWithOptions;
}
// Respect options passed back
const inputWithOptions = selectedContribution.createEditorInput(resource, options, group);
options = inputWithOptions.options ?? options;
const input = inputWithOptions.editor;
// If the editor states it can only be opened once per resource we must close all existing ones first
const singleEditorPerResource = typeof selectedContribution.options?.singlePerResource === 'function' ? selectedContribution.options.singlePerResource() : selectedContribution.options?.singlePerResource;
if (singleEditorPerResource) {
this.closeExistingEditorsForResource(resource, selectedContribution.editorInfo.id, group);
}
return { editor: input, options };
}
private closeExistingEditorsForResource(
resource: URI,
viewType: string,
targetGroup: IEditorGroup,
): void {
const editorInfoForResource = this.findExistingEditorsForResource(resource, viewType);
if (!editorInfoForResource.length) {
return;
}
const editorToUse = editorInfoForResource[0];
// Replace all other editors
for (const { editor, group } of editorInfoForResource) {
if (editor !== editorToUse.editor) {
group.closeEditor(editor);
}
}
if (targetGroup.id !== editorToUse.group.id) {
editorToUse.group.closeEditor(editorToUse.editor);
}
return;
}
/**
* Given a resource and a viewType, returns all editors open for that resouce and viewType.
* @param resource The resource specified
* @param viewType The viewtype
* @returns A list of editors
*/
private findExistingEditorsForResource(
resource: URI,
viewType: string,
): Array<{ editor: IEditorInput, group: IEditorGroup }> {
const out: Array<{ editor: IEditorInput, group: IEditorGroup }> = [];
const orderedGroups = distinct([
...this.editorGroupService.groups,
]);
for (const group of orderedGroups) {
for (const editor of group.editors) {
if (isEqual(editor.resource, resource) && (editor as IContributedEditorInput).viewType === viewType) {
out.push({ editor, group });
}
}
}
return out;
}
private async doHandleConflictingDefaults(resource: URI, editorName: string, currentEditor: IContributedEditorInput, options: IEditorOptions | undefined, group: IEditorGroup) {
type StoredChoice = {
[key: string]: string[];
};
const contributionPoints = this.findMatchingContributions(resource);
const storedChoices: StoredChoice = JSON.parse(this.storageService.get(EditorOverrideService.conflictingDefaultsStorageID, StorageScope.GLOBAL, '{}'));
const globForResource = `*${extname(resource)}`;
// Writes to the storage service that a choice has been made for the currently installed editors
const writeCurrentEditorsToStorage = () => {
storedChoices[globForResource] = [];
contributionPoints.forEach(contrib => storedChoices[globForResource].push(contrib.editorInfo.id));
this.storageService.store(EditorOverrideService.conflictingDefaultsStorageID, JSON.stringify(storedChoices), StorageScope.GLOBAL, StorageTarget.MACHINE);
};
// If the user has already made a choice for this editor we don't want to ask them again
if (storedChoices[globForResource] && storedChoices[globForResource].find(editorID => editorID === currentEditor.viewType)) {
return;
}
const handle = this.notificationService.prompt(Severity.Warning,
localize('editorOverride.conflictingDefaults', 'There are multiple default editors available for the resource.'),
[{
label: localize('editorOverride.configureDefault', 'Configure Default'),
run: async () => {
// Show the picker and tell it to update the setting to whatever the user selected
const picked = await this.doPickEditorOverride(currentEditor, options, group, true);
if (!picked) {
return;
}
const replacementEditor = await this.resolveEditorOverride(currentEditor, picked[0], picked[1] ?? group);
if (!replacementEditor) {
return;
}
// Replace the current editor with the picked one
(replacementEditor.group ?? picked[1] ?? group).replaceEditors([
{
editor: currentEditor,
replacement: replacementEditor.editor,
options: replacementEditor.options ?? picked[0],
}
]);
}
},
{
label: localize('editorOverride.keepDefault', 'Keep {0}', editorName),
run: writeCurrentEditorsToStorage
}
]);
// If the user pressed X we assume they want to keep the current editor as default
const onCloseListener = handle.onDidClose(() => {
writeCurrentEditorsToStorage();
onCloseListener.dispose();
});
}
private mapContributionsToQuickPickEntry(resource: URI, group: IEditorGroup, showDefaultPicker?: boolean) {
const currentEditor = firstOrDefault(group.findEditors(resource));
// If untitled, we want all contribution points
let contributionPoints = resource.scheme === Schemas.untitled ? this._allContributions : this.findMatchingContributions(resource);
// We don't want duplicate Id entries
contributionPoints = distinct(contributionPoints, c => c.editorInfo.id);
const defaultSetting = this.getAssociationsForResource(resource)[0]?.viewType;
// Not the most efficient way to do this, but we want to ensure the text editor is at the top of the quickpick
contributionPoints = contributionPoints.sort((a, b) => {
if (a.editorInfo.id === DEFAULT_EDITOR_ASSOCIATION.id) {
return -1;
} else if (b.editorInfo.id === DEFAULT_EDITOR_ASSOCIATION.id) {
return 1;
} else {
return priorityToRank(b.editorInfo.priority) - priorityToRank(a.editorInfo.priority);
}
});
const quickPickEntries: Array<IQuickPickItem | IQuickPickSeparator> = [];
const currentlyActiveLabel = localize('promptOpenWith.currentlyActive', "Active");
const currentDefaultLabel = localize('promptOpenWith.currentDefault', "Default");
const currentDefaultAndActiveLabel = localize('promptOpenWith.currentDefaultAndActive', "Active and Default");
// Default order = setting -> highest priority -> text
let defaultViewType = defaultSetting;
if (!defaultViewType && contributionPoints.length > 2 && contributionPoints[1]?.editorInfo.priority !== ContributedEditorPriority.option) {
defaultViewType = contributionPoints[1]?.editorInfo.id;
}
if (!defaultViewType) {
defaultViewType = DEFAULT_EDITOR_ASSOCIATION.id;
}
// Map the contributions to quickpick entries
contributionPoints.forEach(contribPoint => {
const isActive = currentEditor ? contribPoint.editorInfo.describes(currentEditor) : false;
const isDefault = contribPoint.editorInfo.id === defaultViewType;
const quickPickEntry: IQuickPickItem = {
id: contribPoint.editorInfo.id,
label: contribPoint.editorInfo.label,
description: isActive && isDefault ? currentDefaultAndActiveLabel : isActive ? currentlyActiveLabel : isDefault ? currentDefaultLabel : undefined,
detail: contribPoint.editorInfo.detail ?? contribPoint.editorInfo.priority,
};
quickPickEntries.push(quickPickEntry);
});
if (!showDefaultPicker) {
const separator: IQuickPickSeparator = { type: 'separator' };
quickPickEntries.push(separator);
const configureDefaultEntry = {
id: EditorOverrideService.configureDefaultID,
label: localize('promptOpenWith.configureDefault', "Configure default editor for '{0}'...", `*${extname(resource)}`),
};
quickPickEntries.push(configureDefaultEntry);
}
return quickPickEntries;
}
private async doPickEditorOverride(editor: IEditorInput, options: IEditorOptions | undefined, group: IEditorGroup, showDefaultPicker?: boolean): Promise<[IEditorOptions, IEditorGroup | undefined] | undefined> {
type EditorOverridePick = {
readonly item: IQuickPickItem;
readonly keyMods?: IKeyMods;
readonly openInBackground: boolean;
};
const resource = EditorResourceAccessor.getOriginalUri(editor);
if (!resource) {
return;
}
// Text editor has the lowest priority because we
const editorOverridePicks = this.mapContributionsToQuickPickEntry(resource, group, showDefaultPicker);
// Create editor override picker
const editorOverridePicker = this.quickInputService.createQuickPick<IQuickPickItem>();
const placeHolderMessage = showDefaultPicker ?
localize('prompOpenWith.updateDefaultPlaceHolder', "Select new default editor for '{0}'", `*${extname(resource)}`) :
localize('promptOpenWith.placeHolder', "Select editor for '{0}'", basename(resource));
editorOverridePicker.placeholder = placeHolderMessage;
editorOverridePicker.canAcceptInBackground = true;
editorOverridePicker.items = editorOverridePicks;
const firstItem = editorOverridePicker.items.find(item => item.type === 'item') as IQuickPickItem | undefined;
if (firstItem) {
editorOverridePicker.selectedItems = [firstItem];
}
// Prompt the user to select an override
const picked: EditorOverridePick | undefined = await new Promise<EditorOverridePick | undefined>(resolve => {
editorOverridePicker.onDidAccept(e => {
let result: EditorOverridePick | undefined = undefined;
if (editorOverridePicker.selectedItems.length === 1) {
result = {
item: editorOverridePicker.selectedItems[0],
keyMods: editorOverridePicker.keyMods,
openInBackground: e.inBackground
};
}
// If asked to always update the setting then update it even if the gear isn't clicked
if (showDefaultPicker && result?.item.id) {
this.updateUserAssociations(`*${extname(resource)}`, result.item.id,);
}
resolve(result);
});
editorOverridePicker.onDidTriggerItemButton(e => {
// Trigger opening and close picker
resolve({ item: e.item, openInBackground: false });
// Persist setting
if (resource && e.item && e.item.id) {
this.updateUserAssociations(`*${extname(resource)}`, e.item.id,);
}
});
editorOverridePicker.show();
});
// Close picker
editorOverridePicker.dispose();
// If the user picked an override, look at how the picker was
// used (e.g. modifier keys, open in background) and create the
// options and group to use accordingly
if (picked) {
// If the user selected to configure default we trigger this picker again and tell it to show the default picker
if (picked.item.id === EditorOverrideService.configureDefaultID) {
return this.doPickEditorOverride(editor, options, group, true);
}
// Figure out target group
let targetGroup: IEditorGroup | undefined;
if (picked.keyMods?.alt || picked.keyMods?.ctrlCmd) {
const direction = preferredSideBySideGroupDirection(this.configurationService);
targetGroup = this.editorGroupService.findGroup({ direction }, group.id);
targetGroup = targetGroup ?? this.editorGroupService.addGroup(group, direction);
}
// Figure out options
const targetOptions: IEditorOptions = {
...options,
override: picked.item.id,
preserveFocus: picked.openInBackground || options?.preserveFocus,
};
return [targetOptions, targetGroup];
}
return undefined;
}
private sendOverrideTelemetry(chosenInput: IContributedEditorInput): void {
type editorOverrideClassification = {
viewType: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
};
type editorOverrideEvent = {
viewType: string
};
if (chosenInput.viewType) {
this.telemetryService.publicLog2<editorOverrideEvent, editorOverrideClassification>('override.viewType', { viewType: chosenInput.viewType });
}
}
private cacheContributionPoints() {
// Create a set to store contributed glob patterns
const cacheStorage: Set<string> = new Set<string>();
// Store just the relative pattern pieces without any path info
for (const [globPattern, contribPoint] of this._contributionPoints) {
const nonOptional = !!contribPoint.find(c => c.editorInfo.priority !== ContributedEditorPriority.option && c.editorInfo.id !== DEFAULT_EDITOR_ASSOCIATION.id);
// Don't keep a cache of the optional ones as those wouldn't be opened on start anyways
if (!nonOptional) {
continue;
}
if (glob.isRelativePattern(globPattern)) {
cacheStorage.add(`${globPattern.pattern}`);
} else {
cacheStorage.add(globPattern);
}
}
// Also store the users settings as those would have to activate on startup as well
const userAssociations = this.getAllUserAssociations();
for (const association of userAssociations) {
if (association.filenamePattern) {
cacheStorage.add(association.filenamePattern);
}
}
this.storageService.store(EditorOverrideService.overrideCacheStorageID, JSON.stringify(Array.from(cacheStorage)), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
private resourceMatchesCache(resource: URI): boolean {
if (!this.cache) {
return false;
}
for (const cacheEntry of this.cache) {
if (globMatchesResource(cacheEntry, resource)) {
return true;
}
}
return false;
}
}
registerSingleton(IEditorOverrideService, EditorOverrideService);