workbench.ts 66.3 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import 'vs/workbench/browser/style';
7

8 9
import { localize } from 'vs/nls';
import { setFileNameComparer } from 'vs/base/common/comparers';
B
Benjamin Pasero 已提交
10
import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';
11 12
import { Event, Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event';
import { EventType, addDisposableListener, addClasses, addClass, removeClass, isAncestor, getClientArea, position, size, removeClasses } from 'vs/base/browser/dom';
13
import { runWhenIdle, IdleValue } from 'vs/base/common/async';
14 15 16
import { getZoomLevel, onDidChangeFullscreen, isFullscreen, getZoomFactor } from 'vs/base/browser/browser';
import { mark } from 'vs/base/common/performance';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
17
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
18
import { Registry } from 'vs/platform/registry/common/platform';
19
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
20
import { IResourceInput } from 'vs/platform/editor/common/editor';
J
Johannes Rieken 已提交
21
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
22
import { IEditorInputFactoryRegistry, Extensions as EditorExtensions, IUntitledResourceInput, IResourceDiffInput } from 'vs/workbench/common/editor';
J
Johannes Rieken 已提交
23
import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart';
24
import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart';
J
Johannes Rieken 已提交
25 26
import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart';
import { StatusbarPart } from 'vs/workbench/browser/parts/statusbar/statusbarPart';
B
Benjamin Pasero 已提交
27
import { TitlebarPart } from 'vs/workbench/browser/parts/titlebar/titlebarPart';
28
import { EditorPart } from 'vs/workbench/browser/parts/editor/editorPart';
29
import { IActionBarRegistry, Extensions as ActionBarExtensions } from 'vs/workbench/browser/actions';
J
Johannes Rieken 已提交
30
import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel';
31
import { ViewletRegistry, Extensions as ViewletExtensions } from 'vs/workbench/browser/viewlet';
J
Johannes Rieken 已提交
32
import { QuickOpenController } from 'vs/workbench/browser/parts/quickopen/quickOpenController';
C
Christof Marti 已提交
33 34
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { QuickInputService } from 'vs/workbench/browser/parts/quickinput/quickInput';
J
Johannes Rieken 已提交
35
import { getServices } from 'vs/platform/instantiation/common/extensions';
B
Benjamin Pasero 已提交
36
import { Position, Parts, IPartService, ILayoutOptions } from 'vs/workbench/services/part/common/partService';
37
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
38
import { IStorageService, StorageScope, IWillSaveStateEvent, WillSaveStateReason } from 'vs/platform/storage/common/storage';
S
SteVen Batten 已提交
39
import { ContextMenuService as HTMLContextMenuService } from 'vs/platform/contextview/browser/contextMenuService';
J
Johannes Rieken 已提交
40 41
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ContextKeyService } from 'vs/platform/contextkey/browser/contextKeyService';
42
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
43
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
I
isidor 已提交
44
import { IActivityService } from 'vs/workbench/services/activity/common/activity';
B
Benjamin Pasero 已提交
45
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
J
Johannes Rieken 已提交
46 47
import { IFileService } from 'vs/platform/files/common/files';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
B
Benjamin Pasero 已提交
48
import { ITitleService } from 'vs/workbench/services/title/common/titleService';
J
Johannes Rieken 已提交
49
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
J
Johannes Rieken 已提交
50 51 52 53
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
B
Benjamin Pasero 已提交
54
import { LifecyclePhase, StartupKind, ILifecycleService, WillShutdownEvent } from 'vs/platform/lifecycle/common/lifecycle';
55
import { IWindowService, IWindowConfiguration, IPath, MenuBarVisibility, getTitleBarStyle, IWindowsService } from 'vs/platform/windows/common/windows';
J
Johannes Rieken 已提交
56
import { IStatusbarService } from 'vs/platform/statusbar/common/statusbar';
S
SteVen Batten 已提交
57
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
J
Johannes Rieken 已提交
58
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
I
isidor 已提交
59
import { ActivityService } from 'vs/workbench/services/activity/browser/activityService';
60
import { IViewsService } from 'vs/workbench/common/views';
S
Sandeep Somavarapu 已提交
61
import { ViewsService } from 'vs/workbench/browser/parts/views/views';
62 63
import { INotificationService } from 'vs/platform/notification/common/notification';
import { NotificationService } from 'vs/workbench/services/notification/common/notificationService';
64 65
import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter';
import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts';
66
import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus';
67
import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
68
import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts';
69
import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';
70
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
71
import { EditorService } from 'vs/workbench/services/editor/browser/editorService';
S
SteVen Batten 已提交
72
import { ContextViewService } from 'vs/platform/contextview/browser/contextViewService';
A
Alex Dima 已提交
73
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
S
SteVen Batten 已提交
74
import { Sizing, Direction, Grid, View } from 'vs/base/browser/ui/grid/grid';
B
Benjamin Pasero 已提交
75
import { WorkbenchLegacyLayout } from 'vs/workbench/browser/legacyLayout';
76 77 78 79 80 81
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { setARIAContainer } from 'vs/base/browser/ui/aria/aria';
import { restoreFontInfo, readFontInfo, saveFontInfo } from 'vs/editor/browser/config/configuration';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
82 83 84
import { ILabelService } from 'vs/platform/label/common/label';
import { LabelService } from 'vs/workbench/services/label/common/labelService';
import { ITelemetryServiceConfig, TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
85
import { combinedAppender, LogAppender, NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
86 87 88 89 90 91 92 93 94 95 96 97 98 99
import { IExtensionGalleryService, IExtensionManagementServerService, IExtensionManagementService, IExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { ExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionEnablementService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { CommandService } from 'vs/workbench/services/commands/common/commandService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { WorkbenchModeServiceImpl } from 'vs/workbench/services/mode/common/workbenchModeService';
import { ITextResourceConfigurationService, ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration';
import { TextResourceConfigurationService } from 'vs/editor/common/services/resourceConfigurationImpl';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { IUntitledEditorService, UntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { ILocalizationsService } from 'vs/platform/localizations/common/localizations';
100
import { HistoryService } from 'vs/workbench/services/history/browser/history';
101
import { WorkbenchThemeService } from 'vs/workbench/services/themes/browser/workbenchThemeService';
102 103
import { IProductService } from 'vs/platform/product/common/product';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
104
import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys';
B
Benjamin Pasero 已提交
105
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
106 107

// import@node
108
import { getDelayedChannel } from 'vs/base/parts/ipc/node/ipc';
109 110 111 112 113 114 115 116 117 118 119 120 121
import { connect as connectNet } from 'vs/base/parts/ipc/node/ipc.net';
import { DialogChannel } from 'vs/platform/dialogs/node/dialogIpc';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/node/telemetryIpc';
import { resolveWorkbenchCommonProperties } from 'vs/platform/telemetry/node/workbenchCommonProperties';
import { IRequestService } from 'vs/platform/request/node/request';
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/node/remoteAgentService';
import { DownloadServiceChannel } from 'vs/platform/download/node/downloadIpc';
import { LogLevelSetterChannel } from 'vs/platform/log/node/logIpc';
import { ExtensionManagementChannelClient } from 'vs/platform/extensionManagement/node/extensionManagementIpc';
import { ExtensionManagementServerService } from 'vs/workbench/services/extensions/node/extensionManagementServerService';
import { MultiExtensionManagementService } from 'vs/workbench/services/extensionManagement/node/multiExtensionManagement';
import { LocalizationsChannelClient } from 'vs/platform/localizations/node/localizationsIpc';
122 123
import { AccessibilityService } from 'vs/platform/accessibility/node/accessibilityService';
import { ProductService } from 'vs/platform/product/node/productService';
B
Benjamin Pasero 已提交
124
import { TextResourcePropertiesService } from 'vs/workbench/services/textfile/node/textResourcePropertiesService';
125
import { RemoteFileService } from 'vs/workbench/services/files/node/remoteFileService';
126 127

// import@electron-browser
128
import { ContextMenuService as NativeContextMenuService } from 'vs/workbench/services/contextmenu/electron-browser/contextmenuService';
129 130 131 132 133 134
import { WorkbenchKeybindingService } from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
import { LifecycleService } from 'vs/platform/lifecycle/electron-browser/lifecycleService';
import { WindowService } from 'vs/platform/windows/electron-browser/windowService';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-browser/remoteAuthorityResolverService';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-browser/remoteAgentServiceImpl';
import { ExtensionService } from 'vs/workbench/services/extensions/electron-browser/extensionService';
B
Benjamin Pasero 已提交
135
import { RequestService } from 'vs/platform/request/electron-browser/requestService';
136

137 138 139 140 141 142 143
enum Identifiers {
	TITLEBAR_PART = 'workbench.parts.titlebar',
	ACTIVITYBAR_PART = 'workbench.parts.activitybar',
	SIDEBAR_PART = 'workbench.parts.sidebar',
	PANEL_PART = 'workbench.parts.panel',
	EDITOR_PART = 'workbench.parts.editor',
	STATUSBAR_PART = 'workbench.parts.statusbar'
I
isidor 已提交
144 145
}

146 147 148 149 150 151 152 153 154 155
enum Settings {
	MENUBAR_VISIBLE = 'window.menuBarVisibility',
	ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible',
	STATUSBAR_VISIBLE = 'workbench.statusBar.visible',

	SIDEBAR_POSITION = 'workbench.sideBar.location',
	PANEL_POSITION = 'workbench.panel.defaultLocation',

	FONT_ALIASING = 'workbench.fontAliasing',
	ZEN_MODE_RESTORE = 'zenMode.restore'
156
}
157

158
enum Storage {
159 160 161 162
	SIDEBAR_HIDDEN = 'workbench.sidebar.hidden',

	PANEL_HIDDEN = 'workbench.panel.hidden',
	PANEL_POSITION = 'workbench.panel.location',
163

164 165
	ZEN_MODE_ENABLED = 'workbench.zenmode.active',
	CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active',
166 167
}

168
export class Workbench extends Disposable implements IPartService {
E
Erich Gamma 已提交
169

B
Benjamin Pasero 已提交
170 171
	//#region workbench

B
Benjamin Pasero 已提交
172 173
	_serviceBrand: any;

B
Benjamin Pasero 已提交
174 175 176 177 178 179
	private readonly _onShutdown = this._register(new Emitter<void>());
	get onShutdown(): Event<void> { return this._onShutdown.event; }

	private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>());
	get onWillShutdown(): Event<WillShutdownEvent> { return this._onWillShutdown.event; }

180
	private previousErrorValue: string;
181
	private previousErrorTime = 0;
182

B
Benjamin Pasero 已提交
183
	private workbench: HTMLElement;
184 185 186

	private restored: boolean;
	private disposed: boolean;
187

188 189
	private editorService: EditorService;
	private editorGroupService: IEditorGroupsService;
B
Benjamin Pasero 已提交
190

B
Benjamin Pasero 已提交
191 192 193
	private instantiationService: IInstantiationService;
	private contextService: IWorkspaceContextService;
	private storageService: IStorageService;
B
Benjamin Pasero 已提交
194
	private configurationService: IConfigurationService;
B
Benjamin Pasero 已提交
195 196 197
	private environmentService: IEnvironmentService;
	private logService: ILogService;
	private windowsService: IWindowsService;
198

B
Benjamin Pasero 已提交
199
	private titlebarPart: TitlebarPart;
E
Erich Gamma 已提交
200 201
	private activitybarPart: ActivitybarPart;
	private sidebarPart: SidebarPart;
I
isidor 已提交
202
	private panelPart: PanelPart;
E
Erich Gamma 已提交
203 204
	private editorPart: EditorPart;
	private statusbarPart: StatusbarPart;
S
SteVen Batten 已提交
205

E
Erich Gamma 已提交
206
	private quickOpen: QuickOpenController;
207 208
	private quickInput: QuickInputService;

209
	private notificationsCenter: NotificationsCenter;
210
	private notificationsToasts: NotificationsToasts;
211

212
	constructor(
213
		private container: HTMLElement,
J
Joao Moreno 已提交
214
		private configuration: IWindowConfiguration,
B
Benjamin Pasero 已提交
215
		private serviceCollection: ServiceCollection,
B
Benjamin Pasero 已提交
216 217 218
		@IInstantiationService instantiationService: IInstantiationService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IStorageService storageService: IStorageService,
B
Benjamin Pasero 已提交
219
		@IConfigurationService configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
220 221 222
		@IEnvironmentService environmentService: IEnvironmentService,
		@ILogService logService: ILogService,
		@IWindowsService windowsService: IWindowsService
223
	) {
224
		super();
E
Erich Gamma 已提交
225

B
Benjamin Pasero 已提交
226 227 228 229 230 231 232 233
		this.instantiationService = instantiationService;
		this.contextService = contextService;
		this.storageService = storageService;
		this.configurationService = configurationService;
		this.environmentService = environmentService;
		this.logService = logService;
		this.windowsService = windowsService;

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
		this.registerErrorHandler();
	}

	private registerErrorHandler(): void {

		// Listen on unhandled rejection events
		window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {

			// See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
			onUnexpectedError(event.reason);

			// Prevent the printing of this event to the console
			event.preventDefault();
		});

		// Install handler for unexpected errors
		setUnexpectedErrorHandler(error => this.handleUnexpectedError(error));
251 252 253 254 255 256 257 258 259

		// Inform user about loading issues from the loader
		(<any>self).require.config({
			onError: err => {
				if (err.errorCode === 'load') {
					onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
				}
			}
		});
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
	}

	private handleUnexpectedError(error: any): void {
		const errorMsg = toErrorMessage(error, true);
		if (!errorMsg) {
			return;
		}

		const now = Date.now();
		if (errorMsg === this.previousErrorValue && now - this.previousErrorTime <= 1000) {
			return; // Return if error message identical to previous and shorter than 1 second
		}

		this.previousErrorTime = now;
		this.previousErrorValue = errorMsg;

		// Log it
		this.logService.error(errorMsg);
	}

280
	startup(): void {
281
		try {
282
			this.doStartup().then(undefined, error => this.logService.error(toErrorMessage(error, true)));
283 284 285 286 287
		} catch (error) {
			this.logService.error(toErrorMessage(error, true));

			throw error; // rethrow because this is a critical issue we cannot handle properly here
		}
288 289
	}

290
	private doStartup(): Promise<void> {
E
Erich Gamma 已提交
291

B
Benjamin Pasero 已提交
292 293 294
		// Logging
		this.logService.trace('workbench configuration', JSON.stringify(this.configuration));

295 296 297 298 299 300 301 302 303 304 305 306
		// Configure emitter leak warning threshold
		setGlobalLeakWarningThreshold(175);

		// Setup Intl for comparers
		setFileNameComparer(new IdleValue(() => {
			const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
			return {
				collator: collator,
				collatorIsNumeric: collator.resolvedOptions().numeric
			};
		}));

307 308 309 310 311 312 313
		// ARIA
		setARIAContainer(document.body);

		// Warm up font cache information before building up too many dom elements
		restoreFontInfo(this.storageService);
		readFontInfo(BareFontInfo.createFromRawSettings(this.configurationService.getValue('editor'), getZoomLevel()));

B
Benjamin Pasero 已提交
314
		// Create Workbench Container
B
Benjamin Pasero 已提交
315
		this.createWorkbenchContainer();
E
Erich Gamma 已提交
316

317
		// Services
B
Benjamin Pasero 已提交
318
		this.initServices(this.serviceCollection);
E
Erich Gamma 已提交
319

B
Benjamin Pasero 已提交
320 321 322
		// Registries
		this.startRegistries();

323
		// Context Keys
324
		this._register(this.instantiationService.createInstance(WorkbenchContextKeysHandler));
J
Joao Moreno 已提交
325

326
		// Register Listeners
B
Benjamin Pasero 已提交
327 328 329 330
		this.instantiationService.invokeFunction(accessor => {
			this.registerListeners(accessor);
			this.registerLayoutListeners(accessor);
		});
E
Erich Gamma 已提交
331

332
		// Layout State
B
Benjamin Pasero 已提交
333
		this.instantiationService.invokeFunction(accessor => this.initLayoutState(accessor));
E
Erich Gamma 已提交
334

335
		// Render Workbench
336
		this.renderWorkbench();
337

338 339
		// Workbench Layout
		this.createWorkbenchLayout();
B
polish  
Benjamin Pasero 已提交
340

341 342 343
		// Layout
		this.layout();

B
Benjamin Pasero 已提交
344 345
		// Restore
		return this.restoreWorkbench();
B
Benjamin Pasero 已提交
346
	}
347

B
Benjamin Pasero 已提交
348
	private createWorkbenchContainer(): void {
B
Benjamin Pasero 已提交
349
		this.workbench = document.createElement('div');
350

351 352 353 354
		const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac';

		addClasses(this.workbench, 'monaco-workbench', platformClass);
		addClasses(document.body, platformClass); // used by our fonts
355
	}
E
Erich Gamma 已提交
356

B
Benjamin Pasero 已提交
357
	private initServices(serviceCollection: ServiceCollection): void {
358

359
		// Parts
B
Benjamin Pasero 已提交
360
		serviceCollection.set(IPartService, this); // TODO@Ben use SyncDescriptor
E
Erich Gamma 已提交
361

362 363 364 365
		// Labels
		serviceCollection.set(ILabelService, new SyncDescriptor(LabelService, undefined, true));

		// Notifications
366
		serviceCollection.set(INotificationService, new SyncDescriptor(NotificationService, undefined, true));
367 368

		// Window
B
Benjamin Pasero 已提交
369
		serviceCollection.set(IWindowService, new SyncDescriptor(WindowService, [this.configuration]));
370

371 372
		// Product
		const productService = new ProductService();
B
Benjamin Pasero 已提交
373
		serviceCollection.set(IProductService, productService); // TODO@Ben use SyncDescriptor
374

375 376 377 378 379 380 381 382 383 384
		// Shared Process
		const sharedProcess = this.windowsService.whenSharedProcessReady()
			.then(() => connectNet(this.environmentService.sharedIPCHandle, `window:${this.configuration.windowId}`))
			.then(client => {
				client.registerChannel('dialog', this.instantiationService.createInstance(DialogChannel));

				return client;
			});

		// Telemetry
B
Benjamin Pasero 已提交
385
		let telemetryService: ITelemetryService;
386
		if (!this.environmentService.isExtensionDevelopment && !this.environmentService.args['disable-telemetry'] && !!productService.enableTelemetry) {
387 388 389
			const channel = getDelayedChannel(sharedProcess.then(c => c.getChannel('telemetryAppender')));
			const config: ITelemetryServiceConfig = {
				appender: combinedAppender(new TelemetryAppenderClient(channel), new LogAppender(this.logService)),
390
				commonProperties: resolveWorkbenchCommonProperties(this.storageService, productService.commit, productService.version, this.configuration.machineId, this.environmentService.installSourcePath),
391 392 393
				piiPaths: [this.environmentService.appRoot, this.environmentService.extensionsPath]
			};

B
Benjamin Pasero 已提交
394
			telemetryService = this._register(this.instantiationService.createInstance(TelemetryService, config));
395
		} else {
B
Benjamin Pasero 已提交
396
			telemetryService = NullTelemetryService;
397 398
		}

B
Benjamin Pasero 已提交
399
		serviceCollection.set(ITelemetryService, telemetryService); // TODO@Ben use SyncDescriptor
400 401

		// Lifecycle
B
Benjamin Pasero 已提交
402
		serviceCollection.set(ILifecycleService, new SyncDescriptor(LifecycleService));
403 404 405 406 407 408 409 410

		// Request Service
		serviceCollection.set(IRequestService, new SyncDescriptor(RequestService, undefined, true));

		// Extension Gallery
		serviceCollection.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService, undefined, true));

		// Remote Resolver
B
Benjamin Pasero 已提交
411
		serviceCollection.set(IRemoteAuthorityResolverService, new SyncDescriptor(RemoteAuthorityResolverService, undefined, true));
412 413

		// Remote Agent
B
Benjamin Pasero 已提交
414
		serviceCollection.set(IRemoteAgentService, new SyncDescriptor(RemoteAgentService, [this.configuration]));
415 416 417 418 419 420 421 422

		// Extensions Management
		const extensionManagementChannel = getDelayedChannel(sharedProcess.then(c => c.getChannel('extensions')));
		const extensionManagementChannelClient = new ExtensionManagementChannelClient(extensionManagementChannel);
		serviceCollection.set(IExtensionManagementServerService, new SyncDescriptor(ExtensionManagementServerService, [extensionManagementChannelClient]));
		serviceCollection.set(IExtensionManagementService, new SyncDescriptor(MultiExtensionManagementService));

		// Extension Enablement
423
		serviceCollection.set(IExtensionEnablementService, new SyncDescriptor(ExtensionEnablementService, undefined, true));
424 425

		// Extensions
426
		serviceCollection.set(IExtensionService, new SyncDescriptor(ExtensionService));
427 428

		// Theming
B
Benjamin Pasero 已提交
429
		serviceCollection.set(IWorkbenchThemeService, new SyncDescriptor(WorkbenchThemeService, [document.body]));
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

		// Commands
		serviceCollection.set(ICommandService, new SyncDescriptor(CommandService, undefined, true));

		// Editor Mode
		serviceCollection.set(IModeService, new SyncDescriptor(WorkbenchModeServiceImpl));

		// Text Resource Config
		serviceCollection.set(ITextResourceConfigurationService, new SyncDescriptor(TextResourceConfigurationService));

		// Text Resource Properties
		serviceCollection.set(ITextResourcePropertiesService, new SyncDescriptor(TextResourcePropertiesService));

		// Editor Models
		serviceCollection.set(IModelService, new SyncDescriptor(ModelServiceImpl, undefined, true));

		// Untitled Editors
		serviceCollection.set(IUntitledEditorService, new SyncDescriptor(UntitledEditorService, undefined, true));

		// Localization
		const localizationsChannel = getDelayedChannel(sharedProcess.then(c => c.getChannel('localizations')));
		serviceCollection.set(ILocalizationsService, new SyncDescriptor(LocalizationsChannelClient, [localizationsChannel]));

453 454
		// Status bar
		this.statusbarPart = this.instantiationService.createInstance(StatusbarPart, Identifiers.STATUSBAR_PART);
B
Benjamin Pasero 已提交
455
		serviceCollection.set(IStatusbarService, this.statusbarPart); // TODO@Ben use SyncDescriptor
456

457
		// Context Keys
458
		serviceCollection.set(IContextKeyService, new SyncDescriptor(ContextKeyService));
459

460
		// Keybindings
B
Benjamin Pasero 已提交
461
		serviceCollection.set(IKeybindingService, new SyncDescriptor(WorkbenchKeybindingService, [window]));
A
Alex Dima 已提交
462

J
Joao Moreno 已提交
463
		// Context view service
B
Benjamin Pasero 已提交
464
		serviceCollection.set(IContextViewService, new SyncDescriptor(ContextViewService, [this.workbench], true));
J
Joao Moreno 已提交
465

S
SteVen Batten 已提交
466
		// Use themable context menus when custom titlebar is enabled to match custom menubar
467
		if (!isMacintosh && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') {
J
fix npe  
Johannes Rieken 已提交
468
			serviceCollection.set(IContextMenuService, new SyncDescriptor(HTMLContextMenuService, [null]));
S
SteVen Batten 已提交
469 470 471
		} else {
			serviceCollection.set(IContextMenuService, new SyncDescriptor(NativeContextMenuService));
		}
472

B
Benjamin Pasero 已提交
473
		// Viewlet service (sidebar part)
474
		this.sidebarPart = this.instantiationService.createInstance(SidebarPart, Identifiers.SIDEBAR_PART);
B
Benjamin Pasero 已提交
475
		serviceCollection.set(IViewletService, this.sidebarPart); // TODO@Ben use SyncDescriptor
E
Erich Gamma 已提交
476

I
isidor 已提交
477
		// Panel service (panel part)
478
		this.panelPart = this.instantiationService.createInstance(PanelPart, Identifiers.PANEL_PART);
B
Benjamin Pasero 已提交
479
		serviceCollection.set(IPanelService, this.panelPart); // TODO@Ben use SyncDescriptor
I
isidor 已提交
480

481 482
		// Views service
		serviceCollection.set(IViewsService, new SyncDescriptor(ViewsService));
S
Sandeep Somavarapu 已提交
483

E
Erich Gamma 已提交
484
		// Activity service (activitybar part)
485
		this.activitybarPart = this.instantiationService.createInstance(ActivitybarPart, Identifiers.ACTIVITYBAR_PART);
486
		serviceCollection.set(IActivityService, new SyncDescriptor(ActivityService, [this.activitybarPart, this.panelPart], true));
E
Erich Gamma 已提交
487

488
		// File Service
B
Benjamin Pasero 已提交
489
		serviceCollection.set(IFileService, new SyncDescriptor(RemoteFileService));
490

491
		// Editor and Group services
492
		this.editorPart = this.instantiationService.createInstance(EditorPart, Identifiers.EDITOR_PART, !this.hasInitialFilesToOpen());
B
Benjamin Pasero 已提交
493
		this.editorGroupService = this.editorPart;
B
Benjamin Pasero 已提交
494
		serviceCollection.set(IEditorGroupsService, this.editorPart); // TODO@Ben use SyncDescriptor
495
		this.editorService = this.instantiationService.createInstance(EditorService);
B
Benjamin Pasero 已提交
496
		serviceCollection.set(IEditorService, this.editorService); // TODO@Ben use SyncDescriptor
E
Erich Gamma 已提交
497

498 499 500
		// Accessibility
		serviceCollection.set(IAccessibilityService, new SyncDescriptor(AccessibilityService, undefined, true));

501 502
		// Title bar
		this.titlebarPart = this.instantiationService.createInstance(TitlebarPart, Identifiers.TITLEBAR_PART);
B
Benjamin Pasero 已提交
503
		serviceCollection.set(ITitleService, this.titlebarPart); // TODO@Ben use SyncDescriptor
B
Benjamin Pasero 已提交
504

505
		// History
506
		serviceCollection.set(IHistoryService, new SyncDescriptor(HistoryService));
507

E
Erich Gamma 已提交
508
		// Quick open service (quick open controller)
509
		this.quickOpen = this.instantiationService.createInstance(QuickOpenController);
B
Benjamin Pasero 已提交
510
		serviceCollection.set(IQuickOpenService, this.quickOpen); // TODO@Ben use SyncDescriptor
511

C
Christof Marti 已提交
512 513
		// Quick input service
		this.quickInput = this.instantiationService.createInstance(QuickInputService);
B
Benjamin Pasero 已提交
514
		serviceCollection.set(IQuickInputService, this.quickInput); // TODO@Ben use SyncDescriptor
C
Christof Marti 已提交
515

B
polish  
Benjamin Pasero 已提交
516
		// Contributed services
B
Benjamin Pasero 已提交
517
		const contributedServices = getServices();
E
Erich Gamma 已提交
518
		for (let contributedService of contributedServices) {
519
			serviceCollection.set(contributedService.id, contributedService.descriptor);
E
Erich Gamma 已提交
520 521
		}

B
Benjamin Pasero 已提交
522
		// TODO@Alex TODO@Sandeep this should move somewhere else
B
Benjamin Pasero 已提交
523 524 525 526 527 528 529 530
		this.instantiationService.invokeFunction(accessor => {
			const remoteAgentConnection = accessor.get(IRemoteAgentService).getConnection();
			if (remoteAgentConnection) {
				remoteAgentConnection.registerChannel('dialog', this.instantiationService.createInstance(DialogChannel));
				remoteAgentConnection.registerChannel('download', new DownloadServiceChannel());
				remoteAgentConnection.registerChannel('loglevel', new LogLevelSetterChannel(this.logService));
			}
		});
531

B
Benjamin Pasero 已提交
532 533 534 535
		// TODO@Sandeep TODO@Martin debt around cyclic dependencies
		this.instantiationService.invokeFunction(accessor => {
			const fileService = accessor.get(IFileService);
			const instantiationService = accessor.get(IInstantiationService);
B
Benjamin Pasero 已提交
536 537
			const configurationService = accessor.get(IConfigurationService) as any;
			const themeService = accessor.get(IWorkbenchThemeService) as any;
B
Benjamin Pasero 已提交
538

B
Benjamin Pasero 已提交
539 540 541 542 543 544 545
			if (typeof configurationService.acquireFileService === 'function') {
				configurationService.acquireFileService(fileService);
			}

			if (typeof configurationService.acquireInstantiationService === 'function') {
				configurationService.acquireInstantiationService(instantiationService);
			}
B
Benjamin Pasero 已提交
546

B
Benjamin Pasero 已提交
547 548 549
			if (typeof themeService.acquireFileService === 'function') {
				themeService.acquireFileService(fileService);
			}
B
Benjamin Pasero 已提交
550
		});
E
Erich Gamma 已提交
551 552
	}

B
Benjamin Pasero 已提交
553 554 555 556 557 558 559 560
	private startRegistries(): void {
		this.instantiationService.invokeFunction(accessor => {
			Registry.as<IActionBarRegistry>(ActionBarExtensions.Actionbar).start(accessor);
			Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor);
			Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor);
		});
	}

561 562 563 564 565 566 567
	private hasInitialFilesToOpen(): boolean {
		return !!(
			(this.configuration.filesToCreate && this.configuration.filesToCreate.length > 0) ||
			(this.configuration.filesToOpen && this.configuration.filesToOpen.length > 0) ||
			(this.configuration.filesToDiff && this.configuration.filesToDiff.length > 0));
	}

B
Benjamin Pasero 已提交
568 569 570 571 572 573 574 575 576 577 578
	private registerListeners(accessor: ServicesAccessor): void {
		const lifecycleService = accessor.get(ILifecycleService);
		const storageService = accessor.get(IStorageService);
		const configurationService = accessor.get(IConfigurationService);

		// Lifecycle
		this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event)));
		this._register(lifecycleService.onShutdown(() => {
			this._onShutdown.fire();
			this.dispose();
		}));
