-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
Copy pathlayout.ts
2818 lines (2304 loc) · 112 KB
/
layout.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 { Disposable, DisposableMap, DisposableStore, IDisposable, toDisposable } from '../../base/common/lifecycle.js';
import { Event, Emitter } from '../../base/common/event.js';
import { EventType, addDisposableListener, getClientArea, position, size, IDimension, isAncestorUsingFlowTo, computeScreenAwareSize, getActiveDocument, getWindows, getActiveWindow, isActiveDocument, getWindow, getWindowId, getActiveElement } from '../../base/browser/dom.js';
import { onDidChangeFullscreen, isFullscreen, isWCOEnabled } from '../../base/browser/browser.js';
import { IWorkingCopyBackupService } from '../services/workingCopy/common/workingCopyBackup.js';
import { isWindows, isLinux, isMacintosh, isWeb, isIOS } from '../../base/common/platform.js';
import { EditorInputCapabilities, GroupIdentifier, isResourceEditorInput, IUntypedEditorInput, pathsToEditors } from '../common/editor.js';
import { SidebarPart } from './parts/sidebar/sidebarPart.js';
import { PanelPart } from './parts/panel/panelPart.js';
import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString, PanelAlignment, ActivityBarPosition, LayoutSettings, MULTI_WINDOW_PARTS, SINGLE_WINDOW_PARTS, ZenModeSettings, EditorTabsMode, EditorActionsLocation, shouldShowCustomTitleBar, isHorizontal } from '../services/layout/browser/layoutService.js';
import { isTemporaryWorkspace, IWorkspaceContextService, WorkbenchState } from '../../platform/workspace/common/workspace.js';
import { IStorageService, StorageScope, StorageTarget } from '../../platform/storage/common/storage.js';
import { IConfigurationChangeEvent, IConfigurationService } from '../../platform/configuration/common/configuration.js';
import { ITitleService } from '../services/title/browser/titleService.js';
import { ServicesAccessor } from '../../platform/instantiation/common/instantiation.js';
import { StartupKind, ILifecycleService } from '../services/lifecycle/common/lifecycle.js';
import { getMenuBarVisibility, IPath, hasNativeTitlebar, hasCustomTitlebar, TitleBarSetting, CustomTitleBarVisibility, useWindowControlsOverlay } from '../../platform/window/common/window.js';
import { IHostService } from '../services/host/browser/host.js';
import { IBrowserWorkbenchEnvironmentService } from '../services/environment/browser/environmentService.js';
import { IEditorService } from '../services/editor/common/editorService.js';
import { EditorGroupLayout, GroupOrientation, GroupsOrder, IEditorGroupsService } from '../services/editor/common/editorGroupsService.js';
import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize, Sizing } from '../../base/browser/ui/grid/grid.js';
import { Part } from './part.js';
import { IStatusbarService } from '../services/statusbar/browser/statusbar.js';
import { IFileService } from '../../platform/files/common/files.js';
import { isCodeEditor } from '../../editor/browser/editorBrowser.js';
import { coalesce } from '../../base/common/arrays.js';
import { assertIsDefined, isDefined } from '../../base/common/types.js';
import { INotificationService, NotificationsFilter } from '../../platform/notification/common/notification.js';
import { IThemeService } from '../../platform/theme/common/themeService.js';
import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from '../common/theme.js';
import { LineNumbersType } from '../../editor/common/config/editorOptions.js';
import { URI } from '../../base/common/uri.js';
import { IViewDescriptorService, ViewContainerLocation } from '../common/views.js';
import { DiffEditorInput } from '../common/editor/diffEditorInput.js';
import { mark } from '../../base/common/performance.js';
import { IExtensionService } from '../services/extensions/common/extensions.js';
import { ILogService } from '../../platform/log/common/log.js';
import { DeferredPromise, Promises } from '../../base/common/async.js';
import { IBannerService } from '../services/banner/browser/bannerService.js';
import { IPaneCompositePartService } from '../services/panecomposite/browser/panecomposite.js';
import { AuxiliaryBarPart } from './parts/auxiliarybar/auxiliaryBarPart.js';
import { ITelemetryService } from '../../platform/telemetry/common/telemetry.js';
import { IAuxiliaryWindowService } from '../services/auxiliaryWindow/browser/auxiliaryWindowService.js';
import { CodeWindow, mainWindow } from '../../base/browser/window.js';
//#region Layout Implementation
interface ILayoutRuntimeState {
activeContainerId: number;
mainWindowFullscreen: boolean;
readonly maximized: Set<number>;
hasFocus: boolean;
mainWindowBorder: boolean;
readonly menuBar: {
toggled: boolean;
};
readonly zenMode: {
readonly transitionDisposables: DisposableMap<string, IDisposable>;
};
}
interface IEditorToOpen {
readonly editor: IUntypedEditorInput;
readonly viewColumn?: number;
}
interface ILayoutInitializationState {
readonly views: {
readonly defaults: string[] | undefined;
readonly containerToRestore: {
sideBar?: string;
panel?: string;
auxiliaryBar?: string;
};
};
readonly editor: {
readonly restoreEditors: boolean;
readonly editorsToOpen: Promise<IEditorToOpen[]>;
};
readonly layout?: {
readonly editors?: EditorGroupLayout;
};
}
interface ILayoutState {
readonly runtime: ILayoutRuntimeState;
readonly initialization: ILayoutInitializationState;
}
enum LayoutClasses {
SIDEBAR_HIDDEN = 'nosidebar',
MAIN_EDITOR_AREA_HIDDEN = 'nomaineditorarea',
PANEL_HIDDEN = 'nopanel',
AUXILIARYBAR_HIDDEN = 'noauxiliarybar',
STATUSBAR_HIDDEN = 'nostatusbar',
FULLSCREEN = 'fullscreen',
MAXIMIZED = 'maximized',
WINDOW_BORDER = 'border'
}
interface IPathToOpen extends IPath {
readonly viewColumn?: number;
}
interface IInitialEditorsState {
readonly filesToOpenOrCreate?: IPathToOpen[];
readonly filesToDiff?: IPathToOpen[];
readonly filesToMerge?: IPathToOpen[];
readonly layout?: EditorGroupLayout;
}
const COMMAND_CENTER_SETTINGS = [
'chat.commandCenter.enabled',
'workbench.navigationControl.enabled',
'workbench.experimental.share.enabled',
];
export const TITLE_BAR_SETTINGS = [
LayoutSettings.ACTIVITY_BAR_LOCATION,
LayoutSettings.COMMAND_CENTER,
...COMMAND_CENTER_SETTINGS,
LayoutSettings.EDITOR_ACTIONS_LOCATION,
LayoutSettings.LAYOUT_ACTIONS,
'window.menuBarVisibility',
TitleBarSetting.TITLE_BAR_STYLE,
TitleBarSetting.CUSTOM_TITLE_BAR_VISIBILITY,
];
export abstract class Layout extends Disposable implements IWorkbenchLayoutService {
declare readonly _serviceBrand: undefined;
//#region Events
private readonly _onDidChangeZenMode = this._register(new Emitter<boolean>());
readonly onDidChangeZenMode = this._onDidChangeZenMode.event;
private readonly _onDidChangeMainEditorCenteredLayout = this._register(new Emitter<boolean>());
readonly onDidChangeMainEditorCenteredLayout = this._onDidChangeMainEditorCenteredLayout.event;
private readonly _onDidChangePanelAlignment = this._register(new Emitter<PanelAlignment>());
readonly onDidChangePanelAlignment = this._onDidChangePanelAlignment.event;
private readonly _onDidChangeWindowMaximized = this._register(new Emitter<{ windowId: number; maximized: boolean }>());
readonly onDidChangeWindowMaximized = this._onDidChangeWindowMaximized.event;
private readonly _onDidChangePanelPosition = this._register(new Emitter<string>());
readonly onDidChangePanelPosition = this._onDidChangePanelPosition.event;
private readonly _onDidChangePartVisibility = this._register(new Emitter<void>());
readonly onDidChangePartVisibility = this._onDidChangePartVisibility.event;
private readonly _onDidChangeNotificationsVisibility = this._register(new Emitter<boolean>());
readonly onDidChangeNotificationsVisibility = this._onDidChangeNotificationsVisibility.event;
private readonly _onDidLayoutMainContainer = this._register(new Emitter<IDimension>());
readonly onDidLayoutMainContainer = this._onDidLayoutMainContainer.event;
private readonly _onDidLayoutActiveContainer = this._register(new Emitter<IDimension>());
readonly onDidLayoutActiveContainer = this._onDidLayoutActiveContainer.event;
private readonly _onDidLayoutContainer = this._register(new Emitter<{ container: HTMLElement; dimension: IDimension }>());
readonly onDidLayoutContainer = this._onDidLayoutContainer.event;
private readonly _onDidAddContainer = this._register(new Emitter<{ container: HTMLElement; disposables: DisposableStore }>());
readonly onDidAddContainer = this._onDidAddContainer.event;
private readonly _onDidChangeActiveContainer = this._register(new Emitter<void>());
readonly onDidChangeActiveContainer = this._onDidChangeActiveContainer.event;
//#endregion
//#region Properties
readonly mainContainer = document.createElement('div');
get activeContainer() { return this.getContainerFromDocument(getActiveDocument()); }
get containers(): Iterable<HTMLElement> {
const containers: HTMLElement[] = [];
for (const { window } of getWindows()) {
containers.push(this.getContainerFromDocument(window.document));
}
return containers;
}
private getContainerFromDocument(targetDocument: Document): HTMLElement {
if (targetDocument === this.mainContainer.ownerDocument) {
// main window
return this.mainContainer;
} else {
// auxiliary window
return targetDocument.body.getElementsByClassName('monaco-workbench')[0] as HTMLElement;
}
}
private readonly containerStylesLoaded = new Map<number /* window ID */, Promise<void>>();
whenContainerStylesLoaded(window: CodeWindow): Promise<void> | undefined {
return this.containerStylesLoaded.get(window.vscodeWindowId);
}
private _mainContainerDimension!: IDimension;
get mainContainerDimension(): IDimension { return this._mainContainerDimension; }
get activeContainerDimension(): IDimension {
return this.getContainerDimension(this.activeContainer);
}
private getContainerDimension(container: HTMLElement): IDimension {
if (container === this.mainContainer) {
return this.mainContainerDimension; // main window
} else {
return getClientArea(container); // auxiliary window
}
}
get mainContainerOffset() {
return this.computeContainerOffset(mainWindow);
}
get activeContainerOffset() {
return this.computeContainerOffset(getWindow(this.activeContainer));
}
private computeContainerOffset(targetWindow: Window) {
let top = 0;
let quickPickTop = 0;
if (this.isVisible(Parts.BANNER_PART)) {
top = this.getPart(Parts.BANNER_PART).maximumHeight;
quickPickTop = top;
}
const titlebarVisible = this.isVisible(Parts.TITLEBAR_PART, targetWindow);
if (titlebarVisible) {
top += this.getPart(Parts.TITLEBAR_PART).maximumHeight;
quickPickTop = top;
}
const isCommandCenterVisible = titlebarVisible && this.configurationService.getValue<boolean>(LayoutSettings.COMMAND_CENTER) !== false;
if (isCommandCenterVisible) {
// If the command center is visible then the quickinput
// should go over the title bar and the banner
quickPickTop = 6;
}
return { top, quickPickTop };
}
//#endregion
private readonly parts = new Map<string, Part>();
private initialized = false;
private workbenchGrid!: SerializableGrid<ISerializableView>;
private titleBarPartView!: ISerializableView;
private bannerPartView!: ISerializableView;
private activityBarPartView!: ISerializableView;
private sideBarPartView!: ISerializableView;
private panelPartView!: ISerializableView;
private auxiliaryBarPartView!: ISerializableView;
private editorPartView!: ISerializableView;
private statusBarPartView!: ISerializableView;
private environmentService!: IBrowserWorkbenchEnvironmentService;
private extensionService!: IExtensionService;
private configurationService!: IConfigurationService;
private storageService!: IStorageService;
private hostService!: IHostService;
private editorService!: IEditorService;
private mainPartEditorService!: IEditorService;
private editorGroupService!: IEditorGroupsService;
private paneCompositeService!: IPaneCompositePartService;
private titleService!: ITitleService;
private viewDescriptorService!: IViewDescriptorService;
private contextService!: IWorkspaceContextService;
private workingCopyBackupService!: IWorkingCopyBackupService;
private notificationService!: INotificationService;
private themeService!: IThemeService;
private statusBarService!: IStatusbarService;
private logService!: ILogService;
private telemetryService!: ITelemetryService;
private auxiliaryWindowService!: IAuxiliaryWindowService;
private state!: ILayoutState;
private stateModel!: LayoutStateModel;
private disposed = false;
constructor(
protected readonly parent: HTMLElement
) {
super();
}
protected initLayout(accessor: ServicesAccessor): void {
// Services
this.environmentService = accessor.get(IBrowserWorkbenchEnvironmentService);
this.configurationService = accessor.get(IConfigurationService);
this.hostService = accessor.get(IHostService);
this.contextService = accessor.get(IWorkspaceContextService);
this.storageService = accessor.get(IStorageService);
this.workingCopyBackupService = accessor.get(IWorkingCopyBackupService);
this.themeService = accessor.get(IThemeService);
this.extensionService = accessor.get(IExtensionService);
this.logService = accessor.get(ILogService);
this.telemetryService = accessor.get(ITelemetryService);
this.auxiliaryWindowService = accessor.get(IAuxiliaryWindowService);
// Parts
this.editorService = accessor.get(IEditorService);
this.mainPartEditorService = this.editorService.createScoped('main', this._store);
this.editorGroupService = accessor.get(IEditorGroupsService);
this.paneCompositeService = accessor.get(IPaneCompositePartService);
this.viewDescriptorService = accessor.get(IViewDescriptorService);
this.titleService = accessor.get(ITitleService);
this.notificationService = accessor.get(INotificationService);
this.statusBarService = accessor.get(IStatusbarService);
accessor.get(IBannerService);
// Listeners
this.registerLayoutListeners();
// State
this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService));
}
private registerLayoutListeners(): void {
// Restore editor if hidden
const showEditorIfHidden = () => {
if (!this.isVisible(Parts.EDITOR_PART, mainWindow)) {
this.toggleMaximizedPanel();
}
};
// Wait to register these listeners after the editor group service
// is ready to avoid conflicts on startup
this.editorGroupService.whenRestored.then(() => {
// Restore main editor part on any editor change in main part
this._register(this.mainPartEditorService.onDidVisibleEditorsChange(showEditorIfHidden));
this._register(this.editorGroupService.mainPart.onDidActivateGroup(showEditorIfHidden));
// Revalidate center layout when active editor changes: diff editor quits centered mode.
this._register(this.mainPartEditorService.onDidActiveEditorChange(() => this.centerMainEditorLayout(this.stateModel.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
});
// Configuration changes
this._register(this.configurationService.onDidChangeConfiguration((e) => {
if ([
...TITLE_BAR_SETTINGS,
LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION,
LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE,
].some(setting => e.affectsConfiguration(setting))) {
// Show Command Center if command center actions enabled
const shareEnabled = e.affectsConfiguration('workbench.experimental.share.enabled') && this.configurationService.getValue<boolean>('workbench.experimental.share.enabled');
const navigationControlEnabled = e.affectsConfiguration('workbench.navigationControl.enabled') && this.configurationService.getValue<boolean>('workbench.navigationControl.enabled');
// Currently not supported for "chat.commandCenter.enabled" as we
// programatically set this during setup and could lead to unwanted titlebar appearing
// const chatControlsEnabled = e.affectsConfiguration('chat.commandCenter.enabled') && this.configurationService.getValue<boolean>('chat.commandCenter.enabled');
if (shareEnabled || navigationControlEnabled) {
if (this.configurationService.getValue<boolean>(LayoutSettings.COMMAND_CENTER) === false) {
this.configurationService.updateValue(LayoutSettings.COMMAND_CENTER, true);
return; // onDidChangeConfiguration will be triggered again
}
}
// Show Custom TitleBar if actions enabled in (or moved to) the titlebar
const editorActionsMovedToTitlebar = e.affectsConfiguration(LayoutSettings.EDITOR_ACTIONS_LOCATION) && this.configurationService.getValue<EditorActionsLocation>(LayoutSettings.EDITOR_ACTIONS_LOCATION) === EditorActionsLocation.TITLEBAR;
const commandCenterEnabled = e.affectsConfiguration(LayoutSettings.COMMAND_CENTER) && this.configurationService.getValue<boolean>(LayoutSettings.COMMAND_CENTER);
const layoutControlsEnabled = e.affectsConfiguration(LayoutSettings.LAYOUT_ACTIONS) && this.configurationService.getValue<boolean>(LayoutSettings.LAYOUT_ACTIONS);
const activityBarMovedToTopOrBottom = e.affectsConfiguration(LayoutSettings.ACTIVITY_BAR_LOCATION) && [ActivityBarPosition.TOP, ActivityBarPosition.BOTTOM].includes(this.configurationService.getValue<ActivityBarPosition>(LayoutSettings.ACTIVITY_BAR_LOCATION));
if (activityBarMovedToTopOrBottom || editorActionsMovedToTitlebar || commandCenterEnabled || layoutControlsEnabled) {
if (this.configurationService.getValue<CustomTitleBarVisibility>(TitleBarSetting.CUSTOM_TITLE_BAR_VISIBILITY) === CustomTitleBarVisibility.NEVER) {
this.configurationService.updateValue(TitleBarSetting.CUSTOM_TITLE_BAR_VISIBILITY, CustomTitleBarVisibility.AUTO);
return; // onDidChangeConfiguration will be triggered again
}
}
this.doUpdateLayoutConfiguration();
}
}));
// Fullscreen changes
this._register(onDidChangeFullscreen(windowId => this.onFullscreenChanged(windowId)));
// Group changes
this._register(this.editorGroupService.mainPart.onDidAddGroup(() => this.centerMainEditorLayout(this.stateModel.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
this._register(this.editorGroupService.mainPart.onDidRemoveGroup(() => this.centerMainEditorLayout(this.stateModel.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
this._register(this.editorGroupService.mainPart.onDidChangeGroupMaximized(() => this.centerMainEditorLayout(this.stateModel.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
// Prevent workbench from scrolling #55456
this._register(addDisposableListener(this.mainContainer, EventType.SCROLL, () => this.mainContainer.scrollTop = 0));
// Menubar visibility changes
const showingCustomMenu = (isWindows || isLinux || isWeb) && !hasNativeTitlebar(this.configurationService);
if (showingCustomMenu) {
this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible)));
}
// Theme changes
this._register(this.themeService.onDidColorThemeChange(() => this.updateWindowsBorder()));
// Window active / focus changes
this._register(this.hostService.onDidChangeFocus(focused => this.onWindowFocusChanged(focused)));
this._register(this.hostService.onDidChangeActiveWindow(() => this.onActiveWindowChanged()));
// WCO changes
if (isWeb && typeof (navigator as any).windowControlsOverlay === 'object') {
this._register(addDisposableListener((navigator as any).windowControlsOverlay, 'geometrychange', () => this.onDidChangeWCO()));
}
// Auxiliary windows
this._register(this.auxiliaryWindowService.onDidOpenAuxiliaryWindow(({ window, disposables }) => {
const windowId = window.window.vscodeWindowId;
this.containerStylesLoaded.set(windowId, window.whenStylesHaveLoaded);
window.whenStylesHaveLoaded.then(() => this.containerStylesLoaded.delete(windowId));
disposables.add(toDisposable(() => this.containerStylesLoaded.delete(windowId)));
const eventDisposables = disposables.add(new DisposableStore());
this._onDidAddContainer.fire({ container: window.container, disposables: eventDisposables });
disposables.add(window.onDidLayout(dimension => this.handleContainerDidLayout(window.container, dimension)));
}));
}
private onMenubarToggled(visible: boolean): void {
if (visible !== this.state.runtime.menuBar.toggled) {
this.state.runtime.menuBar.toggled = visible;
const menuBarVisibility = getMenuBarVisibility(this.configurationService);
// The menu bar toggles the title bar in web because it does not need to be shown for window controls only
if (isWeb && menuBarVisibility === 'toggle') {
this.workbenchGrid.setViewVisible(this.titleBarPartView, shouldShowCustomTitleBar(this.configurationService, mainWindow, this.state.runtime.menuBar.toggled));
}
// The menu bar toggles the title bar in full screen for toggle and classic settings
else if (this.state.runtime.mainWindowFullscreen && (menuBarVisibility === 'toggle' || menuBarVisibility === 'classic')) {
this.workbenchGrid.setViewVisible(this.titleBarPartView, shouldShowCustomTitleBar(this.configurationService, mainWindow, this.state.runtime.menuBar.toggled));
}
// Move layout call to any time the menubar
// is toggled to update consumers of offset
// see issue #115267
this.handleContainerDidLayout(this.mainContainer, this._mainContainerDimension);
}
}
private handleContainerDidLayout(container: HTMLElement, dimension: IDimension): void {
if (container === this.mainContainer) {
this._onDidLayoutMainContainer.fire(dimension);
}
if (isActiveDocument(container)) {
this._onDidLayoutActiveContainer.fire(dimension);
}
this._onDidLayoutContainer.fire({ container, dimension });
}
private onFullscreenChanged(windowId: number): void {
if (windowId !== mainWindow.vscodeWindowId) {
return; // ignore all but main window
}
this.state.runtime.mainWindowFullscreen = isFullscreen(mainWindow);
// Apply as CSS class
if (this.state.runtime.mainWindowFullscreen) {
this.mainContainer.classList.add(LayoutClasses.FULLSCREEN);
} else {
this.mainContainer.classList.remove(LayoutClasses.FULLSCREEN);
const zenModeExitInfo = this.stateModel.getRuntimeValue(LayoutStateKeys.ZEN_MODE_EXIT_INFO);
if (zenModeExitInfo.transitionedToFullScreen && this.isZenModeActive()) {
this.toggleZenMode();
}
}
// Change edge snapping accordingly
this.workbenchGrid.edgeSnapping = this.state.runtime.mainWindowFullscreen;
// Changing fullscreen state of the main window has an impact
// on custom title bar visibility, so we need to update
if (hasCustomTitlebar(this.configurationService)) {
// Propagate to grid
this.workbenchGrid.setViewVisible(this.titleBarPartView, shouldShowCustomTitleBar(this.configurationService, mainWindow, this.state.runtime.menuBar.toggled));
this.updateWindowsBorder(true);
}
}
private onActiveWindowChanged(): void {
const activeContainerId = this.getActiveContainerId();
if (this.state.runtime.activeContainerId !== activeContainerId) {
this.state.runtime.activeContainerId = activeContainerId;
// Indicate active window border
this.updateWindowsBorder();
this._onDidChangeActiveContainer.fire();
}
}
private onWindowFocusChanged(hasFocus: boolean): void {
if (this.state.runtime.hasFocus !== hasFocus) {
this.state.runtime.hasFocus = hasFocus;
this.updateWindowsBorder();
}
}
private getActiveContainerId(): number {
const activeContainer = this.activeContainer;
return getWindow(activeContainer).vscodeWindowId;
}
private doUpdateLayoutConfiguration(skipLayout?: boolean): void {
// Custom Titlebar visibility with native titlebar
this.updateCustomTitleBarVisibility();
// Menubar visibility
this.updateMenubarVisibility(!!skipLayout);
// Centered Layout
this.editorGroupService.whenRestored.then(() => {
this.centerMainEditorLayout(this.stateModel.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED), skipLayout);
});
}
private setSideBarPosition(position: Position): void {
const activityBar = this.getPart(Parts.ACTIVITYBAR_PART);
const sideBar = this.getPart(Parts.SIDEBAR_PART);
const auxiliaryBar = this.getPart(Parts.AUXILIARYBAR_PART);
const newPositionValue = (position === Position.LEFT) ? 'left' : 'right';
const oldPositionValue = (position === Position.RIGHT) ? 'left' : 'right';
const panelAlignment = this.getPanelAlignment();
const panelPosition = this.getPanelPosition();
this.stateModel.setRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON, position);
// Adjust CSS
const activityBarContainer = assertIsDefined(activityBar.getContainer());
const sideBarContainer = assertIsDefined(sideBar.getContainer());
const auxiliaryBarContainer = assertIsDefined(auxiliaryBar.getContainer());
activityBarContainer.classList.remove(oldPositionValue);
sideBarContainer.classList.remove(oldPositionValue);
activityBarContainer.classList.add(newPositionValue);
sideBarContainer.classList.add(newPositionValue);
// Auxiliary Bar has opposite values
auxiliaryBarContainer.classList.remove(newPositionValue);
auxiliaryBarContainer.classList.add(oldPositionValue);
// Update Styles
activityBar.updateStyles();
sideBar.updateStyles();
auxiliaryBar.updateStyles();
// Move activity bar and side bars
this.adjustPartPositions(position, panelAlignment, panelPosition);
}
private updateWindowsBorder(skipLayout = false) {
if (
isWeb ||
isWindows || // not working well with zooming (border often not visible)
useWindowControlsOverlay(this.configurationService) || // not working with WCO (border cannot draw over the overlay)
hasNativeTitlebar(this.configurationService)
) {
return;
}
const theme = this.themeService.getColorTheme();
const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER);
const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER);
const didHaveMainWindowBorder = this.hasMainWindowBorder();
for (const container of this.containers) {
const isMainContainer = container === this.mainContainer;
const isActiveContainer = this.activeContainer === container;
const containerWindowId = getWindowId(getWindow(container));
let windowBorder = false;
if (!this.state.runtime.mainWindowFullscreen && !this.state.runtime.maximized.has(containerWindowId) && (activeBorder || inactiveBorder)) {
windowBorder = true;
// If the inactive color is missing, fallback to the active one
const borderColor = isActiveContainer && this.state.runtime.hasFocus ? activeBorder : inactiveBorder ?? activeBorder;
container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent');
}
if (isMainContainer) {
this.state.runtime.mainWindowBorder = windowBorder;
}
container.classList.toggle(LayoutClasses.WINDOW_BORDER, windowBorder);
}
if (!skipLayout && didHaveMainWindowBorder !== this.hasMainWindowBorder()) {
this.layout();
}
}
private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void {
this._mainContainerDimension = getClientArea(this.parent);
this.stateModel = new LayoutStateModel(this.storageService, this.configurationService, this.contextService);
this.stateModel.load(this._mainContainerDimension);
// Both editor and panel should not be hidden on startup
if (this.stateModel.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN) && this.stateModel.getRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN)) {
this.stateModel.setRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN, false);
}
this._register(this.stateModel.onDidChangeState(change => {
if (change.key === LayoutStateKeys.ACTIVITYBAR_HIDDEN) {
this.setActivityBarHidden(change.value as boolean);
}
if (change.key === LayoutStateKeys.STATUSBAR_HIDDEN) {
this.setStatusBarHidden(change.value as boolean);
}
if (change.key === LayoutStateKeys.SIDEBAR_POSITON) {
this.setSideBarPosition(change.value as Position);
}
if (change.key === LayoutStateKeys.PANEL_POSITION) {
this.setPanelPosition(change.value as Position);
}
if (change.key === LayoutStateKeys.PANEL_ALIGNMENT) {
this.setPanelAlignment(change.value as PanelAlignment);
}
this.doUpdateLayoutConfiguration();
}));
// Layout Initialization State
const initialEditorsState = this.getInitialEditorsState();
if (initialEditorsState) {
this.logService.trace('Initial editor state', initialEditorsState);
}
const initialLayoutState: ILayoutInitializationState = {
layout: {
editors: initialEditorsState?.layout
},
editor: {
restoreEditors: this.shouldRestoreEditors(this.contextService, initialEditorsState),
editorsToOpen: this.resolveEditorsToOpen(fileService, initialEditorsState),
},
views: {
defaults: this.getDefaultLayoutViews(this.environmentService, this.storageService),
containerToRestore: {}
}
};
// Layout Runtime State
const layoutRuntimeState: ILayoutRuntimeState = {
activeContainerId: this.getActiveContainerId(),
mainWindowFullscreen: isFullscreen(mainWindow),
hasFocus: this.hostService.hasFocus,
maximized: new Set<number>(),
mainWindowBorder: false,
menuBar: {
toggled: false,
},
zenMode: {
transitionDisposables: new DisposableMap(),
}
};
this.state = {
initialization: initialLayoutState,
runtime: layoutRuntimeState,
};
// Sidebar View Container To Restore
if (this.isVisible(Parts.SIDEBAR_PART)) {
// Only restore last viewlet if window was reloaded or we are in development mode
let viewContainerToRestore: string | undefined;
if (
!this.environmentService.isBuilt ||
lifecycleService.startupKind === StartupKind.ReloadedWindow ||
this.environmentService.isExtensionDevelopment && !this.environmentService.extensionTestsLocationURI
) {
viewContainerToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id);
} else {
viewContainerToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id;
}
if (viewContainerToRestore) {
this.state.initialization.views.containerToRestore.sideBar = viewContainerToRestore;
} else {
this.stateModel.setRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN, true);
}
}
// Panel View Container To Restore
if (this.isVisible(Parts.PANEL_PART)) {
const viewContainerToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Panel)?.id);
if (viewContainerToRestore) {
this.state.initialization.views.containerToRestore.panel = viewContainerToRestore;
} else {
this.stateModel.setRuntimeValue(LayoutStateKeys.PANEL_HIDDEN, true);
}
}
// Auxiliary View to restore
if (this.isVisible(Parts.AUXILIARYBAR_PART)) {
const viewContainerToRestore = this.storageService.get(AuxiliaryBarPart.activeViewSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.AuxiliaryBar)?.id);
if (viewContainerToRestore) {
this.state.initialization.views.containerToRestore.auxiliaryBar = viewContainerToRestore;
} else {
this.stateModel.setRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN, true);
}
}
// Window border
this.updateWindowsBorder(true);
}
private getDefaultLayoutViews(environmentService: IBrowserWorkbenchEnvironmentService, storageService: IStorageService): string[] | undefined {
const defaultLayout = environmentService.options?.defaultLayout;
if (!defaultLayout) {
return undefined;
}
if (!defaultLayout.force && !storageService.isNew(StorageScope.WORKSPACE)) {
return undefined;
}
const { views } = defaultLayout;
if (views?.length) {
return views.map(view => view.id);
}
return undefined;
}
private shouldRestoreEditors(contextService: IWorkspaceContextService, initialEditorsState: IInitialEditorsState | undefined): boolean {
// Restore editors based on a set of rules:
// - never when running on temporary workspace
// - not when we have files to open, unless:
// - always when `window.restoreWindows: preserve`
if (isTemporaryWorkspace(contextService.getWorkspace())) {
return false;
}
const forceRestoreEditors = this.configurationService.getValue<string>('window.restoreWindows') === 'preserve';
return !!forceRestoreEditors || initialEditorsState === undefined;
}
protected willRestoreEditors(): boolean {
return this.state.initialization.editor.restoreEditors;
}
private async resolveEditorsToOpen(fileService: IFileService, initialEditorsState: IInitialEditorsState | undefined): Promise<IEditorToOpen[]> {
if (initialEditorsState) {
// Merge editor (single)
const filesToMerge = coalesce(await pathsToEditors(initialEditorsState.filesToMerge, fileService, this.logService));
if (filesToMerge.length === 4 && isResourceEditorInput(filesToMerge[0]) && isResourceEditorInput(filesToMerge[1]) && isResourceEditorInput(filesToMerge[2]) && isResourceEditorInput(filesToMerge[3])) {
return [{
editor: {
input1: { resource: filesToMerge[0].resource },
input2: { resource: filesToMerge[1].resource },
base: { resource: filesToMerge[2].resource },
result: { resource: filesToMerge[3].resource },
options: { pinned: true }
}
}];
}
// Diff editor (single)
const filesToDiff = coalesce(await pathsToEditors(initialEditorsState.filesToDiff, fileService, this.logService));
if (filesToDiff.length === 2) {
return [{
editor: {
original: { resource: filesToDiff[0].resource },
modified: { resource: filesToDiff[1].resource },
options: { pinned: true }
}
}];
}
// Normal editor (multiple)
const filesToOpenOrCreate: IEditorToOpen[] = [];
const resolvedFilesToOpenOrCreate = await pathsToEditors(initialEditorsState.filesToOpenOrCreate, fileService, this.logService);
for (let i = 0; i < resolvedFilesToOpenOrCreate.length; i++) {
const resolvedFileToOpenOrCreate = resolvedFilesToOpenOrCreate[i];
if (resolvedFileToOpenOrCreate) {
filesToOpenOrCreate.push({
editor: resolvedFileToOpenOrCreate,
viewColumn: initialEditorsState.filesToOpenOrCreate?.[i].viewColumn // take over `viewColumn` from initial state
});
}
}
return filesToOpenOrCreate;
}
// Empty workbench configured to open untitled file if empty
else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') {
if (this.editorGroupService.hasRestorableState) {
return []; // do not open any empty untitled file if we restored groups/editors from previous session
}
const hasBackups = await this.workingCopyBackupService.hasBackups();
if (hasBackups) {
return []; // do not open any empty untitled file if we have backups to restore
}
return [{
editor: { resource: undefined } // open empty untitled file
}];
}
return [];
}
private _openedDefaultEditors: boolean = false;
get openedDefaultEditors() { return this._openedDefaultEditors; }
private getInitialEditorsState(): IInitialEditorsState | undefined {
// Check for editors / editor layout from `defaultLayout` options first
const defaultLayout = this.environmentService.options?.defaultLayout;
if ((defaultLayout?.editors?.length || defaultLayout?.layout?.editors) && (defaultLayout.force || this.storageService.isNew(StorageScope.WORKSPACE))) {
this._openedDefaultEditors = true;
return {
layout: defaultLayout.layout?.editors,
filesToOpenOrCreate: defaultLayout?.editors?.map(editor => {
return {
viewColumn: editor.viewColumn,
fileUri: URI.revive(editor.uri),
openOnlyIfExists: editor.openOnlyIfExists,
options: editor.options
};
})
};
}
// Then check for files to open, create or diff/merge from main side
const { filesToOpenOrCreate, filesToDiff, filesToMerge } = this.environmentService;
if (filesToOpenOrCreate || filesToDiff || filesToMerge) {
return { filesToOpenOrCreate, filesToDiff, filesToMerge };
}
return undefined;
}
private readonly whenReadyPromise = new DeferredPromise<void>();
protected readonly whenReady = this.whenReadyPromise.p;
private readonly whenRestoredPromise = new DeferredPromise<void>();
readonly whenRestored = this.whenRestoredPromise.p;
private restored = false;
isRestored(): boolean {
return this.restored;
}
protected restoreParts(): void {
// distinguish long running restore operations that
// are required for the layout to be ready from those
// that are needed to signal restoring is done
const layoutReadyPromises: Promise<unknown>[] = [];
const layoutRestoredPromises: Promise<unknown>[] = [];
// Restore editors
layoutReadyPromises.push((async () => {
mark('code/willRestoreEditors');
// first ensure the editor part is ready
await this.editorGroupService.whenReady;
mark('code/restoreEditors/editorGroupsReady');
// apply editor layout if any
if (this.state.initialization.layout?.editors) {
this.editorGroupService.mainPart.applyLayout(this.state.initialization.layout.editors);
}
// then see for editors to open as instructed
// it is important that we trigger this from
// the overall restore flow to reduce possible
// flicker on startup: we want any editor to
// open to get a chance to open first before
// signaling that layout is restored, but we do
// not need to await the editors from having
// fully loaded.
const editors = await this.state.initialization.editor.editorsToOpen;
mark('code/restoreEditors/editorsToOpenResolved');
let openEditorsPromise: Promise<unknown> | undefined = undefined;
if (editors.length) {
// we have to map editors to their groups as instructed
// by the input. this is important to ensure that we open
// the editors in the groups they belong to.
const editorGroupsInVisualOrder = this.editorGroupService.mainPart.getGroups(GroupsOrder.GRID_APPEARANCE);
const mapEditorsToGroup = new Map<GroupIdentifier, Set<IUntypedEditorInput>>();
for (const editor of editors) {
const group = editorGroupsInVisualOrder[(editor.viewColumn ?? 1) - 1]; // viewColumn is index+1 based
let editorsByGroup = mapEditorsToGroup.get(group.id);
if (!editorsByGroup) {
editorsByGroup = new Set<IUntypedEditorInput>();
mapEditorsToGroup.set(group.id, editorsByGroup);
}
editorsByGroup.add(editor.editor);
}
openEditorsPromise = Promise.all(Array.from(mapEditorsToGroup).map(async ([groupId, editors]) => {
try {
await this.editorService.openEditors(Array.from(editors), groupId, { validateTrust: true });
} catch (error) {
this.logService.error(error);
}
}));
}
// do not block the overall layout ready flow from potentially
// slow editors to resolve on startup
layoutRestoredPromises.push(
Promise.all([
openEditorsPromise?.finally(() => mark('code/restoreEditors/editorsOpened')),
this.editorGroupService.whenRestored.finally(() => mark('code/restoreEditors/editorGroupsRestored'))
]).finally(() => {
// the `code/didRestoreEditors` perf mark is specifically
// for when visible editors have resolved, so we only mark
// if when editor group service has restored.
mark('code/didRestoreEditors');
})
);
})());
// Restore default views (only when `IDefaultLayout` is provided)
const restoreDefaultViewsPromise = (async () => {
if (this.state.initialization.views.defaults?.length) {
mark('code/willOpenDefaultViews');
const locationsRestored: { id: string; order: number }[] = [];
const tryOpenView = (view: { id: string; order: number }): boolean => {
const location = this.viewDescriptorService.getViewLocationById(view.id);
if (location !== null) {
const container = this.viewDescriptorService.getViewContainerByViewId(view.id);
if (container) {
if (view.order >= (locationsRestored?.[location]?.order ?? 0)) {
locationsRestored[location] = { id: container.id, order: view.order };
}
const containerModel = this.viewDescriptorService.getViewContainerModel(container);
containerModel.setCollapsed(view.id, false);
containerModel.setVisible(view.id, true);
return true;
}
}
return false;
};
const defaultViews = [...this.state.initialization.views.defaults].reverse().map((v, index) => ({ id: v, order: index }));
let i = defaultViews.length;
while (i) {
i--;
if (tryOpenView(defaultViews[i])) {
defaultViews.splice(i, 1);
}