-
Notifications
You must be signed in to change notification settings - Fork 30.9k
/
Copy patheditorPart.ts
1517 lines (1193 loc) · 51.7 KB
/
editorPart.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 { IThemeService } from '../../../../platform/theme/common/themeService.js';
import { Part } from '../../part.js';
import { Dimension, $, EventHelper, addDisposableGenericMouseDownListener, getWindow, isAncestorOfActiveElement, getActiveElement, isHTMLElement } from '../../../../base/browser/dom.js';
import { Event, Emitter, Relay, PauseableEmitter } from '../../../../base/common/event.js';
import { contrastBorder, editorBackground } from '../../../../platform/theme/common/colorRegistry.js';
import { GroupDirection, GroupsArrangement, GroupOrientation, IMergeGroupOptions, MergeGroupMode, GroupsOrder, GroupLocation, IFindGroupScope, EditorGroupLayout, GroupLayoutArgument, IEditorSideGroup, IEditorDropTargetDelegate, IEditorPart } from '../../../services/editor/common/editorGroupsService.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { IView, orthogonal, LayoutPriority, IViewSize, Direction, SerializableGrid, Sizing, ISerializedGrid, ISerializedNode, Orientation, GridBranchNode, isGridBranchNode, GridNode, createSerializedGrid, Grid } from '../../../../base/browser/ui/grid/grid.js';
import { GroupIdentifier, EditorInputWithOptions, IEditorPartOptions, IEditorPartOptionsChangeEvent, GroupModelChangeKind } from '../../../common/editor.js';
import { EDITOR_GROUP_BORDER, EDITOR_PANE_BACKGROUND } from '../../../common/theme.js';
import { distinct, coalesce } from '../../../../base/common/arrays.js';
import { IEditorGroupView, getEditorPartOptions, impactsEditorPartOptions, IEditorPartCreationOptions, IEditorPartsView, IEditorGroupsView, IEditorGroupViewOptions } from './editor.js';
import { EditorGroupView } from './editorGroupView.js';
import { IConfigurationService, IConfigurationChangeEvent } from '../../../../platform/configuration/common/configuration.js';
import { IDisposable, dispose, toDisposable, DisposableStore } from '../../../../base/common/lifecycle.js';
import { IStorageService, IStorageValueChangeEvent, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { ISerializedEditorGroupModel, isSerializedEditorGroupModel } from '../../../common/editor/editorGroupModel.js';
import { EditorDropTarget } from './editorDropTarget.js';
import { Color } from '../../../../base/common/color.js';
import { CenteredViewLayout } from '../../../../base/browser/ui/centered/centeredViewLayout.js';
import { onUnexpectedError } from '../../../../base/common/errors.js';
import { Parts, IWorkbenchLayoutService, Position } from '../../../services/layout/browser/layoutService.js';
import { DeepPartial, assertIsDefined, assertType } from '../../../../base/common/types.js';
import { CompositeDragAndDropObserver } from '../../dnd.js';
import { DeferredPromise, Promises } from '../../../../base/common/async.js';
import { findGroup } from '../../../services/editor/common/editorGroupFinder.js';
import { SIDE_GROUP } from '../../../services/editor/common/editorService.js';
import { IBoundarySashes } from '../../../../base/browser/ui/sash/sash.js';
import { IHostService } from '../../../services/host/browser/host.js';
import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js';
import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js';
import { EditorPartMaximizedEditorGroupContext, EditorPartMultipleEditorGroupsContext, IsAuxiliaryEditorPartContext } from '../../../common/contextkeys.js';
import { mainWindow } from '../../../../base/browser/window.js';
export interface IEditorPartUIState {
readonly serializedGrid: ISerializedGrid;
readonly activeGroup: GroupIdentifier;
readonly mostRecentActiveGroups: GroupIdentifier[];
}
class GridWidgetView<T extends IView> implements IView {
readonly element: HTMLElement = $('.grid-view-container');
get minimumWidth(): number { return this.gridWidget ? this.gridWidget.minimumWidth : 0; }
get maximumWidth(): number { return this.gridWidget ? this.gridWidget.maximumWidth : Number.POSITIVE_INFINITY; }
get minimumHeight(): number { return this.gridWidget ? this.gridWidget.minimumHeight : 0; }
get maximumHeight(): number { return this.gridWidget ? this.gridWidget.maximumHeight : Number.POSITIVE_INFINITY; }
private _onDidChange = new Relay<{ width: number; height: number } | undefined>();
readonly onDidChange = this._onDidChange.event;
private _gridWidget: Grid<T> | undefined;
get gridWidget(): Grid<T> | undefined {
return this._gridWidget;
}
set gridWidget(grid: Grid<T> | undefined) {
this.element.innerText = '';
if (grid) {
this.element.appendChild(grid.element);
this._onDidChange.input = grid.onDidChange;
} else {
this._onDidChange.input = Event.None;
}
this._gridWidget = grid;
}
layout(width: number, height: number, top: number, left: number): void {
this.gridWidget?.layout(width, height, top, left);
}
dispose(): void {
this._onDidChange.dispose();
}
}
export class EditorPart extends Part implements IEditorPart, IEditorGroupsView {
private static readonly EDITOR_PART_UI_STATE_STORAGE_KEY = 'editorpart.state';
private static readonly EDITOR_PART_CENTERED_VIEW_STORAGE_KEY = 'editorpart.centeredview';
//#region Events
private readonly _onDidFocus = this._register(new Emitter<void>());
readonly onDidFocus = this._onDidFocus.event;
private readonly _onDidLayout = this._register(new Emitter<Dimension>());
readonly onDidLayout = this._onDidLayout.event;
private readonly _onDidChangeActiveGroup = this._register(new Emitter<IEditorGroupView>());
readonly onDidChangeActiveGroup = this._onDidChangeActiveGroup.event;
private readonly _onDidChangeGroupIndex = this._register(new Emitter<IEditorGroupView>());
readonly onDidChangeGroupIndex = this._onDidChangeGroupIndex.event;
private readonly _onDidChangeGroupLabel = this._register(new Emitter<IEditorGroupView>());
readonly onDidChangeGroupLabel = this._onDidChangeGroupLabel.event;
private readonly _onDidChangeGroupLocked = this._register(new Emitter<IEditorGroupView>());
readonly onDidChangeGroupLocked = this._onDidChangeGroupLocked.event;
private readonly _onDidChangeGroupMaximized = this._register(new Emitter<boolean>());
readonly onDidChangeGroupMaximized = this._onDidChangeGroupMaximized.event;
private readonly _onDidActivateGroup = this._register(new Emitter<IEditorGroupView>());
readonly onDidActivateGroup = this._onDidActivateGroup.event;
private readonly _onDidAddGroup = this._register(new PauseableEmitter<IEditorGroupView>());
readonly onDidAddGroup = this._onDidAddGroup.event;
private readonly _onDidRemoveGroup = this._register(new PauseableEmitter<IEditorGroupView>());
readonly onDidRemoveGroup = this._onDidRemoveGroup.event;
private readonly _onDidMoveGroup = this._register(new Emitter<IEditorGroupView>());
readonly onDidMoveGroup = this._onDidMoveGroup.event;
private readonly onDidSetGridWidget = this._register(new Emitter<{ width: number; height: number } | undefined>());
private readonly _onDidChangeSizeConstraints = this._register(new Relay<{ width: number; height: number } | undefined>());
readonly onDidChangeSizeConstraints = Event.any(this.onDidSetGridWidget.event, this._onDidChangeSizeConstraints.event);
private readonly _onDidScroll = this._register(new Relay<void>());
readonly onDidScroll = Event.any(this.onDidSetGridWidget.event, this._onDidScroll.event);
private readonly _onDidChangeEditorPartOptions = this._register(new Emitter<IEditorPartOptionsChangeEvent>());
readonly onDidChangeEditorPartOptions = this._onDidChangeEditorPartOptions.event;
private readonly _onWillDispose = this._register(new Emitter<void>());
readonly onWillDispose = this._onWillDispose.event;
//#endregion
private readonly workspaceMemento = this.getMemento(StorageScope.WORKSPACE, StorageTarget.USER);
private readonly profileMemento = this.getMemento(StorageScope.PROFILE, StorageTarget.MACHINE);
private readonly groupViews = new Map<GroupIdentifier, IEditorGroupView>();
private mostRecentActiveGroups: GroupIdentifier[] = [];
protected container: HTMLElement | undefined;
private scopedInstantiationService!: IInstantiationService;
private centeredLayoutWidget!: CenteredViewLayout;
private gridWidget!: SerializableGrid<IEditorGroupView>;
private readonly gridWidgetDisposables = this._register(new DisposableStore());
private readonly gridWidgetView = this._register(new GridWidgetView<IEditorGroupView>());
constructor(
protected readonly editorPartsView: IEditorPartsView,
id: string,
private readonly groupsLabel: string,
readonly windowId: number,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IStorageService storageService: IStorageService,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IHostService private readonly hostService: IHostService,
@IContextKeyService private readonly contextKeyService: IContextKeyService
) {
super(id, { hasTitle: false }, themeService, storageService, layoutService);
this.registerListeners();
}
private registerListeners(): void {
this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e)));
this._register(this.themeService.onDidFileIconThemeChange(() => this.handleChangedPartOptions()));
this._register(this.onDidChangeMementoValue(StorageScope.WORKSPACE, this._store)(e => this.onDidChangeMementoState(e)));
}
private onConfigurationUpdated(event: IConfigurationChangeEvent): void {
if (impactsEditorPartOptions(event)) {
this.handleChangedPartOptions();
}
}
private handleChangedPartOptions(): void {
const oldPartOptions = this._partOptions;
const newPartOptions = getEditorPartOptions(this.configurationService, this.themeService);
for (const enforcedPartOptions of this.enforcedPartOptions) {
Object.assign(newPartOptions, enforcedPartOptions); // check for overrides
}
this._partOptions = newPartOptions;
this._onDidChangeEditorPartOptions.fire({ oldPartOptions, newPartOptions });
}
private enforcedPartOptions: DeepPartial<IEditorPartOptions>[] = [];
private _partOptions = getEditorPartOptions(this.configurationService, this.themeService);
get partOptions(): IEditorPartOptions { return this._partOptions; }
enforcePartOptions(options: DeepPartial<IEditorPartOptions>): IDisposable {
this.enforcedPartOptions.push(options);
this.handleChangedPartOptions();
return toDisposable(() => {
this.enforcedPartOptions.splice(this.enforcedPartOptions.indexOf(options), 1);
this.handleChangedPartOptions();
});
}
private top = 0;
private left = 0;
private _contentDimension!: Dimension;
get contentDimension(): Dimension { return this._contentDimension; }
private _activeGroup!: IEditorGroupView;
get activeGroup(): IEditorGroupView {
return this._activeGroup;
}
readonly sideGroup: IEditorSideGroup = {
openEditor: (editor, options) => {
const [group] = this.scopedInstantiationService.invokeFunction(accessor => findGroup(accessor, { editor, options }, SIDE_GROUP));
return group.openEditor(editor, options);
}
};
get groups(): IEditorGroupView[] {
return Array.from(this.groupViews.values());
}
get count(): number {
return this.groupViews.size;
}
get orientation(): GroupOrientation {
return (this.gridWidget && this.gridWidget.orientation === Orientation.VERTICAL) ? GroupOrientation.VERTICAL : GroupOrientation.HORIZONTAL;
}
private _isReady = false;
get isReady(): boolean { return this._isReady; }
private readonly whenReadyPromise = new DeferredPromise<void>();
readonly whenReady = this.whenReadyPromise.p;
private readonly whenRestoredPromise = new DeferredPromise<void>();
readonly whenRestored = this.whenRestoredPromise.p;
get hasRestorableState(): boolean {
return !!this.workspaceMemento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY];
}
private _willRestoreState = false;
get willRestoreState(): boolean { return this._willRestoreState; }
getGroups(order = GroupsOrder.CREATION_TIME): IEditorGroupView[] {
switch (order) {
case GroupsOrder.CREATION_TIME:
return this.groups;
case GroupsOrder.MOST_RECENTLY_ACTIVE: {
const mostRecentActive = coalesce(this.mostRecentActiveGroups.map(groupId => this.getGroup(groupId)));
// there can be groups that got never active, even though they exist. in this case
// make sure to just append them at the end so that all groups are returned properly
return distinct([...mostRecentActive, ...this.groups]);
}
case GroupsOrder.GRID_APPEARANCE: {
const views: IEditorGroupView[] = [];
if (this.gridWidget) {
this.fillGridNodes(views, this.gridWidget.getViews());
}
return views;
}
}
}
private fillGridNodes(target: IEditorGroupView[], node: GridBranchNode<IEditorGroupView> | GridNode<IEditorGroupView>): void {
if (isGridBranchNode(node)) {
node.children.forEach(child => this.fillGridNodes(target, child));
} else {
target.push(node.view);
}
}
hasGroup(identifier: GroupIdentifier): boolean {
return this.groupViews.has(identifier);
}
getGroup(identifier: GroupIdentifier): IEditorGroupView | undefined {
return this.groupViews.get(identifier);
}
findGroup(scope: IFindGroupScope, source: IEditorGroupView | GroupIdentifier = this.activeGroup, wrap?: boolean): IEditorGroupView | undefined {
// by direction
if (typeof scope.direction === 'number') {
return this.doFindGroupByDirection(scope.direction, source, wrap);
}
// by location
if (typeof scope.location === 'number') {
return this.doFindGroupByLocation(scope.location, source, wrap);
}
throw new Error('invalid arguments');
}
private doFindGroupByDirection(direction: GroupDirection, source: IEditorGroupView | GroupIdentifier, wrap?: boolean): IEditorGroupView | undefined {
const sourceGroupView = this.assertGroupView(source);
// Find neighbours and sort by our MRU list
const neighbours = this.gridWidget.getNeighborViews(sourceGroupView, this.toGridViewDirection(direction), wrap);
neighbours.sort(((n1, n2) => this.mostRecentActiveGroups.indexOf(n1.id) - this.mostRecentActiveGroups.indexOf(n2.id)));
return neighbours[0];
}
private doFindGroupByLocation(location: GroupLocation, source: IEditorGroupView | GroupIdentifier, wrap?: boolean): IEditorGroupView | undefined {
const sourceGroupView = this.assertGroupView(source);
const groups = this.getGroups(GroupsOrder.GRID_APPEARANCE);
const index = groups.indexOf(sourceGroupView);
switch (location) {
case GroupLocation.FIRST:
return groups[0];
case GroupLocation.LAST:
return groups[groups.length - 1];
case GroupLocation.NEXT: {
let nextGroup: IEditorGroupView | undefined = groups[index + 1];
if (!nextGroup && wrap) {
nextGroup = this.doFindGroupByLocation(GroupLocation.FIRST, source);
}
return nextGroup;
}
case GroupLocation.PREVIOUS: {
let previousGroup: IEditorGroupView | undefined = groups[index - 1];
if (!previousGroup && wrap) {
previousGroup = this.doFindGroupByLocation(GroupLocation.LAST, source);
}
return previousGroup;
}
}
}
activateGroup(group: IEditorGroupView | GroupIdentifier, preserveWindowOrder?: boolean): IEditorGroupView {
const groupView = this.assertGroupView(group);
this.doSetGroupActive(groupView);
// Ensure window on top unless disabled
if (!preserveWindowOrder) {
this.hostService.moveTop(getWindow(this.element));
}
return groupView;
}
restoreGroup(group: IEditorGroupView | GroupIdentifier): IEditorGroupView {
const groupView = this.assertGroupView(group);
this.doRestoreGroup(groupView);
return groupView;
}
getSize(group: IEditorGroupView | GroupIdentifier): { width: number; height: number } {
const groupView = this.assertGroupView(group);
return this.gridWidget.getViewSize(groupView);
}
setSize(group: IEditorGroupView | GroupIdentifier, size: { width: number; height: number }): void {
const groupView = this.assertGroupView(group);
this.gridWidget.resizeView(groupView, size);
}
arrangeGroups(arrangement: GroupsArrangement, target: IEditorGroupView | GroupIdentifier = this.activeGroup): void {
if (this.count < 2) {
return; // require at least 2 groups to show
}
if (!this.gridWidget) {
return; // we have not been created yet
}
const groupView = this.assertGroupView(target);
switch (arrangement) {
case GroupsArrangement.EVEN:
this.gridWidget.distributeViewSizes();
break;
case GroupsArrangement.MAXIMIZE:
if (this.groups.length < 2) {
return; // need at least 2 groups to be maximized
}
this.gridWidget.maximizeView(groupView);
groupView.focus();
break;
case GroupsArrangement.EXPAND:
this.gridWidget.expandView(groupView);
break;
}
}
toggleMaximizeGroup(target: IEditorGroupView | GroupIdentifier = this.activeGroup): void {
if (this.hasMaximizedGroup()) {
this.unmaximizeGroup();
} else {
this.arrangeGroups(GroupsArrangement.MAXIMIZE, target);
}
}
toggleExpandGroup(target: IEditorGroupView | GroupIdentifier = this.activeGroup): void {
if (this.isGroupExpanded(this.activeGroup)) {
this.arrangeGroups(GroupsArrangement.EVEN);
} else {
this.arrangeGroups(GroupsArrangement.EXPAND, target);
}
}
private unmaximizeGroup(): void {
this.gridWidget.exitMaximizedView();
this._activeGroup.focus(); // When making views visible the focus can be affected, so restore it
}
hasMaximizedGroup(): boolean {
return this.gridWidget.hasMaximizedView();
}
private isGroupMaximized(targetGroup: IEditorGroupView): boolean {
return this.gridWidget.isViewMaximized(targetGroup);
}
isGroupExpanded(targetGroup: IEditorGroupView): boolean {
return this.gridWidget.isViewExpanded(targetGroup);
}
setGroupOrientation(orientation: GroupOrientation): void {
if (!this.gridWidget) {
return; // we have not been created yet
}
const newOrientation = (orientation === GroupOrientation.HORIZONTAL) ? Orientation.HORIZONTAL : Orientation.VERTICAL;
if (this.gridWidget.orientation !== newOrientation) {
this.gridWidget.orientation = newOrientation;
}
}
applyLayout(layout: EditorGroupLayout): void {
const restoreFocus = this.shouldRestoreFocus(this.container);
// Determine how many groups we need overall
let layoutGroupsCount = 0;
function countGroups(groups: GroupLayoutArgument[]): void {
for (const group of groups) {
if (Array.isArray(group.groups)) {
countGroups(group.groups);
} else {
layoutGroupsCount++;
}
}
}
countGroups(layout.groups);
// If we currently have too many groups, merge them into the last one
let currentGroupViews = this.getGroups(GroupsOrder.GRID_APPEARANCE);
if (layoutGroupsCount < currentGroupViews.length) {
const lastGroupInLayout = currentGroupViews[layoutGroupsCount - 1];
currentGroupViews.forEach((group, index) => {
if (index >= layoutGroupsCount) {
this.mergeGroup(group, lastGroupInLayout);
}
});
currentGroupViews = this.getGroups(GroupsOrder.GRID_APPEARANCE);
}
const activeGroup = this.activeGroup;
// Prepare grid descriptor to create new grid from
const gridDescriptor = createSerializedGrid({
orientation: this.toGridViewOrientation(
layout.orientation,
this.isTwoDimensionalGrid() ?
this.gridWidget.orientation : // preserve original orientation for 2-dimensional grids
orthogonal(this.gridWidget.orientation) // otherwise flip (fix https://github.com/microsoft/vscode/issues/52975)
),
groups: layout.groups
});
// Recreate gridwidget with descriptor
this.doApplyGridState(gridDescriptor, activeGroup.id, currentGroupViews);
// Restore focus as needed
if (restoreFocus) {
this._activeGroup.focus();
}
}
getLayout(): EditorGroupLayout {
// Example return value:
// { orientation: 0, groups: [ { groups: [ { size: 0.4 }, { size: 0.6 } ], size: 0.5 }, { groups: [ {}, {} ], size: 0.5 } ] }
const serializedGrid = this.gridWidget.serialize();
const orientation = serializedGrid.orientation === Orientation.HORIZONTAL ? GroupOrientation.HORIZONTAL : GroupOrientation.VERTICAL;
const root = this.serializedNodeToGroupLayoutArgument(serializedGrid.root);
return {
orientation,
groups: root.groups as GroupLayoutArgument[]
};
}
private serializedNodeToGroupLayoutArgument(serializedNode: ISerializedNode): GroupLayoutArgument {
if (serializedNode.type === 'branch') {
return {
size: serializedNode.size,
groups: serializedNode.data.map(node => this.serializedNodeToGroupLayoutArgument(node))
};
}
return { size: serializedNode.size };
}
protected shouldRestoreFocus(target: Element | undefined): boolean {
if (!target) {
return false;
}
const activeElement = getActiveElement();
if (activeElement === target.ownerDocument.body) {
return true; // always restore focus if nothing is focused currently
}
// otherwise check for the active element being an ancestor of the target
return isAncestorOfActiveElement(target);
}
private isTwoDimensionalGrid(): boolean {
const views = this.gridWidget.getViews();
if (isGridBranchNode(views)) {
// the grid is 2-dimensional if any children
// of the grid is a branch node
return views.children.some(child => isGridBranchNode(child));
}
return false;
}
addGroup(location: IEditorGroupView | GroupIdentifier, direction: GroupDirection, groupToCopy?: IEditorGroupView): IEditorGroupView {
const locationView = this.assertGroupView(location);
let newGroupView: IEditorGroupView;
// Same groups view: add to grid widget directly
if (locationView.groupsView === this) {
const restoreFocus = this.shouldRestoreFocus(locationView.element);
const shouldExpand = this.groupViews.size > 1 && this.isGroupExpanded(locationView);
newGroupView = this.doCreateGroupView(groupToCopy);
// Add to grid widget
this.gridWidget.addView(
newGroupView,
this.getSplitSizingStyle(),
locationView,
this.toGridViewDirection(direction),
);
// Update container
this.updateContainer();
// Event
this._onDidAddGroup.fire(newGroupView);
// Notify group index change given a new group was added
this.notifyGroupIndexChange();
// Expand new group, if the reference view was previously expanded
if (shouldExpand) {
this.arrangeGroups(GroupsArrangement.EXPAND, newGroupView);
}
// Restore focus if we had it previously after completing the grid
// operation. That operation might cause reparenting of grid views
// which moves focus to the <body> element otherwise.
if (restoreFocus) {
locationView.focus();
}
}
// Different group view: add to grid widget of that group
else {
newGroupView = locationView.groupsView.addGroup(locationView, direction, groupToCopy);
}
return newGroupView;
}
private getSplitSizingStyle(): Sizing {
switch (this._partOptions.splitSizing) {
case 'distribute':
return Sizing.Distribute;
case 'split':
return Sizing.Split;
default:
return Sizing.Auto;
}
}
private doCreateGroupView(from?: IEditorGroupView | ISerializedEditorGroupModel | null, options?: IEditorGroupViewOptions): IEditorGroupView {
// Create group view
let groupView: IEditorGroupView;
if (from instanceof EditorGroupView) {
groupView = EditorGroupView.createCopy(from, this.editorPartsView, this, this.groupsLabel, this.count, this.scopedInstantiationService, options);
} else if (isSerializedEditorGroupModel(from)) {
groupView = EditorGroupView.createFromSerialized(from, this.editorPartsView, this, this.groupsLabel, this.count, this.scopedInstantiationService, options);
} else {
groupView = EditorGroupView.createNew(this.editorPartsView, this, this.groupsLabel, this.count, this.scopedInstantiationService, options);
}
// Keep in map
this.groupViews.set(groupView.id, groupView);
// Track focus
const groupDisposables = new DisposableStore();
groupDisposables.add(groupView.onDidFocus(() => {
this.doSetGroupActive(groupView);
this._onDidFocus.fire();
}));
// Track group changes
groupDisposables.add(groupView.onDidModelChange(e => {
switch (e.kind) {
case GroupModelChangeKind.GROUP_LOCKED:
this._onDidChangeGroupLocked.fire(groupView);
break;
case GroupModelChangeKind.GROUP_INDEX:
this._onDidChangeGroupIndex.fire(groupView);
break;
case GroupModelChangeKind.GROUP_LABEL:
this._onDidChangeGroupLabel.fire(groupView);
break;
}
}));
// Track active editor change after it occurred
groupDisposables.add(groupView.onDidActiveEditorChange(() => {
this.updateContainer();
}));
// Track dispose
Event.once(groupView.onWillDispose)(() => {
dispose(groupDisposables);
this.groupViews.delete(groupView.id);
this.doUpdateMostRecentActive(groupView);
});
return groupView;
}
private doSetGroupActive(group: IEditorGroupView): void {
if (this._activeGroup !== group) {
const previousActiveGroup = this._activeGroup;
this._activeGroup = group;
// Update list of most recently active groups
this.doUpdateMostRecentActive(group, true);
// Mark previous one as inactive
if (previousActiveGroup && !previousActiveGroup.disposed) {
previousActiveGroup.setActive(false);
}
// Mark group as new active
group.setActive(true);
// Expand the group if it is currently minimized
this.doRestoreGroup(group);
// Event
this._onDidChangeActiveGroup.fire(group);
}
// Always fire the event that a group has been activated
// even if its the same group that is already active to
// signal the intent even when nothing has changed.
this._onDidActivateGroup.fire(group);
}
private doRestoreGroup(group: IEditorGroupView): void {
if (!this.gridWidget) {
return; // method is called as part of state restore very early
}
try {
if (this.hasMaximizedGroup() && !this.isGroupMaximized(group)) {
this.unmaximizeGroup();
}
const viewSize = this.gridWidget.getViewSize(group);
if (viewSize.width === group.minimumWidth || viewSize.height === group.minimumHeight) {
this.arrangeGroups(GroupsArrangement.EXPAND, group);
}
} catch (error) {
// ignore: method might be called too early before view is known to grid
}
}
private doUpdateMostRecentActive(group: IEditorGroupView, makeMostRecentlyActive?: boolean): void {
const index = this.mostRecentActiveGroups.indexOf(group.id);
// Remove from MRU list
if (index !== -1) {
this.mostRecentActiveGroups.splice(index, 1);
}
// Add to front as needed
if (makeMostRecentlyActive) {
this.mostRecentActiveGroups.unshift(group.id);
}
}
private toGridViewDirection(direction: GroupDirection): Direction {
switch (direction) {
case GroupDirection.UP: return Direction.Up;
case GroupDirection.DOWN: return Direction.Down;
case GroupDirection.LEFT: return Direction.Left;
case GroupDirection.RIGHT: return Direction.Right;
}
}
private toGridViewOrientation(orientation: GroupOrientation, fallback: Orientation): Orientation {
if (typeof orientation === 'number') {
return orientation === GroupOrientation.HORIZONTAL ? Orientation.HORIZONTAL : Orientation.VERTICAL;
}
return fallback;
}
removeGroup(group: IEditorGroupView | GroupIdentifier, preserveFocus?: boolean): void {
const groupView = this.assertGroupView(group);
if (this.count === 1) {
return; // Cannot remove the last root group
}
// Remove empty group
if (groupView.isEmpty) {
this.doRemoveEmptyGroup(groupView, preserveFocus);
}
// Remove group with editors
else {
this.doRemoveGroupWithEditors(groupView);
}
}
private doRemoveGroupWithEditors(groupView: IEditorGroupView): void {
const mostRecentlyActiveGroups = this.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE);
let lastActiveGroup: IEditorGroupView;
if (this._activeGroup === groupView) {
lastActiveGroup = mostRecentlyActiveGroups[1];
} else {
lastActiveGroup = mostRecentlyActiveGroups[0];
}
// Removing a group with editors should merge these editors into the
// last active group and then remove this group.
this.mergeGroup(groupView, lastActiveGroup);
}
private doRemoveEmptyGroup(groupView: IEditorGroupView, preserveFocus?: boolean): void {
const restoreFocus = !preserveFocus && this.shouldRestoreFocus(this.container);
// Activate next group if the removed one was active
if (this._activeGroup === groupView) {
const mostRecentlyActiveGroups = this.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE);
const nextActiveGroup = mostRecentlyActiveGroups[1]; // [0] will be the current group we are about to dispose
this.doSetGroupActive(nextActiveGroup);
}
// Remove from grid widget & dispose
this.gridWidget.removeView(groupView, this.getSplitSizingStyle());
groupView.dispose();
// Restore focus if we had it previously after completing the grid
// operation. That operation might cause reparenting of grid views
// which moves focus to the <body> element otherwise.
if (restoreFocus) {
this._activeGroup.focus();
}
// Notify group index change given a group was removed
this.notifyGroupIndexChange();
// Update container
this.updateContainer();
// Event
this._onDidRemoveGroup.fire(groupView);
}
moveGroup(group: IEditorGroupView | GroupIdentifier, location: IEditorGroupView | GroupIdentifier, direction: GroupDirection): IEditorGroupView {
const sourceView = this.assertGroupView(group);
const targetView = this.assertGroupView(location);
if (sourceView.id === targetView.id) {
throw new Error('Cannot move group into its own');
}
const restoreFocus = this.shouldRestoreFocus(sourceView.element);
let movedView: IEditorGroupView;
// Same groups view: move via grid widget API
if (sourceView.groupsView === targetView.groupsView) {
this.gridWidget.moveView(sourceView, this.getSplitSizingStyle(), targetView, this.toGridViewDirection(direction));
movedView = sourceView;
}
// Different groups view: move via groups view API
else {
movedView = targetView.groupsView.addGroup(targetView, direction, sourceView);
sourceView.closeAllEditors();
this.removeGroup(sourceView, restoreFocus);
}
// Restore focus if we had it previously after completing the grid
// operation. That operation might cause reparenting of grid views
// which moves focus to the <body> element otherwise.
if (restoreFocus) {
movedView.focus();
}
// Event
this._onDidMoveGroup.fire(movedView);
// Notify group index change given a group was moved
this.notifyGroupIndexChange();
return movedView;
}
copyGroup(group: IEditorGroupView | GroupIdentifier, location: IEditorGroupView | GroupIdentifier, direction: GroupDirection): IEditorGroupView {
const groupView = this.assertGroupView(group);
const locationView = this.assertGroupView(location);
const restoreFocus = this.shouldRestoreFocus(groupView.element);
// Copy the group view
const copiedGroupView = this.addGroup(locationView, direction, groupView);
// Restore focus if we had it
if (restoreFocus) {
copiedGroupView.focus();
}
return copiedGroupView;
}
mergeGroup(group: IEditorGroupView | GroupIdentifier, target: IEditorGroupView | GroupIdentifier, options?: IMergeGroupOptions): boolean {
const sourceView = this.assertGroupView(group);
const targetView = this.assertGroupView(target);
// Collect editors to move/copy
const editors: EditorInputWithOptions[] = [];
let index = (options && typeof options.index === 'number') ? options.index : targetView.count;
for (const editor of sourceView.editors) {
const inactive = !sourceView.isActive(editor) || this._activeGroup !== sourceView;
let actualIndex: number | undefined;
if (targetView.contains(editor) &&
(
// Do not configure an `index` for editors that are sticky in
// the target, otherwise there is a chance of losing that state
// when the editor is moved.
// See https://github.com/microsoft/vscode/issues/239549
targetView.isSticky(editor) ||
// Do not configure an `index` when we are explicitly instructed
options?.preserveExistingIndex
)
) {
// leave `index` as `undefined`
} else {
actualIndex = index;
index++;
}
editors.push({
editor,
options: {
index: actualIndex,
inactive,
preserveFocus: inactive
}
});
}
// Move/Copy editors over into target
let result = true;
if (options?.mode === MergeGroupMode.COPY_EDITORS) {
sourceView.copyEditors(editors, targetView);
} else {
result = sourceView.moveEditors(editors, targetView);
}
// Remove source if the view is now empty and not already removed
if (sourceView.isEmpty && !sourceView.disposed /* could have been disposed already via workbench.editor.closeEmptyGroups setting */) {
this.removeGroup(sourceView, true);
}
return result;
}
mergeAllGroups(target: IEditorGroupView | GroupIdentifier, options?: IMergeGroupOptions): boolean {
const targetView = this.assertGroupView(target);
let result = true;
for (const group of this.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE)) {
if (group === targetView) {
continue; // keep target
}
const merged = this.mergeGroup(group, targetView, options);
if (!merged) {
result = false;
}
}
return result;
}
protected assertGroupView(group: IEditorGroupView | GroupIdentifier): IEditorGroupView {
let groupView: IEditorGroupView | undefined;
if (typeof group === 'number') {
groupView = this.editorPartsView.getGroup(group);
} else {
groupView = group;
}
if (!groupView) {
throw new Error('Invalid editor group provided!');
}
return groupView;
}
createEditorDropTarget(container: unknown, delegate: IEditorDropTargetDelegate): IDisposable {
assertType(isHTMLElement(container));
return this.scopedInstantiationService.createInstance(EditorDropTarget, container, delegate);
}
//#region Part
// TODO @sbatten @joao find something better to prevent editor taking over #79897
get minimumWidth(): number { return Math.min(this.centeredLayoutWidget.minimumWidth, this.layoutService.getMaximumEditorDimensions(this.layoutService.getContainer(getWindow(this.container))).width); }
get maximumWidth(): number { return this.centeredLayoutWidget.maximumWidth; }
get minimumHeight(): number { return Math.min(this.centeredLayoutWidget.minimumHeight, this.layoutService.getMaximumEditorDimensions(this.layoutService.getContainer(getWindow(this.container))).height); }
get maximumHeight(): number { return this.centeredLayoutWidget.maximumHeight; }
get snap(): boolean { return this.layoutService.getPanelAlignment() === 'center'; }
override get onDidChange(): Event<IViewSize | undefined> { return Event.any(this.centeredLayoutWidget.onDidChange, this.onDidSetGridWidget.event); }
readonly priority: LayoutPriority = LayoutPriority.High;
private get gridSeparatorBorder(): Color {
return this.theme.getColor(EDITOR_GROUP_BORDER) || this.theme.getColor(contrastBorder) || Color.transparent;
}
override updateStyles(): void {
const container = assertIsDefined(this.container);
container.style.backgroundColor = this.getColor(editorBackground) || '';
const separatorBorderStyle = { separatorBorder: this.gridSeparatorBorder, background: this.theme.getColor(EDITOR_PANE_BACKGROUND) || Color.transparent };
this.gridWidget.style(separatorBorderStyle);
this.centeredLayoutWidget.styles(separatorBorderStyle);
}
protected override createContentArea(parent: HTMLElement, options?: IEditorPartCreationOptions): HTMLElement {
// Container
this.element = parent;
this.container = $('.content');
if (this.windowId !== mainWindow.vscodeWindowId) {
this.container.classList.add('auxiliary');
}
parent.appendChild(this.container);