-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy patheditorGroupView.ts
1834 lines (1454 loc) · 61.3 KB
/
editorGroupView.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 'vs/css!./media/editorgroupview';
import { EditorGroupModel, IEditorOpenOptions, EditorCloseEvent, ISerializedEditorGroupModel, isSerializedEditorGroupModel } from 'vs/workbench/common/editor/editorGroupModel';
import { EditorInput, EditorOptions, GroupIdentifier, SideBySideEditorInput, CloseDirection, IEditorCloseEvent, ActiveEditorDirtyContext, IEditorPane, EditorGroupEditorsCountContext, SaveReason, IEditorPartOptionsChangeEvent, EditorsOrder, IVisibleEditorPane, ActiveEditorStickyContext, ActiveEditorPinnedContext, EditorResourceAccessor, IEditorMoveEvent } from 'vs/workbench/common/editor';
import { Event, Emitter, Relay } from 'vs/base/common/event';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Dimension, trackFocus, addDisposableListener, EventType, EventHelper, findParentWithClass, clearNode, isAncestor, asCSSUrl } from 'vs/base/browser/dom';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { attachProgressBarStyler } from 'vs/platform/theme/common/styler';
import { IThemeService, registerThemingParticipant, Themable } from 'vs/platform/theme/common/themeService';
import { editorBackground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { EDITOR_GROUP_HEADER_TABS_BACKGROUND, EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND, EDITOR_GROUP_EMPTY_BACKGROUND, EDITOR_GROUP_FOCUSED_EMPTY_BORDER, EDITOR_GROUP_HEADER_BORDER } from 'vs/workbench/common/theme';
import { ICloseEditorsFilter, IGroupChangeEvent, GroupChangeKind, GroupsOrder, ICloseEditorOptions, ICloseAllEditorsOptions, IEditorReplacement } from 'vs/workbench/services/editor/common/editorGroupsService';
import { TabsTitleControl } from 'vs/workbench/browser/parts/editor/tabsTitleControl';
import { EditorControl } from 'vs/workbench/browser/parts/editor/editorControl';
import { IEditorProgressService } from 'vs/platform/progress/common/progress';
import { EditorProgressIndicator } from 'vs/workbench/services/progress/browser/progressIndicator';
import { localize } from 'vs/nls';
import { isErrorWithActions, isPromiseCanceledError } from 'vs/base/common/errors';
import { dispose, MutableDisposable } from 'vs/base/common/lifecycle';
import { Severity, INotificationService } from 'vs/platform/notification/common/notification';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Promises, RunOnceWorker } from 'vs/base/common/async';
import { EventType as TouchEventType, GestureEvent } from 'vs/base/browser/touch';
import { TitleControl } from 'vs/workbench/browser/parts/editor/titleControl';
import { IEditorGroupsAccessor, IEditorGroupView, getActiveTextEditorOptions, EditorServiceImpl, IEditorGroupTitleHeight } from 'vs/workbench/browser/parts/editor/editor';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ActionRunner, IAction, Action } from 'vs/base/common/actions';
import { CLOSE_EDITOR_GROUP_COMMAND_ID } from 'vs/workbench/browser/parts/editor/editorCommands';
import { NoTabsTitleControl } from 'vs/workbench/browser/parts/editor/noTabsTitleControl';
import { IMenuService, MenuId, IMenu } from 'vs/platform/actions/common/actions';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { hash } from 'vs/base/common/hash';
import { guessMimeTypes } from 'vs/base/common/mime';
import { extname, isEqual } from 'vs/base/common/resources';
import { FileAccess, Schemas } from 'vs/base/common/network';
import { EditorActivation, EditorOpenContext } from 'vs/platform/editor/common/editor';
import { IDialogService, IFileDialogService, ConfirmResult } from 'vs/platform/dialogs/common/dialogs';
import { ILogService } from 'vs/platform/log/common/log';
import { Codicon } from 'vs/base/common/codicons';
import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
import { withNullAsUndefined } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
export class EditorGroupView extends Themable implements IEditorGroupView {
//#region factory
static createNew(accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView {
return instantiationService.createInstance(EditorGroupView, accessor, null, index);
}
static createFromSerialized(serialized: ISerializedEditorGroupModel, accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView {
return instantiationService.createInstance(EditorGroupView, accessor, serialized, index);
}
static createCopy(copyFrom: IEditorGroupView, accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView {
return instantiationService.createInstance(EditorGroupView, accessor, copyFrom, index);
}
//#endregion
/**
* Access to the context key service scoped to this editor group.
*/
readonly scopedContextKeyService: IContextKeyService;
//#region events
private readonly _onDidFocus = this._register(new Emitter<void>());
readonly onDidFocus = this._onDidFocus.event;
private readonly _onWillDispose = this._register(new Emitter<void>());
readonly onWillDispose = this._onWillDispose.event;
private readonly _onDidGroupChange = this._register(new Emitter<IGroupChangeEvent>());
readonly onDidGroupChange = this._onDidGroupChange.event;
private readonly _onDidOpenEditorFail = this._register(new Emitter<EditorInput>());
readonly onDidOpenEditorFail = this._onDidOpenEditorFail.event;
private readonly _onWillCloseEditor = this._register(new Emitter<IEditorCloseEvent>());
readonly onWillCloseEditor = this._onWillCloseEditor.event;
private readonly _onDidCloseEditor = this._register(new Emitter<IEditorCloseEvent>());
readonly onDidCloseEditor = this._onDidCloseEditor.event;
private readonly _onWillMoveEditor = this._register(new Emitter<IEditorMoveEvent>());
readonly onWillMoveEditor = this._onWillMoveEditor.event;
//#endregion
private readonly model: EditorGroupModel;
private active: boolean | undefined;
private dimension: Dimension | undefined;
private readonly scopedInstantiationService: IInstantiationService;
private readonly titleContainer: HTMLElement;
private titleAreaControl: TitleControl;
private readonly progressBar: ProgressBar;
private readonly editorContainer: HTMLElement;
private readonly editorControl: EditorControl;
private readonly disposedEditorsWorker = this._register(new RunOnceWorker<EditorInput>(editors => this.handleDisposedEditors(editors), 0));
private readonly mapEditorToPendingConfirmation = new Map<EditorInput, Promise<boolean>>();
private whenRestoredResolve: (() => void) | undefined;
readonly whenRestored = new Promise<void>(resolve => (this.whenRestoredResolve = resolve));
private isRestored = false;
constructor(
private accessor: IEditorGroupsAccessor,
from: IEditorGroupView | ISerializedEditorGroupModel | null,
private _index: number,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IThemeService themeService: IThemeService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IMenuService private readonly menuService: IMenuService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@ILogService private readonly logService: ILogService,
@IEditorService private readonly editorService: EditorServiceImpl,
@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService
) {
super(themeService);
if (from instanceof EditorGroupView) {
this.model = this._register(from.model.clone());
} else if (isSerializedEditorGroupModel(from)) {
this.model = this._register(instantiationService.createInstance(EditorGroupModel, from));
} else {
this.model = this._register(instantiationService.createInstance(EditorGroupModel, undefined));
}
//#region create()
{
// Container
this.element.classList.add('editor-group-container');
// Container listeners
this.registerContainerListeners();
// Container toolbar
this.createContainerToolbar();
// Container context menu
this.createContainerContextMenu();
// Letterpress container
const letterpressContainer = document.createElement('div');
letterpressContainer.classList.add('editor-group-letterpress');
this.element.appendChild(letterpressContainer);
// Progress bar
this.progressBar = this._register(new ProgressBar(this.element));
this._register(attachProgressBarStyler(this.progressBar, this.themeService));
this.progressBar.hide();
// Scoped services
this.scopedContextKeyService = this._register(this.contextKeyService.createScoped(this.element));
this.scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection(
[IContextKeyService, this.scopedContextKeyService],
[IEditorProgressService, this._register(new EditorProgressIndicator(this.progressBar, this))]
));
// Context keys
this.handleGroupContextKeys();
// Title container
this.titleContainer = document.createElement('div');
this.titleContainer.classList.add('title');
this.element.appendChild(this.titleContainer);
// Title control
this.titleAreaControl = this.createTitleAreaControl();
// Editor container
this.editorContainer = document.createElement('div');
this.editorContainer.classList.add('editor-container');
this.element.appendChild(this.editorContainer);
// Editor control
this.editorControl = this._register(this.scopedInstantiationService.createInstance(EditorControl, this.editorContainer, this));
this._onDidChange.input = this.editorControl.onDidChangeSizeConstraints;
// Track Focus
this.doTrackFocus();
// Update containers
this.updateTitleContainer();
this.updateContainer();
// Update styles
this.updateStyles();
}
//#endregion
// Restore editors if provided
const restoreEditorsPromise = this.restoreEditors(from) ?? Promise.resolve();
// Signal restored once editors have restored
restoreEditorsPromise.finally(() => {
this.isRestored = true;
this.whenRestoredResolve?.();
});
// Register Listeners
this.registerListeners();
}
private handleGroupContextKeys(): void {
const groupActiveEditorDirtyContext = ActiveEditorDirtyContext.bindTo(this.scopedContextKeyService);
const groupActiveEditorPinnedContext = ActiveEditorPinnedContext.bindTo(this.scopedContextKeyService);
const groupActiveEditorStickyContext = ActiveEditorStickyContext.bindTo(this.scopedContextKeyService);
const groupEditorsCountContext = EditorGroupEditorsCountContext.bindTo(this.scopedContextKeyService);
const activeEditorListener = new MutableDisposable();
const observeActiveEditor = () => {
activeEditorListener.clear();
const activeEditor = this.model.activeEditor;
if (activeEditor) {
groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving());
activeEditorListener.value = activeEditor.onDidChangeDirty(() => {
groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving());
});
} else {
groupActiveEditorDirtyContext.set(false);
}
};
// Update group contexts based on group changes
this._register(this.onDidGroupChange(e => {
switch (e.kind) {
case GroupChangeKind.EDITOR_ACTIVE:
// Track the active editor and update context key that reflects
// the dirty state of this editor
observeActiveEditor();
break;
case GroupChangeKind.EDITOR_PIN:
if (e.editor && e.editor === this.model.activeEditor) {
groupActiveEditorPinnedContext.set(this.model.isPinned(this.model.activeEditor));
}
break;
case GroupChangeKind.EDITOR_STICKY:
if (e.editor && e.editor === this.model.activeEditor) {
groupActiveEditorStickyContext.set(this.model.isSticky(this.model.activeEditor));
}
break;
}
// Group editors count context
groupEditorsCountContext.set(this.count);
}));
observeActiveEditor();
}
private registerContainerListeners(): void {
// Open new file via doubleclick on empty container
this._register(addDisposableListener(this.element, EventType.DBLCLICK, e => {
if (this.isEmpty) {
EventHelper.stop(e);
this.openEditor(this.editorService.createEditorInput({ forceUntitled: true }), EditorOptions.create({ pinned: true }));
}
}));
// Close empty editor group via middle mouse click
this._register(addDisposableListener(this.element, EventType.AUXCLICK, e => {
if (this.isEmpty && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
this.accessor.removeGroup(this);
}
}));
}
private createContainerToolbar(): void {
// Toolbar Container
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('editor-group-container-toolbar');
this.element.appendChild(toolbarContainer);
// Toolbar
const groupId = this.model.id;
const containerToolbar = this._register(new ActionBar(toolbarContainer, {
ariaLabel: localize('ariaLabelGroupActions', "Editor group actions"), actionRunner: this._register(new class extends ActionRunner {
override async run(action: IAction) {
await action.run(groupId);
}
})
}));
// Toolbar actions
const removeGroupAction = this._register(new Action(
CLOSE_EDITOR_GROUP_COMMAND_ID,
localize('closeGroupAction', "Close"),
Codicon.close.classNames,
true,
async () => this.accessor.removeGroup(this)));
const keybinding = this.keybindingService.lookupKeybinding(removeGroupAction.id);
containerToolbar.push(removeGroupAction, { icon: true, label: false, keybinding: keybinding ? keybinding.getLabel() : undefined });
}
private createContainerContextMenu(): void {
const menu = this._register(this.menuService.createMenu(MenuId.EmptyEditorGroupContext, this.contextKeyService));
this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, e => this.onShowContainerContextMenu(menu, e)));
this._register(addDisposableListener(this.element, TouchEventType.Contextmenu, () => this.onShowContainerContextMenu(menu)));
}
private onShowContainerContextMenu(menu: IMenu, e?: MouseEvent): void {
if (!this.isEmpty) {
return; // only for empty editor groups
}
// Find target anchor
let anchor: HTMLElement | { x: number, y: number } = this.element;
if (e instanceof MouseEvent) {
const event = new StandardMouseEvent(e);
anchor = { x: event.posx, y: event.posy };
}
// Fill in contributed actions
const actions: IAction[] = [];
const actionsDisposable = createAndFillInContextMenuActions(menu, undefined, actions);
// Show it
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => actions,
onHide: () => {
this.focus();
dispose(actionsDisposable);
}
});
}
private doTrackFocus(): void {
// Container
const containerFocusTracker = this._register(trackFocus(this.element));
this._register(containerFocusTracker.onDidFocus(() => {
if (this.isEmpty) {
this._onDidFocus.fire(); // only when empty to prevent accident focus
}
}));
// Title Container
const handleTitleClickOrTouch = (e: MouseEvent | GestureEvent): void => {
let target: HTMLElement;
if (e instanceof MouseEvent) {
if (e.button !== 0) {
return undefined; // only for left mouse click
}
target = e.target as HTMLElement;
} else {
target = (e as GestureEvent).initialTarget as HTMLElement;
}
if (findParentWithClass(target, 'monaco-action-bar', this.titleContainer) ||
findParentWithClass(target, 'monaco-breadcrumb-item', this.titleContainer)
) {
return; // not when clicking on actions or breadcrumbs
}
// timeout to keep focus in editor after mouse up
setTimeout(() => {
this.focus();
});
};
this._register(addDisposableListener(this.titleContainer, EventType.MOUSE_DOWN, e => handleTitleClickOrTouch(e)));
this._register(addDisposableListener(this.titleContainer, TouchEventType.Tap, e => handleTitleClickOrTouch(e)));
// Editor Container
this._register(this.editorControl.onDidFocus(() => {
this._onDidFocus.fire();
}));
}
private updateContainer(): void {
// Empty Container: add some empty container attributes
if (this.isEmpty) {
this.element.classList.add('empty');
this.element.tabIndex = 0;
this.element.setAttribute('aria-label', localize('emptyEditorGroup', "{0} (empty)", this.label));
}
// Non-Empty Container: revert empty container attributes
else {
this.element.classList.remove('empty');
this.element.removeAttribute('tabIndex');
this.element.removeAttribute('aria-label');
}
// Update styles
this.updateStyles();
}
private updateTitleContainer(): void {
this.titleContainer.classList.toggle('tabs', this.accessor.partOptions.showTabs);
this.titleContainer.classList.toggle('show-file-icons', this.accessor.partOptions.showIcons);
}
private createTitleAreaControl(): TitleControl {
// Clear old if existing
if (this.titleAreaControl) {
this.titleAreaControl.dispose();
clearNode(this.titleContainer);
}
// Create new based on options
if (this.accessor.partOptions.showTabs) {
this.titleAreaControl = this.scopedInstantiationService.createInstance(TabsTitleControl, this.titleContainer, this.accessor, this);
} else {
this.titleAreaControl = this.scopedInstantiationService.createInstance(NoTabsTitleControl, this.titleContainer, this.accessor, this);
}
return this.titleAreaControl;
}
private restoreEditors(from: IEditorGroupView | ISerializedEditorGroupModel | null): Promise<void> | undefined {
if (this.model.count === 0) {
return; // nothing to show
}
// Determine editor options
let options: EditorOptions;
if (from instanceof EditorGroupView) {
options = getActiveTextEditorOptions(from); // if we copy from another group, ensure to copy its active editor viewstate
} else {
options = new EditorOptions();
}
const activeEditor = this.model.activeEditor;
if (!activeEditor) {
return;
}
options.pinned = this.model.isPinned(activeEditor); // preserve pinned state
options.sticky = this.model.isSticky(activeEditor); // preserve sticky state
options.preserveFocus = true; // handle focus after editor is opened
const activeElement = document.activeElement;
// Show active editor (intentionally not using async to keep
// `restoreEditors` from executing in same stack)
return this.doShowEditor(activeEditor, { active: true, isNew: false /* restored */ }, options).then(() => {
// Set focused now if this is the active group and focus has
// not changed meanwhile. This prevents focus from being
// stolen accidentally on startup when the user already
// clicked somewhere.
if (this.accessor.activeGroup === this && activeElement === document.activeElement) {
this.focus();
}
});
}
//#region event handling
private registerListeners(): void {
// Model Events
this._register(this.model.onDidChangeEditorPinned(editor => this.onDidChangeEditorPinned(editor)));
this._register(this.model.onDidChangeEditorSticky(editor => this.onDidChangeEditorSticky(editor)));
this._register(this.model.onDidOpenEditor(editor => this.onDidOpenEditor(editor)));
this._register(this.model.onDidCloseEditor(editor => this.handleOnDidCloseEditor(editor)));
this._register(this.model.onWillDisposeEditor(editor => this.onWillDisposeEditor(editor)));
this._register(this.model.onDidChangeEditorDirty(editor => this.onDidChangeEditorDirty(editor)));
this._register(this.model.onDidEditorLabelChange(editor => this.onDidEditorLabelChange(editor)));
// Option Changes
this._register(this.accessor.onDidChangeEditorPartOptions(e => this.onDidChangeEditorPartOptions(e)));
// Visibility
this._register(this.accessor.onDidVisibilityChange(e => this.onDidVisibilityChange(e)));
}
private onDidChangeEditorPinned(editor: EditorInput): void {
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_PIN, editor });
}
private onDidChangeEditorSticky(editor: EditorInput): void {
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_STICKY, editor });
}
private onDidOpenEditor(editor: EditorInput): void {
/* __GDPR__
"editorOpened" : {
"${include}": [
"${EditorTelemetryDescriptor}"
]
}
*/
this.telemetryService.publicLog('editorOpened', this.toEditorTelemetryDescriptor(editor));
// Update container
this.updateContainer();
// Event
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_OPEN, editor });
}
private handleOnDidCloseEditor(event: EditorCloseEvent): void {
// Before close
this._onWillCloseEditor.fire(event);
// Handle event
const editor = event.editor;
const editorsToClose = [editor];
// Include both sides of side by side editors when being closed
if (editor instanceof SideBySideEditorInput) {
editorsToClose.push(editor.primary, editor.secondary);
}
// For each editor to close, we call dispose() to free up any resources.
// However, certain editors might be shared across multiple editor groups
// (including being visible in side by side / diff editors) and as such we
// only dispose when they are not opened elsewhere.
for (const editor of editorsToClose) {
if (this.canDispose(editor)) {
editor.dispose();
}
}
/* __GDPR__
"editorClosed" : {
"${include}": [
"${EditorTelemetryDescriptor}"
]
}
*/
this.telemetryService.publicLog('editorClosed', this.toEditorTelemetryDescriptor(event.editor));
// Update container
this.updateContainer();
// Event
this._onDidCloseEditor.fire(event);
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_CLOSE, editor, editorIndex: event.index });
}
private canDispose(editor: EditorInput): boolean {
for (const groupView of this.accessor.groups) {
if (groupView instanceof EditorGroupView && groupView.model.contains(editor, {
strictEquals: true, // only if this input is not shared across editor groups
supportSideBySide: true // include side by side editor primary & secondary
})) {
return false;
}
}
return true;
}
private toEditorTelemetryDescriptor(editor: EditorInput): object {
const descriptor = editor.getTelemetryDescriptor();
const resource = EditorResourceAccessor.getOriginalUri(editor);
const path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined;
if (resource && path) {
descriptor['resource'] = { mimeType: guessMimeTypes(resource).join(', '), scheme: resource.scheme, ext: extname(resource), path: hash(path) };
/* __GDPR__FRAGMENT__
"EditorTelemetryDescriptor" : {
"resource": { "${inline}": [ "${URIDescriptor}" ] }
}
*/
return descriptor;
}
return descriptor;
}
private onWillDisposeEditor(editor: EditorInput): void {
// To prevent race conditions, we handle disposed editors in our worker with a timeout
// because it can happen that an input is being disposed with the intent to replace
// it with some other input right after.
this.disposedEditorsWorker.work(editor);
}
private handleDisposedEditors(editors: EditorInput[]): void {
// Split between visible and hidden editors
let activeEditor: EditorInput | undefined;
const inactiveEditors: EditorInput[] = [];
for (const editor of editors) {
if (this.model.isActive(editor)) {
activeEditor = editor;
} else if (this.model.contains(editor)) {
inactiveEditors.push(editor);
}
}
// Close all inactive editors first to prevent UI flicker
for (const inactiveEditor of inactiveEditors) {
this.doCloseEditor(inactiveEditor, false);
}
// Close active one last
if (activeEditor) {
this.doCloseEditor(activeEditor, false);
}
}
private onDidChangeEditorPartOptions(event: IEditorPartOptionsChangeEvent): void {
// Title container
this.updateTitleContainer();
// Title control Switch between showing tabs <=> not showing tabs
if (event.oldPartOptions.showTabs !== event.newPartOptions.showTabs) {
// Recreate title control
this.createTitleAreaControl();
// Re-layout
this.relayout();
// Ensure to show active editor if any
if (this.model.activeEditor) {
this.titleAreaControl.openEditor(this.model.activeEditor);
}
}
// Just update title control
else {
this.titleAreaControl.updateOptions(event.oldPartOptions, event.newPartOptions);
}
// Styles
this.updateStyles();
// Pin preview editor once user disables preview
if (event.oldPartOptions.enablePreview && !event.newPartOptions.enablePreview) {
if (this.model.previewEditor) {
this.pinEditor(this.model.previewEditor);
}
}
}
private onDidChangeEditorDirty(editor: EditorInput): void {
// Always show dirty editors pinned
this.pinEditor(editor);
// Forward to title control
this.titleAreaControl.updateEditorDirty(editor);
// Event
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_DIRTY, editor });
}
private onDidEditorLabelChange(editor: EditorInput): void {
// Forward to title control
this.titleAreaControl.updateEditorLabel(editor);
// Event
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_LABEL, editor });
}
private onDidVisibilityChange(visible: boolean): void {
// Forward to editor control
this.editorControl.setVisible(visible);
}
//#endregion
//#region IEditorGroupView
get index(): number {
return this._index;
}
get label(): string {
return localize('groupLabel', "Group {0}", this._index + 1);
}
get ariaLabel(): string {
return localize('groupAriaLabel', "Editor Group {0}", this._index + 1);
}
private _disposed = false;
get disposed(): boolean {
return this._disposed;
}
get isEmpty(): boolean {
return this.model.count === 0;
}
get titleHeight(): IEditorGroupTitleHeight {
return this.titleAreaControl.getHeight();
}
get isMinimized(): boolean {
if (!this.dimension) {
return false;
}
return this.dimension.width === this.minimumWidth || this.dimension.height === this.minimumHeight;
}
notifyIndexChanged(newIndex: number): void {
if (this._index !== newIndex) {
this._index = newIndex;
this._onDidGroupChange.fire({ kind: GroupChangeKind.GROUP_INDEX });
}
}
setActive(isActive: boolean): void {
this.active = isActive;
// Update container
this.element.classList.toggle('active', isActive);
this.element.classList.toggle('inactive', !isActive);
// Update title control
this.titleAreaControl.setActive(isActive);
// Update styles
this.updateStyles();
// Event
this._onDidGroupChange.fire({ kind: GroupChangeKind.GROUP_ACTIVE });
}
//#endregion
//#region IEditorGroup
//#region basics()
get id(): GroupIdentifier {
return this.model.id;
}
get editors(): EditorInput[] {
return this.model.getEditors(EditorsOrder.SEQUENTIAL);
}
get count(): number {
return this.model.count;
}
get stickyCount(): number {
return this.model.stickyCount;
}
get activeEditorPane(): IVisibleEditorPane | undefined {
return this.editorControl ? withNullAsUndefined(this.editorControl.activeEditorPane) : undefined;
}
get activeEditor(): EditorInput | null {
return this.model.activeEditor;
}
get previewEditor(): EditorInput | null {
return this.model.previewEditor;
}
isPinned(editor: EditorInput): boolean {
return this.model.isPinned(editor);
}
isSticky(editorOrIndex: EditorInput | number): boolean {
return this.model.isSticky(editorOrIndex);
}
isActive(editor: EditorInput): boolean {
return this.model.isActive(editor);
}
contains(candidate: EditorInput): boolean {
return this.model.contains(candidate);
}
getEditors(order: EditorsOrder, options?: { excludeSticky?: boolean }): EditorInput[] {
return this.model.getEditors(order, options);
}
findEditors(resource: URI): EditorInput[] {
const canonicalResource = this.uriIdentityService.asCanonicalUri(resource);
return this.getEditors(EditorsOrder.SEQUENTIAL).filter(editor => {
return editor.resource && isEqual(editor.resource, canonicalResource);
});
}
getEditorByIndex(index: number): EditorInput | undefined {
return this.model.getEditorByIndex(index);
}
getIndexOfEditor(editor: EditorInput): number {
return this.model.indexOf(editor);
}
focus(): void {
// Pass focus to editor panes
if (this.activeEditorPane) {
this.activeEditorPane.focus();
} else {
this.element.focus();
}
// Event
this._onDidFocus.fire();
}
pinEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void {
if (candidate && !this.model.isPinned(candidate)) {
// Update model
const editor = this.model.pin(candidate);
// Forward to title control
if (editor) {
this.titleAreaControl.pinEditor(editor);
}
}
}
stickEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void {
this.doStickEditor(candidate, true);
}
unstickEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void {
this.doStickEditor(candidate, false);
}
private doStickEditor(candidate: EditorInput | undefined, sticky: boolean): void {
if (candidate && this.model.isSticky(candidate) !== sticky) {
const oldIndexOfEditor = this.getIndexOfEditor(candidate);
// Update model
const editor = sticky ? this.model.stick(candidate) : this.model.unstick(candidate);
if (!editor) {
return;
}
// If the index of the editor changed, we need to forward this to
// title control and also make sure to emit this as an event
const newIndexOfEditor = this.getIndexOfEditor(editor);
if (newIndexOfEditor !== oldIndexOfEditor) {
this.titleAreaControl.moveEditor(editor, oldIndexOfEditor, newIndexOfEditor);
// Event
this._onDidGroupChange.fire({ kind: GroupChangeKind.EDITOR_MOVE, editor });
}
// Forward sticky state to title control
if (sticky) {
this.titleAreaControl.stickEditor(editor);
} else {
this.titleAreaControl.unstickEditor(editor);
}
}
}
//#endregion
//#region openEditor()
async openEditor(editor: EditorInput, options?: EditorOptions): Promise<IEditorPane | undefined> {
// Guard against invalid inputs
if (!editor) {
return undefined;
}
// Proceed with opening
return this.doOpenEditor(editor, options);
}
private async doOpenEditor(editor: EditorInput, options?: EditorOptions): Promise<IEditorPane | undefined> {
// Guard against invalid inputs. Disposed inputs
// should never open because they emit no events
// e.g. to indicate dirty changes.
if (editor.isDisposed()) {
return;
}
// Determine options
const openEditorOptions: IEditorOpenOptions = {
index: options ? options.index : undefined,
pinned: options?.sticky || !this.accessor.partOptions.enablePreview || editor.isDirty() || (options?.pinned ?? typeof options?.index === 'number' /* unless specified, prefer to pin when opening with index */) || (typeof options?.index === 'number' && this.model.isSticky(options.index)),
sticky: options?.sticky || (typeof options?.index === 'number' && this.model.isSticky(options.index)),
active: this.model.count === 0 || !options || !options.inactive
};
if (options?.sticky && typeof options?.index === 'number' && !this.model.isSticky(options.index)) {
// Special case: we are to open an editor sticky but at an index that is not sticky
// In that case we prefer to open the editor at the index but not sticky. This enables
// to drag a sticky editor to an index that is not sticky to unstick it.
openEditorOptions.sticky = false;
}
if (!openEditorOptions.active && !openEditorOptions.pinned && this.model.activeEditor && !this.model.isPinned(this.model.activeEditor)) {
// Special case: we are to open an editor inactive and not pinned, but the current active
// editor is also not pinned, which means it will get replaced with this one. As such,
// the editor can only be active.
openEditorOptions.active = true;
}
let activateGroup = false;
let restoreGroup = false;
if (options?.activation === EditorActivation.ACTIVATE) {
// Respect option to force activate an editor group.
activateGroup = true;
} else if (options?.activation === EditorActivation.RESTORE) {
// Respect option to force restore an editor group.
restoreGroup = true;
} else if (options?.activation === EditorActivation.PRESERVE) {
// Respect option to preserve active editor group.
activateGroup = false;
restoreGroup = false;
} else if (openEditorOptions.active) {
// Finally, we only activate/restore an editor which is
// opening as active editor.
// If preserveFocus is enabled, we only restore but never
// activate the group.
activateGroup = !options || !options.preserveFocus;
restoreGroup = !activateGroup;
}
// Actually move the editor if a specific index is provided and we figure
// out that the editor is already opened at a different index. This
// ensures the right set of events are fired to the outside.
if (typeof openEditorOptions.index === 'number') {
const indexOfEditor = this.model.indexOf(editor);
if (indexOfEditor !== -1 && indexOfEditor !== openEditorOptions.index) {
this.doMoveEditorInsideGroup(editor, openEditorOptions);
}
}
// Update model and make sure to continue to use the editor we get from
// the model. It is possible that the editor was already opened and we
// want to ensure that we use the existing instance in that case.
const { editor: openedEditor, isNew } = this.model.openEditor(editor, openEditorOptions);
// Show editor
const showEditorResult = this.doShowEditor(openedEditor, { active: !!openEditorOptions.active, isNew }, options);
// Finally make sure the group is active or restored as instructed
if (activateGroup) {
this.accessor.activateGroup(this);
} else if (restoreGroup) {
this.accessor.restoreGroup(this);
}
return showEditorResult;
}
private doShowEditor(editor: EditorInput, context: { active: boolean, isNew: boolean }, options?: EditorOptions): Promise<IEditorPane | undefined> {
// Show in editor control if the active editor changed
let openEditorPromise: Promise<IEditorPane | undefined>;
if (context.active) {
openEditorPromise = (async () => {
try {