I
isidor 已提交
579

580
		// Storage
B
Benjamin Pasero 已提交
581
		this._register(storageService.onWillSaveState(e => this.saveState(e)));
582

583
		// Configuration changes
B
Benjamin Pasero 已提交
584
		this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing()));
585 586
	}

B
Benjamin Pasero 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
	private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto';
	private setFontAliasing() {
		const aliasing = this.configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>(Settings.FONT_ALIASING);
		if (this.fontAliasing === aliasing) {
			return;
		}

		this.fontAliasing = aliasing;

		// Remove all
		const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto'];
		removeClasses(this.workbench, ...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`));

		// Add specific
		if (fontAliasingValues.some(option => option === aliasing)) {
			addClass(this.workbench, `monaco-font-aliasing-${aliasing}`);
		}
	}

E
Erich Gamma 已提交
606
	private renderWorkbench(): void {
607
		if (this.state.sideBar.hidden) {
608
			addClass(this.workbench, 'nosidebar');
E
Erich Gamma 已提交
609
		}
B
Benjamin Pasero 已提交
610

611
		if (this.state.panel.hidden) {
612
			addClass(this.workbench, 'nopanel');
613
		}
B
Benjamin Pasero 已提交
614

615
		if (this.state.statusBar.hidden) {
616
			addClass(this.workbench, 'nostatusbar');
617
		}
E
Erich Gamma 已提交
618

619
		if (this.state.fullscreen) {
620
			addClass(this.workbench, 'fullscreen');
B
Benjamin Pasero 已提交
621 622
		}

623 624 625
		// Apply font aliasing
		this.setFontAliasing();

E
Erich Gamma 已提交
626
		// Create Parts
B
Benjamin Pasero 已提交
627
		this.createTitlebarPart();
E
Erich Gamma 已提交
628 629 630
		this.createActivityBarPart();
		this.createSidebarPart();
		this.createEditorPart();
631
		this.createPanelPart();
E
Erich Gamma 已提交
632 633
		this.createStatusbarPart();

634
		// Notification Handlers
635
		this.instantiationService.invokeFunction(accessor => this.createNotificationsHandlers(accessor));
636

637 638 639
		// Add Workbench to DOM
		this.container.appendChild(this.workbench);
	}
640

B
Benjamin Pasero 已提交
641
	private createTitlebarPart(): void {
642
		const titlebarContainer = this.createPart(Identifiers.TITLEBAR_PART, 'contentinfo', 'titlebar');
B
Benjamin Pasero 已提交
643

B
Benjamin Pasero 已提交
644
		this.titlebarPart.create(titlebarContainer);
B
Benjamin Pasero 已提交
645 646
	}

E
Erich Gamma 已提交
647
	private createActivityBarPart(): void {
648
		const activitybarPartContainer = this.createPart(Identifiers.ACTIVITYBAR_PART, 'navigation', 'activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right');
E
Erich Gamma 已提交
649

B
Benjamin Pasero 已提交
650
		this.activitybarPart.create(activitybarPartContainer);
E
Erich Gamma 已提交
651 652 653
	}

	private createSidebarPart(): void {
654
		const sidebarPartContainer = this.createPart(Identifiers.SIDEBAR_PART, 'complementary', 'sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right');
E
Erich Gamma 已提交
655

B
Benjamin Pasero 已提交
656
		this.sidebarPart.create(sidebarPartContainer);
E
Erich Gamma 已提交
657 658
	}

I
isidor 已提交
659
	private createPanelPart(): void {
660
		const panelPartContainer = this.createPart(Identifiers.PANEL_PART, 'complementary', 'panel', this.state.panel.position === Position.BOTTOM ? 'bottom' : 'right');
I
isidor 已提交
661

B
Benjamin Pasero 已提交
662
		this.panelPart.create(panelPartContainer);
I
isidor 已提交
663 664
	}

E
Erich Gamma 已提交
665
	private createEditorPart(): void {
666
		const editorContainer = this.createPart(Identifiers.EDITOR_PART, 'main', 'editor');
E
Erich Gamma 已提交
667

B
Benjamin Pasero 已提交
668
		this.editorPart.create(editorContainer);
E
Erich Gamma 已提交
669 670 671
	}

	private createStatusbarPart(): void {
672
		const statusbarContainer = this.createPart(Identifiers.STATUSBAR_PART, 'contentinfo', 'statusbar');
B
Benjamin Pasero 已提交
673 674 675 676

		this.statusbarPart.create(statusbarContainer);
	}

677
	private createPart(id: string, role: string, ...classes: string[]): HTMLElement {
B
Benjamin Pasero 已提交
678
		const part = document.createElement('div');
679
		addClasses(part, 'part', ...classes);
B
Benjamin Pasero 已提交
680 681 682
		part.id = id;
		part.setAttribute('role', role);

683 684 685 686 687
		if (!this.configurationService.getValue('workbench.useExperimentalGridLayout')) {
			// Insert all workbench parts at the beginning. Issue #52531
			// This is primarily for the title bar to allow overriding -webkit-app-region
			this.workbench.insertBefore(part, this.workbench.lastChild);
		}
E
Erich Gamma 已提交
688

B
Benjamin Pasero 已提交
689
		return part;
E
Erich Gamma 已提交
690 691
	}

692 693
	private createNotificationsHandlers(accessor: ServicesAccessor): void {
		const notificationService = accessor.get(INotificationService) as NotificationService;
694

695
		// Notifications Center
696
		this.notificationsCenter = this._register(this.instantiationService.createInstance(NotificationsCenter, this.workbench, notificationService.model));
697

698
		// Notifications Toasts
699
		this.notificationsToasts = this._register(this.instantiationService.createInstance(NotificationsToasts, this.workbench, notificationService.model));
700

701
		// Notifications Alerts
702
		this._register(this.instantiationService.createInstance(NotificationsAlerts, notificationService.model));
703 704

		// Notifications Status
705
		const notificationsStatus = this.instantiationService.createInstance(NotificationsStatus, notificationService.model);
706

707
		// Eventing
708
		this._register(this.notificationsCenter.onDidChangeVisibility(() => {
709 710 711 712 713 714 715 716

			// Update status
			notificationsStatus.update(this.notificationsCenter.isVisible);

			// Update toasts
			this.notificationsToasts.update(this.notificationsCenter.isVisible);
		}));

717
		// Register Commands
718
		registerNotificationCommands(this.notificationsCenter, this.notificationsToasts);
719 720
	}

B
Benjamin Pasero 已提交
721
	private restoreWorkbench(): Promise<void> {
B
Benjamin Pasero 已提交
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
		const restorePromises: Promise<any>[] = [];

		// Restore editors
		mark('willRestoreEditors');
		restorePromises.push(this.editorPart.whenRestored.then(() => {

			function openEditors(editors: IResourceEditor[], editorService: IEditorService) {
				if (editors.length) {
					return editorService.openEditors(editors);
				}

				return Promise.resolve(undefined);
			}

			if (Array.isArray(this.state.editor.editorsToOpen)) {
				return openEditors(this.state.editor.editorsToOpen, this.editorService);
			}

			return this.state.editor.editorsToOpen.then(editors => openEditors(editors, this.editorService));
		}).then(() => mark('didRestoreEditors')));

		// Restore Sidebar
		if (this.state.sideBar.viewletToRestore) {
			mark('willRestoreViewlet');
			restorePromises.push(this.sidebarPart.openViewlet(this.state.sideBar.viewletToRestore)
B
Benjamin Pasero 已提交
747 748 749 750 751 752 753
				.then(viewlet => {
					if (!viewlet) {
						return this.sidebarPart.openViewlet(this.sidebarPart.getDefaultViewletId()); // fallback to default viewlet as needed
					}

					return viewlet;
				})
B
Benjamin Pasero 已提交
754 755 756 757 758 759
				.then(() => mark('didRestoreViewlet')));
		}

		// Restore Panel
		if (this.state.panel.panelToRestore) {
			mark('willRestorePanel');
B
Benjamin Pasero 已提交
760
			this.panelPart.openPanel(this.state.panel.panelToRestore);
B
Benjamin Pasero 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773
			mark('didRestorePanel');
		}

		// Restore Zen Mode
		if (this.state.zenMode.restore) {
			this.toggleZenMode(true, true);
		}

		// Restore Editor Center Mode
		if (this.state.editor.restoreCentered) {
			this.centerEditorLayout(true);
		}

774 775 776
		// Emit a warning after 10s if restore does not complete
		const restoreTimeoutHandle = setTimeout(() => this.logService.warn('Workbench did not finish loading in 10 seconds, that might be a problem that should be reported.'), 10000);

B
Benjamin Pasero 已提交
777 778 779 780 781 782
		let error: Error;
		return Promise.all(restorePromises)
			.then(() => clearTimeout(restoreTimeoutHandle))
			.catch(err => error = err)
			.finally(() => this.instantiationService.invokeFunction(accessor => this.whenRestored(accessor, error)));

B
Benjamin Pasero 已提交
783 784
	}

B
Benjamin Pasero 已提交
785
	private whenRestored(accessor: ServicesAccessor, error?: Error): void {
B
Benjamin Pasero 已提交
786
		const lifecycleService = accessor.get(ILifecycleService);
B
Benjamin Pasero 已提交
787

B
Benjamin Pasero 已提交
788 789 790
		this.restored = true;

		// Set lifecycle phase to `Restored`
B
Benjamin Pasero 已提交
791
		lifecycleService.phase = LifecyclePhase.Restored;
B
Benjamin Pasero 已提交
792 793 794 795 796

		// Set lifecycle phase to `Eventually` after a short delay and when
		// idle (min 2.5sec, max 5sec)
		setTimeout(() => {
			this._register(runWhenIdle(() => {
B
Benjamin Pasero 已提交
797
				lifecycleService.phase = LifecyclePhase.Eventually;
B
Benjamin Pasero 已提交
798 799 800 801 802 803 804 805 806 807 808
			}, 2500));
		}, 2500);

		if (error) {
			onUnexpectedError(error);
		}

		// Telemetry: startup metrics
		mark('didStartWorkbench');
	}

809
	private saveState(e: IWillSaveStateEvent): void {
810 811 812

		// Font info
		saveFontInfo(this.storageService);
813 814
	}

815
	dispose(): void {
816
		super.dispose();
817

818
		this.disposed = true;
819 820
	}

B
Benjamin Pasero 已提交
821 822
	//#endregion

823 824
	//#region IPartService

M
Matt Bierner 已提交
825
	private readonly _onTitleBarVisibilityChange: Emitter<void> = this._register(new Emitter<void>());
826
	get onTitleBarVisibilityChange(): Event<void> { return this._onTitleBarVisibilityChange.event; }
827

828 829 830
	private readonly _onZenMode: Emitter<boolean> = this._register(new Emitter<boolean>());
	get onZenModeChange(): Event<boolean> { return this._onZenMode.event; }

B
Benjamin Pasero 已提交
831
	private workbenchGrid: Grid<View> | WorkbenchLegacyLayout;
832 833 834 835 836 837 838 839

	private titleBarPartView: View;
	private activityBarPartView: View;
	private sideBarPartView: View;
	private panelPartView: View;
	private editorPartView: View;
	private statusBarPartView: View;

B
Benjamin Pasero 已提交
840 841 842
	private contextViewService: IContextViewService;
	private windowService: IWindowService;

843 844 845
	private readonly state = {
		fullscreen: false,

846 847 848 849 850 851 852 853 854 855 856 857
		menuBar: {
			visibility: undefined as MenuBarVisibility,
			toggled: false
		},

		activityBar: {
			hidden: false
		},

		sideBar: {
			hidden: false,
			position: undefined as Position,
858 859
			width: 300,
			viewletToRestore: undefined as string
860 861 862 863
		},

		editor: {
			hidden: false,
864 865 866
			centered: false,
			restoreCentered: false,
			editorsToOpen: undefined as Promise<IResourceEditor[]> | IResourceEditor[]
867 868 869 870 871 872
		},

		panel: {
			hidden: false,
			position: undefined as Position,
			height: 350,
873 874
			width: 350,
			panelToRestore: undefined as string
875 876 877 878 879 880 881 882
		},

		statusBar: {
			hidden: false
		},

		zenMode: {
			active: false,
883
			restore: false,
884 885 886 887 888 889 890 891
			transitionedToFullScreen: false,
			transitionedToCenteredEditorLayout: false,
			wasSideBarVisible: false,
			wasPanelVisible: false,
			transitionDisposeables: [] as IDisposable[]
		}
	};

B
Benjamin Pasero 已提交
892 893 894 895 896 897 898
	private registerLayoutListeners(accessor: ServicesAccessor): void {
		const storageService = accessor.get(IStorageService);
		const editorService = accessor.get(IEditorService);
		const configurationService = accessor.get(IConfigurationService);
		const editorGroupService = accessor.get(IEditorGroupsService);
		const titleService = accessor.get(ITitleService);
		const environmentService = accessor.get(IEnvironmentService);
899 900

		// Storage
B
Benjamin Pasero 已提交
901
		this._register(storageService.onWillSaveState(e => this.saveLayoutState(e)));
902 903

		// Restore editor if hidden and it changes
B
Benjamin Pasero 已提交
904 905
		this._register(editorService.onDidVisibleEditorsChange(() => this.setEditorHidden(false)));
		this._register(editorGroupService.onDidActivateGroup(() => this.setEditorHidden(false)));
906 907

		// Configuration changes
B
Benjamin Pasero 已提交
908
		this._register(configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration()));
909 910 911 912 913

		// Fullscreen changes
		this._register(onDidChangeFullscreen(() => this.onFullscreenChanged()));

		// Group changes
B
Benjamin Pasero 已提交
914 915
		this._register(editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered)));
		this._register(editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered)));
916 917 918 919 920

		// Prevent workbench from scrolling #55456
		this._register(addDisposableListener(this.workbench, EventType.SCROLL, () => this.workbench.scrollTop = 0));

		// Menubar visibility changes
B
Benjamin Pasero 已提交
921 922
		if ((isWindows || isLinux) && getTitleBarStyle(configurationService, environmentService) === 'custom') {
			this._register(titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible)));
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
		}
	}

	private onMenubarToggled(visible: boolean) {
		if (visible !== this.state.menuBar.toggled) {
			this.state.menuBar.toggled = visible;

			if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) {
				this._onTitleBarVisibilityChange.fire();
				this.layout();
			}
		}
	}

	private onFullscreenChanged(): void {
		this.state.fullscreen = isFullscreen();

		// Apply as CSS class
		if (this.state.fullscreen) {
			addClass(this.workbench, 'fullscreen');
		} else {
			removeClass(this.workbench, 'fullscreen');

			if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) {
				this.toggleZenMode();
			}
		}

		// Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update
		if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') {
			this._onTitleBarVisibilityChange.fire();
			this.layout(); // handle title bar when fullscreen changes
		}
	}

	private doUpdateLayoutConfiguration(skipLayout?: boolean): void {
959

B
Benjamin Pasero 已提交
960
		// Sidebar position
961 962 963 964 965 966
		const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION);
		const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT;
		if (newSidebarPosition !== this.getSideBarPosition()) {
			this.setSideBarPosition(newSidebarPosition);
		}

B
Benjamin Pasero 已提交
967 968
		// Panel position
		this.updatePanelPosition();
969 970 971

		if (!this.state.zenMode.active) {

B
Benjamin Pasero 已提交
972
			// Statusbar visibility
973 974 975 976 977
			const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE);
			if (newStatusbarHiddenValue !== this.state.statusBar.hidden) {
				this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout);
			}

B
Benjamin Pasero 已提交
978
			// Activitybar visibility
979 980 981 982 983 984
			const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE);
			if (newActivityBarHiddenValue !== this.state.activityBar.hidden) {
				this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout);
			}
		}

B
Benjamin Pasero 已提交
985
		// Menubar visibility
986 987 988 989
		const newMenubarVisibility = this.configurationService.getValue<MenuBarVisibility>(Settings.MENUBAR_VISIBLE);
		this.setMenubarVisibility(newMenubarVisibility, !!skipLayout);
	}

B
Benjamin Pasero 已提交
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
	private setSideBarPosition(position: Position): void {
		const wasHidden = this.state.sideBar.hidden;

		if (this.state.sideBar.hidden) {
			this.setSideBarHidden(false, true /* Skip Layout */);
		}

		const newPositionValue = (position === Position.LEFT) ? 'left' : 'right';
		const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right';
		this.state.sideBar.position = position;

		// Adjust CSS
		removeClass(this.activitybarPart.getContainer(), oldPositionValue);
		removeClass(this.sidebarPart.getContainer(), oldPositionValue);
		addClass(this.activitybarPart.getContainer(), newPositionValue);
		addClass(this.sidebarPart.getContainer(), newPositionValue);

		// Update Styles
		this.activitybarPart.updateStyles();
		this.sidebarPart.updateStyles();

		// Layout
		if (this.workbenchGrid instanceof Grid) {
			if (!wasHidden) {
				this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView);
			}

			this.workbenchGrid.removeView(this.sideBarPartView);
			this.workbenchGrid.removeView(this.activityBarPartView);

			if (!this.state.panel.hidden && this.state.panel.position === Position.BOTTOM) {
				this.workbenchGrid.removeView(this.panelPartView);
			}

			this.layout();
		} else {
			this.workbenchGrid.layout();
		}
	}

B
Benjamin Pasero 已提交
1030 1031 1032 1033 1034 1035
	private initLayoutState(accessor: ServicesAccessor): void {
		const configurationService = accessor.get(IConfigurationService);
		const storageService = accessor.get(IStorageService);
		const lifecycleService = accessor.get(ILifecycleService);
		const contextService = accessor.get(IWorkspaceContextService);
		const environmentService = accessor.get(IEnvironmentService);
1036

B
Benjamin Pasero 已提交
1037 1038 1039
		this.windowService = accessor.get(IWindowService);
		this.contextViewService = accessor.get(IContextViewService);

1040 1041
		// Fullscreen
		this.state.fullscreen = isFullscreen();
1042

1043
		// Menubar visibility
B
Benjamin Pasero 已提交
1044
		this.state.menuBar.visibility = configurationService.getValue<MenuBarVisibility>(Settings.MENUBAR_VISIBLE);
1045 1046

		// Activity bar visibility
B
Benjamin Pasero 已提交
1047
		this.state.activityBar.hidden = !configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE);
1048

1049
		// Sidebar visibility
B
Benjamin Pasero 已提交
1050
		this.state.sideBar.hidden = storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, contextService.getWorkbenchState() === WorkbenchState.EMPTY);
1051

1052
		// Sidebar position
B
Benjamin Pasero 已提交
1053
		this.state.sideBar.position = (configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT;
1054 1055 1056 1057 1058 1059 1060

		// Sidebar viewlet
		if (!this.state.sideBar.hidden) {
			const viewletRegistry = Registry.as<ViewletRegistry>(ViewletExtensions.Viewlets);

			// Only restore last viewlet if window was reloaded or we are in development mode
			let viewletToRestore: string;
B
Benjamin Pasero 已提交
1061 1062
			if (!environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow) {
				viewletToRestore = storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, viewletRegistry.getDefaultViewletId());
1063 1064 1065 1066 1067 1068 1069 1070 1071
			} else {
				viewletToRestore = viewletRegistry.getDefaultViewletId();
			}

			if (viewletToRestore) {
				this.state.sideBar.viewletToRestore = viewletToRestore;
			} else {
				this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore
			}
1072 1073
		}

1074
		// Editor centered layout
B
Benjamin Pasero 已提交
1075
		this.state.editor.restoreCentered = storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false);
1076

1077
		// Editors to open
B
Benjamin Pasero 已提交
1078
		this.state.editor.editorsToOpen = this.resolveEditorsToOpen(accessor);
1079 1080

		// Panel visibility
B
Benjamin Pasero 已提交
1081
		this.state.panel.hidden = storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true);
1082 1083

		// Panel position
B
Benjamin Pasero 已提交
1084
		this.updatePanelPosition();
1085

1086 1087 1088 1089
		// Panel to restore
		if (!this.state.panel.hidden) {
			const panelRegistry = Registry.as<PanelRegistry>(PanelExtensions.Panels);

B
Benjamin Pasero 已提交
1090
			let panelToRestore = storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, panelRegistry.getDefaultPanelId());
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
			if (!panelRegistry.hasPanel(panelToRestore)) {
				panelToRestore = panelRegistry.getDefaultPanelId(); // fallback to default if panel is unknown
			}

			if (panelToRestore) {
				this.state.panel.panelToRestore = panelToRestore;
			} else {
				this.state.panel.hidden = true; // we hide panel if there is no panel to restore
			}
		}
1101 1102

		// Statusbar visibility
B
Benjamin Pasero 已提交
1103
		this.state.statusBar.hidden = !configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE);
1104

1105
		// Zen mode enablement
B
Benjamin Pasero 已提交
1106
		this.state.zenMode.restore = storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && configurationService.getValue(Settings.ZEN_MODE_RESTORE);
1107 1108
	}

B
Benjamin Pasero 已提交
1109 1110 1111 1112 1113 1114
	private resolveEditorsToOpen(accessor: ServicesAccessor): Promise<IResourceEditor[]> | IResourceEditor[] {
		const configuration = accessor.get(IWindowService).getConfiguration();
		const configurationService = accessor.get(IConfigurationService);
		const contextService = accessor.get(IWorkspaceContextService);
		const editorGroupService = accessor.get(IEditorGroupsService);
		const backupFileService = accessor.get(IBackupFileService);
1115 1116 1117 1118 1119

		// Files to open, diff or create
		if (this.hasInitialFilesToOpen()) {

			// Files to diff is exclusive
B
Benjamin Pasero 已提交
1120
			const filesToDiff = this.toInputs(configuration.filesToDiff, false);
1121 1122 1123 1124 1125 1126 1127 1128 1129
			if (filesToDiff && filesToDiff.length === 2) {
				return [<IResourceDiffInput>{
					leftResource: filesToDiff[0].resource,
					rightResource: filesToDiff[1].resource,
					options: { pinned: true },
					forceFile: true
				}];
			}

B
Benjamin Pasero 已提交
1130 1131
			const filesToCreate = this.toInputs(configuration.filesToCreate, true);
			const filesToOpen = this.toInputs(configuration.filesToOpen, false);
1132 1133 1134 1135 1136 1137

			// Otherwise: Open/Create files
			return [...filesToOpen, ...filesToCreate];
		}

		// Empty workbench
B
Benjamin Pasero 已提交
1138 1139
		else if (contextService.getWorkbenchState() === WorkbenchState.EMPTY && configurationService.inspect('workbench.startupEditor').value === 'newUntitledFile') {
			const isEmpty = editorGroupService.count === 1 && editorGroupService.activeGroup.count === 0;
1140 1141 1142 1143
			if (!isEmpty) {
				return []; // do not open any empty untitled file if we restored editors from previous session
			}

B
Benjamin Pasero 已提交
1144
			return backupFileService.hasBackups().then(hasBackups => {
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
				if (hasBackups) {
					return []; // do not open any empty untitled file if we have backups to restore
				}

				return [<IUntitledResourceInput>{}];
			});
		}

		return [];
	}

	private toInputs(paths: IPath[], isNew: boolean): Array<IResourceInput | IUntitledResourceInput> {
		if (!paths || !paths.length) {
			return [];
		}

		return paths.map(p => {
			const resource = p.fileUri;
			let input: IResourceInput | IUntitledResourceInput;
			if (isNew) {
				input = { filePath: resource.fsPath, options: { pinned: true } } as IUntitledResourceInput;
			} else {
				input = { resource, options: { pinned: true }, forceFile: true } as IResourceInput;
			}

			if (!isNew && p.lineNumber) {
				input.options.selection = {
					startLineNumber: p.lineNumber,
					startColumn: p.columnNumber
				};
			}

			return input;
		});
	}

B
Benjamin Pasero 已提交
1181
	private updatePanelPosition() {
1182
		const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION);
1183
		const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition);
1184 1185 1186 1187

		this.state.panel.position = (panelPosition === 'right') ? Position.RIGHT : Position.BOTTOM;
	}

B
Benjamin Pasero 已提交
1188
	isRestored(): boolean {
1189
		return this.restored;
1190
	}
1191

1192 1193 1194 1195 1196
	hasFocus(part: Parts): boolean {
		const activeElement = document.activeElement;
		if (!activeElement) {
			return false;
		}
1197

1198
		const container = this.getContainer(part);
1199

1200
		return isAncestor(activeElement, container);
1201
	}
1202

1203
	getContainer(part: Parts): HTMLElement | null {
1204 1205
		switch (part) {
			case Parts.TITLEBAR_PART:
1206
				return this.titlebarPart.getContainer();
1207
			case Parts.ACTIVITYBAR_PART:
1208
				return this.activitybarPart.getContainer();
1209
			case Parts.SIDEBAR_PART:
1210
				return this.sidebarPart.getContainer();
1211
			case Parts.PANEL_PART:
1212
				return this.panelPart.getContainer();
1213
			case Parts.EDITOR_PART:
1214
				return this.editorPart.getContainer();
1215
			case Parts.STATUSBAR_PART:
1216
				return this.statusbarPart.getContainer();
1217
		}
1218

1219
		return null;
1220
	}
1221

1222 1223 1224
	isVisible(part: Parts): boolean {
		switch (part) {
			case Parts.TITLEBAR_PART:
1225
				if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') {
1226
					return false;
1227
				} else if (!this.state.fullscreen) {
1228 1229 1230
					return true;
				} else if (isMacintosh) {
					return false;
1231
				} else if (this.state.menuBar.visibility === 'visible') {
1232
					return true;
1233 1234
				} else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') {
					return this.state.menuBar.toggled;
1235 1236 1237
				}

				return false;
1238
			case Parts.SIDEBAR_PART:
1239
				return !this.state.sideBar.hidden;
1240
			case Parts.PANEL_PART:
1241
				return !this.state.panel.hidden;
1242
			case Parts.STATUSBAR_PART:
1243
				return !this.state.statusBar.hidden;
1244
			case Parts.ACTIVITYBAR_PART:
1245
				return !this.state.activityBar.hidden;
1246
			case Parts.EDITOR_PART:
1247
				return this.workbenchGrid instanceof Grid ? !this.state.editor.hidden : true;
E
Erich Gamma 已提交
1248
		}
1249

1250
		return true; // any other part cannot be hidden
E
Erich Gamma 已提交
1251 1252
	}

1253 1254 1255
	getTitleBarOffset(): number {
		let offset = 0;
		if (this.isVisible(Parts.TITLEBAR_PART)) {
S
SteVen Batten 已提交
1256
			if (this.workbenchGrid instanceof Grid) {
S
SteVen Batten 已提交
1257
				offset = this.titlebarPart.maximumHeight;
S
SteVen Batten 已提交
1258 1259 1260
			} else {
				offset = this.workbenchGrid.partLayoutInfo.titlebar.height;

1261
				if (isMacintosh || this.state.menuBar.visibility === 'hidden') {
B
Benjamin Pasero 已提交
1262 1263
					offset /= getZoomFactor();
				}
1264
			}
E
Erich Gamma 已提交
1265
		}
1266 1267

		return offset;
E
Erich Gamma 已提交
1268
	}
1269

1270 1271
	getWorkbenchElement(): HTMLElement {
		return this.workbench;
1272
	}
1273

I
isidor 已提交
1274
	toggleZenMode(skipLayout?: boolean, restoring = false): void {
1275 1276
		this.state.zenMode.active = !this.state.zenMode.active;
		this.state.zenMode.transitionDisposeables = dispose(this.state.zenMode.transitionDisposeables);
1277

B
Benjamin Pasero 已提交
1278 1279
		const setLineNumbers = (lineNumbers: any) => this.editorService.visibleTextEditorWidgets.forEach(editor => editor.updateOptions({ lineNumbers }));

1280 1281
		// Check if zen mode transitioned to full screen and if now we are out of zen mode
		// -> we need to go out of full screen (same goes for the centered editor layout)
1282
		let toggleFullScreen = false;
1283 1284

		// Zen Mode Active
1285 1286 1287 1288 1289 1290 1291 1292 1293
		if (this.state.zenMode.active) {
			const config: {
				fullScreen: boolean;
				centerLayout: boolean;
				hideTabs: boolean;
				hideActivityBar: boolean;
				hideStatusBar: boolean;
				hideLineNumbers: boolean;
			} = this.configurationService.getValue('zenMode');
1294

1295
			toggleFullScreen = !this.state.fullscreen && config.fullScreen;
B
Benjamin Pasero 已提交
1296

1297 1298 1299 1300
			this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen;
			this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout;
			this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART);
			this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART);
1301

1302 1303
			this.setPanelHidden(true, true);
			this.setSideBarHidden(true, true);
I
isidor 已提交
1304

1305 1306 1307
			if (config.hideActivityBar) {
				this.setActivityBarHidden(true, true);
			}
1308

I
isidor 已提交
1309
			if (config.hideStatusBar) {
I
isidor 已提交
1310 1311
				this.setStatusBarHidden(true, true);
			}
1312

I
isidor 已提交
1313 1314
			if (config.hideLineNumbers) {
				setLineNumbers('off');
1315
				this.state.zenMode.transitionDisposeables.push(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off')));
I
isidor 已提交
1316 1317
			}

1318
			if (config.hideTabs && this.editorPart.partOptions.showTabs) {
1319
				this.state.zenMode.transitionDisposeables.push(this.editorPart.enforcePartOptions({ showTabs: false }));
I
isidor 已提交
1320
			}
1321 1322 1323 1324

			if (config.centerLayout) {
				this.centerEditorLayout(true, true);
			}
1325 1326 1327 1328
		}

		// Zen Mode Inactive
		else {
1329
			if (this.state.zenMode.wasPanelVisible) {
1330
				this.setPanelHidden(false, true);
1331
			}
1332

1333
			if (this.state.zenMode.wasSideBarVisible) {
1334
				this.setSideBarHidden(false, true);
1335
			}
1336

1337
			if (this.state.zenMode.transitionedToCenteredEditorLayout) {
1338 1339
				this.centerEditorLayout(false, true);
			}
B
Benjamin Pasero 已提交
1340

I
isidor 已提交
1341
			setLineNumbers(this.configurationService.getValue('editor.lineNumbers'));
1342

1343
			// Status bar and activity bar visibility come from settings -> update their visibility.
1344
			this.doUpdateLayoutConfiguration(true);
1345

B
Benjamin Pasero 已提交
1346
			this.editorGroupService.activeGroup.focus();
1347

1348
			toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen;
I
isidor 已提交
1349
		}
1350

I
isidor 已提交
1351
		if (!skipLayout) {
1352
			this.layout();
I
isidor 已提交
1353
		}
1354

1355
		if (toggleFullScreen) {
1356
			this.windowService.toggleFullScreen();
1357
		}
1358 1359 1360

		// Event
		this._onZenMode.fire(this.state.zenMode.active);
I
isidor 已提交
1361 1362
	}

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
	private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void {
		this.state.statusBar.hidden = hidden;

		// Adjust CSS
		if (hidden) {
			addClass(this.workbench, 'nostatusbar');
		} else {
			removeClass(this.workbench, 'nostatusbar');
		}

		// Layout
		if (!skipLayout) {
			if (this.workbenchGrid instanceof Grid) {
				this.layout();
			} else {
				this.workbenchGrid.layout();
			}
		}
	}

	private createWorkbenchLayout(): void {
		if (this.configurationService.getValue('workbench.useExperimentalGridLayout')) {

			// Create view wrappers for all parts
			this.titleBarPartView = new View(this.titlebarPart);
			this.sideBarPartView = new View(this.sidebarPart);
			this.activityBarPartView = new View(this.activitybarPart);
			this.editorPartView = new View(this.editorPart);
			this.panelPartView = new View(this.panelPart);
			this.statusBarPartView = new View(this.statusbarPart);

			this.workbenchGrid = new Grid(this.editorPartView, { proportionalLayout: false });

			this.workbench.prepend(this.workbenchGrid.element);
		} else {
			this.workbenchGrid = this.instantiationService.createInstance(
B
Benjamin Pasero 已提交
1399
				WorkbenchLegacyLayout,
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
				this.container,
				this.workbench,
				{
					titlebar: this.titlebarPart,
					activitybar: this.activitybarPart,
					editor: this.editorPart,
					sidebar: this.sidebarPart,
					panel: this.panelPart,
					statusbar: this.statusbarPart,
				},
				this.quickOpen,
				this.quickInput,
				this.notificationsCenter,
				this.notificationsToasts
			);
		}
	}

	layout(options?: ILayoutOptions): void {
		this.contextViewService.layout();

		if (!this.disposed) {
			if (this.workbenchGrid instanceof Grid) {
				const dimensions = getClientArea(this.container);
				position(this.workbench, 0, 0, 0, 0, 'relative');
				size(this.workbench, dimensions.width, dimensions.height);

				// Layout the grid
				this.workbenchGrid.layout(dimensions.width, dimensions.height);

				// Layout non-view ui components
				this.quickInput.layout(dimensions);
				this.quickOpen.layout(dimensions);
				this.notificationsCenter.layout(dimensions);
				this.notificationsToasts.layout(dimensions);

				// Layout Grid
				this.layoutGrid();
			} else {
				this.workbenchGrid.layout(options);
			}
		}
	}

	private layoutGrid(): void {
S
SteVen Batten 已提交
1445
		if (!(this.workbenchGrid instanceof Grid)) {
1446 1447 1448
			return;
		}

S
SteVen Batten 已提交
1449
		let panelInGrid = this.workbenchGrid.hasView(this.panelPartView);
1450 1451 1452 1453
		let sidebarInGrid = this.workbenchGrid.hasView(this.sideBarPartView);
		let activityBarInGrid = this.workbenchGrid.hasView(this.activityBarPartView);
		let statusBarInGrid = this.workbenchGrid.hasView(this.statusBarPartView);
		let titlebarInGrid = this.workbenchGrid.hasView(this.titleBarPartView);
1454

S
SteVen Batten 已提交
1455 1456
		// Add parts to grid
		if (!statusBarInGrid) {
1457
			this.workbenchGrid.addView(this.statusBarPartView, Sizing.Split, this.editorPartView, Direction.Down);
S
SteVen Batten 已提交
1458 1459 1460
			statusBarInGrid = true;
		}

1461 1462
		if (!titlebarInGrid && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') {
			this.workbenchGrid.addView(this.titleBarPartView, Sizing.Split, this.editorPartView, Direction.Up);
S
SteVen Batten 已提交
1463 1464
			titlebarInGrid = true;
		}
S
SteVen Batten 已提交
1465

S
SteVen Batten 已提交
1466
		if (!activityBarInGrid) {
1467
			this.workbenchGrid.addView(this.activityBarPartView, Sizing.Split, panelInGrid && this.state.sideBar.position === this.state.panel.position ? this.panelPartView : this.editorPartView, this.state.sideBar.position === Position.RIGHT ? Direction.Right : Direction.Left);
S
SteVen Batten 已提交
1468 1469
			activityBarInGrid = true;
		}
S
SteVen Batten 已提交
1470

S
SteVen Batten 已提交
1471
		if (!sidebarInGrid) {
1472
			this.workbenchGrid.addView(this.sideBarPartView, this.state.sideBar.width !== undefined ? this.state.sideBar.width : Sizing.Split, this.activityBarPartView, this.state.sideBar.position === Position.LEFT ? Direction.Right : Direction.Left);
S
SteVen Batten 已提交
1473 1474
			sidebarInGrid = true;
		}
S
SteVen Batten 已提交
1475

S
SteVen Batten 已提交
1476
		if (!panelInGrid) {
1477
			this.workbenchGrid.addView(this.panelPartView, this.getPanelDimension(this.state.panel.position) !== undefined ? this.getPanelDimension(this.state.panel.position) : Sizing.Split, this.editorPartView, this.state.panel.position === Position.BOTTOM ? Direction.Down : Direction.Right);
S
SteVen Batten 已提交
1478
			panelInGrid = true;
S
SteVen Batten 已提交
1479 1480
		}

S
SteVen Batten 已提交
1481
		// Hide parts
1482
		if (this.state.panel.hidden) {
S
SteVen Batten 已提交
1483 1484 1485
			this.panelPartView.hide();
		}

1486 1487
		if (this.state.statusBar.hidden) {
			this.statusBarPartView.hide();
S
SteVen Batten 已提交
1488 1489 1490
		}

		if (!this.isVisible(Parts.TITLEBAR_PART)) {
1491
			this.titleBarPartView.hide();
S
SteVen Batten 已提交
1492 1493
		}

1494 1495
		if (this.state.activityBar.hidden) {
			this.activityBarPartView.hide();
S
SteVen Batten 已提交
1496 1497
		}

1498 1499
		if (this.state.sideBar.hidden) {
			this.sideBarPartView.hide();
S
SteVen Batten 已提交
1500 1501
		}

1502
		if (this.state.editor.hidden) {
S
SteVen Batten 已提交
1503 1504 1505
			this.editorPartView.hide();
		}

S
SteVen Batten 已提交
1506
		// Show visible parts
1507
		if (!this.state.editor.hidden) {
S
SteVen Batten 已提交
1508 1509 1510
			this.editorPartView.show();
		}

1511 1512
		if (!this.state.statusBar.hidden) {
			this.statusBarPartView.show();
S
SteVen Batten 已提交
1513
		}
S
SteVen Batten 已提交
1514

S
SteVen Batten 已提交
1515
		if (this.isVisible(Parts.TITLEBAR_PART)) {
1516
			this.titleBarPartView.show();
S
SteVen Batten 已提交
1517 1518
		}

1519 1520
		if (!this.state.activityBar.hidden) {
			this.activityBarPartView.show();
S
SteVen Batten 已提交
1521
		}
S
SteVen Batten 已提交
1522

1523 1524
		if (!this.state.sideBar.hidden) {
			this.sideBarPartView.show();
S
SteVen Batten 已提交
1525 1526
		}

1527
		if (!this.state.panel.hidden) {
S
SteVen Batten 已提交
1528
			this.panelPartView.show();
S
SteVen Batten 已提交
1529 1530 1531
		}
	}

B
Benjamin Pasero 已提交
1532 1533 1534 1535
	private getPanelDimension(position: Position): number | undefined {
		return position === Position.BOTTOM ? this.state.panel.height : this.state.panel.width;
	}

1536
	isEditorLayoutCentered(): boolean {
1537
		return this.state.editor.centered;
S
SrTobi 已提交
1538 1539
	}

1540
	centerEditorLayout(active: boolean, skipLayout?: boolean): void {
1541 1542
		this.state.editor.centered = active;

B
Benjamin Pasero 已提交
1543 1544
		this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE);

1545
		let smartActive = active;
1546
		if (this.editorPart.groups.length > 1 && this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize')) {
B
Benjamin Pasero 已提交
1547
			smartActive = false; // Respect the auto resize setting - do not go into centered layout if there is more than 1 group.
1548
		}
B
Benjamin Pasero 已提交
1549

1550
		// Enter Centered Editor Layout
1551 1552
		if (this.editorPart.isLayoutCentered() !== smartActive) {
			this.editorPart.centerLayout(smartActive);
1553

1554 1555 1556
			if (!skipLayout) {
				this.layout();
			}
1557
		}
S
SrTobi 已提交
1558 1559
	}

1560
	resizePart(part: Parts, sizeChange: number): void {
S
SteVen Batten 已提交
1561
		let view: View;
1562 1563
		switch (part) {
			case Parts.SIDEBAR_PART:
1564
				view = this.sideBarPartView;
1565
			case Parts.PANEL_PART:
S
SteVen Batten 已提交
1566
				view = this.panelPartView;
1567
			case Parts.EDITOR_PART:
S
SteVen Batten 已提交
1568 1569
				view = this.editorPartView;
				if (this.workbenchGrid instanceof Grid) {
1570 1571 1572 1573
					this.workbenchGrid.resizeView(view, this.workbenchGrid.getViewSize(view) + sizeChange);
				} else {
					this.workbenchGrid.resizePart(part, sizeChange);
				}
1574 1575
				break;
			default:
B
Benjamin Pasero 已提交
1576
				return; // Cannot resize other parts
1577 1578 1579
		}
	}

1580
	setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void {
1581
		this.state.activityBar.hidden = hidden;
1582

1583 1584
		// Layout
		if (!skipLayout) {
S
SteVen Batten 已提交
1585
			if (this.workbenchGrid instanceof Grid) {
S
SteVen Batten 已提交
1586
				this.layout();
1587 1588 1589
			} else {
				this.workbenchGrid.layout();
			}
1590
		}
1591
	}
1592

S
SteVen Batten 已提交
1593
	setEditorHidden(hidden: boolean, skipLayout?: boolean): void {
1594
		if (!(this.workbenchGrid instanceof Grid) || hidden === this.state.editor.hidden) {
S
SteVen Batten 已提交
1595 1596 1597
			return;
		}

1598
		this.state.editor.hidden = hidden;
S
SteVen Batten 已提交
1599 1600

		// The editor and the panel cannot be hidden at the same time
1601
		if (this.state.editor.hidden && this.state.panel.hidden) {
S
SteVen Batten 已提交
1602 1603 1604 1605 1606 1607 1608 1609
			this.setPanelHidden(false, true);
		}

		if (!skipLayout) {
			this.layout();
		}
	}

1610
	setSideBarHidden(hidden: boolean, skipLayout?: boolean): void {
1611
		this.state.sideBar.hidden = hidden;
1612 1613 1614

		// Adjust CSS
		if (hidden) {
1615
			addClass(this.workbench, 'nosidebar');
1616
		} else {
1617
			removeClass(this.workbench, 'nosidebar');
1618 1619
		}

1620 1621
		// If sidebar becomes hidden, also hide the current active Viewlet if any
		if (hidden && this.sidebarPart.getActiveViewlet()) {
1622 1623 1624
			this.sidebarPart.hideActiveViewlet();

			// Pass Focus to Editor or Panel if Sidebar is now hidden
1625
			const activePanel = this.panelPart.getActivePanel();
1626 1627 1628 1629 1630
			if (this.hasFocus(Parts.PANEL_PART) && activePanel) {
				activePanel.focus();
			} else {
				this.editorGroupService.activeGroup.focus();
			}
1631 1632 1633 1634 1635 1636
		}

		// If sidebar becomes visible, show last active Viewlet or default viewlet
		else if (!hidden && !this.sidebarPart.getActiveViewlet()) {
			const viewletToOpen = this.sidebarPart.getLastActiveViewletId();
			if (viewletToOpen) {
I
isidor 已提交
1637
				const viewlet = this.sidebarPart.openViewlet(viewletToOpen, true);
1638
				if (!viewlet) {
I
isidor 已提交
1639
					this.sidebarPart.openViewlet(this.sidebarPart.getDefaultViewletId(), true);
1640
				}
1641
			}
1642 1643
		}

1644 1645 1646
		// Remember in settings
		const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY;
		if (hidden !== defaultHidden) {
1647
			this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE);
1648
		} else {
1649
			this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE);
1650
		}
1651

1652 1653
		// Layout
		if (!skipLayout) {
S
SteVen Batten 已提交
1654
			if (this.workbenchGrid instanceof Grid) {
S
SteVen Batten 已提交
1655
				this.layout();
1656 1657 1658
			} else {
				this.workbenchGrid.layout();
			}
1659
		}
1660
	}
1661

1662
	setPanelHidden(hidden: boolean, skipLayout?: boolean): void {
1663
		this.state.panel.hidden = hidden;
1664 1665 1666

		// Adjust CSS
		if (hidden) {
1667
			addClass(this.workbench, 'nopanel');
1668
		} else {
1669
			removeClass(this.workbench, 'nopanel');
1670 1671 1672 1673
		}

		// If panel part becomes hidden, also hide the current active panel if any
		if (hidden && this.panelPart.getActivePanel()) {
1674 1675
			this.panelPart.hideActivePanel();
			this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden
1676 1677 1678 1679 1680 1681
		}

		// If panel part becomes visible, show last active panel or default panel
		else if (!hidden && !this.panelPart.getActivePanel()) {
			const panelToOpen = this.panelPart.getLastActivePanelId();
			if (panelToOpen) {
I
isidor 已提交
1682 1683
				const focus = !skipLayout;
				this.panelPart.openPanel(panelToOpen, focus);
1684 1685 1686
			}
		}

1687 1688
		// Remember in settings
		if (!hidden) {
1689
			this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE);
1690
		} else {
1691
			this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE);
1692
		}
1693

1694 1695
		// The editor and panel cannot be hidden at the same time
		if (hidden && this.state.editor.hidden) {
S
SteVen Batten 已提交
1696 1697 1698
			this.setEditorHidden(false, true);
		}

1699 1700
		// Layout
		if (!skipLayout) {
S
SteVen Batten 已提交
1701
			if (this.workbenchGrid instanceof Grid) {
S
SteVen Batten 已提交
1702
				this.layout();
1703 1704 1705
			} else {
				this.workbenchGrid.layout();
			}
1706
		}
1707 1708 1709
	}

	toggleMaximizedPanel(): void {
S
SteVen Batten 已提交
1710 1711
		if (this.workbenchGrid instanceof Grid) {
			this.workbenchGrid.maximizeViewSize(this.panelPartView);
1712 1713 1714
		} else {
			this.workbenchGrid.layout({ toggleMaximizedPanel: true, source: Parts.PANEL_PART });
		}
1715 1716 1717
	}

	isPanelMaximized(): boolean {
S
SteVen Batten 已提交
1718
		if (this.workbenchGrid instanceof Grid) {
1719
			try {
S
SteVen Batten 已提交
1720
				return this.workbenchGrid.getViewSize2(this.panelPartView).height === this.panelPart.maximumHeight;
1721 1722 1723 1724 1725 1726
			} catch (e) {
				return false;
			}
		} else {
			return this.workbenchGrid.isPanelMaximized();
		}
1727 1728 1729
	}

	getSideBarPosition(): Position {
1730
		return this.state.sideBar.position;
1731 1732
	}

S
SteVen Batten 已提交
1733
	setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void {
1734 1735
		if (this.state.menuBar.visibility !== visibility) {
			this.state.menuBar.visibility = visibility;
1736

1737
			// Layout
S
SteVen Batten 已提交
1738
			if (!skipLayout) {
S
SteVen Batten 已提交
1739
				if (this.workbenchGrid instanceof Grid) {
1740
					const dimensions = getClientArea(this.container);
1741 1742 1743 1744
					this.workbenchGrid.layout(dimensions.width, dimensions.height);
				} else {
					this.workbenchGrid.layout();
				}
S
SteVen Batten 已提交
1745
			}
1746 1747 1748
		}
	}

S
SteVen Batten 已提交
1749
	getMenubarVisibility(): MenuBarVisibility {
1750
		return this.state.menuBar.visibility;
S
SteVen Batten 已提交
1751 1752
	}

1753
	getPanelPosition(): Position {
1754
		return this.state.panel.position;
1755 1756
	}

1757
	setPanelPosition(position: Position): void {
1758
		const wasHidden = this.state.panel.hidden;
1759

1760
		if (this.state.panel.hidden) {
1761
			this.setPanelHidden(false, true /* Skip Layout */);
1762
		} else {
1763
			this.savePanelDimension();
1764
		}
1765

1766
		const newPositionValue = (position === Position.BOTTOM) ? 'bottom' : 'right';
1767 1768
		const oldPositionValue = (this.state.panel.position === Position.BOTTOM) ? 'bottom' : 'right';
		this.state.panel.position = position;
B
Benjamin Pasero 已提交
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778

		function positionToString(position: Position): string {
			switch (position) {
				case Position.LEFT: return 'left';
				case Position.RIGHT: return 'right';
				case Position.BOTTOM: return 'bottom';
			}
		}

		this.storageService.store(Storage.PANEL_POSITION, positionToString(this.state.panel.position), StorageScope.WORKSPACE);
1779

1780
		// Adjust CSS
1781 1782
		removeClass(this.panelPart.getContainer(), oldPositionValue);
		addClass(this.panelPart.getContainer(), newPositionValue);
1783

1784 1785 1786 1787
		// Update Styles
		this.panelPart.updateStyles();

		// Layout
S
SteVen Batten 已提交
1788 1789
		if (this.workbenchGrid instanceof Grid) {
			if (!wasHidden) {
1790
				this.savePanelDimension();
1791
			}
1792

1793
			this.workbenchGrid.removeView(this.panelPartView);
S
SteVen Batten 已提交
1794
			this.layout();
1795 1796 1797 1798
		} else {
			this.workbenchGrid.layout();
		}
	}
1799

1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
	private savePanelDimension(): void {
		if (!(this.workbenchGrid instanceof Grid)) {
			return;
		}

		if (this.state.panel.position === Position.BOTTOM) {
			this.state.panel.height = this.workbenchGrid.getViewSize(this.panelPartView);
		} else {
			this.state.panel.width = this.workbenchGrid.getViewSize(this.panelPartView);
		}
	}

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
	private saveLayoutState(e: IWillSaveStateEvent): void {

		// Zen Mode
		if (this.state.zenMode.active) {
			this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE);
		} else {
			this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE);
		}

		if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) {
			if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) {
				this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes
			}
		}
	}

1828
	//#endregion
1829
}