-
Notifications
You must be signed in to change notification settings - Fork 29.5k
/
historyService.ts
2126 lines (1672 loc) · 70.5 KB
/
historyService.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 { localize } from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import { IResourceEditorInput, IEditorOptions } from 'vs/platform/editor/common/editor';
import { IEditorPane, IEditorCloseEvent, EditorResourceAccessor, IEditorIdentifier, GroupIdentifier, EditorsOrder, SideBySideEditor, IUntypedEditorInput, isResourceEditorInput, isEditorInput, isSideBySideEditorInput, EditorCloseContext, IEditorPaneSelection, EditorPaneSelectionCompareResult, EditorPaneSelectionChangeReason, isEditorPaneWithSelection, IEditorPaneSelectionChangeEvent, IEditorPaneWithSelection, IEditorWillMoveEvent, GroupModelChangeKind } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { GoFilter, GoScope, IHistoryService } from 'vs/workbench/services/history/common/history';
import { FileChangesEvent, IFileService, FileChangeType, FILES_EXCLUDE_CONFIG, FileOperationEvent, FileOperation } from 'vs/platform/files/common/files';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { dispose, Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { Emitter, Event } from 'vs/base/common/event';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { getExcludes, ISearchConfiguration, SEARCH_EXCLUDE_CONFIG } from 'vs/workbench/services/search/common/search';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { EditorServiceImpl } from 'vs/workbench/browser/parts/editor/editor';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { coalesce, remove } from 'vs/base/common/arrays';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { addDisposableListener, EventType, EventHelper, WindowIdleValue } from 'vs/base/browser/dom';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { Schemas } from 'vs/base/common/network';
import { onUnexpectedError } from 'vs/base/common/errors';
import { ResourceGlobMatcher } from 'vs/workbench/common/resources';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { ILifecycleService, LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ILogService, LogLevel } from 'vs/platform/log/common/log';
import { mainWindow } from 'vs/base/browser/window';
interface ISerializedEditorHistoryEntry {
readonly editor: Omit<IResourceEditorInput, 'resource'> & { resource: string };
}
interface IRecentlyClosedEditor {
readonly editorId: string | undefined;
readonly editor: IUntypedEditorInput;
readonly resource: URI | undefined;
readonly associatedResources: URI[];
readonly index: number;
readonly sticky: boolean;
}
export class HistoryService extends Disposable implements IHistoryService {
declare readonly _serviceBrand: undefined;
private static readonly MOUSE_NAVIGATION_SETTING = 'workbench.editor.mouseBackForwardToNavigate';
private static readonly NAVIGATION_SCOPE_SETTING = 'workbench.editor.navigationScope';
private readonly activeEditorListeners = this._register(new DisposableStore());
private lastActiveEditor: IEditorIdentifier | undefined = undefined;
private readonly editorHelper = this.instantiationService.createInstance(EditorHelper);
constructor(
@IEditorService private readonly editorService: EditorServiceImpl,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IStorageService private readonly storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IFileService private readonly fileService: IFileService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@ILogService private readonly logService: ILogService
) {
super();
this.registerListeners();
// if the service is created late enough that an editor is already opened
// make sure to trigger the onActiveEditorChanged() to track the editor
// properly (fixes https://github.com/microsoft/vscode/issues/59908)
if (this.editorService.activeEditorPane) {
this.onDidActiveEditorChange();
}
}
private registerListeners(): void {
// Mouse back/forward support
this.registerMouseNavigationListener();
// Editor changes
this._register(this.editorService.onDidActiveEditorChange(() => this.onDidActiveEditorChange()));
this._register(this.editorService.onDidOpenEditorFail(event => this.remove(event.editor)));
this._register(this.editorService.onDidCloseEditor(event => this.onDidCloseEditor(event)));
this._register(this.editorService.onDidMostRecentlyActiveEditorsChange(() => this.handleEditorEventInRecentEditorsStack()));
// Editor group changes
this._register(this.editorGroupService.onDidRemoveGroup(e => this.onDidRemoveGroup(e)));
// File changes
this._register(this.fileService.onDidFilesChange(event => this.onDidFilesChange(event)));
this._register(this.fileService.onDidRunOperation(event => this.onDidFilesChange(event)));
// Storage
this._register(this.storageService.onWillSaveState(() => this.saveState()));
// Configuration
this.registerEditorNavigationScopeChangeListener();
// Context keys
this._register(this.onDidChangeEditorNavigationStack(() => this.updateContextKeys()));
this._register(this.editorGroupService.onDidChangeActiveGroup(() => this.updateContextKeys()));
}
private onDidCloseEditor(e: IEditorCloseEvent): void {
this.handleEditorCloseEventInHistory(e);
this.handleEditorCloseEventInReopen(e);
}
private registerMouseNavigationListener(): void {
const mouseBackForwardSupportListener = this._register(new DisposableStore());
const handleMouseBackForwardSupport = () => {
mouseBackForwardSupportListener.clear();
if (this.configurationService.getValue(HistoryService.MOUSE_NAVIGATION_SETTING)) {
this._register(Event.runAndSubscribe(this.layoutService.onDidAddContainer, ({ container, disposables }) => {
const eventDisposables = disposables.add(new DisposableStore());
eventDisposables.add(addDisposableListener(container, EventType.MOUSE_DOWN, e => this.onMouseDownOrUp(e, true)));
eventDisposables.add(addDisposableListener(container, EventType.MOUSE_UP, e => this.onMouseDownOrUp(e, false)));
mouseBackForwardSupportListener.add(eventDisposables);
}, { container: this.layoutService.mainContainer, disposables: this._store }));
}
};
this._register(this.configurationService.onDidChangeConfiguration(event => {
if (event.affectsConfiguration(HistoryService.MOUSE_NAVIGATION_SETTING)) {
handleMouseBackForwardSupport();
}
}));
handleMouseBackForwardSupport();
}
private onMouseDownOrUp(event: MouseEvent, isMouseDown: boolean): void {
// Support to navigate in history when mouse buttons 4/5 are pressed
// We want to trigger this on mouse down for a faster experience
// but we also need to prevent mouse up from triggering the default
// which is to navigate in the browser history.
switch (event.button) {
case 3:
EventHelper.stop(event);
if (isMouseDown) {
this.goBack();
}
break;
case 4:
EventHelper.stop(event);
if (isMouseDown) {
this.goForward();
}
break;
}
}
private onDidRemoveGroup(group: IEditorGroup): void {
this.handleEditorGroupRemoveInNavigationStacks(group);
}
private onDidActiveEditorChange(): void {
const activeEditorGroup = this.editorGroupService.activeGroup;
const activeEditorPane = activeEditorGroup.activeEditorPane;
if (this.lastActiveEditor && this.editorHelper.matchesEditorIdentifier(this.lastActiveEditor, activeEditorPane)) {
return; // return if the active editor is still the same
}
// Remember as last active editor (can be undefined if none opened)
this.lastActiveEditor = activeEditorPane?.input ? { editor: activeEditorPane.input, groupId: activeEditorPane.group.id } : undefined;
// Dispose old listeners
this.activeEditorListeners.clear();
// Handle editor change unless the editor is transient. In that case
// setup a listener to see if the transient editor becomes non-transient
// (https://github.com/microsoft/vscode/issues/211769)
if (!activeEditorPane?.group.isTransient(activeEditorPane.input)) {
this.handleActiveEditorChange(activeEditorGroup, activeEditorPane);
} else {
this.logService.trace(`[History]: ignoring transient editor change until becoming non-transient (editor: ${activeEditorPane.input?.resource?.toString()}})`);
const transientListener = activeEditorGroup.onDidModelChange(e => {
if (e.kind === GroupModelChangeKind.EDITOR_TRANSIENT && e.editor === activeEditorPane.input && !activeEditorPane.group.isTransient(activeEditorPane.input)) {
transientListener.dispose();
this.handleActiveEditorChange(activeEditorGroup, activeEditorPane);
}
});
this.activeEditorListeners.add(transientListener);
}
// Listen to selection changes unless the editor is transient
if (isEditorPaneWithSelection(activeEditorPane)) {
this.activeEditorListeners.add(activeEditorPane.onDidChangeSelection(e => {
if (!activeEditorPane.group.isTransient(activeEditorPane.input)) {
this.handleActiveEditorSelectionChangeEvent(activeEditorGroup, activeEditorPane, e);
} else {
this.logService.trace(`[History]: ignoring transient editor selection change (editor: ${activeEditorPane.input?.resource?.toString()}})`);
}
}));
}
// Context keys
this.updateContextKeys();
}
private onDidFilesChange(event: FileChangesEvent | FileOperationEvent): void {
// External file changes (watcher)
if (event instanceof FileChangesEvent) {
if (event.gotDeleted()) {
this.remove(event);
}
}
// Internal file changes (e.g. explorer)
else {
// Delete
if (event.isOperation(FileOperation.DELETE)) {
this.remove(event);
}
// Move
else if (event.isOperation(FileOperation.MOVE) && event.target.isFile) {
this.move(event);
}
}
}
private handleActiveEditorChange(group: IEditorGroup, editorPane?: IEditorPane): void {
this.handleActiveEditorChangeInHistory(editorPane);
this.handleActiveEditorChangeInNavigationStacks(group, editorPane);
}
private handleActiveEditorSelectionChangeEvent(group: IEditorGroup, editorPane: IEditorPaneWithSelection, event: IEditorPaneSelectionChangeEvent): void {
this.handleActiveEditorSelectionChangeInNavigationStacks(group, editorPane, event);
}
private move(event: FileOperationEvent): void {
this.moveInHistory(event);
this.moveInEditorNavigationStacks(event);
}
private remove(editor: EditorInput): void;
private remove(event: FileChangesEvent): void;
private remove(event: FileOperationEvent): void;
private remove(arg1: EditorInput | FileChangesEvent | FileOperationEvent): void {
this.removeFromHistory(arg1);
this.removeFromEditorNavigationStacks(arg1);
this.removeFromRecentlyClosedEditors(arg1);
this.removeFromRecentlyOpened(arg1);
}
private removeFromRecentlyOpened(arg1: EditorInput | FileChangesEvent | FileOperationEvent): void {
let resource: URI | undefined = undefined;
if (isEditorInput(arg1)) {
resource = EditorResourceAccessor.getOriginalUri(arg1);
} else if (arg1 instanceof FileChangesEvent) {
// Ignore for now (recently opened are most often out of workspace files anyway for which there are no file events)
} else {
resource = arg1.resource;
}
if (resource) {
this.workspacesService.removeRecentlyOpened([resource]);
}
}
clear(): void {
// History
this.clearRecentlyOpened();
// Navigation (next, previous)
this.clearEditorNavigationStacks();
// Recently closed editors
this.recentlyClosedEditors = [];
// Context Keys
this.updateContextKeys();
}
//#region History Context Keys
private readonly canNavigateBackContextKey = (new RawContextKey<boolean>('canNavigateBack', false, localize('canNavigateBack', "Whether it is possible to navigate back in editor history"))).bindTo(this.contextKeyService);
private readonly canNavigateForwardContextKey = (new RawContextKey<boolean>('canNavigateForward', false, localize('canNavigateForward', "Whether it is possible to navigate forward in editor history"))).bindTo(this.contextKeyService);
private readonly canNavigateBackInNavigationsContextKey = (new RawContextKey<boolean>('canNavigateBackInNavigationLocations', false, localize('canNavigateBackInNavigationLocations', "Whether it is possible to navigate back in editor navigation locations history"))).bindTo(this.contextKeyService);
private readonly canNavigateForwardInNavigationsContextKey = (new RawContextKey<boolean>('canNavigateForwardInNavigationLocations', false, localize('canNavigateForwardInNavigationLocations', "Whether it is possible to navigate forward in editor navigation locations history"))).bindTo(this.contextKeyService);
private readonly canNavigateToLastNavigationLocationContextKey = (new RawContextKey<boolean>('canNavigateToLastNavigationLocation', false, localize('canNavigateToLastNavigationLocation', "Whether it is possible to navigate to the last editor navigation location"))).bindTo(this.contextKeyService);
private readonly canNavigateBackInEditsContextKey = (new RawContextKey<boolean>('canNavigateBackInEditLocations', false, localize('canNavigateBackInEditLocations', "Whether it is possible to navigate back in editor edit locations history"))).bindTo(this.contextKeyService);
private readonly canNavigateForwardInEditsContextKey = (new RawContextKey<boolean>('canNavigateForwardInEditLocations', false, localize('canNavigateForwardInEditLocations', "Whether it is possible to navigate forward in editor edit locations history"))).bindTo(this.contextKeyService);
private readonly canNavigateToLastEditLocationContextKey = (new RawContextKey<boolean>('canNavigateToLastEditLocation', false, localize('canNavigateToLastEditLocation', "Whether it is possible to navigate to the last editor edit location"))).bindTo(this.contextKeyService);
private readonly canReopenClosedEditorContextKey = (new RawContextKey<boolean>('canReopenClosedEditor', false, localize('canReopenClosedEditor', "Whether it is possible to reopen the last closed editor"))).bindTo(this.contextKeyService);
updateContextKeys(): void {
this.contextKeyService.bufferChangeEvents(() => {
const activeStack = this.getStack();
this.canNavigateBackContextKey.set(activeStack.canGoBack(GoFilter.NONE));
this.canNavigateForwardContextKey.set(activeStack.canGoForward(GoFilter.NONE));
this.canNavigateBackInNavigationsContextKey.set(activeStack.canGoBack(GoFilter.NAVIGATION));
this.canNavigateForwardInNavigationsContextKey.set(activeStack.canGoForward(GoFilter.NAVIGATION));
this.canNavigateToLastNavigationLocationContextKey.set(activeStack.canGoLast(GoFilter.NAVIGATION));
this.canNavigateBackInEditsContextKey.set(activeStack.canGoBack(GoFilter.EDITS));
this.canNavigateForwardInEditsContextKey.set(activeStack.canGoForward(GoFilter.EDITS));
this.canNavigateToLastEditLocationContextKey.set(activeStack.canGoLast(GoFilter.EDITS));
this.canReopenClosedEditorContextKey.set(this.recentlyClosedEditors.length > 0);
});
}
//#endregion
//#region Editor History Navigation (limit: 50)
private readonly _onDidChangeEditorNavigationStack = this._register(new Emitter<void>());
readonly onDidChangeEditorNavigationStack = this._onDidChangeEditorNavigationStack.event;
private defaultScopedEditorNavigationStack: IEditorNavigationStacks | undefined = undefined;
private readonly editorGroupScopedNavigationStacks = new Map<GroupIdentifier, { stack: IEditorNavigationStacks; disposable: IDisposable }>();
private readonly editorScopedNavigationStacks = new Map<GroupIdentifier, Map<EditorInput, { stack: IEditorNavigationStacks; disposable: IDisposable }>>();
private editorNavigationScope = GoScope.DEFAULT;
private registerEditorNavigationScopeChangeListener(): void {
const handleEditorNavigationScopeChange = () => {
// Ensure to start fresh when setting changes
this.disposeEditorNavigationStacks();
// Update scope
const configuredScope = this.configurationService.getValue(HistoryService.NAVIGATION_SCOPE_SETTING);
if (configuredScope === 'editorGroup') {
this.editorNavigationScope = GoScope.EDITOR_GROUP;
} else if (configuredScope === 'editor') {
this.editorNavigationScope = GoScope.EDITOR;
} else {
this.editorNavigationScope = GoScope.DEFAULT;
}
};
this._register(this.configurationService.onDidChangeConfiguration(event => {
if (event.affectsConfiguration(HistoryService.NAVIGATION_SCOPE_SETTING)) {
handleEditorNavigationScopeChange();
}
}));
handleEditorNavigationScopeChange();
}
private getStack(group = this.editorGroupService.activeGroup, editor = group.activeEditor): IEditorNavigationStacks {
switch (this.editorNavigationScope) {
// Per Editor
case GoScope.EDITOR: {
if (!editor) {
return new NoOpEditorNavigationStacks();
}
let stacksForGroup = this.editorScopedNavigationStacks.get(group.id);
if (!stacksForGroup) {
stacksForGroup = new Map<EditorInput, { stack: IEditorNavigationStacks; disposable: IDisposable }>();
this.editorScopedNavigationStacks.set(group.id, stacksForGroup);
}
let stack = stacksForGroup.get(editor)?.stack;
if (!stack) {
const disposable = new DisposableStore();
stack = disposable.add(this.instantiationService.createInstance(EditorNavigationStacks, GoScope.EDITOR));
disposable.add(stack.onDidChange(() => this._onDidChangeEditorNavigationStack.fire()));
stacksForGroup.set(editor, { stack, disposable });
}
return stack;
}
// Per Editor Group
case GoScope.EDITOR_GROUP: {
let stack = this.editorGroupScopedNavigationStacks.get(group.id)?.stack;
if (!stack) {
const disposable = new DisposableStore();
stack = disposable.add(this.instantiationService.createInstance(EditorNavigationStacks, GoScope.EDITOR_GROUP));
disposable.add(stack.onDidChange(() => this._onDidChangeEditorNavigationStack.fire()));
this.editorGroupScopedNavigationStacks.set(group.id, { stack, disposable });
}
return stack;
}
// Global
case GoScope.DEFAULT: {
if (!this.defaultScopedEditorNavigationStack) {
this.defaultScopedEditorNavigationStack = this._register(this.instantiationService.createInstance(EditorNavigationStacks, GoScope.DEFAULT));
this._register(this.defaultScopedEditorNavigationStack.onDidChange(() => this._onDidChangeEditorNavigationStack.fire()));
}
return this.defaultScopedEditorNavigationStack;
}
}
}
goForward(filter?: GoFilter): Promise<void> {
return this.getStack().goForward(filter);
}
goBack(filter?: GoFilter): Promise<void> {
return this.getStack().goBack(filter);
}
goPrevious(filter?: GoFilter): Promise<void> {
return this.getStack().goPrevious(filter);
}
goLast(filter?: GoFilter): Promise<void> {
return this.getStack().goLast(filter);
}
private handleActiveEditorChangeInNavigationStacks(group: IEditorGroup, editorPane?: IEditorPane): void {
this.getStack(group, editorPane?.input).handleActiveEditorChange(editorPane);
}
private handleActiveEditorSelectionChangeInNavigationStacks(group: IEditorGroup, editorPane: IEditorPaneWithSelection, event: IEditorPaneSelectionChangeEvent): void {
this.getStack(group, editorPane.input).handleActiveEditorSelectionChange(editorPane, event);
}
private handleEditorCloseEventInHistory(e: IEditorCloseEvent): void {
const editors = this.editorScopedNavigationStacks.get(e.groupId);
if (editors) {
const editorStack = editors.get(e.editor);
if (editorStack) {
editorStack.disposable.dispose();
editors.delete(e.editor);
}
if (editors.size === 0) {
this.editorScopedNavigationStacks.delete(e.groupId);
}
}
}
private handleEditorGroupRemoveInNavigationStacks(group: IEditorGroup): void {
// Global
this.defaultScopedEditorNavigationStack?.remove(group.id);
// Editor groups
const editorGroupStack = this.editorGroupScopedNavigationStacks.get(group.id);
if (editorGroupStack) {
editorGroupStack.disposable.dispose();
this.editorGroupScopedNavigationStacks.delete(group.id);
}
}
private clearEditorNavigationStacks(): void {
this.withEachEditorNavigationStack(stack => stack.clear());
}
private removeFromEditorNavigationStacks(arg1: EditorInput | FileChangesEvent | FileOperationEvent): void {
this.withEachEditorNavigationStack(stack => stack.remove(arg1));
}
private moveInEditorNavigationStacks(event: FileOperationEvent): void {
this.withEachEditorNavigationStack(stack => stack.move(event));
}
private withEachEditorNavigationStack(fn: (stack: IEditorNavigationStacks) => void): void {
// Global
if (this.defaultScopedEditorNavigationStack) {
fn(this.defaultScopedEditorNavigationStack);
}
// Per editor group
for (const [, entry] of this.editorGroupScopedNavigationStacks) {
fn(entry.stack);
}
// Per editor
for (const [, entries] of this.editorScopedNavigationStacks) {
for (const [, entry] of entries) {
fn(entry.stack);
}
}
}
private disposeEditorNavigationStacks(): void {
// Global
this.defaultScopedEditorNavigationStack?.dispose();
this.defaultScopedEditorNavigationStack = undefined;
// Per Editor group
for (const [, stack] of this.editorGroupScopedNavigationStacks) {
stack.disposable.dispose();
}
this.editorGroupScopedNavigationStacks.clear();
// Per Editor
for (const [, stacks] of this.editorScopedNavigationStacks) {
for (const [, stack] of stacks) {
stack.disposable.dispose();
}
}
this.editorScopedNavigationStacks.clear();
}
//#endregion
//#region Navigation: Next/Previous Used Editor
private recentlyUsedEditorsStack: readonly IEditorIdentifier[] | undefined = undefined;
private recentlyUsedEditorsStackIndex = 0;
private recentlyUsedEditorsInGroupStack: readonly IEditorIdentifier[] | undefined = undefined;
private recentlyUsedEditorsInGroupStackIndex = 0;
private navigatingInRecentlyUsedEditorsStack = false;
private navigatingInRecentlyUsedEditorsInGroupStack = false;
openNextRecentlyUsedEditor(groupId?: GroupIdentifier): Promise<void> {
const [stack, index] = this.ensureRecentlyUsedStack(index => index - 1, groupId);
return this.doNavigateInRecentlyUsedEditorsStack(stack[index], groupId);
}
openPreviouslyUsedEditor(groupId?: GroupIdentifier): Promise<void> {
const [stack, index] = this.ensureRecentlyUsedStack(index => index + 1, groupId);
return this.doNavigateInRecentlyUsedEditorsStack(stack[index], groupId);
}
private async doNavigateInRecentlyUsedEditorsStack(editorIdentifier: IEditorIdentifier | undefined, groupId?: GroupIdentifier): Promise<void> {
if (editorIdentifier) {
const acrossGroups = typeof groupId !== 'number' || !this.editorGroupService.getGroup(groupId);
if (acrossGroups) {
this.navigatingInRecentlyUsedEditorsStack = true;
} else {
this.navigatingInRecentlyUsedEditorsInGroupStack = true;
}
const group = this.editorGroupService.getGroup(editorIdentifier.groupId) ?? this.editorGroupService.activeGroup;
try {
await group.openEditor(editorIdentifier.editor);
} finally {
if (acrossGroups) {
this.navigatingInRecentlyUsedEditorsStack = false;
} else {
this.navigatingInRecentlyUsedEditorsInGroupStack = false;
}
}
}
}
private ensureRecentlyUsedStack(indexModifier: (index: number) => number, groupId?: GroupIdentifier): [readonly IEditorIdentifier[], number] {
let editors: readonly IEditorIdentifier[];
let index: number;
const group = typeof groupId === 'number' ? this.editorGroupService.getGroup(groupId) : undefined;
// Across groups
if (!group) {
editors = this.recentlyUsedEditorsStack || this.editorService.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE);
index = this.recentlyUsedEditorsStackIndex;
}
// Within group
else {
editors = this.recentlyUsedEditorsInGroupStack || group.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE).map(editor => ({ groupId: group.id, editor }));
index = this.recentlyUsedEditorsInGroupStackIndex;
}
// Adjust index
let newIndex = indexModifier(index);
if (newIndex < 0) {
newIndex = 0;
} else if (newIndex > editors.length - 1) {
newIndex = editors.length - 1;
}
// Remember index and editors
if (!group) {
this.recentlyUsedEditorsStack = editors;
this.recentlyUsedEditorsStackIndex = newIndex;
} else {
this.recentlyUsedEditorsInGroupStack = editors;
this.recentlyUsedEditorsInGroupStackIndex = newIndex;
}
return [editors, newIndex];
}
private handleEditorEventInRecentEditorsStack(): void {
// Drop all-editors stack unless navigating in all editors
if (!this.navigatingInRecentlyUsedEditorsStack) {
this.recentlyUsedEditorsStack = undefined;
this.recentlyUsedEditorsStackIndex = 0;
}
// Drop in-group-editors stack unless navigating in group
if (!this.navigatingInRecentlyUsedEditorsInGroupStack) {
this.recentlyUsedEditorsInGroupStack = undefined;
this.recentlyUsedEditorsInGroupStackIndex = 0;
}
}
//#endregion
//#region File: Reopen Closed Editor (limit: 20)
private static readonly MAX_RECENTLY_CLOSED_EDITORS = 20;
private recentlyClosedEditors: IRecentlyClosedEditor[] = [];
private ignoreEditorCloseEvent = false;
private handleEditorCloseEventInReopen(event: IEditorCloseEvent): void {
if (this.ignoreEditorCloseEvent) {
return; // blocked
}
const { editor, context } = event;
if (context === EditorCloseContext.REPLACE || context === EditorCloseContext.MOVE) {
return; // ignore if editor was replaced or moved
}
const untypedEditor = editor.toUntyped();
if (!untypedEditor) {
return; // we need a untyped editor to restore from going forward
}
const associatedResources: URI[] = [];
const editorResource = EditorResourceAccessor.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.BOTH });
if (URI.isUri(editorResource)) {
associatedResources.push(editorResource);
} else if (editorResource) {
associatedResources.push(...coalesce([editorResource.primary, editorResource.secondary]));
}
// Remove from list of recently closed before...
this.removeFromRecentlyClosedEditors(editor);
// ...adding it as last recently closed
this.recentlyClosedEditors.push({
editorId: editor.editorId,
editor: untypedEditor,
resource: EditorResourceAccessor.getOriginalUri(editor),
associatedResources,
index: event.index,
sticky: event.sticky
});
// Bounding
if (this.recentlyClosedEditors.length > HistoryService.MAX_RECENTLY_CLOSED_EDITORS) {
this.recentlyClosedEditors.shift();
}
// Context
this.canReopenClosedEditorContextKey.set(true);
}
async reopenLastClosedEditor(): Promise<void> {
// Open editor if we have one
const lastClosedEditor = this.recentlyClosedEditors.pop();
let reopenClosedEditorPromise: Promise<void> | undefined = undefined;
if (lastClosedEditor) {
reopenClosedEditorPromise = this.doReopenLastClosedEditor(lastClosedEditor);
}
// Update context
this.canReopenClosedEditorContextKey.set(this.recentlyClosedEditors.length > 0);
return reopenClosedEditorPromise;
}
private async doReopenLastClosedEditor(lastClosedEditor: IRecentlyClosedEditor): Promise<void> {
const options: IEditorOptions = { pinned: true, sticky: lastClosedEditor.sticky, index: lastClosedEditor.index, ignoreError: true };
// Special sticky handling: remove the index property from options
// if that would result in sticky state to not preserve or apply
// wrongly.
if (
(lastClosedEditor.sticky && !this.editorGroupService.activeGroup.isSticky(lastClosedEditor.index)) ||
(!lastClosedEditor.sticky && this.editorGroupService.activeGroup.isSticky(lastClosedEditor.index))
) {
options.index = undefined;
}
// Re-open editor unless already opened
let editorPane: IEditorPane | undefined = undefined;
if (!this.editorGroupService.activeGroup.contains(lastClosedEditor.editor)) {
// Fix for https://github.com/microsoft/vscode/issues/107850
// If opening an editor fails, it is possible that we get
// another editor-close event as a result. But we really do
// want to ignore that in our list of recently closed editors
// to prevent endless loops.
this.ignoreEditorCloseEvent = true;
try {
editorPane = await this.editorService.openEditor({
...lastClosedEditor.editor,
options: {
...lastClosedEditor.editor.options,
...options
}
});
} finally {
this.ignoreEditorCloseEvent = false;
}
}
// If no editor was opened, try with the next one
if (!editorPane) {
// Fix for https://github.com/microsoft/vscode/issues/67882
// If opening of the editor fails, make sure to try the next one
// but make sure to remove this one from the list to prevent
// endless loops.
remove(this.recentlyClosedEditors, lastClosedEditor);
// Try with next one
this.reopenLastClosedEditor();
}
}
private removeFromRecentlyClosedEditors(arg1: EditorInput | FileChangesEvent | FileOperationEvent): void {
this.recentlyClosedEditors = this.recentlyClosedEditors.filter(recentlyClosedEditor => {
if (isEditorInput(arg1) && recentlyClosedEditor.editorId !== arg1.editorId) {
return true; // keep: different editor identifiers
}
if (recentlyClosedEditor.resource && this.editorHelper.matchesFile(recentlyClosedEditor.resource, arg1)) {
return false; // remove: editor matches directly
}
if (recentlyClosedEditor.associatedResources.some(associatedResource => this.editorHelper.matchesFile(associatedResource, arg1))) {
return false; // remove: an associated resource matches
}
return true; // keep
});
// Update context
this.canReopenClosedEditorContextKey.set(this.recentlyClosedEditors.length > 0);
}
//#endregion
//#region Go to: Recently Opened Editor (limit: 200, persisted)
private static readonly MAX_HISTORY_ITEMS = 200;
private static readonly HISTORY_STORAGE_KEY = 'history.entries';
private history: Array<EditorInput | IResourceEditorInput> | undefined = undefined;
private readonly editorHistoryListeners = new Map<EditorInput, DisposableStore>();
private readonly resourceExcludeMatcher = this._register(new WindowIdleValue(mainWindow, () => {
const matcher = this._register(this.instantiationService.createInstance(
ResourceGlobMatcher,
root => getExcludes(root ? this.configurationService.getValue<ISearchConfiguration>({ resource: root }) : this.configurationService.getValue<ISearchConfiguration>()) || Object.create(null),
event => event.affectsConfiguration(FILES_EXCLUDE_CONFIG) || event.affectsConfiguration(SEARCH_EXCLUDE_CONFIG)
));
this._register(matcher.onExpressionChange(() => this.removeExcludedFromHistory()));
return matcher;
}));
private handleActiveEditorChangeInHistory(editorPane?: IEditorPane): void {
// Ensure we have not configured to exclude input and don't track invalid inputs
const editor = editorPane?.input;
if (!editor || editor.isDisposed() || !this.includeInHistory(editor)) {
return;
}
// Remove any existing entry and add to the beginning
this.removeFromHistory(editor);
this.addToHistory(editor);
}
private addToHistory(editor: EditorInput | IResourceEditorInput, insertFirst = true): void {
this.ensureHistoryLoaded(this.history);
const historyInput = this.editorHelper.preferResourceEditorInput(editor);
if (!historyInput) {
return;
}
// Insert based on preference
if (insertFirst) {
this.history.unshift(historyInput);
} else {
this.history.push(historyInput);
}
// Respect max entries setting
if (this.history.length > HistoryService.MAX_HISTORY_ITEMS) {
this.editorHelper.clearOnEditorDispose(this.history.pop()!, this.editorHistoryListeners);
}
// React to editor input disposing
if (isEditorInput(editor)) {
this.editorHelper.onEditorDispose(editor, () => this.updateHistoryOnEditorDispose(historyInput), this.editorHistoryListeners);
}
}
private updateHistoryOnEditorDispose(editor: EditorInput | IResourceEditorInput): void {
if (isEditorInput(editor)) {
// Any non side-by-side editor input gets removed directly on dispose
if (!isSideBySideEditorInput(editor)) {
this.removeFromHistory(editor);
}
// Side-by-side editors get special treatment: we try to distill the
// possibly untyped resource inputs from both sides to be able to
// offer these entries from the history to the user still unless
// they are excluded.
else {
const resourceInputs: IResourceEditorInput[] = [];
const sideInputs = editor.primary.matches(editor.secondary) ? [editor.primary] : [editor.primary, editor.secondary];
for (const sideInput of sideInputs) {
const candidateResourceInput = this.editorHelper.preferResourceEditorInput(sideInput);
if (isResourceEditorInput(candidateResourceInput) && this.includeInHistory(candidateResourceInput)) {
resourceInputs.push(candidateResourceInput);
}
}
// Insert the untyped resource inputs where our disposed
// side-by-side editor input is in the history stack
this.replaceInHistory(editor, ...resourceInputs);
}
} else {
// Remove any editor that should not be included in history
if (!this.includeInHistory(editor)) {
this.removeFromHistory(editor);
}
}
}
private includeInHistory(editor: EditorInput | IResourceEditorInput): boolean {
if (isEditorInput(editor)) {
return true; // include any non files
}
return !this.resourceExcludeMatcher.value.matches(editor.resource);
}
private removeExcludedFromHistory(): void {
this.ensureHistoryLoaded(this.history);
this.history = this.history.filter(entry => {
const include = this.includeInHistory(entry);
// Cleanup any listeners associated with the input when removing from history
if (!include) {
this.editorHelper.clearOnEditorDispose(entry, this.editorHistoryListeners);
}
return include;
});
}
private moveInHistory(event: FileOperationEvent): void {
if (event.isOperation(FileOperation.MOVE)) {
const removed = this.removeFromHistory(event);
if (removed) {
this.addToHistory({ resource: event.target.resource });
}
}
}
removeFromHistory(arg1: EditorInput | IResourceEditorInput | FileChangesEvent | FileOperationEvent): boolean {
let removed = false;
this.ensureHistoryLoaded(this.history);
this.history = this.history.filter(entry => {
const matches = this.editorHelper.matchesEditor(arg1, entry);
// Cleanup any listeners associated with the input when removing from history
if (matches) {
this.editorHelper.clearOnEditorDispose(arg1, this.editorHistoryListeners);
removed = true;
}
return !matches;
});
return removed;
}
private replaceInHistory(editor: EditorInput | IResourceEditorInput, ...replacements: ReadonlyArray<EditorInput | IResourceEditorInput>): void {
this.ensureHistoryLoaded(this.history);
let replaced = false;
const newHistory: Array<EditorInput | IResourceEditorInput> = [];
for (const entry of this.history) {
// Entry matches and is going to be disposed + replaced
if (this.editorHelper.matchesEditor(editor, entry)) {
// Cleanup any listeners associated with the input when replacing from history
this.editorHelper.clearOnEditorDispose(editor, this.editorHistoryListeners);
// Insert replacements but only once
if (!replaced) {
newHistory.push(...replacements);
replaced = true;
}
}
// Entry does not match, but only add it if it didn't match
// our replacements already
else if (!replacements.some(replacement => this.editorHelper.matchesEditor(replacement, entry))) {
newHistory.push(entry);
}
}
// If the target editor to replace was not found, make sure to
// insert the replacements to the end to ensure we got them
if (!replaced) {
newHistory.push(...replacements);
}
this.history = newHistory;
}
clearRecentlyOpened(): void {
this.history = [];
for (const [, disposable] of this.editorHistoryListeners) {
dispose(disposable);
}
this.editorHistoryListeners.clear();
}
getHistory(): readonly (EditorInput | IResourceEditorInput)[] {
this.ensureHistoryLoaded(this.history);
return this.history;
}
private ensureHistoryLoaded(history: Array<EditorInput | IResourceEditorInput> | undefined): asserts history {
if (!this.history) {
// Until history is loaded, it is just empty
this.history = [];
// We want to seed history from opened editors
// too as well as previous stored state, so we
// need to wait for the editor groups being ready
if (this.editorGroupService.isReady) {
this.loadHistory();
} else {
(async () => {
await this.editorGroupService.whenReady;
this.loadHistory();
})();
}
}
}