-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
Copy patheditorService.ts
1350 lines (1074 loc) · 48.8 KB
/
editorService.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.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IResourceEditorInput, IEditorOptions, EditorActivation, EditorOverride, IResourceEditorInputIdentifier, ITextEditorOptions, ITextResourceEditorInput } from 'vs/platform/editor/common/editor';
import { SideBySideEditor, IEditorInput, IEditorPane, GroupIdentifier, IFileEditorInput, IUntitledTextResourceEditorInput, IResourceDiffEditorInput, IEditorInputFactoryRegistry, EditorExtensions, IEditorInputWithOptions, isEditorInputWithOptions, IEditorIdentifier, IEditorCloseEvent, ITextEditorPane, ITextDiffEditorPane, IRevertOptions, SaveReason, EditorsOrder, isTextEditorPane, IWorkbenchEditorConfiguration, EditorResourceAccessor, IVisibleEditorPane, EditorInputCapabilities, isResourceDiffEditorInput, IUntypedEditorInput, DEFAULT_EDITOR_ASSOCIATION, UntypedEditorContext, isResourceEditorInput, isEditorInput } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput';
import { TextResourceEditorInput } from 'vs/workbench/common/editor/textResourceEditorInput';
import { Registry } from 'vs/platform/registry/common/platform';
import { ResourceMap } from 'vs/base/common/map';
import { IUntitledTextEditorService } from 'vs/workbench/services/untitled/common/untitledTextEditorService';
import { IFileService, FileOperationEvent, FileOperation, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
import { Schemas } from 'vs/base/common/network';
import { Event, Emitter } from 'vs/base/common/event';
import { URI } from 'vs/base/common/uri';
import { basename, joinPath } from 'vs/base/common/resources';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IEditorGroupsService, IEditorGroup, GroupsOrder, IEditorReplacement, GroupChangeKind, preferredSideBySideGroupDirection, isEditorReplacement, isEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { SIDE_GROUP, IUntypedEditorReplacement, IEditorService, SIDE_GROUP_TYPE, ACTIVE_GROUP_TYPE, ISaveEditorsOptions, ISaveAllEditorsOptions, IRevertAllEditorsOptions, IBaseSaveRevertAllEditorOptions, IOpenEditorsOptions } from 'vs/workbench/services/editor/common/editorService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable, IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle';
import { coalesce, distinct } from 'vs/base/common/arrays';
import { isCodeEditor, isDiffEditor, ICodeEditor, IDiffEditor, isCompositeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorGroupView, EditorServiceImpl } from 'vs/workbench/browser/parts/editor/editor';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { isUndefined, withNullAsUndefined } from 'vs/base/common/types';
import { EditorsObserver } from 'vs/workbench/browser/parts/editor/editorsObserver';
import { IUntitledTextEditorModel } from 'vs/workbench/services/untitled/common/untitledTextEditorModel';
import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput';
import { Promises, timeout } from 'vs/base/common/async';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { indexOfPath } from 'vs/base/common/extpath';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
import { RegisteredEditorPriority, IEditorOverrideService, OverrideStatus, ReturnedOverride } from 'vs/workbench/services/editor/common/editorOverrideService';
import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { IWorkspaceTrustRequestService, WorkspaceTrustUriResponse } from 'vs/platform/workspace/common/workspaceTrust';
import { IHostService } from 'vs/workbench/services/host/browser/host';
type CachedEditorInput = TextResourceEditorInput | IFileEditorInput | UntitledTextEditorInput;
type OpenInEditorGroup = IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE;
function isOpenInEditorGroup(obj: unknown): obj is OpenInEditorGroup {
const candidate = obj as OpenInEditorGroup | undefined;
return typeof obj === 'number' || isEditorGroup(candidate);
}
export class EditorService extends Disposable implements EditorServiceImpl {
declare readonly _serviceBrand: undefined;
//#region events
private readonly _onDidActiveEditorChange = this._register(new Emitter<void>());
readonly onDidActiveEditorChange = this._onDidActiveEditorChange.event;
private readonly _onDidVisibleEditorsChange = this._register(new Emitter<void>());
readonly onDidVisibleEditorsChange = this._onDidVisibleEditorsChange.event;
private readonly _onDidCloseEditor = this._register(new Emitter<IEditorCloseEvent>());
readonly onDidCloseEditor = this._onDidCloseEditor.event;
private readonly _onDidOpenEditorFail = this._register(new Emitter<IEditorIdentifier>());
readonly onDidOpenEditorFail = this._onDidOpenEditorFail.event;
private readonly _onDidMostRecentlyActiveEditorsChange = this._register(new Emitter<void>());
readonly onDidMostRecentlyActiveEditorsChange = this._onDidMostRecentlyActiveEditorsChange.event;
//#endregion
private readonly fileEditorInputFactory = Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).getFileEditorInputFactory();
constructor(
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IUntitledTextEditorService private readonly untitledTextEditorService: IUntitledTextEditorService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IEditorOverrideService private readonly editorOverrideService: IEditorOverrideService,
@IWorkingCopyService private readonly workingCopyService: IWorkingCopyService,
@IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService,
@IHostService private readonly hostService: IHostService,
) {
super();
this.onConfigurationUpdated(configurationService.getValue<IWorkbenchEditorConfiguration>());
this.registerListeners();
// Register the default editor to the override service
// so that it shows up in the editors picker
this.registerDefaultOverride();
}
private registerListeners(): void {
// Editor & group changes
this.editorGroupService.whenReady.then(() => this.onEditorGroupsReady());
this.editorGroupService.onDidChangeActiveGroup(group => this.handleActiveEditorChange(group));
this.editorGroupService.onDidAddGroup(group => this.registerGroupListeners(group as IEditorGroupView));
this.editorsObserver.onDidMostRecentlyActiveEditorsChange(() => this._onDidMostRecentlyActiveEditorsChange.fire());
// Out of workspace file watchers
this._register(this.onDidVisibleEditorsChange(() => this.handleVisibleEditorsChange()));
// File changes & operations
// Note: there is some duplication with the two file event handlers- Since we cannot always rely on the disk events
// carrying all necessary data in all environments, we also use the file operation events to make sure operations are handled.
// In any case there is no guarantee if the local event is fired first or the disk one. Thus, code must handle the case
// that the event ordering is random as well as might not carry all information needed.
this._register(this.fileService.onDidRunOperation(e => this.onDidRunFileOperation(e)));
this._register(this.fileService.onDidFilesChange(e => this.onDidFilesChange(e)));
// Configuration
this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(this.configurationService.getValue<IWorkbenchEditorConfiguration>())));
}
private registerDefaultOverride(): void {
this._register(this.editorOverrideService.registerEditor(
'*',
{
id: DEFAULT_EDITOR_ASSOCIATION.id,
label: DEFAULT_EDITOR_ASSOCIATION.displayName,
detail: DEFAULT_EDITOR_ASSOCIATION.providerDisplayName,
priority: RegisteredEditorPriority.builtin
},
{},
editor => ({ editor: this.createEditorInput(editor) }),
untitledEditor => ({ editor: this.createEditorInput(untitledEditor) }),
diffEditor => ({ editor: this.createEditorInput(diffEditor) })
));
}
//#region Editor & group event handlers
private lastActiveEditor: IEditorInput | undefined = undefined;
private onEditorGroupsReady(): void {
// Register listeners to each opened group
for (const group of this.editorGroupService.groups) {
this.registerGroupListeners(group as IEditorGroupView);
}
// Fire initial set of editor events if there is an active editor
if (this.activeEditor) {
this.doHandleActiveEditorChangeEvent();
this._onDidVisibleEditorsChange.fire();
}
}
private handleActiveEditorChange(group: IEditorGroup): void {
if (group !== this.editorGroupService.activeGroup) {
return; // ignore if not the active group
}
if (!this.lastActiveEditor && !group.activeEditor) {
return; // ignore if we still have no active editor
}
this.doHandleActiveEditorChangeEvent();
}
private doHandleActiveEditorChangeEvent(): void {
// Remember as last active
const activeGroup = this.editorGroupService.activeGroup;
this.lastActiveEditor = withNullAsUndefined(activeGroup.activeEditor);
// Fire event to outside parties
this._onDidActiveEditorChange.fire();
}
private registerGroupListeners(group: IEditorGroupView): void {
const groupDisposables = new DisposableStore();
groupDisposables.add(group.onDidGroupChange(e => {
if (e.kind === GroupChangeKind.EDITOR_ACTIVE) {
this.handleActiveEditorChange(group);
this._onDidVisibleEditorsChange.fire();
}
}));
groupDisposables.add(group.onDidCloseEditor(event => {
this._onDidCloseEditor.fire(event);
}));
groupDisposables.add(group.onDidOpenEditorFail(editor => {
this._onDidOpenEditorFail.fire({ editor, groupId: group.id });
}));
Event.once(group.onWillDispose)(() => {
dispose(groupDisposables);
});
}
//#endregion
//#region Visible Editors Change: Install file watchers for out of workspace resources that became visible
private readonly activeOutOfWorkspaceWatchers = new ResourceMap<IDisposable>();
private handleVisibleEditorsChange(): void {
const visibleOutOfWorkspaceResources = new ResourceMap<URI>();
for (const editor of this.visibleEditors) {
const resources = distinct(coalesce([
EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }),
EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY })
]), resource => resource.toString());
for (const resource of resources) {
if (this.fileService.canHandleResource(resource) && !this.contextService.isInsideWorkspace(resource)) {
visibleOutOfWorkspaceResources.set(resource, resource);
}
}
}
// Handle no longer visible out of workspace resources
for (const resource of this.activeOutOfWorkspaceWatchers.keys()) {
if (!visibleOutOfWorkspaceResources.get(resource)) {
dispose(this.activeOutOfWorkspaceWatchers.get(resource));
this.activeOutOfWorkspaceWatchers.delete(resource);
}
}
// Handle newly visible out of workspace resources
for (const resource of visibleOutOfWorkspaceResources.keys()) {
if (!this.activeOutOfWorkspaceWatchers.get(resource)) {
const disposable = this.fileService.watch(resource);
this.activeOutOfWorkspaceWatchers.set(resource, disposable);
}
}
}
//#endregion
//#region File Changes: Move & Deletes to move or close opend editors
private onDidRunFileOperation(e: FileOperationEvent): void {
// Handle moves specially when file is opened
if (e.isOperation(FileOperation.MOVE)) {
this.handleMovedFile(e.resource, e.target.resource);
}
// Handle deletes
if (e.isOperation(FileOperation.DELETE) || e.isOperation(FileOperation.MOVE)) {
this.handleDeletedFile(e.resource, false, e.target ? e.target.resource : undefined);
}
}
private onDidFilesChange(e: FileChangesEvent): void {
if (e.gotDeleted()) {
this.handleDeletedFile(e, true);
}
}
private handleMovedFile(source: URI, target: URI): void {
for (const group of this.editorGroupService.groups) {
let replacements: (IUntypedEditorReplacement | IEditorReplacement)[] = [];
for (const editor of group.editors) {
const resource = editor.resource;
if (!resource || !this.uriIdentityService.extUri.isEqualOrParent(resource, source)) {
continue; // not matching our resource
}
// Determine new resulting target resource
let targetResource: URI;
if (this.uriIdentityService.extUri.isEqual(source, resource)) {
targetResource = target; // file got moved
} else {
const index = indexOfPath(resource.path, source.path, this.uriIdentityService.extUri.ignorePathCasing(resource));
targetResource = joinPath(target, resource.path.substr(index + source.path.length + 1)); // parent folder got moved
}
// Delegate rename() to editor instance
const moveResult = editor.rename(group.id, targetResource);
if (!moveResult) {
return; // not target - ignore
}
const optionOverrides = {
preserveFocus: true,
pinned: group.isPinned(editor),
sticky: group.isSticky(editor),
index: group.getIndexOfEditor(editor),
inactive: !group.isActive(editor)
};
// Construct a replacement with our extra options mixed in
if (isEditorInput(moveResult.editor)) {
replacements.push({
editor,
replacement: moveResult.editor,
options: {
...moveResult.options,
...optionOverrides
}
});
} else {
replacements.push({
editor,
replacement: {
...moveResult.editor,
options: {
...moveResult.editor.options,
...optionOverrides
}
}
});
}
}
// Apply replacements
if (replacements.length) {
this.replaceEditors(replacements, group);
}
}
}
private closeOnFileDelete: boolean = false;
private onConfigurationUpdated(configuration: IWorkbenchEditorConfiguration): void {
if (typeof configuration.workbench?.editor?.closeOnFileDelete === 'boolean') {
this.closeOnFileDelete = configuration.workbench.editor.closeOnFileDelete;
} else {
this.closeOnFileDelete = false; // default
}
}
private handleDeletedFile(arg1: URI | FileChangesEvent, isExternal: boolean, movedTo?: URI): void {
for (const editor of this.getAllNonDirtyEditors({ includeUntitled: false, supportSideBySide: true })) {
(async () => {
const resource = editor.resource;
if (!resource) {
return;
}
// Handle deletes in opened editors depending on:
// - we close any editor when `closeOnFileDelete: true`
// - we close any editor when the delete occurred from within VSCode
// - we close any editor without resolved working copy assuming that
// this editor could not be opened after the file is gone
if (this.closeOnFileDelete || !isExternal || !this.workingCopyService.has(resource)) {
// Do NOT close any opened editor that matches the resource path (either equal or being parent) of the
// resource we move to (movedTo). Otherwise we would close a resource that has been renamed to the same
// path but different casing.
if (movedTo && this.uriIdentityService.extUri.isEqualOrParent(resource, movedTo)) {
return;
}
let matches = false;
if (arg1 instanceof FileChangesEvent) {
matches = arg1.contains(resource, FileChangeType.DELETED);
} else {
matches = this.uriIdentityService.extUri.isEqualOrParent(resource, arg1);
}
if (!matches) {
return;
}
// We have received reports of users seeing delete events even though the file still
// exists (network shares issue: https://github.com/microsoft/vscode/issues/13665).
// Since we do not want to close an editor without reason, we have to check if the
// file is really gone and not just a faulty file event.
// This only applies to external file events, so we need to check for the isExternal
// flag.
let exists = false;
if (isExternal && this.fileService.canHandleResource(resource)) {
await timeout(100);
exists = await this.fileService.exists(resource);
}
if (!exists && !editor.isDisposed()) {
editor.dispose();
}
}
})();
}
}
private getAllNonDirtyEditors(options: { includeUntitled: boolean, supportSideBySide: boolean }): IEditorInput[] {
const editors: IEditorInput[] = [];
function conditionallyAddEditor(editor: IEditorInput): void {
if (editor.hasCapability(EditorInputCapabilities.Untitled) && !options.includeUntitled) {
return;
}
if (editor.isDirty()) {
return;
}
editors.push(editor);
}
for (const editor of this.editors) {
if (options.supportSideBySide && editor instanceof SideBySideEditorInput) {
conditionallyAddEditor(editor.primary);
conditionallyAddEditor(editor.secondary);
} else {
conditionallyAddEditor(editor);
}
}
return editors;
}
//#endregion
//#region Editor accessors
private readonly editorsObserver = this._register(this.instantiationService.createInstance(EditorsObserver));
get activeEditorPane(): IVisibleEditorPane | undefined {
return this.editorGroupService.activeGroup?.activeEditorPane;
}
get activeTextEditorControl(): ICodeEditor | IDiffEditor | undefined {
const activeEditorPane = this.activeEditorPane;
if (activeEditorPane) {
const activeControl = activeEditorPane.getControl();
if (isCodeEditor(activeControl) || isDiffEditor(activeControl)) {
return activeControl;
}
if (isCompositeEditor(activeControl) && isCodeEditor(activeControl.activeCodeEditor)) {
return activeControl.activeCodeEditor;
}
}
return undefined;
}
get activeTextEditorMode(): string | undefined {
let activeCodeEditor: ICodeEditor | undefined = undefined;
const activeTextEditorControl = this.activeTextEditorControl;
if (isDiffEditor(activeTextEditorControl)) {
activeCodeEditor = activeTextEditorControl.getModifiedEditor();
} else {
activeCodeEditor = activeTextEditorControl;
}
return activeCodeEditor?.getModel()?.getLanguageIdentifier().language;
}
get count(): number {
return this.editorsObserver.count;
}
get editors(): IEditorInput[] {
return this.getEditors(EditorsOrder.SEQUENTIAL).map(({ editor }) => editor);
}
getEditors(order: EditorsOrder, options?: { excludeSticky?: boolean }): readonly IEditorIdentifier[] {
switch (order) {
// MRU
case EditorsOrder.MOST_RECENTLY_ACTIVE:
if (options?.excludeSticky) {
return this.editorsObserver.editors.filter(({ groupId, editor }) => !this.editorGroupService.getGroup(groupId)?.isSticky(editor));
}
return this.editorsObserver.editors;
// Sequential
case EditorsOrder.SEQUENTIAL:
const editors: IEditorIdentifier[] = [];
for (const group of this.editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)) {
editors.push(...group.getEditors(EditorsOrder.SEQUENTIAL, options).map(editor => ({ editor, groupId: group.id })));
}
return editors;
}
}
get activeEditor(): IEditorInput | undefined {
const activeGroup = this.editorGroupService.activeGroup;
return activeGroup ? withNullAsUndefined(activeGroup.activeEditor) : undefined;
}
get visibleEditorPanes(): IVisibleEditorPane[] {
return coalesce(this.editorGroupService.groups.map(group => group.activeEditorPane));
}
get visibleTextEditorControls(): Array<ICodeEditor | IDiffEditor> {
const visibleTextEditorControls: Array<ICodeEditor | IDiffEditor> = [];
for (const visibleEditorPane of this.visibleEditorPanes) {
const control = visibleEditorPane.getControl();
if (isCodeEditor(control) || isDiffEditor(control)) {
visibleTextEditorControls.push(control);
}
}
return visibleTextEditorControls;
}
get visibleEditors(): IEditorInput[] {
return coalesce(this.editorGroupService.groups.map(group => group.activeEditor));
}
//#endregion
//#region openEditor()
openEditor(editor: IEditorInput, options?: IEditorOptions, group?: OpenInEditorGroup): Promise<IEditorPane | undefined>;
openEditor(editor: IResourceEditorInput, group?: OpenInEditorGroup): Promise<IEditorPane | undefined>;
openEditor(editor: ITextResourceEditorInput | IUntitledTextResourceEditorInput, group?: OpenInEditorGroup): Promise<ITextEditorPane | undefined>;
openEditor(editor: IResourceDiffEditorInput, group?: OpenInEditorGroup): Promise<ITextDiffEditorPane | undefined>;
async openEditor(editor: IEditorInput | IUntypedEditorInput, optionsOrPreferredGroup?: IEditorOptions | OpenInEditorGroup, preferredGroup?: OpenInEditorGroup): Promise<IEditorPane | undefined> {
let typedEditor: IEditorInput | undefined = undefined;
let options = isEditorInput(editor) ? optionsOrPreferredGroup as IEditorOptions : editor.options;
let group: IEditorGroup | undefined = undefined;
let activation: EditorActivation | undefined = undefined;
if (isOpenInEditorGroup(optionsOrPreferredGroup)) {
preferredGroup = optionsOrPreferredGroup;
}
// Resolve override unless disabled
if (options?.override !== EditorOverride.DISABLED) {
const [resolvedEditor, resolvedGroup, resolvedActivation] = await this.doResolveEditor(isEditorInput(editor) ? { editor, options } : editor, preferredGroup);
if (resolvedEditor === OverrideStatus.ABORT) {
return; // skip editor if override is aborted
}
group = resolvedGroup;
activation = resolvedActivation;
// We resolved an editor to use
if (isEditorInputWithOptions(resolvedEditor)) {
typedEditor = resolvedEditor.editor;
options = resolvedEditor.options;
}
}
// Override is disabled or did not apply
if (!typedEditor) {
typedEditor = isEditorInput(editor) ? editor : this.createEditorInput(editor);
}
// If group still isn't defined because of a disabled override we resolve it
if (!group) {
([group, activation] = this.findTargetGroup({ editor: typedEditor, options }, preferredGroup));
}
// Mixin editor group activation if any
if (activation) {
options = { ...options, activation };
}
return group.openEditor(typedEditor, options);
}
private async doResolveEditor(editor: IEditorInputWithOptions | IUntypedEditorInput, preferredGroup: OpenInEditorGroup | undefined): Promise<[ReturnedOverride, IEditorGroup | undefined, EditorActivation | undefined]> {
let untypedEditor: IUntypedEditorInput | undefined = undefined;
// Typed: convert to untyped to be able to resolve the override
if (isEditorInputWithOptions(editor)) {
untypedEditor = editor.editor.toUntyped(undefined, UntypedEditorContext.Default);
if (untypedEditor) {
// Preserve original options: specifically it is
// possible that a `override` was defined from
// the outside and we do not want to loose it.
untypedEditor.options = { ...untypedEditor.options, ...editor.options };
}
}
// Untyped: take as is
else {
untypedEditor = editor;
}
// Typed editors that cannot convert to untyped will be taken
// as is without override.
if (!untypedEditor) {
return [OverrideStatus.NONE, undefined, undefined];
}
// We need a `override` for the untyped editor if it is
// not there so we call into the editor override service
let hasConflictingDefaults = false;
if (typeof untypedEditor.options?.override !== 'string') {
const populatedInfo = await this.editorOverrideService.populateEditorId(untypedEditor);
if (!populatedInfo) {
return [OverrideStatus.ABORT, undefined, undefined]; // we could not resolve the editor id
}
hasConflictingDefaults = populatedInfo.conflictingDefault;
}
// If we didn't get an override just return as none and let the editor continue as normal
if (!untypedEditor.options?.override) {
return [OverrideStatus.NONE, undefined, undefined];
}
// Find the target group for the editor
const [group, activation] = this.findTargetGroup(untypedEditor, preferredGroup);
return [await this.editorOverrideService.resolveEditorInput(untypedEditor, group, hasConflictingDefaults), group, activation];
}
private findTargetGroup(editor: IEditorInputWithOptions, preferredGroup: OpenInEditorGroup | undefined): [IEditorGroup, EditorActivation | undefined];
private findTargetGroup(editor: IUntypedEditorInput, preferredGroup: OpenInEditorGroup | undefined): [IEditorGroup, EditorActivation | undefined];
private findTargetGroup(editor: IEditorInputWithOptions | IUntypedEditorInput, preferredGroup: OpenInEditorGroup | undefined): [IEditorGroup, EditorActivation | undefined] {
const group = this.doFindTargetGroup(editor, preferredGroup);
// Resolve editor activation strategy
let activation: EditorActivation | undefined = undefined;
if (
this.editorGroupService.activeGroup !== group && // only if target group is not already active
editor.options && !editor.options.inactive && // never for inactive editors
editor.options.preserveFocus && // only if preserveFocus
typeof editor.options.activation !== 'number' && // only if activation is not already defined (either true or false)
preferredGroup !== SIDE_GROUP // never for the SIDE_GROUP
) {
// If the resolved group is not the active one, we typically
// want the group to become active. There are a few cases
// where we stay away from encorcing this, e.g. if the caller
// is already providing `activation`.
//
// Specifically for historic reasons we do not activate a
// group is it is opened as `SIDE_GROUP` with `preserveFocus:true`.
// repeated Alt-clicking of files in the explorer always open
// into the same side group and not cause a group to be created each time.
activation = EditorActivation.ACTIVATE;
}
return [group, activation];
}
private doFindTargetGroup(editor: IEditorInputWithOptions | IUntypedEditorInput, preferredGroup: OpenInEditorGroup | undefined): IEditorGroup {
let group: IEditorGroup | undefined;
// Group: Instance of Group
if (preferredGroup && typeof preferredGroup !== 'number') {
group = preferredGroup;
}
// Group: Side by Side
else if (preferredGroup === SIDE_GROUP) {
group = this.findSideBySideGroup();
}
// Group: Specific Group
else if (typeof preferredGroup === 'number' && preferredGroup >= 0) {
group = this.editorGroupService.getGroup(preferredGroup);
}
// Group: Unspecified without a specific index to open
else if (!editor.options || typeof editor.options.index !== 'number') {
const groupsByLastActive = this.editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE);
// Respect option to reveal an editor if it is already visible in any group
if (editor.options?.revealIfVisible) {
for (const lastActiveGroup of groupsByLastActive) {
if (lastActiveGroup.isActive(editor)) {
group = lastActiveGroup;
break;
}
}
}
// Respect option to reveal an editor if it is open (not necessarily visible)
// Still prefer to reveal an editor in a group where the editor is active though.
if (!group) {
if (editor.options?.revealIfOpened || this.configurationService.getValue<boolean>('workbench.editor.revealIfOpen')) {
let groupWithInputActive: IEditorGroup | undefined = undefined;
let groupWithInputOpened: IEditorGroup | undefined = undefined;
for (const group of groupsByLastActive) {
if (group.contains(editor)) {
if (!groupWithInputOpened) {
groupWithInputOpened = group;
}
if (!groupWithInputActive && group.isActive(editor)) {
groupWithInputActive = group;
}
}
if (groupWithInputOpened && groupWithInputActive) {
break; // we found all groups we wanted
}
}
// Prefer a target group where the input is visible
group = groupWithInputActive || groupWithInputOpened;
}
}
}
// Fallback to active group if target not valid
if (!group) {
group = this.editorGroupService.activeGroup;
}
return group;
}
private findSideBySideGroup(): IEditorGroup {
const direction = preferredSideBySideGroupDirection(this.configurationService);
let neighbourGroup = this.editorGroupService.findGroup({ direction });
if (!neighbourGroup) {
neighbourGroup = this.editorGroupService.addGroup(this.editorGroupService.activeGroup, direction);
}
return neighbourGroup;
}
//#endregion
//#region openEditors()
openEditors(editors: IEditorInputWithOptions[], group?: OpenInEditorGroup, options?: IOpenEditorsOptions): Promise<IEditorPane[]>;
openEditors(editors: IUntypedEditorInput[], group?: OpenInEditorGroup, options?: IOpenEditorsOptions): Promise<IEditorPane[]>;
async openEditors(editors: Array<IEditorInputWithOptions | IUntypedEditorInput>, preferredGroup?: OpenInEditorGroup, options?: IOpenEditorsOptions): Promise<IEditorPane[]> {
// Pass all editors to trust service to determine if
// we should proceed with opening the editors if we
// are asked to validate trust.
if (options?.validateTrust) {
const editorsTrusted = await this.handleWorkspaceTrust(editors);
if (!editorsTrusted) {
return [];
}
}
// Find target groups for editors to open
const mapGroupToTypedEditors = new Map<IEditorGroup, Array<IEditorInputWithOptions>>();
for (const editor of editors) {
let typedEditor: IEditorInputWithOptions | undefined = undefined;
let group: IEditorGroup | undefined = undefined;
// Resolve override unless disabled
if (editor.options?.override !== EditorOverride.DISABLED) {
const [resolvedEditor, resolvedGroup] = await this.doResolveEditor(editor, preferredGroup);
if (resolvedEditor === OverrideStatus.ABORT) {
continue; // skip editor if override is aborted
}
group = resolvedGroup;
// We resolved an editor to use
if (isEditorInputWithOptions(resolvedEditor)) {
typedEditor = resolvedEditor;
}
}
// Override is disabled or did not apply
if (!typedEditor) {
typedEditor = isEditorInputWithOptions(editor) ? editor : { editor: this.createEditorInput(editor), options: editor.options };
}
// If group still isn't defined because of a disabled override we resolve it
if (!group) {
group = this.doFindTargetGroup(typedEditor, preferredGroup);
}
// Update map of groups to editors
let targetGroupEditors = mapGroupToTypedEditors.get(group);
if (!targetGroupEditors) {
targetGroupEditors = [];
mapGroupToTypedEditors.set(group, targetGroupEditors);
}
targetGroupEditors.push(typedEditor);
}
// Open in target groups
const result: Promise<IEditorPane | null>[] = [];
for (const [group, editors] of mapGroupToTypedEditors) {
result.push(group.openEditors(editors));
}
return coalesce(await Promises.settled(result));
}
private async handleWorkspaceTrust(editors: Array<IEditorInputWithOptions | IUntypedEditorInput>): Promise<boolean> {
const { resources, diffMode } = this.extractEditorResources(editors);
const trustResult = await this.workspaceTrustRequestService.requestOpenFilesTrust(resources);
switch (trustResult) {
case WorkspaceTrustUriResponse.Open:
return true;
case WorkspaceTrustUriResponse.OpenInNewWindow:
await this.hostService.openWindow(resources.map(resource => ({ fileUri: resource })), { forceNewWindow: true, diffMode });
return false;
case WorkspaceTrustUriResponse.Cancel:
return false;
}
}
private extractEditorResources(editors: Array<IEditorInputWithOptions | IUntypedEditorInput>): { resources: URI[], diffMode?: boolean } {
const resources = new ResourceMap<boolean>();
let diffMode = false;
for (const editor of editors) {
// Typed Editor
if (isEditorInputWithOptions(editor)) {
const resource = EditorResourceAccessor.getOriginalUri(editor.editor, { supportSideBySide: SideBySideEditor.BOTH });
if (URI.isUri(resource)) {
resources.set(resource, true);
} else if (resource) {
if (resource.primary) {
resources.set(resource.primary, true);
}
if (resource.secondary) {
resources.set(resource.secondary, true);
}
diffMode = editor.editor instanceof DiffEditorInput;
}
}
// Untyped editor
else {
if (isResourceDiffEditorInput(editor)) {
const originalResourceEditor = editor.original;
if (URI.isUri(originalResourceEditor.resource)) {
resources.set(originalResourceEditor.resource, true);
}
const modifiedResourceEditor = editor.modified;
if (URI.isUri(modifiedResourceEditor.resource)) {
resources.set(modifiedResourceEditor.resource, true);
}
diffMode = true;
} else if (isResourceEditorInput(editor)) {
resources.set(editor.resource, true);
}
}
}
return {
resources: Array.from(resources.keys()),
diffMode
};
}
//#endregion
//#region isOpened()
isOpened(editor: IResourceEditorInputIdentifier): boolean {
return this.editorsObserver.hasEditor({
resource: this.uriIdentityService.asCanonicalUri(editor.resource),
typeId: editor.typeId,
editorId: editor.editorId
});
}
//#endregion
//#region isOpened()
isVisible(editor: IEditorInput): boolean {
for (const group of this.editorGroupService.groups) {
if (group.activeEditor?.matches(editor)) {
return true;
}
}
return false;
}
//#endregion
//#region findEditors()
findEditors(resource: URI): readonly IEditorIdentifier[];
findEditors(editor: IResourceEditorInputIdentifier): readonly IEditorIdentifier[];
findEditors(resource: URI, group: IEditorGroup | GroupIdentifier): readonly IEditorInput[];
findEditors(editor: IResourceEditorInputIdentifier, group: IEditorGroup | GroupIdentifier): IEditorInput | undefined;
findEditors(arg1: URI | IResourceEditorInputIdentifier, arg2?: IEditorGroup | GroupIdentifier): readonly IEditorIdentifier[] | readonly IEditorInput[] | IEditorInput | undefined;
findEditors(arg1: URI | IResourceEditorInputIdentifier, arg2?: IEditorGroup | GroupIdentifier): readonly IEditorIdentifier[] | readonly IEditorInput[] | IEditorInput | undefined {
const resource = URI.isUri(arg1) ? arg1 : arg1.resource;
const typeId = URI.isUri(arg1) ? undefined : arg1.typeId;
// Do a quick check for the resource via the editor observer
// which is a very efficient way to find an editor by resource
if (!this.editorsObserver.hasEditors(resource)) {
if (URI.isUri(arg1) || isUndefined(arg2)) {
return [];
}
return undefined;
}
// Search only in specific group
if (!isUndefined(arg2)) {
const targetGroup = typeof arg2 === 'number' ? this.editorGroupService.getGroup(arg2) : arg2;
// Resource provided: result is an array
if (URI.isUri(arg1)) {
if (!targetGroup) {
return [];
}
return targetGroup.findEditors(resource);
}
// Editor identifier provided, result is single
else {
if (!targetGroup) {
return undefined;
}
const editors = targetGroup.findEditors(resource);
for (const editor of editors) {
if (editor.typeId === typeId) {
return editor;
}
}
return undefined;
}
}
// Search across all groups in MRU order
else {
const result: IEditorIdentifier[] = [];
for (const group of this.editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE)) {
const editors: IEditorInput[] = [];
// Resource provided: result is an array
if (URI.isUri(arg1)) {
editors.push(...this.findEditors(arg1, group));
}
// Editor identifier provided, result is single
else {
const editor = this.findEditors(arg1, group);
if (editor) {
editors.push(editor);
}
}
result.push(...editors.map(editor => ({ editor, groupId: group.id })));
}
return result;
}
}
//#endregion
//#region replaceEditors()
async replaceEditors(replacements: IUntypedEditorReplacement[], group: IEditorGroup | GroupIdentifier): Promise<void>;
async replaceEditors(replacements: IEditorReplacement[], group: IEditorGroup | GroupIdentifier): Promise<void>;
async replaceEditors(replacements: Array<IEditorReplacement | IUntypedEditorReplacement>, group: IEditorGroup | GroupIdentifier): Promise<void> {
const targetGroup = typeof group === 'number' ? this.editorGroupService.getGroup(group) : group;
// Convert all replacements to typed editors unless already
// typed and handle overrides properly.
const typedReplacements: IEditorReplacement[] = [];
for (const replacement of replacements) {
let typedReplacement: IEditorReplacement | undefined = undefined;
// Figure out the override rule based on options
let override: string | EditorOverride | undefined;
if (isEditorReplacement(replacement)) {
override = replacement.options?.override;
} else {
override = replacement.replacement.options?.override;
}
// Resolve override unless disabled
if (override !== EditorOverride.DISABLED) {
const [resolvedEditor] = await this.doResolveEditor(
isEditorReplacement(replacement) ? { editor: replacement.replacement, options: replacement.options } : replacement.replacement,
targetGroup
);
if (resolvedEditor === OverrideStatus.ABORT) {
continue; // skip editor if override is aborted
}
// We resolved an editor to use
if (isEditorInputWithOptions(resolvedEditor)) {